blob: 8a1ed72d7c0cd13201a7f595de6afc66bde2b9ef [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 Moolenaar4f974752019-02-17 17:44:42 +010049# if defined(FEAT_TITLE) && !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;
103typedef int COLORREF;
104typedef int CONSOLE_CURSOR_INFO;
105typedef int COORD;
106typedef int DWORD;
107typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100108typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000109typedef int HDC;
110typedef int HFONT;
111typedef int HICON;
112typedef int HINSTANCE;
113typedef int HWND;
114typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200115typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116typedef int KEY_EVENT_RECORD;
117typedef int LOGFONT;
118typedef int LPBOOL;
119typedef int LPCTSTR;
120typedef int LPDWORD;
121typedef int LPSTR;
122typedef int LPTSTR;
123typedef int LPVOID;
124typedef int MOUSE_EVENT_RECORD;
125typedef int PACL;
126typedef int PDWORD;
127typedef int PHANDLE;
128typedef int PRINTDLG;
129typedef int PSECURITY_DESCRIPTOR;
130typedef int PSID;
131typedef int SECURITY_INFORMATION;
132typedef int SHORT;
133typedef int SMALL_RECT;
134typedef int TEXTMETRIC;
135typedef int TOKEN_INFORMATION_CLASS;
136typedef int TRUSTEE;
137typedef int WORD;
138typedef int WCHAR;
139typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100140typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200141typedef int SE_OBJECT_TYPE;
142typedef int PSNSECINFO;
143typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100144typedef int STARTUPINFO;
145typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200146typedef int LPSECURITY_ATTRIBUTES;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100147# define __stdcall // empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200150#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100151// Win32 Console handles for input and output
Bram Moolenaar071d4272004-06-13 20:20:40 +0000152static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
153static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
154
Bram Moolenaar0f873732019-12-05 20:28:46 +0100155// Win32 Screen buffer,coordinate,console I/O information
Bram Moolenaar071d4272004-06-13 20:20:40 +0000156static SMALL_RECT g_srScrollRegion;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100157static COORD g_coord; // 0-based, but external coords are 1-based
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158
Bram Moolenaar0f873732019-12-05 20:28:46 +0100159// The attribute of the screen when the editor was started
160static WORD g_attrDefault = 7; // lightgray text on black background
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161static WORD g_attrCurrent;
162
Bram Moolenaar0f873732019-12-05 20:28:46 +0100163static int g_fCBrkPressed = FALSE; // set by ctrl-break interrupt
164static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
165static int g_fForceExit = FALSE; // set when forcefully exiting
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167static void scroll(unsigned cLines);
168static void set_scroll_region(unsigned left, unsigned top,
169 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100170static void set_scroll_region_tb(unsigned top, unsigned bottom);
171static void set_scroll_region_lr(unsigned left, unsigned right);
172static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000173static void delete_lines(unsigned cLines);
174static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static int s_cursor_visible = TRUE;
177static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200178#endif
179#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100189static int conpty_working = 0;
Bram Moolenaar57da6982019-09-13 22:30:11 +0200190static int conpty_type = 0;
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100191static int conpty_stable = 0;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +0200192static int conpty_fix_type = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100193static void vtp_flag_init();
194
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200195#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100196static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100197static void vtp_init();
198static void vtp_exit();
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100199static void vtp_sgr_bulk(int arg);
200static void vtp_sgr_bulks(int argc, int *argv);
201
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200202static int wt_working = 0;
203static void wt_init();
204
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100205static guicolor_T save_console_bg_rgb;
206static guicolor_T save_console_fg_rgb;
Bram Moolenaardf543822020-01-30 11:53:59 +0100207static guicolor_T store_console_bg_rgb;
208static guicolor_T store_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100209
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200210static int g_color_index_bg = 0;
211static int g_color_index_fg = 7;
212
213# ifdef FEAT_TERMGUICOLORS
214static int default_console_color_bg = 0x000000; // black
215static int default_console_color_fg = 0xc0c0c0; // white
216# endif
217
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100218# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200219# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200220# define USE_WT (wt_working)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100221# else
222# define USE_VTP 0
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200223# define USE_WT 0
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100224# endif
225
226static void set_console_color_rgb(void);
227static void reset_console_color_rgb(void);
Bram Moolenaardf543822020-01-30 11:53:59 +0100228static void restore_console_color_rgb(void);
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100229#endif
230
Bram Moolenaar0f873732019-12-05 20:28:46 +0100231// This flag is newly created from Windows 10
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
233# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
234#endif
235
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200236#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100237static int suppress_winsize = 1; // don't fiddle with console
Bram Moolenaar071d4272004-06-13 20:20:40 +0000238#endif
239
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200240static char_u *exe_path = NULL;
241
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100242static BOOL win8_or_later = FALSE;
243
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200244# if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
245# define UChar UnicodeChar
246# else
247# define UChar uChar.UnicodeChar
248# endif
249
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200250#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +0100251// Dynamic loading for portability
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100252typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
253{
254 ULONG cbSize;
255 COORD dwSize;
256 COORD dwCursorPosition;
257 WORD wAttributes;
258 SMALL_RECT srWindow;
259 COORD dwMaximumWindowSize;
260 WORD wPopupAttributes;
261 BOOL bFullscreenSupported;
262 COLORREF ColorTable[16];
263} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
264typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
265static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
266typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
267static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
268static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100269#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100270
271/*
272 * Get version number including build number
273 */
274typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100275#define MAKE_VER(major, minor, build) \
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100276 (((major) << 24) | ((minor) << 16) | (build))
277
278 static DWORD
279get_build_number(void)
280{
281 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
282 HMODULE hNtdll;
283 PfnRtlGetVersion pRtlGetVersion;
284 DWORD ver = MAKE_VER(0, 0, 0);
285
286 hNtdll = GetModuleHandle("ntdll.dll");
287 if (hNtdll != NULL)
288 {
289 pRtlGetVersion =
290 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
291 pRtlGetVersion(&osver);
292 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
293 min(osver.dwMinorVersion, 255),
294 min(osver.dwBuildNumber, 32767));
295 }
296 return ver;
297}
298
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200299#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200300 static BOOL
301is_ambiwidth_event(
302 INPUT_RECORD *ir)
303{
304 return ir->EventType == KEY_EVENT
305 && ir->Event.KeyEvent.bKeyDown
306 && ir->Event.KeyEvent.wRepeatCount == 1
307 && ir->Event.KeyEvent.wVirtualKeyCode == 0x12
308 && ir->Event.KeyEvent.wVirtualScanCode == 0x38
309 && ir->Event.KeyEvent.UChar == 0
310 && ir->Event.KeyEvent.dwControlKeyState == 2;
311}
312
313 static void
314make_ambiwidth_event(
315 INPUT_RECORD *down,
316 INPUT_RECORD *up)
317{
318 down->Event.KeyEvent.wVirtualKeyCode = 0;
319 down->Event.KeyEvent.wVirtualScanCode = 0;
320 down->Event.KeyEvent.UChar = up->Event.KeyEvent.UChar;
321 down->Event.KeyEvent.dwControlKeyState = 0;
322}
323
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324/*
325 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100326 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100327 */
328 static BOOL
329read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100330 HANDLE hInput,
331 INPUT_RECORD *lpBuffer,
332 DWORD nLength,
333 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100334{
335 enum
336 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100337 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100338 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100339 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100340 static DWORD s_dwIndex = 0;
341 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100342 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100343 int head;
344 int tail;
345 int i;
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200346 static INPUT_RECORD s_irPseudo;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100347
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200348 if (nLength == -2)
349 return (s_dwMax > 0) ? TRUE : FALSE;
350
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100351 if (!win8_or_later)
352 {
353 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200354 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
355 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100356 }
357
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100358 if (s_dwMax == 0)
359 {
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200360 if (!USE_WT && nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200361 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200362 GetNumberOfConsoleInputEvents(hInput, &dwEvents);
363 if (dwEvents == 0 && nLength == -1)
364 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
365 ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100366 s_dwIndex = 0;
367 s_dwMax = dwEvents;
368 if (dwEvents == 0)
369 {
370 *lpEvents = 0;
371 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100372 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100373
Bram Moolenaar06b7b582020-05-30 17:49:25 +0200374 for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
375 if (is_ambiwidth_event(&s_irCache[i]))
376 make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
377
Bram Moolenaardd415a62014-02-05 14:02:27 +0100378 if (s_dwMax > 1)
379 {
380 head = 0;
381 tail = s_dwMax - 1;
382 while (head != tail)
383 {
384 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
385 && s_irCache[head + 1].EventType
386 == WINDOW_BUFFER_SIZE_EVENT)
387 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100388 // Remove duplicate event to avoid flicker.
Bram Moolenaardd415a62014-02-05 14:02:27 +0100389 for (i = head; i < tail; ++i)
390 s_irCache[i] = s_irCache[i + 1];
391 --tail;
392 continue;
393 }
394 head++;
395 }
396 s_dwMax = tail + 1;
397 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100398 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100399
Bram Moolenaarbc970da2020-04-26 19:00:07 +0200400 if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
401 {
402 if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
403 {
404 s_irPseudo = s_irCache[s_dwIndex];
405 s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
406 s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
407 *lpBuffer = s_irPseudo;
408 *lpEvents = 1;
409 return TRUE;
410 }
411 }
412
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100413 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200414 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100415 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100416 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100417 return TRUE;
418}
419
420/*
421 * Version of PeekConsoleInput() that works with IME.
422 */
423 static BOOL
424peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100425 HANDLE hInput,
426 INPUT_RECORD *lpBuffer,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +0200427 DWORD nLength UNUSED,
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100428 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100429{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100430 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100431}
432
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100433# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200434 static DWORD
435msg_wait_for_multiple_objects(
436 DWORD nCount,
437 LPHANDLE pHandles,
438 BOOL fWaitAll,
439 DWORD dwMilliseconds,
440 DWORD dwWakeMask)
441{
442 if (read_console_input(NULL, NULL, -2, NULL))
443 return WAIT_OBJECT_0;
444 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
445 dwMilliseconds, dwWakeMask);
446}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100447# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200448
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100449# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200450 static DWORD
451wait_for_single_object(
452 HANDLE hHandle,
453 DWORD dwMilliseconds)
454{
455 if (read_console_input(NULL, NULL, -2, NULL))
456 return WAIT_OBJECT_0;
457 return WaitForSingleObject(hHandle, dwMilliseconds);
458}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100459# endif
460#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200461
Bram Moolenaar071d4272004-06-13 20:20:40 +0000462 static void
463get_exe_name(void)
464{
Bram Moolenaar0f873732019-12-05 20:28:46 +0100465 // Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
466 // as the maximum length that works (plus a NUL byte).
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100467#define MAX_ENV_PATH_LEN 8192
468 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200469 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470
471 if (exe_name == NULL)
472 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100473 // store the name of the executable, may be used for $VIM
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100474 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 if (*temp != NUL)
476 exe_name = FullName_save((char_u *)temp, FALSE);
477 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000478
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200479 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000480 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +0200481 exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000483 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100484 // Append our starting directory to $PATH, so that when doing
485 // "!xxd" it's found in our starting directory. Needed because
486 // SearchPath() also looks there.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200487 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100488 if (p == NULL
489 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200490 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100491 if (p == NULL || *p == NUL)
492 temp[0] = NUL;
493 else
494 {
495 STRCPY(temp, p);
496 STRCAT(temp, ";");
497 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200498 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100499 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200500 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000501 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000502 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503}
504
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200505/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100506 * Unescape characters in "p" that appear in "escaped".
507 */
508 static void
509unescape_shellxquote(char_u *p, char_u *escaped)
510{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100511 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100512 int n;
513
514 while (*p != NUL)
515 {
516 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
517 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100518 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100519 p += n;
520 l -= n;
521 }
522}
523
524/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200525 * Load library "name".
526 */
527 HINSTANCE
528vimLoadLib(char *name)
529{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200530 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200531
Bram Moolenaar3d0e7a92021-05-01 17:46:03 +0200532 // No need to load any library when registering OLE.
533 if (found_register_arg)
534 return dll;
535
Bram Moolenaar0f873732019-12-05 20:28:46 +0100536 // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
537 // vimLoadLib() recursively, which causes a stack overflow.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200538 if (exe_path == NULL)
539 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200540 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200541 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200542 WCHAR old_dirw[MAXPATHL];
543
544 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
545 {
Bram Moolenaar0f873732019-12-05 20:28:46 +0100546 // Change directory to where the executable is, both to make
547 // sure we find a .dll there and to avoid looking for a .dll
548 // in the current directory.
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100549 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200550 dll = LoadLibrary(name);
551 SetCurrentDirectoryW(old_dirw);
552 return dll;
553 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200554 }
555 return dll;
556}
557
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200558#if defined(VIMDLL) || defined(PROTO)
559/*
560 * Check if the current executable file is for the GUI subsystem.
561 */
562 int
563mch_is_gui_executable(void)
564{
565 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
566 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
567 PIMAGE_NT_HEADERS pPE;
568
569 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
570 return FALSE;
571 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
572 if (pPE->Signature != IMAGE_NT_SIGNATURE)
573 return FALSE;
574 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
575 return TRUE;
576 return FALSE;
577}
578#endif
579
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100580#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
581/*
582 * Get related information about 'funcname' which is imported by 'hInst'.
583 * If 'info' is 0, return the function address.
584 * If 'info' is 1, return the module name which the function is imported from.
585 */
586 static void *
587get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
588{
589 PBYTE pImage = (PBYTE)hInst;
590 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
591 PIMAGE_NT_HEADERS pPE;
592 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
Bram Moolenaar0f873732019-12-05 20:28:46 +0100593 PIMAGE_THUNK_DATA pIAT; // Import Address Table
594 PIMAGE_THUNK_DATA pINT; // Import Name Table
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100595 PIMAGE_IMPORT_BY_NAME pImpName;
596
597 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
598 return NULL;
599 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
600 if (pPE->Signature != IMAGE_NT_SIGNATURE)
601 return NULL;
602 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
603 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
604 .VirtualAddress);
605 for (; pImpDesc->FirstThunk; ++pImpDesc)
606 {
607 if (!pImpDesc->OriginalFirstThunk)
608 continue;
609 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
610 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
611 for (; pIAT->u1.Function; ++pIAT, ++pINT)
612 {
613 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
614 continue;
615 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
616 + (UINT_PTR)(pINT->u1.AddressOfData));
617 if (strcmp((char *)pImpName->Name, funcname) == 0)
618 {
619 switch (info)
620 {
621 case 0:
622 return (void *)pIAT->u1.Function;
623 case 1:
624 return (void *)(pImage + pImpDesc->Name);
625 default:
626 return NULL;
627 }
628 }
629 }
630 }
631 return NULL;
632}
633
634/*
635 * Get the module handle which 'funcname' in 'hInst' is imported from.
636 */
637 HINSTANCE
638find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
639{
640 char *modulename;
641
642 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
643 if (modulename != NULL)
644 return GetModuleHandleA(modulename);
645 return NULL;
646}
647
648/*
649 * Get the address of 'funcname' which is imported by 'hInst' DLL.
650 */
651 void *
652get_dll_import_func(HINSTANCE hInst, const char *funcname)
653{
654 return get_imported_func_info(hInst, funcname, 0);
655}
656#endif
657
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
659# ifndef GETTEXT_DLL
660# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200661# define GETTEXT_DLL_ALT1 "libintl-8.dll"
662# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000663# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +0100664// Dummy functions
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000665static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200666static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000667static char *null_libintl_textdomain(const char *);
668static char *null_libintl_bindtextdomain(const char *, const char *);
669static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100670static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200672static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000673char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200674char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
675 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000676char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
677char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000679char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
680 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100681int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000682
683 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100684dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000685{
686 int i;
687 static struct
688 {
689 char *name;
690 FARPROC *ptr;
691 } libintl_entry[] =
692 {
693 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200694 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000695 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
696 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
697 {NULL, NULL}
698 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100699 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700
Bram Moolenaar7554c542018-10-06 15:03:15 +0200701 // No need to initialize twice.
702 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000703 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200704 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100705 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100706# ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100707 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200708 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100709# endif
710# ifdef GETTEXT_DLL_ALT2
Bram Moolenaar7554c542018-10-06 15:03:15 +0200711 if (!hLibintlDLL)
712 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100713# endif
Bram Moolenaar938ee832016-01-24 15:36:03 +0100714 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000715 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200716 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200718 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100719 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200720 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200722 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723 }
724 for (i = 0; libintl_entry[i].name != NULL
725 && libintl_entry[i].ptr != NULL; ++i)
726 {
727 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
728 libintl_entry[i].name)) == NULL)
729 {
730 dyn_libintl_end();
731 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000732 {
733 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100734 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000735 verbose_leave();
736 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000737 return 0;
738 }
739 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000740
Bram Moolenaar0f873732019-12-05 20:28:46 +0100741 // The bind_textdomain_codeset() function is optional.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000742 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000743 "bind_textdomain_codeset");
744 if (dyn_libintl_bind_textdomain_codeset == NULL)
745 dyn_libintl_bind_textdomain_codeset =
746 null_libintl_bind_textdomain_codeset;
747
Bram Moolenaar0f873732019-12-05 20:28:46 +0100748 // _wputenv() function for the libintl.dll is optional.
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100749 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
750 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100751 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100752 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
753 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100754
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 return 1;
756}
757
758 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100759dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760{
761 if (hLibintlDLL)
762 FreeLibrary(hLibintlDLL);
763 hLibintlDLL = NULL;
764 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200765 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000766 dyn_libintl_textdomain = null_libintl_textdomain;
767 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000768 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100769 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770}
771
772 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000773null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000774{
775 return (char*)msgid;
776}
777
778 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200779null_libintl_ngettext(
780 const char *msgid,
781 const char *msgid_plural,
782 unsigned long n)
783{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200784 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200785}
786
Bram Moolenaaree695f72016-08-03 22:08:45 +0200787 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100788null_libintl_bindtextdomain(
789 const char *domainname UNUSED,
790 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791{
792 return NULL;
793}
794
795 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100796null_libintl_bind_textdomain_codeset(
797 const char *domainname UNUSED,
798 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000799{
800 return NULL;
801}
802
803 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100804null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805{
806 return NULL;
807}
808
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200809 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100810null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100811{
812 return 0;
813}
814
Bram Moolenaar0f873732019-12-05 20:28:46 +0100815#endif // DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816
Bram Moolenaar0f873732019-12-05 20:28:46 +0100817// This symbol is not defined in older versions of the SDK or Visual C++
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818
819#ifndef VER_PLATFORM_WIN32_WINDOWS
820# define VER_PLATFORM_WIN32_WINDOWS 1
821#endif
822
Bram Moolenaar071d4272004-06-13 20:20:40 +0000823#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100824# ifndef PROTO
825# include <aclapi.h>
826# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200827# ifndef PROTECTED_DACL_SECURITY_INFORMATION
828# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
829# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830#endif
831
Bram Moolenaar27515922013-06-29 15:36:26 +0200832#ifdef HAVE_ACL
833/*
834 * Enables or disables the specified privilege.
835 */
836 static BOOL
837win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
838{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100839 BOOL bResult;
840 LUID luid;
841 HANDLE hToken;
842 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200843
844 if (!OpenProcessToken(GetCurrentProcess(),
845 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
846 return FALSE;
847
848 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
849 {
850 CloseHandle(hToken);
851 return FALSE;
852 }
853
Bram Moolenaar45500912014-07-09 20:51:07 +0200854 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200855 tokenPrivileges.Privileges[0].Luid = luid;
856 tokenPrivileges.Privileges[0].Attributes = bEnable ?
857 SE_PRIVILEGE_ENABLED : 0;
858
859 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
860 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
861
862 CloseHandle(hToken);
863
864 return bResult && GetLastError() == ERROR_SUCCESS;
865}
866#endif
867
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100868#ifdef _MSC_VER
869// Suppress the deprecation warning for using GetVersionEx().
870// It is needed for implementing "windowsversion()".
871# pragma warning(push)
872# pragma warning(disable: 4996)
873#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874/*
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200875 * Set "win8_or_later" and fill in "windowsVersion" if possible.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876 */
877 void
878PlatformId(void)
879{
880 static int done = FALSE;
881
882 if (!done)
883 {
884 OSVERSIONINFO ovi;
885
886 ovi.dwOSVersionInfoSize = sizeof(ovi);
887 GetVersionEx(&ovi);
888
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200889#ifdef FEAT_EVAL
Bram Moolenaar0c1e3742019-12-27 13:49:24 +0100890 vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
891 (int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
Bram Moolenaar1e1d2e82020-05-18 20:17:02 +0200892#endif
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100893 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
894 || ovi.dwMajorVersion > 6)
895 win8_or_later = TRUE;
896
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897#ifdef HAVE_ACL
Bram Moolenaar0f873732019-12-05 20:28:46 +0100898 // Enable privilege for getting or setting SACLs.
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200899 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900#endif
901 done = TRUE;
902 }
903}
Bram Moolenaar29d2f452020-12-04 19:42:52 +0100904#ifdef _MSC_VER
905# pragma warning(pop)
906#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200908#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000909
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100910# define SHIFT (SHIFT_PRESSED)
911# define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
912# define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
913# define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914
915
Bram Moolenaar0f873732019-12-05 20:28:46 +0100916// When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
917// We map function keys to their ANSI terminal equivalents, as produced
918// by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
919// ANSI key with a value >= '\300' is nonstandard, but provided anyway
920// so that the user can have access to all SHIFT-, CTRL-, and ALT-
921// combinations of function/arrow/etc keys.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000923static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924{
925 WORD wVirtKey;
926 BOOL fAnsiKey;
927 int chAlone;
928 int chShift;
929 int chCtrl;
930 int chAlt;
931} VirtKeyMap[] =
932{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200933// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
935
936 { VK_F1, TRUE, ';', 'T', '^', 'h', },
937 { VK_F2, TRUE, '<', 'U', '_', 'i', },
938 { VK_F3, TRUE, '=', 'V', '`', 'j', },
939 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
940 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
941 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
942 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
943 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
944 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
945 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200946 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
947 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200949 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
950 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
951 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
952 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
953 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
954 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
955 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
956 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
957 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
958 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100959 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200961 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100963# if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200964 // Most people don't have F13-F20, but what the hell...
965 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
966 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
967 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
968 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
969 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
970 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
971 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
972 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar912bc4a2019-12-01 18:58:11 +0100973# endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200974 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
975 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
976 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
977 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200979 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
980 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
981 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
982 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
983 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
984 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
985 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
986 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
987 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
988 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100989 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000990};
991
992
Bram Moolenaar0f873732019-12-05 20:28:46 +0100993/*
994 * The return code indicates key code size.
995 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +0000997win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000998 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999{
1000 UINT uMods = pker->dwControlKeyState;
1001 static int s_iIsDead = 0;
1002 static WORD awAnsiCode[2];
1003 static BYTE abKeystate[256];
1004
1005
1006 if (s_iIsDead == 2)
1007 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001008 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001009 s_iIsDead = 0;
1010 return 1;
1011 }
1012
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001013 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014 return 1;
1015
Bram Moolenaara80faa82020-04-12 19:37:17 +02001016 CLEAR_FIELD(abKeystate);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017
Bram Moolenaar0f873732019-12-05 20:28:46 +01001018 // Clear any pending dead keys
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001019 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020
1021 if (uMods & SHIFT_PRESSED)
1022 abKeystate[VK_SHIFT] = 0x80;
1023 if (uMods & CAPSLOCK_ON)
1024 abKeystate[VK_CAPITAL] = 1;
1025
1026 if ((uMods & ALT_GR) == ALT_GR)
1027 {
1028 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1029 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1030 }
1031
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001032 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1033 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001034
1035 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001036 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037
1038 return s_iIsDead;
1039}
1040
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041static BOOL g_fJustGotFocus = FALSE;
1042
1043/*
1044 * Decode a KEY_EVENT into one or two keystrokes
1045 */
1046 static BOOL
1047decode_key_event(
1048 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001049 WCHAR *pch,
1050 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051 int *pmodifiers,
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02001052 BOOL fDoPost UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053{
1054 int i;
1055 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1056
1057 *pch = *pch2 = NUL;
1058 g_fJustGotFocus = FALSE;
1059
Bram Moolenaar0f873732019-12-05 20:28:46 +01001060 // ignore key up events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001061 if (!pker->bKeyDown)
1062 return FALSE;
1063
Bram Moolenaar0f873732019-12-05 20:28:46 +01001064 // ignore some keystrokes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065 switch (pker->wVirtualKeyCode)
1066 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001067 // modifiers
Bram Moolenaar071d4272004-06-13 20:20:40 +00001068 case VK_SHIFT:
1069 case VK_CONTROL:
Bram Moolenaar0f873732019-12-05 20:28:46 +01001070 case VK_MENU: // Alt key
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 return FALSE;
1072
1073 default:
1074 break;
1075 }
1076
Bram Moolenaar0f873732019-12-05 20:28:46 +01001077 // special cases
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001078 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == 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
1108 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1109 {
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 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001140 *pch = (i > 0) ? pker->UChar : 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 Moolenaar071d4272004-06-13 20:20:40 +00001183
1184/*
1185 * Enable or disable mouse input
1186 */
1187 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001188mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001189{
1190 DWORD cmodein;
1191
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001192# ifdef VIMDLL
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001193 if (gui.in_use)
1194 return;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001195# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001196 if (!g_fMouseAvail)
1197 return;
1198
1199 g_fMouseActive = on;
1200 GetConsoleMode(g_hConIn, &cmodein);
1201
1202 if (g_fMouseActive)
1203 cmodein |= ENABLE_MOUSE_INPUT;
1204 else
1205 cmodein &= ~ENABLE_MOUSE_INPUT;
1206
1207 SetConsoleMode(g_hConIn, cmodein);
1208}
1209
Bram Moolenaar157d8132018-03-06 17:09:20 +01001210
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001211# if defined(FEAT_BEVAL_TERM) || defined(PROTO)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001212/*
1213 * Called when 'balloonevalterm' changed.
1214 */
1215 void
1216mch_bevalterm_changed(void)
1217{
1218 mch_setmouse(g_fMouseActive);
1219}
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001220# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001221
Bram Moolenaar071d4272004-06-13 20:20:40 +00001222/*
1223 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1224 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1225 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1226 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1227 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1228 * and we return the mouse position in g_xMouse and g_yMouse.
1229 *
1230 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1231 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1232 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1233 *
1234 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1235 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1236 *
1237 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1238 * moves, even if it stays within the same character cell. We ignore
1239 * all MOUSE_MOVED messages if the position hasn't really changed, and
1240 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1241 * we're only interested in MOUSE_DRAG).
1242 *
1243 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1244 * 2-button mouses by pressing the left & right buttons simultaneously.
1245 * In practice, it's almost impossible to click both at the same time,
1246 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1247 * in such cases, if the user is clicking quickly.
1248 */
1249 static BOOL
1250decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001251 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001252{
1253 static int s_nOldButton = -1;
1254 static int s_nOldMouseClick = -1;
1255 static int s_xOldMouse = -1;
1256 static int s_yOldMouse = -1;
1257 static linenr_T s_old_topline = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001258# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259 static int s_old_topfill = 0;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001260# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261 static int s_cClicks = 1;
1262 static BOOL s_fReleased = TRUE;
1263 static DWORD s_dwLastClickTime = 0;
1264 static BOOL s_fNextIsMiddle = FALSE;
1265
Bram Moolenaar0f873732019-12-05 20:28:46 +01001266 static DWORD cButtons = 0; // number of buttons supported
Bram Moolenaar071d4272004-06-13 20:20:40 +00001267
1268 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1269 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1270 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1271 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1272
1273 int nButton;
1274
1275 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1276 cButtons = 2;
1277
1278 if (!g_fMouseAvail || !g_fMouseActive)
1279 {
1280 g_nMouseClick = -1;
1281 return FALSE;
1282 }
1283
Bram Moolenaar0f873732019-12-05 20:28:46 +01001284 // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285 if (g_fJustGotFocus)
1286 {
1287 g_fJustGotFocus = FALSE;
1288 return FALSE;
1289 }
1290
Bram Moolenaar0f873732019-12-05 20:28:46 +01001291 // unprocessed mouse click?
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292 if (g_nMouseClick != -1)
1293 return TRUE;
1294
1295 nButton = -1;
1296 g_xMouse = pmer->dwMousePosition.X;
1297 g_yMouse = pmer->dwMousePosition.Y;
1298
1299 if (pmer->dwEventFlags == MOUSE_MOVED)
1300 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001301 // Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1302 // events even when the mouse moves only within a char cell.)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001303 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1304 return FALSE;
1305 }
1306
Bram Moolenaar0f873732019-12-05 20:28:46 +01001307 // If no buttons are pressed...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1309 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001310 nButton = MOUSE_RELEASE;
1311
Bram Moolenaar0f873732019-12-05 20:28:46 +01001312 // If the last thing returned was MOUSE_RELEASE, ignore this
Bram Moolenaar071d4272004-06-13 20:20:40 +00001313 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001314 {
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001315# ifdef FEAT_BEVAL_TERM
Bram Moolenaar0f873732019-12-05 20:28:46 +01001316 // do return mouse move events when we want them
Bram Moolenaar157d8132018-03-06 17:09:20 +01001317 if (p_bevalterm)
1318 nButton = MOUSE_DRAG;
1319 else
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001320# endif
Bram Moolenaar157d8132018-03-06 17:09:20 +01001321 return FALSE;
1322 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323
Bram Moolenaar071d4272004-06-13 20:20:40 +00001324 s_fReleased = TRUE;
1325 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001326 else // one or more buttons pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001328 // on a 2-button mouse, hold down left and right buttons
1329 // simultaneously to get MIDDLE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001330
1331 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1332 {
1333 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1334
Bram Moolenaar0f873732019-12-05 20:28:46 +01001335 // if either left or right button only is pressed, see if the
1336 // next mouse event has both of them pressed
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337 if (dwLR == LEFT || dwLR == RIGHT)
1338 {
1339 for (;;)
1340 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001341 // wait a short time for next input event
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1343 != WAIT_OBJECT_0)
1344 break;
1345 else
1346 {
1347 DWORD cRecords = 0;
1348 INPUT_RECORD ir;
1349 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1350
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001351 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001352
1353 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1354 || !(pmer2->dwButtonState & LEFT_RIGHT))
1355 break;
1356 else
1357 {
1358 if (pmer2->dwEventFlags != MOUSE_MOVED)
1359 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001360 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001361
1362 return decode_mouse_event(pmer2);
1363 }
1364 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1365 s_yOldMouse == pmer2->dwMousePosition.Y)
1366 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001367 // throw away spurious mouse move
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001368 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001369
Bram Moolenaar0f873732019-12-05 20:28:46 +01001370 // are there any more mouse events in queue?
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001371 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372
1373 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1374 break;
1375 }
1376 else
1377 break;
1378 }
1379 }
1380 }
1381 }
1382 }
1383
1384 if (s_fNextIsMiddle)
1385 {
1386 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1387 ? MOUSE_DRAG : MOUSE_MIDDLE;
1388 s_fNextIsMiddle = FALSE;
1389 }
1390 else if (cButtons == 2 &&
1391 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1392 {
1393 nButton = MOUSE_MIDDLE;
1394
1395 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1396 {
1397 s_fNextIsMiddle = TRUE;
1398 nButton = MOUSE_RELEASE;
1399 }
1400 }
1401 else if ((pmer->dwButtonState & LEFT) == LEFT)
1402 nButton = MOUSE_LEFT;
1403 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1404 nButton = MOUSE_MIDDLE;
1405 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1406 nButton = MOUSE_RIGHT;
1407
1408 if (! s_fReleased && ! s_fNextIsMiddle
1409 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1410 return FALSE;
1411
1412 s_fReleased = s_fNextIsMiddle;
1413 }
1414
1415 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1416 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001417 // button pressed or released, without mouse moving
Bram Moolenaar071d4272004-06-13 20:20:40 +00001418 if (nButton != -1 && nButton != MOUSE_RELEASE)
1419 {
1420 DWORD dwCurrentTime = GetTickCount();
1421
1422 if (s_xOldMouse != g_xMouse
1423 || s_yOldMouse != g_yMouse
1424 || s_nOldButton != nButton
1425 || s_old_topline != curwin->w_topline
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001426# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427 || s_old_topfill != curwin->w_topfill
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001428# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001429 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1430 {
1431 s_cClicks = 1;
1432 }
1433 else if (++s_cClicks > 4)
1434 {
1435 s_cClicks = 1;
1436 }
1437
1438 s_dwLastClickTime = dwCurrentTime;
1439 }
1440 }
1441 else if (pmer->dwEventFlags == MOUSE_MOVED)
1442 {
1443 if (nButton != -1 && nButton != MOUSE_RELEASE)
1444 nButton = MOUSE_DRAG;
1445
1446 s_cClicks = 1;
1447 }
1448
1449 if (nButton == -1)
1450 return FALSE;
1451
1452 if (nButton != MOUSE_RELEASE)
1453 s_nOldButton = nButton;
1454
1455 g_nMouseClick = nButton;
1456
1457 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1458 g_nMouseClick |= MOUSE_SHIFT;
1459 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1460 g_nMouseClick |= MOUSE_CTRL;
1461 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1462 g_nMouseClick |= MOUSE_ALT;
1463
1464 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1465 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1466
Bram Moolenaar0f873732019-12-05 20:28:46 +01001467 // only pass on interesting (i.e., different) mouse events
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468 if (s_xOldMouse == g_xMouse
1469 && s_yOldMouse == g_yMouse
1470 && s_nOldMouseClick == g_nMouseClick)
1471 {
1472 g_nMouseClick = -1;
1473 return FALSE;
1474 }
1475
1476 s_xOldMouse = g_xMouse;
1477 s_yOldMouse = g_yMouse;
1478 s_old_topline = curwin->w_topline;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001479# ifdef FEAT_DIFF
Bram Moolenaar071d4272004-06-13 20:20:40 +00001480 s_old_topfill = curwin->w_topfill;
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001481# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482 s_nOldMouseClick = g_nMouseClick;
1483
1484 return TRUE;
1485}
1486
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001487#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488
1489
1490#ifdef MCH_CURSOR_SHAPE
1491/*
1492 * Set the shape of the cursor.
1493 * 'thickness' can be from 1 (thin) to 99 (block)
1494 */
1495 static void
1496mch_set_cursor_shape(int thickness)
1497{
1498 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1499 ConsoleCursorInfo.dwSize = thickness;
1500 ConsoleCursorInfo.bVisible = s_cursor_visible;
1501
1502 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1503 if (s_cursor_visible)
1504 SetConsoleCursorPosition(g_hConOut, g_coord);
1505}
1506
1507 void
1508mch_update_cursor(void)
1509{
1510 int idx;
1511 int thickness;
1512
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001513# ifdef VIMDLL
1514 if (gui.in_use)
1515 return;
1516# endif
1517
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 /*
1519 * How the cursor is drawn depends on the current mode.
1520 */
1521 idx = get_shape_idx(FALSE);
1522
1523 if (shape_table[idx].shape == SHAPE_BLOCK)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001524 thickness = 99; // 100 doesn't work on W95
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525 else
1526 thickness = shape_table[idx].percentage;
1527 mch_set_cursor_shape(thickness);
1528}
1529#endif
1530
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001531#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532/*
1533 * Handle FOCUS_EVENT.
1534 */
1535 static void
1536handle_focus_event(INPUT_RECORD ir)
1537{
1538 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1539 ui_focus_change((int)g_fJustGotFocus);
1540}
1541
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001542static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1543
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544/*
1545 * Wait until console input from keyboard or mouse is available,
1546 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001547 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548 * Return TRUE if something is available FALSE if not.
1549 */
1550 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001551WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552{
1553 DWORD dwNow = 0, dwEndTime = 0;
1554 INPUT_RECORD ir;
1555 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001556 WCHAR ch, ch2;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001557# ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001558 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001559# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560
1561 if (msec > 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001562 // Wait until the specified time has elapsed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 dwEndTime = GetTickCount() + msec;
1564 else if (msec < 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001565 // Wait forever.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001566 dwEndTime = INFINITE;
1567
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001568 // We need to loop until the end of the time period, because
1569 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 for (;;)
1571 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001572 // Only process messages when waiting.
1573 if (msec != 0)
1574 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001575# ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001576 parse_queued_messages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001577# endif
1578# ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001579 mzvim_check_threads();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001580# endif
1581# ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001582 serverProcessPendingMessages();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001583# endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001584 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001585
Bram Moolenaara1cb1d12019-10-17 23:00:07 +02001586 if (g_nMouseClick != -1
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001587# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001588 || (!ignore_input && input_available())
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001589# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 )
1591 return TRUE;
1592
1593 if (msec > 0)
1594 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001595 // If the specified wait time has passed, return. Beware that
1596 // GetTickCount() may wrap around (overflow).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001598 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 break;
1600 }
1601 if (msec != 0)
1602 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001603 DWORD dwWaitTime = dwEndTime - dwNow;
1604
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001605 // Don't wait for more than 11 msec to avoid dropping characters,
1606 // check channel while waiting for input and handle a callback from
1607 // 'balloonexpr'.
1608 if (dwWaitTime > 11)
1609 dwWaitTime = 11;
1610
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001611# ifdef FEAT_MZSCHEME
Bram Moolenaarc478ee32020-12-01 21:27:51 +01001612 if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001613 dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001614# endif
1615# ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001616 // When waiting very briefly don't trigger timers.
1617 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001618 {
1619 long due_time;
1620
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001621 // Trigger timers and then get the time in msec until the next
1622 // one is due. Wait up to that time.
1623 due_time = check_due_timer();
1624 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001625 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001626 // timer may have used feedkeys().
1627 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001628 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001629 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1630 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001631 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001632# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001633 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001634# ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001635 // Wait for either an event on the console input or a
1636 // message in the client-server window.
1637 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1638 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001639# else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001640 wait_for_single_object(g_hConIn, dwWaitTime)
1641 != WAIT_OBJECT_0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001642# endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001643 )
1644 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645 }
1646
1647 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001648 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001649
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001650# ifdef FEAT_MBYTE_IME
matveyt4eb19142021-05-20 11:54:10 +02001651 // May have to redraw if the cursor ends up in the wrong place.
1652 // Only when not peeking.
1653 if (State & CMDLINE && msg_row == Rows - 1 && msec != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001654 {
1655 CONSOLE_SCREEN_BUFFER_INFO csbi;
1656
1657 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1658 {
1659 if (csbi.dwCursorPosition.Y != msg_row)
1660 {
matveyte08795e2021-05-07 15:00:17 +02001661 // The screen is now messed up, must redraw the command
1662 // line and later all the windows.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 redraw_all_later(CLEAR);
matveyte08795e2021-05-07 15:00:17 +02001664 compute_cmdrow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665 redrawcmd();
1666 }
1667 }
1668 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001669# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670
1671 if (cRecords > 0)
1672 {
1673 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1674 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001675# ifdef FEAT_MBYTE_IME
Bram Moolenaar0f873732019-12-05 20:28:46 +01001676 // Windows IME sends two '\n's with only one 'ENTER'. First:
1677 // wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001678 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1680 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001681 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001682 continue;
1683 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001684# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1686 NULL, FALSE))
1687 return TRUE;
1688 }
1689
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001690 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691
1692 if (ir.EventType == FOCUS_EVENT)
1693 handle_focus_event(ir);
1694 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001695 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001696 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1697
Bram Moolenaar36698e32019-12-11 22:57:40 +01001698 // Only call shell_resized() when the size actually changed to
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001699 // avoid the screen is cleared.
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001700 if (dwSize.X != Columns || dwSize.Y != Rows)
1701 {
1702 CONSOLE_SCREEN_BUFFER_INFO csbi;
1703 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
Bram Moolenaar36698e32019-12-11 22:57:40 +01001704 dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001705 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Bram Moolenaar36698e32019-12-11 22:57:40 +01001706 if (dwSize.X != Columns || dwSize.Y != Rows)
1707 {
1708 ResizeConBuf(g_hConOut, dwSize);
1709 shell_resized();
1710 }
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001711 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001712 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 else if (ir.EventType == MOUSE_EVENT
1714 && decode_mouse_event(&ir.Event.MouseEvent))
1715 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716 }
1717 else if (msec == 0)
1718 break;
1719 }
1720
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001721# ifdef FEAT_CLIENTSERVER
Bram Moolenaar0f873732019-12-05 20:28:46 +01001722 // Something might have been received while we were waiting.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 if (input_available())
1724 return TRUE;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001725# endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001726
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727 return FALSE;
1728}
1729
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730/*
1731 * return non-zero if a character is available
1732 */
1733 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001734mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001736# ifdef VIMDLL
1737 if (gui.in_use)
1738 return TRUE;
1739# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001740 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001741}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001742
1743# if defined(FEAT_TERMINAL) || defined(PROTO)
1744/*
1745 * Check for any pending input or messages.
1746 */
1747 int
1748mch_check_messages(void)
1749{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001750# ifdef VIMDLL
1751 if (gui.in_use)
1752 return TRUE;
1753# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001754 return WaitForChar(0L, TRUE);
1755}
1756# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001757
1758/*
1759 * Create the console input. Used when reading stdin doesn't work.
1760 */
1761 static void
1762create_conin(void)
1763{
1764 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1765 FILE_SHARE_READ|FILE_SHARE_WRITE,
1766 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001767 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768 did_create_conin = TRUE;
1769}
1770
1771/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001772 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001774 static WCHAR
1775tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001777 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778
1779 for (;;)
1780 {
1781 INPUT_RECORD ir;
1782 DWORD cRecords = 0;
1783
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001784# ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001785 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786 if (input_available())
1787 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001788 if (g_nMouseClick != -1)
1789 return 0;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001790# endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001791 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 {
1793 if (did_create_conin)
1794 read_error_exit();
1795 create_conin();
1796 continue;
1797 }
1798
1799 if (ir.EventType == KEY_EVENT)
1800 {
1801 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1802 pmodifiers, TRUE))
1803 return ch;
1804 }
1805 else if (ir.EventType == FOCUS_EVENT)
1806 handle_focus_event(ir);
1807 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1808 shell_resized();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 else if (ir.EventType == MOUSE_EVENT)
1810 {
1811 if (decode_mouse_event(&ir.Event.MouseEvent))
1812 return 0;
1813 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 }
1815}
Bram Moolenaar0f873732019-12-05 20:28:46 +01001816#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817
1818
1819/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001820 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001821 * Get one or more characters from the keyboard or the mouse.
1822 * If time == 0, do not wait for characters.
1823 * If time == n, wait a short time for characters.
1824 * If time == -1, wait forever for characters.
1825 * Returns the number of characters read into buf.
1826 */
1827 int
1828mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001829 char_u *buf UNUSED,
1830 int maxlen UNUSED,
1831 long time UNUSED,
1832 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001834#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001835
1836 int len;
1837 int c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001838# ifdef VIMDLL
1839// Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1840# define TYPEAHEADSPACE 6
1841# else
1842# define TYPEAHEADSPACE 0
1843# endif
1844# define TYPEAHEADLEN (20 + TYPEAHEADSPACE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01001845 static char_u typeahead[TYPEAHEADLEN]; // previously typed bytes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 static int typeaheadlen = 0;
1847
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001848# ifdef VIMDLL
1849 if (gui.in_use)
1850 return 0;
1851# endif
1852
Bram Moolenaar0f873732019-12-05 20:28:46 +01001853 // First use any typeahead that was kept because "buf" was too small.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001854 if (typeaheadlen > 0)
1855 goto theend;
1856
Bram Moolenaar071d4272004-06-13 20:20:40 +00001857 if (time >= 0)
1858 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001859 if (!WaitForChar(time, FALSE)) // no character available
Bram Moolenaar071d4272004-06-13 20:20:40 +00001860 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01001862 else // time == -1, wait forever
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001864 mch_set_winsize_now(); // Allow winsize changes from now on
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865
Bram Moolenaar3918c952005-03-15 22:34:55 +00001866 /*
1867 * If there is no character available within 2 seconds (default)
1868 * write the autoscript file to disk. Or cause the CursorHold event
1869 * to be triggered.
1870 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001871 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001873 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001874 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001875 buf[0] = K_SPECIAL;
1876 buf[1] = KS_EXTRA;
1877 buf[2] = (int)KE_CURSORHOLD;
1878 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001880 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881 }
1882 }
1883
1884 /*
1885 * Try to read as many characters as there are, until the buffer is full.
1886 */
1887
Bram Moolenaar0f873732019-12-05 20:28:46 +01001888 // we will get at least one key. Get more if they are available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889 g_fCBrkPressed = FALSE;
1890
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001891# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 if (fdDump)
1893 fputc('[', fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001894# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895
Bram Moolenaar0f873732019-12-05 20:28:46 +01001896 // Keep looping until there is something in the typeahead buffer and more
1897 // to get and still room in the buffer (up to two bytes for a char and
1898 // three bytes for a modifier).
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001899 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001900 && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 {
1902 if (typebuf_changed(tb_change_cnt))
1903 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001904 // "buf" may be invalid now if a client put something in the
1905 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906 typeaheadlen = 0;
1907 break;
1908 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909 if (g_nMouseClick != -1)
1910 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001911# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 if (fdDump)
1913 fprintf(fdDump, "{%02x @ %d, %d}",
1914 g_nMouseClick, g_xMouse, g_yMouse);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001915# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 typeahead[typeaheadlen++] = ESC + 128;
1917 typeahead[typeaheadlen++] = 'M';
1918 typeahead[typeaheadlen++] = g_nMouseClick;
1919 typeahead[typeaheadlen++] = g_xMouse + '!';
1920 typeahead[typeaheadlen++] = g_yMouse + '!';
1921 g_nMouseClick = -1;
1922 }
1923 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001925 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001926 int modifiers = 0;
1927
1928 c = tgetch(&modifiers, &ch2);
1929
1930 if (typebuf_changed(tb_change_cnt))
1931 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01001932 // "buf" may be invalid now if a client put something in the
1933 // typeahead buffer and "buf" is in the typeahead buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934 typeaheadlen = 0;
1935 break;
1936 }
1937
1938 if (c == Ctrl_C && ctrl_c_interrupts)
1939 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001940# if defined(FEAT_CLIENTSERVER)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001941 trash_input_buf();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01001942# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001943 got_int = TRUE;
1944 }
1945
Bram Moolenaar071d4272004-06-13 20:20:40 +00001946 if (g_nMouseClick == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947 {
1948 int n = 1;
1949
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001950 if (ch2 == NUL)
1951 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001952 int i, j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001953 char_u *p;
1954 WCHAR ch[2];
1955
1956 ch[0] = c;
Bram Moolenaar0f873732019-12-05 20:28:46 +01001957 if (c >= 0xD800 && c <= 0xDBFF) // High surrogate
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001958 {
1959 ch[1] = tgetch(&modifiers, &ch2);
1960 n++;
1961 }
1962 p = utf16_to_enc(ch, &n);
1963 if (p != NULL)
1964 {
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001965 for (i = 0, j = 0; i < n; i++)
1966 {
1967 typeahead[typeaheadlen + j++] = p[i];
1968# ifdef VIMDLL
1969 if (p[i] == CSI)
1970 {
1971 typeahead[typeaheadlen + j++] = KS_EXTRA;
1972 typeahead[typeaheadlen + j++] = KE_CSI;
1973 }
1974# endif
1975 }
1976 n = j;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001977 vim_free(p);
1978 }
1979 }
1980 else
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001981 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001982 typeahead[typeaheadlen] = c;
Bram Moolenaar8f027fe2020-03-04 23:21:35 +01001983# ifdef VIMDLL
1984 if (c == CSI)
1985 {
1986 typeahead[typeaheadlen + 1] = KS_EXTRA;
1987 typeahead[typeaheadlen + 2] = KE_CSI;
1988 n = 3;
1989 }
1990# endif
1991 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 if (ch2 != NUL)
1993 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001994 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001995 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001996 switch (ch2)
1997 {
1998 case (WCHAR)'\324': // SHIFT+Insert
1999 case (WCHAR)'\325': // CTRL+Insert
2000 case (WCHAR)'\327': // SHIFT+Delete
2001 case (WCHAR)'\330': // CTRL+Delete
2002 typeahead[typeaheadlen + n] = (char_u)ch2;
2003 n++;
2004 break;
2005
2006 default:
2007 typeahead[typeaheadlen + n] = 3;
2008 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2009 n += 2;
2010 break;
2011 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01002012 }
2013 else
2014 {
2015 typeahead[typeaheadlen + n] = 3;
2016 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2017 n += 2;
2018 }
Bram Moolenaar45500912014-07-09 20:51:07 +02002019 }
2020
Bram Moolenaar0f873732019-12-05 20:28:46 +01002021 // Use the ALT key to set the 8th bit of the character
2022 // when it's one byte, the 8th bit isn't set yet and not
2023 // using a double-byte encoding (would become a lead
2024 // byte).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 if ((modifiers & MOD_MASK_ALT)
2026 && n == 1
2027 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029 )
2030 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00002031 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2032 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 modifiers &= ~MOD_MASK_ALT;
2034 }
2035
2036 if (modifiers != 0)
2037 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002038 // Prepend modifiers to the character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039 mch_memmove(typeahead + typeaheadlen + 3,
2040 typeahead + typeaheadlen, n);
2041 typeahead[typeaheadlen++] = K_SPECIAL;
2042 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2043 typeahead[typeaheadlen++] = modifiers;
2044 }
2045
2046 typeaheadlen += n;
2047
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002048# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 if (fdDump)
2050 fputc(c, fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002051# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052 }
2053 }
2054 }
2055
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002056# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 if (fdDump)
2058 {
2059 fputs("]\n", fdDump);
2060 fflush(fdDump);
2061 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002062# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063
Bram Moolenaar071d4272004-06-13 20:20:40 +00002064theend:
Bram Moolenaar0f873732019-12-05 20:28:46 +01002065 // Move typeahead to "buf", as much as fits.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002066 len = 0;
2067 while (len < maxlen && typeaheadlen > 0)
2068 {
2069 buf[len++] = typeahead[0];
2070 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2071 }
Bram Moolenaar7ca86fe2020-09-03 19:25:11 +02002072# ifdef FEAT_JOB_CHANNEL
2073 if (len > 0)
2074 {
2075 buf[len] = NUL;
2076 ch_log(NULL, "raw key input: \"%s\"", buf);
2077 }
2078# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079 return len;
2080
Bram Moolenaar0f873732019-12-05 20:28:46 +01002081#else // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082 return 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002083#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002084}
2085
Bram Moolenaar82881492012-11-20 16:53:39 +01002086#ifndef PROTO
2087# ifndef __MINGW32__
Bram Moolenaar0f873732019-12-05 20:28:46 +01002088# include <shellapi.h> // required for FindExecutable()
Bram Moolenaar82881492012-11-20 16:53:39 +01002089# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090#endif
2091
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002092/*
Bram Moolenaar95da1362020-05-30 18:37:55 +02002093 * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
Bram Moolenaar43663192017-03-05 14:29:12 +01002094 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2095 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002096 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002097 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002098 static int
Bram Moolenaar95da1362020-05-30 18:37:55 +02002099executable_file(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002100{
Bram Moolenaar95da1362020-05-30 18:37:55 +02002101 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002102 {
Bram Moolenaar95da1362020-05-30 18:37:55 +02002103 if (path != NULL)
2104 *path = FullName_save((char_u *)name, FALSE);
2105 return TRUE;
2106 }
2107 return FALSE;
2108}
2109
2110/*
2111 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2112 * If "use_path" is FALSE: Return TRUE if "name" exists.
2113 * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2114 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2115 * the allocated memory.
2116 */
2117 static int
2118executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2119{
2120 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2121 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2122 // UTF-8.
2123 char_u buf[_MAX_PATH * 3];
2124 size_t len = STRLEN(name);
2125 size_t tmplen;
2126 char_u *p, *e, *e2;
2127 char_u *pathbuf = NULL;
2128 char_u *pathext = NULL;
2129 char_u *pathextbuf = NULL;
2130 int noext = FALSE;
2131 int retval = FALSE;
2132
2133 if (len >= sizeof(buf)) // safety check
Bram Moolenaar43663192017-03-05 14:29:12 +01002134 return FALSE;
Bram Moolenaar95da1362020-05-30 18:37:55 +02002135
2136 // Using the name directly when a Unix-shell like 'shell'.
2137 if (strstr((char *)gettail(p_sh), "sh") != NULL)
2138 noext = TRUE;
2139
2140 if (use_pathext)
2141 {
2142 pathext = mch_getenv("PATHEXT");
2143 if (pathext == NULL)
2144 pathext = (char_u *)".com;.exe;.bat;.cmd";
2145
2146 if (noext == FALSE)
2147 {
2148 /*
2149 * Loop over all extensions in $PATHEXT.
2150 * Check "name" ends with extension.
2151 */
2152 p = pathext;
2153 while (*p)
2154 {
2155 if (p[0] == ';'
2156 || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2157 {
2158 // Skip empty or single ".".
2159 ++p;
2160 continue;
2161 }
2162 e = vim_strchr(p, ';');
2163 if (e == NULL)
2164 e = p + STRLEN(p);
2165 tmplen = e - p;
2166
2167 if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2168 {
2169 noext = TRUE;
2170 break;
2171 }
2172
2173 p = e;
2174 }
2175 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002176 }
2177
Bram Moolenaar95da1362020-05-30 18:37:55 +02002178 // Prepend single "." to pathext, it's means no extension added.
2179 if (pathext == NULL)
2180 pathext = (char_u *)".";
2181 else if (noext == TRUE)
2182 {
2183 if (pathextbuf == NULL)
2184 pathextbuf = alloc(STRLEN(pathext) + 3);
2185 if (pathextbuf == NULL)
2186 {
2187 retval = FALSE;
2188 goto theend;
2189 }
2190 STRCPY(pathextbuf, ".;");
2191 STRCAT(pathextbuf, pathext);
2192 pathext = pathextbuf;
2193 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002194
Bram Moolenaar95da1362020-05-30 18:37:55 +02002195 // Use $PATH when "use_path" is TRUE and "name" is basename.
2196 if (use_path && gettail((char_u *)name) == (char_u *)name)
2197 {
2198 p = mch_getenv("PATH");
2199 if (p != NULL)
2200 {
2201 pathbuf = alloc(STRLEN(p) + 3);
2202 if (pathbuf == NULL)
2203 {
2204 retval = FALSE;
2205 goto theend;
2206 }
2207 STRCPY(pathbuf, ".;");
2208 STRCAT(pathbuf, p);
2209 }
2210 }
2211
2212 /*
2213 * Walk through all entries in $PATH to check if "name" exists there and
2214 * is an executable file.
2215 */
2216 p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2217 while (*p)
2218 {
2219 if (*p == ';') // Skip empty entry
2220 {
2221 ++p;
2222 continue;
2223 }
2224 e = vim_strchr(p, ';');
2225 if (e == NULL)
2226 e = p + STRLEN(p);
2227
2228 if (e - p + len + 2 > sizeof(buf))
2229 {
2230 retval = FALSE;
2231 goto theend;
2232 }
2233 // A single "." that means current dir.
2234 if (e - p == 1 && *p == '.')
2235 STRCPY(buf, name);
2236 else
2237 {
2238 vim_strncpy(buf, p, e - p);
2239 add_pathsep(buf);
2240 STRCAT(buf, name);
2241 }
2242 tmplen = STRLEN(buf);
2243
2244 /*
2245 * Loop over all extensions in $PATHEXT.
2246 * Check "name" with extension added.
2247 */
2248 p = pathext;
2249 while (*p)
2250 {
2251 if (*p == ';')
2252 {
2253 // Skip empty entry
2254 ++p;
2255 continue;
2256 }
2257 e2 = vim_strchr(p, (int)';');
2258 if (e2 == NULL)
2259 e2 = p + STRLEN(p);
2260
2261 if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2262 {
2263 // Not a single "." that means no extension is added.
2264 if (e2 - p + tmplen + 1 > sizeof(buf))
2265 {
2266 retval = FALSE;
2267 goto theend;
2268 }
2269 vim_strncpy(buf + tmplen, p, e2 - p);
2270 }
2271 if (executable_file((char *)buf, path))
2272 {
2273 retval = TRUE;
2274 goto theend;
2275 }
2276
2277 p = e2;
2278 }
2279
2280 p = e;
2281 }
2282
2283theend:
2284 free(pathextbuf);
2285 free(pathbuf);
2286 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287}
2288
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002289#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2290 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002291/*
2292 * Bad parameter handler.
2293 *
2294 * Certain MS CRT functions will intentionally crash when passed invalid
2295 * parameters to highlight possible security holes. Setting this function as
2296 * the bad parameter handler will prevent the crash.
2297 *
2298 * In debug builds the parameters contain CRT information that might help track
2299 * down the source of a problem, but in non-debug builds the arguments are all
2300 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2301 * worth allowing these to make debugging of issues easier.
2302 */
2303 static void
2304bad_param_handler(const wchar_t *expression,
2305 const wchar_t *function,
2306 const wchar_t *file,
2307 unsigned int line,
2308 uintptr_t pReserved)
2309{
2310}
2311
2312# define SET_INVALID_PARAM_HANDLER \
2313 ((void)_set_invalid_parameter_handler(bad_param_handler))
2314#else
2315# define SET_INVALID_PARAM_HANDLER
2316#endif
2317
Bram Moolenaar4f974752019-02-17 17:44:42 +01002318#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319
2320/*
2321 * GUI version of mch_init().
2322 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002323 static void
2324mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002326# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002328# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329
Bram Moolenaar0f873732019-12-05 20:28:46 +01002330 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002331 SET_INVALID_PARAM_HANDLER;
2332
Bram Moolenaar0f873732019-12-05 20:28:46 +01002333 // Let critical errors result in a failure, not in a dialog box. Required
2334 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 SetErrorMode(SEM_FAILCRITICALERRORS);
2336
Bram Moolenaar0f873732019-12-05 20:28:46 +01002337 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338
Bram Moolenaar0f873732019-12-05 20:28:46 +01002339 // Specify window size. Is there a place to get the default from?
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340 Rows = 25;
2341 Columns = 80;
2342
Bram Moolenaar0f873732019-12-05 20:28:46 +01002343 // Look for 'vimrun'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344 {
2345 char_u vimrun_location[_MAX_PATH + 4];
2346
Bram Moolenaar0f873732019-12-05 20:28:46 +01002347 // First try in same directory as gvim.exe
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 STRCPY(vimrun_location, exe_name);
2349 STRCPY(gettail(vimrun_location), "vimrun.exe");
2350 if (mch_getperm(vimrun_location) >= 0)
2351 {
2352 if (*skiptowhite(vimrun_location) != NUL)
2353 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01002354 // Enclose path with white space in double quotes.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 mch_memmove(vimrun_location + 1, vimrun_location,
2356 STRLEN(vimrun_location) + 1);
2357 *vimrun_location = '"';
2358 STRCPY(gettail(vimrun_location), "vimrun\" ");
2359 }
2360 else
2361 STRCPY(gettail(vimrun_location), "vimrun ");
2362
2363 vimrun_path = (char *)vim_strsave(vimrun_location);
2364 s_dont_use_vimrun = FALSE;
2365 }
Bram Moolenaar95da1362020-05-30 18:37:55 +02002366 else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 s_dont_use_vimrun = FALSE;
2368
Bram Moolenaar0f873732019-12-05 20:28:46 +01002369 // Don't give the warning for a missing vimrun.exe right now, but only
2370 // when vimrun was supposed to be used. Don't bother people that do
2371 // not need vimrun.exe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372 if (s_dont_use_vimrun)
2373 need_vimrun_warning = TRUE;
2374 }
2375
2376 /*
2377 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2378 * Otherwise the default "findstr /n" is used.
2379 */
Bram Moolenaar95da1362020-05-30 18:37:55 +02002380 if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2382
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002383# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002384 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002385# endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002386
2387 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388}
2389
2390
Bram Moolenaar0f873732019-12-05 20:28:46 +01002391#endif // FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002392
2393#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002395# define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2396# define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002397
2398/*
2399 * ClearConsoleBuffer()
2400 * Description:
2401 * Clears the entire contents of the console screen buffer, using the
2402 * specified attribute.
2403 * Returns:
2404 * TRUE on success
2405 */
2406 static BOOL
2407ClearConsoleBuffer(WORD wAttribute)
2408{
2409 CONSOLE_SCREEN_BUFFER_INFO csbi;
2410 COORD coord;
2411 DWORD NumCells, dummy;
2412
2413 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2414 return FALSE;
2415
2416 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2417 coord.X = 0;
2418 coord.Y = 0;
2419 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2420 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2423 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425
2426 return TRUE;
2427}
2428
2429/*
2430 * FitConsoleWindow()
2431 * Description:
2432 * Checks if the console window will fit within given buffer dimensions.
2433 * Also, if requested, will shrink the window to fit.
2434 * Returns:
2435 * TRUE on success
2436 */
2437 static BOOL
2438FitConsoleWindow(
2439 COORD dwBufferSize,
2440 BOOL WantAdjust)
2441{
2442 CONSOLE_SCREEN_BUFFER_INFO csbi;
2443 COORD dwWindowSize;
2444 BOOL NeedAdjust = FALSE;
2445
2446 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2447 {
2448 /*
2449 * A buffer resize will fail if the current console window does
2450 * not lie completely within that buffer. To avoid this, we might
2451 * have to move and possibly shrink the window.
2452 */
2453 if (csbi.srWindow.Right >= dwBufferSize.X)
2454 {
2455 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2456 if (dwWindowSize.X > dwBufferSize.X)
2457 dwWindowSize.X = dwBufferSize.X;
2458 csbi.srWindow.Right = dwBufferSize.X - 1;
2459 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2460 NeedAdjust = TRUE;
2461 }
2462 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2463 {
2464 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2465 if (dwWindowSize.Y > dwBufferSize.Y)
2466 dwWindowSize.Y = dwBufferSize.Y;
2467 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2468 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2469 NeedAdjust = TRUE;
2470 }
2471 if (NeedAdjust && WantAdjust)
2472 {
2473 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2474 return FALSE;
2475 }
2476 return TRUE;
2477 }
2478
2479 return FALSE;
2480}
2481
2482typedef struct ConsoleBufferStruct
2483{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002484 BOOL IsValid;
2485 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002486 PCHAR_INFO Buffer;
2487 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002488 PSMALL_RECT Regions;
2489 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002490} ConsoleBuffer;
2491
2492/*
2493 * SaveConsoleBuffer()
2494 * Description:
2495 * Saves important information about the console buffer, including the
2496 * actual buffer contents. The saved information is suitable for later
2497 * restoration by RestoreConsoleBuffer().
2498 * Returns:
2499 * TRUE if all information was saved; FALSE otherwise
2500 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2501 */
2502 static BOOL
2503SaveConsoleBuffer(
2504 ConsoleBuffer *cb)
2505{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002506 DWORD NumCells;
2507 COORD BufferCoord;
2508 SMALL_RECT ReadRegion;
2509 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002510 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002511
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 if (cb == NULL)
2513 return FALSE;
2514
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002515 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 {
2517 cb->IsValid = FALSE;
2518 return FALSE;
2519 }
2520 cb->IsValid = TRUE;
2521
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002522 /*
2523 * Allocate a buffer large enough to hold the entire console screen
2524 * buffer. If this ConsoleBuffer structure has already been initialized
2525 * with a buffer of the correct size, then just use that one.
2526 */
2527 if (!cb->IsValid || cb->Buffer == NULL ||
2528 cb->BufferSize.X != cb->Info.dwSize.X ||
2529 cb->BufferSize.Y != cb->Info.dwSize.Y)
2530 {
2531 cb->BufferSize.X = cb->Info.dwSize.X;
2532 cb->BufferSize.Y = cb->Info.dwSize.Y;
2533 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2534 vim_free(cb->Buffer);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002535 cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002536 if (cb->Buffer == NULL)
2537 return FALSE;
2538 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539
2540 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002541 * We will now copy the console screen buffer into our buffer.
2542 * ReadConsoleOutput() seems to be limited as far as how much you
2543 * can read at a time. Empirically, this number seems to be about
2544 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2545 * in chunks until it is all copied. The chunks will all have the
2546 * same horizontal characteristics, so initialize them now. The
2547 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002549 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002550 ReadRegion.Left = 0;
2551 ReadRegion.Right = cb->Info.dwSize.X - 1;
2552 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002553
2554 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2555 if (cb->Regions == NULL || numregions != cb->NumRegions)
2556 {
2557 cb->NumRegions = numregions;
2558 vim_free(cb->Regions);
Bram Moolenaarc799fe22019-05-28 23:08:19 +02002559 cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002560 if (cb->Regions == NULL)
2561 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002562 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002563 return FALSE;
2564 }
2565 }
2566
2567 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002569 /*
2570 * Read into position (0, Y) in our buffer.
2571 */
2572 BufferCoord.Y = Y;
2573 /*
2574 * Read the region whose top left corner is (0, Y) and whose bottom
2575 * right corner is (width - 1, Y + Y_incr - 1). This should define
2576 * a region of size width by Y_incr. Don't worry if this region is
2577 * too large for the remaining buffer; it will be cropped.
2578 */
2579 ReadRegion.Top = Y;
2580 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01002581 if (!ReadConsoleOutputW(g_hConOut, // output handle
2582 cb->Buffer, // our buffer
2583 cb->BufferSize, // dimensions of our buffer
2584 BufferCoord, // offset in our buffer
2585 &ReadRegion)) // region to save
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002586 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002587 VIM_CLEAR(cb->Buffer);
2588 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002589 return FALSE;
2590 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002591 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592 }
2593
2594 return TRUE;
2595}
2596
2597/*
2598 * RestoreConsoleBuffer()
2599 * Description:
2600 * Restores important information about the console buffer, including the
2601 * actual buffer contents, if desired. The information to restore is in
2602 * the same format used by SaveConsoleBuffer().
2603 * Returns:
2604 * TRUE on success
2605 */
2606 static BOOL
2607RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002608 ConsoleBuffer *cb,
2609 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002611 COORD BufferCoord;
2612 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002613 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614
2615 if (cb == NULL || !cb->IsValid)
2616 return FALSE;
2617
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002618 /*
2619 * Before restoring the buffer contents, clear the current buffer, and
2620 * restore the cursor position and window information. Doing this now
2621 * prevents old buffer contents from "flashing" onto the screen.
2622 */
2623 if (RestoreScreen)
2624 ClearConsoleBuffer(cb->Info.wAttributes);
2625
2626 FitConsoleWindow(cb->Info.dwSize, TRUE);
2627 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2628 return FALSE;
2629 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2630 return FALSE;
2631
2632 if (!RestoreScreen)
2633 {
2634 /*
2635 * No need to restore the screen buffer contents, so we're done.
2636 */
2637 return TRUE;
2638 }
2639
2640 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2641 return FALSE;
2642 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2643 return FALSE;
2644
2645 /*
2646 * Restore the screen buffer contents.
2647 */
2648 if (cb->Buffer != NULL)
2649 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002650 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002651 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002652 BufferCoord.X = cb->Regions[i].Left;
2653 BufferCoord.Y = cb->Regions[i].Top;
2654 WriteRegion = cb->Regions[i];
Bram Moolenaar0f873732019-12-05 20:28:46 +01002655 if (!WriteConsoleOutputW(g_hConOut, // output handle
2656 cb->Buffer, // our buffer
2657 cb->BufferSize, // dimensions of our buffer
2658 BufferCoord, // offset in our buffer
2659 &WriteRegion)) // region to restore
Bram Moolenaar444fda22017-08-11 20:37:00 +02002660 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002661 }
2662 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663
2664 return TRUE;
2665}
2666
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002667# define FEAT_RESTORE_ORIG_SCREEN
2668# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002669static ConsoleBuffer g_cbOrig = { 0 };
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002670# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002671static ConsoleBuffer g_cbNonTermcap = { 0 };
2672static ConsoleBuffer g_cbTermcap = { 0 };
2673
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002674# ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675char g_szOrigTitle[256] = { 0 };
Bram Moolenaar0f873732019-12-05 20:28:46 +01002676HWND g_hWnd = NULL; // also used in os_mswin.c
Bram Moolenaar071d4272004-06-13 20:20:40 +00002677static HICON g_hOrigIconSmall = NULL;
2678static HICON g_hOrigIcon = NULL;
2679static HICON g_hVimIcon = NULL;
2680static BOOL g_fCanChangeIcon = FALSE;
2681
Bram Moolenaar0f873732019-12-05 20:28:46 +01002682// ICON* are not defined in VC++ 4.0
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002683# ifndef ICON_SMALL
2684# define ICON_SMALL 0
2685# endif
2686# ifndef ICON_BIG
2687# define ICON_BIG 1
2688# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689/*
2690 * GetConsoleIcon()
2691 * Description:
2692 * Attempts to retrieve the small icon and/or the big icon currently in
2693 * use by a given window.
2694 * Returns:
2695 * TRUE on success
2696 */
2697 static BOOL
2698GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002699 HWND hWnd,
2700 HICON *phIconSmall,
2701 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702{
2703 if (hWnd == NULL)
2704 return FALSE;
2705
2706 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002707 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2708 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002709 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002710 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2711 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 return TRUE;
2713}
2714
2715/*
2716 * SetConsoleIcon()
2717 * Description:
2718 * Attempts to change the small icon and/or the big icon currently in
2719 * use by a given window.
2720 * Returns:
2721 * TRUE on success
2722 */
2723 static BOOL
2724SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002725 HWND hWnd,
2726 HICON hIconSmall,
2727 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 if (hWnd == NULL)
2730 return FALSE;
2731
2732 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002733 SendMessage(hWnd, WM_SETICON,
2734 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002735 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002736 SendMessage(hWnd, WM_SETICON,
2737 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738 return TRUE;
2739}
2740
2741/*
2742 * SaveConsoleTitleAndIcon()
2743 * Description:
2744 * Saves the current console window title in g_szOrigTitle, for later
2745 * restoration. Also, attempts to obtain a handle to the console window,
2746 * and use it to save the small and big icons currently in use by the
2747 * console window. This is not always possible on some versions of Windows;
2748 * nor is it possible when running Vim remotely using Telnet (since the
2749 * console window the user sees is owned by a remote process).
2750 */
2751 static void
2752SaveConsoleTitleAndIcon(void)
2753{
Bram Moolenaar0f873732019-12-05 20:28:46 +01002754 // Save the original title.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2756 return;
2757
2758 /*
2759 * Obtain a handle to the console window using GetConsoleWindow() from
2760 * KERNEL32.DLL; we need to handle in order to change the window icon.
2761 * This function only exists on NT-based Windows, starting with Windows
2762 * 2000. On older operating systems, we can't change the window icon
2763 * anyway.
2764 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002765 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766 if (g_hWnd == NULL)
2767 return;
2768
Bram Moolenaar0f873732019-12-05 20:28:46 +01002769 // Save the original console window icon.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2771 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2772 return;
2773
Bram Moolenaar0f873732019-12-05 20:28:46 +01002774 // Extract the first icon contained in the Vim executable.
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002775 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002776 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777 if (g_hVimIcon != NULL)
2778 g_fCanChangeIcon = TRUE;
2779}
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002780# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781
2782static int g_fWindInitCalled = FALSE;
2783static int g_fTermcapMode = FALSE;
2784static CONSOLE_CURSOR_INFO g_cci;
2785static DWORD g_cmodein = 0;
2786static DWORD g_cmodeout = 0;
2787
2788/*
2789 * non-GUI version of mch_init().
2790 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002791 static void
2792mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793{
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002794# ifndef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002795 CONSOLE_SCREEN_BUFFER_INFO csbi;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002796# endif
2797# ifndef __MINGW32__
Bram Moolenaar071d4272004-06-13 20:20:40 +00002798 extern int _fmode;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002799# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800
Bram Moolenaar0f873732019-12-05 20:28:46 +01002801 // Silently handle invalid parameters to CRT functions
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002802 SET_INVALID_PARAM_HANDLER;
2803
Bram Moolenaar0f873732019-12-05 20:28:46 +01002804 // Let critical errors result in a failure, not in a dialog box. Required
2805 // for the timestamp test to work on removed floppies.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002806 SetErrorMode(SEM_FAILCRITICALERRORS);
2807
Bram Moolenaar0f873732019-12-05 20:28:46 +01002808 _fmode = O_BINARY; // we do our own CR-LF translation
Bram Moolenaar071d4272004-06-13 20:20:40 +00002809 out_flush();
2810
Bram Moolenaar0f873732019-12-05 20:28:46 +01002811 // Obtain handles for the standard Console I/O devices
Bram Moolenaar071d4272004-06-13 20:20:40 +00002812 if (read_cmd_fd == 0)
2813 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2814 else
2815 create_conin();
2816 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2817
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002818# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar0f873732019-12-05 20:28:46 +01002819 // Save the initial console buffer for later restoration
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002820 SaveConsoleBuffer(&g_cbOrig);
2821 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002822# else
Bram Moolenaar0f873732019-12-05 20:28:46 +01002823 // Get current text attributes
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002824 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2825 g_attrCurrent = g_attrDefault = csbi.wAttributes;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002826# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002827 if (cterm_normal_fg_color == 0)
2828 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2829 if (cterm_normal_bg_color == 0)
2830 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2831
Bram Moolenaarbdace832019-03-02 10:13:42 +01002832 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002833 g_color_index_fg = g_attrDefault & 0xf;
2834 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2835
Bram Moolenaar0f873732019-12-05 20:28:46 +01002836 // set termcap codes to current text attributes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002837 update_tcap(g_attrCurrent);
2838
2839 GetConsoleCursorInfo(g_hConOut, &g_cci);
2840 GetConsoleMode(g_hConIn, &g_cmodein);
2841 GetConsoleMode(g_hConOut, &g_cmodeout);
2842
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002843# ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00002844 SaveConsoleTitleAndIcon();
2845 /*
2846 * Set both the small and big icons of the console window to Vim's icon.
2847 * Note that Vim presently only has one size of icon (32x32), but it
2848 * automatically gets scaled down to 16x16 when setting the small icon.
2849 */
2850 if (g_fCanChangeIcon)
2851 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002852# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853
2854 ui_get_shellsize();
2855
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002856# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857 fdDump = fopen("dump", "wt");
2858
2859 if (fdDump)
2860 {
2861 time_t t;
2862
2863 time(&t);
2864 fputs(ctime(&t), fdDump);
2865 fflush(fdDump);
2866 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002867# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868
2869 g_fWindInitCalled = TRUE;
2870
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002873# ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002874 win_clip_init();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002875# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002876
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02002877 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002878 vtp_init();
Bram Moolenaar06b7b582020-05-30 17:49:25 +02002879 wt_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880}
2881
2882/*
2883 * non-GUI version of mch_exit().
2884 * Shut down and exit with status `r'
2885 * Careful: mch_exit() may be called before mch_init()!
2886 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002887 static void
2888mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002890 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002892 vtp_exit();
2893
Bram Moolenaar955f1982017-02-05 15:10:51 +01002894 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895 if (g_fWindInitCalled)
2896 settmode(TMODE_COOK);
2897
Bram Moolenaar0f873732019-12-05 20:28:46 +01002898 ml_close_all(TRUE); // remove all memfiles
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899
2900 if (g_fWindInitCalled)
2901 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002902# ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002903 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904 /*
2905 * Restore both the small and big icons of the console window to
2906 * what they were at startup. Don't do this when the window is
2907 * closed, Vim would hang here.
2908 */
2909 if (g_fCanChangeIcon && !g_fForceExit)
2910 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002911# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002913# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914 if (fdDump)
2915 {
2916 time_t t;
2917
2918 time(&t);
2919 fputs(ctime(&t), fdDump);
2920 fclose(fdDump);
2921 }
2922 fdDump = NULL;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002923# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 }
2925
2926 SetConsoleCursorInfo(g_hConOut, &g_cci);
2927 SetConsoleMode(g_hConIn, g_cmodein);
2928 SetConsoleMode(g_hConOut, g_cmodeout);
2929
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002930# ifdef DYNAMIC_GETTEXT
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931 dyn_libintl_end();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01002932# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002933
2934 exit(r);
2935}
Bram Moolenaar0f873732019-12-05 20:28:46 +01002936#endif // !FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002938 void
2939mch_init(void)
2940{
2941#ifdef VIMDLL
2942 if (gui.starting)
2943 mch_init_g();
2944 else
2945 mch_init_c();
2946#elif defined(FEAT_GUI_MSWIN)
2947 mch_init_g();
2948#else
2949 mch_init_c();
2950#endif
2951}
2952
2953 void
2954mch_exit(int r)
2955{
Bram Moolenaar173d8412020-04-19 14:02:26 +02002956#ifdef FEAT_NETBEANS_INTG
2957 netbeans_send_disconnect();
2958#endif
2959
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002960#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002961 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002962 mch_exit_g(r);
2963 else
2964 mch_exit_c(r);
2965#elif defined(FEAT_GUI_MSWIN)
2966 mch_exit_g(r);
2967#else
2968 mch_exit_c(r);
2969#endif
2970}
2971
Bram Moolenaar071d4272004-06-13 20:20:40 +00002972/*
2973 * Do we have an interactive window?
2974 */
2975 int
2976mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002977 int argc UNUSED,
2978 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979{
2980 get_exe_name();
2981
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002982#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01002983 return OK; // GUI always has a tty
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002985# ifdef VIMDLL
2986 if (gui.in_use)
2987 return OK;
2988# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989 if (isatty(1))
2990 return OK;
2991 return FAIL;
2992#endif
2993}
2994
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002995/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002996 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997 * When "len" is > 0, also expand short to long filenames.
2998 */
2999 void
3000fname_case(
3001 char_u *name,
3002 int len)
3003{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003004 int flen;
3005 WCHAR *p;
3006 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00003008 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003009 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010 return;
3011
3012 slash_adjust(name);
3013
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003014 p = enc_to_utf16(name, NULL);
3015 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02003016 return;
3017
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003018 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003019 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003020 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003022 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003024 if (len > 0 || flen >= (int)STRLEN(q))
3025 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3026 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027 }
3028 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01003029 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030}
3031
3032
3033/*
3034 * Insert user name in s[len].
3035 */
3036 int
3037mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003038 char_u *s,
3039 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003041 WCHAR wszUserName[256 + 1]; // UNLEN is 256
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003042 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003044 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003045 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003046 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003047
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003048 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003049 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003050 vim_strncpy(s, p, len - 1);
3051 vim_free(p);
3052 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003053 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003054 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003055 s[0] = NUL;
3056 return FAIL;
3057}
3058
3059
3060/*
3061 * Insert host name in s[len].
3062 */
3063 void
3064mch_get_host_name(
3065 char_u *s,
3066 int len)
3067{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003068 WCHAR wszHostName[256 + 1];
3069 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003070
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003071 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003072 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003073 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003074
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003075 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003076 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003077 vim_strncpy(s, p, len - 1);
3078 vim_free(p);
3079 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003080 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003081 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082}
3083
3084
3085/*
3086 * return process ID
3087 */
3088 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003089mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090{
3091 return (long)GetCurrentProcessId();
3092}
3093
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003094/*
3095 * return TRUE if process "pid" is still running
3096 */
3097 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02003098mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02003099{
3100 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3101 DWORD status = 0;
3102 int ret = FALSE;
3103
3104 if (hProcess == NULL)
3105 return FALSE; // might not have access
3106 if (GetExitCodeProcess(hProcess, &status) )
3107 ret = status == STILL_ACTIVE;
3108 CloseHandle(hProcess);
3109 return ret;
3110}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111
3112/*
3113 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3114 * Return OK for success, FAIL for failure.
3115 */
3116 int
3117mch_dirname(
3118 char_u *buf,
3119 int len)
3120{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003121 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003122
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123 /*
3124 * Originally this was:
3125 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3126 * But the Win32s known bug list says that getcwd() doesn't work
3127 * so use the Win32 system call instead. <Negri>
3128 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003129 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003131 WCHAR wcbuf[_MAX_PATH + 1];
3132 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003134 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003136 p = utf16_to_enc(wcbuf, NULL);
3137 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003138 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003139 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003141 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142 }
3143 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003144 if (p == NULL)
3145 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003146
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003147 if (p != NULL)
3148 {
3149 vim_strncpy(buf, p, len - 1);
3150 vim_free(p);
3151 return OK;
3152 }
3153 }
3154 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155}
3156
3157/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003158 * Get file permissions for "name".
3159 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 */
3161 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003162mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003164 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003165 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003167 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003168 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169}
3170
3171
3172/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003173 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003174 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003175 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003176 */
3177 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003178mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003180 long n;
3181 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003182
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003183 p = enc_to_utf16(name, NULL);
3184 if (p == NULL)
3185 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003187 n = _wchmod(p, perm);
3188 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003189 if (n == -1)
3190 return FAIL;
3191
3192 win32_set_archive(name);
3193
3194 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003195}
3196
3197/*
3198 * Set hidden flag for "name".
3199 */
3200 void
3201mch_hide(char_u *name)
3202{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003203 int attrs = win32_getattrs(name);
3204 if (attrs == -1)
3205 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003207 attrs |= FILE_ATTRIBUTE_HIDDEN;
3208 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003209}
3210
3211/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003212 * Return TRUE if file "name" exists and is hidden.
3213 */
3214 int
3215mch_ishidden(char_u *name)
3216{
3217 int f = win32_getattrs(name);
3218
3219 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003220 return FALSE; // file does not exist at all
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003221
3222 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3223}
3224
3225/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226 * return TRUE if "name" is a directory
3227 * return FALSE if "name" is not a directory or upon error
3228 */
3229 int
3230mch_isdir(char_u *name)
3231{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003232 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233
3234 if (f == -1)
Bram Moolenaar0f873732019-12-05 20:28:46 +01003235 return FALSE; // file does not exist at all
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236
3237 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3238}
3239
3240/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003241 * return TRUE if "name" is a directory, NOT a symlink to a directory
3242 * return FALSE if "name" is not a directory
3243 * return FALSE for error
3244 */
3245 int
3246mch_isrealdir(char_u *name)
3247{
3248 return mch_isdir(name) && !mch_is_symbolic_link(name);
3249}
3250
3251/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003252 * Create directory "name".
3253 * Return 0 on success, -1 on error.
3254 */
3255 int
3256mch_mkdir(char_u *name)
3257{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003258 WCHAR *p;
3259 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003260
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003261 p = enc_to_utf16(name, NULL);
3262 if (p == NULL)
3263 return -1;
3264 retval = _wmkdir(p);
3265 vim_free(p);
3266 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003267}
3268
3269/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003270 * Delete directory "name".
3271 * Return 0 on success, -1 on error.
3272 */
3273 int
3274mch_rmdir(char_u *name)
3275{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003276 WCHAR *p;
3277 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003278
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003279 p = enc_to_utf16(name, NULL);
3280 if (p == NULL)
3281 return -1;
3282 retval = _wrmdir(p);
3283 vim_free(p);
3284 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003285}
3286
3287/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003288 * Return TRUE if file "fname" has more than one link.
3289 */
3290 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003291mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003292{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003293 BY_HANDLE_FILE_INFORMATION info;
3294
3295 return win32_fileinfo(fname, &info) == FILEINFO_OK
3296 && info.nNumberOfLinks > 1;
3297}
3298
3299/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003300 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003301 */
3302 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003303mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003304{
3305 HANDLE hFind;
3306 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003307 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003308 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003309 WIN32_FIND_DATAW findDataW;
3310
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003311 wn = enc_to_utf16(name, NULL);
3312 if (wn == NULL)
3313 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003314
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003315 hFind = FindFirstFileW(wn, &findDataW);
3316 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003317 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003318 {
3319 fileFlags = findDataW.dwFileAttributes;
3320 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003321 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003322 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003323
3324 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003325 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3326 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003327 res = TRUE;
3328
3329 return res;
3330}
3331
3332/*
3333 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3334 * link.
3335 */
3336 int
3337mch_is_linked(char_u *fname)
3338{
3339 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3340 return TRUE;
3341 return FALSE;
3342}
3343
3344/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003345 * Get the by-handle-file-information for "fname".
3346 * Returns FILEINFO_OK when OK.
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003347 * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003348 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3349 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3350 */
3351 int
3352win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3353{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003354 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003355 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003356 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003357
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003358 wn = enc_to_utf16(fname, NULL);
3359 if (wn == NULL)
3360 return FILEINFO_ENC_FAIL;
3361
3362 hFile = CreateFileW(wn, // file name
3363 GENERIC_READ, // access mode
3364 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3365 NULL, // security descriptor
3366 OPEN_EXISTING, // creation disposition
3367 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3368 NULL); // handle to template file
3369 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003370
3371 if (hFile != INVALID_HANDLE_VALUE)
3372 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003373 if (GetFileInformationByHandle(hFile, info) != 0)
3374 res = FILEINFO_OK;
3375 else
3376 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003377 CloseHandle(hFile);
3378 }
3379
Bram Moolenaar03f48552006-02-28 23:52:23 +00003380 return res;
3381}
3382
3383/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003384 * get file attributes for `name'
3385 * -1 : error
3386 * else FILE_ATTRIBUTE_* defined in winnt.h
3387 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003388 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003389win32_getattrs(char_u *name)
3390{
3391 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003392 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003393
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003394 p = enc_to_utf16(name, NULL);
3395 if (p == NULL)
3396 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003397
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003398 attr = GetFileAttributesW(p);
3399 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003400
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003401 return attr;
3402}
3403
3404/*
3405 * set file attributes for `name' to `attrs'
3406 *
3407 * return -1 for failure, 0 otherwise
3408 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003409 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003410win32_setattrs(char_u *name, int attrs)
3411{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003412 int res;
3413 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003414
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003415 p = enc_to_utf16(name, NULL);
3416 if (p == NULL)
3417 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003418
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003419 res = SetFileAttributesW(p, attrs);
3420 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003421
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003422 return res ? 0 : -1;
3423}
3424
3425/*
3426 * Set archive flag for "name".
3427 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003428 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003429win32_set_archive(char_u *name)
3430{
3431 int attrs = win32_getattrs(name);
3432 if (attrs == -1)
3433 return -1;
3434
3435 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3436 return win32_setattrs(name, attrs);
3437}
3438
3439/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440 * Return TRUE if file or directory "name" is writable (not readonly).
3441 * Strange semantics of Win32: a readonly directory is writable, but you can't
3442 * delete a file. Let's say this means it is writable.
3443 */
3444 int
3445mch_writable(char_u *name)
3446{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003447 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003448
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003449 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3450 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451}
3452
Bram Moolenaar071d4272004-06-13 20:20:40 +00003453/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003454 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003455 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003456 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3457 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003458 */
3459 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003460mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461{
Bram Moolenaar95da1362020-05-30 18:37:55 +02003462 return executable_exists((char *)name, path, TRUE, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003463}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003464
3465/*
3466 * Check what "name" is:
3467 * NODE_NORMAL: file or directory (or doesn't exist)
3468 * NODE_WRITABLE: writable device, socket, fifo, etc.
3469 * NODE_OTHER: non-writable things
3470 */
3471 int
3472mch_nodetype(char_u *name)
3473{
3474 HANDLE hFile;
3475 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003476 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477
Bram Moolenaar0f873732019-12-05 20:28:46 +01003478 // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3479 // read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3480 // here.
Bram Moolenaar043545e2006-10-10 16:44:07 +00003481 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3482 return NODE_WRITABLE;
3483
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003484 wn = enc_to_utf16(name, NULL);
3485 if (wn == NULL)
3486 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003487
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003488 hFile = CreateFileW(wn, // file name
3489 GENERIC_WRITE, // access mode
3490 0, // share mode
3491 NULL, // security descriptor
3492 OPEN_EXISTING, // creation disposition
3493 0, // file attributes
3494 NULL); // handle to template file
3495 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003496 if (hFile == INVALID_HANDLE_VALUE)
3497 return NODE_NORMAL;
3498
3499 type = GetFileType(hFile);
3500 CloseHandle(hFile);
3501 if (type == FILE_TYPE_CHAR)
3502 return NODE_WRITABLE;
3503 if (type == FILE_TYPE_DISK)
3504 return NODE_NORMAL;
3505 return NODE_OTHER;
3506}
3507
3508#ifdef HAVE_ACL
3509struct my_acl
3510{
3511 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3512 PSID pSidOwner;
3513 PSID pSidGroup;
3514 PACL pDacl;
3515 PACL pSacl;
3516};
3517#endif
3518
3519/*
3520 * Return a pointer to the ACL of file "fname" in allocated memory.
3521 * Return NULL if the ACL is not available for whatever reason.
3522 */
3523 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003524mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525{
3526#ifndef HAVE_ACL
3527 return (vim_acl_T)NULL;
3528#else
3529 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003530 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003531
Bram Moolenaarc799fe22019-05-28 23:08:19 +02003532 p = ALLOC_CLEAR_ONE(struct my_acl);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003533 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003535 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003536
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003537 wn = enc_to_utf16(fname, NULL);
3538 if (wn == NULL)
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003539 {
3540 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003541 return NULL;
Bram Moolenaarbbf9f342020-11-10 22:03:40 +01003542 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003543
3544 // Try to retrieve the entire security descriptor.
3545 err = GetNamedSecurityInfoW(
3546 wn, // Abstract filename
3547 SE_FILE_OBJECT, // File Object
3548 OWNER_SECURITY_INFORMATION |
3549 GROUP_SECURITY_INFORMATION |
3550 DACL_SECURITY_INFORMATION |
3551 SACL_SECURITY_INFORMATION,
3552 &p->pSidOwner, // Ownership information.
3553 &p->pSidGroup, // Group membership.
3554 &p->pDacl, // Discretionary information.
3555 &p->pSacl, // For auditing purposes.
3556 &p->pSecurityDescriptor);
3557 if (err == ERROR_ACCESS_DENIED ||
3558 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003559 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003560 // Retrieve only DACL.
3561 (void)GetNamedSecurityInfoW(
3562 wn,
3563 SE_FILE_OBJECT,
3564 DACL_SECURITY_INFORMATION,
3565 NULL,
3566 NULL,
3567 &p->pDacl,
3568 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003569 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003570 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003571 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003572 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003573 mch_free_acl((vim_acl_T)p);
3574 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003575 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003576 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003577 }
3578
3579 return (vim_acl_T)p;
3580#endif
3581}
3582
Bram Moolenaar27515922013-06-29 15:36:26 +02003583#ifdef HAVE_ACL
3584/*
3585 * Check if "acl" contains inherited ACE.
3586 */
3587 static BOOL
3588is_acl_inherited(PACL acl)
3589{
3590 DWORD i;
3591 ACL_SIZE_INFORMATION acl_info;
3592 PACCESS_ALLOWED_ACE ace;
3593
3594 acl_info.AceCount = 0;
3595 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3596 for (i = 0; i < acl_info.AceCount; i++)
3597 {
3598 GetAce(acl, i, (LPVOID *)&ace);
3599 if (ace->Header.AceFlags & INHERITED_ACE)
3600 return TRUE;
3601 }
3602 return FALSE;
3603}
3604#endif
3605
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606/*
3607 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3608 * Errors are ignored.
3609 * This must only be called with "acl" equal to what mch_get_acl() returned.
3610 */
3611 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003612mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613{
3614#ifdef HAVE_ACL
3615 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003616 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003617 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003619 if (p == NULL)
3620 return;
3621
3622 wn = enc_to_utf16(fname, NULL);
3623 if (wn == NULL)
3624 return;
3625
3626 // Set security flags
3627 if (p->pSidOwner)
3628 sec_info |= OWNER_SECURITY_INFORMATION;
3629 if (p->pSidGroup)
3630 sec_info |= GROUP_SECURITY_INFORMATION;
3631 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003632 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003633 sec_info |= DACL_SECURITY_INFORMATION;
3634 // Do not inherit its parent's DACL.
3635 // If the DACL is inherited, Cygwin permissions would be changed.
3636 if (!is_acl_inherited(p->pDacl))
3637 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003638 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003639 if (p->pSacl)
3640 sec_info |= SACL_SECURITY_INFORMATION;
3641
3642 (void)SetNamedSecurityInfoW(
3643 wn, // Abstract filename
3644 SE_FILE_OBJECT, // File Object
3645 sec_info,
3646 p->pSidOwner, // Ownership information.
3647 p->pSidGroup, // Group membership.
3648 p->pDacl, // Discretionary information.
3649 p->pSacl // For auditing purposes.
3650 );
3651 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652#endif
3653}
3654
3655 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003656mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657{
3658#ifdef HAVE_ACL
3659 struct my_acl *p = (struct my_acl *)acl;
3660
3661 if (p != NULL)
3662 {
3663 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3664 vim_free(p);
3665 }
3666#endif
3667}
3668
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003669#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670
3671/*
3672 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3673 */
3674 static BOOL WINAPI
3675handler_routine(
3676 DWORD dwCtrlType)
3677{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003678 INPUT_RECORD ir;
3679 DWORD out;
3680
Bram Moolenaar071d4272004-06-13 20:20:40 +00003681 switch (dwCtrlType)
3682 {
3683 case CTRL_C_EVENT:
3684 if (ctrl_c_interrupts)
3685 g_fCtrlCPressed = TRUE;
3686 return TRUE;
3687
3688 case CTRL_BREAK_EVENT:
3689 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003690 ctrl_break_was_pressed = TRUE;
Bram Moolenaar0f873732019-12-05 20:28:46 +01003691 // ReadConsoleInput is blocking, send a key event to continue.
Bram Moolenaar589b1102017-08-12 16:39:05 +02003692 ir.EventType = KEY_EVENT;
3693 ir.Event.KeyEvent.bKeyDown = TRUE;
3694 ir.Event.KeyEvent.wRepeatCount = 1;
3695 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3696 ir.Event.KeyEvent.wVirtualScanCode = 0;
3697 ir.Event.KeyEvent.dwControlKeyState = 0;
3698 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3699 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700 return TRUE;
3701
Bram Moolenaar0f873732019-12-05 20:28:46 +01003702 // fatal events: shut down gracefully
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703 case CTRL_CLOSE_EVENT:
3704 case CTRL_LOGOFF_EVENT:
3705 case CTRL_SHUTDOWN_EVENT:
3706 windgoto((int)Rows - 1, 0);
3707 g_fForceExit = TRUE;
3708
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003709 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003710 (dwCtrlType == CTRL_CLOSE_EVENT
3711 ? _("close")
3712 : dwCtrlType == CTRL_LOGOFF_EVENT
3713 ? _("logoff")
3714 : _("shutdown")));
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003715# ifdef DEBUG
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716 OutputDebugString(IObuff);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003717# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003718
Bram Moolenaar0f873732019-12-05 20:28:46 +01003719 preserve_exit(); // output IObuff, preserve files and exit
Bram Moolenaar071d4272004-06-13 20:20:40 +00003720
Bram Moolenaar0f873732019-12-05 20:28:46 +01003721 return TRUE; // not reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722
3723 default:
3724 return FALSE;
3725 }
3726}
3727
3728
3729/*
3730 * set the tty in (raw) ? "raw" : "cooked" mode
3731 */
3732 void
Bram Moolenaar26e86442020-05-17 14:06:16 +02003733mch_settmode(tmode_T tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003734{
3735 DWORD cmodein;
3736 DWORD cmodeout;
3737 BOOL bEnableHandler;
3738
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003739# ifdef VIMDLL
3740 if (gui.in_use)
3741 return;
3742# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743 GetConsoleMode(g_hConIn, &cmodein);
3744 GetConsoleMode(g_hConOut, &cmodeout);
3745 if (tmode == TMODE_RAW)
3746 {
3747 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3748 ENABLE_ECHO_INPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 if (g_fMouseActive)
3750 cmodein |= ENABLE_MOUSE_INPUT;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003751 cmodeout &= ~(
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003752# ifdef FEAT_TERMGUICOLORS
Bram Moolenaar0f873732019-12-05 20:28:46 +01003753 // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3754 // VTP.
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003755 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003756# else
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003757 ENABLE_PROCESSED_OUTPUT |
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003758# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003759 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760 bEnableHandler = TRUE;
3761 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01003762 else // cooked
Bram Moolenaar071d4272004-06-13 20:20:40 +00003763 {
3764 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3765 ENABLE_ECHO_INPUT);
3766 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3767 bEnableHandler = FALSE;
3768 }
3769 SetConsoleMode(g_hConIn, cmodein);
3770 SetConsoleMode(g_hConOut, cmodeout);
3771 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3772
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003773# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774 if (fdDump)
3775 {
3776 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3777 tmode == TMODE_RAW ? "raw" :
3778 tmode == TMODE_COOK ? "cooked" : "normal",
3779 cmodein, cmodeout);
3780 fflush(fdDump);
3781 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003782# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783}
3784
3785
3786/*
3787 * Get the size of the current window in `Rows' and `Columns'
3788 * Return OK when size could be determined, FAIL otherwise.
3789 */
3790 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003791mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792{
3793 CONSOLE_SCREEN_BUFFER_INFO csbi;
3794
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003795# ifdef VIMDLL
3796 if (gui.in_use)
3797 return OK;
3798# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3800 {
3801 /*
3802 * For some reason, we are trying to get the screen dimensions
3803 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3804 * variables are really intended to mean the size of Vim screen
3805 * while in termcap mode.
3806 */
3807 Rows = g_cbTermcap.Info.dwSize.Y;
3808 Columns = g_cbTermcap.Info.dwSize.X;
3809 }
3810 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3811 {
3812 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3813 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3814 }
3815 else
3816 {
3817 Rows = 25;
3818 Columns = 80;
3819 }
3820 return OK;
3821}
3822
3823/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003824 * Resize console buffer to 'COORD'
3825 */
3826 static void
3827ResizeConBuf(
3828 HANDLE hConsole,
3829 COORD coordScreen)
3830{
3831 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3832 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003833# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003834 if (fdDump)
3835 {
3836 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3837 GetLastError());
3838 fflush(fdDump);
3839 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003840# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003841 }
3842}
3843
3844/*
3845 * Resize console window size to 'srWindowRect'
3846 */
3847 static void
3848ResizeWindow(
3849 HANDLE hConsole,
3850 SMALL_RECT srWindowRect)
3851{
3852 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3853 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003854# ifdef MCH_WRITE_DUMP
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003855 if (fdDump)
3856 {
3857 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3858 GetLastError());
3859 fflush(fdDump);
3860 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003861# endif
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003862 }
3863}
3864
3865/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866 * Set a console window to `xSize' * `ySize'
3867 */
3868 static void
3869ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003870 HANDLE hConsole,
3871 int xSize,
3872 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873{
Bram Moolenaar0f873732019-12-05 20:28:46 +01003874 CONSOLE_SCREEN_BUFFER_INFO csbi; // hold current console buffer info
3875 SMALL_RECT srWindowRect; // hold the new console size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876 COORD coordScreen;
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003877 COORD cursor;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003878 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003879
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003880# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00003881 if (fdDump)
3882 {
3883 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3884 fflush(fdDump);
3885 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01003886# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887
Bram Moolenaar0f873732019-12-05 20:28:46 +01003888 // get the largest size we can size the console window to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003889 coordScreen = GetLargestConsoleWindowSize(hConsole);
3890
Bram Moolenaar0f873732019-12-05 20:28:46 +01003891 // define the new console window size and scroll position
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3893 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3894 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3895
3896 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3897 {
3898 int sx, sy;
3899
3900 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3901 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3902 if (sy < ySize || sx < xSize)
3903 {
3904 /*
3905 * Increasing number of lines/columns, do buffer first.
3906 * Use the maximal size in x and y direction.
3907 */
3908 if (sy < ySize)
3909 coordScreen.Y = ySize;
3910 else
3911 coordScreen.Y = sy;
3912 if (sx < xSize)
3913 coordScreen.X = xSize;
3914 else
3915 coordScreen.X = sx;
3916 SetConsoleScreenBufferSize(hConsole, coordScreen);
3917 }
3918 }
3919
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003920 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 coordScreen.X = xSize;
3922 coordScreen.Y = ySize;
3923
Bram Moolenaar2551c032018-08-23 22:38:31 +02003924 // In the new console call API, only the first time in reverse order
3925 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003927 ResizeWindow(hConsole, srWindowRect);
3928 ResizeConBuf(hConsole, coordScreen);
3929 }
3930 else
3931 {
Bram Moolenaarf49a6922019-07-15 20:37:05 +02003932 // Workaround for a Windows 10 bug
3933 cursor.X = srWindowRect.Left;
3934 cursor.Y = srWindowRect.Top;
3935 SetConsoleCursorPosition(hConsole, cursor);
3936
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003937 ResizeConBuf(hConsole, coordScreen);
3938 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003939 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003940 }
3941}
3942
3943
3944/*
3945 * Set the console window to `Rows' * `Columns'
3946 */
3947 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003948mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003949{
3950 COORD coordScreen;
3951
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003952# ifdef VIMDLL
3953 if (gui.in_use)
3954 return;
3955# endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01003956 // Don't change window size while still starting up
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957 if (suppress_winsize != 0)
3958 {
3959 suppress_winsize = 2;
3960 return;
3961 }
3962
3963 if (term_console)
3964 {
3965 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3966
Bram Moolenaar0f873732019-12-05 20:28:46 +01003967 // Clamp Rows and Columns to reasonable values
Bram Moolenaar071d4272004-06-13 20:20:40 +00003968 if (Rows > coordScreen.Y)
3969 Rows = coordScreen.Y;
3970 if (Columns > coordScreen.X)
3971 Columns = coordScreen.X;
3972
3973 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3974 }
3975}
3976
3977/*
3978 * Rows and/or Columns has changed.
3979 */
3980 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003981mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003982{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003983# ifdef VIMDLL
3984 if (gui.in_use)
3985 return;
3986# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003987 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3988}
3989
3990
3991/*
3992 * Called when started up, to set the winsize that was delayed.
3993 */
3994 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003995mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996{
3997 if (suppress_winsize == 2)
3998 {
3999 suppress_winsize = 0;
4000 mch_set_shellsize();
4001 shell_resized();
4002 }
4003 suppress_winsize = 0;
4004}
Bram Moolenaar0f873732019-12-05 20:28:46 +01004005#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004006
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004007 static BOOL
4008vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004009 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004010 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004011 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004012 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004013 PROCESS_INFORMATION *pi,
4014 LPVOID *env,
4015 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004016{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004017 BOOL ret = FALSE;
4018 WCHAR *wcmd, *wcwd = NULL;
4019
4020 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4021 if (wcmd == NULL)
4022 return FALSE;
4023 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004024 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004025 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4026 if (wcwd == NULL)
4027 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004028 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004029
4030 ret = CreateProcessW(
4031 NULL, // Executable name
4032 wcmd, // Command to execute
4033 NULL, // Process security attributes
4034 NULL, // Thread security attributes
4035 inherit_handles, // Inherit handles
4036 flags, // Creation flags
4037 env, // Environment
4038 wcwd, // Current directory
4039 (LPSTARTUPINFOW)si, // Startup information
4040 pi); // Process information
4041theend:
4042 vim_free(wcmd);
4043 vim_free(wcwd);
4044 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004045}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046
4047
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004048 static HINSTANCE
4049vim_shell_execute(
4050 char *cmd,
4051 INT n_show_cmd)
4052{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004053 HINSTANCE ret;
4054 WCHAR *wcmd;
4055
4056 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4057 if (wcmd == NULL)
4058 return (HINSTANCE) 0;
4059
4060 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4061 vim_free(wcmd);
4062 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004063}
4064
4065
Bram Moolenaar4f974752019-02-17 17:44:42 +01004066#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004067
4068/*
4069 * Specialised version of system() for Win32 GUI mode.
4070 * This version proceeds as follows:
4071 * 1. Create a console window for use by the subprocess
4072 * 2. Run the subprocess (it gets the allocated console by default)
4073 * 3. Wait for the subprocess to terminate and get its exit code
4074 * 4. Prompt the user to press a key to close the console window
4075 */
4076 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004077mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004078{
4079 STARTUPINFO si;
4080 PROCESS_INFORMATION pi;
4081 DWORD ret = 0;
4082 HWND hwnd = GetFocus();
4083
4084 si.cb = sizeof(si);
4085 si.lpReserved = NULL;
4086 si.lpDesktop = NULL;
4087 si.lpTitle = NULL;
4088 si.dwFlags = STARTF_USESHOWWINDOW;
4089 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004090 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004091 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004092 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004093 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004094 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 else
4096 si.wShowWindow = SW_SHOWNORMAL;
4097 si.cbReserved2 = 0;
4098 si.lpReserved2 = NULL;
4099
Bram Moolenaar0f873732019-12-05 20:28:46 +01004100 // Now, run the command
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004101 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004102 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4103 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104
Bram Moolenaar0f873732019-12-05 20:28:46 +01004105 // Wait for the command to terminate before continuing
Bram Moolenaar071d4272004-06-13 20:20:40 +00004106 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004107# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 int delay = 1;
4109
Bram Moolenaar0f873732019-12-05 20:28:46 +01004110 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111 for (;;)
4112 {
4113 MSG msg;
4114
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004115 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 {
4117 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004118 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004119 delay = 1;
4120 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 }
4122 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4123 break;
4124
Bram Moolenaar0f873732019-12-05 20:28:46 +01004125 // We start waiting for a very short time and then increase it, so
4126 // that we respond quickly when the process is quick, and don't
4127 // consume too much overhead when it's slow.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004128 if (delay < 50)
4129 delay += 10;
4130 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004131# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 WaitForSingleObject(pi.hProcess, INFINITE);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01004133# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134
Bram Moolenaar0f873732019-12-05 20:28:46 +01004135 // Get the command exit code
Bram Moolenaar071d4272004-06-13 20:20:40 +00004136 GetExitCodeProcess(pi.hProcess, &ret);
4137 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138
Bram Moolenaar0f873732019-12-05 20:28:46 +01004139 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140 CloseHandle(pi.hThread);
4141 CloseHandle(pi.hProcess);
4142
Bram Moolenaar0f873732019-12-05 20:28:46 +01004143 // Try to get input focus back. Doesn't always work though.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004144 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4145
4146 return ret;
4147}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004148
4149/*
4150 * Thread launched by the gui to send the current buffer data to the
4151 * process. This way avoid to hang up vim totally if the children
4152 * process take a long time to process the lines.
4153 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004154 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004155sub_process_writer(LPVOID param)
4156{
4157 HANDLE g_hChildStd_IN_Wr = param;
4158 linenr_T lnum = curbuf->b_op_start.lnum;
4159 DWORD len = 0;
4160 DWORD l;
4161 char_u *lp = ml_get(lnum);
4162 char_u *s;
4163 int written = 0;
4164
4165 for (;;)
4166 {
4167 l = (DWORD)STRLEN(lp + written);
4168 if (l == 0)
4169 len = 0;
4170 else if (lp[written] == NL)
4171 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004172 // NL -> NUL translation
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004173 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4174 }
4175 else
4176 {
4177 s = vim_strchr(lp + written, NL);
4178 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4179 s == NULL ? l : (DWORD)(s - (lp + written)),
4180 &len, NULL);
4181 }
4182 if (len == (int)l)
4183 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004184 // Finished a line, add a NL, unless this line should not have
4185 // one.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004186 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004187 || (!curbuf->b_p_bin
4188 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004189 || (lnum != curbuf->b_no_eol_lnum
4190 && (lnum != curbuf->b_ml.ml_line_count
4191 || curbuf->b_p_eol)))
4192 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004193 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4194 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004195 }
4196
4197 ++lnum;
4198 if (lnum > curbuf->b_op_end.lnum)
4199 break;
4200
4201 lp = ml_get(lnum);
4202 written = 0;
4203 }
4204 else if (len > 0)
4205 written += len;
4206 }
4207
Bram Moolenaar0f873732019-12-05 20:28:46 +01004208 // finished all the lines, close pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004209 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004210 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004211}
4212
4213
Bram Moolenaar0f873732019-12-05 20:28:46 +01004214# define BUFLEN 100 // length for buffer, stolen from unix version
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004215
4216/*
4217 * This function read from the children's stdout and write the
4218 * data on screen or in the buffer accordingly.
4219 */
4220 static void
4221dump_pipe(int options,
4222 HANDLE g_hChildStd_OUT_Rd,
4223 garray_T *ga,
4224 char_u buffer[],
4225 DWORD *buffer_off)
4226{
4227 DWORD availableBytes = 0;
4228 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004229 int ret;
4230 DWORD len;
4231 DWORD toRead;
4232 int repeatCount;
4233
Bram Moolenaar0f873732019-12-05 20:28:46 +01004234 // we query the pipe to see if there is any data to read
4235 // to avoid to perform a blocking read
4236 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4237 NULL, // optional buffer
4238 0, // buffer size
4239 NULL, // number of read bytes
4240 &availableBytes, // available bytes total
4241 NULL); // byteLeft
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004242
4243 repeatCount = 0;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004244 // We got real data in the pipe, read it
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004245 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004246 {
4247 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004248 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004249 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004250 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004251
Bram Moolenaar0f873732019-12-05 20:28:46 +01004252 // If we haven't read anything, there is a problem
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004253 if (len == 0)
4254 break;
4255
4256 availableBytes -= len;
4257
4258 if (options & SHELL_READ)
4259 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004260 // Do NUL -> NL translation, append NL separated
4261 // lines to the current buffer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004262 for (i = 0; i < len; ++i)
4263 {
4264 if (buffer[i] == NL)
4265 append_ga_line(ga);
4266 else if (buffer[i] == NUL)
4267 ga_append(ga, NL);
4268 else
4269 ga_append(ga, buffer[i]);
4270 }
4271 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004272 else if (has_mbyte)
4273 {
4274 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004275 int c;
4276 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004277
4278 len += *buffer_off;
4279 buffer[len] = NUL;
4280
Bram Moolenaar0f873732019-12-05 20:28:46 +01004281 // Check if the last character in buffer[] is
4282 // incomplete, keep these bytes for the next
4283 // round.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004284 for (p = buffer; p < buffer + len; p += l)
4285 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004286 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004287 if (l == 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004288 l = 1; // NUL byte?
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004289 else if (MB_BYTE2LEN(*p) != l)
4290 break;
4291 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004292 if (p == buffer) // no complete character
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004293 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004294 // avoid getting stuck at an illegal byte
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004295 if (len >= 12)
4296 ++p;
4297 else
4298 {
4299 *buffer_off = len;
4300 return;
4301 }
4302 }
4303 c = *p;
4304 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004305 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004306 if (p < buffer + len)
4307 {
4308 *p = c;
4309 *buffer_off = (DWORD)((buffer + len) - p);
4310 mch_memmove(buffer, p, *buffer_off);
4311 return;
4312 }
4313 *buffer_off = 0;
4314 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004315 else
4316 {
4317 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004318 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004319 }
4320
4321 windgoto(msg_row, msg_col);
4322 cursor_on();
4323 out_flush();
4324 }
4325}
4326
4327/*
4328 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4329 * for communication and doesn't open any new window.
4330 */
4331 static int
4332mch_system_piped(char *cmd, int options)
4333{
4334 STARTUPINFO si;
4335 PROCESS_INFORMATION pi;
4336 DWORD ret = 0;
4337
4338 HANDLE g_hChildStd_IN_Rd = NULL;
4339 HANDLE g_hChildStd_IN_Wr = NULL;
4340 HANDLE g_hChildStd_OUT_Rd = NULL;
4341 HANDLE g_hChildStd_OUT_Wr = NULL;
4342
Bram Moolenaar0f873732019-12-05 20:28:46 +01004343 char_u buffer[BUFLEN + 1]; // reading buffer + size
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004344 DWORD len;
4345
Bram Moolenaar0f873732019-12-05 20:28:46 +01004346 // buffer used to receive keys
4347 char_u ta_buf[BUFLEN + 1]; // TypeAHead
4348 int ta_len = 0; // valid bytes in ta_buf[]
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004349
4350 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004351 int noread_cnt = 0;
4352 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004353 int delay = 1;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004354 DWORD buffer_off = 0; // valid bytes in buffer[]
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004355 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004356
4357 SECURITY_ATTRIBUTES saAttr;
4358
Bram Moolenaar0f873732019-12-05 20:28:46 +01004359 // Set the bInheritHandle flag so pipe handles are inherited.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004360 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4361 saAttr.bInheritHandle = TRUE;
4362 saAttr.lpSecurityDescriptor = NULL;
4363
4364 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004365 // Ensure the read handle to the pipe for STDOUT is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004366 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004367 // Create a pipe for the child process's STDIN.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004368 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004369 // Ensure the write handle to the pipe for STDIN is not inherited.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004370 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004371 {
4372 CloseHandle(g_hChildStd_IN_Rd);
4373 CloseHandle(g_hChildStd_IN_Wr);
4374 CloseHandle(g_hChildStd_OUT_Rd);
4375 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004376 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004377 }
4378
4379 si.cb = sizeof(si);
4380 si.lpReserved = NULL;
4381 si.lpDesktop = NULL;
4382 si.lpTitle = NULL;
4383 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4384
Bram Moolenaar0f873732019-12-05 20:28:46 +01004385 // set-up our file redirection
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004386 si.hStdError = g_hChildStd_OUT_Wr;
4387 si.hStdOutput = g_hChildStd_OUT_Wr;
4388 si.hStdInput = g_hChildStd_IN_Rd;
4389 si.wShowWindow = SW_HIDE;
4390 si.cbReserved2 = 0;
4391 si.lpReserved2 = NULL;
4392
4393 if (options & SHELL_READ)
4394 ga_init2(&ga, 1, BUFLEN);
4395
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004396 if (cmd != NULL)
4397 {
4398 p = (char *)vim_strsave((char_u *)cmd);
4399 if (p != NULL)
4400 unescape_shellxquote((char_u *)p, p_sxe);
4401 else
4402 p = cmd;
4403 }
4404
Bram Moolenaar0f873732019-12-05 20:28:46 +01004405 // Now, run the command.
4406 // About "Inherit handles" being TRUE: this command can be litigious,
4407 // handle inheritance was deactivated for pending temp file, but, if we
4408 // deactivate it, the pipes don't work for some reason.
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004409 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4410 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004411
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004412 if (p != cmd)
4413 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004414
Bram Moolenaar0f873732019-12-05 20:28:46 +01004415 // Close our unused side of the pipes
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004416 CloseHandle(g_hChildStd_IN_Rd);
4417 CloseHandle(g_hChildStd_OUT_Wr);
4418
4419 if (options & SHELL_WRITE)
4420 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004421 HANDLE thread = (HANDLE)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004422 _beginthreadex(NULL, // security attributes
4423 0, // default stack size
4424 sub_process_writer, // function to be executed
4425 g_hChildStd_IN_Wr, // parameter
4426 0, // creation flag, start immediately
4427 NULL); // we don't care about thread id
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004428 CloseHandle(thread);
4429 g_hChildStd_IN_Wr = NULL;
4430 }
4431
Bram Moolenaar0f873732019-12-05 20:28:46 +01004432 // Keep updating the window while waiting for the shell to finish.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004433 for (;;)
4434 {
4435 MSG msg;
4436
Bram Moolenaar175d0702013-12-11 18:36:33 +01004437 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004438 {
4439 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004440 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004441 }
4442
Bram Moolenaar0f873732019-12-05 20:28:46 +01004443 // write pipe information in the window
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004444 if ((options & (SHELL_READ|SHELL_WRITE))
4445# ifdef FEAT_GUI
4446 || gui.in_use
4447# endif
4448 )
4449 {
4450 len = 0;
4451 if (!(options & SHELL_EXPAND)
4452 && ((options &
4453 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4454 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4455# ifdef FEAT_GUI
4456 || gui.in_use
4457# endif
4458 )
4459 && (ta_len > 0 || noread_cnt > 4))
4460 {
4461 if (ta_len == 0)
4462 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004463 // Get extra characters when we don't have any. Reset the
4464 // counter and timer.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004465 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004466 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4467 }
4468 if (ta_len > 0 || len > 0)
4469 {
4470 /*
4471 * For pipes: Check for CTRL-C: send interrupt signal to
4472 * child. Check for CTRL-D: EOF, close pipe to child.
4473 */
4474 if (len == 1 && cmd != NULL)
4475 {
4476 if (ta_buf[ta_len] == Ctrl_C)
4477 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004478 // Learn what exit code is expected, for
4479 // now put 9 as SIGKILL
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004480 TerminateProcess(pi.hProcess, 9);
4481 }
4482 if (ta_buf[ta_len] == Ctrl_D)
4483 {
4484 CloseHandle(g_hChildStd_IN_Wr);
4485 g_hChildStd_IN_Wr = NULL;
4486 }
4487 }
4488
Bram Moolenaarf4140482020-02-15 23:06:45 +01004489 term_replace_bs_del_keycode(ta_buf, ta_len, len);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004490
4491 /*
4492 * For pipes: echo the typed characters. For a pty this
4493 * does not seem to work.
4494 */
4495 for (i = ta_len; i < ta_len + len; ++i)
4496 {
4497 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4498 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004499 else if (has_mbyte)
4500 {
4501 int l = (*mb_ptr2len)(ta_buf + i);
4502
4503 msg_outtrans_len(ta_buf + i, l);
4504 i += l - 1;
4505 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004506 else
4507 msg_outtrans_len(ta_buf + i, 1);
4508 }
4509 windgoto(msg_row, msg_col);
4510 out_flush();
4511
4512 ta_len += len;
4513
4514 /*
4515 * Write the characters to the child, unless EOF has been
4516 * typed for pipes. Write one character at a time, to
4517 * avoid losing too much typeahead. When writing buffer
4518 * lines, drop the typed characters (only check for
4519 * CTRL-C).
4520 */
4521 if (options & SHELL_WRITE)
4522 ta_len = 0;
4523 else if (g_hChildStd_IN_Wr != NULL)
4524 {
4525 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4526 1, &len, NULL);
4527 // if we are typing in, we want to keep things reactive
4528 delay = 1;
4529 if (len > 0)
4530 {
4531 ta_len -= len;
4532 mch_memmove(ta_buf, ta_buf + len, ta_len);
4533 }
4534 }
4535 }
4536 }
4537 }
4538
4539 if (ta_len)
4540 ui_inchar_undo(ta_buf, ta_len);
4541
4542 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4543 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004544 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004545 break;
4546 }
4547
4548 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004549 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004550
Bram Moolenaar0f873732019-12-05 20:28:46 +01004551 // We start waiting for a very short time and then increase it, so
4552 // that we respond quickly when the process is quick, and don't
4553 // consume too much overhead when it's slow.
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004554 if (delay < 50)
4555 delay += 10;
4556 }
4557
Bram Moolenaar0f873732019-12-05 20:28:46 +01004558 // Close the pipe
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004559 CloseHandle(g_hChildStd_OUT_Rd);
4560 if (g_hChildStd_IN_Wr != NULL)
4561 CloseHandle(g_hChildStd_IN_Wr);
4562
4563 WaitForSingleObject(pi.hProcess, INFINITE);
4564
Bram Moolenaar0f873732019-12-05 20:28:46 +01004565 // Get the command exit code
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004566 GetExitCodeProcess(pi.hProcess, &ret);
4567
4568 if (options & SHELL_READ)
4569 {
4570 if (ga.ga_len > 0)
4571 {
4572 append_ga_line(&ga);
Bram Moolenaar0f873732019-12-05 20:28:46 +01004573 // remember that the NL was missing
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004574 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4575 }
4576 else
4577 curbuf->b_no_eol_lnum = 0;
4578 ga_clear(&ga);
4579 }
4580
Bram Moolenaar0f873732019-12-05 20:28:46 +01004581 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004582 CloseHandle(pi.hThread);
4583 CloseHandle(pi.hProcess);
4584
4585 return ret;
4586}
4587
4588 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004589mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004590{
Bram Moolenaar0f873732019-12-05 20:28:46 +01004591 // if we can pipe and the shelltemp option is off
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004592 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004593 return mch_system_piped(cmd, options);
4594 else
4595 return mch_system_classic(cmd, options);
4596}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004597#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004599#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004600 static int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02004601mch_system_c(char *cmd, int options UNUSED)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004602{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004603 int ret;
4604 WCHAR *wcmd;
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004605 char_u *buf;
4606 size_t len;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004607
Bram Moolenaar2efc44b2019-10-05 12:09:32 +02004608 // If the command starts and ends with double quotes, enclose the command
4609 // in parentheses.
4610 len = STRLEN(cmd);
4611 if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4612 {
4613 len += 3;
4614 buf = alloc(len);
4615 if (buf == NULL)
4616 return -1;
4617 vim_snprintf((char *)buf, len, "(%s)", cmd);
4618 wcmd = enc_to_utf16(buf, NULL);
4619 free(buf);
4620 }
4621 else
4622 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4623
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004624 if (wcmd == NULL)
4625 return -1;
4626
4627 ret = _wsystem(wcmd);
4628 vim_free(wcmd);
4629 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004630}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004631
4632#endif
4633
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004634 static int
4635mch_system(char *cmd, int options)
4636{
4637#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004638 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004639 return mch_system_g(cmd, options);
4640 else
4641 return mch_system_c(cmd, options);
4642#elif defined(FEAT_GUI_MSWIN)
4643 return mch_system_g(cmd, options);
4644#else
4645 return mch_system_c(cmd, options);
4646#endif
4647}
4648
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004649#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4650/*
4651 * Use a terminal window to run a shell command in.
4652 */
4653 static int
4654mch_call_shell_terminal(
4655 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004656 int options UNUSED) // SHELL_*, see vim.h
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004657{
4658 jobopt_T opt;
4659 char_u *newcmd = NULL;
4660 typval_T argvar[2];
4661 long_u cmdlen;
4662 int retval = -1;
4663 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004664 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004665 aco_save_T aco;
Bram Moolenaar0f873732019-12-05 20:28:46 +01004666 oparg_T oa; // operator arguments
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004667
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004668 if (cmd == NULL)
4669 cmdlen = STRLEN(p_sh) + 1;
4670 else
4671 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004672 newcmd = alloc(cmdlen);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004673 if (newcmd == NULL)
4674 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004675 if (cmd == NULL)
4676 {
4677 STRCPY(newcmd, p_sh);
4678 ch_log(NULL, "starting terminal to run a shell");
4679 }
4680 else
4681 {
4682 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4683 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4684 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004685
4686 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004687
4688 argvar[0].v_type = VAR_STRING;
4689 argvar[0].vval.v_string = newcmd;
4690 argvar[1].v_type = VAR_UNKNOWN;
4691 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004692 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004693 {
4694 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004695 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004696 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004697
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004698 job = term_getjob(buf->b_term);
4699 ++job->jv_refcount;
4700
Bram Moolenaar0f873732019-12-05 20:28:46 +01004701 // Find a window to make "buf" curbuf.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004702 aucmd_prepbuf(&aco, buf);
4703
4704 clear_oparg(&oa);
4705 while (term_use_loop())
4706 {
4707 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4708 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004709 // If terminal_loop() returns OK we got a key that is handled
4710 // in Normal model. We don't do redrawing anyway.
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004711 if (terminal_loop(TRUE) == OK)
4712 normal_cmd(&oa, TRUE);
4713 }
4714 else
4715 normal_cmd(&oa, TRUE);
4716 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004717 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004718 ch_log(NULL, "system command finished");
4719
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004720 job_unref(job);
4721
Bram Moolenaar0f873732019-12-05 20:28:46 +01004722 // restore curwin/curbuf and a few other things
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004723 aucmd_restbuf(&aco);
4724
4725 wait_return(TRUE);
4726 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4727
4728 vim_free(newcmd);
4729 return retval;
4730}
4731#endif
4732
Bram Moolenaar071d4272004-06-13 20:20:40 +00004733/*
4734 * Either execute a command by calling the shell or start a new shell
4735 */
4736 int
4737mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004738 char_u *cmd,
Bram Moolenaar0f873732019-12-05 20:28:46 +01004739 int options) // SHELL_*, see vim.h
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740{
4741 int x = 0;
4742 int tmode = cur_tmode;
4743#ifdef FEAT_TITLE
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004744 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004745
Bram Moolenaar0f873732019-12-05 20:28:46 +01004746 // Change the title to reflect that we are in a subshell.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004747 if (GetConsoleTitleW(szShellTitle,
4748 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004749 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004750 if (cmd == NULL)
4751 wcscat(szShellTitle, L" :sh");
4752 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004753 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004754 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004755
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004756 if (wn != NULL)
4757 {
4758 wcscat(szShellTitle, L" - !");
4759 if ((wcslen(szShellTitle) + wcslen(wn) <
4760 sizeof(szShellTitle)/sizeof(WCHAR)))
4761 wcscat(szShellTitle, wn);
4762 SetConsoleTitleW(szShellTitle);
4763 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004764 }
4765 }
4766 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004767#endif
4768
4769 out_flush();
4770
4771#ifdef MCH_WRITE_DUMP
4772 if (fdDump)
4773 {
4774 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4775 fflush(fdDump);
4776 }
4777#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004778#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004779 // TODO: make the terminal window work with input or output redirected.
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004780 if (
4781# ifdef VIMDLL
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004782 gui.in_use &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004783# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004784 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004785 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4786 {
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004787 char_u *cmdbase = cmd;
4788
Bram Moolenaar4d5c1262019-09-20 17:20:02 +02004789 if (cmdbase != NULL)
4790 // Skip a leading quote and (.
4791 while (*cmdbase == '"' || *cmdbase == '(')
4792 ++cmdbase;
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004793
4794 // Check the command does not begin with "start "
Bram Moolenaar36e7a822019-11-13 21:49:24 +01004795 if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4796 || !VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004797 {
4798 // Use a terminal window to run the command in.
4799 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004800# ifdef FEAT_TITLE
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004801 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004802# endif
Bram Moolenaar7c348bb2019-06-08 12:05:22 +02004803 return x;
4804 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004805 }
4806#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004807
4808 /*
4809 * Catch all deadly signals while running the external command, because a
4810 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4811 */
4812 signal(SIGINT, SIG_IGN);
4813#if defined(__GNUC__) && !defined(__MINGW32__)
4814 signal(SIGKILL, SIG_IGN);
4815#else
4816 signal(SIGBREAK, SIG_IGN);
4817#endif
4818 signal(SIGILL, SIG_IGN);
4819 signal(SIGFPE, SIG_IGN);
4820 signal(SIGSEGV, SIG_IGN);
4821 signal(SIGTERM, SIG_IGN);
4822 signal(SIGABRT, SIG_IGN);
4823
4824 if (options & SHELL_COOKED)
Bram Moolenaar0f873732019-12-05 20:28:46 +01004825 settmode(TMODE_COOK); // set to normal mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00004826
4827 if (cmd == NULL)
4828 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004829 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830 }
4831 else
4832 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004833 // we use "command" or "cmd" to start the shell; slow but easy
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004834 char_u *newcmd = NULL;
4835 char_u *cmdbase = cmd;
4836 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004837
Bram Moolenaar0f873732019-12-05 20:28:46 +01004838 // Skip a leading ", ( and "(.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004839 if (*cmdbase == '"' )
4840 ++cmdbase;
4841 if (*cmdbase == '(')
4842 ++cmdbase;
4843
Bram Moolenaar1c465442017-03-12 20:10:05 +01004844 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004845 {
4846 STARTUPINFO si;
4847 PROCESS_INFORMATION pi;
4848 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004849 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004850 char_u *p;
4851
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004852 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004853 si.cb = sizeof(si);
4854 si.lpReserved = NULL;
4855 si.lpDesktop = NULL;
4856 si.lpTitle = NULL;
4857 si.dwFlags = 0;
4858 si.cbReserved2 = 0;
4859 si.lpReserved2 = NULL;
4860
4861 cmdbase = skipwhite(cmdbase + 5);
4862 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004863 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004864 {
4865 cmdbase = skipwhite(cmdbase + 4);
4866 si.dwFlags = STARTF_USESHOWWINDOW;
4867 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004868 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004869 }
4870 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004871 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004872 {
4873 cmdbase = skipwhite(cmdbase + 2);
4874 flags = CREATE_NO_WINDOW;
4875 si.dwFlags = STARTF_USESTDHANDLES;
4876 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004878 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004879 NULL, // Security att.
4880 OPEN_EXISTING, // Open flags
4881 FILE_ATTRIBUTE_NORMAL, // File att.
4882 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004883 si.hStdOutput = si.hStdInput;
4884 si.hStdError = si.hStdInput;
4885 }
4886
Bram Moolenaar0f873732019-12-05 20:28:46 +01004887 // Remove a trailing ", ) and )" if they have a match
4888 // at the start of the command.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004889 if (cmdbase > cmd)
4890 {
4891 p = cmdbase + STRLEN(cmdbase);
4892 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4893 *--p = NUL;
4894 if (p > cmdbase && p[-1] == ')'
4895 && (*cmd =='(' || cmd[1] == '('))
4896 *--p = NUL;
4897 }
4898
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004899 newcmd = cmdbase;
4900 unescape_shellxquote(cmdbase, p_sxe);
4901
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004902 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004903 * If creating new console, arguments are passed to the
4904 * 'cmd.exe' as-is. If it's not, arguments are not treated
4905 * correctly for current 'cmd.exe'. So unescape characters in
4906 * shellxescape except '|' for avoiding to be treated as
4907 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004908 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004909 if (flags != CREATE_NEW_CONSOLE)
4910 {
4911 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004912 char_u *cmd_shell = mch_getenv("COMSPEC");
4913
4914 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004915 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004916
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004917 subcmd = vim_strsave_escaped_ext(cmdbase,
4918 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004919 if (subcmd != NULL)
4920 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004921 // make "cmd.exe /c arguments"
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004922 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004923 newcmd = alloc(cmdlen);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004924 if (newcmd != NULL)
4925 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004926 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004927 else
4928 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004929 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004930 }
4931 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004932
4933 /*
4934 * Now, start the command as a process, so that it doesn't
4935 * inherit our handles which causes unpleasant dangling swap
4936 * files if we exit before the spawned process
4937 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004938 if (vim_create_process((char *)newcmd, FALSE, flags,
4939 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004940 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004941 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4942 > (HINSTANCE)32)
4943 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004944 else
4945 {
4946 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004947#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004948# ifdef VIMDLL
4949 if (gui.in_use)
4950# endif
4951 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004952#endif
4953 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004954
4955 if (newcmd != cmdbase)
4956 vim_free(newcmd);
4957
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004958 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004959 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01004960 // Close the handle to \\.\NUL created above.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004961 CloseHandle(si.hStdInput);
4962 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01004963 // Close the handles to the subprocess, so that it goes away
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004964 CloseHandle(pi.hThread);
4965 CloseHandle(pi.hProcess);
4966 }
4967 else
4968 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004969 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004970#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004971 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004972 (!s_dont_use_vimrun && p_stmp ?
4973 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4974 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004975#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004976 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004977
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004978 newcmd = alloc(cmdlen);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004979 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004980 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004981#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004982 if (
4983# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004984 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004985# endif
4986 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004987 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004988 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4989 "External commands will not pause after completion.\n"
4990 "See :help win32-vimrun for more information.");
4991 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004992 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4993 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01004994
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004995 if (wmsg != NULL && wtitle != NULL)
4996 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4997 vim_free(wmsg);
4998 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999 need_vimrun_warning = FALSE;
5000 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005001 if (
5002# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005003 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005004# endif
5005 !s_dont_use_vimrun && p_stmp)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005006 // Use vimrun to execute the command. It opens a console
5007 // window, which can be closed without killing Vim.
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005008 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005009 vimrun_path,
5010 (msg_silent != 0 || (options & SHELL_DOOUT))
5011 ? "-s " : "",
5012 p_sh, p_shcf, cmd);
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005013 else if (
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005014# ifdef VIMDLL
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005015 (gui.in_use || gui.starting) &&
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005016# endif
Bram Moolenaar0e6bfb92019-07-31 20:53:56 +02005017 s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
Bram Moolenaarfcc4d922019-05-24 13:32:36 +02005018 // workaround for the case that "vimrun" does not exist
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005019 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5020 p_sh, p_shcf, p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02005021 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005022#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005023 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005024 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005026 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005027 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028 }
5029 }
5030
5031 if (tmode == TMODE_RAW)
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005032 {
5033 // The shell may have messed with the mode, always set it.
5034 cur_tmode = TMODE_UNKNOWN;
Bram Moolenaar0f873732019-12-05 20:28:46 +01005035 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar3b1f18f2020-05-16 23:15:08 +02005036 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005037
Bram Moolenaar0f873732019-12-05 20:28:46 +01005038 // Print the return value, unless "vimrun" was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005039 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01005040#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02005041 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005042 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043#endif
5044 )
5045 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005046 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005047 msg_putchar('\n');
5048 }
5049#ifdef FEAT_TITLE
5050 resettitle();
5051#endif
5052
5053 signal(SIGINT, SIG_DFL);
5054#if defined(__GNUC__) && !defined(__MINGW32__)
5055 signal(SIGKILL, SIG_DFL);
5056#else
5057 signal(SIGBREAK, SIG_DFL);
5058#endif
5059 signal(SIGILL, SIG_DFL);
5060 signal(SIGFPE, SIG_DFL);
5061 signal(SIGSEGV, SIG_DFL);
5062 signal(SIGTERM, SIG_DFL);
5063 signal(SIGABRT, SIG_DFL);
5064
5065 return x;
5066}
5067
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005068#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005069 static HANDLE
5070job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005071 char_u *fname,
5072 DWORD dwDesiredAccess,
5073 DWORD dwShareMode,
5074 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5075 DWORD dwCreationDisposition,
5076 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005077{
5078 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005079 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01005080
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005081 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005082 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005083 return INVALID_HANDLE_VALUE;
5084
5085 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5086 lpSecurityAttributes, dwCreationDisposition,
5087 dwFlagsAndAttributes, NULL);
5088 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005089 return h;
5090}
5091
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005092/*
5093 * Turn the dictionary "env" into a NUL separated list that can be used as the
5094 * environment argument of vim_create_process().
5095 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005096 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005097win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005098{
5099 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005100 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005101 LPVOID base = GetEnvironmentStringsW();
5102
Bram Moolenaar0f873732019-12-05 20:28:46 +01005103 // for last \0
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005104 if (ga_grow(gap, 1) == FAIL)
5105 return;
5106
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005107 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005108 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005109 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005110 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005111 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005112 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005113 typval_T *item = &dict_lookup(hi)->di_tv;
5114 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01005115 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005116 --todo;
5117 if (wkey != NULL && wval != NULL)
5118 {
5119 size_t n;
5120 size_t lkey = wcslen(wkey);
5121 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005122
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005123 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5124 continue;
5125 for (n = 0; n < lkey; n++)
5126 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5127 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5128 for (n = 0; n < lval; n++)
5129 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5130 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5131 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005132 vim_free(wkey);
5133 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005134 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005135 }
5136 }
5137
Bram Moolenaar355757a2020-02-10 22:06:32 +01005138 if (base)
5139 {
5140 WCHAR *p = (WCHAR*) base;
5141
5142 // for last \0
5143 if (ga_grow(gap, 1) == FAIL)
5144 return;
5145
5146 while (*p != 0 || *(p + 1) != 0)
5147 {
5148 if (ga_grow(gap, 1) == OK)
5149 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5150 p++;
5151 }
5152 FreeEnvironmentStrings(base);
5153 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5154 }
5155
Bram Moolenaar493359e2018-06-12 20:25:52 +02005156# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005157 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005158# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005159 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005160 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005161# endif
5162# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005163 char_u *version = get_vim_var_str(VV_VERSION);
5164 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005165# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005166 // size of "VIM_SERVERNAME=" and value,
5167 // plus "VIM_TERMINAL=" and value,
5168 // plus two terminating NULs
5169 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005170# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005171 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005172# endif
5173# ifdef FEAT_TERMINAL
5174 + 13 + version_len + 2
5175# endif
5176 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005177
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005178 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005179 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005180# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005181 for (n = 0; n < 15; n++)
5182 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5183 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005184 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005185 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5186 (WCHAR)servername[n];
5187 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005188# endif
5189# ifdef FEAT_TERMINAL
5190 if (is_terminal)
5191 {
5192 for (n = 0; n < 13; n++)
5193 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5194 (WCHAR)"VIM_TERMINAL="[n];
5195 for (n = 0; n < version_len; n++)
5196 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5197 (WCHAR)version[n];
5198 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5199 }
5200# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005201 }
5202 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005203# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005204}
5205
Bram Moolenaarb091f302019-01-19 14:37:00 +01005206/*
5207 * Create a pair of pipes.
5208 * Return TRUE for success, FALSE for failure.
5209 */
5210 static BOOL
5211create_pipe_pair(HANDLE handles[2])
5212{
5213 static LONG s;
5214 char name[64];
5215 SECURITY_ATTRIBUTES sa;
5216
5217 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5218 GetCurrentProcessId(),
5219 InterlockedIncrement(&s));
5220
5221 // Create named pipe. Max size of named pipe is 65535.
5222 handles[1] = CreateNamedPipe(
5223 name,
5224 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5225 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005226 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005227
5228 if (handles[1] == INVALID_HANDLE_VALUE)
5229 return FALSE;
5230
5231 sa.nLength = sizeof(sa);
5232 sa.bInheritHandle = TRUE;
5233 sa.lpSecurityDescriptor = NULL;
5234
5235 handles[0] = CreateFile(name,
5236 FILE_GENERIC_READ,
5237 FILE_SHARE_READ, &sa,
5238 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5239
5240 if (handles[0] == INVALID_HANDLE_VALUE)
5241 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005242 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005243 return FALSE;
5244 }
5245
5246 return TRUE;
5247}
5248
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005249 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005250mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005251{
5252 STARTUPINFO si;
5253 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005254 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005255 SECURITY_ATTRIBUTES saAttr;
5256 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005257 HANDLE ifd[2];
5258 HANDLE ofd[2];
5259 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005260 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005261
5262 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5263 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5264 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5265 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5266 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5267 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5268 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5269
5270 if (use_out_for_err && use_null_for_out)
5271 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005272
5273 ifd[0] = INVALID_HANDLE_VALUE;
5274 ifd[1] = INVALID_HANDLE_VALUE;
5275 ofd[0] = INVALID_HANDLE_VALUE;
5276 ofd[1] = INVALID_HANDLE_VALUE;
5277 efd[0] = INVALID_HANDLE_VALUE;
5278 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005279 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005280
Bram Moolenaar14207f42016-10-27 21:13:10 +02005281 jo = CreateJobObject(NULL, NULL);
5282 if (jo == NULL)
5283 {
5284 job->jv_status = JOB_FAILED;
5285 goto failed;
5286 }
5287
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005288 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005289 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005290
Bram Moolenaar76467df2016-02-12 19:30:26 +01005291 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005292 ZeroMemory(&si, sizeof(si));
5293 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005294 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005295 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005296
Bram Moolenaard8070362016-02-15 21:56:54 +01005297 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5298 saAttr.bInheritHandle = TRUE;
5299 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005300
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005301 if (use_file_for_in)
5302 {
5303 char_u *fname = options->jo_io_name[PART_IN];
5304
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005305 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5306 FILE_SHARE_READ | FILE_SHARE_WRITE,
5307 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5308 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005309 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005310 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005311 goto failed;
5312 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005313 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005314 else if (!use_null_for_in
5315 && (!create_pipe_pair(ifd)
5316 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005317 goto failed;
5318
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005319 if (use_file_for_out)
5320 {
5321 char_u *fname = options->jo_io_name[PART_OUT];
5322
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005323 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5324 FILE_SHARE_READ | FILE_SHARE_WRITE,
5325 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5326 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005327 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005328 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005329 goto failed;
5330 }
5331 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005332 else if (!use_null_for_out &&
5333 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005334 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005335 goto failed;
5336
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005337 if (use_file_for_err)
5338 {
5339 char_u *fname = options->jo_io_name[PART_ERR];
5340
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005341 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5342 FILE_SHARE_READ | FILE_SHARE_WRITE,
5343 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5344 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005345 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005346 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005347 goto failed;
5348 }
5349 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005350 else if (!use_out_for_err && !use_null_for_err &&
5351 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005352 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005353 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005354
Bram Moolenaard8070362016-02-15 21:56:54 +01005355 si.dwFlags |= STARTF_USESTDHANDLES;
5356 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005357 si.hStdOutput = ofd[1];
5358 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5359
5360 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5361 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005362 if (options->jo_set & JO_CHANNEL)
5363 {
5364 channel = options->jo_channel;
5365 if (channel != NULL)
5366 ++channel->ch_refcount;
5367 }
5368 else
5369 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005370 if (channel == NULL)
5371 goto failed;
5372 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005373
5374 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005375 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005376 CREATE_DEFAULT_ERROR_MODE |
5377 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005378 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005379 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005380 &si, &pi,
5381 ga.ga_data,
5382 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005383 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005384 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005385 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005386 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005387 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005388
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005389 ga_clear(&ga);
5390
Bram Moolenaar14207f42016-10-27 21:13:10 +02005391 if (!AssignProcessToJobObject(jo, pi.hProcess))
5392 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005393 // if failing, switch the way to terminate
5394 // process with TerminateProcess.
Bram Moolenaar14207f42016-10-27 21:13:10 +02005395 CloseHandle(jo);
5396 jo = NULL;
5397 }
5398 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005399 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005400 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005401 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005402 job->jv_status = JOB_STARTED;
5403
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005404 CloseHandle(ifd[0]);
5405 CloseHandle(ofd[1]);
5406 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005407 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005408
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005409 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005410 if (channel != NULL)
5411 {
5412 channel_set_pipes(channel,
5413 use_file_for_in || use_null_for_in
5414 ? INVALID_FD : (sock_T)ifd[1],
5415 use_file_for_out || use_null_for_out
5416 ? INVALID_FD : (sock_T)ofd[0],
5417 use_out_for_err || use_file_for_err || use_null_for_err
5418 ? INVALID_FD : (sock_T)efd[0]);
5419 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005420 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005421 return;
5422
5423failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005424 CloseHandle(ifd[0]);
5425 CloseHandle(ofd[0]);
5426 CloseHandle(efd[0]);
5427 CloseHandle(ifd[1]);
5428 CloseHandle(ofd[1]);
5429 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005430 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005431 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005432}
5433
5434 char *
5435mch_job_status(job_T *job)
5436{
5437 DWORD dwExitCode = 0;
5438
Bram Moolenaar76467df2016-02-12 19:30:26 +01005439 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5440 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005441 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005442 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005443 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005444 {
5445 ch_log(job->jv_channel, "Job ended");
5446 job->jv_status = JOB_ENDED;
5447 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005448 return "dead";
5449 }
5450 return "run";
5451}
5452
Bram Moolenaar97792de2016-10-15 18:36:49 +02005453 job_T *
5454mch_detect_ended_job(job_T *job_list)
5455{
5456 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5457 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5458 job_T *job = job_list;
5459
5460 while (job != NULL)
5461 {
5462 DWORD n;
5463 DWORD result;
5464
5465 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5466 && job != NULL; job = job->jv_next)
5467 {
5468 if (job->jv_status == JOB_STARTED)
5469 {
5470 jobHandles[n] = job->jv_proc_info.hProcess;
5471 jobArray[n] = job;
5472 ++n;
5473 }
5474 }
5475 if (n == 0)
5476 continue;
5477 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5478 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5479 {
5480 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5481
5482 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5483 return wait_job;
5484 }
5485 }
5486 return NULL;
5487}
5488
Bram Moolenaarfb630902016-10-29 14:55:00 +02005489 static BOOL
5490terminate_all(HANDLE process, int code)
5491{
5492 PROCESSENTRY32 pe;
5493 HANDLE h = INVALID_HANDLE_VALUE;
5494 DWORD pid = GetProcessId(process);
5495
5496 if (pid != 0)
5497 {
5498 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5499 if (h != INVALID_HANDLE_VALUE)
5500 {
5501 pe.dwSize = sizeof(PROCESSENTRY32);
5502 if (!Process32First(h, &pe))
5503 goto theend;
5504
5505 do
5506 {
5507 if (pe.th32ParentProcessID == pid)
5508 {
5509 HANDLE ph = OpenProcess(
5510 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5511 if (ph != NULL)
5512 {
5513 terminate_all(ph, code);
5514 CloseHandle(ph);
5515 }
5516 }
5517 } while (Process32Next(h, &pe));
5518
5519 CloseHandle(h);
5520 }
5521 }
5522
5523theend:
5524 return TerminateProcess(process, code);
5525}
5526
5527/*
5528 * Send a (deadly) signal to "job".
5529 * Return FAIL if it didn't work.
5530 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005531 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005532mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005533{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005534 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005535
Bram Moolenaar923d9262016-02-25 20:56:01 +01005536 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005537 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01005538 // deadly signal
Bram Moolenaar14207f42016-10-27 21:13:10 +02005539 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005540 {
5541 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5542 job->jv_channel->ch_killing = TRUE;
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005543 return TerminateJobObject(job->jv_job_object, -1) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005544 }
Bram Moolenaarb3e195c2020-02-10 21:32:19 +01005545 return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005546 }
5547
5548 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5549 return FAIL;
5550 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005551 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5552 job->jv_proc_info.dwProcessId)
5553 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005554 FreeConsole();
5555 return ret;
5556}
5557
5558/*
5559 * Clear the data related to "job".
5560 */
5561 void
5562mch_clear_job(job_T *job)
5563{
5564 if (job->jv_status != JOB_FAILED)
5565 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005566 if (job->jv_job_object != NULL)
5567 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005568 CloseHandle(job->jv_proc_info.hProcess);
5569 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005570}
5571#endif
5572
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005574#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575
5576/*
5577 * Start termcap mode
5578 */
5579 static void
5580termcap_mode_start(void)
5581{
5582 DWORD cmodein;
5583
5584 if (g_fTermcapMode)
5585 return;
5586
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005587 if (!p_rs && USE_VTP)
5588 vtp_printf("\033[?1049h");
5589
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 SaveConsoleBuffer(&g_cbNonTermcap);
5591
5592 if (g_cbTermcap.IsValid)
5593 {
5594 /*
5595 * We've been in termcap mode before. Restore certain screen
5596 * characteristics, including the buffer size and the window
5597 * size. Since we will be redrawing the screen, we don't need
5598 * to restore the actual contents of the buffer.
5599 */
5600 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005601 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005602 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5603 Rows = g_cbTermcap.Info.dwSize.Y;
5604 Columns = g_cbTermcap.Info.dwSize.X;
5605 }
5606 else
5607 {
5608 /*
5609 * This is our first time entering termcap mode. Clear the console
5610 * screen buffer, and resize the buffer to match the current window
5611 * size. We will use this as the size of our editing environment.
5612 */
5613 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005614 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005615 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5616 }
5617
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005618# ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005619 resettitle();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005620# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621
5622 GetConsoleMode(g_hConIn, &cmodein);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 if (g_fMouseActive)
5624 cmodein |= ENABLE_MOUSE_INPUT;
5625 else
5626 cmodein &= ~ENABLE_MOUSE_INPUT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627 cmodein |= ENABLE_WINDOW_INPUT;
5628 SetConsoleMode(g_hConIn, cmodein);
5629
5630 redraw_later_clear();
5631 g_fTermcapMode = TRUE;
5632}
5633
5634
5635/*
5636 * End termcap mode
5637 */
5638 static void
5639termcap_mode_end(void)
5640{
5641 DWORD cmodein;
5642 ConsoleBuffer *cb;
5643 COORD coord;
5644 DWORD dwDummy;
5645
5646 if (!g_fTermcapMode)
5647 return;
5648
5649 SaveConsoleBuffer(&g_cbTermcap);
5650
5651 GetConsoleMode(g_hConIn, &cmodein);
5652 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5653 SetConsoleMode(g_hConIn, cmodein);
5654
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005655# ifdef FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005656 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005657# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005658 cb = &g_cbNonTermcap;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01005659# endif
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005660 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaardf543822020-01-30 11:53:59 +01005661 restore_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005662 SetConsoleCursorInfo(g_hConOut, &g_cci);
5663
5664 if (p_rs || exiting)
5665 {
5666 /*
5667 * Clear anything that happens to be on the current line.
5668 */
5669 coord.X = 0;
5670 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5671 FillConsoleOutputCharacter(g_hConOut, ' ',
5672 cb->Info.dwSize.X, coord, &dwDummy);
5673 /*
5674 * The following is just for aesthetics. If we are exiting without
5675 * restoring the screen, then we want to have a prompt string
5676 * appear at the bottom line. However, the command interpreter
5677 * seems to always advance the cursor one line before displaying
5678 * the prompt string, which causes the screen to scroll. To
5679 * counter this, move the cursor up one line before exiting.
5680 */
5681 if (exiting && !p_rs)
5682 coord.Y--;
5683 /*
5684 * Position the cursor at the leftmost column of the desired row.
5685 */
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005686 SetConsoleCursorPosition(g_hConOut, coord);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005687 }
5688
Bram Moolenaar81ccbf12020-04-15 21:05:30 +02005689 if (!p_rs && USE_VTP)
Bram Moolenaar0afdcf82020-04-01 18:29:10 +02005690 vtp_printf("\033[?1049l");
5691
Bram Moolenaar071d4272004-06-13 20:20:40 +00005692 g_fTermcapMode = FALSE;
5693}
Bram Moolenaar0f873732019-12-05 20:28:46 +01005694#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695
5696
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005697#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698 void
5699mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005700 char_u *s UNUSED,
5701 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005702{
Bram Moolenaar0f873732019-12-05 20:28:46 +01005703 // never used
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704}
5705
5706#else
5707
5708/*
5709 * clear `n' chars, starting from `coord'
5710 */
5711 static void
5712clear_chars(
5713 COORD coord,
5714 DWORD n)
5715{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005716 if (!USE_VTP)
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02005717 {
5718 DWORD dwDummy;
5719
5720 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5721 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5722 &dwDummy);
5723 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005724 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005725 {
5726 set_console_color_rgb();
5727 gotoxy(coord.X + 1, coord.Y + 1);
5728 vtp_printf("\033[%dX", n);
5729 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005730}
5731
5732
5733/*
5734 * Clear the screen
5735 */
5736 static void
5737clear_screen(void)
5738{
5739 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005740
5741 if (!USE_VTP)
5742 clear_chars(g_coord, Rows * Columns);
5743 else
5744 {
5745 set_console_color_rgb();
5746 gotoxy(1, 1);
5747 vtp_printf("\033[2J");
5748 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005749}
5750
5751
5752/*
5753 * Clear to end of display
5754 */
5755 static void
5756clear_to_end_of_display(void)
5757{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005758 COORD save = g_coord;
5759
5760 if (!USE_VTP)
5761 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005762 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005763 else
5764 {
5765 set_console_color_rgb();
5766 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5767 vtp_printf("\033[0J");
5768
5769 gotoxy(save.X + 1, save.Y + 1);
5770 g_coord = save;
5771 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005772}
5773
5774
5775/*
5776 * Clear to end of line
5777 */
5778 static void
5779clear_to_end_of_line(void)
5780{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005781 COORD save = g_coord;
5782
5783 if (!USE_VTP)
5784 clear_chars(g_coord, Columns - g_coord.X);
5785 else
5786 {
5787 set_console_color_rgb();
5788 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5789 vtp_printf("\033[0K");
5790
5791 gotoxy(save.X + 1, save.Y + 1);
5792 g_coord = save;
5793 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794}
5795
5796
5797/*
5798 * Scroll the scroll region up by `cLines' lines
5799 */
5800 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005801scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802{
5803 COORD oldcoord = g_coord;
5804
5805 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5806 delete_lines(cLines);
5807
5808 g_coord = oldcoord;
5809}
5810
5811
5812/*
5813 * Set the scroll region
5814 */
5815 static void
5816set_scroll_region(
5817 unsigned left,
5818 unsigned top,
5819 unsigned right,
5820 unsigned bottom)
5821{
5822 if (left >= right
5823 || top >= bottom
5824 || right > (unsigned) Columns - 1
5825 || bottom > (unsigned) Rows - 1)
5826 return;
5827
5828 g_srScrollRegion.Left = left;
5829 g_srScrollRegion.Top = top;
5830 g_srScrollRegion.Right = right;
5831 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005832}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005833
Bram Moolenaar6982f422019-02-16 16:48:01 +01005834 static void
5835set_scroll_region_tb(
5836 unsigned top,
5837 unsigned bottom)
5838{
5839 if (top >= bottom || bottom > (unsigned)Rows - 1)
5840 return;
5841
5842 g_srScrollRegion.Top = top;
5843 g_srScrollRegion.Bottom = bottom;
5844}
5845
5846 static void
5847set_scroll_region_lr(
5848 unsigned left,
5849 unsigned right)
5850{
5851 if (left >= right || right > (unsigned)Columns - 1)
5852 return;
5853
5854 g_srScrollRegion.Left = left;
5855 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856}
5857
5858
5859/*
5860 * Insert `cLines' lines at the current cursor position
5861 */
5862 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005863insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005864{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005865 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005866 COORD dest;
5867 CHAR_INFO fill;
5868
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005869 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5870
Bram Moolenaar6982f422019-02-16 16:48:01 +01005871 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872 dest.Y = g_coord.Y + cLines;
5873
Bram Moolenaar6982f422019-02-16 16:48:01 +01005874 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875 source.Top = g_coord.Y;
5876 source.Right = g_srScrollRegion.Right;
5877 source.Bottom = g_srScrollRegion.Bottom - cLines;
5878
Bram Moolenaar6982f422019-02-16 16:48:01 +01005879 clip.Left = g_srScrollRegion.Left;
5880 clip.Top = g_coord.Y;
5881 clip.Right = g_srScrollRegion.Right;
5882 clip.Bottom = g_srScrollRegion.Bottom;
5883
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005884 fill.Char.AsciiChar = ' ';
5885 if (!USE_VTP)
5886 fill.Attributes = g_attrCurrent;
5887 else
5888 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005889
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005890 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005891
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005892 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5893
Bram Moolenaar6982f422019-02-16 16:48:01 +01005894 // Here we have to deal with a win32 console flake: If the scroll
5895 // region looks like abc and we scroll c to a and fill with d we get
5896 // cbd... if we scroll block c one line at a time to a, we get cdd...
5897 // vim expects cdd consistently... So we have to deal with that
5898 // here... (this also occurs scrolling the same way in the other
5899 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005900
5901 if (source.Bottom < dest.Y)
5902 {
5903 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005904 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005905
Bram Moolenaar6982f422019-02-16 16:48:01 +01005906 coord.X = source.Left;
5907 for (i = clip.Top; i < dest.Y; ++i)
5908 {
5909 coord.Y = i;
5910 clear_chars(coord, source.Right - source.Left + 1);
5911 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005913
5914 if (USE_WT)
5915 {
5916 COORD coord;
5917 int i;
5918
5919 coord.X = source.Left;
5920 for (i = source.Top; i < dest.Y; ++i)
5921 {
5922 coord.Y = i;
5923 clear_chars(coord, source.Right - source.Left + 1);
5924 }
5925 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005926}
5927
5928
5929/*
5930 * Delete `cLines' lines at the current cursor position
5931 */
5932 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005933delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005935 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 COORD dest;
5937 CHAR_INFO fill;
5938 int nb;
5939
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005940 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5941
Bram Moolenaar6982f422019-02-16 16:48:01 +01005942 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943 dest.Y = g_coord.Y;
5944
Bram Moolenaar6982f422019-02-16 16:48:01 +01005945 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946 source.Top = g_coord.Y + cLines;
5947 source.Right = g_srScrollRegion.Right;
5948 source.Bottom = g_srScrollRegion.Bottom;
5949
Bram Moolenaar6982f422019-02-16 16:48:01 +01005950 clip.Left = g_srScrollRegion.Left;
5951 clip.Top = g_coord.Y;
5952 clip.Right = g_srScrollRegion.Right;
5953 clip.Bottom = g_srScrollRegion.Bottom;
5954
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005955 fill.Char.AsciiChar = ' ';
5956 if (!USE_VTP)
5957 fill.Attributes = g_attrCurrent;
5958 else
5959 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005960
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005961 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005962
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005963 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5964
Bram Moolenaar6982f422019-02-16 16:48:01 +01005965 // Here we have to deal with a win32 console flake; See insert_lines()
5966 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967
5968 nb = dest.Y + (source.Bottom - source.Top) + 1;
5969
5970 if (nb < source.Top)
5971 {
5972 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005973 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005974
Bram Moolenaar6982f422019-02-16 16:48:01 +01005975 coord.X = source.Left;
5976 for (i = nb; i < clip.Bottom; ++i)
5977 {
5978 coord.Y = i;
5979 clear_chars(coord, source.Right - source.Left + 1);
5980 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005981 }
Bram Moolenaar06b7b582020-05-30 17:49:25 +02005982
5983 if (USE_WT)
5984 {
5985 COORD coord;
5986 int i;
5987
5988 coord.X = source.Left;
5989 for (i = nb; i <= source.Bottom; ++i)
5990 {
5991 coord.Y = i;
5992 clear_chars(coord, source.Right - source.Left + 1);
5993 }
5994 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005995}
5996
5997
5998/*
Bram Moolenaar2313b612019-09-27 14:14:32 +02005999 * Set the cursor position to (x,y) (1-based).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006000 */
6001 static void
6002gotoxy(
6003 unsigned x,
6004 unsigned y)
6005{
6006 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6007 return;
6008
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006009 if (!USE_VTP)
Bram Moolenaar2313b612019-09-27 14:14:32 +02006010 {
Bram Moolenaar82e743c2020-03-26 15:39:53 +01006011 // There are reports of double-width characters not displayed
6012 // correctly. This workaround should fix it, similar to how it's done
6013 // for VTP.
6014 g_coord.X = 0;
6015 SetConsoleCursorPosition(g_hConOut, g_coord);
6016
Bram Moolenaar2313b612019-09-27 14:14:32 +02006017 // external cursor coords are 1-based; internal are 0-based
6018 g_coord.X = x - 1;
6019 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006020 SetConsoleCursorPosition(g_hConOut, g_coord);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006021 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006022 else
Bram Moolenaar2313b612019-09-27 14:14:32 +02006023 {
6024 // Move the cursor to the left edge of the screen to prevent screen
Bram Moolenaara1299742019-10-10 16:36:00 +02006025 // destruction. Insider build bug. Always enabled because it's cheap
6026 // and avoids mistakes with recognizing the build.
6027 vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006028
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006029 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar2313b612019-09-27 14:14:32 +02006030
6031 g_coord.X = x - 1;
6032 g_coord.Y = y - 1;
6033 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006034}
6035
6036
6037/*
6038 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006039 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006040 */
6041 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006042textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006043{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006044 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006045
6046 SetConsoleTextAttribute(g_hConOut, wAttr);
6047}
6048
6049
6050 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006051textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006053 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006055 if (!USE_VTP)
6056 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6057 else
6058 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006059}
6060
6061
6062 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006063textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006064{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006065 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006067 if (!USE_VTP)
6068 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6069 else
6070 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006071}
6072
6073
6074/*
6075 * restore the default text attribute (whatever we started with)
6076 */
6077 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006078normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006079{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006080 if (!USE_VTP)
6081 textattr(g_attrDefault);
6082 else
6083 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084}
6085
6086
6087static WORD g_attrPreStandout = 0;
6088
6089/*
6090 * Make the text standout, by brightening it
6091 */
6092 static void
6093standout(void)
6094{
6095 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006096
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6098}
6099
6100
6101/*
6102 * Turn off standout mode
6103 */
6104 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006105standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106{
6107 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006109
6110 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006111}
6112
6113
6114/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006115 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 */
6117 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006118mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006119{
6120 char_u *p;
6121 int n;
6122
6123 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6124 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006125 if (
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006126# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006127 !p_tgc &&
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006128# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006129 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130 {
6131 p = T_ME + 2;
6132 n = getdigits(&p);
6133 if (*p == 'm' && n > 0)
6134 {
6135 cterm_normal_fg_color = (n & 0xf) + 1;
6136 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6137 }
6138 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006139# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006140 cterm_normal_fg_gui_color = INVALCOLOR;
6141 cterm_normal_bg_gui_color = INVALCOLOR;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006142# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143}
6144
6145
6146/*
6147 * visual bell: flash the screen
6148 */
6149 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006150visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006151{
6152 COORD coordOrigin = {0, 0};
6153 WORD attrFlash = ~g_attrCurrent & 0xff;
6154
6155 DWORD dwDummy;
Bram Moolenaarc799fe22019-05-28 23:08:19 +02006156 LPWORD oldattrs = ALLOC_MULT(WORD, Rows * Columns);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157
6158 if (oldattrs == NULL)
6159 return;
6160 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6161 coordOrigin, &dwDummy);
6162 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6163 coordOrigin, &dwDummy);
6164
Bram Moolenaar0f873732019-12-05 20:28:46 +01006165 Sleep(15); // wait for 15 msec
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006166 if (!USE_VTP)
6167 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 coordOrigin, &dwDummy);
6169 vim_free(oldattrs);
6170}
6171
6172
6173/*
6174 * Make the cursor visible or invisible
6175 */
6176 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006177cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178{
6179 s_cursor_visible = fVisible;
Bram Moolenaar2695de62020-04-17 21:13:01 +02006180
6181 if (USE_VTP)
6182 vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6183
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006184# ifdef MCH_CURSOR_SHAPE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185 mch_update_cursor();
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006186# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187}
6188
6189
6190/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006191 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006192 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006193 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006194 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006195write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006196 char_u *pchBuf,
6197 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006199 COORD coord = g_coord;
6200 DWORD written;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006201 DWORD n, cchwritten;
6202 static DWORD cells;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006203 static WCHAR *unicodebuf = NULL;
6204 static int unibuflen = 0;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006205 static int length;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006206 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006207 static WCHAR *utf8spbuf = NULL;
6208 static int utf8splength;
6209 static DWORD utf8spcells;
6210 static WCHAR **utf8usingbuf = &unicodebuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006212 if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006213 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006214 utf8usingbuf = &unicodebuf;
6215 do
6216 {
6217 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6218 unicodebuf, unibuflen);
6219 if (length && length <= unibuflen)
6220 break;
6221 vim_free(unicodebuf);
6222 unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6223 unibuflen = unibuflen ? 0 : length;
6224 } while(1);
6225 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006226 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006227 else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6228 {
6229 if (utf8usingbuf != &utf8spbuf)
6230 {
6231 if (utf8spbuf == NULL)
6232 {
6233 cells = mb_string2cells((char_u *)" ", 1);
6234 length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6235 utf8spbuf = LALLOC_MULT(WCHAR, length);
6236 if (utf8spbuf != NULL)
6237 {
6238 MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6239 utf8usingbuf = &utf8spbuf;
6240 utf8splength = length;
6241 utf8spcells = cells;
6242 }
6243 }
6244 else
6245 {
6246 utf8usingbuf = &utf8spbuf;
6247 length = utf8splength;
6248 cells = utf8spcells;
6249 }
6250 }
6251 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006252
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006253 if (!USE_VTP)
6254 {
6255 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6256 coord, &written);
6257 // When writing fails or didn't write a single character, pretend one
6258 // character was written, otherwise we get stuck.
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006259 if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006260 coord, &cchwritten) == 0
6261 || cchwritten == 0 || cchwritten == (DWORD)-1)
6262 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006263 }
6264 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006265 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006266 if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006267 NULL) == 0 || cchwritten == 0)
6268 cchwritten = 1;
6269 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006270
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006271 if (cchwritten == length)
6272 {
6273 written = cbToWrite;
6274 g_coord.X += (SHORT)cells;
6275 }
6276 else
6277 {
6278 char_u *p = pchBuf;
6279 for (n = 0; n < cchwritten; n++)
6280 MB_CPTR_ADV(p);
6281 written = p - pchBuf;
6282 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006283 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284
6285 while (g_coord.X > g_srScrollRegion.Right)
6286 {
6287 g_coord.X -= (SHORT) Columns;
6288 if (g_coord.Y < g_srScrollRegion.Bottom)
6289 g_coord.Y++;
6290 }
6291
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006292 // Cursor under VTP is always in the correct position, no need to reset.
6293 if (!USE_VTP)
6294 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295
6296 return written;
6297}
6298
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006299 static char_u *
6300get_seq(
6301 int *args,
6302 int *count,
6303 char_u *head)
6304{
6305 int argc;
6306 char_u *p;
6307
6308 if (head == NULL || *head != '\033')
6309 return NULL;
6310
6311 argc = 0;
6312 p = head;
6313 ++p;
6314 do
6315 {
6316 ++p;
6317 args[argc] = getdigits(&p);
6318 argc += (argc < 15) ? 1 : 0;
6319 } while (*p == ';');
6320 *count = argc;
6321
6322 return p;
6323}
6324
6325 static char_u *
6326get_sgr(
6327 int *args,
6328 int *count,
6329 char_u *head)
6330{
6331 char_u *p = get_seq(args, count, head);
6332
6333 return (p && *p == 'm') ? ++p : NULL;
6334}
6335
6336/*
6337 * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6338 */
6339 static char_u *
6340sgrn2(
6341 char_u *head,
6342 int n)
6343{
6344 int argc;
6345 int args[16];
6346 char_u *p = get_sgr(args, &argc, head);
6347
6348 return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6349}
6350
6351/*
6352 * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6353 */
6354 static char_u *
6355sgrnc(
6356 char_u *head,
6357 int n)
6358{
6359 int argc;
6360 int args[16];
6361 char_u *p = get_sgr(args, &argc, head);
6362
6363 return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6364 ? p : NULL;
6365}
6366
6367 static char_u *
6368skipblank(char_u *q)
6369{
6370 char_u *p = q;
6371
6372 while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6373 ++p;
6374 return p;
6375}
6376
6377/*
6378 * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6379 * NULL.
6380 */
6381 static char_u *
6382sgrn2c(
6383 char_u *head,
6384 int n)
6385{
6386 char_u *p = sgrn2(head, n);
6387
6388 return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6389}
6390
6391/*
6392 * If there is only a newline between the sequence immediately following it,
6393 * a pointer to the character following the newline is returned.
6394 * Otherwise NULL.
6395 */
6396 static char_u *
6397sgrn2cn(
6398 char_u *head,
6399 int n)
6400{
6401 char_u *p = sgrn2(head, n);
6402
6403 return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6404}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405
6406/*
6407 * mch_write(): write the output buffer to the screen, translating ESC
6408 * sequences into calls to console output routines.
6409 */
6410 void
6411mch_write(
6412 char_u *s,
6413 int len)
6414{
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006415 char_u *end = s + len;
6416
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006417# ifdef VIMDLL
6418 if (gui.in_use)
6419 return;
6420# endif
6421
Bram Moolenaar071d4272004-06-13 20:20:40 +00006422 if (!term_console)
6423 {
6424 write(1, s, (unsigned)len);
6425 return;
6426 }
6427
Bram Moolenaar0f873732019-12-05 20:28:46 +01006428 // translate ESC | sequences into faked bios calls
Bram Moolenaar071d4272004-06-13 20:20:40 +00006429 while (len--)
6430 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006431 int prefix = -1;
6432 char_u ch;
6433
6434 // While processing a sequence, on rare occasions it seems that another
6435 // sequence may be inserted asynchronously.
6436 if (len < 0)
6437 {
6438 redraw_all_later(CLEAR);
6439 return;
6440 }
6441
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006442 while (s + ++prefix < end)
6443 {
6444 ch = s[prefix];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006445 if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6446 && ch != '\a' && ch != '\033'))
6447 break;
Bram Moolenaard23f8bd2021-04-21 11:30:48 +02006448 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006449
6450 if (p_wd)
6451 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006452 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453 if (prefix != 0)
6454 prefix = 1;
6455 }
6456
6457 if (prefix != 0)
6458 {
6459 DWORD nWritten;
6460
6461 nWritten = write_chars(s, prefix);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006462# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006463 if (fdDump)
6464 {
6465 fputc('>', fdDump);
6466 fwrite(s, sizeof(char_u), nWritten, fdDump);
6467 fputs("<\n", fdDump);
6468 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006469# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470 len -= (nWritten - 1);
6471 s += nWritten;
6472 }
6473 else if (s[0] == '\n')
6474 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006475 // \n, newline: go to the beginning of the next line or scroll
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476 if (g_coord.Y == g_srScrollRegion.Bottom)
6477 {
6478 scroll(1);
6479 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6480 }
6481 else
6482 {
6483 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6484 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006485# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486 if (fdDump)
6487 fputs("\\n\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006488# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 s++;
6490 }
6491 else if (s[0] == '\r')
6492 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006493 // \r, carriage return: go to beginning of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00006494 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006495# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496 if (fdDump)
6497 fputs("\\r\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006498# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006499 s++;
6500 }
6501 else if (s[0] == '\b')
6502 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006503 // \b, backspace: move cursor one position left
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504 if (g_coord.X > g_srScrollRegion.Left)
6505 g_coord.X--;
6506 else if (g_coord.Y > g_srScrollRegion.Top)
6507 {
6508 g_coord.X = g_srScrollRegion.Right;
6509 g_coord.Y--;
6510 }
6511 gotoxy(g_coord.X + 1, g_coord.Y + 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006512# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 if (fdDump)
6514 fputs("\\b\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006515# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006516 s++;
6517 }
6518 else if (s[0] == '\a')
6519 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006520 // \a, bell
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 MessageBeep(0xFFFFFFFF);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006522# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523 if (fdDump)
6524 fputs("\\a\n", fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006525# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526 s++;
6527 }
6528 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6529 {
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006530# ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006531 char_u *old_s = s;
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006532# endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006533 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006534 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006535 char_u *sp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536
6537 switch (s[2])
6538 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 case '0': case '1': case '2': case '3': case '4':
6540 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006541 if (*(p = get_seq(args, &argc, s)) != 'm')
6542 goto notsgr;
6543
6544 p = s;
6545
6546 // Handling frequent optional sequences. Output to the screen
6547 // takes too long, so do not output as much as possible.
6548
6549 // If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6550 // resetFG,FG,BG are omitted.
6551 if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006552 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006553 p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6554 len = len + 1 - (int)(p - s);
6555 s = p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556 break;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006557 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006558
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02006559 // If FG,BG,BG,FG of SGR are connected, the first FG can be
6560 // omitted.
6561 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6562 p = sp;
6563
6564 // If FG,BG,FG,BG of SGR are connected, the first FG can be
6565 // omitted.
6566 if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6567 p = sp;
6568
6569 // If BG,BG of SGR are connected, the first BG can be omitted.
6570 if (sgrn2((sp = sgrn2(p, 48)), 48))
6571 p = sp;
6572
6573 // If restoreFG and FG are connected, the restoreFG can be
6574 // omitted.
6575 if (sgrn2((sp = sgrnc(p, 39)), 38))
6576 p = sp;
6577
6578 p = get_seq(args, &argc, p);
6579
6580notsgr:
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006581 arg1 = args[0];
6582 arg2 = args[1];
6583 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006584 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006585 if (argc == 1 && args[0] == 0)
6586 normvideo();
6587 else if (argc == 1)
6588 {
6589 if (USE_VTP)
6590 textcolor((WORD) arg1);
6591 else
6592 textattr((WORD) arg1);
6593 }
6594 else if (USE_VTP)
6595 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006596 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006597 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006599 gotoxy(arg2, arg1);
6600 }
6601 else if (argc == 2 && *p == 'r')
6602 {
6603 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6604 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006605 else if (argc == 2 && *p == 'R')
6606 {
6607 set_scroll_region_tb(arg1, arg2);
6608 }
6609 else if (argc == 2 && *p == 'V')
6610 {
6611 set_scroll_region_lr(arg1, arg2);
6612 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006613 else if (argc == 1 && *p == 'A')
6614 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006615 gotoxy(g_coord.X + 1,
6616 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6617 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006618 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619 {
6620 textbackground((WORD) arg1);
6621 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006622 else if (argc == 1 && *p == 'C')
6623 {
6624 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6625 g_coord.Y + 1);
6626 }
6627 else if (argc == 1 && *p == 'f')
6628 {
6629 textcolor((WORD) arg1);
6630 }
6631 else if (argc == 1 && *p == 'H')
6632 {
6633 gotoxy(1, arg1);
6634 }
6635 else if (argc == 1 && *p == 'L')
6636 {
6637 insert_lines(arg1);
6638 }
6639 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006640 {
6641 delete_lines(arg1);
6642 }
6643
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006644 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 s = p + 1;
6646 break;
6647
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 gotoxy(g_coord.X + 1,
6650 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6651 goto got3;
6652
6653 case 'B':
6654 visual_bell();
6655 goto got3;
6656
6657 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6659 g_coord.Y + 1);
6660 goto got3;
6661
6662 case 'E':
6663 termcap_mode_end();
6664 goto got3;
6665
6666 case 'F':
6667 standout();
6668 goto got3;
6669
6670 case 'f':
6671 standend();
6672 goto got3;
6673
6674 case 'H':
6675 gotoxy(1, 1);
6676 goto got3;
6677
6678 case 'j':
6679 clear_to_end_of_display();
6680 goto got3;
6681
6682 case 'J':
6683 clear_screen();
6684 goto got3;
6685
6686 case 'K':
6687 clear_to_end_of_line();
6688 goto got3;
6689
6690 case 'L':
6691 insert_lines(1);
6692 goto got3;
6693
6694 case 'M':
6695 delete_lines(1);
6696 goto got3;
6697
6698 case 'S':
6699 termcap_mode_start();
6700 goto got3;
6701
6702 case 'V':
6703 cursor_visible(TRUE);
6704 goto got3;
6705
6706 case 'v':
6707 cursor_visible(FALSE);
6708 goto got3;
6709
6710 got3:
6711 s += 3;
6712 len -= 2;
6713 }
6714
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006715# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716 if (fdDump)
6717 {
6718 fputs("ESC | ", fdDump);
6719 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6720 fputc('\n', fdDump);
6721 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006722# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723 }
6724 else
6725 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006726 // Write a single character
Bram Moolenaar071d4272004-06-13 20:20:40 +00006727 DWORD nWritten;
6728
6729 nWritten = write_chars(s, 1);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006730# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006731 if (fdDump)
6732 {
6733 fputc('>', fdDump);
6734 fwrite(s, sizeof(char_u), nWritten, fdDump);
6735 fputs("<\n", fdDump);
6736 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006737# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006738
6739 len -= (nWritten - 1);
6740 s += nWritten;
6741 }
6742 }
6743
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006744# ifdef MCH_WRITE_DUMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745 if (fdDump)
6746 fflush(fdDump);
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01006747# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006748}
6749
Bram Moolenaar0f873732019-12-05 20:28:46 +01006750#endif // FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006751
6752
6753/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006754 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755 */
6756 void
6757mch_delay(
6758 long msec,
Bram Moolenaar0981c872020-08-23 14:28:37 +02006759 int flags UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006761#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01006762 Sleep((int)msec); // never wait for input
6763#else // Console
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006764# ifdef VIMDLL
6765 if (gui.in_use)
6766 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006767 Sleep((int)msec); // never wait for input
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006768 return;
6769 }
6770# endif
Bram Moolenaar0981c872020-08-23 14:28:37 +02006771 if (flags & MCH_DELAY_IGNOREINPUT)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006772# ifdef FEAT_MZSCHEME
6773 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6774 {
6775 int towait = p_mzq;
6776
Bram Moolenaar0f873732019-12-05 20:28:46 +01006777 // if msec is large enough, wait by portions in p_mzq
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006778 while (msec > 0)
6779 {
6780 mzvim_check_threads();
6781 if (msec < towait)
6782 towait = msec;
6783 Sleep(towait);
6784 msec -= towait;
6785 }
6786 }
6787 else
6788# endif
6789 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006791 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792#endif
6793}
6794
6795
6796/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006797 * This version of remove is not scared by a readonly (backup) file.
6798 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006799 * Return 0 for success, -1 for failure.
6800 */
6801 int
6802mch_remove(char_u *name)
6803{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006804 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006805 int n;
6806
Bram Moolenaar203258c2016-01-17 22:15:16 +01006807 /*
6808 * On Windows, deleting a directory's symbolic link is done by
6809 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6810 */
6811 if (mch_isdir(name) && mch_is_symbolic_link(name))
6812 return mch_rmdir(name);
6813
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006814 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6815
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006816 wn = enc_to_utf16(name, NULL);
6817 if (wn == NULL)
6818 return -1;
6819
6820 n = DeleteFileW(wn) ? 0 : -1;
6821 vim_free(wn);
6822 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823}
6824
6825
6826/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006827 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828 */
6829 void
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02006830mch_breakcheck(int force UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006832#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6833# ifdef VIMDLL
6834 if (!gui.in_use)
6835# endif
6836 if (g_fCtrlCPressed || g_fCBrkPressed)
6837 {
6838 ctrl_break_was_pressed = g_fCBrkPressed;
6839 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6840 got_int = TRUE;
6841 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842#endif
6843}
6844
Bram Moolenaar0f873732019-12-05 20:28:46 +01006845// physical RAM to leave for the OS
Bram Moolenaaree273972016-01-02 21:11:51 +01006846#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006847
6848/*
6849 * How much main memory in KiB that can be used by VIM.
6850 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006851 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006852mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006853{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006854 MEMORYSTATUSEX ms;
6855
Bram Moolenaar0f873732019-12-05 20:28:46 +01006856 // Need to use GlobalMemoryStatusEx() when there is more memory than
6857 // what fits in 32 bits.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006858 ms.dwLength = sizeof(MEMORYSTATUSEX);
6859 GlobalMemoryStatusEx(&ms);
6860 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006861 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006862 // Process address space fits in physical RAM, use all of it.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006863 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006864 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006865 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006866 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01006867 // Catch old NT box or perverse hardware setup.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006868 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006869 }
Bram Moolenaar0f873732019-12-05 20:28:46 +01006870 // Use physical RAM less reserve for OS + data.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006871 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006872}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006873
Bram Moolenaar071d4272004-06-13 20:20:40 +00006874/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006875 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6877 * file whose short file name is "FOO.BAR" (its long file name will
6878 * be correct: "foo.bar~"). Because a file can be accessed by
6879 * either its SFN or its LFN, "foo.bar" has effectively been
6880 * renamed to "foo.bar", which is not at all what was wanted. This
6881 * seems to happen only when renaming files with three-character
6882 * extensions by appending a suffix that does not include ".".
6883 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6884 *
6885 * There is another problem, which isn't really a bug but isn't right either:
6886 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6887 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6888 * service pack 6. Doesn't seem to happen on Windows 98.
6889 *
6890 * Like rename(), returns 0 upon success, non-zero upon failure.
6891 * Should probably set errno appropriately when errors occur.
6892 */
6893 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006894mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006896 WCHAR *p;
6897 int i;
6898 WCHAR szTempFile[_MAX_PATH + 1];
6899 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006900 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006902 // No need to play tricks unless the file name contains a "~" as the
6903 // seventh character.
6904 p = wold;
6905 for (i = 0; wold[i] != NUL; ++i)
6906 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6907 && wold[i + 1] != 0)
6908 p = wold + i + 1;
6909 if ((int)(wold + i - p) < 8 || p[6] != '~')
6910 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006911
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006912 // Get base path of new file name. Undocumented feature: If pszNewFile is
6913 // a directory, no error is returned and pszFilePart will be NULL.
6914 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006915 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006916 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006918 // Get (and create) a unique temporary file name in directory of new file
6919 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920 return -2;
6921
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006922 // blow the temp file away
6923 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924 return -3;
6925
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006926 // rename old file to the temp file
6927 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 return -4;
6929
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006930 // now create an empty file called pszOldFile; this prevents the operating
6931 // system using pszOldFile as an alias (SFN) if we're renaming within the
6932 // same directory. For example, we're editing a file called
6933 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6934 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6935 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6936 // cause all sorts of problems later in buf_write(). So, we create an
6937 // empty file called filena~1.txt and the system will have to find some
6938 // other SFN for filena~1.txt~, such as filena~2.txt
6939 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6941 return -5;
6942 if (!CloseHandle(hf))
6943 return -6;
6944
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006945 // rename the temp file to the new file
6946 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006948 // Renaming failed. Rename the file back to its old name, so that it
6949 // looks like nothing happened.
6950 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951 return -7;
6952 }
6953
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006954 // Seems to be left around on Novell filesystems
6955 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006956
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006957 // finally, remove the empty old file
6958 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959 return -8;
6960
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006961 return 0;
6962}
6963
6964
6965/*
6966 * Converts the filenames to UTF-16, then call mch_wrename().
6967 * Like rename(), returns 0 upon success, non-zero upon failure.
6968 */
6969 int
6970mch_rename(
6971 const char *pszOldFile,
6972 const char *pszNewFile)
6973{
6974 WCHAR *wold = NULL;
6975 WCHAR *wnew = NULL;
6976 int retval = -1;
6977
6978 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6979 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6980 if (wold != NULL && wnew != NULL)
6981 retval = mch_wrename(wold, wnew);
6982 vim_free(wold);
6983 vim_free(wnew);
6984 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985}
6986
6987/*
6988 * Get the default shell for the current hardware platform
6989 */
6990 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006991default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006992{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006993 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994}
6995
6996/*
6997 * mch_access() extends access() to do more detailed check on network drives.
6998 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6999 */
7000 int
7001mch_access(char *n, int p)
7002{
7003 HANDLE hFile;
Bram Moolenaar0f873732019-12-05 20:28:46 +01007004 int retval = -1; // default: fail
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007005 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007006
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007007 wn = enc_to_utf16((char_u *)n, NULL);
7008 if (wn == NULL)
7009 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007011 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00007014
7015 if (p & R_OK)
7016 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007017 // Read check is performed by seeing if we can do a find file on
7018 // the directory for any file.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007019 int i;
7020 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007021
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007022 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7023 TempNameW[i] = wn[i];
7024 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7025 TempNameW[i++] = '\\';
7026 TempNameW[i++] = '*';
7027 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007029 hFile = FindFirstFileW(TempNameW, &d);
7030 if (hFile == INVALID_HANDLE_VALUE)
7031 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007032 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034 }
7035
7036 if (p & W_OK)
7037 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007038 // Trying to create a temporary file in the directory should catch
7039 // directories on read-only network shares. However, in
7040 // directories whose ACL allows writes but denies deletes will end
7041 // up keeping the temporary file :-(.
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007042 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7043 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007044 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007045 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046 }
7047 }
7048 else
7049 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007050 // Don't consider a file read-only if another process has opened it.
7051 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7052
Bram Moolenaar0f873732019-12-05 20:28:46 +01007053 // Trying to open the file for the required access does ACL, read-only
7054 // network share, and file attribute checks.
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007055 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7056 | ((p & R_OK) ? GENERIC_READ : 0);
7057
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007058 hFile = CreateFileW(wn, access_mode, share_mode,
7059 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060 if (hFile == INVALID_HANDLE_VALUE)
7061 goto getout;
7062 CloseHandle(hFile);
7063 }
7064
Bram Moolenaar0f873732019-12-05 20:28:46 +01007065 retval = 0; // success
Bram Moolenaar071d4272004-06-13 20:20:40 +00007066getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007068 return retval;
7069}
7070
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007072 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073 */
7074 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007075mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076{
7077 WCHAR *wn;
7078 int f;
7079
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007080 wn = enc_to_utf16((char_u *)name, NULL);
7081 if (wn == NULL)
7082 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007084 f = _wopen(wn, flags, mode);
7085 vim_free(wn);
7086 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087}
7088
7089/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007090 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091 */
7092 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007093mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007094{
7095 WCHAR *wn, *wm;
7096 FILE *f = NULL;
7097
Bram Moolenaara12a1612019-01-24 16:39:02 +01007098#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0f873732019-12-05 20:28:46 +01007099 // Work around an annoying assertion in the Microsoft debug CRT
7100 // when mode's text/binary setting doesn't match _get_fmode().
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007101 char newMode = mode[strlen(mode) - 1];
7102 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007103
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007104 _get_fmode(&oldMode);
7105 if (newMode == 't')
7106 _set_fmode(_O_TEXT);
7107 else if (newMode == 'b')
7108 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007109#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007110 wn = enc_to_utf16((char_u *)name, NULL);
7111 wm = enc_to_utf16((char_u *)mode, NULL);
7112 if (wn != NULL && wm != NULL)
7113 f = _wfopen(wn, wm);
7114 vim_free(wn);
7115 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007116
Bram Moolenaara12a1612019-01-24 16:39:02 +01007117#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007118 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007119#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007120 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007121}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122
Bram Moolenaar071d4272004-06-13 20:20:40 +00007123/*
7124 * SUB STREAM (aka info stream) handling:
7125 *
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01007126 * NTFS can have sub streams for each file. The normal contents of a file is
7127 * stored in the main stream, and extra contents (author information, title and
7128 * so on) can be stored in a sub stream. After Windows 2000, the user can
7129 * access and store this information in sub streams via an explorer's property
7130 * menu item in the right click menu. This information in sub streams was lost
7131 * when copying only the main stream. Therefore we have to copy sub streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007132 *
7133 * Incomplete explanation:
7134 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7135 * More useful info and an example:
7136 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7137 */
7138
7139/*
7140 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7141 * and write to stream "substream" of file "to".
7142 * Errors are ignored.
7143 */
7144 static void
7145copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7146{
7147 HANDLE hTo;
7148 WCHAR *to_name;
7149
7150 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7151 wcscpy(to_name, to);
7152 wcscat(to_name, substream);
7153
7154 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7155 FILE_ATTRIBUTE_NORMAL, NULL);
7156 if (hTo != INVALID_HANDLE_VALUE)
7157 {
7158 long done;
7159 DWORD todo;
7160 DWORD readcnt, written;
7161 char buf[4096];
7162
Bram Moolenaar0f873732019-12-05 20:28:46 +01007163 // Copy block of bytes at a time. Abort when something goes wrong.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007164 for (done = 0; done < len; done += written)
7165 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007166 // (size_t) cast for Borland C 5.5
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007167 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7168 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007169 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7170 FALSE, FALSE, context)
7171 || readcnt != todo
7172 || !WriteFile(hTo, buf, todo, &written, NULL)
7173 || written != todo)
7174 break;
7175 }
7176 CloseHandle(hTo);
7177 }
7178
7179 free(to_name);
7180}
7181
7182/*
7183 * Copy info streams from file "from" to file "to".
7184 */
7185 static void
7186copy_infostreams(char_u *from, char_u *to)
7187{
7188 WCHAR *fromw;
7189 WCHAR *tow;
7190 HANDLE sh;
7191 WIN32_STREAM_ID sid;
7192 int headersize;
7193 WCHAR streamname[_MAX_PATH];
7194 DWORD readcount;
7195 void *context = NULL;
7196 DWORD lo, hi;
7197 int len;
7198
Bram Moolenaar0f873732019-12-05 20:28:46 +01007199 // Convert the file names to wide characters.
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007200 fromw = enc_to_utf16(from, NULL);
7201 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007202 if (fromw != NULL && tow != NULL)
7203 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007204 // Open the file for reading.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007205 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7206 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7207 if (sh != INVALID_HANDLE_VALUE)
7208 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007209 // Use BackupRead() to find the info streams. Repeat until we
7210 // have done them all.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007211 for (;;)
7212 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007213 // Get the header to find the length of the stream name. If
7214 // the "readcount" is zero we have done all info streams.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007215 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007216 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007217 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7218 &readcount, FALSE, FALSE, &context)
7219 || readcount == 0)
7220 break;
7221
Bram Moolenaar0f873732019-12-05 20:28:46 +01007222 // We only deal with streams that have a name. The normal
7223 // file data appears to be without a name, even though docs
7224 // suggest it is called "::$DATA".
Bram Moolenaar071d4272004-06-13 20:20:40 +00007225 if (sid.dwStreamNameSize > 0)
7226 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007227 // Read the stream name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007228 if (!BackupRead(sh, (LPBYTE)streamname,
7229 sid.dwStreamNameSize,
7230 &readcount, FALSE, FALSE, &context))
7231 break;
7232
Bram Moolenaar0f873732019-12-05 20:28:46 +01007233 // Copy an info stream with a name ":anything:$DATA".
7234 // Skip "::$DATA", it has no stream name (examples suggest
7235 // it might be used for the normal file contents).
7236 // Note that BackupRead() counts bytes, but the name is in
7237 // wide characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007238 len = readcount / sizeof(WCHAR);
7239 streamname[len] = 0;
7240 if (len > 7 && wcsicmp(streamname + len - 6,
7241 L":$DATA") == 0)
7242 {
7243 streamname[len - 6] = 0;
7244 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007245 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007246 }
7247 }
7248
Bram Moolenaar0f873732019-12-05 20:28:46 +01007249 // Advance to the next stream. We might try seeking too far,
7250 // but BackupSeek() doesn't skip over stream borders, thus
7251 // that's OK.
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007252 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253 &lo, &hi, &context);
7254 }
7255
Bram Moolenaar0f873732019-12-05 20:28:46 +01007256 // Clear the context.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007257 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7258
7259 CloseHandle(sh);
7260 }
7261 }
7262 vim_free(fromw);
7263 vim_free(tow);
7264}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007265
7266/*
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007267 * ntdll.dll definitions
7268 */
7269#define FileEaInformation 7
7270#ifndef STATUS_SUCCESS
7271# define STATUS_SUCCESS ((NTSTATUS) 0x00000000L)
7272#endif
7273
7274typedef struct _FILE_FULL_EA_INFORMATION_ {
7275 ULONG NextEntryOffset;
7276 UCHAR Flags;
7277 UCHAR EaNameLength;
7278 USHORT EaValueLength;
7279 CHAR EaName[1];
7280} FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7281
7282typedef struct _FILE_EA_INFORMATION_ {
7283 ULONG EaSize;
7284} FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7285
7286typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7287 PHANDLE FileHandle,
7288 ACCESS_MASK DesiredAccess,
7289 POBJECT_ATTRIBUTES ObjectAttributes,
7290 PIO_STATUS_BLOCK IoStatusBlock,
7291 ULONG ShareAccess,
7292 ULONG OpenOptions);
7293typedef NTSTATUS (NTAPI *PfnNtClose)(
7294 HANDLE Handle);
7295typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7296 HANDLE FileHandle,
7297 PIO_STATUS_BLOCK IoStatusBlock,
7298 PVOID Buffer,
7299 ULONG Length);
7300typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7301 HANDLE FileHandle,
7302 PIO_STATUS_BLOCK IoStatusBlock,
7303 PVOID Buffer,
7304 ULONG Length,
7305 BOOLEAN ReturnSingleEntry,
7306 PVOID EaList,
7307 ULONG EaListLength,
7308 PULONG EaIndex,
7309 BOOLEAN RestartScan);
7310typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7311 HANDLE FileHandle,
7312 PIO_STATUS_BLOCK IoStatusBlock,
7313 PVOID FileInformation,
7314 ULONG Length,
7315 FILE_INFORMATION_CLASS FileInformationClass);
7316typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7317 PUNICODE_STRING DestinationString,
7318 PCWSTR SourceString);
7319
7320PfnNtOpenFile pNtOpenFile = NULL;
7321PfnNtClose pNtClose = NULL;
7322PfnNtSetEaFile pNtSetEaFile = NULL;
7323PfnNtQueryEaFile pNtQueryEaFile = NULL;
7324PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7325PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7326
7327/*
7328 * Load ntdll.dll functions.
7329 */
7330 static BOOL
7331load_ntdll(void)
7332{
7333 static int loaded = -1;
7334
7335 if (loaded == -1)
7336 {
7337 HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7338 if (hNtdll != NULL)
7339 {
7340 pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7341 pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7342 pNtSetEaFile = (PfnNtSetEaFile)
7343 GetProcAddress(hNtdll, "NtSetEaFile");
7344 pNtQueryEaFile = (PfnNtQueryEaFile)
7345 GetProcAddress(hNtdll, "NtQueryEaFile");
7346 pNtQueryInformationFile = (PfnNtQueryInformationFile)
7347 GetProcAddress(hNtdll, "NtQueryInformationFile");
7348 pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7349 GetProcAddress(hNtdll, "RtlInitUnicodeString");
7350 }
7351 if (pNtOpenFile == NULL
7352 || pNtClose == NULL
7353 || pNtSetEaFile == NULL
7354 || pNtQueryEaFile == NULL
7355 || pNtQueryInformationFile == NULL
7356 || pRtlInitUnicodeString == NULL)
7357 loaded = FALSE;
7358 else
7359 loaded = TRUE;
7360 }
7361 return (BOOL) loaded;
7362}
7363
7364/*
7365 * Copy extended attributes (EA) from file "from" to file "to".
7366 */
7367 static void
7368copy_extattr(char_u *from, char_u *to)
7369{
7370 char_u *fromf = NULL;
7371 char_u *tof = NULL;
7372 WCHAR *fromw = NULL;
7373 WCHAR *tow = NULL;
7374 UNICODE_STRING u;
7375 HANDLE h;
7376 OBJECT_ATTRIBUTES oa;
7377 IO_STATUS_BLOCK iosb;
7378 FILE_EA_INFORMATION_ eainfo = {0};
7379 void *ea = NULL;
7380
7381 if (!load_ntdll())
7382 return;
7383
7384 // Convert the file names to the fully qualified object names.
7385 fromf = alloc(STRLEN(from) + 5);
7386 tof = alloc(STRLEN(to) + 5);
7387 if (fromf == NULL || tof == NULL)
7388 goto theend;
7389 STRCPY(fromf, "\\??\\");
7390 STRCAT(fromf, from);
7391 STRCPY(tof, "\\??\\");
7392 STRCAT(tof, to);
7393
7394 // Convert the names to wide characters.
7395 fromw = enc_to_utf16(fromf, NULL);
7396 tow = enc_to_utf16(tof, NULL);
7397 if (fromw == NULL || tow == NULL)
7398 goto theend;
7399
7400 // Get the EA.
7401 pRtlInitUnicodeString(&u, fromw);
7402 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7403 if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7404 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7405 goto theend;
7406 pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7407 FileEaInformation);
7408 if (eainfo.EaSize != 0)
7409 {
7410 ea = alloc(eainfo.EaSize);
7411 if (ea != NULL)
7412 {
7413 if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7414 NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7415 {
7416 vim_free(ea);
7417 ea = NULL;
7418 }
7419 }
7420 }
7421 pNtClose(h);
7422
7423 // Set the EA.
7424 if (ea != NULL)
7425 {
7426 pRtlInitUnicodeString(&u, tow);
7427 InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7428 if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7429 FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7430 goto theend;
7431
7432 pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7433 pNtClose(h);
7434 }
7435
7436theend:
7437 vim_free(fromf);
7438 vim_free(tof);
7439 vim_free(fromw);
7440 vim_free(tow);
7441 vim_free(ea);
7442}
7443
7444/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007445 * Copy file attributes from file "from" to file "to".
7446 * For Windows NT and later we copy info streams.
7447 * Always returns zero, errors are ignored.
7448 */
7449 int
7450mch_copy_file_attribute(char_u *from, char_u *to)
7451{
Bram Moolenaar0f873732019-12-05 20:28:46 +01007452 // File streams only work on Windows NT and later.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007453 copy_infostreams(from, to);
Bram Moolenaare7bebc42021-02-01 20:50:37 +01007454 copy_extattr(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007455 return 0;
7456}
7457
7458#if defined(MYRESETSTKOFLW) || defined(PROTO)
7459/*
7460 * Recreate a destroyed stack guard page in win32.
7461 * Written by Benjamin Peterson.
7462 */
7463
Bram Moolenaar0f873732019-12-05 20:28:46 +01007464// These magic numbers are from the MS header files
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007465# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00007466
7467/*
7468 * This function does the same thing as _resetstkoflw(), which is only
7469 * available in DevStudio .net and later.
7470 * Returns 0 for failure, 1 for success.
7471 */
7472 int
7473myresetstkoflw(void)
7474{
7475 BYTE *pStackPtr;
7476 BYTE *pGuardPage;
7477 BYTE *pStackBase;
7478 BYTE *pLowestPossiblePage;
7479 MEMORY_BASIC_INFORMATION mbi;
7480 SYSTEM_INFO si;
7481 DWORD nPageSize;
7482 DWORD dummy;
7483
Bram Moolenaar0f873732019-12-05 20:28:46 +01007484 // We need to know the system page size.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007485 GetSystemInfo(&si);
7486 nPageSize = si.dwPageSize;
7487
Bram Moolenaar0f873732019-12-05 20:28:46 +01007488 // ...and the current stack pointer
Bram Moolenaar071d4272004-06-13 20:20:40 +00007489 pStackPtr = (BYTE*)_alloca(1);
7490
Bram Moolenaar0f873732019-12-05 20:28:46 +01007491 // ...and the base of the stack.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007492 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7493 return 0;
7494 pStackBase = (BYTE*)mbi.AllocationBase;
7495
Bram Moolenaar4b96df52020-01-26 22:00:26 +01007496 // ...and the page that's min_stack_req pages away from stack base; this is
Bram Moolenaar0f873732019-12-05 20:28:46 +01007497 // the lowest page we could use.
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007498 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007499
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007501 // We want the first committed page in the stack Start at the stack
7502 // base and move forward through memory until we find a committed block.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007503 BYTE *pBlock = pStackBase;
7504
Bram Moolenaara466c992005-07-09 21:03:22 +00007505 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 {
7507 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7508 return 0;
7509
7510 pBlock += mbi.RegionSize;
7511
7512 if (mbi.State & MEM_COMMIT)
7513 break;
7514 }
7515
Bram Moolenaar0f873732019-12-05 20:28:46 +01007516 // mbi now describes the first committed block in the stack.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007517 if (mbi.Protect & PAGE_GUARD)
7518 return 1;
7519
Bram Moolenaar0f873732019-12-05 20:28:46 +01007520 // decide where the guard page should start
Bram Moolenaar071d4272004-06-13 20:20:40 +00007521 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7522 pGuardPage = pLowestPossiblePage;
7523 else
7524 pGuardPage = (BYTE*)mbi.BaseAddress;
7525
Bram Moolenaar0f873732019-12-05 20:28:46 +01007526 // allocate the guard page
Bram Moolenaar071d4272004-06-13 20:20:40 +00007527 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7528 return 0;
7529
Bram Moolenaar0f873732019-12-05 20:28:46 +01007530 // apply the guard attribute to the page
Bram Moolenaar071d4272004-06-13 20:20:40 +00007531 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7532 &dummy))
7533 return 0;
7534 }
7535
7536 return 1;
7537}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007538#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007539
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007540
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007541/*
7542 * The command line arguments in UCS2
7543 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007544static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007545static LPWSTR *ArglistW = NULL;
7546static int global_argc = 0;
7547static char **global_argv;
7548
Bram Moolenaar0f873732019-12-05 20:28:46 +01007549static int used_file_argc = 0; // last argument in global_argv[] used
7550 // for the argument list.
7551static int *used_file_indexes = NULL; // indexes in global_argv[] for
7552 // command line arguments added to
7553 // the argument list
7554static int used_file_count = 0; // nr of entries in used_file_indexes
7555static int used_file_literal = FALSE; // take file names literally
7556static int used_file_full_path = FALSE; // file name was full path
7557static int used_file_diff_mode = FALSE; // file name was with diff mode
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007558static int used_alist_count = 0;
7559
7560
7561/*
7562 * Get the command line arguments. Unicode version.
7563 * Returns argc. Zero when something fails.
7564 */
7565 int
7566get_cmd_argsW(char ***argvp)
7567{
7568 char **argv = NULL;
7569 int argc = 0;
7570 int i;
7571
Bram Moolenaar14993322014-09-09 12:25:33 +02007572 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007573 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7574 if (ArglistW != NULL)
7575 {
7576 argv = malloc((nArgsW + 1) * sizeof(char *));
7577 if (argv != NULL)
7578 {
7579 argc = nArgsW;
7580 argv[argc] = NULL;
7581 for (i = 0; i < argc; ++i)
7582 {
7583 int len;
7584
Bram Moolenaar0f873732019-12-05 20:28:46 +01007585 // Convert each Unicode argument to the current codepage.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007586 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007587 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007588 (LPSTR *)&argv[i], &len, 0, 0);
7589 if (argv[i] == NULL)
7590 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007591 // Out of memory, clear everything.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007592 while (i > 0)
7593 free(argv[--i]);
7594 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007595 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007596 argc = 0;
7597 }
7598 }
7599 }
7600 }
7601
7602 global_argc = argc;
7603 global_argv = argv;
7604 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007605 {
7606 if (used_file_indexes != NULL)
7607 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007608 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007609 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007610
7611 if (argvp != NULL)
7612 *argvp = argv;
7613 return argc;
7614}
7615
7616 void
7617free_cmd_argsW(void)
7618{
7619 if (ArglistW != NULL)
7620 {
7621 GlobalFree(ArglistW);
7622 ArglistW = NULL;
7623 }
7624}
7625
7626/*
7627 * Remember "name" is an argument that was added to the argument list.
7628 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7629 * is called.
7630 */
7631 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007632used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007633{
7634 int i;
7635
7636 if (used_file_indexes == NULL)
7637 return;
7638 for (i = used_file_argc + 1; i < global_argc; ++i)
7639 if (STRCMP(global_argv[i], name) == 0)
7640 {
7641 used_file_argc = i;
7642 used_file_indexes[used_file_count++] = i;
7643 break;
7644 }
7645 used_file_literal = literal;
7646 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007647 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007648}
7649
7650/*
7651 * Remember the length of the argument list as it was. If it changes then we
7652 * leave it alone when 'encoding' is set.
7653 */
7654 void
7655set_alist_count(void)
7656{
7657 used_alist_count = GARGCOUNT;
7658}
7659
7660/*
7661 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7662 * has been changed while starting up. Use the UCS-2 command line arguments
7663 * and convert them to 'encoding'.
7664 */
7665 void
7666fix_arg_enc(void)
7667{
7668 int i;
7669 int idx;
7670 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007671 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007672
Bram Moolenaar0f873732019-12-05 20:28:46 +01007673 // Safety checks:
7674 // - if argument count differs between the wide and non-wide argument
7675 // list, something must be wrong.
7676 // - the file name arguments must have been located.
7677 // - the length of the argument list wasn't changed by the user.
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007678 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007679 || ArglistW == NULL
7680 || used_file_indexes == NULL
7681 || used_file_count == 0
7682 || used_alist_count != GARGCOUNT)
7683 return;
7684
Bram Moolenaar0f873732019-12-05 20:28:46 +01007685 // Remember the buffer numbers for the arguments.
Bram Moolenaarc799fe22019-05-28 23:08:19 +02007686 fnum_list = ALLOC_MULT(int, GARGCOUNT);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007687 if (fnum_list == NULL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007688 return; // out of memory
Bram Moolenaar86b68352004-12-27 21:59:20 +00007689 for (i = 0; i < GARGCOUNT; ++i)
7690 fnum_list[i] = GARGLIST[i].ae_fnum;
7691
Bram Moolenaar0f873732019-12-05 20:28:46 +01007692 // Clear the argument list. Make room for the new arguments.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007693 alist_clear(&global_alist);
7694 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar0f873732019-12-05 20:28:46 +01007695 return; // out of memory
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007696
7697 for (i = 0; i < used_file_count; ++i)
7698 {
7699 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007700 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007701 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007702 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007703 int literal = used_file_literal;
7704
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007705#ifdef FEAT_DIFF
Bram Moolenaar0f873732019-12-05 20:28:46 +01007706 // When using diff mode may need to concatenate file name to
7707 // directory name. Just like it's done in main().
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007708 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7709 && !mch_isdir(alist_name(&GARGLIST[0])))
7710 {
7711 char_u *r;
7712
7713 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7714 if (r != NULL)
7715 {
7716 vim_free(str);
7717 str = r;
7718 }
7719 }
Bram Moolenaar912bc4a2019-12-01 18:58:11 +01007720#endif
Bram Moolenaar0f873732019-12-05 20:28:46 +01007721 // Re-use the old buffer by renaming it. When not using literal
7722 // names it's done by alist_expand() below.
Bram Moolenaar86b68352004-12-27 21:59:20 +00007723 if (used_file_literal)
7724 buf_set_name(fnum_list[i], str);
7725
Bram Moolenaar0f873732019-12-05 20:28:46 +01007726 // Check backtick literal. backtick literal is already expanded in
7727 // main.c, so this part add str as literal.
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007728 if (literal == FALSE)
7729 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007730 size_t len = STRLEN(str);
7731
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007732 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7733 literal = TRUE;
7734 }
7735 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007736 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007737 }
7738
7739 if (!used_file_literal)
7740 {
Bram Moolenaar0f873732019-12-05 20:28:46 +01007741 // Now expand wildcards in the arguments.
7742 // Temporarily add '(' and ')' to 'isfname'. These are valid
7743 // filename characters but are excluded from 'isfname' to make
7744 // "gf" work on a file name in parenthesis (e.g.: see vim.h).
7745 // Also, unset wildignore to not be influenced by this option.
7746 // The arguments specified in command-line should be kept even if
7747 // encoding options were changed.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007748 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007749 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007750 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007751 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007752 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007753 }
7754
Bram Moolenaar0f873732019-12-05 20:28:46 +01007755 // If wildcard expansion failed, we are editing the first file of the
7756 // arglist and there is no file name: Edit the first argument now.
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007757 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7758 {
7759 do_cmdline_cmd((char_u *)":rewind");
7760 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007761 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007762 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007763
7764 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007765}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007766
7767 int
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02007768mch_setenv(char *var, char *value, int x UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007769{
7770 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007771 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007772
Bram Moolenaar964b3742019-05-24 18:54:09 +02007773 envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007774 if (envbuf == NULL)
7775 return -1;
7776
7777 sprintf((char *)envbuf, "%s=%s", var, value);
7778
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007779 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007780
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007781 vim_free(envbuf);
7782 if (p == NULL)
7783 return -1;
7784 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007785#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007786 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007787#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007788 // Unlike Un*x systems, we can free the string for _wputenv().
7789 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007790
7791 return 0;
7792}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007793
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007794/*
7795 * Support for 256 colors and 24-bit colors was added in Windows 10
7796 * version 1703 (Creators update).
7797 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007798#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7799
7800/*
7801 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaar57da6982019-09-13 22:30:11 +02007802 * version 1809 (October 2018 update).
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007803 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007804#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007805
7806/*
7807 * ConPTY differences between versions, need different logic.
7808 * version 1903 (May 2019 update).
7809 */
7810#define CONPTY_1903_BUILD MAKE_VER(10, 0, 18362)
7811
7812/*
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007813 * version 1909 (November 2019 update).
7814 */
7815#define CONPTY_1909_BUILD MAKE_VER(10, 0, 18363)
7816
7817/*
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007818 * Stay ahead of the next update, and when it's done, fix this.
7819 * version ? (2020 update, temporarily use the build number of insider preview)
7820 */
7821#define CONPTY_NEXT_UPDATE_BUILD MAKE_VER(10, 0, 19587)
7822
7823/*
Bram Moolenaar57da6982019-09-13 22:30:11 +02007824 * Confirm until this version. Also the logic changes.
7825 * insider preview.
7826 */
Bram Moolenaar4c063dd2019-10-04 21:29:12 +02007827#define CONPTY_INSIDER_BUILD MAKE_VER(10, 0, 18995)
Bram Moolenaar57da6982019-09-13 22:30:11 +02007828
7829/*
7830 * Not stable now.
7831 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007832#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007833
7834 static void
7835vtp_flag_init(void)
7836{
7837 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007838#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007839 DWORD mode;
7840 HANDLE out;
7841
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007842# ifdef VIMDLL
7843 if (!gui.in_use)
7844# endif
7845 {
7846 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007847
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007848 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7849 GetConsoleMode(out, &mode);
7850 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7851 if (SetConsoleMode(out, mode) == 0)
7852 vtp_working = 0;
7853 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007854#endif
7855
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007856 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007857 conpty_working = 1;
7858 if (ver >= CONPTY_STABLE_BUILD)
7859 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007860
Bram Moolenaar57da6982019-09-13 22:30:11 +02007861 if (ver <= CONPTY_INSIDER_BUILD)
7862 conpty_type = 3;
Bram Moolenaar36e7a822019-11-13 21:49:24 +01007863 if (ver <= CONPTY_1909_BUILD)
7864 conpty_type = 2;
Bram Moolenaar57da6982019-09-13 22:30:11 +02007865 if (ver <= CONPTY_1903_BUILD)
7866 conpty_type = 2;
7867 if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7868 conpty_type = 1;
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02007869
7870 if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7871 conpty_fix_type = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007872}
7873
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007874#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007875
7876 static void
7877vtp_init(void)
7878{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007879 HMODULE hKerneldll;
7880 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007881# ifdef FEAT_TERMGUICOLORS
7882 COLORREF fg, bg;
7883# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007884
Bram Moolenaar0f873732019-12-05 20:28:46 +01007885 // Use functions supported from Vista
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007886 hKerneldll = GetModuleHandle("kernel32.dll");
7887 if (hKerneldll != NULL)
7888 {
7889 pGetConsoleScreenBufferInfoEx =
7890 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7891 hKerneldll, "GetConsoleScreenBufferInfoEx");
7892 pSetConsoleScreenBufferInfoEx =
7893 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7894 hKerneldll, "SetConsoleScreenBufferInfoEx");
7895 if (pGetConsoleScreenBufferInfoEx != NULL
7896 && pSetConsoleScreenBufferInfoEx != NULL)
7897 has_csbiex = TRUE;
7898 }
7899
7900 csbi.cbSize = sizeof(csbi);
7901 if (has_csbiex)
7902 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007903 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7904 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
Bram Moolenaardf543822020-01-30 11:53:59 +01007905 store_console_bg_rgb = save_console_bg_rgb;
7906 store_console_fg_rgb = save_console_fg_rgb;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007907
7908# ifdef FEAT_TERMGUICOLORS
7909 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7910 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7911 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7912 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7913 default_console_color_bg = bg;
7914 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007915# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007916
7917 set_console_color_rgb();
7918}
7919
7920 static void
7921vtp_exit(void)
7922{
Bram Moolenaardf543822020-01-30 11:53:59 +01007923 restore_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007924}
7925
Bram Moolenaar06b7b582020-05-30 17:49:25 +02007926 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007927vtp_printf(
7928 char *format,
7929 ...)
7930{
7931 char_u buf[100];
7932 va_list list;
7933 DWORD result;
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007934 int len;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007935
7936 va_start(list, format);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007937 len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007938 va_end(list);
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007939 WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007940 return (int)result;
7941}
7942
7943 static void
7944vtp_sgr_bulk(
7945 int arg)
7946{
7947 int args[1];
7948
7949 args[0] = arg;
7950 vtp_sgr_bulks(1, args);
7951}
7952
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007953#define FAST256(x) \
7954 if ((*p-- = "0123456789"[(n = x % 10)]) \
7955 && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7956 && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7957
7958#define FAST256CASE(x) \
7959 case x: \
7960 FAST256(newargs[x - 1]);
7961
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007962 static void
7963vtp_sgr_bulks(
7964 int argc,
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007965 int *args)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007966{
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007967#define MAXSGR 16
7968#define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
7969 char_u buf[SGRBUFSIZE];
7970 char_u *p;
7971 int in, out;
7972 int newargs[16];
7973 static int sgrfgr = -1, sgrfgg, sgrfgb;
7974 static int sgrbgr = -1, sgrbgg, sgrbgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007975
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007976 if (argc == 0)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007977 {
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007978 sgrfgr = sgrbgr = -1;
7979 vtp_printf("033[m");
7980 return;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007981 }
Bram Moolenaar4e5534f2020-04-30 20:59:57 +02007982
7983 in = out = 0;
7984 while (in < argc)
7985 {
7986 int s = args[in];
7987 int copylen = 1;
7988
7989 if (s == 38)
7990 {
7991 if (argc - in >= 5 && args[in + 1] == 2)
7992 {
7993 if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
7994 && sgrfgb == args[in + 4])
7995 {
7996 in += 5;
7997 copylen = 0;
7998 }
7999 else
8000 {
8001 sgrfgr = args[in + 2];
8002 sgrfgg = args[in + 3];
8003 sgrfgb = args[in + 4];
8004 copylen = 5;
8005 }
8006 }
8007 else if (argc - in >= 3 && args[in + 1] == 5)
8008 {
8009 sgrfgr = -1;
8010 copylen = 3;
8011 }
8012 }
8013 else if (s == 48)
8014 {
8015 if (argc - in >= 5 && args[in + 1] == 2)
8016 {
8017 if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8018 && sgrbgb == args[in + 4])
8019 {
8020 in += 5;
8021 copylen = 0;
8022 }
8023 else
8024 {
8025 sgrbgr = args[in + 2];
8026 sgrbgg = args[in + 3];
8027 sgrbgb = args[in + 4];
8028 copylen = 5;
8029 }
8030 }
8031 else if (argc - in >= 3 && args[in + 1] == 5)
8032 {
8033 sgrbgr = -1;
8034 copylen = 3;
8035 }
8036 }
8037 else if (30 <= s && s <= 39)
8038 sgrfgr = -1;
8039 else if (90 <= s && s <= 97)
8040 sgrfgr = -1;
8041 else if (40 <= s && s <= 49)
8042 sgrbgr = -1;
8043 else if (100 <= s && s <= 107)
8044 sgrbgr = -1;
8045 else if (s == 0)
8046 sgrfgr = sgrbgr = -1;
8047
8048 while (copylen--)
8049 newargs[out++] = args[in++];
8050 }
8051
8052 p = &buf[sizeof(buf) - 1];
8053 *p-- = 'm';
8054
8055 switch (out)
8056 {
8057 int n, m;
8058 DWORD r;
8059
8060 FAST256CASE(16);
8061 *p-- = ';';
8062 FAST256CASE(15);
8063 *p-- = ';';
8064 FAST256CASE(14);
8065 *p-- = ';';
8066 FAST256CASE(13);
8067 *p-- = ';';
8068 FAST256CASE(12);
8069 *p-- = ';';
8070 FAST256CASE(11);
8071 *p-- = ';';
8072 FAST256CASE(10);
8073 *p-- = ';';
8074 FAST256CASE(9);
8075 *p-- = ';';
8076 FAST256CASE(8);
8077 *p-- = ';';
8078 FAST256CASE(7);
8079 *p-- = ';';
8080 FAST256CASE(6);
8081 *p-- = ';';
8082 FAST256CASE(5);
8083 *p-- = ';';
8084 FAST256CASE(4);
8085 *p-- = ';';
8086 FAST256CASE(3);
8087 *p-- = ';';
8088 FAST256CASE(2);
8089 *p-- = ';';
8090 FAST256CASE(1);
8091 *p-- = '[';
8092 *p = '\033';
8093 WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8094 default:
8095 break;
8096 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008097}
8098
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008099 static void
8100wt_init(void)
8101{
8102 wt_working = (mch_getenv("WT_SESSION") != NULL);
8103}
8104
8105 int
8106use_wt(void)
8107{
8108 return USE_WT;
8109}
8110
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008111# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008112 static int
8113ctermtoxterm(
8114 int cterm)
8115{
Bram Moolenaar9894e392018-05-05 14:29:06 +02008116 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008117
8118 cterm_color2rgb(cterm, &r, &g, &b, &idx);
8119 return (((int)r << 16) | ((int)g << 8) | (int)b);
8120}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02008121# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008122
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008123 static void
8124set_console_color_rgb(void)
8125{
8126# ifdef FEAT_TERMGUICOLORS
8127 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaara050b942019-12-02 21:35:31 +01008128 guicolor_T fg, bg;
8129 int ctermfg, ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008130
8131 if (!USE_VTP)
8132 return;
8133
Bram Moolenaara050b942019-12-02 21:35:31 +01008134 get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8135
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008136 if (USE_WT)
8137 {
8138 term_fg_rgb_color(fg);
8139 term_bg_rgb_color(bg);
8140 return;
8141 }
8142
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008143 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8144 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8145
8146 csbi.cbSize = sizeof(csbi);
8147 if (has_csbiex)
8148 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8149
8150 csbi.cbSize = sizeof(csbi);
8151 csbi.srWindow.Right += 1;
8152 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008153 store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8154 store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008155 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8156 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008157 if (has_csbiex)
8158 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8159# endif
8160}
8161
Bram Moolenaara050b942019-12-02 21:35:31 +01008162# if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8163 void
8164get_default_console_color(
8165 int *cterm_fg,
8166 int *cterm_bg,
8167 guicolor_T *gui_fg,
8168 guicolor_T *gui_bg)
8169{
8170 int id;
8171 guicolor_T guifg = INVALCOLOR;
8172 guicolor_T guibg = INVALCOLOR;
8173 int ctermfg = 0;
8174 int ctermbg = 0;
8175
8176 id = syn_name2id((char_u *)"Normal");
8177 if (id > 0 && p_tgc)
8178 syn_id2colors(id, &guifg, &guibg);
8179 if (guifg == INVALCOLOR)
8180 {
8181 ctermfg = -1;
8182 if (id > 0)
8183 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8184 guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8185 : default_console_color_fg;
8186 cterm_normal_fg_gui_color = guifg;
8187 ctermfg = ctermfg < 0 ? 0 : ctermfg;
8188 }
8189 if (guibg == INVALCOLOR)
8190 {
8191 ctermbg = -1;
8192 if (id > 0)
8193 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8194 guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8195 : default_console_color_bg;
8196 cterm_normal_bg_gui_color = guibg;
8197 ctermbg = ctermbg < 0 ? 0 : ctermbg;
8198 }
8199
8200 *cterm_fg = ctermfg;
8201 *cterm_bg = ctermbg;
8202 *gui_fg = guifg;
8203 *gui_bg = guibg;
8204}
8205# endif
8206
Bram Moolenaardf543822020-01-30 11:53:59 +01008207/*
8208 * Set the console colors to the original colors or the last set colors.
8209 */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008210 static void
8211reset_console_color_rgb(void)
8212{
8213# ifdef FEAT_TERMGUICOLORS
8214 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8215
Bram Moolenaar06b7b582020-05-30 17:49:25 +02008216 if (USE_WT)
8217 return;
8218
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008219 csbi.cbSize = sizeof(csbi);
8220 if (has_csbiex)
8221 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8222
8223 csbi.cbSize = sizeof(csbi);
8224 csbi.srWindow.Right += 1;
8225 csbi.srWindow.Bottom += 1;
Bram Moolenaardf543822020-01-30 11:53:59 +01008226 csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8227 csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8228 if (has_csbiex)
8229 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8230# endif
8231}
8232
8233/*
8234 * Set the console colors to the original colors.
8235 */
8236 static void
8237restore_console_color_rgb(void)
8238{
8239# ifdef FEAT_TERMGUICOLORS
8240 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8241
8242 csbi.cbSize = sizeof(csbi);
8243 if (has_csbiex)
8244 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8245
8246 csbi.cbSize = sizeof(csbi);
8247 csbi.srWindow.Right += 1;
8248 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02008249 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8250 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008251 if (has_csbiex)
8252 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8253# endif
8254}
8255
8256 void
8257control_console_color_rgb(void)
8258{
8259 if (USE_VTP)
8260 set_console_color_rgb();
8261 else
8262 reset_console_color_rgb();
8263}
8264
8265 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01008266use_vtp(void)
8267{
8268 return USE_VTP;
8269}
8270
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02008271 int
8272is_term_win32(void)
8273{
8274 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8275}
8276
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01008277 int
8278has_vtp_working(void)
8279{
8280 return vtp_working;
8281}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008282
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01008283#endif
8284
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008285 int
8286has_conpty_working(void)
8287{
8288 return conpty_working;
8289}
8290
8291 int
Bram Moolenaar57da6982019-09-13 22:30:11 +02008292get_conpty_type(void)
8293{
8294 return conpty_type;
8295}
8296
8297 int
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01008298is_conpty_stable(void)
8299{
8300 return conpty_stable;
8301}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008302
Bram Moolenaar7ed8f592020-04-28 20:44:42 +02008303 int
8304get_conpty_fix_type(void)
8305{
8306 return conpty_fix_type;
8307}
8308
Bram Moolenaarafde13b2019-04-28 19:46:49 +02008309#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01008310 void
8311resize_console_buf(void)
8312{
8313 CONSOLE_SCREEN_BUFFER_INFO csbi;
8314 COORD coord;
8315 SMALL_RECT newsize;
8316
8317 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8318 {
8319 coord.X = SRWIDTH(csbi.srWindow);
8320 coord.Y = SRHEIGHT(csbi.srWindow);
8321 SetConsoleScreenBufferSize(g_hConOut, coord);
8322
8323 newsize.Left = 0;
8324 newsize.Top = 0;
8325 newsize.Right = coord.X - 1;
8326 newsize.Bottom = coord.Y - 1;
8327 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8328
8329 SetConsoleScreenBufferSize(g_hConOut, coord);
8330 }
8331}
8332#endif