blob: 33d48cf7fa7a95e50714b595a7b44709a6f542a4 [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
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
Bram Moolenaar4f974752019-02-17 17:44:42 +010048# if defined(FEAT_TITLE) && !defined(FEAT_GUI_MSWIN)
Bram Moolenaar82881492012-11-20 16:53:39 +010049# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200149#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150/* Win32 Console handles for input and output */
151static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
152static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
153
154/* Win32 Screen buffer,coordinate,console I/O information */
155static SMALL_RECT g_srScrollRegion;
156static COORD g_coord; /* 0-based, but external coords are 1-based */
157
158/* The attribute of the screen when the editor was started */
159static WORD g_attrDefault = 7; /* lightgray text on black background */
160static WORD g_attrCurrent;
161
162static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
163static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
164static int g_fForceExit = FALSE; /* set when forcefully exiting */
165
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166static void scroll(unsigned cLines);
167static void set_scroll_region(unsigned left, unsigned top,
168 unsigned right, unsigned bottom);
Bram Moolenaar6982f422019-02-16 16:48:01 +0100169static void set_scroll_region_tb(unsigned top, unsigned bottom);
170static void set_scroll_region_lr(unsigned left, unsigned right);
171static void insert_lines(unsigned cLines);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000172static void delete_lines(unsigned cLines);
173static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175static int s_cursor_visible = TRUE;
176static int did_create_conin = FALSE;
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200177#endif
178#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179static int s_dont_use_vimrun = TRUE;
180static int need_vimrun_warning = FALSE;
181static char *vimrun_path = "vimrun ";
182#endif
183
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200184static int win32_getattrs(char_u *name);
185static int win32_setattrs(char_u *name, int attrs);
186static int win32_set_archive(char_u *name);
187
Bram Moolenaard9ef1b82019-02-13 19:23:10 +0100188static int conpty_working = 0;
189static int conpty_stable = 0;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100190static void vtp_flag_init();
191
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200192#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar6902c0e2019-02-16 14:07:37 +0100193static int vtp_working = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100194static void vtp_init();
195static void vtp_exit();
196static int vtp_printf(char *format, ...);
197static void vtp_sgr_bulk(int arg);
198static void vtp_sgr_bulks(int argc, int *argv);
199
200static guicolor_T save_console_bg_rgb;
201static guicolor_T save_console_fg_rgb;
202
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200203static int g_color_index_bg = 0;
204static int g_color_index_fg = 7;
205
206# ifdef FEAT_TERMGUICOLORS
207static int default_console_color_bg = 0x000000; // black
208static int default_console_color_fg = 0xc0c0c0; // white
209# endif
210
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100211# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200212# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100213# else
214# define USE_VTP 0
215# endif
216
217static void set_console_color_rgb(void);
218static void reset_console_color_rgb(void);
219#endif
220
221/* This flag is newly created from Windows 10 */
222#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
223# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
224#endif
225
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200226#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000227static int suppress_winsize = 1; /* don't fiddle with console */
228#endif
229
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200230static char_u *exe_path = NULL;
231
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100232static BOOL win8_or_later = FALSE;
233
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200234#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100235/* Dynamic loading for portability */
236typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
237{
238 ULONG cbSize;
239 COORD dwSize;
240 COORD dwCursorPosition;
241 WORD wAttributes;
242 SMALL_RECT srWindow;
243 COORD dwMaximumWindowSize;
244 WORD wPopupAttributes;
245 BOOL bFullscreenSupported;
246 COLORREF ColorTable[16];
247} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
248typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
249static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
250typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
251static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
252static BOOL has_csbiex = FALSE;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +0100253#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100254
255/*
256 * Get version number including build number
257 */
258typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
259# define MAKE_VER(major, minor, build) \
260 (((major) << 24) | ((minor) << 16) | (build))
261
262 static DWORD
263get_build_number(void)
264{
265 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
266 HMODULE hNtdll;
267 PfnRtlGetVersion pRtlGetVersion;
268 DWORD ver = MAKE_VER(0, 0, 0);
269
270 hNtdll = GetModuleHandle("ntdll.dll");
271 if (hNtdll != NULL)
272 {
273 pRtlGetVersion =
274 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
275 pRtlGetVersion(&osver);
276 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
277 min(osver.dwMinorVersion, 255),
278 min(osver.dwBuildNumber, 32767));
279 }
280 return ver;
281}
282
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200283#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100284/*
285 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100286 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100287 */
288 static BOOL
289read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 HANDLE hInput,
291 INPUT_RECORD *lpBuffer,
292 DWORD nLength,
293 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100294{
295 enum
296 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100297 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100299 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100300 static DWORD s_dwIndex = 0;
301 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100302 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100303 int head;
304 int tail;
305 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100306
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200307 if (nLength == -2)
308 return (s_dwMax > 0) ? TRUE : FALSE;
309
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100310 if (!win8_or_later)
311 {
312 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200313 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
314 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100315 }
316
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100317 if (s_dwMax == 0)
318 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200320 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
321 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100322 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100323 s_dwIndex = 0;
324 s_dwMax = dwEvents;
325 if (dwEvents == 0)
326 {
327 *lpEvents = 0;
328 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100329 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100330
331 if (s_dwMax > 1)
332 {
333 head = 0;
334 tail = s_dwMax - 1;
335 while (head != tail)
336 {
337 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
338 && s_irCache[head + 1].EventType
339 == WINDOW_BUFFER_SIZE_EVENT)
340 {
341 /* Remove duplicate event to avoid flicker. */
342 for (i = head; i < tail; ++i)
343 s_irCache[i] = s_irCache[i + 1];
344 --tail;
345 continue;
346 }
347 head++;
348 }
349 s_dwMax = tail + 1;
350 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100351 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100352
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100353 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200354 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100355 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100356 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100357 return TRUE;
358}
359
360/*
361 * Version of PeekConsoleInput() that works with IME.
362 */
363 static BOOL
364peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100365 HANDLE hInput,
366 INPUT_RECORD *lpBuffer,
367 DWORD nLength,
368 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100369{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100370 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100371}
372
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100373# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200374 static DWORD
375msg_wait_for_multiple_objects(
376 DWORD nCount,
377 LPHANDLE pHandles,
378 BOOL fWaitAll,
379 DWORD dwMilliseconds,
380 DWORD dwWakeMask)
381{
382 if (read_console_input(NULL, NULL, -2, NULL))
383 return WAIT_OBJECT_0;
384 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
385 dwMilliseconds, dwWakeMask);
386}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100387# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200388
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100389# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200390 static DWORD
391wait_for_single_object(
392 HANDLE hHandle,
393 DWORD dwMilliseconds)
394{
395 if (read_console_input(NULL, NULL, -2, NULL))
396 return WAIT_OBJECT_0;
397 return WaitForSingleObject(hHandle, dwMilliseconds);
398}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100399# endif
400#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200401
Bram Moolenaar071d4272004-06-13 20:20:40 +0000402 static void
403get_exe_name(void)
404{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100405 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
406 * as the maximum length that works (plus a NUL byte). */
407#define MAX_ENV_PATH_LEN 8192
408 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200409 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000410
411 if (exe_name == NULL)
412 {
413 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100414 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000415 if (*temp != NUL)
416 exe_name = FullName_save((char_u *)temp, FALSE);
417 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000418
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200419 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000420 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200421 exe_path = vim_strnsave(exe_name,
422 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200423 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000424 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200425 /* Append our starting directory to $PATH, so that when doing
426 * "!xxd" it's found in our starting directory. Needed because
427 * SearchPath() also looks there. */
428 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100429 if (p == NULL
430 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200431 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100432 if (p == NULL || *p == NUL)
433 temp[0] = NUL;
434 else
435 {
436 STRCPY(temp, p);
437 STRCAT(temp, ";");
438 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200439 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100440 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200441 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000442 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000443 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444}
445
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200446/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100447 * Unescape characters in "p" that appear in "escaped".
448 */
449 static void
450unescape_shellxquote(char_u *p, char_u *escaped)
451{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100452 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100453 int n;
454
455 while (*p != NUL)
456 {
457 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
458 mch_memmove(p, p + 1, l--);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100459 n = (*mb_ptr2len)(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100460 p += n;
461 l -= n;
462 }
463}
464
465/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200466 * Load library "name".
467 */
468 HINSTANCE
469vimLoadLib(char *name)
470{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200471 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200473 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
474 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 if (exe_path == NULL)
476 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200477 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200479 WCHAR old_dirw[MAXPATHL];
480
481 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
482 {
483 /* Change directory to where the executable is, both to make
484 * sure we find a .dll there and to avoid looking for a .dll
485 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100486 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 dll = LoadLibrary(name);
488 SetCurrentDirectoryW(old_dirw);
489 return dll;
490 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200491 }
492 return dll;
493}
494
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200495#if defined(VIMDLL) || defined(PROTO)
496/*
497 * Check if the current executable file is for the GUI subsystem.
498 */
499 int
500mch_is_gui_executable(void)
501{
502 PBYTE pImage = (PBYTE)GetModuleHandle(NULL);
503 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)pImage;
504 PIMAGE_NT_HEADERS pPE;
505
506 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
507 return FALSE;
508 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
509 if (pPE->Signature != IMAGE_NT_SIGNATURE)
510 return FALSE;
511 if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
512 return TRUE;
513 return FALSE;
514}
515#endif
516
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100517#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
518/*
519 * Get related information about 'funcname' which is imported by 'hInst'.
520 * If 'info' is 0, return the function address.
521 * If 'info' is 1, return the module name which the function is imported from.
522 */
523 static void *
524get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
525{
526 PBYTE pImage = (PBYTE)hInst;
527 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
528 PIMAGE_NT_HEADERS pPE;
529 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
530 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
531 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
532 PIMAGE_IMPORT_BY_NAME pImpName;
533
534 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
535 return NULL;
536 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
537 if (pPE->Signature != IMAGE_NT_SIGNATURE)
538 return NULL;
539 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
540 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
541 .VirtualAddress);
542 for (; pImpDesc->FirstThunk; ++pImpDesc)
543 {
544 if (!pImpDesc->OriginalFirstThunk)
545 continue;
546 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
547 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
548 for (; pIAT->u1.Function; ++pIAT, ++pINT)
549 {
550 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
551 continue;
552 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
553 + (UINT_PTR)(pINT->u1.AddressOfData));
554 if (strcmp((char *)pImpName->Name, funcname) == 0)
555 {
556 switch (info)
557 {
558 case 0:
559 return (void *)pIAT->u1.Function;
560 case 1:
561 return (void *)(pImage + pImpDesc->Name);
562 default:
563 return NULL;
564 }
565 }
566 }
567 }
568 return NULL;
569}
570
571/*
572 * Get the module handle which 'funcname' in 'hInst' is imported from.
573 */
574 HINSTANCE
575find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
576{
577 char *modulename;
578
579 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
580 if (modulename != NULL)
581 return GetModuleHandleA(modulename);
582 return NULL;
583}
584
585/*
586 * Get the address of 'funcname' which is imported by 'hInst' DLL.
587 */
588 void *
589get_dll_import_func(HINSTANCE hInst, const char *funcname)
590{
591 return get_imported_func_info(hInst, funcname, 0);
592}
593#endif
594
Bram Moolenaar071d4272004-06-13 20:20:40 +0000595#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
596# ifndef GETTEXT_DLL
597# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar7554c542018-10-06 15:03:15 +0200598# define GETTEXT_DLL_ALT1 "libintl-8.dll"
599# define GETTEXT_DLL_ALT2 "intl.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000600# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200601/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000602static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200603static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000604static char *null_libintl_textdomain(const char *);
605static char *null_libintl_bindtextdomain(const char *, const char *);
606static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100607static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200609static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000610char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200611char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
612 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000613char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
614char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000616char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
617 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100618int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000619
620 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100621dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622{
623 int i;
624 static struct
625 {
626 char *name;
627 FARPROC *ptr;
628 } libintl_entry[] =
629 {
630 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200631 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
633 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
634 {NULL, NULL}
635 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100636 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000637
Bram Moolenaar7554c542018-10-06 15:03:15 +0200638 // No need to initialize twice.
639 if (hLibintlDLL != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640 return 1;
Bram Moolenaar7554c542018-10-06 15:03:15 +0200641 // Load gettext library (libintl.dll and other names).
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100642 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar7554c542018-10-06 15:03:15 +0200643#ifdef GETTEXT_DLL_ALT1
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100644 if (!hLibintlDLL)
Bram Moolenaar7554c542018-10-06 15:03:15 +0200645 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
646#endif
647#ifdef GETTEXT_DLL_ALT2
648 if (!hLibintlDLL)
649 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100650#endif
651 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200653 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200655 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100656 semsg(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200657 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000658 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200659 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000660 }
661 for (i = 0; libintl_entry[i].name != NULL
662 && libintl_entry[i].ptr != NULL; ++i)
663 {
664 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
665 libintl_entry[i].name)) == NULL)
666 {
667 dyn_libintl_end();
668 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000669 {
670 verbose_enter();
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100671 semsg(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000672 verbose_leave();
673 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000674 return 0;
675 }
676 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000677
678 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000679 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000680 "bind_textdomain_codeset");
681 if (dyn_libintl_bind_textdomain_codeset == NULL)
682 dyn_libintl_bind_textdomain_codeset =
683 null_libintl_bind_textdomain_codeset;
684
Bram Moolenaar0eb035c2019-04-02 22:15:55 +0200685 /* _wputenv() function for the libintl.dll is optional. */
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100686 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
687 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100688 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100689 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
690 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100691
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692 return 1;
693}
694
695 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100696dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697{
698 if (hLibintlDLL)
699 FreeLibrary(hLibintlDLL);
700 hLibintlDLL = NULL;
701 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200702 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000703 dyn_libintl_textdomain = null_libintl_textdomain;
704 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000705 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100706 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000707}
708
709 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000710null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000711{
712 return (char*)msgid;
713}
714
715 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200716null_libintl_ngettext(
717 const char *msgid,
718 const char *msgid_plural,
719 unsigned long n)
720{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200721 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200722}
723
Bram Moolenaaree695f72016-08-03 22:08:45 +0200724 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100725null_libintl_bindtextdomain(
726 const char *domainname UNUSED,
727 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728{
729 return NULL;
730}
731
732 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100733null_libintl_bind_textdomain_codeset(
734 const char *domainname UNUSED,
735 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000736{
737 return NULL;
738}
739
740 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100741null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742{
743 return NULL;
744}
745
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200746 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100747null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100748{
749 return 0;
750}
751
Bram Moolenaar071d4272004-06-13 20:20:40 +0000752#endif /* DYNAMIC_GETTEXT */
753
754/* This symbol is not defined in older versions of the SDK or Visual C++ */
755
756#ifndef VER_PLATFORM_WIN32_WINDOWS
757# define VER_PLATFORM_WIN32_WINDOWS 1
758#endif
759
760DWORD g_PlatformId;
761
762#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100763# ifndef PROTO
764# include <aclapi.h>
765# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200766# ifndef PROTECTED_DACL_SECURITY_INFORMATION
767# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
768# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769#endif
770
Bram Moolenaar27515922013-06-29 15:36:26 +0200771#ifdef HAVE_ACL
772/*
773 * Enables or disables the specified privilege.
774 */
775 static BOOL
776win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
777{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100778 BOOL bResult;
779 LUID luid;
780 HANDLE hToken;
781 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200782
783 if (!OpenProcessToken(GetCurrentProcess(),
784 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
785 return FALSE;
786
787 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
788 {
789 CloseHandle(hToken);
790 return FALSE;
791 }
792
Bram Moolenaar45500912014-07-09 20:51:07 +0200793 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200794 tokenPrivileges.Privileges[0].Luid = luid;
795 tokenPrivileges.Privileges[0].Attributes = bEnable ?
796 SE_PRIVILEGE_ENABLED : 0;
797
798 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
799 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
800
801 CloseHandle(hToken);
802
803 return bResult && GetLastError() == ERROR_SUCCESS;
804}
805#endif
806
Bram Moolenaar071d4272004-06-13 20:20:40 +0000807/*
808 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
809 * VER_PLATFORM_WIN32_WINDOWS (Win95).
810 */
811 void
812PlatformId(void)
813{
814 static int done = FALSE;
815
816 if (!done)
817 {
818 OSVERSIONINFO ovi;
819
820 ovi.dwOSVersionInfoSize = sizeof(ovi);
821 GetVersionEx(&ovi);
822
823 g_PlatformId = ovi.dwPlatformId;
824
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100825 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
826 || ovi.dwMajorVersion > 6)
827 win8_or_later = TRUE;
828
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200830 /* Enable privilege for getting or setting SACLs. */
831 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832#endif
833 done = TRUE;
834 }
835}
836
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200837#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838
839#define SHIFT (SHIFT_PRESSED)
840#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
841#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
842#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
843
844
845/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
846 * We map function keys to their ANSI terminal equivalents, as produced
847 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
848 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
849 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
850 * combinations of function/arrow/etc keys.
851 */
852
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000853static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000854{
855 WORD wVirtKey;
856 BOOL fAnsiKey;
857 int chAlone;
858 int chShift;
859 int chCtrl;
860 int chAlt;
861} VirtKeyMap[] =
862{
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200863// Key ANSI alone shift ctrl alt
Bram Moolenaar071d4272004-06-13 20:20:40 +0000864 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
865
866 { VK_F1, TRUE, ';', 'T', '^', 'h', },
867 { VK_F2, TRUE, '<', 'U', '_', 'i', },
868 { VK_F3, TRUE, '=', 'V', '`', 'j', },
869 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
870 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
871 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
872 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
873 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
874 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
875 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200876 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
877 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200879 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
880 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
881 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, // PgUp
882 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
883 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
884 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
885 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
886 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, // PgDn
887 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
888 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100889 { VK_BACK, TRUE, 'x', 'y', 'z', '{', }, // Backspace
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200891 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, // PrtScrn
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892
893#if 0
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200894 // Most people don't have F13-F20, but what the hell...
895 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
896 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
897 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
898 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
899 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
900 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
901 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
902 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903#endif
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200904 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, // keyp '+'
905 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, // keyp '-'
906 // { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, // keyp '/'
907 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, // keyp '*'
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +0200909 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
910 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
911 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
912 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
913 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
914 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
915 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
916 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
917 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
918 // Sorry, out of number space! <negri>
Bram Moolenaarb70a47b2019-03-30 22:11:21 +0100919 { VK_NUMPAD9,TRUE, '\376', '\377', '|', '}', },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920};
921
922
923#ifdef _MSC_VER
924// The ToAscii bug destroys several registers. Need to turn off optimization
925// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000926# pragma warning(push)
927# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928# pragma optimize("", off)
929#endif
930
931#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200932# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200934# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935#endif
936
937/* The return code indicates key code size. */
938 static int
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000940 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941{
942 UINT uMods = pker->dwControlKeyState;
943 static int s_iIsDead = 0;
944 static WORD awAnsiCode[2];
945 static BYTE abKeystate[256];
946
947
948 if (s_iIsDead == 2)
949 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200950 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951 s_iIsDead = 0;
952 return 1;
953 }
954
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200955 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000956 return 1;
957
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200958 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200961 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962
963 if (uMods & SHIFT_PRESSED)
964 abKeystate[VK_SHIFT] = 0x80;
965 if (uMods & CAPSLOCK_ON)
966 abKeystate[VK_CAPITAL] = 1;
967
968 if ((uMods & ALT_GR) == ALT_GR)
969 {
970 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
971 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
972 }
973
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200974 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
975 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976
977 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200978 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979
980 return s_iIsDead;
981}
982
983#ifdef _MSC_VER
984/* MUST switch optimization on again here, otherwise a call to
985 * decode_key_event() may crash (e.g. when hitting caps-lock) */
986# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000987# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000988
989# if (_MSC_VER < 1100)
990/* MUST turn off global optimisation for this next function, or
991 * pressing ctrl-minus in insert mode crashes Vim when built with
992 * VC4.1. -- negri. */
993# pragma optimize("g", off)
994# endif
995#endif
996
997static BOOL g_fJustGotFocus = FALSE;
998
999/*
1000 * Decode a KEY_EVENT into one or two keystrokes
1001 */
1002 static BOOL
1003decode_key_event(
1004 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001005 WCHAR *pch,
1006 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001007 int *pmodifiers,
1008 BOOL fDoPost)
1009{
1010 int i;
1011 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1012
1013 *pch = *pch2 = NUL;
1014 g_fJustGotFocus = FALSE;
1015
1016 /* ignore key up events */
1017 if (!pker->bKeyDown)
1018 return FALSE;
1019
1020 /* ignore some keystrokes */
1021 switch (pker->wVirtualKeyCode)
1022 {
1023 /* modifiers */
1024 case VK_SHIFT:
1025 case VK_CONTROL:
1026 case VK_MENU: /* Alt key */
1027 return FALSE;
1028
1029 default:
1030 break;
1031 }
1032
1033 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001034 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035 {
1036 /* Ctrl-6 is Ctrl-^ */
1037 if (pker->wVirtualKeyCode == '6')
1038 {
1039 *pch = Ctrl_HAT;
1040 return TRUE;
1041 }
1042 /* Ctrl-2 is Ctrl-@ */
1043 else if (pker->wVirtualKeyCode == '2')
1044 {
1045 *pch = NUL;
1046 return TRUE;
1047 }
1048 /* Ctrl-- is Ctrl-_ */
1049 else if (pker->wVirtualKeyCode == 0xBD)
1050 {
1051 *pch = Ctrl__;
1052 return TRUE;
1053 }
1054 }
1055
1056 /* Shift-TAB */
1057 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1058 {
1059 *pch = K_NUL;
1060 *pch2 = '\017';
1061 return TRUE;
1062 }
1063
1064 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1065 {
1066 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1067 {
1068 if (nModifs == 0)
1069 *pch = VirtKeyMap[i].chAlone;
1070 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1071 *pch = VirtKeyMap[i].chShift;
1072 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1073 *pch = VirtKeyMap[i].chCtrl;
1074 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1075 *pch = VirtKeyMap[i].chAlt;
1076
1077 if (*pch != 0)
1078 {
1079 if (VirtKeyMap[i].fAnsiKey)
1080 {
1081 *pch2 = *pch;
1082 *pch = K_NUL;
1083 }
1084
1085 return TRUE;
1086 }
1087 }
1088 }
1089
1090 i = win32_kbd_patch_key(pker);
1091
1092 if (i < 0)
1093 *pch = NUL;
1094 else
1095 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001096 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001097
1098 if (pmodifiers != NULL)
1099 {
1100 /* Pass on the ALT key as a modifier, but only when not combined
1101 * with CTRL (which is ALTGR). */
1102 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1103 *pmodifiers |= MOD_MASK_ALT;
1104
1105 /* Pass on SHIFT only for special keys, because we don't know when
1106 * it's already included with the character. */
1107 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1108 *pmodifiers |= MOD_MASK_SHIFT;
1109
1110 /* Pass on CTRL only for non-special keys, because we don't know
1111 * when it's already included with the character. And not when
1112 * combined with ALT (which is ALTGR). */
1113 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1114 && *pch >= 0x20 && *pch < 0x80)
1115 *pmodifiers |= MOD_MASK_CTRL;
1116 }
1117 }
1118
1119 return (*pch != NUL);
1120}
1121
1122#ifdef _MSC_VER
1123# pragma optimize("", on)
1124#endif
1125
Bram Moolenaar4f974752019-02-17 17:44:42 +01001126#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127
1128
1129#ifdef FEAT_MOUSE
1130
1131/*
1132 * For the GUI the mouse handling is in gui_w32.c.
1133 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001134# if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001135 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001136mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137{
1138}
1139# else
1140static int g_fMouseAvail = FALSE; /* mouse present */
1141static int g_fMouseActive = FALSE; /* mouse enabled */
1142static int g_nMouseClick = -1; /* mouse status */
1143static int g_xMouse; /* mouse x coordinate */
1144static int g_yMouse; /* mouse y coordinate */
1145
1146/*
1147 * Enable or disable mouse input
1148 */
1149 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001150mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151{
1152 DWORD cmodein;
1153
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001154# ifdef VIMDLL
1155 if (gui.in_use)
1156 return;
1157# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158 if (!g_fMouseAvail)
1159 return;
1160
1161 g_fMouseActive = on;
1162 GetConsoleMode(g_hConIn, &cmodein);
1163
1164 if (g_fMouseActive)
1165 cmodein |= ENABLE_MOUSE_INPUT;
1166 else
1167 cmodein &= ~ENABLE_MOUSE_INPUT;
1168
1169 SetConsoleMode(g_hConIn, cmodein);
1170}
1171
Bram Moolenaar157d8132018-03-06 17:09:20 +01001172
1173#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1174/*
1175 * Called when 'balloonevalterm' changed.
1176 */
1177 void
1178mch_bevalterm_changed(void)
1179{
1180 mch_setmouse(g_fMouseActive);
1181}
1182#endif
1183
Bram Moolenaar071d4272004-06-13 20:20:40 +00001184/*
1185 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1186 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1187 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1188 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1189 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1190 * and we return the mouse position in g_xMouse and g_yMouse.
1191 *
1192 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1193 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1194 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1195 *
1196 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1197 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1198 *
1199 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1200 * moves, even if it stays within the same character cell. We ignore
1201 * all MOUSE_MOVED messages if the position hasn't really changed, and
1202 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1203 * we're only interested in MOUSE_DRAG).
1204 *
1205 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1206 * 2-button mouses by pressing the left & right buttons simultaneously.
1207 * In practice, it's almost impossible to click both at the same time,
1208 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1209 * in such cases, if the user is clicking quickly.
1210 */
1211 static BOOL
1212decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001213 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214{
1215 static int s_nOldButton = -1;
1216 static int s_nOldMouseClick = -1;
1217 static int s_xOldMouse = -1;
1218 static int s_yOldMouse = -1;
1219 static linenr_T s_old_topline = 0;
1220#ifdef FEAT_DIFF
1221 static int s_old_topfill = 0;
1222#endif
1223 static int s_cClicks = 1;
1224 static BOOL s_fReleased = TRUE;
1225 static DWORD s_dwLastClickTime = 0;
1226 static BOOL s_fNextIsMiddle = FALSE;
1227
1228 static DWORD cButtons = 0; /* number of buttons supported */
1229
1230 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1231 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1232 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1233 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1234
1235 int nButton;
1236
1237 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1238 cButtons = 2;
1239
1240 if (!g_fMouseAvail || !g_fMouseActive)
1241 {
1242 g_nMouseClick = -1;
1243 return FALSE;
1244 }
1245
1246 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1247 if (g_fJustGotFocus)
1248 {
1249 g_fJustGotFocus = FALSE;
1250 return FALSE;
1251 }
1252
1253 /* unprocessed mouse click? */
1254 if (g_nMouseClick != -1)
1255 return TRUE;
1256
1257 nButton = -1;
1258 g_xMouse = pmer->dwMousePosition.X;
1259 g_yMouse = pmer->dwMousePosition.Y;
1260
1261 if (pmer->dwEventFlags == MOUSE_MOVED)
1262 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001263 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001264 * events even when the mouse moves only within a char cell.) */
1265 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1266 return FALSE;
1267 }
1268
1269 /* If no buttons are pressed... */
1270 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1271 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001272 nButton = MOUSE_RELEASE;
1273
Bram Moolenaar071d4272004-06-13 20:20:40 +00001274 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1275 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001276 {
1277#ifdef FEAT_BEVAL_TERM
1278 /* do return mouse move events when we want them */
1279 if (p_bevalterm)
1280 nButton = MOUSE_DRAG;
1281 else
1282#endif
1283 return FALSE;
1284 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286 s_fReleased = TRUE;
1287 }
1288 else /* one or more buttons pressed */
1289 {
1290 /* on a 2-button mouse, hold down left and right buttons
1291 * simultaneously to get MIDDLE. */
1292
1293 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1294 {
1295 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1296
1297 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001298 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299 if (dwLR == LEFT || dwLR == RIGHT)
1300 {
1301 for (;;)
1302 {
1303 /* wait a short time for next input event */
1304 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1305 != WAIT_OBJECT_0)
1306 break;
1307 else
1308 {
1309 DWORD cRecords = 0;
1310 INPUT_RECORD ir;
1311 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1312
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001313 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001314
1315 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1316 || !(pmer2->dwButtonState & LEFT_RIGHT))
1317 break;
1318 else
1319 {
1320 if (pmer2->dwEventFlags != MOUSE_MOVED)
1321 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001322 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323
1324 return decode_mouse_event(pmer2);
1325 }
1326 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1327 s_yOldMouse == pmer2->dwMousePosition.Y)
1328 {
1329 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001330 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331
1332 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001333 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001334
1335 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1336 break;
1337 }
1338 else
1339 break;
1340 }
1341 }
1342 }
1343 }
1344 }
1345
1346 if (s_fNextIsMiddle)
1347 {
1348 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1349 ? MOUSE_DRAG : MOUSE_MIDDLE;
1350 s_fNextIsMiddle = FALSE;
1351 }
1352 else if (cButtons == 2 &&
1353 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1354 {
1355 nButton = MOUSE_MIDDLE;
1356
1357 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1358 {
1359 s_fNextIsMiddle = TRUE;
1360 nButton = MOUSE_RELEASE;
1361 }
1362 }
1363 else if ((pmer->dwButtonState & LEFT) == LEFT)
1364 nButton = MOUSE_LEFT;
1365 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1366 nButton = MOUSE_MIDDLE;
1367 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1368 nButton = MOUSE_RIGHT;
1369
1370 if (! s_fReleased && ! s_fNextIsMiddle
1371 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1372 return FALSE;
1373
1374 s_fReleased = s_fNextIsMiddle;
1375 }
1376
1377 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1378 {
1379 /* button pressed or released, without mouse moving */
1380 if (nButton != -1 && nButton != MOUSE_RELEASE)
1381 {
1382 DWORD dwCurrentTime = GetTickCount();
1383
1384 if (s_xOldMouse != g_xMouse
1385 || s_yOldMouse != g_yMouse
1386 || s_nOldButton != nButton
1387 || s_old_topline != curwin->w_topline
1388#ifdef FEAT_DIFF
1389 || s_old_topfill != curwin->w_topfill
1390#endif
1391 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1392 {
1393 s_cClicks = 1;
1394 }
1395 else if (++s_cClicks > 4)
1396 {
1397 s_cClicks = 1;
1398 }
1399
1400 s_dwLastClickTime = dwCurrentTime;
1401 }
1402 }
1403 else if (pmer->dwEventFlags == MOUSE_MOVED)
1404 {
1405 if (nButton != -1 && nButton != MOUSE_RELEASE)
1406 nButton = MOUSE_DRAG;
1407
1408 s_cClicks = 1;
1409 }
1410
1411 if (nButton == -1)
1412 return FALSE;
1413
1414 if (nButton != MOUSE_RELEASE)
1415 s_nOldButton = nButton;
1416
1417 g_nMouseClick = nButton;
1418
1419 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1420 g_nMouseClick |= MOUSE_SHIFT;
1421 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1422 g_nMouseClick |= MOUSE_CTRL;
1423 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1424 g_nMouseClick |= MOUSE_ALT;
1425
1426 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1427 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1428
1429 /* only pass on interesting (i.e., different) mouse events */
1430 if (s_xOldMouse == g_xMouse
1431 && s_yOldMouse == g_yMouse
1432 && s_nOldMouseClick == g_nMouseClick)
1433 {
1434 g_nMouseClick = -1;
1435 return FALSE;
1436 }
1437
1438 s_xOldMouse = g_xMouse;
1439 s_yOldMouse = g_yMouse;
1440 s_old_topline = curwin->w_topline;
1441#ifdef FEAT_DIFF
1442 s_old_topfill = curwin->w_topfill;
1443#endif
1444 s_nOldMouseClick = g_nMouseClick;
1445
1446 return TRUE;
1447}
1448
Bram Moolenaar4f974752019-02-17 17:44:42 +01001449# endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450#endif /* FEAT_MOUSE */
1451
1452
1453#ifdef MCH_CURSOR_SHAPE
1454/*
1455 * Set the shape of the cursor.
1456 * 'thickness' can be from 1 (thin) to 99 (block)
1457 */
1458 static void
1459mch_set_cursor_shape(int thickness)
1460{
1461 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1462 ConsoleCursorInfo.dwSize = thickness;
1463 ConsoleCursorInfo.bVisible = s_cursor_visible;
1464
1465 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1466 if (s_cursor_visible)
1467 SetConsoleCursorPosition(g_hConOut, g_coord);
1468}
1469
1470 void
1471mch_update_cursor(void)
1472{
1473 int idx;
1474 int thickness;
1475
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001476# ifdef VIMDLL
1477 if (gui.in_use)
1478 return;
1479# endif
1480
Bram Moolenaar071d4272004-06-13 20:20:40 +00001481 /*
1482 * How the cursor is drawn depends on the current mode.
1483 */
1484 idx = get_shape_idx(FALSE);
1485
1486 if (shape_table[idx].shape == SHAPE_BLOCK)
1487 thickness = 99; /* 100 doesn't work on W95 */
1488 else
1489 thickness = shape_table[idx].percentage;
1490 mch_set_cursor_shape(thickness);
1491}
1492#endif
1493
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001494#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495/*
1496 * Handle FOCUS_EVENT.
1497 */
1498 static void
1499handle_focus_event(INPUT_RECORD ir)
1500{
1501 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1502 ui_focus_change((int)g_fJustGotFocus);
1503}
1504
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001505static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1506
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507/*
1508 * Wait until console input from keyboard or mouse is available,
1509 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001510 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511 * Return TRUE if something is available FALSE if not.
1512 */
1513 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001514WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515{
1516 DWORD dwNow = 0, dwEndTime = 0;
1517 INPUT_RECORD ir;
1518 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001519 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001520#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001521 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001522#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523
1524 if (msec > 0)
1525 /* Wait until the specified time has elapsed. */
1526 dwEndTime = GetTickCount() + msec;
1527 else if (msec < 0)
1528 /* Wait forever. */
1529 dwEndTime = INFINITE;
1530
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01001531 // We need to loop until the end of the time period, because
1532 // we might get multiple unusable mouse events in that time.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 for (;;)
1534 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001535 // Only process messages when waiting.
1536 if (msec != 0)
1537 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001538#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001539 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001540#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001541#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001542 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001543#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001545 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001547 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001548
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549 if (0
1550#ifdef FEAT_MOUSE
1551 || g_nMouseClick != -1
1552#endif
1553#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001554 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555#endif
1556 )
1557 return TRUE;
1558
1559 if (msec > 0)
1560 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001561 /* If the specified wait time has passed, return. Beware that
1562 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001564 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565 break;
1566 }
1567 if (msec != 0)
1568 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001569 DWORD dwWaitTime = dwEndTime - dwNow;
1570
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001571#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001572 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001573 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001574 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001575 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001576 /* If there is readahead then parse_queued_messages() timed out
1577 * and we should call it again soon. */
1578 if (channel_any_readahead())
1579 dwWaitTime = 10;
1580 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001581#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001582#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001583 if (p_beval && dwWaitTime > 100)
1584 /* The 'balloonexpr' may indirectly invoke a callback while
1585 * waiting for a character, need to check often. */
1586 dwWaitTime = 100;
1587#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001588#ifdef FEAT_MZSCHEME
1589 if (mzthreads_allowed() && p_mzq > 0
1590 && (msec < 0 || (long)dwWaitTime > p_mzq))
1591 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1592#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001593#ifdef FEAT_TIMERS
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001594 // When waiting very briefly don't trigger timers.
1595 if (dwWaitTime > 10)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001596 {
1597 long due_time;
1598
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001599 // Trigger timers and then get the time in msec until the next
1600 // one is due. Wait up to that time.
1601 due_time = check_due_timer();
1602 if (typebuf.tb_change_cnt != tb_change_cnt)
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001603 {
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001604 // timer may have used feedkeys().
1605 return FALSE;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001606 }
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001607 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1608 dwWaitTime = due_time;
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001609 }
1610#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001611 if (
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612#ifdef FEAT_CLIENTSERVER
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001613 // Wait for either an event on the console input or a
1614 // message in the client-server window.
1615 msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1616 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617#else
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001618 wait_for_single_object(g_hConIn, dwWaitTime)
1619 != WAIT_OBJECT_0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620#endif
Bram Moolenaar1f20daa2019-01-19 21:12:24 +01001621 )
1622 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623 }
1624
1625 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001626 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627
1628#ifdef FEAT_MBYTE_IME
1629 if (State & CMDLINE && msg_row == Rows - 1)
1630 {
1631 CONSOLE_SCREEN_BUFFER_INFO csbi;
1632
1633 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1634 {
1635 if (csbi.dwCursorPosition.Y != msg_row)
1636 {
1637 /* The screen is now messed up, must redraw the
1638 * command line and later all the windows. */
1639 redraw_all_later(CLEAR);
1640 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1641 redrawcmd();
1642 }
1643 }
1644 }
1645#endif
1646
1647 if (cRecords > 0)
1648 {
1649 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1650 {
1651#ifdef FEAT_MBYTE_IME
1652 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1653 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001654 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001655 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1656 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001657 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658 continue;
1659 }
1660#endif
1661 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1662 NULL, FALSE))
1663 return TRUE;
1664 }
1665
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001666 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001667
1668 if (ir.EventType == FOCUS_EVENT)
1669 handle_focus_event(ir);
1670 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001671 {
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001672 COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1673
1674 // Only call shell_resized() when the size actually change to
1675 // avoid the screen is cleard.
1676 if (dwSize.X != Columns || dwSize.Y != Rows)
1677 {
1678 CONSOLE_SCREEN_BUFFER_INFO csbi;
1679 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
1680 dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1681 ResizeConBuf(g_hConOut, dwSize);
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001682 shell_resized();
Bram Moolenaar78d21da2019-02-17 15:00:52 +01001683 }
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001684 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685#ifdef FEAT_MOUSE
1686 else if (ir.EventType == MOUSE_EVENT
1687 && decode_mouse_event(&ir.Event.MouseEvent))
1688 return TRUE;
1689#endif
1690 }
1691 else if (msec == 0)
1692 break;
1693 }
1694
1695#ifdef FEAT_CLIENTSERVER
1696 /* Something might have been received while we were waiting. */
1697 if (input_available())
1698 return TRUE;
1699#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001700
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701 return FALSE;
1702}
1703
Bram Moolenaar071d4272004-06-13 20:20:40 +00001704/*
1705 * return non-zero if a character is available
1706 */
1707 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001708mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001710# ifdef VIMDLL
1711 if (gui.in_use)
1712 return TRUE;
1713# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001714 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001716
1717# if defined(FEAT_TERMINAL) || defined(PROTO)
1718/*
1719 * Check for any pending input or messages.
1720 */
1721 int
1722mch_check_messages(void)
1723{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001724# ifdef VIMDLL
1725 if (gui.in_use)
1726 return TRUE;
1727# endif
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001728 return WaitForChar(0L, TRUE);
1729}
1730# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731
1732/*
1733 * Create the console input. Used when reading stdin doesn't work.
1734 */
1735 static void
1736create_conin(void)
1737{
1738 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1739 FILE_SHARE_READ|FILE_SHARE_WRITE,
1740 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001741 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742 did_create_conin = TRUE;
1743}
1744
1745/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001746 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001747 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001748 static WCHAR
1749tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001750{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001751 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752
1753 for (;;)
1754 {
1755 INPUT_RECORD ir;
1756 DWORD cRecords = 0;
1757
1758#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001759 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 if (input_available())
1761 return 0;
1762# ifdef FEAT_MOUSE
1763 if (g_nMouseClick != -1)
1764 return 0;
1765# endif
1766#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001767 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001768 {
1769 if (did_create_conin)
1770 read_error_exit();
1771 create_conin();
1772 continue;
1773 }
1774
1775 if (ir.EventType == KEY_EVENT)
1776 {
1777 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1778 pmodifiers, TRUE))
1779 return ch;
1780 }
1781 else if (ir.EventType == FOCUS_EVENT)
1782 handle_focus_event(ir);
1783 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1784 shell_resized();
1785#ifdef FEAT_MOUSE
1786 else if (ir.EventType == MOUSE_EVENT)
1787 {
1788 if (decode_mouse_event(&ir.Event.MouseEvent))
1789 return 0;
1790 }
1791#endif
1792 }
1793}
Bram Moolenaar4f974752019-02-17 17:44:42 +01001794#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795
1796
1797/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001798 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 * Get one or more characters from the keyboard or the mouse.
1800 * If time == 0, do not wait for characters.
1801 * If time == n, wait a short time for characters.
1802 * If time == -1, wait forever for characters.
1803 * Returns the number of characters read into buf.
1804 */
1805 int
1806mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001807 char_u *buf UNUSED,
1808 int maxlen UNUSED,
1809 long time UNUSED,
1810 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001812#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813
1814 int len;
1815 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816#define TYPEAHEADLEN 20
1817 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1818 static int typeaheadlen = 0;
1819
Bram Moolenaarafde13b2019-04-28 19:46:49 +02001820# ifdef VIMDLL
1821 if (gui.in_use)
1822 return 0;
1823# endif
1824
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 /* First use any typeahead that was kept because "buf" was too small. */
1826 if (typeaheadlen > 0)
1827 goto theend;
1828
Bram Moolenaar071d4272004-06-13 20:20:40 +00001829 if (time >= 0)
1830 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001831 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 }
1834 else /* time == -1, wait forever */
1835 {
1836 mch_set_winsize_now(); /* Allow winsize changes from now on */
1837
Bram Moolenaar3918c952005-03-15 22:34:55 +00001838 /*
1839 * If there is no character available within 2 seconds (default)
1840 * write the autoscript file to disk. Or cause the CursorHold event
1841 * to be triggered.
1842 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001843 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001845 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001847 buf[0] = K_SPECIAL;
1848 buf[1] = KS_EXTRA;
1849 buf[2] = (int)KE_CURSORHOLD;
1850 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001852 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001853 }
1854 }
1855
1856 /*
1857 * Try to read as many characters as there are, until the buffer is full.
1858 */
1859
1860 /* we will get at least one key. Get more if they are available. */
1861 g_fCBrkPressed = FALSE;
1862
1863#ifdef MCH_WRITE_DUMP
1864 if (fdDump)
1865 fputc('[', fdDump);
1866#endif
1867
1868 /* Keep looping until there is something in the typeahead buffer and more
1869 * to get and still room in the buffer (up to two bytes for a char and
1870 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001871 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872 && typeaheadlen + 5 <= TYPEAHEADLEN)
1873 {
1874 if (typebuf_changed(tb_change_cnt))
1875 {
1876 /* "buf" may be invalid now if a client put something in the
1877 * typeahead buffer and "buf" is in the typeahead buffer. */
1878 typeaheadlen = 0;
1879 break;
1880 }
1881#ifdef FEAT_MOUSE
1882 if (g_nMouseClick != -1)
1883 {
1884# ifdef MCH_WRITE_DUMP
1885 if (fdDump)
1886 fprintf(fdDump, "{%02x @ %d, %d}",
1887 g_nMouseClick, g_xMouse, g_yMouse);
1888# endif
1889 typeahead[typeaheadlen++] = ESC + 128;
1890 typeahead[typeaheadlen++] = 'M';
1891 typeahead[typeaheadlen++] = g_nMouseClick;
1892 typeahead[typeaheadlen++] = g_xMouse + '!';
1893 typeahead[typeaheadlen++] = g_yMouse + '!';
1894 g_nMouseClick = -1;
1895 }
1896 else
1897#endif
1898 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001899 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001900 int modifiers = 0;
1901
1902 c = tgetch(&modifiers, &ch2);
1903
1904 if (typebuf_changed(tb_change_cnt))
1905 {
1906 /* "buf" may be invalid now if a client put something in the
1907 * typeahead buffer and "buf" is in the typeahead buffer. */
1908 typeaheadlen = 0;
1909 break;
1910 }
1911
1912 if (c == Ctrl_C && ctrl_c_interrupts)
1913 {
1914#if defined(FEAT_CLIENTSERVER)
1915 trash_input_buf();
1916#endif
1917 got_int = TRUE;
1918 }
1919
1920#ifdef FEAT_MOUSE
1921 if (g_nMouseClick == -1)
1922#endif
1923 {
1924 int n = 1;
1925
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001926 if (ch2 == NUL)
1927 {
1928 int i;
1929 char_u *p;
1930 WCHAR ch[2];
1931
1932 ch[0] = c;
1933 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1934 {
1935 ch[1] = tgetch(&modifiers, &ch2);
1936 n++;
1937 }
1938 p = utf16_to_enc(ch, &n);
1939 if (p != NULL)
1940 {
1941 for (i = 0; i < n; i++)
1942 typeahead[typeaheadlen + i] = p[i];
1943 vim_free(p);
1944 }
1945 }
1946 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001947 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 if (ch2 != NUL)
1949 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001950 if (c == K_NUL)
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001951 {
Bram Moolenaar0cc7b2d2018-10-07 15:49:56 +02001952 switch (ch2)
1953 {
1954 case (WCHAR)'\324': // SHIFT+Insert
1955 case (WCHAR)'\325': // CTRL+Insert
1956 case (WCHAR)'\327': // SHIFT+Delete
1957 case (WCHAR)'\330': // CTRL+Delete
1958 typeahead[typeaheadlen + n] = (char_u)ch2;
1959 n++;
1960 break;
1961
1962 default:
1963 typeahead[typeaheadlen + n] = 3;
1964 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1965 n += 2;
1966 break;
1967 }
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001968 }
1969 else
1970 {
1971 typeahead[typeaheadlen + n] = 3;
1972 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1973 n += 2;
1974 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001975 }
1976
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 /* Use the ALT key to set the 8th bit of the character
1978 * when it's one byte, the 8th bit isn't set yet and not
1979 * using a double-byte encoding (would become a lead
1980 * byte). */
1981 if ((modifiers & MOD_MASK_ALT)
1982 && n == 1
1983 && (typeahead[typeaheadlen] & 0x80) == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 && !enc_dbcs
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 )
1986 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001987 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1988 typeahead + typeaheadlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989 modifiers &= ~MOD_MASK_ALT;
1990 }
1991
1992 if (modifiers != 0)
1993 {
1994 /* Prepend modifiers to the character. */
1995 mch_memmove(typeahead + typeaheadlen + 3,
1996 typeahead + typeaheadlen, n);
1997 typeahead[typeaheadlen++] = K_SPECIAL;
1998 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1999 typeahead[typeaheadlen++] = modifiers;
2000 }
2001
2002 typeaheadlen += n;
2003
2004#ifdef MCH_WRITE_DUMP
2005 if (fdDump)
2006 fputc(c, fdDump);
2007#endif
2008 }
2009 }
2010 }
2011
2012#ifdef MCH_WRITE_DUMP
2013 if (fdDump)
2014 {
2015 fputs("]\n", fdDump);
2016 fflush(fdDump);
2017 }
2018#endif
2019
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020theend:
2021 /* Move typeahead to "buf", as much as fits. */
2022 len = 0;
2023 while (len < maxlen && typeaheadlen > 0)
2024 {
2025 buf[len++] = typeahead[0];
2026 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2027 }
2028 return len;
2029
Bram Moolenaar4f974752019-02-17 17:44:42 +01002030#else /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 return 0;
Bram Moolenaar4f974752019-02-17 17:44:42 +01002032#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033}
2034
Bram Moolenaar82881492012-11-20 16:53:39 +01002035#ifndef PROTO
2036# ifndef __MINGW32__
2037# include <shellapi.h> /* required for FindExecutable() */
2038# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039#endif
2040
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002041/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002042 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2043 * If "use_path" is FALSE: Return TRUE if "name" exists.
2044 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2045 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002046 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002047 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002048 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002049executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002051 WCHAR *p;
2052 WCHAR fnamew[_MAX_PATH];
2053 WCHAR *dumw;
2054 WCHAR *wcurpath, *wnewpath;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002055 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002056
Bram Moolenaar43663192017-03-05 14:29:12 +01002057 if (!use_path)
2058 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002059 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002060 {
2061 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002062 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002063 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002064 *path = vim_strsave((char_u *)name);
2065 else
2066 *path = FullName_save((char_u *)name, FALSE);
2067 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002068 return TRUE;
2069 }
2070 return FALSE;
2071 }
2072
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002073 p = enc_to_utf16((char_u *)name, NULL);
2074 if (p == NULL)
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002075 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002076
2077 wcurpath = _wgetenv(L"PATH");
2078 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2079 * sizeof(WCHAR));
2080 if (wnewpath == NULL)
2081 return FALSE;
2082 wcscpy(wnewpath, L".;");
2083 wcscat(wnewpath, wcurpath);
2084 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2085 vim_free(wnewpath);
2086 vim_free(p);
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002087 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002088 return FALSE;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002089 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002090 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002091 if (path != NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002092 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002093 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094}
2095
Bram Moolenaar1eed5322019-02-26 17:03:54 +01002096#if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2097 (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002098/*
2099 * Bad parameter handler.
2100 *
2101 * Certain MS CRT functions will intentionally crash when passed invalid
2102 * parameters to highlight possible security holes. Setting this function as
2103 * the bad parameter handler will prevent the crash.
2104 *
2105 * In debug builds the parameters contain CRT information that might help track
2106 * down the source of a problem, but in non-debug builds the arguments are all
2107 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2108 * worth allowing these to make debugging of issues easier.
2109 */
2110 static void
2111bad_param_handler(const wchar_t *expression,
2112 const wchar_t *function,
2113 const wchar_t *file,
2114 unsigned int line,
2115 uintptr_t pReserved)
2116{
2117}
2118
2119# define SET_INVALID_PARAM_HANDLER \
2120 ((void)_set_invalid_parameter_handler(bad_param_handler))
2121#else
2122# define SET_INVALID_PARAM_HANDLER
2123#endif
2124
Bram Moolenaar4f974752019-02-17 17:44:42 +01002125#ifdef FEAT_GUI_MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126
2127/*
2128 * GUI version of mch_init().
2129 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002130 static void
2131mch_init_g(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132{
2133#ifndef __MINGW32__
2134 extern int _fmode;
2135#endif
2136
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002137 /* Silently handle invalid parameters to CRT functions */
2138 SET_INVALID_PARAM_HANDLER;
2139
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 /* Let critical errors result in a failure, not in a dialog box. Required
2141 * for the timestamp test to work on removed floppies. */
2142 SetErrorMode(SEM_FAILCRITICALERRORS);
2143
2144 _fmode = O_BINARY; /* we do our own CR-LF translation */
2145
2146 /* Specify window size. Is there a place to get the default from? */
2147 Rows = 25;
2148 Columns = 80;
2149
2150 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002151 {
2152 char_u vimrun_location[_MAX_PATH + 4];
2153
2154 /* First try in same directory as gvim.exe */
2155 STRCPY(vimrun_location, exe_name);
2156 STRCPY(gettail(vimrun_location), "vimrun.exe");
2157 if (mch_getperm(vimrun_location) >= 0)
2158 {
2159 if (*skiptowhite(vimrun_location) != NUL)
2160 {
2161 /* Enclose path with white space in double quotes. */
2162 mch_memmove(vimrun_location + 1, vimrun_location,
2163 STRLEN(vimrun_location) + 1);
2164 *vimrun_location = '"';
2165 STRCPY(gettail(vimrun_location), "vimrun\" ");
2166 }
2167 else
2168 STRCPY(gettail(vimrun_location), "vimrun ");
2169
2170 vimrun_path = (char *)vim_strsave(vimrun_location);
2171 s_dont_use_vimrun = FALSE;
2172 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002173 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002174 s_dont_use_vimrun = FALSE;
2175
2176 /* Don't give the warning for a missing vimrun.exe right now, but only
2177 * when vimrun was supposed to be used. Don't bother people that do
2178 * not need vimrun.exe. */
2179 if (s_dont_use_vimrun)
2180 need_vimrun_warning = TRUE;
2181 }
2182
2183 /*
2184 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2185 * Otherwise the default "findstr /n" is used.
2186 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002187 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002188 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2189
2190#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002191 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192#endif
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002193
2194 vtp_flag_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002195}
2196
2197
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002198#endif /* FEAT_GUI_MSWIN */
2199
2200#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002201
2202#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2203#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2204
2205/*
2206 * ClearConsoleBuffer()
2207 * Description:
2208 * Clears the entire contents of the console screen buffer, using the
2209 * specified attribute.
2210 * Returns:
2211 * TRUE on success
2212 */
2213 static BOOL
2214ClearConsoleBuffer(WORD wAttribute)
2215{
2216 CONSOLE_SCREEN_BUFFER_INFO csbi;
2217 COORD coord;
2218 DWORD NumCells, dummy;
2219
2220 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2221 return FALSE;
2222
2223 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2224 coord.X = 0;
2225 coord.Y = 0;
2226 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2227 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2230 coord, &dummy))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232
2233 return TRUE;
2234}
2235
2236/*
2237 * FitConsoleWindow()
2238 * Description:
2239 * Checks if the console window will fit within given buffer dimensions.
2240 * Also, if requested, will shrink the window to fit.
2241 * Returns:
2242 * TRUE on success
2243 */
2244 static BOOL
2245FitConsoleWindow(
2246 COORD dwBufferSize,
2247 BOOL WantAdjust)
2248{
2249 CONSOLE_SCREEN_BUFFER_INFO csbi;
2250 COORD dwWindowSize;
2251 BOOL NeedAdjust = FALSE;
2252
2253 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2254 {
2255 /*
2256 * A buffer resize will fail if the current console window does
2257 * not lie completely within that buffer. To avoid this, we might
2258 * have to move and possibly shrink the window.
2259 */
2260 if (csbi.srWindow.Right >= dwBufferSize.X)
2261 {
2262 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2263 if (dwWindowSize.X > dwBufferSize.X)
2264 dwWindowSize.X = dwBufferSize.X;
2265 csbi.srWindow.Right = dwBufferSize.X - 1;
2266 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2267 NeedAdjust = TRUE;
2268 }
2269 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2270 {
2271 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2272 if (dwWindowSize.Y > dwBufferSize.Y)
2273 dwWindowSize.Y = dwBufferSize.Y;
2274 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2275 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2276 NeedAdjust = TRUE;
2277 }
2278 if (NeedAdjust && WantAdjust)
2279 {
2280 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2281 return FALSE;
2282 }
2283 return TRUE;
2284 }
2285
2286 return FALSE;
2287}
2288
2289typedef struct ConsoleBufferStruct
2290{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002291 BOOL IsValid;
2292 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002293 PCHAR_INFO Buffer;
2294 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002295 PSMALL_RECT Regions;
2296 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297} ConsoleBuffer;
2298
2299/*
2300 * SaveConsoleBuffer()
2301 * Description:
2302 * Saves important information about the console buffer, including the
2303 * actual buffer contents. The saved information is suitable for later
2304 * restoration by RestoreConsoleBuffer().
2305 * Returns:
2306 * TRUE if all information was saved; FALSE otherwise
2307 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2308 */
2309 static BOOL
2310SaveConsoleBuffer(
2311 ConsoleBuffer *cb)
2312{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002313 DWORD NumCells;
2314 COORD BufferCoord;
2315 SMALL_RECT ReadRegion;
2316 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002317 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002318
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 if (cb == NULL)
2320 return FALSE;
2321
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002322 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323 {
2324 cb->IsValid = FALSE;
2325 return FALSE;
2326 }
2327 cb->IsValid = TRUE;
2328
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002329 /*
2330 * Allocate a buffer large enough to hold the entire console screen
2331 * buffer. If this ConsoleBuffer structure has already been initialized
2332 * with a buffer of the correct size, then just use that one.
2333 */
2334 if (!cb->IsValid || cb->Buffer == NULL ||
2335 cb->BufferSize.X != cb->Info.dwSize.X ||
2336 cb->BufferSize.Y != cb->Info.dwSize.Y)
2337 {
2338 cb->BufferSize.X = cb->Info.dwSize.X;
2339 cb->BufferSize.Y = cb->Info.dwSize.Y;
2340 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2341 vim_free(cb->Buffer);
2342 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2343 if (cb->Buffer == NULL)
2344 return FALSE;
2345 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346
2347 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002348 * We will now copy the console screen buffer into our buffer.
2349 * ReadConsoleOutput() seems to be limited as far as how much you
2350 * can read at a time. Empirically, this number seems to be about
2351 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2352 * in chunks until it is all copied. The chunks will all have the
2353 * same horizontal characteristics, so initialize them now. The
2354 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002356 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002357 ReadRegion.Left = 0;
2358 ReadRegion.Right = cb->Info.dwSize.X - 1;
2359 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002360
2361 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2362 if (cb->Regions == NULL || numregions != cb->NumRegions)
2363 {
2364 cb->NumRegions = numregions;
2365 vim_free(cb->Regions);
2366 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2367 if (cb->Regions == NULL)
2368 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002369 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002370 return FALSE;
2371 }
2372 }
2373
2374 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002376 /*
2377 * Read into position (0, Y) in our buffer.
2378 */
2379 BufferCoord.Y = Y;
2380 /*
2381 * Read the region whose top left corner is (0, Y) and whose bottom
2382 * right corner is (width - 1, Y + Y_incr - 1). This should define
2383 * a region of size width by Y_incr. Don't worry if this region is
2384 * too large for the remaining buffer; it will be cropped.
2385 */
2386 ReadRegion.Top = Y;
2387 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002388 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002389 cb->Buffer, /* our buffer */
2390 cb->BufferSize, /* dimensions of our buffer */
2391 BufferCoord, /* offset in our buffer */
2392 &ReadRegion)) /* region to save */
2393 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002394 VIM_CLEAR(cb->Buffer);
2395 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002396 return FALSE;
2397 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002398 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 }
2400
2401 return TRUE;
2402}
2403
2404/*
2405 * RestoreConsoleBuffer()
2406 * Description:
2407 * Restores important information about the console buffer, including the
2408 * actual buffer contents, if desired. The information to restore is in
2409 * the same format used by SaveConsoleBuffer().
2410 * Returns:
2411 * TRUE on success
2412 */
2413 static BOOL
2414RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002415 ConsoleBuffer *cb,
2416 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002418 COORD BufferCoord;
2419 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002420 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421
2422 if (cb == NULL || !cb->IsValid)
2423 return FALSE;
2424
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002425 /*
2426 * Before restoring the buffer contents, clear the current buffer, and
2427 * restore the cursor position and window information. Doing this now
2428 * prevents old buffer contents from "flashing" onto the screen.
2429 */
2430 if (RestoreScreen)
2431 ClearConsoleBuffer(cb->Info.wAttributes);
2432
2433 FitConsoleWindow(cb->Info.dwSize, TRUE);
2434 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2435 return FALSE;
2436 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2437 return FALSE;
2438
2439 if (!RestoreScreen)
2440 {
2441 /*
2442 * No need to restore the screen buffer contents, so we're done.
2443 */
2444 return TRUE;
2445 }
2446
2447 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2448 return FALSE;
2449 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2450 return FALSE;
2451
2452 /*
2453 * Restore the screen buffer contents.
2454 */
2455 if (cb->Buffer != NULL)
2456 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002457 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002458 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002459 BufferCoord.X = cb->Regions[i].Left;
2460 BufferCoord.Y = cb->Regions[i].Top;
2461 WriteRegion = cb->Regions[i];
2462 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2463 cb->Buffer, /* our buffer */
2464 cb->BufferSize, /* dimensions of our buffer */
2465 BufferCoord, /* offset in our buffer */
2466 &WriteRegion)) /* region to restore */
Bram Moolenaar444fda22017-08-11 20:37:00 +02002467 return FALSE;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002468 }
2469 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470
2471 return TRUE;
2472}
2473
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002474#define FEAT_RESTORE_ORIG_SCREEN
2475#ifdef FEAT_RESTORE_ORIG_SCREEN
2476static ConsoleBuffer g_cbOrig = { 0 };
2477#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478static ConsoleBuffer g_cbNonTermcap = { 0 };
2479static ConsoleBuffer g_cbTermcap = { 0 };
2480
2481#ifdef FEAT_TITLE
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482char g_szOrigTitle[256] = { 0 };
2483HWND g_hWnd = NULL; /* also used in os_mswin.c */
2484static HICON g_hOrigIconSmall = NULL;
2485static HICON g_hOrigIcon = NULL;
2486static HICON g_hVimIcon = NULL;
2487static BOOL g_fCanChangeIcon = FALSE;
2488
2489/* ICON* are not defined in VC++ 4.0 */
2490#ifndef ICON_SMALL
2491#define ICON_SMALL 0
2492#endif
2493#ifndef ICON_BIG
2494#define ICON_BIG 1
2495#endif
2496/*
2497 * GetConsoleIcon()
2498 * Description:
2499 * Attempts to retrieve the small icon and/or the big icon currently in
2500 * use by a given window.
2501 * Returns:
2502 * TRUE on success
2503 */
2504 static BOOL
2505GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002506 HWND hWnd,
2507 HICON *phIconSmall,
2508 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509{
2510 if (hWnd == NULL)
2511 return FALSE;
2512
2513 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002514 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2515 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002517 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2518 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 return TRUE;
2520}
2521
2522/*
2523 * SetConsoleIcon()
2524 * Description:
2525 * Attempts to change the small icon and/or the big icon currently in
2526 * use by a given window.
2527 * Returns:
2528 * TRUE on success
2529 */
2530 static BOOL
2531SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002532 HWND hWnd,
2533 HICON hIconSmall,
2534 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 if (hWnd == NULL)
2537 return FALSE;
2538
2539 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002540 SendMessage(hWnd, WM_SETICON,
2541 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002543 SendMessage(hWnd, WM_SETICON,
2544 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 return TRUE;
2546}
2547
2548/*
2549 * SaveConsoleTitleAndIcon()
2550 * Description:
2551 * Saves the current console window title in g_szOrigTitle, for later
2552 * restoration. Also, attempts to obtain a handle to the console window,
2553 * and use it to save the small and big icons currently in use by the
2554 * console window. This is not always possible on some versions of Windows;
2555 * nor is it possible when running Vim remotely using Telnet (since the
2556 * console window the user sees is owned by a remote process).
2557 */
2558 static void
2559SaveConsoleTitleAndIcon(void)
2560{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561 /* Save the original title. */
2562 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2563 return;
2564
2565 /*
2566 * Obtain a handle to the console window using GetConsoleWindow() from
2567 * KERNEL32.DLL; we need to handle in order to change the window icon.
2568 * This function only exists on NT-based Windows, starting with Windows
2569 * 2000. On older operating systems, we can't change the window icon
2570 * anyway.
2571 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002572 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573 if (g_hWnd == NULL)
2574 return;
2575
2576 /* Save the original console window icon. */
2577 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2578 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2579 return;
2580
2581 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002582 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002583 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 if (g_hVimIcon != NULL)
2585 g_fCanChangeIcon = TRUE;
2586}
2587#endif
2588
2589static int g_fWindInitCalled = FALSE;
2590static int g_fTermcapMode = FALSE;
2591static CONSOLE_CURSOR_INFO g_cci;
2592static DWORD g_cmodein = 0;
2593static DWORD g_cmodeout = 0;
2594
2595/*
2596 * non-GUI version of mch_init().
2597 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002598 static void
2599mch_init_c(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002601#ifndef FEAT_RESTORE_ORIG_SCREEN
2602 CONSOLE_SCREEN_BUFFER_INFO csbi;
2603#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604#ifndef __MINGW32__
2605 extern int _fmode;
2606#endif
2607
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002608 /* Silently handle invalid parameters to CRT functions */
2609 SET_INVALID_PARAM_HANDLER;
2610
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 /* Let critical errors result in a failure, not in a dialog box. Required
2612 * for the timestamp test to work on removed floppies. */
2613 SetErrorMode(SEM_FAILCRITICALERRORS);
2614
2615 _fmode = O_BINARY; /* we do our own CR-LF translation */
2616 out_flush();
2617
2618 /* Obtain handles for the standard Console I/O devices */
2619 if (read_cmd_fd == 0)
2620 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2621 else
2622 create_conin();
2623 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2624
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002625#ifdef FEAT_RESTORE_ORIG_SCREEN
2626 /* Save the initial console buffer for later restoration */
2627 SaveConsoleBuffer(&g_cbOrig);
2628 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2629#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002631 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2632 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2633#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 if (cterm_normal_fg_color == 0)
2635 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2636 if (cterm_normal_bg_color == 0)
2637 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2638
Bram Moolenaarbdace832019-03-02 10:13:42 +01002639 // Fg and Bg color index number at startup
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002640 g_color_index_fg = g_attrDefault & 0xf;
2641 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2642
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643 /* set termcap codes to current text attributes */
2644 update_tcap(g_attrCurrent);
2645
2646 GetConsoleCursorInfo(g_hConOut, &g_cci);
2647 GetConsoleMode(g_hConIn, &g_cmodein);
2648 GetConsoleMode(g_hConOut, &g_cmodeout);
2649
2650#ifdef FEAT_TITLE
2651 SaveConsoleTitleAndIcon();
2652 /*
2653 * Set both the small and big icons of the console window to Vim's icon.
2654 * Note that Vim presently only has one size of icon (32x32), but it
2655 * automatically gets scaled down to 16x16 when setting the small icon.
2656 */
2657 if (g_fCanChangeIcon)
2658 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2659#endif
2660
2661 ui_get_shellsize();
2662
2663#ifdef MCH_WRITE_DUMP
2664 fdDump = fopen("dump", "wt");
2665
2666 if (fdDump)
2667 {
2668 time_t t;
2669
2670 time(&t);
2671 fputs(ctime(&t), fdDump);
2672 fflush(fdDump);
2673 }
2674#endif
2675
2676 g_fWindInitCalled = TRUE;
2677
2678#ifdef FEAT_MOUSE
2679 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2680#endif
2681
2682#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002683 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002685
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01002686 vtp_flag_init();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002687 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688}
2689
2690/*
2691 * non-GUI version of mch_exit().
2692 * Shut down and exit with status `r'
2693 * Careful: mch_exit() may be called before mch_init()!
2694 */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002695 static void
2696mch_exit_c(int r)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002697{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002698 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002699
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002700 vtp_exit();
2701
Bram Moolenaar955f1982017-02-05 15:10:51 +01002702 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703 if (g_fWindInitCalled)
2704 settmode(TMODE_COOK);
2705
2706 ml_close_all(TRUE); /* remove all memfiles */
2707
2708 if (g_fWindInitCalled)
2709 {
2710#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002711 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 /*
2713 * Restore both the small and big icons of the console window to
2714 * what they were at startup. Don't do this when the window is
2715 * closed, Vim would hang here.
2716 */
2717 if (g_fCanChangeIcon && !g_fForceExit)
2718 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2719#endif
2720
2721#ifdef MCH_WRITE_DUMP
2722 if (fdDump)
2723 {
2724 time_t t;
2725
2726 time(&t);
2727 fputs(ctime(&t), fdDump);
2728 fclose(fdDump);
2729 }
2730 fdDump = NULL;
2731#endif
2732 }
2733
2734 SetConsoleCursorInfo(g_hConOut, &g_cci);
2735 SetConsoleMode(g_hConIn, g_cmodein);
2736 SetConsoleMode(g_hConOut, g_cmodeout);
2737
2738#ifdef DYNAMIC_GETTEXT
2739 dyn_libintl_end();
2740#endif
2741
2742 exit(r);
2743}
Bram Moolenaar4f974752019-02-17 17:44:42 +01002744#endif /* !FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002746 void
2747mch_init(void)
2748{
2749#ifdef VIMDLL
2750 if (gui.starting)
2751 mch_init_g();
2752 else
2753 mch_init_c();
2754#elif defined(FEAT_GUI_MSWIN)
2755 mch_init_g();
2756#else
2757 mch_init_c();
2758#endif
2759}
2760
2761 void
2762mch_exit(int r)
2763{
2764#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02002765 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002766 mch_exit_g(r);
2767 else
2768 mch_exit_c(r);
2769#elif defined(FEAT_GUI_MSWIN)
2770 mch_exit_g(r);
2771#else
2772 mch_exit_c(r);
2773#endif
2774}
2775
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776/*
2777 * Do we have an interactive window?
2778 */
2779 int
2780mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002781 int argc UNUSED,
2782 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783{
2784 get_exe_name();
2785
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002786#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787 return OK; /* GUI always has a tty */
2788#else
Bram Moolenaarafde13b2019-04-28 19:46:49 +02002789# ifdef VIMDLL
2790 if (gui.in_use)
2791 return OK;
2792# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793 if (isatty(1))
2794 return OK;
2795 return FAIL;
2796#endif
2797}
2798
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002799/*
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002800 * Set the case of the file name, if it already exists.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 * When "len" is > 0, also expand short to long filenames.
2802 */
2803 void
2804fname_case(
2805 char_u *name,
2806 int len)
2807{
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002808 int flen;
2809 WCHAR *p;
2810 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002811
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002812 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002813 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814 return;
2815
2816 slash_adjust(name);
2817
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002818 p = enc_to_utf16(name, NULL);
2819 if (p == NULL)
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002820 return;
2821
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002822 if (GetLongPathNameW(p, buf, _MAX_PATH))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002823 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002824 char_u *q = utf16_to_enc(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002825
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002826 if (q != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002827 {
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002828 if (len > 0 || flen >= (int)STRLEN(q))
2829 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2830 vim_free(q);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831 }
2832 }
Bram Moolenaar8bb41b32019-03-30 17:28:16 +01002833 vim_free(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834}
2835
2836
2837/*
2838 * Insert user name in s[len].
2839 */
2840 int
2841mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002842 char_u *s,
2843 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002844{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002845 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2846 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002848 if (GetUserNameW(wszUserName, &wcch))
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002849 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002850 char_u *p = utf16_to_enc(wszUserName, NULL);
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002851
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002852 if (p != NULL)
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002853 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002854 vim_strncpy(s, p, len - 1);
2855 vim_free(p);
2856 return OK;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002857 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002858 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859 s[0] = NUL;
2860 return FAIL;
2861}
2862
2863
2864/*
2865 * Insert host name in s[len].
2866 */
2867 void
2868mch_get_host_name(
2869 char_u *s,
2870 int len)
2871{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002872 WCHAR wszHostName[256 + 1];
2873 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002875 if (GetComputerNameW(wszHostName, &wcch))
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002876 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002877 char_u *p = utf16_to_enc(wszHostName, NULL);
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002878
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002879 if (p != NULL)
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002880 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002881 vim_strncpy(s, p, len - 1);
2882 vim_free(p);
2883 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002884 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002885 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886}
2887
2888
2889/*
2890 * return process ID
2891 */
2892 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002893mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894{
2895 return (long)GetCurrentProcessId();
2896}
2897
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002898/*
2899 * return TRUE if process "pid" is still running
2900 */
2901 int
Bram Moolenaar1b243ea2019-04-28 22:50:40 +02002902mch_process_running(long pid)
Bram Moolenaar67cf86b2019-04-28 22:25:38 +02002903{
2904 HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
2905 DWORD status = 0;
2906 int ret = FALSE;
2907
2908 if (hProcess == NULL)
2909 return FALSE; // might not have access
2910 if (GetExitCodeProcess(hProcess, &status) )
2911 ret = status == STILL_ACTIVE;
2912 CloseHandle(hProcess);
2913 return ret;
2914}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915
2916/*
2917 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2918 * Return OK for success, FAIL for failure.
2919 */
2920 int
2921mch_dirname(
2922 char_u *buf,
2923 int len)
2924{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002925 WCHAR wbuf[_MAX_PATH + 1];
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002926
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 /*
2928 * Originally this was:
2929 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2930 * But the Win32s known bug list says that getcwd() doesn't work
2931 * so use the Win32 system call instead. <Negri>
2932 */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002933 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002935 WCHAR wcbuf[_MAX_PATH + 1];
2936 char_u *p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002938 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002940 p = utf16_to_enc(wcbuf, NULL);
2941 if (STRLEN(p) >= (size_t)len)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02002942 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002943 // long path name is too long, fall back to short one
Bram Moolenaar071d4272004-06-13 20:20:40 +00002944 vim_free(p);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002945 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 }
2947 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002948 if (p == NULL)
2949 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02002950
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002951 if (p != NULL)
2952 {
2953 vim_strncpy(buf, p, len - 1);
2954 vim_free(p);
2955 return OK;
2956 }
2957 }
2958 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959}
2960
2961/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002962 * Get file permissions for "name".
2963 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964 */
2965 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002966mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002968 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002969 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002971 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002972 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973}
2974
2975
2976/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002977 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002978 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002979 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002980 */
2981 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002982mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002984 long n;
2985 WCHAR *p;
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002986
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002987 p = enc_to_utf16(name, NULL);
2988 if (p == NULL)
2989 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02002991 n = _wchmod(p, perm);
2992 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002993 if (n == -1)
2994 return FAIL;
2995
2996 win32_set_archive(name);
2997
2998 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002999}
3000
3001/*
3002 * Set hidden flag for "name".
3003 */
3004 void
3005mch_hide(char_u *name)
3006{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003007 int attrs = win32_getattrs(name);
3008 if (attrs == -1)
3009 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003010
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003011 attrs |= FILE_ATTRIBUTE_HIDDEN;
3012 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003013}
3014
3015/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003016 * Return TRUE if file "name" exists and is hidden.
3017 */
3018 int
3019mch_ishidden(char_u *name)
3020{
3021 int f = win32_getattrs(name);
3022
3023 if (f == -1)
3024 return FALSE; /* file does not exist at all */
3025
3026 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3027}
3028
3029/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003030 * return TRUE if "name" is a directory
3031 * return FALSE if "name" is not a directory or upon error
3032 */
3033 int
3034mch_isdir(char_u *name)
3035{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003036 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037
3038 if (f == -1)
3039 return FALSE; /* file does not exist at all */
3040
3041 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3042}
3043
3044/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003045 * return TRUE if "name" is a directory, NOT a symlink to a directory
3046 * return FALSE if "name" is not a directory
3047 * return FALSE for error
3048 */
3049 int
3050mch_isrealdir(char_u *name)
3051{
3052 return mch_isdir(name) && !mch_is_symbolic_link(name);
3053}
3054
3055/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003056 * Create directory "name".
3057 * Return 0 on success, -1 on error.
3058 */
3059 int
3060mch_mkdir(char_u *name)
3061{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003062 WCHAR *p;
3063 int retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003064
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003065 p = enc_to_utf16(name, NULL);
3066 if (p == NULL)
3067 return -1;
3068 retval = _wmkdir(p);
3069 vim_free(p);
3070 return retval;
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003071}
3072
3073/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003074 * Delete directory "name".
3075 * Return 0 on success, -1 on error.
3076 */
3077 int
3078mch_rmdir(char_u *name)
3079{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003080 WCHAR *p;
3081 int retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003082
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003083 p = enc_to_utf16(name, NULL);
3084 if (p == NULL)
3085 return -1;
3086 retval = _wrmdir(p);
3087 vim_free(p);
3088 return retval;
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003089}
3090
3091/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003092 * Return TRUE if file "fname" has more than one link.
3093 */
3094 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003095mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003096{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003097 BY_HANDLE_FILE_INFORMATION info;
3098
3099 return win32_fileinfo(fname, &info) == FILEINFO_OK
3100 && info.nNumberOfLinks > 1;
3101}
3102
3103/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003104 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003105 */
3106 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003107mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003108{
3109 HANDLE hFind;
3110 int res = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003111 DWORD fileFlags = 0, reparseTag = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003112 WCHAR *wn;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003113 WIN32_FIND_DATAW findDataW;
3114
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003115 wn = enc_to_utf16(name, NULL);
3116 if (wn == NULL)
3117 return FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003118
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003119 hFind = FindFirstFileW(wn, &findDataW);
3120 vim_free(wn);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003121 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003122 {
3123 fileFlags = findDataW.dwFileAttributes;
3124 reparseTag = findDataW.dwReserved0;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003125 FindClose(hFind);
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003126 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003127
3128 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003129 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3130 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003131 res = TRUE;
3132
3133 return res;
3134}
3135
3136/*
3137 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3138 * link.
3139 */
3140 int
3141mch_is_linked(char_u *fname)
3142{
3143 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3144 return TRUE;
3145 return FALSE;
3146}
3147
3148/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003149 * Get the by-handle-file-information for "fname".
3150 * Returns FILEINFO_OK when OK.
3151 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3152 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3153 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3154 */
3155 int
3156win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3157{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003158 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003159 int res = FILEINFO_READ_FAIL;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003160 WCHAR *wn;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003161
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003162 wn = enc_to_utf16(fname, NULL);
3163 if (wn == NULL)
3164 return FILEINFO_ENC_FAIL;
3165
3166 hFile = CreateFileW(wn, // file name
3167 GENERIC_READ, // access mode
3168 FILE_SHARE_READ | FILE_SHARE_WRITE, // share mode
3169 NULL, // security descriptor
3170 OPEN_EXISTING, // creation disposition
3171 FILE_FLAG_BACKUP_SEMANTICS, // file attributes
3172 NULL); // handle to template file
3173 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003174
3175 if (hFile != INVALID_HANDLE_VALUE)
3176 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003177 if (GetFileInformationByHandle(hFile, info) != 0)
3178 res = FILEINFO_OK;
3179 else
3180 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003181 CloseHandle(hFile);
3182 }
3183
Bram Moolenaar03f48552006-02-28 23:52:23 +00003184 return res;
3185}
3186
3187/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003188 * get file attributes for `name'
3189 * -1 : error
3190 * else FILE_ATTRIBUTE_* defined in winnt.h
3191 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003192 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003193win32_getattrs(char_u *name)
3194{
3195 int attr;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003196 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003197
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003198 p = enc_to_utf16(name, NULL);
3199 if (p == NULL)
3200 return INVALID_FILE_ATTRIBUTES;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003201
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003202 attr = GetFileAttributesW(p);
3203 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003204
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003205 return attr;
3206}
3207
3208/*
3209 * set file attributes for `name' to `attrs'
3210 *
3211 * return -1 for failure, 0 otherwise
3212 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003213 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003214win32_setattrs(char_u *name, int attrs)
3215{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003216 int res;
3217 WCHAR *p;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003218
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003219 p = enc_to_utf16(name, NULL);
3220 if (p == NULL)
3221 return -1;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003222
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003223 res = SetFileAttributesW(p, attrs);
3224 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003225
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003226 return res ? 0 : -1;
3227}
3228
3229/*
3230 * Set archive flag for "name".
3231 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003232 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003233win32_set_archive(char_u *name)
3234{
3235 int attrs = win32_getattrs(name);
3236 if (attrs == -1)
3237 return -1;
3238
3239 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3240 return win32_setattrs(name, attrs);
3241}
3242
3243/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244 * Return TRUE if file or directory "name" is writable (not readonly).
3245 * Strange semantics of Win32: a readonly directory is writable, but you can't
3246 * delete a file. Let's say this means it is writable.
3247 */
3248 int
3249mch_writable(char_u *name)
3250{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003251 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003253 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3254 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255}
3256
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003258 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003259 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003260 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3261 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 */
3263 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003264mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265{
Bram Moolenaar86621892019-03-30 21:51:28 +01003266 // WinNT and later can use _MAX_PATH wide characters for a pathname, which
3267 // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
3268 // UTF-8.
3269 char_u buf[_MAX_PATH * 3];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003270 int len = (int)STRLEN(name);
Bram Moolenaar82956662018-10-06 15:18:45 +02003271 char_u *p, *saved;
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003272
Bram Moolenaar86621892019-03-30 21:51:28 +01003273 if (len >= sizeof(buf)) // safety check
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003274 return FALSE;
3275
Bram Moolenaar86621892019-03-30 21:51:28 +01003276 // Try using the name directly when a Unix-shell like 'shell'.
Bram Moolenaar82956662018-10-06 15:18:45 +02003277 if (strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003278 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003279 return TRUE;
3280
3281 /*
3282 * Loop over all extensions in $PATHEXT.
3283 */
Bram Moolenaar82956662018-10-06 15:18:45 +02003284 p = mch_getenv("PATHEXT");
3285 if (p == NULL)
3286 p = (char_u *)".com;.exe;.bat;.cmd";
3287 saved = vim_strsave(p);
3288 if (saved == NULL)
3289 return FALSE;
3290 p = saved;
3291 while (*p)
3292 {
3293 char_u *tmp = vim_strchr(p, ';');
3294
3295 if (tmp != NULL)
3296 *tmp = NUL;
3297 if (_stricoll((char *)name + len - STRLEN(p), (char *)p) == 0
3298 && executable_exists((char *)name, path, use_path))
3299 {
3300 vim_free(saved);
3301 return TRUE;
3302 }
3303 if (tmp == NULL)
3304 break;
3305 p = tmp + 1;
3306 }
3307 vim_free(saved);
3308
Bram Moolenaar86621892019-03-30 21:51:28 +01003309 vim_strncpy(buf, name, sizeof(buf) - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003310 p = mch_getenv("PATHEXT");
3311 if (p == NULL)
3312 p = (char_u *)".com;.exe;.bat;.cmd";
3313 while (*p)
3314 {
3315 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3316 {
3317 /* A single "." means no extension is added. */
3318 buf[len] = NUL;
3319 ++p;
3320 if (*p)
3321 ++p;
3322 }
3323 else
Bram Moolenaar86621892019-03-30 21:51:28 +01003324 copy_option_part(&p, buf + len, sizeof(buf) - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003325 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003326 return TRUE;
3327 }
3328 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003329}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330
3331/*
3332 * Check what "name" is:
3333 * NODE_NORMAL: file or directory (or doesn't exist)
3334 * NODE_WRITABLE: writable device, socket, fifo, etc.
3335 * NODE_OTHER: non-writable things
3336 */
3337 int
3338mch_nodetype(char_u *name)
3339{
3340 HANDLE hFile;
3341 int type;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003342 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343
Bram Moolenaar043545e2006-10-10 16:44:07 +00003344 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3345 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3346 * here. */
3347 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3348 return NODE_WRITABLE;
3349
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003350 wn = enc_to_utf16(name, NULL);
3351 if (wn == NULL)
3352 return NODE_NORMAL;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003353
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003354 hFile = CreateFileW(wn, // file name
3355 GENERIC_WRITE, // access mode
3356 0, // share mode
3357 NULL, // security descriptor
3358 OPEN_EXISTING, // creation disposition
3359 0, // file attributes
3360 NULL); // handle to template file
3361 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003362 if (hFile == INVALID_HANDLE_VALUE)
3363 return NODE_NORMAL;
3364
3365 type = GetFileType(hFile);
3366 CloseHandle(hFile);
3367 if (type == FILE_TYPE_CHAR)
3368 return NODE_WRITABLE;
3369 if (type == FILE_TYPE_DISK)
3370 return NODE_NORMAL;
3371 return NODE_OTHER;
3372}
3373
3374#ifdef HAVE_ACL
3375struct my_acl
3376{
3377 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3378 PSID pSidOwner;
3379 PSID pSidGroup;
3380 PACL pDacl;
3381 PACL pSacl;
3382};
3383#endif
3384
3385/*
3386 * Return a pointer to the ACL of file "fname" in allocated memory.
3387 * Return NULL if the ACL is not available for whatever reason.
3388 */
3389 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003390mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003391{
3392#ifndef HAVE_ACL
3393 return (vim_acl_T)NULL;
3394#else
3395 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003396 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003398 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3399 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003400 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003401 WCHAR *wn;
Bram Moolenaar27515922013-06-29 15:36:26 +02003402
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003403 wn = enc_to_utf16(fname, NULL);
3404 if (wn == NULL)
3405 return NULL;
3406
3407 // Try to retrieve the entire security descriptor.
3408 err = GetNamedSecurityInfoW(
3409 wn, // Abstract filename
3410 SE_FILE_OBJECT, // File Object
3411 OWNER_SECURITY_INFORMATION |
3412 GROUP_SECURITY_INFORMATION |
3413 DACL_SECURITY_INFORMATION |
3414 SACL_SECURITY_INFORMATION,
3415 &p->pSidOwner, // Ownership information.
3416 &p->pSidGroup, // Group membership.
3417 &p->pDacl, // Discretionary information.
3418 &p->pSacl, // For auditing purposes.
3419 &p->pSecurityDescriptor);
3420 if (err == ERROR_ACCESS_DENIED ||
3421 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003422 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003423 // Retrieve only DACL.
3424 (void)GetNamedSecurityInfoW(
3425 wn,
3426 SE_FILE_OBJECT,
3427 DACL_SECURITY_INFORMATION,
3428 NULL,
3429 NULL,
3430 &p->pDacl,
3431 NULL,
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003432 &p->pSecurityDescriptor);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003433 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003434 if (p->pSecurityDescriptor == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003435 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003436 mch_free_acl((vim_acl_T)p);
3437 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003439 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440 }
3441
3442 return (vim_acl_T)p;
3443#endif
3444}
3445
Bram Moolenaar27515922013-06-29 15:36:26 +02003446#ifdef HAVE_ACL
3447/*
3448 * Check if "acl" contains inherited ACE.
3449 */
3450 static BOOL
3451is_acl_inherited(PACL acl)
3452{
3453 DWORD i;
3454 ACL_SIZE_INFORMATION acl_info;
3455 PACCESS_ALLOWED_ACE ace;
3456
3457 acl_info.AceCount = 0;
3458 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3459 for (i = 0; i < acl_info.AceCount; i++)
3460 {
3461 GetAce(acl, i, (LPVOID *)&ace);
3462 if (ace->Header.AceFlags & INHERITED_ACE)
3463 return TRUE;
3464 }
3465 return FALSE;
3466}
3467#endif
3468
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469/*
3470 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3471 * Errors are ignored.
3472 * This must only be called with "acl" equal to what mch_get_acl() returned.
3473 */
3474 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003475mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003476{
3477#ifdef HAVE_ACL
3478 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003479 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003480 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003482 if (p == NULL)
3483 return;
3484
3485 wn = enc_to_utf16(fname, NULL);
3486 if (wn == NULL)
3487 return;
3488
3489 // Set security flags
3490 if (p->pSidOwner)
3491 sec_info |= OWNER_SECURITY_INFORMATION;
3492 if (p->pSidGroup)
3493 sec_info |= GROUP_SECURITY_INFORMATION;
3494 if (p->pDacl)
Bram Moolenaar27515922013-06-29 15:36:26 +02003495 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003496 sec_info |= DACL_SECURITY_INFORMATION;
3497 // Do not inherit its parent's DACL.
3498 // If the DACL is inherited, Cygwin permissions would be changed.
3499 if (!is_acl_inherited(p->pDacl))
3500 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
Bram Moolenaar27515922013-06-29 15:36:26 +02003501 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003502 if (p->pSacl)
3503 sec_info |= SACL_SECURITY_INFORMATION;
3504
3505 (void)SetNamedSecurityInfoW(
3506 wn, // Abstract filename
3507 SE_FILE_OBJECT, // File Object
3508 sec_info,
3509 p->pSidOwner, // Ownership information.
3510 p->pSidGroup, // Group membership.
3511 p->pDacl, // Discretionary information.
3512 p->pSacl // For auditing purposes.
3513 );
3514 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003515#endif
3516}
3517
3518 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003519mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003520{
3521#ifdef HAVE_ACL
3522 struct my_acl *p = (struct my_acl *)acl;
3523
3524 if (p != NULL)
3525 {
3526 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3527 vim_free(p);
3528 }
3529#endif
3530}
3531
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003532#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533
3534/*
3535 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3536 */
3537 static BOOL WINAPI
3538handler_routine(
3539 DWORD dwCtrlType)
3540{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003541 INPUT_RECORD ir;
3542 DWORD out;
3543
Bram Moolenaar071d4272004-06-13 20:20:40 +00003544 switch (dwCtrlType)
3545 {
3546 case CTRL_C_EVENT:
3547 if (ctrl_c_interrupts)
3548 g_fCtrlCPressed = TRUE;
3549 return TRUE;
3550
3551 case CTRL_BREAK_EVENT:
3552 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003553 ctrl_break_was_pressed = TRUE;
3554 /* ReadConsoleInput is blocking, send a key event to continue. */
3555 ir.EventType = KEY_EVENT;
3556 ir.Event.KeyEvent.bKeyDown = TRUE;
3557 ir.Event.KeyEvent.wRepeatCount = 1;
3558 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3559 ir.Event.KeyEvent.wVirtualScanCode = 0;
3560 ir.Event.KeyEvent.dwControlKeyState = 0;
3561 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3562 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563 return TRUE;
3564
3565 /* fatal events: shut down gracefully */
3566 case CTRL_CLOSE_EVENT:
3567 case CTRL_LOGOFF_EVENT:
3568 case CTRL_SHUTDOWN_EVENT:
3569 windgoto((int)Rows - 1, 0);
3570 g_fForceExit = TRUE;
3571
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003572 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003573 (dwCtrlType == CTRL_CLOSE_EVENT
3574 ? _("close")
3575 : dwCtrlType == CTRL_LOGOFF_EVENT
3576 ? _("logoff")
3577 : _("shutdown")));
3578#ifdef DEBUG
3579 OutputDebugString(IObuff);
3580#endif
3581
3582 preserve_exit(); /* output IObuff, preserve files and exit */
3583
3584 return TRUE; /* not reached */
3585
3586 default:
3587 return FALSE;
3588 }
3589}
3590
3591
3592/*
3593 * set the tty in (raw) ? "raw" : "cooked" mode
3594 */
3595 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003596mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003597{
3598 DWORD cmodein;
3599 DWORD cmodeout;
3600 BOOL bEnableHandler;
3601
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003602# ifdef VIMDLL
3603 if (gui.in_use)
3604 return;
3605# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 GetConsoleMode(g_hConIn, &cmodein);
3607 GetConsoleMode(g_hConOut, &cmodeout);
3608 if (tmode == TMODE_RAW)
3609 {
3610 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3611 ENABLE_ECHO_INPUT);
3612#ifdef FEAT_MOUSE
3613 if (g_fMouseActive)
3614 cmodein |= ENABLE_MOUSE_INPUT;
3615#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003616 cmodeout &= ~(
3617#ifdef FEAT_TERMGUICOLORS
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003618 /* Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003619 * VTP. */
3620 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3621#else
3622 ENABLE_PROCESSED_OUTPUT |
3623#endif
3624 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 bEnableHandler = TRUE;
3626 }
3627 else /* cooked */
3628 {
3629 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3630 ENABLE_ECHO_INPUT);
3631 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3632 bEnableHandler = FALSE;
3633 }
3634 SetConsoleMode(g_hConIn, cmodein);
3635 SetConsoleMode(g_hConOut, cmodeout);
3636 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3637
3638#ifdef MCH_WRITE_DUMP
3639 if (fdDump)
3640 {
3641 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3642 tmode == TMODE_RAW ? "raw" :
3643 tmode == TMODE_COOK ? "cooked" : "normal",
3644 cmodein, cmodeout);
3645 fflush(fdDump);
3646 }
3647#endif
3648}
3649
3650
3651/*
3652 * Get the size of the current window in `Rows' and `Columns'
3653 * Return OK when size could be determined, FAIL otherwise.
3654 */
3655 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003656mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003657{
3658 CONSOLE_SCREEN_BUFFER_INFO csbi;
3659
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003660# ifdef VIMDLL
3661 if (gui.in_use)
3662 return OK;
3663# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3665 {
3666 /*
3667 * For some reason, we are trying to get the screen dimensions
3668 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3669 * variables are really intended to mean the size of Vim screen
3670 * while in termcap mode.
3671 */
3672 Rows = g_cbTermcap.Info.dwSize.Y;
3673 Columns = g_cbTermcap.Info.dwSize.X;
3674 }
3675 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3676 {
3677 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3678 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3679 }
3680 else
3681 {
3682 Rows = 25;
3683 Columns = 80;
3684 }
3685 return OK;
3686}
3687
3688/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003689 * Resize console buffer to 'COORD'
3690 */
3691 static void
3692ResizeConBuf(
3693 HANDLE hConsole,
3694 COORD coordScreen)
3695{
3696 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3697 {
3698#ifdef MCH_WRITE_DUMP
3699 if (fdDump)
3700 {
3701 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3702 GetLastError());
3703 fflush(fdDump);
3704 }
3705#endif
3706 }
3707}
3708
3709/*
3710 * Resize console window size to 'srWindowRect'
3711 */
3712 static void
3713ResizeWindow(
3714 HANDLE hConsole,
3715 SMALL_RECT srWindowRect)
3716{
3717 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3718 {
3719#ifdef MCH_WRITE_DUMP
3720 if (fdDump)
3721 {
3722 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3723 GetLastError());
3724 fflush(fdDump);
3725 }
3726#endif
3727 }
3728}
3729
3730/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003731 * Set a console window to `xSize' * `ySize'
3732 */
3733 static void
3734ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003735 HANDLE hConsole,
3736 int xSize,
3737 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003738{
3739 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3740 SMALL_RECT srWindowRect; /* hold the new console size */
3741 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02003742 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743
3744#ifdef MCH_WRITE_DUMP
3745 if (fdDump)
3746 {
3747 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3748 fflush(fdDump);
3749 }
3750#endif
3751
3752 /* get the largest size we can size the console window to */
3753 coordScreen = GetLargestConsoleWindowSize(hConsole);
3754
3755 /* define the new console window size and scroll position */
3756 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3757 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3758 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3759
3760 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3761 {
3762 int sx, sy;
3763
3764 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3765 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3766 if (sy < ySize || sx < xSize)
3767 {
3768 /*
3769 * Increasing number of lines/columns, do buffer first.
3770 * Use the maximal size in x and y direction.
3771 */
3772 if (sy < ySize)
3773 coordScreen.Y = ySize;
3774 else
3775 coordScreen.Y = sy;
3776 if (sx < xSize)
3777 coordScreen.X = xSize;
3778 else
3779 coordScreen.X = sx;
3780 SetConsoleScreenBufferSize(hConsole, coordScreen);
3781 }
3782 }
3783
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003784 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 coordScreen.X = xSize;
3786 coordScreen.Y = ySize;
3787
Bram Moolenaar2551c032018-08-23 22:38:31 +02003788 // In the new console call API, only the first time in reverse order
3789 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003791 ResizeWindow(hConsole, srWindowRect);
3792 ResizeConBuf(hConsole, coordScreen);
3793 }
3794 else
3795 {
3796 ResizeConBuf(hConsole, coordScreen);
3797 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02003798 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799 }
3800}
3801
3802
3803/*
3804 * Set the console window to `Rows' * `Columns'
3805 */
3806 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003807mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808{
3809 COORD coordScreen;
3810
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003811# ifdef VIMDLL
3812 if (gui.in_use)
3813 return;
3814# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003815 /* Don't change window size while still starting up */
3816 if (suppress_winsize != 0)
3817 {
3818 suppress_winsize = 2;
3819 return;
3820 }
3821
3822 if (term_console)
3823 {
3824 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3825
3826 /* Clamp Rows and Columns to reasonable values */
3827 if (Rows > coordScreen.Y)
3828 Rows = coordScreen.Y;
3829 if (Columns > coordScreen.X)
3830 Columns = coordScreen.X;
3831
3832 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3833 }
3834}
3835
3836/*
3837 * Rows and/or Columns has changed.
3838 */
3839 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003840mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003841{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02003842# ifdef VIMDLL
3843 if (gui.in_use)
3844 return;
3845# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003846 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3847}
3848
3849
3850/*
3851 * Called when started up, to set the winsize that was delayed.
3852 */
3853 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003854mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855{
3856 if (suppress_winsize == 2)
3857 {
3858 suppress_winsize = 0;
3859 mch_set_shellsize();
3860 shell_resized();
3861 }
3862 suppress_winsize = 0;
3863}
Bram Moolenaar4f974752019-02-17 17:44:42 +01003864#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003866 static BOOL
3867vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003868 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003869 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003870 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003871 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003872 PROCESS_INFORMATION *pi,
3873 LPVOID *env,
3874 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003875{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003876 BOOL ret = FALSE;
3877 WCHAR *wcmd, *wcwd = NULL;
3878
3879 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3880 if (wcmd == NULL)
3881 return FALSE;
3882 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003883 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003884 wcwd = enc_to_utf16((char_u *)cwd, NULL);
3885 if (wcwd == NULL)
3886 goto theend;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003887 }
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003888
3889 ret = CreateProcessW(
3890 NULL, // Executable name
3891 wcmd, // Command to execute
3892 NULL, // Process security attributes
3893 NULL, // Thread security attributes
3894 inherit_handles, // Inherit handles
3895 flags, // Creation flags
3896 env, // Environment
3897 wcwd, // Current directory
3898 (LPSTARTUPINFOW)si, // Startup information
3899 pi); // Process information
3900theend:
3901 vim_free(wcmd);
3902 vim_free(wcwd);
3903 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003904}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905
3906
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003907 static HINSTANCE
3908vim_shell_execute(
3909 char *cmd,
3910 INT n_show_cmd)
3911{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02003912 HINSTANCE ret;
3913 WCHAR *wcmd;
3914
3915 wcmd = enc_to_utf16((char_u *)cmd, NULL);
3916 if (wcmd == NULL)
3917 return (HINSTANCE) 0;
3918
3919 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
3920 vim_free(wcmd);
3921 return ret;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01003922}
3923
3924
Bram Moolenaar4f974752019-02-17 17:44:42 +01003925#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003926
3927/*
3928 * Specialised version of system() for Win32 GUI mode.
3929 * This version proceeds as follows:
3930 * 1. Create a console window for use by the subprocess
3931 * 2. Run the subprocess (it gets the allocated console by default)
3932 * 3. Wait for the subprocess to terminate and get its exit code
3933 * 4. Prompt the user to press a key to close the console window
3934 */
3935 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003936mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003937{
3938 STARTUPINFO si;
3939 PROCESS_INFORMATION pi;
3940 DWORD ret = 0;
3941 HWND hwnd = GetFocus();
3942
3943 si.cb = sizeof(si);
3944 si.lpReserved = NULL;
3945 si.lpDesktop = NULL;
3946 si.lpTitle = NULL;
3947 si.dwFlags = STARTF_USESHOWWINDOW;
3948 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003949 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003950 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003952 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003953 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003954 else
3955 si.wShowWindow = SW_SHOWNORMAL;
3956 si.cbReserved2 = 0;
3957 si.lpReserved2 = NULL;
3958
Bram Moolenaar071d4272004-06-13 20:20:40 +00003959 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003960 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02003961 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
3962 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003963
3964 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965 {
3966#ifdef FEAT_GUI
3967 int delay = 1;
3968
3969 /* Keep updating the window while waiting for the shell to finish. */
3970 for (;;)
3971 {
3972 MSG msg;
3973
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003974 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003975 {
3976 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003977 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003978 delay = 1;
3979 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980 }
3981 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3982 break;
3983
3984 /* We start waiting for a very short time and then increase it, so
3985 * that we respond quickly when the process is quick, and don't
3986 * consume too much overhead when it's slow. */
3987 if (delay < 50)
3988 delay += 10;
3989 }
3990#else
3991 WaitForSingleObject(pi.hProcess, INFINITE);
3992#endif
3993
3994 /* Get the command exit code */
3995 GetExitCodeProcess(pi.hProcess, &ret);
3996 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003997
3998 /* Close the handles to the subprocess, so that it goes away */
3999 CloseHandle(pi.hThread);
4000 CloseHandle(pi.hProcess);
4001
4002 /* Try to get input focus back. Doesn't always work though. */
4003 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4004
4005 return ret;
4006}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004007
4008/*
4009 * Thread launched by the gui to send the current buffer data to the
4010 * process. This way avoid to hang up vim totally if the children
4011 * process take a long time to process the lines.
4012 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004013 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004014sub_process_writer(LPVOID param)
4015{
4016 HANDLE g_hChildStd_IN_Wr = param;
4017 linenr_T lnum = curbuf->b_op_start.lnum;
4018 DWORD len = 0;
4019 DWORD l;
4020 char_u *lp = ml_get(lnum);
4021 char_u *s;
4022 int written = 0;
4023
4024 for (;;)
4025 {
4026 l = (DWORD)STRLEN(lp + written);
4027 if (l == 0)
4028 len = 0;
4029 else if (lp[written] == NL)
4030 {
4031 /* NL -> NUL translation */
4032 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4033 }
4034 else
4035 {
4036 s = vim_strchr(lp + written, NL);
4037 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4038 s == NULL ? l : (DWORD)(s - (lp + written)),
4039 &len, NULL);
4040 }
4041 if (len == (int)l)
4042 {
4043 /* Finished a line, add a NL, unless this line should not have
4044 * one. */
4045 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004046 || (!curbuf->b_p_bin
4047 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004048 || (lnum != curbuf->b_no_eol_lnum
4049 && (lnum != curbuf->b_ml.ml_line_count
4050 || curbuf->b_p_eol)))
4051 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004052 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4053 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004054 }
4055
4056 ++lnum;
4057 if (lnum > curbuf->b_op_end.lnum)
4058 break;
4059
4060 lp = ml_get(lnum);
4061 written = 0;
4062 }
4063 else if (len > 0)
4064 written += len;
4065 }
4066
4067 /* finished all the lines, close pipe */
4068 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004069 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004070}
4071
4072
4073# define BUFLEN 100 /* length for buffer, stolen from unix version */
4074
4075/*
4076 * This function read from the children's stdout and write the
4077 * data on screen or in the buffer accordingly.
4078 */
4079 static void
4080dump_pipe(int options,
4081 HANDLE g_hChildStd_OUT_Rd,
4082 garray_T *ga,
4083 char_u buffer[],
4084 DWORD *buffer_off)
4085{
4086 DWORD availableBytes = 0;
4087 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004088 int ret;
4089 DWORD len;
4090 DWORD toRead;
4091 int repeatCount;
4092
4093 /* we query the pipe to see if there is any data to read
4094 * to avoid to perform a blocking read */
4095 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4096 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004097 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004098 NULL, /* number of read bytes */
4099 &availableBytes, /* available bytes total */
4100 NULL); /* byteLeft */
4101
4102 repeatCount = 0;
4103 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004104 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004105 {
4106 repeatCount++;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004107 toRead = (DWORD)(BUFLEN - *buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004108 toRead = availableBytes < toRead ? availableBytes : toRead;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004109 ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004110
4111 /* If we haven't read anything, there is a problem */
4112 if (len == 0)
4113 break;
4114
4115 availableBytes -= len;
4116
4117 if (options & SHELL_READ)
4118 {
4119 /* Do NUL -> NL translation, append NL separated
4120 * lines to the current buffer. */
4121 for (i = 0; i < len; ++i)
4122 {
4123 if (buffer[i] == NL)
4124 append_ga_line(ga);
4125 else if (buffer[i] == NUL)
4126 ga_append(ga, NL);
4127 else
4128 ga_append(ga, buffer[i]);
4129 }
4130 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004131 else if (has_mbyte)
4132 {
4133 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004134 int c;
4135 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004136
4137 len += *buffer_off;
4138 buffer[len] = NUL;
4139
4140 /* Check if the last character in buffer[] is
4141 * incomplete, keep these bytes for the next
4142 * round. */
4143 for (p = buffer; p < buffer + len; p += l)
4144 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004145 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004146 if (l == 0)
4147 l = 1; /* NUL byte? */
4148 else if (MB_BYTE2LEN(*p) != l)
4149 break;
4150 }
4151 if (p == buffer) /* no complete character */
4152 {
4153 /* avoid getting stuck at an illegal byte */
4154 if (len >= 12)
4155 ++p;
4156 else
4157 {
4158 *buffer_off = len;
4159 return;
4160 }
4161 }
4162 c = *p;
4163 *p = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004164 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004165 if (p < buffer + len)
4166 {
4167 *p = c;
4168 *buffer_off = (DWORD)((buffer + len) - p);
4169 mch_memmove(buffer, p, *buffer_off);
4170 return;
4171 }
4172 *buffer_off = 0;
4173 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004174 else
4175 {
4176 buffer[len] = NUL;
Bram Moolenaar32526b32019-01-19 17:43:09 +01004177 msg_puts((char *)buffer);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004178 }
4179
4180 windgoto(msg_row, msg_col);
4181 cursor_on();
4182 out_flush();
4183 }
4184}
4185
4186/*
4187 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4188 * for communication and doesn't open any new window.
4189 */
4190 static int
4191mch_system_piped(char *cmd, int options)
4192{
4193 STARTUPINFO si;
4194 PROCESS_INFORMATION pi;
4195 DWORD ret = 0;
4196
4197 HANDLE g_hChildStd_IN_Rd = NULL;
4198 HANDLE g_hChildStd_IN_Wr = NULL;
4199 HANDLE g_hChildStd_OUT_Rd = NULL;
4200 HANDLE g_hChildStd_OUT_Wr = NULL;
4201
4202 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4203 DWORD len;
4204
4205 /* buffer used to receive keys */
4206 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4207 int ta_len = 0; /* valid bytes in ta_buf[] */
4208
4209 DWORD i;
4210 int c;
4211 int noread_cnt = 0;
4212 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004213 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004214 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004215 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004216
4217 SECURITY_ATTRIBUTES saAttr;
4218
4219 /* Set the bInheritHandle flag so pipe handles are inherited. */
4220 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4221 saAttr.bInheritHandle = TRUE;
4222 saAttr.lpSecurityDescriptor = NULL;
4223
4224 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4225 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004226 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004227 /* Create a pipe for the child process's STDIN. */
4228 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4229 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004230 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004231 {
4232 CloseHandle(g_hChildStd_IN_Rd);
4233 CloseHandle(g_hChildStd_IN_Wr);
4234 CloseHandle(g_hChildStd_OUT_Rd);
4235 CloseHandle(g_hChildStd_OUT_Wr);
Bram Moolenaar32526b32019-01-19 17:43:09 +01004236 msg_puts(_("\nCannot create pipes\n"));
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004237 }
4238
4239 si.cb = sizeof(si);
4240 si.lpReserved = NULL;
4241 si.lpDesktop = NULL;
4242 si.lpTitle = NULL;
4243 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4244
4245 /* set-up our file redirection */
4246 si.hStdError = g_hChildStd_OUT_Wr;
4247 si.hStdOutput = g_hChildStd_OUT_Wr;
4248 si.hStdInput = g_hChildStd_IN_Rd;
4249 si.wShowWindow = SW_HIDE;
4250 si.cbReserved2 = 0;
4251 si.lpReserved2 = NULL;
4252
4253 if (options & SHELL_READ)
4254 ga_init2(&ga, 1, BUFLEN);
4255
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004256 if (cmd != NULL)
4257 {
4258 p = (char *)vim_strsave((char_u *)cmd);
4259 if (p != NULL)
4260 unescape_shellxquote((char_u *)p, p_sxe);
4261 else
4262 p = cmd;
4263 }
4264
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004265 /* Now, run the command.
4266 * About "Inherit handles" being TRUE: this command can be litigious,
4267 * handle inheritance was deactivated for pending temp file, but, if we
4268 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004269 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4270 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004271
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004272 if (p != cmd)
4273 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004274
4275 /* Close our unused side of the pipes */
4276 CloseHandle(g_hChildStd_IN_Rd);
4277 CloseHandle(g_hChildStd_OUT_Wr);
4278
4279 if (options & SHELL_WRITE)
4280 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004281 HANDLE thread = (HANDLE)
4282 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004283 0, /* default stack size */
4284 sub_process_writer, /* function to be executed */
4285 g_hChildStd_IN_Wr, /* parameter */
4286 0, /* creation flag, start immediately */
4287 NULL); /* we don't care about thread id */
4288 CloseHandle(thread);
4289 g_hChildStd_IN_Wr = NULL;
4290 }
4291
4292 /* Keep updating the window while waiting for the shell to finish. */
4293 for (;;)
4294 {
4295 MSG msg;
4296
Bram Moolenaar175d0702013-12-11 18:36:33 +01004297 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004298 {
4299 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004300 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004301 }
4302
4303 /* write pipe information in the window */
4304 if ((options & (SHELL_READ|SHELL_WRITE))
4305# ifdef FEAT_GUI
4306 || gui.in_use
4307# endif
4308 )
4309 {
4310 len = 0;
4311 if (!(options & SHELL_EXPAND)
4312 && ((options &
4313 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4314 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4315# ifdef FEAT_GUI
4316 || gui.in_use
4317# endif
4318 )
4319 && (ta_len > 0 || noread_cnt > 4))
4320 {
4321 if (ta_len == 0)
4322 {
4323 /* Get extra characters when we don't have any. Reset the
4324 * counter and timer. */
4325 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004326 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4327 }
4328 if (ta_len > 0 || len > 0)
4329 {
4330 /*
4331 * For pipes: Check for CTRL-C: send interrupt signal to
4332 * child. Check for CTRL-D: EOF, close pipe to child.
4333 */
4334 if (len == 1 && cmd != NULL)
4335 {
4336 if (ta_buf[ta_len] == Ctrl_C)
4337 {
4338 /* Learn what exit code is expected, for
4339 * now put 9 as SIGKILL */
4340 TerminateProcess(pi.hProcess, 9);
4341 }
4342 if (ta_buf[ta_len] == Ctrl_D)
4343 {
4344 CloseHandle(g_hChildStd_IN_Wr);
4345 g_hChildStd_IN_Wr = NULL;
4346 }
4347 }
4348
4349 /* replace K_BS by <BS> and K_DEL by <DEL> */
4350 for (i = ta_len; i < ta_len + len; ++i)
4351 {
4352 if (ta_buf[i] == CSI && len - i > 2)
4353 {
4354 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4355 if (c == K_DEL || c == K_KDEL || c == K_BS)
4356 {
4357 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4358 (size_t)(len - i - 2));
4359 if (c == K_DEL || c == K_KDEL)
4360 ta_buf[i] = DEL;
4361 else
4362 ta_buf[i] = Ctrl_H;
4363 len -= 2;
4364 }
4365 }
4366 else if (ta_buf[i] == '\r')
4367 ta_buf[i] = '\n';
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004368 if (has_mbyte)
4369 i += (*mb_ptr2len_len)(ta_buf + i,
4370 ta_len + len - i) - 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004371 }
4372
4373 /*
4374 * For pipes: echo the typed characters. For a pty this
4375 * does not seem to work.
4376 */
4377 for (i = ta_len; i < ta_len + len; ++i)
4378 {
4379 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4380 msg_putchar(ta_buf[i]);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004381 else if (has_mbyte)
4382 {
4383 int l = (*mb_ptr2len)(ta_buf + i);
4384
4385 msg_outtrans_len(ta_buf + i, l);
4386 i += l - 1;
4387 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004388 else
4389 msg_outtrans_len(ta_buf + i, 1);
4390 }
4391 windgoto(msg_row, msg_col);
4392 out_flush();
4393
4394 ta_len += len;
4395
4396 /*
4397 * Write the characters to the child, unless EOF has been
4398 * typed for pipes. Write one character at a time, to
4399 * avoid losing too much typeahead. When writing buffer
4400 * lines, drop the typed characters (only check for
4401 * CTRL-C).
4402 */
4403 if (options & SHELL_WRITE)
4404 ta_len = 0;
4405 else if (g_hChildStd_IN_Wr != NULL)
4406 {
4407 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4408 1, &len, NULL);
4409 // if we are typing in, we want to keep things reactive
4410 delay = 1;
4411 if (len > 0)
4412 {
4413 ta_len -= len;
4414 mch_memmove(ta_buf, ta_buf + len, ta_len);
4415 }
4416 }
4417 }
4418 }
4419 }
4420
4421 if (ta_len)
4422 ui_inchar_undo(ta_buf, ta_len);
4423
4424 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4425 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004426 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004427 break;
4428 }
4429
4430 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004431 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004432
4433 /* We start waiting for a very short time and then increase it, so
4434 * that we respond quickly when the process is quick, and don't
4435 * consume too much overhead when it's slow. */
4436 if (delay < 50)
4437 delay += 10;
4438 }
4439
4440 /* Close the pipe */
4441 CloseHandle(g_hChildStd_OUT_Rd);
4442 if (g_hChildStd_IN_Wr != NULL)
4443 CloseHandle(g_hChildStd_IN_Wr);
4444
4445 WaitForSingleObject(pi.hProcess, INFINITE);
4446
4447 /* Get the command exit code */
4448 GetExitCodeProcess(pi.hProcess, &ret);
4449
4450 if (options & SHELL_READ)
4451 {
4452 if (ga.ga_len > 0)
4453 {
4454 append_ga_line(&ga);
4455 /* remember that the NL was missing */
4456 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4457 }
4458 else
4459 curbuf->b_no_eol_lnum = 0;
4460 ga_clear(&ga);
4461 }
4462
4463 /* Close the handles to the subprocess, so that it goes away */
4464 CloseHandle(pi.hThread);
4465 CloseHandle(pi.hProcess);
4466
4467 return ret;
4468}
4469
4470 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004471mch_system_g(char *cmd, int options)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004472{
4473 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004474 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004475 return mch_system_piped(cmd, options);
4476 else
4477 return mch_system_classic(cmd, options);
4478}
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004479#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004481#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004482 static int
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004483mch_system_c(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004484{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004485 int ret;
4486 WCHAR *wcmd;
4487
4488 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4489 if (wcmd == NULL)
4490 return -1;
4491
4492 ret = _wsystem(wcmd);
4493 vim_free(wcmd);
4494 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004495}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004496
4497#endif
4498
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004499 static int
4500mch_system(char *cmd, int options)
4501{
4502#ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004503 if (gui.in_use || gui.starting)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004504 return mch_system_g(cmd, options);
4505 else
4506 return mch_system_c(cmd, options);
4507#elif defined(FEAT_GUI_MSWIN)
4508 return mch_system_g(cmd, options);
4509#else
4510 return mch_system_c(cmd, options);
4511#endif
4512}
4513
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004514#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4515/*
4516 * Use a terminal window to run a shell command in.
4517 */
4518 static int
4519mch_call_shell_terminal(
4520 char_u *cmd,
4521 int options UNUSED) /* SHELL_*, see vim.h */
4522{
4523 jobopt_T opt;
4524 char_u *newcmd = NULL;
4525 typval_T argvar[2];
4526 long_u cmdlen;
4527 int retval = -1;
4528 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004529 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004530 aco_save_T aco;
4531 oparg_T oa; /* operator arguments */
4532
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004533 if (cmd == NULL)
4534 cmdlen = STRLEN(p_sh) + 1;
4535 else
4536 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004537 newcmd = lalloc(cmdlen, TRUE);
4538 if (newcmd == NULL)
4539 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004540 if (cmd == NULL)
4541 {
4542 STRCPY(newcmd, p_sh);
4543 ch_log(NULL, "starting terminal to run a shell");
4544 }
4545 else
4546 {
4547 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4548 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4549 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004550
4551 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004552
4553 argvar[0].v_type = VAR_STRING;
4554 argvar[0].vval.v_string = newcmd;
4555 argvar[1].v_type = VAR_UNKNOWN;
4556 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004557 if (buf == NULL)
Bram Moolenaar9029b912019-03-21 19:58:00 +01004558 {
4559 vim_free(newcmd);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004560 return 255;
Bram Moolenaar9029b912019-03-21 19:58:00 +01004561 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004562
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004563 job = term_getjob(buf->b_term);
4564 ++job->jv_refcount;
4565
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004566 /* Find a window to make "buf" curbuf. */
4567 aucmd_prepbuf(&aco, buf);
4568
4569 clear_oparg(&oa);
4570 while (term_use_loop())
4571 {
4572 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4573 {
4574 /* If terminal_loop() returns OK we got a key that is handled
4575 * in Normal model. We don't do redrawing anyway. */
4576 if (terminal_loop(TRUE) == OK)
4577 normal_cmd(&oa, TRUE);
4578 }
4579 else
4580 normal_cmd(&oa, TRUE);
4581 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004582 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004583 ch_log(NULL, "system command finished");
4584
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004585 job_unref(job);
4586
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004587 /* restore curwin/curbuf and a few other things */
4588 aucmd_restbuf(&aco);
4589
4590 wait_return(TRUE);
4591 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4592
4593 vim_free(newcmd);
4594 return retval;
4595}
4596#endif
4597
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598/*
4599 * Either execute a command by calling the shell or start a new shell
4600 */
4601 int
4602mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004603 char_u *cmd,
4604 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004605{
4606 int x = 0;
4607 int tmode = cur_tmode;
4608#ifdef FEAT_TITLE
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004609 WCHAR szShellTitle[512];
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004610
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004611 /* Change the title to reflect that we are in a subshell. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004612 if (GetConsoleTitleW(szShellTitle,
4613 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004614 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004615 if (cmd == NULL)
4616 wcscat(szShellTitle, L" :sh");
4617 else
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004618 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004619 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004620
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004621 if (wn != NULL)
4622 {
4623 wcscat(szShellTitle, L" - !");
4624 if ((wcslen(szShellTitle) + wcslen(wn) <
4625 sizeof(szShellTitle)/sizeof(WCHAR)))
4626 wcscat(szShellTitle, wn);
4627 SetConsoleTitleW(szShellTitle);
4628 vim_free(wn);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004629 }
4630 }
4631 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004632#endif
4633
4634 out_flush();
4635
4636#ifdef MCH_WRITE_DUMP
4637 if (fdDump)
4638 {
4639 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4640 fflush(fdDump);
4641 }
4642#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004643#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4644 /* TODO: make the terminal window work with input or output redirected. */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004645 if (
4646# ifdef VIMDLL
4647 gui.in_use &&
4648# endif
4649 vim_strchr(p_go, GO_TERMINAL) != NULL
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004650 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4651 {
4652 /* Use a terminal window to run the command in. */
4653 x = mch_call_shell_terminal(cmd, options);
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004654# ifdef FEAT_TITLE
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004655 resettitle();
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01004656# endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004657 return x;
4658 }
4659#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004660
4661 /*
4662 * Catch all deadly signals while running the external command, because a
4663 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4664 */
4665 signal(SIGINT, SIG_IGN);
4666#if defined(__GNUC__) && !defined(__MINGW32__)
4667 signal(SIGKILL, SIG_IGN);
4668#else
4669 signal(SIGBREAK, SIG_IGN);
4670#endif
4671 signal(SIGILL, SIG_IGN);
4672 signal(SIGFPE, SIG_IGN);
4673 signal(SIGSEGV, SIG_IGN);
4674 signal(SIGTERM, SIG_IGN);
4675 signal(SIGABRT, SIG_IGN);
4676
4677 if (options & SHELL_COOKED)
4678 settmode(TMODE_COOK); /* set to normal mode */
4679
4680 if (cmd == NULL)
4681 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004682 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004683 }
4684 else
4685 {
4686 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004687 char_u *newcmd = NULL;
4688 char_u *cmdbase = cmd;
4689 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004690
4691 /* Skip a leading ", ( and "(. */
4692 if (*cmdbase == '"' )
4693 ++cmdbase;
4694 if (*cmdbase == '(')
4695 ++cmdbase;
4696
Bram Moolenaar1c465442017-03-12 20:10:05 +01004697 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004698 {
4699 STARTUPINFO si;
4700 PROCESS_INFORMATION pi;
4701 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004702 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004703 char_u *p;
4704
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004705 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004706 si.cb = sizeof(si);
4707 si.lpReserved = NULL;
4708 si.lpDesktop = NULL;
4709 si.lpTitle = NULL;
4710 si.dwFlags = 0;
4711 si.cbReserved2 = 0;
4712 si.lpReserved2 = NULL;
4713
4714 cmdbase = skipwhite(cmdbase + 5);
4715 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004716 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004717 {
4718 cmdbase = skipwhite(cmdbase + 4);
4719 si.dwFlags = STARTF_USESHOWWINDOW;
4720 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004721 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004722 }
4723 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004724 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004725 {
4726 cmdbase = skipwhite(cmdbase + 2);
4727 flags = CREATE_NO_WINDOW;
4728 si.dwFlags = STARTF_USESTDHANDLES;
4729 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004730 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004731 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004732 NULL, // Security att.
4733 OPEN_EXISTING, // Open flags
4734 FILE_ATTRIBUTE_NORMAL, // File att.
4735 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004736 si.hStdOutput = si.hStdInput;
4737 si.hStdError = si.hStdInput;
4738 }
4739
4740 /* Remove a trailing ", ) and )" if they have a match
4741 * at the start of the command. */
4742 if (cmdbase > cmd)
4743 {
4744 p = cmdbase + STRLEN(cmdbase);
4745 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4746 *--p = NUL;
4747 if (p > cmdbase && p[-1] == ')'
4748 && (*cmd =='(' || cmd[1] == '('))
4749 *--p = NUL;
4750 }
4751
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004752 newcmd = cmdbase;
4753 unescape_shellxquote(cmdbase, p_sxe);
4754
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004755 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004756 * If creating new console, arguments are passed to the
4757 * 'cmd.exe' as-is. If it's not, arguments are not treated
4758 * correctly for current 'cmd.exe'. So unescape characters in
4759 * shellxescape except '|' for avoiding to be treated as
4760 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004761 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004762 if (flags != CREATE_NEW_CONSOLE)
4763 {
4764 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004765 char_u *cmd_shell = mch_getenv("COMSPEC");
4766
4767 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004768 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004769
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004770 subcmd = vim_strsave_escaped_ext(cmdbase,
4771 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004772 if (subcmd != NULL)
4773 {
4774 /* make "cmd.exe /c arguments" */
4775 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004776 newcmd = lalloc(cmdlen, TRUE);
4777 if (newcmd != NULL)
4778 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004779 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004780 else
4781 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004782 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004783 }
4784 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004785
4786 /*
4787 * Now, start the command as a process, so that it doesn't
4788 * inherit our handles which causes unpleasant dangling swap
4789 * files if we exit before the spawned process
4790 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004791 if (vim_create_process((char *)newcmd, FALSE, flags,
4792 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004793 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004794 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4795 > (HINSTANCE)32)
4796 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004797 else
4798 {
4799 x = -1;
Bram Moolenaar4f974752019-02-17 17:44:42 +01004800#ifdef FEAT_GUI_MSWIN
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004801# ifdef VIMDLL
4802 if (gui.in_use)
4803# endif
4804 emsg(_("E371: Command not found"));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004805#endif
4806 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004807
4808 if (newcmd != cmdbase)
4809 vim_free(newcmd);
4810
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004811 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004812 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004813 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004814 CloseHandle(si.hStdInput);
4815 }
4816 /* Close the handles to the subprocess, so that it goes away */
4817 CloseHandle(pi.hThread);
4818 CloseHandle(pi.hProcess);
4819 }
4820 else
4821 {
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004822 cmdlen =
Bram Moolenaar4f974752019-02-17 17:44:42 +01004823#ifdef FEAT_GUI_MSWIN
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004824 ((gui.in_use || gui.starting) ?
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004825 (!s_dont_use_vimrun && p_stmp ?
4826 STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4827 : 0) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004828#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004829 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004830
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004831 newcmd = lalloc(cmdlen, TRUE);
4832 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004833 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01004834#if defined(FEAT_GUI_MSWIN)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004835 if (
4836# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004837 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004838# endif
4839 need_vimrun_warning)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004840 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004841 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4842 "External commands will not pause after completion.\n"
4843 "See :help win32-vimrun for more information.");
4844 char *title = _("Vim Warning");
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004845 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4846 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
Bram Moolenaar63e43442016-11-19 17:28:44 +01004847
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004848 if (wmsg != NULL && wtitle != NULL)
4849 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4850 vim_free(wmsg);
4851 vim_free(wtitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852 need_vimrun_warning = FALSE;
4853 }
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004854 if (
4855# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004856 (gui.in_use || gui.starting) &&
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004857# endif
4858 !s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004859 /* Use vimrun to execute the command. It opens a console
4860 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004861 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862 vimrun_path,
4863 (msg_silent != 0 || (options & SHELL_DOOUT))
4864 ? "-s " : "",
4865 p_sh, p_shcf, cmd);
4866 else
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004867# ifdef VIMDLL
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004868 if (gui.in_use || gui.starting)
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004869# endif
4870 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
4871 p_sh, p_shcf, p_sh, p_shcf, cmd);
4872# ifdef VIMDLL
4873 else
4874# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004875#endif
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004876#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004877 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004878 p_sh, p_shcf, cmd);
Bram Moolenaar98ffe4c2019-05-07 23:01:39 +02004879#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004880 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004881 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004882 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004883 }
4884 }
4885
4886 if (tmode == TMODE_RAW)
4887 settmode(TMODE_RAW); /* set to raw mode */
4888
4889 /* Print the return value, unless "vimrun" was used. */
4890 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
Bram Moolenaar4f974752019-02-17 17:44:42 +01004891#if defined(FEAT_GUI_MSWIN)
Bram Moolenaar294d9bf2019-05-23 20:12:46 +02004892 && ((gui.in_use || gui.starting) ?
Bram Moolenaarafde13b2019-04-28 19:46:49 +02004893 ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894#endif
4895 )
4896 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004897 smsg(_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898 msg_putchar('\n');
4899 }
4900#ifdef FEAT_TITLE
4901 resettitle();
4902#endif
4903
4904 signal(SIGINT, SIG_DFL);
4905#if defined(__GNUC__) && !defined(__MINGW32__)
4906 signal(SIGKILL, SIG_DFL);
4907#else
4908 signal(SIGBREAK, SIG_DFL);
4909#endif
4910 signal(SIGILL, SIG_DFL);
4911 signal(SIGFPE, SIG_DFL);
4912 signal(SIGSEGV, SIG_DFL);
4913 signal(SIGTERM, SIG_DFL);
4914 signal(SIGABRT, SIG_DFL);
4915
4916 return x;
4917}
4918
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004919#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004920 static HANDLE
4921job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01004922 char_u *fname,
4923 DWORD dwDesiredAccess,
4924 DWORD dwShareMode,
4925 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4926 DWORD dwCreationDisposition,
4927 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004928{
4929 HANDLE h;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004930 WCHAR *wn;
Bram Moolenaara12a1612019-01-24 16:39:02 +01004931
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004932 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004933 if (wn == NULL)
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02004934 return INVALID_HANDLE_VALUE;
4935
4936 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4937 lpSecurityAttributes, dwCreationDisposition,
4938 dwFlagsAndAttributes, NULL);
4939 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004940 return h;
4941}
4942
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004943/*
4944 * Turn the dictionary "env" into a NUL separated list that can be used as the
4945 * environment argument of vim_create_process().
4946 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01004947 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004948win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004949{
4950 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004951 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004952 LPVOID base = GetEnvironmentStringsW();
4953
4954 /* for last \0 */
4955 if (ga_grow(gap, 1) == FAIL)
4956 return;
4957
4958 if (base)
4959 {
4960 WCHAR *p = (WCHAR*) base;
4961
4962 /* for last \0 */
4963 if (ga_grow(gap, 1) == FAIL)
4964 return;
4965
4966 while (*p != 0 || *(p + 1) != 0)
4967 {
4968 if (ga_grow(gap, 1) == OK)
4969 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
4970 p++;
4971 }
4972 FreeEnvironmentStrings(base);
4973 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
4974 }
4975
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004976 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004977 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004978 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004979 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004980 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004981 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004982 typval_T *item = &dict_lookup(hi)->di_tv;
4983 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
Bram Moolenaard155d7a2018-12-21 16:04:21 +01004984 WCHAR *wval = enc_to_utf16(tv_get_string(item), NULL);
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004985 --todo;
4986 if (wkey != NULL && wval != NULL)
4987 {
4988 size_t n;
4989 size_t lkey = wcslen(wkey);
4990 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02004991
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01004992 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
4993 continue;
4994 for (n = 0; n < lkey; n++)
4995 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
4996 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
4997 for (n = 0; n < lval; n++)
4998 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
4999 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5000 }
Bram Moolenaarbdace832019-03-02 10:13:42 +01005001 vim_free(wkey);
5002 vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005003 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005004 }
5005 }
5006
Bram Moolenaar493359e2018-06-12 20:25:52 +02005007# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005008 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005009# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005010 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005011 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005012# endif
5013# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005014 char_u *version = get_vim_var_str(VV_VERSION);
5015 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005016# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005017 // size of "VIM_SERVERNAME=" and value,
5018 // plus "VIM_TERMINAL=" and value,
5019 // plus two terminating NULs
5020 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005021# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005022 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005023# endif
5024# ifdef FEAT_TERMINAL
5025 + 13 + version_len + 2
5026# endif
5027 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005028
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005029 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005030 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005031# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005032 for (n = 0; n < 15; n++)
5033 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5034 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005035 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005036 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5037 (WCHAR)servername[n];
5038 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005039# endif
5040# ifdef FEAT_TERMINAL
5041 if (is_terminal)
5042 {
5043 for (n = 0; n < 13; n++)
5044 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5045 (WCHAR)"VIM_TERMINAL="[n];
5046 for (n = 0; n < version_len; n++)
5047 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5048 (WCHAR)version[n];
5049 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5050 }
5051# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005052 }
5053 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005054# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005055}
5056
Bram Moolenaarb091f302019-01-19 14:37:00 +01005057/*
5058 * Create a pair of pipes.
5059 * Return TRUE for success, FALSE for failure.
5060 */
5061 static BOOL
5062create_pipe_pair(HANDLE handles[2])
5063{
5064 static LONG s;
5065 char name[64];
5066 SECURITY_ATTRIBUTES sa;
5067
5068 sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5069 GetCurrentProcessId(),
5070 InterlockedIncrement(&s));
5071
5072 // Create named pipe. Max size of named pipe is 65535.
5073 handles[1] = CreateNamedPipe(
5074 name,
5075 PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5076 PIPE_TYPE_BYTE | PIPE_NOWAIT,
Bram Moolenaar24058382019-01-24 23:11:49 +01005077 1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005078
5079 if (handles[1] == INVALID_HANDLE_VALUE)
5080 return FALSE;
5081
5082 sa.nLength = sizeof(sa);
5083 sa.bInheritHandle = TRUE;
5084 sa.lpSecurityDescriptor = NULL;
5085
5086 handles[0] = CreateFile(name,
5087 FILE_GENERIC_READ,
5088 FILE_SHARE_READ, &sa,
5089 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5090
5091 if (handles[0] == INVALID_HANDLE_VALUE)
5092 {
Bram Moolenaar6982f422019-02-16 16:48:01 +01005093 CloseHandle(handles[1]);
Bram Moolenaarb091f302019-01-19 14:37:00 +01005094 return FALSE;
5095 }
5096
5097 return TRUE;
5098}
5099
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005100 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005101mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005102{
5103 STARTUPINFO si;
5104 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005105 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005106 SECURITY_ATTRIBUTES saAttr;
5107 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005108 HANDLE ifd[2];
5109 HANDLE ofd[2];
5110 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005111 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005112
5113 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5114 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5115 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5116 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5117 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5118 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5119 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5120
5121 if (use_out_for_err && use_null_for_out)
5122 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005123
5124 ifd[0] = INVALID_HANDLE_VALUE;
5125 ifd[1] = INVALID_HANDLE_VALUE;
5126 ofd[0] = INVALID_HANDLE_VALUE;
5127 ofd[1] = INVALID_HANDLE_VALUE;
5128 efd[0] = INVALID_HANDLE_VALUE;
5129 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005130 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005131
Bram Moolenaar14207f42016-10-27 21:13:10 +02005132 jo = CreateJobObject(NULL, NULL);
5133 if (jo == NULL)
5134 {
5135 job->jv_status = JOB_FAILED;
5136 goto failed;
5137 }
5138
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005139 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005140 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005141
Bram Moolenaar76467df2016-02-12 19:30:26 +01005142 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005143 ZeroMemory(&si, sizeof(si));
5144 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005145 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005146 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005147
Bram Moolenaard8070362016-02-15 21:56:54 +01005148 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5149 saAttr.bInheritHandle = TRUE;
5150 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005151
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005152 if (use_file_for_in)
5153 {
5154 char_u *fname = options->jo_io_name[PART_IN];
5155
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005156 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5157 FILE_SHARE_READ | FILE_SHARE_WRITE,
5158 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5159 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005160 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005161 semsg(_(e_notopen), fname);
Bram Moolenaar94d01912016-03-08 13:48:51 +01005162 goto failed;
5163 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005164 }
Bram Moolenaarb091f302019-01-19 14:37:00 +01005165 else if (!use_null_for_in
5166 && (!create_pipe_pair(ifd)
5167 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005168 goto failed;
5169
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005170 if (use_file_for_out)
5171 {
5172 char_u *fname = options->jo_io_name[PART_OUT];
5173
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005174 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5175 FILE_SHARE_READ | FILE_SHARE_WRITE,
5176 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5177 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005178 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005179 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005180 goto failed;
5181 }
5182 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005183 else if (!use_null_for_out &&
5184 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005185 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005186 goto failed;
5187
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005188 if (use_file_for_err)
5189 {
5190 char_u *fname = options->jo_io_name[PART_ERR];
5191
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005192 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5193 FILE_SHARE_READ | FILE_SHARE_WRITE,
5194 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5195 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005196 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005197 semsg(_(e_notopen), fname);
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005198 goto failed;
5199 }
5200 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005201 else if (!use_out_for_err && !use_null_for_err &&
5202 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005203 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005204 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005205
Bram Moolenaard8070362016-02-15 21:56:54 +01005206 si.dwFlags |= STARTF_USESTDHANDLES;
5207 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005208 si.hStdOutput = ofd[1];
5209 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5210
5211 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5212 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005213 if (options->jo_set & JO_CHANNEL)
5214 {
5215 channel = options->jo_channel;
5216 if (channel != NULL)
5217 ++channel->ch_refcount;
5218 }
5219 else
5220 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005221 if (channel == NULL)
5222 goto failed;
5223 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005224
5225 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005226 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005227 CREATE_DEFAULT_ERROR_MODE |
5228 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005229 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005230 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005231 &si, &pi,
5232 ga.ga_data,
5233 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005234 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005235 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005236 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005237 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005238 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005239
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005240 ga_clear(&ga);
5241
Bram Moolenaar14207f42016-10-27 21:13:10 +02005242 if (!AssignProcessToJobObject(jo, pi.hProcess))
5243 {
5244 /* if failing, switch the way to terminate
5245 * process with TerminateProcess. */
5246 CloseHandle(jo);
5247 jo = NULL;
5248 }
5249 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005250 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005251 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005252 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005253 job->jv_status = JOB_STARTED;
5254
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005255 CloseHandle(ifd[0]);
5256 CloseHandle(ofd[1]);
5257 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005258 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005259
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005260 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005261 if (channel != NULL)
5262 {
5263 channel_set_pipes(channel,
5264 use_file_for_in || use_null_for_in
5265 ? INVALID_FD : (sock_T)ifd[1],
5266 use_file_for_out || use_null_for_out
5267 ? INVALID_FD : (sock_T)ofd[0],
5268 use_out_for_err || use_file_for_err || use_null_for_err
5269 ? INVALID_FD : (sock_T)efd[0]);
5270 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005271 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005272 return;
5273
5274failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005275 CloseHandle(ifd[0]);
5276 CloseHandle(ofd[0]);
5277 CloseHandle(efd[0]);
5278 CloseHandle(ifd[1]);
5279 CloseHandle(ofd[1]);
5280 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005281 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005282 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005283}
5284
5285 char *
5286mch_job_status(job_T *job)
5287{
5288 DWORD dwExitCode = 0;
5289
Bram Moolenaar76467df2016-02-12 19:30:26 +01005290 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5291 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005292 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005293 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005294 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005295 {
5296 ch_log(job->jv_channel, "Job ended");
5297 job->jv_status = JOB_ENDED;
5298 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005299 return "dead";
5300 }
5301 return "run";
5302}
5303
Bram Moolenaar97792de2016-10-15 18:36:49 +02005304 job_T *
5305mch_detect_ended_job(job_T *job_list)
5306{
5307 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5308 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5309 job_T *job = job_list;
5310
5311 while (job != NULL)
5312 {
5313 DWORD n;
5314 DWORD result;
5315
5316 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5317 && job != NULL; job = job->jv_next)
5318 {
5319 if (job->jv_status == JOB_STARTED)
5320 {
5321 jobHandles[n] = job->jv_proc_info.hProcess;
5322 jobArray[n] = job;
5323 ++n;
5324 }
5325 }
5326 if (n == 0)
5327 continue;
5328 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5329 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5330 {
5331 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5332
5333 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5334 return wait_job;
5335 }
5336 }
5337 return NULL;
5338}
5339
Bram Moolenaarfb630902016-10-29 14:55:00 +02005340 static BOOL
5341terminate_all(HANDLE process, int code)
5342{
5343 PROCESSENTRY32 pe;
5344 HANDLE h = INVALID_HANDLE_VALUE;
5345 DWORD pid = GetProcessId(process);
5346
5347 if (pid != 0)
5348 {
5349 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5350 if (h != INVALID_HANDLE_VALUE)
5351 {
5352 pe.dwSize = sizeof(PROCESSENTRY32);
5353 if (!Process32First(h, &pe))
5354 goto theend;
5355
5356 do
5357 {
5358 if (pe.th32ParentProcessID == pid)
5359 {
5360 HANDLE ph = OpenProcess(
5361 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5362 if (ph != NULL)
5363 {
5364 terminate_all(ph, code);
5365 CloseHandle(ph);
5366 }
5367 }
5368 } while (Process32Next(h, &pe));
5369
5370 CloseHandle(h);
5371 }
5372 }
5373
5374theend:
5375 return TerminateProcess(process, code);
5376}
5377
5378/*
5379 * Send a (deadly) signal to "job".
5380 * Return FAIL if it didn't work.
5381 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005382 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005383mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005384{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005385 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005386
Bram Moolenaar923d9262016-02-25 20:56:01 +01005387 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005388 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005389 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005390 if (job->jv_job_object != NULL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005391 {
5392 if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5393 job->jv_channel->ch_killing = TRUE;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005394 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01005395 }
Bram Moolenaarfb630902016-10-29 14:55:00 +02005396 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005397 }
5398
5399 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5400 return FAIL;
5401 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005402 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5403 job->jv_proc_info.dwProcessId)
5404 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005405 FreeConsole();
5406 return ret;
5407}
5408
5409/*
5410 * Clear the data related to "job".
5411 */
5412 void
5413mch_clear_job(job_T *job)
5414{
5415 if (job->jv_status != JOB_FAILED)
5416 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005417 if (job->jv_job_object != NULL)
5418 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005419 CloseHandle(job->jv_proc_info.hProcess);
5420 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005421}
5422#endif
5423
Bram Moolenaar071d4272004-06-13 20:20:40 +00005424
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005425#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005426
5427/*
5428 * Start termcap mode
5429 */
5430 static void
5431termcap_mode_start(void)
5432{
5433 DWORD cmodein;
5434
5435 if (g_fTermcapMode)
5436 return;
5437
5438 SaveConsoleBuffer(&g_cbNonTermcap);
5439
5440 if (g_cbTermcap.IsValid)
5441 {
5442 /*
5443 * We've been in termcap mode before. Restore certain screen
5444 * characteristics, including the buffer size and the window
5445 * size. Since we will be redrawing the screen, we don't need
5446 * to restore the actual contents of the buffer.
5447 */
5448 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005449 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005450 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5451 Rows = g_cbTermcap.Info.dwSize.Y;
5452 Columns = g_cbTermcap.Info.dwSize.X;
5453 }
5454 else
5455 {
5456 /*
5457 * This is our first time entering termcap mode. Clear the console
5458 * screen buffer, and resize the buffer to match the current window
5459 * size. We will use this as the size of our editing environment.
5460 */
5461 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005462 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5464 }
5465
5466#ifdef FEAT_TITLE
5467 resettitle();
5468#endif
5469
5470 GetConsoleMode(g_hConIn, &cmodein);
5471#ifdef FEAT_MOUSE
5472 if (g_fMouseActive)
5473 cmodein |= ENABLE_MOUSE_INPUT;
5474 else
5475 cmodein &= ~ENABLE_MOUSE_INPUT;
5476#endif
5477 cmodein |= ENABLE_WINDOW_INPUT;
5478 SetConsoleMode(g_hConIn, cmodein);
5479
5480 redraw_later_clear();
5481 g_fTermcapMode = TRUE;
5482}
5483
5484
5485/*
5486 * End termcap mode
5487 */
5488 static void
5489termcap_mode_end(void)
5490{
5491 DWORD cmodein;
5492 ConsoleBuffer *cb;
5493 COORD coord;
5494 DWORD dwDummy;
5495
5496 if (!g_fTermcapMode)
5497 return;
5498
5499 SaveConsoleBuffer(&g_cbTermcap);
5500
5501 GetConsoleMode(g_hConIn, &cmodein);
5502 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5503 SetConsoleMode(g_hConIn, cmodein);
5504
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005505#ifdef FEAT_RESTORE_ORIG_SCREEN
5506 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5507#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005508 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005509#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005510 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005511 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512 SetConsoleCursorInfo(g_hConOut, &g_cci);
5513
5514 if (p_rs || exiting)
5515 {
5516 /*
5517 * Clear anything that happens to be on the current line.
5518 */
5519 coord.X = 0;
5520 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5521 FillConsoleOutputCharacter(g_hConOut, ' ',
5522 cb->Info.dwSize.X, coord, &dwDummy);
5523 /*
5524 * The following is just for aesthetics. If we are exiting without
5525 * restoring the screen, then we want to have a prompt string
5526 * appear at the bottom line. However, the command interpreter
5527 * seems to always advance the cursor one line before displaying
5528 * the prompt string, which causes the screen to scroll. To
5529 * counter this, move the cursor up one line before exiting.
5530 */
5531 if (exiting && !p_rs)
5532 coord.Y--;
5533 /*
5534 * Position the cursor at the leftmost column of the desired row.
5535 */
5536 SetConsoleCursorPosition(g_hConOut, coord);
5537 }
5538
5539 g_fTermcapMode = FALSE;
5540}
Bram Moolenaar4f974752019-02-17 17:44:42 +01005541#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542
5543
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005544#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005545 void
5546mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005547 char_u *s UNUSED,
5548 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549{
5550 /* never used */
5551}
5552
5553#else
5554
5555/*
5556 * clear `n' chars, starting from `coord'
5557 */
5558 static void
5559clear_chars(
5560 COORD coord,
5561 DWORD n)
5562{
5563 DWORD dwDummy;
5564
5565 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005566
5567 if (!USE_VTP)
5568 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5569 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005570 {
5571 set_console_color_rgb();
5572 gotoxy(coord.X + 1, coord.Y + 1);
5573 vtp_printf("\033[%dX", n);
5574 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575}
5576
5577
5578/*
5579 * Clear the screen
5580 */
5581 static void
5582clear_screen(void)
5583{
5584 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005585
5586 if (!USE_VTP)
5587 clear_chars(g_coord, Rows * Columns);
5588 else
5589 {
5590 set_console_color_rgb();
5591 gotoxy(1, 1);
5592 vtp_printf("\033[2J");
5593 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594}
5595
5596
5597/*
5598 * Clear to end of display
5599 */
5600 static void
5601clear_to_end_of_display(void)
5602{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005603 COORD save = g_coord;
5604
5605 if (!USE_VTP)
5606 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005608 else
5609 {
5610 set_console_color_rgb();
5611 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5612 vtp_printf("\033[0J");
5613
5614 gotoxy(save.X + 1, save.Y + 1);
5615 g_coord = save;
5616 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005617}
5618
5619
5620/*
5621 * Clear to end of line
5622 */
5623 static void
5624clear_to_end_of_line(void)
5625{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005626 COORD save = g_coord;
5627
5628 if (!USE_VTP)
5629 clear_chars(g_coord, Columns - g_coord.X);
5630 else
5631 {
5632 set_console_color_rgb();
5633 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5634 vtp_printf("\033[0K");
5635
5636 gotoxy(save.X + 1, save.Y + 1);
5637 g_coord = save;
5638 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005639}
5640
5641
5642/*
5643 * Scroll the scroll region up by `cLines' lines
5644 */
5645 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005646scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005647{
5648 COORD oldcoord = g_coord;
5649
5650 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5651 delete_lines(cLines);
5652
5653 g_coord = oldcoord;
5654}
5655
5656
5657/*
5658 * Set the scroll region
5659 */
5660 static void
5661set_scroll_region(
5662 unsigned left,
5663 unsigned top,
5664 unsigned right,
5665 unsigned bottom)
5666{
5667 if (left >= right
5668 || top >= bottom
5669 || right > (unsigned) Columns - 1
5670 || bottom > (unsigned) Rows - 1)
5671 return;
5672
5673 g_srScrollRegion.Left = left;
5674 g_srScrollRegion.Top = top;
5675 g_srScrollRegion.Right = right;
5676 g_srScrollRegion.Bottom = bottom;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005677}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005678
Bram Moolenaar6982f422019-02-16 16:48:01 +01005679 static void
5680set_scroll_region_tb(
5681 unsigned top,
5682 unsigned bottom)
5683{
5684 if (top >= bottom || bottom > (unsigned)Rows - 1)
5685 return;
5686
5687 g_srScrollRegion.Top = top;
5688 g_srScrollRegion.Bottom = bottom;
5689}
5690
5691 static void
5692set_scroll_region_lr(
5693 unsigned left,
5694 unsigned right)
5695{
5696 if (left >= right || right > (unsigned)Columns - 1)
5697 return;
5698
5699 g_srScrollRegion.Left = left;
5700 g_srScrollRegion.Right = right;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701}
5702
5703
5704/*
5705 * Insert `cLines' lines at the current cursor position
5706 */
5707 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005708insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005709{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005710 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711 COORD dest;
5712 CHAR_INFO fill;
5713
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005714 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5715
Bram Moolenaar6982f422019-02-16 16:48:01 +01005716 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005717 dest.Y = g_coord.Y + cLines;
5718
Bram Moolenaar6982f422019-02-16 16:48:01 +01005719 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005720 source.Top = g_coord.Y;
5721 source.Right = g_srScrollRegion.Right;
5722 source.Bottom = g_srScrollRegion.Bottom - cLines;
5723
Bram Moolenaar6982f422019-02-16 16:48:01 +01005724 clip.Left = g_srScrollRegion.Left;
5725 clip.Top = g_coord.Y;
5726 clip.Right = g_srScrollRegion.Right;
5727 clip.Bottom = g_srScrollRegion.Bottom;
5728
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005729 fill.Char.AsciiChar = ' ';
5730 if (!USE_VTP)
5731 fill.Attributes = g_attrCurrent;
5732 else
5733 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005735 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005736
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005737 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5738
Bram Moolenaar6982f422019-02-16 16:48:01 +01005739 // Here we have to deal with a win32 console flake: If the scroll
5740 // region looks like abc and we scroll c to a and fill with d we get
5741 // cbd... if we scroll block c one line at a time to a, we get cdd...
5742 // vim expects cdd consistently... So we have to deal with that
5743 // here... (this also occurs scrolling the same way in the other
5744 // direction).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745
5746 if (source.Bottom < dest.Y)
5747 {
5748 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005749 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750
Bram Moolenaar6982f422019-02-16 16:48:01 +01005751 coord.X = source.Left;
5752 for (i = clip.Top; i < dest.Y; ++i)
5753 {
5754 coord.Y = i;
5755 clear_chars(coord, source.Right - source.Left + 1);
5756 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005757 }
5758}
5759
5760
5761/*
5762 * Delete `cLines' lines at the current cursor position
5763 */
5764 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005765delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766{
Bram Moolenaar6982f422019-02-16 16:48:01 +01005767 SMALL_RECT source, clip;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 COORD dest;
5769 CHAR_INFO fill;
5770 int nb;
5771
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005772 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5773
Bram Moolenaar6982f422019-02-16 16:48:01 +01005774 dest.X = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775 dest.Y = g_coord.Y;
5776
Bram Moolenaar6982f422019-02-16 16:48:01 +01005777 source.Left = g_srScrollRegion.Left;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005778 source.Top = g_coord.Y + cLines;
5779 source.Right = g_srScrollRegion.Right;
5780 source.Bottom = g_srScrollRegion.Bottom;
5781
Bram Moolenaar6982f422019-02-16 16:48:01 +01005782 clip.Left = g_srScrollRegion.Left;
5783 clip.Top = g_coord.Y;
5784 clip.Right = g_srScrollRegion.Right;
5785 clip.Bottom = g_srScrollRegion.Bottom;
5786
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005787 fill.Char.AsciiChar = ' ';
5788 if (!USE_VTP)
5789 fill.Attributes = g_attrCurrent;
5790 else
5791 fill.Attributes = g_attrDefault;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005793 set_console_color_rgb();
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005794
Bram Moolenaar3b5fef62019-03-17 14:54:53 +01005795 ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5796
Bram Moolenaar6982f422019-02-16 16:48:01 +01005797 // Here we have to deal with a win32 console flake; See insert_lines()
5798 // above.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799
5800 nb = dest.Y + (source.Bottom - source.Top) + 1;
5801
5802 if (nb < source.Top)
5803 {
5804 COORD coord;
Bram Moolenaar6982f422019-02-16 16:48:01 +01005805 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806
Bram Moolenaar6982f422019-02-16 16:48:01 +01005807 coord.X = source.Left;
5808 for (i = nb; i < clip.Bottom; ++i)
5809 {
5810 coord.Y = i;
5811 clear_chars(coord, source.Right - source.Left + 1);
5812 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005813 }
5814}
5815
5816
5817/*
5818 * Set the cursor position
5819 */
5820 static void
5821gotoxy(
5822 unsigned x,
5823 unsigned y)
5824{
5825 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5826 return;
5827
5828 /* external cursor coords are 1-based; internal are 0-based */
5829 g_coord.X = x - 1;
5830 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005831
5832 if (!USE_VTP)
5833 SetConsoleCursorPosition(g_hConOut, g_coord);
5834 else
5835 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005836}
5837
5838
5839/*
5840 * Set the current text attribute = (foreground | background)
Bram Moolenaarafde13b2019-04-28 19:46:49 +02005841 * See ../runtime/doc/os_win32.txt for the numbers.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842 */
5843 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005844textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005845{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005846 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005847
5848 SetConsoleTextAttribute(g_hConOut, wAttr);
5849}
5850
5851
5852 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005853textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005855 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005856
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005857 if (!USE_VTP)
5858 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5859 else
5860 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005861}
5862
5863
5864 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005865textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005866{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005867 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005868
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005869 if (!USE_VTP)
5870 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5871 else
5872 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005873}
5874
5875
5876/*
5877 * restore the default text attribute (whatever we started with)
5878 */
5879 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005880normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005882 if (!USE_VTP)
5883 textattr(g_attrDefault);
5884 else
5885 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005886}
5887
5888
5889static WORD g_attrPreStandout = 0;
5890
5891/*
5892 * Make the text standout, by brightening it
5893 */
5894 static void
5895standout(void)
5896{
5897 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005898
Bram Moolenaar071d4272004-06-13 20:20:40 +00005899 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5900}
5901
5902
5903/*
5904 * Turn off standout mode
5905 */
5906 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005907standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005908{
5909 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005911
5912 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005913}
5914
5915
5916/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005917 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005918 */
5919 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005920mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005921{
5922 char_u *p;
5923 int n;
5924
5925 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5926 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005927 if (
5928#ifdef FEAT_TERMGUICOLORS
5929 !p_tgc &&
5930#endif
5931 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932 {
5933 p = T_ME + 2;
5934 n = getdigits(&p);
5935 if (*p == 'm' && n > 0)
5936 {
5937 cterm_normal_fg_color = (n & 0xf) + 1;
5938 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5939 }
5940 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005941#ifdef FEAT_TERMGUICOLORS
5942 cterm_normal_fg_gui_color = INVALCOLOR;
5943 cterm_normal_bg_gui_color = INVALCOLOR;
5944#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945}
5946
5947
5948/*
5949 * visual bell: flash the screen
5950 */
5951 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005952visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005953{
5954 COORD coordOrigin = {0, 0};
5955 WORD attrFlash = ~g_attrCurrent & 0xff;
5956
5957 DWORD dwDummy;
5958 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5959
5960 if (oldattrs == NULL)
5961 return;
5962 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5963 coordOrigin, &dwDummy);
5964 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5965 coordOrigin, &dwDummy);
5966
5967 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005968 if (!USE_VTP)
5969 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970 coordOrigin, &dwDummy);
5971 vim_free(oldattrs);
5972}
5973
5974
5975/*
5976 * Make the cursor visible or invisible
5977 */
5978 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005979cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980{
5981 s_cursor_visible = fVisible;
5982#ifdef MCH_CURSOR_SHAPE
5983 mch_update_cursor();
5984#endif
5985}
5986
5987
5988/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005989 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005990 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005991 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005992 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005994 char_u *pchBuf,
5995 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005996{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02005997 COORD coord = g_coord;
5998 DWORD written;
5999 DWORD n, cchwritten, cells;
6000 static WCHAR *unicodebuf = NULL;
6001 static int unibuflen = 0;
6002 int length;
6003 int cp = enc_utf8 ? CP_UTF8 : enc_codepage;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006005 length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6006 if (unicodebuf == NULL || length > unibuflen)
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006007 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006008 vim_free(unicodebuf);
6009 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6010 unibuflen = length;
6011 }
6012 MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6013 unicodebuf, unibuflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006014
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006015 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006016
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006017 if (!USE_VTP)
6018 {
6019 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6020 coord, &written);
6021 // When writing fails or didn't write a single character, pretend one
6022 // character was written, otherwise we get stuck.
6023 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6024 coord, &cchwritten) == 0
6025 || cchwritten == 0 || cchwritten == (DWORD)-1)
6026 cchwritten = 1;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006027 }
6028 else
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006029 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006030 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6031 NULL) == 0 || cchwritten == 0)
6032 cchwritten = 1;
6033 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006034
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006035 if (cchwritten == length)
6036 {
6037 written = cbToWrite;
6038 g_coord.X += (SHORT)cells;
6039 }
6040 else
6041 {
6042 char_u *p = pchBuf;
6043 for (n = 0; n < cchwritten; n++)
6044 MB_CPTR_ADV(p);
6045 written = p - pchBuf;
6046 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006047 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006048
6049 while (g_coord.X > g_srScrollRegion.Right)
6050 {
6051 g_coord.X -= (SHORT) Columns;
6052 if (g_coord.Y < g_srScrollRegion.Bottom)
6053 g_coord.Y++;
6054 }
6055
6056 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6057
6058 return written;
6059}
6060
6061
6062/*
6063 * mch_write(): write the output buffer to the screen, translating ESC
6064 * sequences into calls to console output routines.
6065 */
6066 void
6067mch_write(
6068 char_u *s,
6069 int len)
6070{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006071# ifdef VIMDLL
6072 if (gui.in_use)
6073 return;
6074# endif
6075
Bram Moolenaar071d4272004-06-13 20:20:40 +00006076 s[len] = NUL;
6077
6078 if (!term_console)
6079 {
6080 write(1, s, (unsigned)len);
6081 return;
6082 }
6083
6084 /* translate ESC | sequences into faked bios calls */
6085 while (len--)
6086 {
6087 /* optimization: use one single write_chars for runs of text,
6088 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006089 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006090
6091 if (p_wd)
6092 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006093 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094 if (prefix != 0)
6095 prefix = 1;
6096 }
6097
6098 if (prefix != 0)
6099 {
6100 DWORD nWritten;
6101
6102 nWritten = write_chars(s, prefix);
6103#ifdef MCH_WRITE_DUMP
6104 if (fdDump)
6105 {
6106 fputc('>', fdDump);
6107 fwrite(s, sizeof(char_u), nWritten, fdDump);
6108 fputs("<\n", fdDump);
6109 }
6110#endif
6111 len -= (nWritten - 1);
6112 s += nWritten;
6113 }
6114 else if (s[0] == '\n')
6115 {
6116 /* \n, newline: go to the beginning of the next line or scroll */
6117 if (g_coord.Y == g_srScrollRegion.Bottom)
6118 {
6119 scroll(1);
6120 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6121 }
6122 else
6123 {
6124 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6125 }
6126#ifdef MCH_WRITE_DUMP
6127 if (fdDump)
6128 fputs("\\n\n", fdDump);
6129#endif
6130 s++;
6131 }
6132 else if (s[0] == '\r')
6133 {
6134 /* \r, carriage return: go to beginning of line */
6135 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6136#ifdef MCH_WRITE_DUMP
6137 if (fdDump)
6138 fputs("\\r\n", fdDump);
6139#endif
6140 s++;
6141 }
6142 else if (s[0] == '\b')
6143 {
6144 /* \b, backspace: move cursor one position left */
6145 if (g_coord.X > g_srScrollRegion.Left)
6146 g_coord.X--;
6147 else if (g_coord.Y > g_srScrollRegion.Top)
6148 {
6149 g_coord.X = g_srScrollRegion.Right;
6150 g_coord.Y--;
6151 }
6152 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6153#ifdef MCH_WRITE_DUMP
6154 if (fdDump)
6155 fputs("\\b\n", fdDump);
6156#endif
6157 s++;
6158 }
6159 else if (s[0] == '\a')
6160 {
6161 /* \a, bell */
6162 MessageBeep(0xFFFFFFFF);
6163#ifdef MCH_WRITE_DUMP
6164 if (fdDump)
6165 fputs("\\a\n", fdDump);
6166#endif
6167 s++;
6168 }
6169 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6170 {
6171#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006172 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006174 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006175 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176
6177 switch (s[2])
6178 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179 case '0': case '1': case '2': case '3': case '4':
6180 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006181 p = s + 1;
6182 do
6183 {
6184 ++p;
6185 args[argc] = getdigits(&p);
6186 argc += (argc < 15) ? 1 : 0;
6187 if (p > s + len)
6188 break;
6189 } while (*p == ';');
6190
Bram Moolenaar071d4272004-06-13 20:20:40 +00006191 if (p > s + len)
6192 break;
6193
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006194 arg1 = args[0];
6195 arg2 = args[1];
6196 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006198 if (argc == 1 && args[0] == 0)
6199 normvideo();
6200 else if (argc == 1)
6201 {
6202 if (USE_VTP)
6203 textcolor((WORD) arg1);
6204 else
6205 textattr((WORD) arg1);
6206 }
6207 else if (USE_VTP)
6208 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006210 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006212 gotoxy(arg2, arg1);
6213 }
6214 else if (argc == 2 && *p == 'r')
6215 {
6216 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6217 }
Bram Moolenaar6982f422019-02-16 16:48:01 +01006218 else if (argc == 2 && *p == 'R')
6219 {
6220 set_scroll_region_tb(arg1, arg2);
6221 }
6222 else if (argc == 2 && *p == 'V')
6223 {
6224 set_scroll_region_lr(arg1, arg2);
6225 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006226 else if (argc == 1 && *p == 'A')
6227 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228 gotoxy(g_coord.X + 1,
6229 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6230 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006231 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232 {
6233 textbackground((WORD) arg1);
6234 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006235 else if (argc == 1 && *p == 'C')
6236 {
6237 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6238 g_coord.Y + 1);
6239 }
6240 else if (argc == 1 && *p == 'f')
6241 {
6242 textcolor((WORD) arg1);
6243 }
6244 else if (argc == 1 && *p == 'H')
6245 {
6246 gotoxy(1, arg1);
6247 }
6248 else if (argc == 1 && *p == 'L')
6249 {
6250 insert_lines(arg1);
6251 }
6252 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253 {
6254 delete_lines(arg1);
6255 }
6256
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006257 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006258 s = p + 1;
6259 break;
6260
Bram Moolenaar071d4272004-06-13 20:20:40 +00006261 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 gotoxy(g_coord.X + 1,
6263 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6264 goto got3;
6265
6266 case 'B':
6267 visual_bell();
6268 goto got3;
6269
6270 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6272 g_coord.Y + 1);
6273 goto got3;
6274
6275 case 'E':
6276 termcap_mode_end();
6277 goto got3;
6278
6279 case 'F':
6280 standout();
6281 goto got3;
6282
6283 case 'f':
6284 standend();
6285 goto got3;
6286
6287 case 'H':
6288 gotoxy(1, 1);
6289 goto got3;
6290
6291 case 'j':
6292 clear_to_end_of_display();
6293 goto got3;
6294
6295 case 'J':
6296 clear_screen();
6297 goto got3;
6298
6299 case 'K':
6300 clear_to_end_of_line();
6301 goto got3;
6302
6303 case 'L':
6304 insert_lines(1);
6305 goto got3;
6306
6307 case 'M':
6308 delete_lines(1);
6309 goto got3;
6310
6311 case 'S':
6312 termcap_mode_start();
6313 goto got3;
6314
6315 case 'V':
6316 cursor_visible(TRUE);
6317 goto got3;
6318
6319 case 'v':
6320 cursor_visible(FALSE);
6321 goto got3;
6322
6323 got3:
6324 s += 3;
6325 len -= 2;
6326 }
6327
6328#ifdef MCH_WRITE_DUMP
6329 if (fdDump)
6330 {
6331 fputs("ESC | ", fdDump);
6332 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6333 fputc('\n', fdDump);
6334 }
6335#endif
6336 }
6337 else
6338 {
6339 /* Write a single character */
6340 DWORD nWritten;
6341
6342 nWritten = write_chars(s, 1);
6343#ifdef MCH_WRITE_DUMP
6344 if (fdDump)
6345 {
6346 fputc('>', fdDump);
6347 fwrite(s, sizeof(char_u), nWritten, fdDump);
6348 fputs("<\n", fdDump);
6349 }
6350#endif
6351
6352 len -= (nWritten - 1);
6353 s += nWritten;
6354 }
6355 }
6356
6357#ifdef MCH_WRITE_DUMP
6358 if (fdDump)
6359 fflush(fdDump);
6360#endif
6361}
6362
Bram Moolenaar4f974752019-02-17 17:44:42 +01006363#endif /* FEAT_GUI_MSWIN */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364
6365
6366/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006367 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368 */
6369 void
6370mch_delay(
6371 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006372 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006373{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006374#if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006376#else /* Console */
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006377# ifdef VIMDLL
6378 if (gui.in_use)
6379 {
6380 Sleep((int)msec); /* never wait for input */
6381 return;
6382 }
6383# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006384 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006385# ifdef FEAT_MZSCHEME
6386 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6387 {
6388 int towait = p_mzq;
6389
6390 /* if msec is large enough, wait by portions in p_mzq */
6391 while (msec > 0)
6392 {
6393 mzvim_check_threads();
6394 if (msec < towait)
6395 towait = msec;
6396 Sleep(towait);
6397 msec -= towait;
6398 }
6399 }
6400 else
6401# endif
6402 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006404 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006405#endif
6406}
6407
6408
6409/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006410 * This version of remove is not scared by a readonly (backup) file.
6411 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006412 * Return 0 for success, -1 for failure.
6413 */
6414 int
6415mch_remove(char_u *name)
6416{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006417 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006418 int n;
6419
Bram Moolenaar203258c2016-01-17 22:15:16 +01006420 /*
6421 * On Windows, deleting a directory's symbolic link is done by
6422 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6423 */
6424 if (mch_isdir(name) && mch_is_symbolic_link(name))
6425 return mch_rmdir(name);
6426
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006427 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6428
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006429 wn = enc_to_utf16(name, NULL);
6430 if (wn == NULL)
6431 return -1;
6432
6433 n = DeleteFileW(wn) ? 0 : -1;
6434 vim_free(wn);
6435 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006436}
6437
6438
6439/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006440 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006441 */
6442 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006443mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444{
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006445#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6446# ifdef VIMDLL
6447 if (!gui.in_use)
6448# endif
6449 if (g_fCtrlCPressed || g_fCBrkPressed)
6450 {
6451 ctrl_break_was_pressed = g_fCBrkPressed;
6452 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6453 got_int = TRUE;
6454 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455#endif
6456}
6457
Bram Moolenaaree273972016-01-02 21:11:51 +01006458/* physical RAM to leave for the OS */
6459#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006460
6461/*
6462 * How much main memory in KiB that can be used by VIM.
6463 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006464 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006465mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006466{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006467 MEMORYSTATUSEX ms;
6468
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006469 /* Need to use GlobalMemoryStatusEx() when there is more memory than
Bram Moolenaarafde13b2019-04-28 19:46:49 +02006470 * what fits in 32 bits. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006471 ms.dwLength = sizeof(MEMORYSTATUSEX);
6472 GlobalMemoryStatusEx(&ms);
6473 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006474 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006475 /* Process address space fits in physical RAM, use all of it. */
6476 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006477 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006478 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006479 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006480 /* Catch old NT box or perverse hardware setup. */
6481 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006482 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006483 /* Use physical RAM less reserve for OS + data. */
6484 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006485}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006486
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006488 * mch_wrename() works around a bug in rename (aka MoveFile) in
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6490 * file whose short file name is "FOO.BAR" (its long file name will
6491 * be correct: "foo.bar~"). Because a file can be accessed by
6492 * either its SFN or its LFN, "foo.bar" has effectively been
6493 * renamed to "foo.bar", which is not at all what was wanted. This
6494 * seems to happen only when renaming files with three-character
6495 * extensions by appending a suffix that does not include ".".
6496 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6497 *
6498 * There is another problem, which isn't really a bug but isn't right either:
6499 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6500 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6501 * service pack 6. Doesn't seem to happen on Windows 98.
6502 *
6503 * Like rename(), returns 0 upon success, non-zero upon failure.
6504 * Should probably set errno appropriately when errors occur.
6505 */
6506 int
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006507mch_wrename(WCHAR *wold, WCHAR *wnew)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006508{
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006509 WCHAR *p;
6510 int i;
6511 WCHAR szTempFile[_MAX_PATH + 1];
6512 WCHAR szNewPath[_MAX_PATH + 1];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 HANDLE hf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006514
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006515 // No need to play tricks unless the file name contains a "~" as the
6516 // seventh character.
6517 p = wold;
6518 for (i = 0; wold[i] != NUL; ++i)
6519 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6520 && wold[i + 1] != 0)
6521 p = wold + i + 1;
6522 if ((int)(wold + i - p) < 8 || p[6] != '~')
6523 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006524
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006525 // Get base path of new file name. Undocumented feature: If pszNewFile is
6526 // a directory, no error is returned and pszFilePart will be NULL.
6527 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528 return -1;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006529 *p = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006531 // Get (and create) a unique temporary file name in directory of new file
6532 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 return -2;
6534
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006535 // blow the temp file away
6536 if (!DeleteFileW(szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 return -3;
6538
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006539 // rename old file to the temp file
6540 if (!MoveFileW(wold, szTempFile))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541 return -4;
6542
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006543 // now create an empty file called pszOldFile; this prevents the operating
6544 // system using pszOldFile as an alias (SFN) if we're renaming within the
6545 // same directory. For example, we're editing a file called
6546 // filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6547 // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6548 // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6549 // cause all sorts of problems later in buf_write(). So, we create an
6550 // empty file called filena~1.txt and the system will have to find some
6551 // other SFN for filena~1.txt~, such as filena~2.txt
6552 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6554 return -5;
6555 if (!CloseHandle(hf))
6556 return -6;
6557
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006558 // rename the temp file to the new file
6559 if (!MoveFileW(szTempFile, wnew))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006560 {
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006561 // Renaming failed. Rename the file back to its old name, so that it
6562 // looks like nothing happened.
6563 (void)MoveFileW(szTempFile, wold);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564 return -7;
6565 }
6566
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006567 // Seems to be left around on Novell filesystems
6568 DeleteFileW(szTempFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006569
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006570 // finally, remove the empty old file
6571 if (!DeleteFileW(wold))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006572 return -8;
6573
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006574 return 0;
6575}
6576
6577
6578/*
6579 * Converts the filenames to UTF-16, then call mch_wrename().
6580 * Like rename(), returns 0 upon success, non-zero upon failure.
6581 */
6582 int
6583mch_rename(
6584 const char *pszOldFile,
6585 const char *pszNewFile)
6586{
6587 WCHAR *wold = NULL;
6588 WCHAR *wnew = NULL;
6589 int retval = -1;
6590
6591 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6592 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
6593 if (wold != NULL && wnew != NULL)
6594 retval = mch_wrename(wold, wnew);
6595 vim_free(wold);
6596 vim_free(wnew);
6597 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006598}
6599
6600/*
6601 * Get the default shell for the current hardware platform
6602 */
6603 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006604default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006606 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006607}
6608
6609/*
6610 * mch_access() extends access() to do more detailed check on network drives.
6611 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6612 */
6613 int
6614mch_access(char *n, int p)
6615{
6616 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 int retval = -1; /* default: fail */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006618 WCHAR *wn;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006619
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006620 wn = enc_to_utf16((char_u *)n, NULL);
6621 if (wn == NULL)
6622 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006624 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626 WCHAR TempNameW[_MAX_PATH + 16] = L"";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006627
6628 if (p & R_OK)
6629 {
6630 /* Read check is performed by seeing if we can do a find file on
6631 * the directory for any file. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006632 int i;
6633 WIN32_FIND_DATAW d;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006635 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6636 TempNameW[i] = wn[i];
6637 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6638 TempNameW[i++] = '\\';
6639 TempNameW[i++] = '*';
6640 TempNameW[i++] = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006642 hFile = FindFirstFileW(TempNameW, &d);
6643 if (hFile == INVALID_HANDLE_VALUE)
6644 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006645 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 (void)FindClose(hFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 }
6648
6649 if (p & W_OK)
6650 {
6651 /* Trying to create a temporary file in the directory should catch
6652 * directories on read-only network shares. However, in
6653 * directories whose ACL allows writes but denies deletes will end
6654 * up keeping the temporary file :-(. */
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006655 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6656 goto getout;
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006657 else
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006658 DeleteFileW(TempNameW);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 }
6660 }
6661 else
6662 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006663 // Don't consider a file read-only if another process has opened it.
6664 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
6665
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666 /* Trying to open the file for the required access does ACL, read-only
6667 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02006668 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
6669 | ((p & R_OK) ? GENERIC_READ : 0);
6670
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006671 hFile = CreateFileW(wn, access_mode, share_mode,
6672 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006673 if (hFile == INVALID_HANDLE_VALUE)
6674 goto getout;
6675 CloseHandle(hFile);
6676 }
6677
6678 retval = 0; /* success */
6679getout:
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 vim_free(wn);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681 return retval;
6682}
6683
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006685 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 */
6687 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006688mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006689{
6690 WCHAR *wn;
6691 int f;
6692
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006693 wn = enc_to_utf16((char_u *)name, NULL);
6694 if (wn == NULL)
6695 return -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006697 f = _wopen(wn, flags, mode);
6698 vim_free(wn);
6699 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700}
6701
6702/*
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006703 * Version of fopen() that uses UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 */
6705 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006706mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707{
6708 WCHAR *wn, *wm;
6709 FILE *f = NULL;
6710
Bram Moolenaara12a1612019-01-24 16:39:02 +01006711#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006712 /* Work around an annoying assertion in the Microsoft debug CRT
6713 * when mode's text/binary setting doesn't match _get_fmode(). */
6714 char newMode = mode[strlen(mode) - 1];
6715 int oldMode = 0;
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006716
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006717 _get_fmode(&oldMode);
6718 if (newMode == 't')
6719 _set_fmode(_O_TEXT);
6720 else if (newMode == 'b')
6721 _set_fmode(_O_BINARY);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006722#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006723 wn = enc_to_utf16((char_u *)name, NULL);
6724 wm = enc_to_utf16((char_u *)mode, NULL);
6725 if (wn != NULL && wm != NULL)
6726 f = _wfopen(wn, wm);
6727 vim_free(wn);
6728 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006729
Bram Moolenaara12a1612019-01-24 16:39:02 +01006730#if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006731 _set_fmode(oldMode);
Bram Moolenaara12a1612019-01-24 16:39:02 +01006732#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02006733 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006734}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735
Bram Moolenaar071d4272004-06-13 20:20:40 +00006736/*
6737 * SUB STREAM (aka info stream) handling:
6738 *
6739 * NTFS can have sub streams for each file. Normal contents of file is
6740 * stored in the main stream, and extra contents (author information and
6741 * title and so on) can be stored in sub stream. After Windows 2000, user
6742 * can access and store those informations in sub streams via explorer's
6743 * property menuitem in right click menu. Those informations in sub streams
6744 * were lost when copying only the main stream. So we have to copy sub
6745 * streams.
6746 *
6747 * Incomplete explanation:
6748 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6749 * More useful info and an example:
6750 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6751 */
6752
6753/*
6754 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6755 * and write to stream "substream" of file "to".
6756 * Errors are ignored.
6757 */
6758 static void
6759copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6760{
6761 HANDLE hTo;
6762 WCHAR *to_name;
6763
6764 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6765 wcscpy(to_name, to);
6766 wcscat(to_name, substream);
6767
6768 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6769 FILE_ATTRIBUTE_NORMAL, NULL);
6770 if (hTo != INVALID_HANDLE_VALUE)
6771 {
6772 long done;
6773 DWORD todo;
6774 DWORD readcnt, written;
6775 char buf[4096];
6776
6777 /* Copy block of bytes at a time. Abort when something goes wrong. */
6778 for (done = 0; done < len; done += written)
6779 {
6780 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006781 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6782 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006783 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6784 FALSE, FALSE, context)
6785 || readcnt != todo
6786 || !WriteFile(hTo, buf, todo, &written, NULL)
6787 || written != todo)
6788 break;
6789 }
6790 CloseHandle(hTo);
6791 }
6792
6793 free(to_name);
6794}
6795
6796/*
6797 * Copy info streams from file "from" to file "to".
6798 */
6799 static void
6800copy_infostreams(char_u *from, char_u *to)
6801{
6802 WCHAR *fromw;
6803 WCHAR *tow;
6804 HANDLE sh;
6805 WIN32_STREAM_ID sid;
6806 int headersize;
6807 WCHAR streamname[_MAX_PATH];
6808 DWORD readcount;
6809 void *context = NULL;
6810 DWORD lo, hi;
6811 int len;
6812
6813 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006814 fromw = enc_to_utf16(from, NULL);
6815 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 if (fromw != NULL && tow != NULL)
6817 {
6818 /* Open the file for reading. */
6819 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6820 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6821 if (sh != INVALID_HANDLE_VALUE)
6822 {
6823 /* Use BackupRead() to find the info streams. Repeat until we
6824 * have done them all.*/
6825 for (;;)
6826 {
6827 /* Get the header to find the length of the stream name. If
6828 * the "readcount" is zero we have done all info streams. */
6829 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006830 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006831 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6832 &readcount, FALSE, FALSE, &context)
6833 || readcount == 0)
6834 break;
6835
6836 /* We only deal with streams that have a name. The normal
6837 * file data appears to be without a name, even though docs
6838 * suggest it is called "::$DATA". */
6839 if (sid.dwStreamNameSize > 0)
6840 {
6841 /* Read the stream name. */
6842 if (!BackupRead(sh, (LPBYTE)streamname,
6843 sid.dwStreamNameSize,
6844 &readcount, FALSE, FALSE, &context))
6845 break;
6846
6847 /* Copy an info stream with a name ":anything:$DATA".
6848 * Skip "::$DATA", it has no stream name (examples suggest
6849 * it might be used for the normal file contents).
6850 * Note that BackupRead() counts bytes, but the name is in
6851 * wide characters. */
6852 len = readcount / sizeof(WCHAR);
6853 streamname[len] = 0;
6854 if (len > 7 && wcsicmp(streamname + len - 6,
6855 L":$DATA") == 0)
6856 {
6857 streamname[len - 6] = 0;
6858 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006859 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860 }
6861 }
6862
6863 /* Advance to the next stream. We might try seeking too far,
6864 * but BackupSeek() doesn't skip over stream borders, thus
6865 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006866 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867 &lo, &hi, &context);
6868 }
6869
6870 /* Clear the context. */
6871 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6872
6873 CloseHandle(sh);
6874 }
6875 }
6876 vim_free(fromw);
6877 vim_free(tow);
6878}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879
6880/*
6881 * Copy file attributes from file "from" to file "to".
6882 * For Windows NT and later we copy info streams.
6883 * Always returns zero, errors are ignored.
6884 */
6885 int
6886mch_copy_file_attribute(char_u *from, char_u *to)
6887{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006888 /* File streams only work on Windows NT and later. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006889 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006890 return 0;
6891}
6892
6893#if defined(MYRESETSTKOFLW) || defined(PROTO)
6894/*
6895 * Recreate a destroyed stack guard page in win32.
6896 * Written by Benjamin Peterson.
6897 */
6898
6899/* These magic numbers are from the MS header files */
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01006900# define MIN_STACK_WINNT 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901
6902/*
6903 * This function does the same thing as _resetstkoflw(), which is only
6904 * available in DevStudio .net and later.
6905 * Returns 0 for failure, 1 for success.
6906 */
6907 int
6908myresetstkoflw(void)
6909{
6910 BYTE *pStackPtr;
6911 BYTE *pGuardPage;
6912 BYTE *pStackBase;
6913 BYTE *pLowestPossiblePage;
6914 MEMORY_BASIC_INFORMATION mbi;
6915 SYSTEM_INFO si;
6916 DWORD nPageSize;
6917 DWORD dummy;
6918
Bram Moolenaar071d4272004-06-13 20:20:40 +00006919 /* We need to know the system page size. */
6920 GetSystemInfo(&si);
6921 nPageSize = si.dwPageSize;
6922
6923 /* ...and the current stack pointer */
6924 pStackPtr = (BYTE*)_alloca(1);
6925
6926 /* ...and the base of the stack. */
6927 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6928 return 0;
6929 pStackBase = (BYTE*)mbi.AllocationBase;
6930
6931 /* ...and the page thats min_stack_req pages away from stack base; this is
6932 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006933 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006934
Bram Moolenaar071d4272004-06-13 20:20:40 +00006935 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006936 /* We want the first committed page in the stack Start at the stack
6937 * base and move forward through memory until we find a committed block.
6938 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006939 BYTE *pBlock = pStackBase;
6940
Bram Moolenaara466c992005-07-09 21:03:22 +00006941 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 {
6943 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6944 return 0;
6945
6946 pBlock += mbi.RegionSize;
6947
6948 if (mbi.State & MEM_COMMIT)
6949 break;
6950 }
6951
6952 /* mbi now describes the first committed block in the stack. */
6953 if (mbi.Protect & PAGE_GUARD)
6954 return 1;
6955
6956 /* decide where the guard page should start */
6957 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6958 pGuardPage = pLowestPossiblePage;
6959 else
6960 pGuardPage = (BYTE*)mbi.BaseAddress;
6961
6962 /* allocate the guard page */
6963 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6964 return 0;
6965
6966 /* apply the guard attribute to the page */
6967 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6968 &dummy))
6969 return 0;
6970 }
6971
6972 return 1;
6973}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006974#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006976
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006977/*
6978 * The command line arguments in UCS2
6979 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006980static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006981static LPWSTR *ArglistW = NULL;
6982static int global_argc = 0;
6983static char **global_argv;
6984
6985static int used_file_argc = 0; /* last argument in global_argv[] used
6986 for the argument list. */
6987static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6988 command line arguments added to
6989 the argument list */
6990static int used_file_count = 0; /* nr of entries in used_file_indexes */
6991static int used_file_literal = FALSE; /* take file names literally */
6992static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006993static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006994static int used_alist_count = 0;
6995
6996
6997/*
6998 * Get the command line arguments. Unicode version.
6999 * Returns argc. Zero when something fails.
7000 */
7001 int
7002get_cmd_argsW(char ***argvp)
7003{
7004 char **argv = NULL;
7005 int argc = 0;
7006 int i;
7007
Bram Moolenaar14993322014-09-09 12:25:33 +02007008 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007009 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7010 if (ArglistW != NULL)
7011 {
7012 argv = malloc((nArgsW + 1) * sizeof(char *));
7013 if (argv != NULL)
7014 {
7015 argc = nArgsW;
7016 argv[argc] = NULL;
7017 for (i = 0; i < argc; ++i)
7018 {
7019 int len;
7020
7021 /* Convert each Unicode argument to the current codepage. */
7022 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007023 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007024 (LPSTR *)&argv[i], &len, 0, 0);
7025 if (argv[i] == NULL)
7026 {
7027 /* Out of memory, clear everything. */
7028 while (i > 0)
7029 free(argv[--i]);
7030 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007031 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007032 argc = 0;
7033 }
7034 }
7035 }
7036 }
7037
7038 global_argc = argc;
7039 global_argv = argv;
7040 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007041 {
7042 if (used_file_indexes != NULL)
7043 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007044 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007045 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007046
7047 if (argvp != NULL)
7048 *argvp = argv;
7049 return argc;
7050}
7051
7052 void
7053free_cmd_argsW(void)
7054{
7055 if (ArglistW != NULL)
7056 {
7057 GlobalFree(ArglistW);
7058 ArglistW = NULL;
7059 }
7060}
7061
7062/*
7063 * Remember "name" is an argument that was added to the argument list.
7064 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7065 * is called.
7066 */
7067 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007068used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007069{
7070 int i;
7071
7072 if (used_file_indexes == NULL)
7073 return;
7074 for (i = used_file_argc + 1; i < global_argc; ++i)
7075 if (STRCMP(global_argv[i], name) == 0)
7076 {
7077 used_file_argc = i;
7078 used_file_indexes[used_file_count++] = i;
7079 break;
7080 }
7081 used_file_literal = literal;
7082 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007083 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007084}
7085
7086/*
7087 * Remember the length of the argument list as it was. If it changes then we
7088 * leave it alone when 'encoding' is set.
7089 */
7090 void
7091set_alist_count(void)
7092{
7093 used_alist_count = GARGCOUNT;
7094}
7095
7096/*
7097 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7098 * has been changed while starting up. Use the UCS-2 command line arguments
7099 * and convert them to 'encoding'.
7100 */
7101 void
7102fix_arg_enc(void)
7103{
7104 int i;
7105 int idx;
7106 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007107 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007108
7109 /* Safety checks:
7110 * - if argument count differs between the wide and non-wide argument
7111 * list, something must be wrong.
7112 * - the file name arguments must have been located.
7113 * - the length of the argument list wasn't changed by the user.
7114 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007115 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007116 || ArglistW == NULL
7117 || used_file_indexes == NULL
7118 || used_file_count == 0
7119 || used_alist_count != GARGCOUNT)
7120 return;
7121
Bram Moolenaar86b68352004-12-27 21:59:20 +00007122 /* Remember the buffer numbers for the arguments. */
7123 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7124 if (fnum_list == NULL)
7125 return; /* out of memory */
7126 for (i = 0; i < GARGCOUNT; ++i)
7127 fnum_list[i] = GARGLIST[i].ae_fnum;
7128
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007129 /* Clear the argument list. Make room for the new arguments. */
7130 alist_clear(&global_alist);
7131 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007132 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007133
7134 for (i = 0; i < used_file_count; ++i)
7135 {
7136 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007137 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007138 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007139 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007140 int literal = used_file_literal;
7141
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007142# ifdef FEAT_DIFF
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007143 /* When using diff mode may need to concatenate file name to
7144 * directory name. Just like it's done in main(). */
7145 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7146 && !mch_isdir(alist_name(&GARGLIST[0])))
7147 {
7148 char_u *r;
7149
7150 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7151 if (r != NULL)
7152 {
7153 vim_free(str);
7154 str = r;
7155 }
7156 }
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007157# endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007158 /* Re-use the old buffer by renaming it. When not using literal
7159 * names it's done by alist_expand() below. */
7160 if (used_file_literal)
7161 buf_set_name(fnum_list[i], str);
7162
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007163 /* Check backtick literal. backtick literal is already expanded in
7164 * main.c, so this part add str as literal. */
7165 if (literal == FALSE)
7166 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007167 size_t len = STRLEN(str);
7168
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007169 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7170 literal = TRUE;
7171 }
7172 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007173 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007174 }
7175
7176 if (!used_file_literal)
7177 {
7178 /* Now expand wildcards in the arguments. */
7179 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7180 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007181 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7182 * Also, unset wildignore to not be influenced by this option.
7183 * The arguments specified in command-line should be kept even if
7184 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007185 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007186 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007187 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007188 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007189 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007190 }
7191
7192 /* If wildcard expansion failed, we are editing the first file of the
7193 * arglist and there is no file name: Edit the first argument now. */
7194 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7195 {
7196 do_cmdline_cmd((char_u *)":rewind");
7197 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007198 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007199 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007200
7201 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007202}
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007203
7204 int
7205mch_setenv(char *var, char *value, int x)
7206{
7207 char_u *envbuf;
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007208 WCHAR *p;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007209
7210 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7211 if (envbuf == NULL)
7212 return -1;
7213
7214 sprintf((char *)envbuf, "%s=%s", var, value);
7215
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007216 p = enc_to_utf16(envbuf, NULL);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007217
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007218 vim_free(envbuf);
7219 if (p == NULL)
7220 return -1;
7221 _wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007222#ifdef libintl_wputenv
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007223 libintl_wputenv(p);
Bram Moolenaara12a1612019-01-24 16:39:02 +01007224#endif
Bram Moolenaar0eb035c2019-04-02 22:15:55 +02007225 // Unlike Un*x systems, we can free the string for _wputenv().
7226 vim_free(p);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007227
7228 return 0;
7229}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007230
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007231/*
7232 * Support for 256 colors and 24-bit colors was added in Windows 10
7233 * version 1703 (Creators update).
7234 */
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007235#define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7236
7237/*
7238 * Support for pseudo-console (ConPTY) was added in windows 10
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007239 * version 1809 (October 2018 update). However, that version is unstable.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007240 */
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007241#define CONPTY_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 17763)
7242#define CONPTY_STABLE_BUILD MAKE_VER(10, 0, 32767) // T.B.D.
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007243
7244 static void
7245vtp_flag_init(void)
7246{
7247 DWORD ver = get_build_number();
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007248#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007249 DWORD mode;
7250 HANDLE out;
7251
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007252# ifdef VIMDLL
7253 if (!gui.in_use)
7254# endif
7255 {
7256 out = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007257
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007258 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7259 GetConsoleMode(out, &mode);
7260 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7261 if (SetConsoleMode(out, mode) == 0)
7262 vtp_working = 0;
7263 }
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007264#endif
7265
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007266 if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007267 conpty_working = 1;
7268 if (ver >= CONPTY_STABLE_BUILD)
7269 conpty_stable = 1;
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007270
7271}
7272
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007273#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007274
7275 static void
7276vtp_init(void)
7277{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007278 HMODULE hKerneldll;
7279 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007280# ifdef FEAT_TERMGUICOLORS
7281 COLORREF fg, bg;
7282# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007283
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007284 /* Use functions supported from Vista */
7285 hKerneldll = GetModuleHandle("kernel32.dll");
7286 if (hKerneldll != NULL)
7287 {
7288 pGetConsoleScreenBufferInfoEx =
7289 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7290 hKerneldll, "GetConsoleScreenBufferInfoEx");
7291 pSetConsoleScreenBufferInfoEx =
7292 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7293 hKerneldll, "SetConsoleScreenBufferInfoEx");
7294 if (pGetConsoleScreenBufferInfoEx != NULL
7295 && pSetConsoleScreenBufferInfoEx != NULL)
7296 has_csbiex = TRUE;
7297 }
7298
7299 csbi.cbSize = sizeof(csbi);
7300 if (has_csbiex)
7301 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007302 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7303 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7304
7305# ifdef FEAT_TERMGUICOLORS
7306 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7307 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7308 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7309 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7310 default_console_color_bg = bg;
7311 default_console_color_fg = fg;
Bram Moolenaarc4568ab2018-11-16 16:21:05 +01007312# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007313
7314 set_console_color_rgb();
7315}
7316
7317 static void
7318vtp_exit(void)
7319{
7320 reset_console_color_rgb();
7321}
7322
7323 static int
7324vtp_printf(
7325 char *format,
7326 ...)
7327{
7328 char_u buf[100];
7329 va_list list;
7330 DWORD result;
7331
7332 va_start(list, format);
7333 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7334 va_end(list);
7335 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7336 return (int)result;
7337}
7338
7339 static void
7340vtp_sgr_bulk(
7341 int arg)
7342{
7343 int args[1];
7344
7345 args[0] = arg;
7346 vtp_sgr_bulks(1, args);
7347}
7348
7349 static void
7350vtp_sgr_bulks(
7351 int argc,
7352 int *args
7353)
7354{
7355 /* 2('\033[') + 4('255.') * 16 + NUL */
7356 char_u buf[2 + (4 * 16) + 1];
7357 char_u *p;
7358 int i;
7359
7360 p = buf;
7361 *p++ = '\033';
7362 *p++ = '[';
7363
7364 for (i = 0; i < argc; ++i)
7365 {
7366 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7367 *p++ = ';';
7368 }
7369 p--;
7370 *p++ = 'm';
7371 *p = NUL;
7372 vtp_printf((char *)buf);
7373}
7374
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007375# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007376 static int
7377ctermtoxterm(
7378 int cterm)
7379{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007380 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007381
7382 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7383 return (((int)r << 16) | ((int)g << 8) | (int)b);
7384}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007385# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007386
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007387 static void
7388set_console_color_rgb(void)
7389{
7390# ifdef FEAT_TERMGUICOLORS
7391 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7392 int id;
7393 guicolor_T fg = INVALCOLOR;
7394 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007395 int ctermfg;
7396 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007397
7398 if (!USE_VTP)
7399 return;
7400
7401 id = syn_name2id((char_u *)"Normal");
Bram Moolenaard5a58862019-03-07 06:40:27 +01007402 if (id > 0 && p_tgc)
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007403 syn_id2colors(id, &fg, &bg);
7404 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007405 {
7406 ctermfg = -1;
7407 if (id > 0)
7408 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007409 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7410 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007411 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007412 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007413 {
7414 ctermbg = -1;
7415 if (id > 0)
7416 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007417 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7418 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007419 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007420 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7421 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7422
7423 csbi.cbSize = sizeof(csbi);
7424 if (has_csbiex)
7425 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7426
7427 csbi.cbSize = sizeof(csbi);
7428 csbi.srWindow.Right += 1;
7429 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007430 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7431 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007432 if (has_csbiex)
7433 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7434# endif
7435}
7436
7437 static void
7438reset_console_color_rgb(void)
7439{
7440# ifdef FEAT_TERMGUICOLORS
7441 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7442
7443 csbi.cbSize = sizeof(csbi);
7444 if (has_csbiex)
7445 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7446
7447 csbi.cbSize = sizeof(csbi);
7448 csbi.srWindow.Right += 1;
7449 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007450 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7451 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007452 if (has_csbiex)
7453 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7454# endif
7455}
7456
7457 void
7458control_console_color_rgb(void)
7459{
7460 if (USE_VTP)
7461 set_console_color_rgb();
7462 else
7463 reset_console_color_rgb();
7464}
7465
7466 int
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007467use_vtp(void)
7468{
7469 return USE_VTP;
7470}
7471
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007472 int
7473is_term_win32(void)
7474{
7475 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7476}
7477
Bram Moolenaaraa5df7e2019-02-03 14:53:10 +01007478 int
7479has_vtp_working(void)
7480{
7481 return vtp_working;
7482}
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007483
Bram Moolenaar6902c0e2019-02-16 14:07:37 +01007484#endif
7485
Bram Moolenaard9ef1b82019-02-13 19:23:10 +01007486 int
7487has_conpty_working(void)
7488{
7489 return conpty_working;
7490}
7491
7492 int
7493is_conpty_stable(void)
7494{
7495 return conpty_stable;
7496}
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007497
Bram Moolenaarafde13b2019-04-28 19:46:49 +02007498#if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
Bram Moolenaar78d21da2019-02-17 15:00:52 +01007499 void
7500resize_console_buf(void)
7501{
7502 CONSOLE_SCREEN_BUFFER_INFO csbi;
7503 COORD coord;
7504 SMALL_RECT newsize;
7505
7506 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
7507 {
7508 coord.X = SRWIDTH(csbi.srWindow);
7509 coord.Y = SRHEIGHT(csbi.srWindow);
7510 SetConsoleScreenBufferSize(g_hConOut, coord);
7511
7512 newsize.Left = 0;
7513 newsize.Top = 0;
7514 newsize.Right = coord.X - 1;
7515 newsize.Bottom = coord.Y - 1;
7516 SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
7517
7518 SetConsoleScreenBufferSize(g_hConOut, coord);
7519 }
7520}
7521#endif