xref: /vim-8.2.3635/src/os_win32.c (revision 0526815c)
1 /* vi:set ts=8 sts=4 sw=4 noet:
2  *
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
13  * the console version only, so there is a lot of "#ifndef FEAT_GUI_MSWIN".
14  *
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 <[email protected]> wrote most of this.
20  * Roger Knobbe <[email protected]> did the initial port of Vim 3.0.
21  */
22 
23 #include "vim.h"
24 
25 #ifdef FEAT_MZSCHEME
26 # include "if_mzsch.h"
27 #endif
28 
29 #include <sys/types.h>
30 #include <signal.h>
31 #include <limits.h>
32 
33 // cproto fails on missing include files
34 #ifndef PROTO
35 # include <process.h>
36 # include <winternl.h>
37 #endif
38 
39 #undef chdir
40 #ifdef __GNUC__
41 # ifndef __MINGW32__
42 #  include <dirent.h>
43 # endif
44 #else
45 # include <direct.h>
46 #endif
47 
48 #ifndef PROTO
49 # if defined(FEAT_TITLE) && !defined(FEAT_GUI_MSWIN)
50 #  include <shellapi.h>
51 # endif
52 #endif
53 
54 #ifdef FEAT_JOB_CHANNEL
55 # include <tlhelp32.h>
56 #endif
57 
58 #ifdef __MINGW32__
59 # ifndef FROM_LEFT_1ST_BUTTON_PRESSED
60 #  define FROM_LEFT_1ST_BUTTON_PRESSED    0x0001
61 # endif
62 # ifndef RIGHTMOST_BUTTON_PRESSED
63 #  define RIGHTMOST_BUTTON_PRESSED	  0x0002
64 # endif
65 # ifndef FROM_LEFT_2ND_BUTTON_PRESSED
66 #  define FROM_LEFT_2ND_BUTTON_PRESSED    0x0004
67 # endif
68 # ifndef FROM_LEFT_3RD_BUTTON_PRESSED
69 #  define FROM_LEFT_3RD_BUTTON_PRESSED    0x0008
70 # endif
71 # ifndef FROM_LEFT_4TH_BUTTON_PRESSED
72 #  define FROM_LEFT_4TH_BUTTON_PRESSED    0x0010
73 # endif
74 
75 /*
76  * EventFlags
77  */
78 # ifndef MOUSE_MOVED
79 #  define MOUSE_MOVED   0x0001
80 # endif
81 # ifndef DOUBLE_CLICK
82 #  define DOUBLE_CLICK  0x0002
83 # endif
84 #endif
85 
86 // Record all output and all keyboard & mouse input
87 // #define MCH_WRITE_DUMP
88 
89 #ifdef MCH_WRITE_DUMP
90 FILE* fdDump = NULL;
91 #endif
92 
93 /*
94  * When generating prototypes for Win32 on Unix, these lines make the syntax
95  * errors disappear.  They do not need to be correct.
96  */
97 #ifdef PROTO
98 # define WINAPI
99 typedef char * LPCSTR;
100 typedef char * LPWSTR;
101 typedef int ACCESS_MASK;
102 typedef int BOOL;
103 typedef int COLORREF;
104 typedef int CONSOLE_CURSOR_INFO;
105 typedef int COORD;
106 typedef int DWORD;
107 typedef int HANDLE;
108 typedef int LPHANDLE;
109 typedef int HDC;
110 typedef int HFONT;
111 typedef int HICON;
112 typedef int HINSTANCE;
113 typedef int HWND;
114 typedef int INPUT_RECORD;
115 typedef int INT;
116 typedef int KEY_EVENT_RECORD;
117 typedef int LOGFONT;
118 typedef int LPBOOL;
119 typedef int LPCTSTR;
120 typedef int LPDWORD;
121 typedef int LPSTR;
122 typedef int LPTSTR;
123 typedef int LPVOID;
124 typedef int MOUSE_EVENT_RECORD;
125 typedef int PACL;
126 typedef int PDWORD;
127 typedef int PHANDLE;
128 typedef int PRINTDLG;
129 typedef int PSECURITY_DESCRIPTOR;
130 typedef int PSID;
131 typedef int SECURITY_INFORMATION;
132 typedef int SHORT;
133 typedef int SMALL_RECT;
134 typedef int TEXTMETRIC;
135 typedef int TOKEN_INFORMATION_CLASS;
136 typedef int TRUSTEE;
137 typedef int WORD;
138 typedef int WCHAR;
139 typedef void VOID;
140 typedef int BY_HANDLE_FILE_INFORMATION;
141 typedef int SE_OBJECT_TYPE;
142 typedef int PSNSECINFO;
143 typedef int PSNSECINFOW;
144 typedef int STARTUPINFO;
145 typedef int PROCESS_INFORMATION;
146 typedef int LPSECURITY_ATTRIBUTES;
147 # define __stdcall // empty
148 #endif
149 
150 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
151 // Win32 Console handles for input and output
152 static HANDLE g_hConIn  = INVALID_HANDLE_VALUE;
153 static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
154 
155 // Win32 Screen buffer,coordinate,console I/O information
156 static SMALL_RECT g_srScrollRegion;
157 static COORD	  g_coord;  // 0-based, but external coords are 1-based
158 
159 // The attribute of the screen when the editor was started
160 static WORD  g_attrDefault = 7;  // lightgray text on black background
161 static WORD  g_attrCurrent;
162 
163 static int g_fCBrkPressed = FALSE;  // set by ctrl-break interrupt
164 static int g_fCtrlCPressed = FALSE; // set when ctrl-C or ctrl-break detected
165 static int g_fForceExit = FALSE;    // set when forcefully exiting
166 
167 static void scroll(unsigned cLines);
168 static void set_scroll_region(unsigned left, unsigned top,
169 			      unsigned right, unsigned bottom);
170 static void set_scroll_region_tb(unsigned top, unsigned bottom);
171 static void set_scroll_region_lr(unsigned left, unsigned right);
172 static void insert_lines(unsigned cLines);
173 static void delete_lines(unsigned cLines);
174 static void gotoxy(unsigned x, unsigned y);
175 static void standout(void);
176 static int s_cursor_visible = TRUE;
177 static int did_create_conin = FALSE;
178 #endif
179 #ifdef FEAT_GUI_MSWIN
180 static int s_dont_use_vimrun = TRUE;
181 static int need_vimrun_warning = FALSE;
182 static char *vimrun_path = "vimrun ";
183 #endif
184 
185 static int win32_getattrs(char_u *name);
186 static int win32_setattrs(char_u *name, int attrs);
187 static int win32_set_archive(char_u *name);
188 
189 static int conpty_working = 0;
190 static int conpty_type = 0;
191 static int conpty_stable = 0;
192 static int conpty_fix_type = 0;
193 static void vtp_flag_init();
194 
195 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
196 static int vtp_working = 0;
197 static void vtp_init();
198 static void vtp_exit();
199 static void vtp_sgr_bulk(int arg);
200 static void vtp_sgr_bulks(int argc, int *argv);
201 
202 static int wt_working = 0;
203 static void wt_init();
204 
205 static guicolor_T save_console_bg_rgb;
206 static guicolor_T save_console_fg_rgb;
207 static guicolor_T store_console_bg_rgb;
208 static guicolor_T store_console_fg_rgb;
209 
210 static int g_color_index_bg = 0;
211 static int g_color_index_fg = 7;
212 
213 # ifdef FEAT_TERMGUICOLORS
214 static int default_console_color_bg = 0x000000; // black
215 static int default_console_color_fg = 0xc0c0c0; // white
216 # endif
217 
218 # ifdef FEAT_TERMGUICOLORS
219 #  define USE_VTP		(vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
220 #  define USE_WT		(wt_working)
221 # else
222 #  define USE_VTP		0
223 #  define USE_WT		0
224 # endif
225 
226 static void set_console_color_rgb(void);
227 static void reset_console_color_rgb(void);
228 static void restore_console_color_rgb(void);
229 #endif
230 
231 // This flag is newly created from Windows 10
232 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
233 # define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
234 #endif
235 
236 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
237 static int suppress_winsize = 1;	// don't fiddle with console
238 #endif
239 
240 static char_u *exe_path = NULL;
241 
242 static BOOL win8_or_later = FALSE;
243 
244 # if defined(__GNUC__) && !defined(__MINGW32__)  && !defined(__CYGWIN__)
245 #  define UChar UnicodeChar
246 # else
247 #  define UChar uChar.UnicodeChar
248 # endif
249 
250 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
251 // Dynamic loading for portability
252 typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
253 {
254     ULONG cbSize;
255     COORD dwSize;
256     COORD dwCursorPosition;
257     WORD wAttributes;
258     SMALL_RECT srWindow;
259     COORD dwMaximumWindowSize;
260     WORD wPopupAttributes;
261     BOOL bFullscreenSupported;
262     COLORREF ColorTable[16];
263 } DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
264 typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
265 static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
266 typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
267 static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
268 static BOOL has_csbiex = FALSE;
269 #endif
270 
271 /*
272  * Get version number including build number
273  */
274 typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
275 #define MAKE_VER(major, minor, build) \
276     (((major) << 24) | ((minor) << 16) | (build))
277 
278     static DWORD
get_build_number(void)279 get_build_number(void)
280 {
281     OSVERSIONINFOW	osver = {sizeof(OSVERSIONINFOW)};
282     HMODULE		hNtdll;
283     PfnRtlGetVersion	pRtlGetVersion;
284     DWORD		ver = MAKE_VER(0, 0, 0);
285 
286     hNtdll = GetModuleHandle("ntdll.dll");
287     if (hNtdll != NULL)
288     {
289 	pRtlGetVersion =
290 	    (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
291 	pRtlGetVersion(&osver);
292 	ver = MAKE_VER(min(osver.dwMajorVersion, 255),
293 		       min(osver.dwMinorVersion, 255),
294 		       min(osver.dwBuildNumber, 32767));
295     }
296     return ver;
297 }
298 
299 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
300     static BOOL
is_ambiwidth_event(INPUT_RECORD * ir)301 is_ambiwidth_event(
302     INPUT_RECORD *ir)
303 {
304     return ir->EventType == KEY_EVENT
305 		&& ir->Event.KeyEvent.bKeyDown
306 		&& ir->Event.KeyEvent.wRepeatCount == 1
307 		&& ir->Event.KeyEvent.wVirtualKeyCode == 0x12
308 		&& ir->Event.KeyEvent.wVirtualScanCode == 0x38
309 		&& ir->Event.KeyEvent.UChar == 0
310 		&& ir->Event.KeyEvent.dwControlKeyState == 2;
311 }
312 
313     static void
make_ambiwidth_event(INPUT_RECORD * down,INPUT_RECORD * up)314 make_ambiwidth_event(
315     INPUT_RECORD *down,
316     INPUT_RECORD *up)
317 {
318     down->Event.KeyEvent.wVirtualKeyCode = 0;
319     down->Event.KeyEvent.wVirtualScanCode = 0;
320     down->Event.KeyEvent.UChar = up->Event.KeyEvent.UChar;
321     down->Event.KeyEvent.dwControlKeyState = 0;
322 }
323 
324 /*
325  * Version of ReadConsoleInput() that works with IME.
326  * Works around problems on Windows 8.
327  */
328     static BOOL
read_console_input(HANDLE hInput,INPUT_RECORD * lpBuffer,DWORD nLength,LPDWORD lpEvents)329 read_console_input(
330     HANDLE	    hInput,
331     INPUT_RECORD    *lpBuffer,
332     DWORD	    nLength,
333     LPDWORD	    lpEvents)
334 {
335     enum
336     {
337 	IRSIZE = 10
338     };
339     static INPUT_RECORD s_irCache[IRSIZE];
340     static DWORD s_dwIndex = 0;
341     static DWORD s_dwMax = 0;
342     DWORD dwEvents;
343     int head;
344     int tail;
345     int i;
346     static INPUT_RECORD s_irPseudo;
347 
348     if (nLength == -2)
349 	return (s_dwMax > 0) ? TRUE : FALSE;
350 
351     if (!win8_or_later)
352     {
353 	if (nLength == -1)
354 	    return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
355 	return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
356     }
357 
358     if (s_dwMax == 0)
359     {
360 	if (!USE_WT && nLength == -1)
361 	    return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
362 	GetNumberOfConsoleInputEvents(hInput, &dwEvents);
363 	if (dwEvents == 0 && nLength == -1)
364 	    return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
365 	ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents);
366 	s_dwIndex = 0;
367 	s_dwMax = dwEvents;
368 	if (dwEvents == 0)
369 	{
370 	    *lpEvents = 0;
371 	    return TRUE;
372 	}
373 
374 	for (i = s_dwIndex; i < (int)s_dwMax - 1; ++i)
375 	    if (is_ambiwidth_event(&s_irCache[i]))
376 		make_ambiwidth_event(&s_irCache[i], &s_irCache[i + 1]);
377 
378 	if (s_dwMax > 1)
379 	{
380 	    head = 0;
381 	    tail = s_dwMax - 1;
382 	    while (head != tail)
383 	    {
384 		if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
385 			&& s_irCache[head + 1].EventType
386 						  == WINDOW_BUFFER_SIZE_EVENT)
387 		{
388 		    // Remove duplicate event to avoid flicker.
389 		    for (i = head; i < tail; ++i)
390 			s_irCache[i] = s_irCache[i + 1];
391 		    --tail;
392 		    continue;
393 		}
394 		head++;
395 	    }
396 	    s_dwMax = tail + 1;
397 	}
398     }
399 
400     if (s_irCache[s_dwIndex].EventType == KEY_EVENT)
401     {
402 	if (s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount > 1)
403 	{
404 	    s_irPseudo = s_irCache[s_dwIndex];
405 	    s_irPseudo.Event.KeyEvent.wRepeatCount = 1;
406 	    s_irCache[s_dwIndex].Event.KeyEvent.wRepeatCount--;
407 	    *lpBuffer = s_irPseudo;
408 	    *lpEvents = 1;
409 	    return TRUE;
410 	}
411     }
412 
413     *lpBuffer = s_irCache[s_dwIndex];
414     if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
415 	s_dwMax = 0;
416     *lpEvents = 1;
417     return TRUE;
418 }
419 
420 /*
421  * Version of PeekConsoleInput() that works with IME.
422  */
423     static BOOL
peek_console_input(HANDLE hInput,INPUT_RECORD * lpBuffer,DWORD nLength UNUSED,LPDWORD lpEvents)424 peek_console_input(
425     HANDLE	    hInput,
426     INPUT_RECORD    *lpBuffer,
427     DWORD	    nLength UNUSED,
428     LPDWORD	    lpEvents)
429 {
430     return read_console_input(hInput, lpBuffer, -1, lpEvents);
431 }
432 
433 # ifdef FEAT_CLIENTSERVER
434     static DWORD
msg_wait_for_multiple_objects(DWORD nCount,LPHANDLE pHandles,BOOL fWaitAll,DWORD dwMilliseconds,DWORD dwWakeMask)435 msg_wait_for_multiple_objects(
436     DWORD    nCount,
437     LPHANDLE pHandles,
438     BOOL     fWaitAll,
439     DWORD    dwMilliseconds,
440     DWORD    dwWakeMask)
441 {
442     if (read_console_input(NULL, NULL, -2, NULL))
443 	return WAIT_OBJECT_0;
444     return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
445 				     dwMilliseconds, dwWakeMask);
446 }
447 # endif
448 
449 # ifndef FEAT_CLIENTSERVER
450     static DWORD
wait_for_single_object(HANDLE hHandle,DWORD dwMilliseconds)451 wait_for_single_object(
452     HANDLE hHandle,
453     DWORD dwMilliseconds)
454 {
455     if (read_console_input(NULL, NULL, -2, NULL))
456 	return WAIT_OBJECT_0;
457     return WaitForSingleObject(hHandle, dwMilliseconds);
458 }
459 # endif
460 #endif
461 
462     static void
get_exe_name(void)463 get_exe_name(void)
464 {
465     // Maximum length of $PATH is more than MAXPATHL.  8191 is often mentioned
466     // as the maximum length that works (plus a NUL byte).
467 #define MAX_ENV_PATH_LEN 8192
468     char	temp[MAX_ENV_PATH_LEN];
469     char_u	*p;
470 
471     if (exe_name == NULL)
472     {
473 	// store the name of the executable, may be used for $VIM
474 	GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
475 	if (*temp != NUL)
476 	    exe_name = FullName_save((char_u *)temp, FALSE);
477     }
478 
479     if (exe_path == NULL && exe_name != NULL)
480     {
481 	exe_path = vim_strnsave(exe_name, gettail_sep(exe_name) - exe_name);
482 	if (exe_path != NULL)
483 	{
484 	    // Append our starting directory to $PATH, so that when doing
485 	    // "!xxd" it's found in our starting directory.  Needed because
486 	    // SearchPath() also looks there.
487 	    p = mch_getenv("PATH");
488 	    if (p == NULL
489 		       || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
490 	    {
491 		if (p == NULL || *p == NUL)
492 		    temp[0] = NUL;
493 		else
494 		{
495 		    STRCPY(temp, p);
496 		    STRCAT(temp, ";");
497 		}
498 		STRCAT(temp, exe_path);
499 		vim_setenv((char_u *)"PATH", (char_u *)temp);
500 	    }
501 	}
502     }
503 }
504 
505 /*
506  * Unescape characters in "p" that appear in "escaped".
507  */
508     static void
unescape_shellxquote(char_u * p,char_u * escaped)509 unescape_shellxquote(char_u *p, char_u *escaped)
510 {
511     int	    l = (int)STRLEN(p);
512     int	    n;
513 
514     while (*p != NUL)
515     {
516 	if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
517 	    mch_memmove(p, p + 1, l--);
518 	n = (*mb_ptr2len)(p);
519 	p += n;
520 	l -= n;
521     }
522 }
523 
524 /*
525  * Load library "name".
526  */
527     HINSTANCE
vimLoadLib(char * name)528 vimLoadLib(char *name)
529 {
530     HINSTANCE	dll = NULL;
531 
532     // No need to load any library when registering OLE.
533     if (found_register_arg)
534 	return dll;
535 
536     // NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
537     // vimLoadLib() recursively, which causes a stack overflow.
538     if (exe_path == NULL)
539 	get_exe_name();
540     if (exe_path != NULL)
541     {
542 	WCHAR old_dirw[MAXPATHL];
543 
544 	if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
545 	{
546 	    // Change directory to where the executable is, both to make
547 	    // sure we find a .dll there and to avoid looking for a .dll
548 	    // in the current directory.
549 	    SetCurrentDirectory((LPCSTR)exe_path);
550 	    dll = LoadLibrary(name);
551 	    SetCurrentDirectoryW(old_dirw);
552 	    return dll;
553 	}
554     }
555     return dll;
556 }
557 
558 #if defined(VIMDLL) || defined(PROTO)
559 /*
560  * Check if the current executable file is for the GUI subsystem.
561  */
562     int
mch_is_gui_executable(void)563 mch_is_gui_executable(void)
564 {
565     PBYTE		pImage = (PBYTE)GetModuleHandle(NULL);
566     PIMAGE_DOS_HEADER	pDOS = (PIMAGE_DOS_HEADER)pImage;
567     PIMAGE_NT_HEADERS	pPE;
568 
569     if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
570 	return FALSE;
571     pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
572     if (pPE->Signature != IMAGE_NT_SIGNATURE)
573 	return FALSE;
574     if (pPE->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
575 	return TRUE;
576     return FALSE;
577 }
578 #endif
579 
580 #if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
581 /*
582  * Get related information about 'funcname' which is imported by 'hInst'.
583  * If 'info' is 0, return the function address.
584  * If 'info' is 1, return the module name which the function is imported from.
585  */
586     static void *
get_imported_func_info(HINSTANCE hInst,const char * funcname,int info)587 get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
588 {
589     PBYTE			pImage = (PBYTE)hInst;
590     PIMAGE_DOS_HEADER		pDOS = (PIMAGE_DOS_HEADER)hInst;
591     PIMAGE_NT_HEADERS		pPE;
592     PIMAGE_IMPORT_DESCRIPTOR	pImpDesc;
593     PIMAGE_THUNK_DATA		pIAT;	    // Import Address Table
594     PIMAGE_THUNK_DATA		pINT;	    // Import Name Table
595     PIMAGE_IMPORT_BY_NAME	pImpName;
596 
597     if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
598 	return NULL;
599     pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
600     if (pPE->Signature != IMAGE_NT_SIGNATURE)
601 	return NULL;
602     pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
603 	    + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
604 							    .VirtualAddress);
605     for (; pImpDesc->FirstThunk; ++pImpDesc)
606     {
607 	if (!pImpDesc->OriginalFirstThunk)
608 	    continue;
609 	pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
610 	pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
611 	for (; pIAT->u1.Function; ++pIAT, ++pINT)
612 	{
613 	    if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
614 		continue;
615 	    pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
616 					+ (UINT_PTR)(pINT->u1.AddressOfData));
617 	    if (strcmp((char *)pImpName->Name, funcname) == 0)
618 	    {
619 		switch (info)
620 		{
621 		    case 0:
622 			return (void *)pIAT->u1.Function;
623 		    case 1:
624 			return (void *)(pImage + pImpDesc->Name);
625 		    default:
626 			return NULL;
627 		}
628 	    }
629 	}
630     }
631     return NULL;
632 }
633 
634 /*
635  * Get the module handle which 'funcname' in 'hInst' is imported from.
636  */
637     HINSTANCE
find_imported_module_by_funcname(HINSTANCE hInst,const char * funcname)638 find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
639 {
640     char    *modulename;
641 
642     modulename = (char *)get_imported_func_info(hInst, funcname, 1);
643     if (modulename != NULL)
644 	return GetModuleHandleA(modulename);
645     return NULL;
646 }
647 
648 /*
649  * Get the address of 'funcname' which is imported by 'hInst' DLL.
650  */
651     void *
get_dll_import_func(HINSTANCE hInst,const char * funcname)652 get_dll_import_func(HINSTANCE hInst, const char *funcname)
653 {
654     return get_imported_func_info(hInst, funcname, 0);
655 }
656 #endif
657 
658 #if defined(DYNAMIC_GETTEXT) || defined(PROTO)
659 # ifndef GETTEXT_DLL
660 #  define GETTEXT_DLL "libintl.dll"
661 #  define GETTEXT_DLL_ALT1 "libintl-8.dll"
662 #  define GETTEXT_DLL_ALT2 "intl.dll"
663 # endif
664 // Dummy functions
665 static char *null_libintl_gettext(const char *);
666 static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
667 static char *null_libintl_textdomain(const char *);
668 static char *null_libintl_bindtextdomain(const char *, const char *);
669 static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
670 static int null_libintl_wputenv(const wchar_t *);
671 
672 static HINSTANCE hLibintlDLL = NULL;
673 char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
674 char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
675 						= null_libintl_ngettext;
676 char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
677 char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
678 						= null_libintl_bindtextdomain;
679 char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
680 				       = null_libintl_bind_textdomain_codeset;
681 int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
682 
683     int
dyn_libintl_init(void)684 dyn_libintl_init(void)
685 {
686     int i;
687     static struct
688     {
689 	char	    *name;
690 	FARPROC	    *ptr;
691     } libintl_entry[] =
692     {
693 	{"gettext", (FARPROC*)&dyn_libintl_gettext},
694 	{"ngettext", (FARPROC*)&dyn_libintl_ngettext},
695 	{"textdomain", (FARPROC*)&dyn_libintl_textdomain},
696 	{"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
697 	{NULL, NULL}
698     };
699     HINSTANCE hmsvcrt;
700 
701     // No need to initialize twice.
702     if (hLibintlDLL != NULL)
703 	return 1;
704     // Load gettext library (libintl.dll and other names).
705     hLibintlDLL = vimLoadLib(GETTEXT_DLL);
706 # ifdef GETTEXT_DLL_ALT1
707     if (!hLibintlDLL)
708 	hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT1);
709 # endif
710 # ifdef GETTEXT_DLL_ALT2
711     if (!hLibintlDLL)
712 	hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT2);
713 # endif
714     if (!hLibintlDLL)
715     {
716 	if (p_verbose > 0)
717 	{
718 	    verbose_enter();
719 	    semsg(_(e_loadlib), GETTEXT_DLL, GetWin32Error());
720 	    verbose_leave();
721 	}
722 	return 0;
723     }
724     for (i = 0; libintl_entry[i].name != NULL
725 					 && libintl_entry[i].ptr != NULL; ++i)
726     {
727 	if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
728 					      libintl_entry[i].name)) == NULL)
729 	{
730 	    dyn_libintl_end();
731 	    if (p_verbose > 0)
732 	    {
733 		verbose_enter();
734 		semsg(_(e_loadfunc), libintl_entry[i].name);
735 		verbose_leave();
736 	    }
737 	    return 0;
738 	}
739     }
740 
741     // The bind_textdomain_codeset() function is optional.
742     dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
743 						   "bind_textdomain_codeset");
744     if (dyn_libintl_bind_textdomain_codeset == NULL)
745 	dyn_libintl_bind_textdomain_codeset =
746 					 null_libintl_bind_textdomain_codeset;
747 
748     // _wputenv() function for the libintl.dll is optional.
749     hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
750     if (hmsvcrt != NULL)
751 	dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
752     if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
753 	dyn_libintl_wputenv = null_libintl_wputenv;
754 
755     return 1;
756 }
757 
758     void
dyn_libintl_end(void)759 dyn_libintl_end(void)
760 {
761     if (hLibintlDLL)
762 	FreeLibrary(hLibintlDLL);
763     hLibintlDLL			= NULL;
764     dyn_libintl_gettext		= null_libintl_gettext;
765     dyn_libintl_ngettext	= null_libintl_ngettext;
766     dyn_libintl_textdomain	= null_libintl_textdomain;
767     dyn_libintl_bindtextdomain	= null_libintl_bindtextdomain;
768     dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
769     dyn_libintl_wputenv		= null_libintl_wputenv;
770 }
771 
772     static char *
null_libintl_gettext(const char * msgid)773 null_libintl_gettext(const char *msgid)
774 {
775     return (char*)msgid;
776 }
777 
778     static char *
null_libintl_ngettext(const char * msgid,const char * msgid_plural,unsigned long n)779 null_libintl_ngettext(
780 	const char *msgid,
781 	const char *msgid_plural,
782 	unsigned long n)
783 {
784     return (char *)(n == 1 ? msgid : msgid_plural);
785 }
786 
787     static char *
null_libintl_bindtextdomain(const char * domainname UNUSED,const char * dirname UNUSED)788 null_libintl_bindtextdomain(
789 	const char *domainname UNUSED,
790 	const char *dirname UNUSED)
791 {
792     return NULL;
793 }
794 
795     static char *
null_libintl_bind_textdomain_codeset(const char * domainname UNUSED,const char * codeset UNUSED)796 null_libintl_bind_textdomain_codeset(
797 	const char *domainname UNUSED,
798 	const char *codeset UNUSED)
799 {
800     return NULL;
801 }
802 
803     static char *
null_libintl_textdomain(const char * domainname UNUSED)804 null_libintl_textdomain(const char *domainname UNUSED)
805 {
806     return NULL;
807 }
808 
809     static int
null_libintl_wputenv(const wchar_t * envstring UNUSED)810 null_libintl_wputenv(const wchar_t *envstring UNUSED)
811 {
812     return 0;
813 }
814 
815 #endif // DYNAMIC_GETTEXT
816 
817 // This symbol is not defined in older versions of the SDK or Visual C++
818 
819 #ifndef VER_PLATFORM_WIN32_WINDOWS
820 # define VER_PLATFORM_WIN32_WINDOWS 1
821 #endif
822 
823 #ifdef HAVE_ACL
824 # ifndef PROTO
825 #  include <aclapi.h>
826 # endif
827 # ifndef PROTECTED_DACL_SECURITY_INFORMATION
828 #  define PROTECTED_DACL_SECURITY_INFORMATION	0x80000000L
829 # endif
830 #endif
831 
832 #ifdef HAVE_ACL
833 /*
834  * Enables or disables the specified privilege.
835  */
836     static BOOL
win32_enable_privilege(LPTSTR lpszPrivilege,BOOL bEnable)837 win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
838 {
839     BOOL		bResult;
840     LUID		luid;
841     HANDLE		hToken;
842     TOKEN_PRIVILEGES	tokenPrivileges;
843 
844     if (!OpenProcessToken(GetCurrentProcess(),
845 		TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
846 	return FALSE;
847 
848     if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
849     {
850 	CloseHandle(hToken);
851 	return FALSE;
852     }
853 
854     tokenPrivileges.PrivilegeCount	     = 1;
855     tokenPrivileges.Privileges[0].Luid       = luid;
856     tokenPrivileges.Privileges[0].Attributes = bEnable ?
857 						    SE_PRIVILEGE_ENABLED : 0;
858 
859     bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
860 	    sizeof(TOKEN_PRIVILEGES), NULL, NULL);
861 
862     CloseHandle(hToken);
863 
864     return bResult && GetLastError() == ERROR_SUCCESS;
865 }
866 #endif
867 
868 #ifdef _MSC_VER
869 // Suppress the deprecation warning for using GetVersionEx().
870 // It is needed for implementing "windowsversion()".
871 # pragma warning(push)
872 # pragma warning(disable: 4996)
873 #endif
874 /*
875  * Set "win8_or_later" and fill in "windowsVersion" if possible.
876  */
877     void
PlatformId(void)878 PlatformId(void)
879 {
880     static int done = FALSE;
881 
882     if (!done)
883     {
884 	OSVERSIONINFO ovi;
885 
886 	ovi.dwOSVersionInfoSize = sizeof(ovi);
887 	GetVersionEx(&ovi);
888 
889 #ifdef FEAT_EVAL
890 	vim_snprintf(windowsVersion, sizeof(windowsVersion), "%d.%d",
891 		(int)ovi.dwMajorVersion, (int)ovi.dwMinorVersion);
892 #endif
893 	if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
894 		|| ovi.dwMajorVersion > 6)
895 	    win8_or_later = TRUE;
896 
897 #ifdef HAVE_ACL
898 	// Enable privilege for getting or setting SACLs.
899 	win32_enable_privilege(SE_SECURITY_NAME, TRUE);
900 #endif
901 	done = TRUE;
902     }
903 }
904 #ifdef _MSC_VER
905 # pragma warning(pop)
906 #endif
907 
908 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
909 
910 # define SHIFT  (SHIFT_PRESSED)
911 # define CTRL   (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
912 # define ALT    (RIGHT_ALT_PRESSED  | LEFT_ALT_PRESSED)
913 # define ALT_GR (RIGHT_ALT_PRESSED  | LEFT_CTRL_PRESSED)
914 
915 
916 // When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
917 // We map function keys to their ANSI terminal equivalents, as produced
918 // by ANSI.SYS, for compatibility with the MS-DOS version of Vim.  Any
919 // ANSI key with a value >= '\300' is nonstandard, but provided anyway
920 // so that the user can have access to all SHIFT-, CTRL-, and ALT-
921 // combinations of function/arrow/etc keys.
922 
923 static const struct
924 {
925     WORD    wVirtKey;
926     BOOL    fAnsiKey;
927     int	    chAlone;
928     int	    chShift;
929     int	    chCtrl;
930     int	    chAlt;
931 } VirtKeyMap[] =
932 {
933 //    Key	ANSI	alone	shift	ctrl	    alt
934     { VK_ESCAPE,FALSE,	ESC,	ESC,	ESC,	    ESC,    },
935 
936     { VK_F1,	TRUE,	';',	'T',	'^',	    'h', },
937     { VK_F2,	TRUE,	'<',	'U',	'_',	    'i', },
938     { VK_F3,	TRUE,	'=',	'V',	'`',	    'j', },
939     { VK_F4,	TRUE,	'>',	'W',	'a',	    'k', },
940     { VK_F5,	TRUE,	'?',	'X',	'b',	    'l', },
941     { VK_F6,	TRUE,	'@',	'Y',	'c',	    'm', },
942     { VK_F7,	TRUE,	'A',	'Z',	'd',	    'n', },
943     { VK_F8,	TRUE,	'B',	'[',	'e',	    'o', },
944     { VK_F9,	TRUE,	'C',	'\\',	'f',	    'p', },
945     { VK_F10,	TRUE,	'D',	']',	'g',	    'q', },
946     { VK_F11,	TRUE,	'\205',	'\207',	'\211',	    '\213', },
947     { VK_F12,	TRUE,	'\206',	'\210',	'\212',	    '\214', },
948 
949     { VK_HOME,	TRUE,	'G',	'\302',	'w',	    '\303', },
950     { VK_UP,	TRUE,	'H',	'\304',	'\305',	    '\306', },
951     { VK_PRIOR,	TRUE,	'I',	'\307',	'\204',	    '\310', }, // PgUp
952     { VK_LEFT,	TRUE,	'K',	'\311',	's',	    '\312', },
953     { VK_RIGHT,	TRUE,	'M',	'\313',	't',	    '\314', },
954     { VK_END,	TRUE,	'O',	'\315',	'u',	    '\316', },
955     { VK_DOWN,	TRUE,	'P',	'\317',	'\320',	    '\321', },
956     { VK_NEXT,	TRUE,	'Q',	'\322',	'v',	    '\323', }, // PgDn
957     { VK_INSERT,TRUE,	'R',	'\324',	'\325',	    '\326', },
958     { VK_DELETE,TRUE,	'S',	'\327',	'\330',	    '\331', },
959     { VK_BACK,	TRUE,	'x',	'y',	'z',	    '{', }, // Backspace
960 
961     { VK_SNAPSHOT,TRUE,	0,	0,	0,	    'r', }, // PrtScrn
962 
963 # if 0
964     // Most people don't have F13-F20, but what the hell...
965     { VK_F13,	TRUE,	'\332',	'\333',	'\334',	    '\335', },
966     { VK_F14,	TRUE,	'\336',	'\337',	'\340',	    '\341', },
967     { VK_F15,	TRUE,	'\342',	'\343',	'\344',	    '\345', },
968     { VK_F16,	TRUE,	'\346',	'\347',	'\350',	    '\351', },
969     { VK_F17,	TRUE,	'\352',	'\353',	'\354',	    '\355', },
970     { VK_F18,	TRUE,	'\356',	'\357',	'\360',	    '\361', },
971     { VK_F19,	TRUE,	'\362',	'\363',	'\364',	    '\365', },
972     { VK_F20,	TRUE,	'\366',	'\367',	'\370',	    '\371', },
973 # endif
974     { VK_ADD,	TRUE,   'N',    'N',    'N',	'N',	}, // keyp '+'
975     { VK_SUBTRACT, TRUE,'J',	'J',    'J',	'J',	}, // keyp '-'
976  // { VK_DIVIDE,   TRUE,'N',	'N',    'N',	'N',	}, // keyp '/'
977     { VK_MULTIPLY, TRUE,'7',	'7',    '7',	'7',	}, // keyp '*'
978 
979     { VK_NUMPAD0,TRUE,  '\332',	'\333',	'\334',	    '\335', },
980     { VK_NUMPAD1,TRUE,  '\336',	'\337',	'\340',	    '\341', },
981     { VK_NUMPAD2,TRUE,  '\342',	'\343',	'\344',	    '\345', },
982     { VK_NUMPAD3,TRUE,  '\346',	'\347',	'\350',	    '\351', },
983     { VK_NUMPAD4,TRUE,  '\352',	'\353',	'\354',	    '\355', },
984     { VK_NUMPAD5,TRUE,  '\356',	'\357',	'\360',	    '\361', },
985     { VK_NUMPAD6,TRUE,  '\362',	'\363',	'\364',	    '\365', },
986     { VK_NUMPAD7,TRUE,  '\366',	'\367',	'\370',	    '\371', },
987     { VK_NUMPAD8,TRUE,  '\372',	'\373',	'\374',	    '\375', },
988     // Sorry, out of number space! <negri>
989     { VK_NUMPAD9,TRUE,  '\376',	'\377',	'|',	    '}', },
990 };
991 
992 
993 /*
994  * The return code indicates key code size.
995  */
996     static int
win32_kbd_patch_key(KEY_EVENT_RECORD * pker)997 win32_kbd_patch_key(
998     KEY_EVENT_RECORD *pker)
999 {
1000     UINT uMods = pker->dwControlKeyState;
1001     static int s_iIsDead = 0;
1002     static WORD awAnsiCode[2];
1003     static BYTE abKeystate[256];
1004 
1005 
1006     if (s_iIsDead == 2)
1007     {
1008 	pker->UChar = (WCHAR) awAnsiCode[1];
1009 	s_iIsDead = 0;
1010 	return 1;
1011     }
1012 
1013     if (pker->UChar != 0)
1014 	return 1;
1015 
1016     CLEAR_FIELD(abKeystate);
1017 
1018     // Clear any pending dead keys
1019     ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
1020 
1021     if (uMods & SHIFT_PRESSED)
1022 	abKeystate[VK_SHIFT] = 0x80;
1023     if (uMods & CAPSLOCK_ON)
1024 	abKeystate[VK_CAPITAL] = 1;
1025 
1026     if ((uMods & ALT_GR) == ALT_GR)
1027     {
1028 	abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
1029 	    abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
1030     }
1031 
1032     s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
1033 			abKeystate, awAnsiCode, 2, 0);
1034 
1035     if (s_iIsDead > 0)
1036 	pker->UChar = (WCHAR) awAnsiCode[0];
1037 
1038     return s_iIsDead;
1039 }
1040 
1041 static BOOL g_fJustGotFocus = FALSE;
1042 
1043 /*
1044  * Decode a KEY_EVENT into one or two keystrokes
1045  */
1046     static BOOL
decode_key_event(KEY_EVENT_RECORD * pker,WCHAR * pch,WCHAR * pch2,int * pmodifiers,BOOL fDoPost UNUSED)1047 decode_key_event(
1048     KEY_EVENT_RECORD	*pker,
1049     WCHAR		*pch,
1050     WCHAR		*pch2,
1051     int			*pmodifiers,
1052     BOOL		fDoPost UNUSED)
1053 {
1054     int i;
1055     const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1056 
1057     *pch = *pch2 = NUL;
1058     g_fJustGotFocus = FALSE;
1059 
1060     // ignore key up events
1061     if (!pker->bKeyDown)
1062 	return FALSE;
1063 
1064     // ignore some keystrokes
1065     switch (pker->wVirtualKeyCode)
1066     {
1067     // modifiers
1068     case VK_SHIFT:
1069     case VK_CONTROL:
1070     case VK_MENU:   // Alt key
1071 	return FALSE;
1072 
1073     default:
1074 	break;
1075     }
1076 
1077     // special cases
1078     if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
1079     {
1080 	// Ctrl-6 is Ctrl-^
1081 	if (pker->wVirtualKeyCode == '6')
1082 	{
1083 	    *pch = Ctrl_HAT;
1084 	    return TRUE;
1085 	}
1086 	// Ctrl-2 is Ctrl-@
1087 	else if (pker->wVirtualKeyCode == '2')
1088 	{
1089 	    *pch = NUL;
1090 	    return TRUE;
1091 	}
1092 	// Ctrl-- is Ctrl-_
1093 	else if (pker->wVirtualKeyCode == 0xBD)
1094 	{
1095 	    *pch = Ctrl__;
1096 	    return TRUE;
1097 	}
1098     }
1099 
1100     // Shift-TAB
1101     if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1102     {
1103 	*pch = K_NUL;
1104 	*pch2 = '\017';
1105 	return TRUE;
1106     }
1107 
1108     for (i = ARRAY_LENGTH(VirtKeyMap);  --i >= 0;  )
1109     {
1110 	if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1111 	{
1112 	    if (nModifs == 0)
1113 		*pch = VirtKeyMap[i].chAlone;
1114 	    else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1115 		*pch = VirtKeyMap[i].chShift;
1116 	    else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1117 		*pch = VirtKeyMap[i].chCtrl;
1118 	    else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1119 		*pch = VirtKeyMap[i].chAlt;
1120 
1121 	    if (*pch != 0)
1122 	    {
1123 		if (VirtKeyMap[i].fAnsiKey)
1124 		{
1125 		    *pch2 = *pch;
1126 		    *pch = K_NUL;
1127 		}
1128 
1129 		return TRUE;
1130 	    }
1131 	}
1132     }
1133 
1134     i = win32_kbd_patch_key(pker);
1135 
1136     if (i < 0)
1137 	*pch = NUL;
1138     else
1139     {
1140 	*pch = (i > 0) ? pker->UChar : NUL;
1141 
1142 	if (pmodifiers != NULL)
1143 	{
1144 	    // Pass on the ALT key as a modifier, but only when not combined
1145 	    // with CTRL (which is ALTGR).
1146 	    if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1147 		*pmodifiers |= MOD_MASK_ALT;
1148 
1149 	    // Pass on SHIFT only for special keys, because we don't know when
1150 	    // it's already included with the character.
1151 	    if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1152 		*pmodifiers |= MOD_MASK_SHIFT;
1153 
1154 	    // Pass on CTRL only for non-special keys, because we don't know
1155 	    // when it's already included with the character.  And not when
1156 	    // combined with ALT (which is ALTGR).
1157 	    if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1158 					       && *pch >= 0x20 && *pch < 0x80)
1159 		*pmodifiers |= MOD_MASK_CTRL;
1160 	}
1161     }
1162 
1163     return (*pch != NUL);
1164 }
1165 
1166 #endif // FEAT_GUI_MSWIN
1167 
1168 
1169 /*
1170  * For the GUI the mouse handling is in gui_w32.c.
1171  */
1172 #if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
1173     void
mch_setmouse(int on UNUSED)1174 mch_setmouse(int on UNUSED)
1175 {
1176 }
1177 #else
1178 static int g_fMouseAvail = FALSE;   // mouse present
1179 static int g_fMouseActive = FALSE;  // mouse enabled
1180 static int g_nMouseClick = -1;	    // mouse status
1181 static int g_xMouse;		    // mouse x coordinate
1182 static int g_yMouse;		    // mouse y coordinate
1183 static DWORD g_cmodein = 0;         // Original console input mode
1184 static DWORD g_cmodeout = 0;        // Original console output mode
1185 
1186 /*
1187  * Enable or disable mouse input
1188  */
1189     void
mch_setmouse(int on)1190 mch_setmouse(int on)
1191 {
1192     DWORD cmodein;
1193 
1194 # ifdef VIMDLL
1195     if (gui.in_use)
1196 	return;
1197 # endif
1198     if (!g_fMouseAvail)
1199 	return;
1200 
1201     g_fMouseActive = on;
1202     GetConsoleMode(g_hConIn, &cmodein);
1203 
1204     if (g_fMouseActive)
1205     {
1206 	cmodein |= ENABLE_MOUSE_INPUT;
1207 	cmodein &= ~ENABLE_QUICK_EDIT_MODE;
1208     }
1209     else
1210     {
1211 	cmodein &= ~ENABLE_MOUSE_INPUT;
1212 	cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
1213     }
1214 
1215     SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
1216 }
1217 
1218 
1219 # if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1220 /*
1221  * Called when 'balloonevalterm' changed.
1222  */
1223     void
mch_bevalterm_changed(void)1224 mch_bevalterm_changed(void)
1225 {
1226     mch_setmouse(g_fMouseActive);
1227 }
1228 # endif
1229 
1230 /*
1231  * Decode a MOUSE_EVENT.  If it's a valid event, return MOUSE_LEFT,
1232  * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1233  * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1234  * or a MOUSE_LEFT, _MIDDLE, or _RIGHT.  We encode the button type,
1235  * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1236  * and we return the mouse position in g_xMouse and g_yMouse.
1237  *
1238  * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1239  * MOUSE_DRAGs and one MOUSE_RELEASE.  MOUSE_RELEASE will be followed only
1240  * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1241  *
1242  * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1243  * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1244  *
1245  * Windows will send us MOUSE_MOVED notifications whenever the mouse
1246  * moves, even if it stays within the same character cell.  We ignore
1247  * all MOUSE_MOVED messages if the position hasn't really changed, and
1248  * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1249  * we're only interested in MOUSE_DRAG).
1250  *
1251  * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1252  * 2-button mouses by pressing the left & right buttons simultaneously.
1253  * In practice, it's almost impossible to click both at the same time,
1254  * so we need to delay a little.  Also, we tend not to get MOUSE_RELEASE
1255  * in such cases, if the user is clicking quickly.
1256  */
1257     static BOOL
decode_mouse_event(MOUSE_EVENT_RECORD * pmer)1258 decode_mouse_event(
1259     MOUSE_EVENT_RECORD *pmer)
1260 {
1261     static int s_nOldButton = -1;
1262     static int s_nOldMouseClick = -1;
1263     static int s_xOldMouse = -1;
1264     static int s_yOldMouse = -1;
1265     static linenr_T s_old_topline = 0;
1266 # ifdef FEAT_DIFF
1267     static int s_old_topfill = 0;
1268 # endif
1269     static int s_cClicks = 1;
1270     static BOOL s_fReleased = TRUE;
1271     static DWORD s_dwLastClickTime = 0;
1272     static BOOL s_fNextIsMiddle = FALSE;
1273 
1274     static DWORD cButtons = 0;	// number of buttons supported
1275 
1276     const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1277     const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1278     const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1279     const DWORD LEFT_RIGHT = LEFT | RIGHT;
1280 
1281     int nButton;
1282 
1283     if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1284 	cButtons = 2;
1285 
1286     if (!g_fMouseAvail || !g_fMouseActive)
1287     {
1288 	g_nMouseClick = -1;
1289 	return FALSE;
1290     }
1291 
1292     // get a spurious MOUSE_EVENT immediately after receiving focus; ignore
1293     if (g_fJustGotFocus)
1294     {
1295 	g_fJustGotFocus = FALSE;
1296 	return FALSE;
1297     }
1298 
1299     // unprocessed mouse click?
1300     if (g_nMouseClick != -1)
1301 	return TRUE;
1302 
1303     nButton = -1;
1304     g_xMouse = pmer->dwMousePosition.X;
1305     g_yMouse = pmer->dwMousePosition.Y;
1306 
1307     if (pmer->dwEventFlags == MOUSE_MOVED)
1308     {
1309 	// Ignore MOUSE_MOVED events if (x, y) hasn't changed.	(We get these
1310 	// events even when the mouse moves only within a char cell.)
1311 	if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1312 	    return FALSE;
1313     }
1314 
1315     // If no buttons are pressed...
1316     if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1317     {
1318 	nButton = MOUSE_RELEASE;
1319 
1320 	// If the last thing returned was MOUSE_RELEASE, ignore this
1321 	if (s_fReleased)
1322 	{
1323 # ifdef FEAT_BEVAL_TERM
1324 	    // do return mouse move events when we want them
1325 	    if (p_bevalterm)
1326 		nButton = MOUSE_DRAG;
1327 	    else
1328 # endif
1329 		return FALSE;
1330 	}
1331 
1332 	s_fReleased = TRUE;
1333     }
1334     else    // one or more buttons pressed
1335     {
1336 	// on a 2-button mouse, hold down left and right buttons
1337 	// simultaneously to get MIDDLE.
1338 
1339 	if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1340 	{
1341 	    DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1342 
1343 	    // if either left or right button only is pressed, see if the
1344 	    // next mouse event has both of them pressed
1345 	    if (dwLR == LEFT || dwLR == RIGHT)
1346 	    {
1347 		for (;;)
1348 		{
1349 		    // wait a short time for next input event
1350 		    if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1351 							     != WAIT_OBJECT_0)
1352 			break;
1353 		    else
1354 		    {
1355 			DWORD cRecords = 0;
1356 			INPUT_RECORD ir;
1357 			MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1358 
1359 			peek_console_input(g_hConIn, &ir, 1, &cRecords);
1360 
1361 			if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1362 				|| !(pmer2->dwButtonState & LEFT_RIGHT))
1363 			    break;
1364 			else
1365 			{
1366 			    if (pmer2->dwEventFlags != MOUSE_MOVED)
1367 			    {
1368 				read_console_input(g_hConIn, &ir, 1, &cRecords);
1369 
1370 				return decode_mouse_event(pmer2);
1371 			    }
1372 			    else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1373 				     s_yOldMouse == pmer2->dwMousePosition.Y)
1374 			    {
1375 				// throw away spurious mouse move
1376 				read_console_input(g_hConIn, &ir, 1, &cRecords);
1377 
1378 				// are there any more mouse events in queue?
1379 				peek_console_input(g_hConIn, &ir, 1, &cRecords);
1380 
1381 				if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1382 				    break;
1383 			    }
1384 			    else
1385 				break;
1386 			}
1387 		    }
1388 		}
1389 	    }
1390 	}
1391 
1392 	if (s_fNextIsMiddle)
1393 	{
1394 	    nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1395 		? MOUSE_DRAG : MOUSE_MIDDLE;
1396 	    s_fNextIsMiddle = FALSE;
1397 	}
1398 	else if (cButtons == 2	&&
1399 	    ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1400 	{
1401 	    nButton = MOUSE_MIDDLE;
1402 
1403 	    if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1404 	    {
1405 		s_fNextIsMiddle = TRUE;
1406 		nButton = MOUSE_RELEASE;
1407 	    }
1408 	}
1409 	else if ((pmer->dwButtonState & LEFT) == LEFT)
1410 	    nButton = MOUSE_LEFT;
1411 	else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1412 	    nButton = MOUSE_MIDDLE;
1413 	else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1414 	    nButton = MOUSE_RIGHT;
1415 
1416 	if (! s_fReleased && ! s_fNextIsMiddle
1417 		&& nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1418 	    return FALSE;
1419 
1420 	s_fReleased = s_fNextIsMiddle;
1421     }
1422 
1423     if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1424     {
1425 	// button pressed or released, without mouse moving
1426 	if (nButton != -1 && nButton != MOUSE_RELEASE)
1427 	{
1428 	    DWORD dwCurrentTime = GetTickCount();
1429 
1430 	    if (s_xOldMouse != g_xMouse
1431 		    || s_yOldMouse != g_yMouse
1432 		    || s_nOldButton != nButton
1433 		    || s_old_topline != curwin->w_topline
1434 # ifdef FEAT_DIFF
1435 		    || s_old_topfill != curwin->w_topfill
1436 # endif
1437 		    || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1438 	    {
1439 		s_cClicks = 1;
1440 	    }
1441 	    else if (++s_cClicks > 4)
1442 	    {
1443 		s_cClicks = 1;
1444 	    }
1445 
1446 	    s_dwLastClickTime = dwCurrentTime;
1447 	}
1448     }
1449     else if (pmer->dwEventFlags == MOUSE_MOVED)
1450     {
1451 	if (nButton != -1 && nButton != MOUSE_RELEASE)
1452 	    nButton = MOUSE_DRAG;
1453 
1454 	s_cClicks = 1;
1455     }
1456 
1457     if (nButton == -1)
1458 	return FALSE;
1459 
1460     if (nButton != MOUSE_RELEASE)
1461 	s_nOldButton = nButton;
1462 
1463     g_nMouseClick = nButton;
1464 
1465     if (pmer->dwControlKeyState & SHIFT_PRESSED)
1466 	g_nMouseClick |= MOUSE_SHIFT;
1467     if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1468 	g_nMouseClick |= MOUSE_CTRL;
1469     if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED  | LEFT_ALT_PRESSED))
1470 	g_nMouseClick |= MOUSE_ALT;
1471 
1472     if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1473 	SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1474 
1475     // only pass on interesting (i.e., different) mouse events
1476     if (s_xOldMouse == g_xMouse
1477 	    && s_yOldMouse == g_yMouse
1478 	    && s_nOldMouseClick == g_nMouseClick)
1479     {
1480 	g_nMouseClick = -1;
1481 	return FALSE;
1482     }
1483 
1484     s_xOldMouse = g_xMouse;
1485     s_yOldMouse = g_yMouse;
1486     s_old_topline = curwin->w_topline;
1487 # ifdef FEAT_DIFF
1488     s_old_topfill = curwin->w_topfill;
1489 # endif
1490     s_nOldMouseClick = g_nMouseClick;
1491 
1492     return TRUE;
1493 }
1494 
1495 #endif // FEAT_GUI_MSWIN
1496 
1497 
1498 #ifdef MCH_CURSOR_SHAPE
1499 /*
1500  * Set the shape of the cursor.
1501  * 'thickness' can be from 1 (thin) to 99 (block)
1502  */
1503     static void
mch_set_cursor_shape(int thickness)1504 mch_set_cursor_shape(int thickness)
1505 {
1506     CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1507     ConsoleCursorInfo.dwSize = thickness;
1508     ConsoleCursorInfo.bVisible = s_cursor_visible;
1509 
1510     SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1511     if (s_cursor_visible)
1512 	SetConsoleCursorPosition(g_hConOut, g_coord);
1513 }
1514 
1515     void
mch_update_cursor(void)1516 mch_update_cursor(void)
1517 {
1518     int		idx;
1519     int		thickness;
1520 
1521 # ifdef VIMDLL
1522     if (gui.in_use)
1523 	return;
1524 # endif
1525 
1526     /*
1527      * How the cursor is drawn depends on the current mode.
1528      */
1529     idx = get_shape_idx(FALSE);
1530 
1531     if (shape_table[idx].shape == SHAPE_BLOCK)
1532 	thickness = 99;	// 100 doesn't work on W95
1533     else
1534 	thickness = shape_table[idx].percentage;
1535     mch_set_cursor_shape(thickness);
1536 }
1537 #endif
1538 
1539 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
1540 /*
1541  * Handle FOCUS_EVENT.
1542  */
1543     static void
handle_focus_event(INPUT_RECORD ir)1544 handle_focus_event(INPUT_RECORD ir)
1545 {
1546     g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1547     ui_focus_change((int)g_fJustGotFocus);
1548 }
1549 
1550 static void ResizeConBuf(HANDLE hConsole, COORD coordScreen);
1551 
1552 /*
1553  * Wait until console input from keyboard or mouse is available,
1554  * or the time is up.
1555  * When "ignore_input" is TRUE even wait when input is available.
1556  * Return TRUE if something is available FALSE if not.
1557  */
1558     static int
WaitForChar(long msec,int ignore_input)1559 WaitForChar(long msec, int ignore_input)
1560 {
1561     DWORD	    dwNow = 0, dwEndTime = 0;
1562     INPUT_RECORD    ir;
1563     DWORD	    cRecords;
1564     WCHAR	    ch, ch2;
1565 # ifdef FEAT_TIMERS
1566     int		    tb_change_cnt = typebuf.tb_change_cnt;
1567 # endif
1568 
1569     if (msec > 0)
1570 	// Wait until the specified time has elapsed.
1571 	dwEndTime = GetTickCount() + msec;
1572     else if (msec < 0)
1573 	// Wait forever.
1574 	dwEndTime = INFINITE;
1575 
1576     // We need to loop until the end of the time period, because
1577     // we might get multiple unusable mouse events in that time.
1578     for (;;)
1579     {
1580 	// Only process messages when waiting.
1581 	if (msec != 0)
1582 	{
1583 # ifdef MESSAGE_QUEUE
1584 	    parse_queued_messages();
1585 # endif
1586 # ifdef FEAT_MZSCHEME
1587 	    mzvim_check_threads();
1588 # endif
1589 # ifdef FEAT_CLIENTSERVER
1590 	    serverProcessPendingMessages();
1591 # endif
1592 	}
1593 
1594 	if (g_nMouseClick != -1
1595 # ifdef FEAT_CLIENTSERVER
1596 		|| (!ignore_input && input_available())
1597 # endif
1598 	   )
1599 	    return TRUE;
1600 
1601 	if (msec > 0)
1602 	{
1603 	    // If the specified wait time has passed, return.  Beware that
1604 	    // GetTickCount() may wrap around (overflow).
1605 	    dwNow = GetTickCount();
1606 	    if ((int)(dwNow - dwEndTime) >= 0)
1607 		break;
1608 	}
1609 	if (msec != 0)
1610 	{
1611 	    DWORD dwWaitTime = dwEndTime - dwNow;
1612 
1613 	    // Don't wait for more than 11 msec to avoid dropping characters,
1614 	    // check channel while waiting for input and handle a callback from
1615 	    // 'balloonexpr'.
1616 	    if (dwWaitTime > 11)
1617 		dwWaitTime = 11;
1618 
1619 # ifdef FEAT_MZSCHEME
1620 	    if (mzthreads_allowed() && p_mzq > 0 && (long)dwWaitTime > p_mzq)
1621 		dwWaitTime = p_mzq; // don't wait longer than 'mzquantum'
1622 # endif
1623 # ifdef FEAT_TIMERS
1624 	    // When waiting very briefly don't trigger timers.
1625 	    if (dwWaitTime > 10)
1626 	    {
1627 		long	due_time;
1628 
1629 		// Trigger timers and then get the time in msec until the next
1630 		// one is due.  Wait up to that time.
1631 		due_time = check_due_timer();
1632 		if (typebuf.tb_change_cnt != tb_change_cnt)
1633 		{
1634 		    // timer may have used feedkeys().
1635 		    return FALSE;
1636 		}
1637 		if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1638 		    dwWaitTime = due_time;
1639 	    }
1640 # endif
1641 	    if (
1642 # ifdef FEAT_CLIENTSERVER
1643 		    // Wait for either an event on the console input or a
1644 		    // message in the client-server window.
1645 		    msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
1646 				  dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0
1647 # else
1648 		    wait_for_single_object(g_hConIn, dwWaitTime)
1649 							      != WAIT_OBJECT_0
1650 # endif
1651 		    )
1652 		continue;
1653 	}
1654 
1655 	cRecords = 0;
1656 	peek_console_input(g_hConIn, &ir, 1, &cRecords);
1657 
1658 # ifdef FEAT_MBYTE_IME
1659 	// May have to redraw if the cursor ends up in the wrong place.
1660 	// Only when not peeking.
1661 	if (State & CMDLINE && msg_row == Rows - 1 && msec != 0)
1662 	{
1663 	    CONSOLE_SCREEN_BUFFER_INFO csbi;
1664 
1665 	    if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1666 	    {
1667 		if (csbi.dwCursorPosition.Y != msg_row)
1668 		{
1669 		    // The screen is now messed up, must redraw the command
1670 		    // line and later all the windows.
1671 		    redraw_all_later(CLEAR);
1672 		    compute_cmdrow();
1673 		    redrawcmd();
1674 		}
1675 	    }
1676 	}
1677 # endif
1678 
1679 	if (cRecords > 0)
1680 	{
1681 	    if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1682 	    {
1683 # ifdef FEAT_MBYTE_IME
1684 		// Windows IME sends two '\n's with only one 'ENTER'.  First:
1685 		// wVirtualKeyCode == 13. second: wVirtualKeyCode == 0
1686 		if (ir.Event.KeyEvent.UChar == 0
1687 			&& ir.Event.KeyEvent.wVirtualKeyCode == 13)
1688 		{
1689 		    read_console_input(g_hConIn, &ir, 1, &cRecords);
1690 		    continue;
1691 		}
1692 # endif
1693 		if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1694 								 NULL, FALSE))
1695 		    return TRUE;
1696 	    }
1697 
1698 	    read_console_input(g_hConIn, &ir, 1, &cRecords);
1699 
1700 	    if (ir.EventType == FOCUS_EVENT)
1701 		handle_focus_event(ir);
1702 	    else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1703 	    {
1704 		COORD dwSize = ir.Event.WindowBufferSizeEvent.dwSize;
1705 
1706 		// Only call shell_resized() when the size actually changed to
1707 		// avoid the screen is cleared.
1708 		if (dwSize.X != Columns || dwSize.Y != Rows)
1709 		{
1710 		    CONSOLE_SCREEN_BUFFER_INFO csbi;
1711 		    GetConsoleScreenBufferInfo(g_hConOut, &csbi);
1712 		    dwSize.X = csbi.srWindow.Right - csbi.srWindow.Left + 1;
1713 		    dwSize.Y = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
1714 		    if (dwSize.X != Columns || dwSize.Y != Rows)
1715 		    {
1716 			ResizeConBuf(g_hConOut, dwSize);
1717 			shell_resized();
1718 		    }
1719 		}
1720 	    }
1721 	    else if (ir.EventType == MOUSE_EVENT
1722 		    && decode_mouse_event(&ir.Event.MouseEvent))
1723 		return TRUE;
1724 	}
1725 	else if (msec == 0)
1726 	    break;
1727     }
1728 
1729 # ifdef FEAT_CLIENTSERVER
1730     // Something might have been received while we were waiting.
1731     if (input_available())
1732 	return TRUE;
1733 # endif
1734 
1735     return FALSE;
1736 }
1737 
1738 /*
1739  * return non-zero if a character is available
1740  */
1741     int
mch_char_avail(void)1742 mch_char_avail(void)
1743 {
1744 # ifdef VIMDLL
1745     if (gui.in_use)
1746 	return TRUE;
1747 # endif
1748     return WaitForChar(0L, FALSE);
1749 }
1750 
1751 # if defined(FEAT_TERMINAL) || defined(PROTO)
1752 /*
1753  * Check for any pending input or messages.
1754  */
1755     int
mch_check_messages(void)1756 mch_check_messages(void)
1757 {
1758 #  ifdef VIMDLL
1759     if (gui.in_use)
1760 	return TRUE;
1761 #  endif
1762     return WaitForChar(0L, TRUE);
1763 }
1764 # endif
1765 
1766 /*
1767  * Create the console input.  Used when reading stdin doesn't work.
1768  */
1769     static void
create_conin(void)1770 create_conin(void)
1771 {
1772     g_hConIn =	CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1773 			FILE_SHARE_READ|FILE_SHARE_WRITE,
1774 			(LPSECURITY_ATTRIBUTES) NULL,
1775 			OPEN_EXISTING, 0, (HANDLE)NULL);
1776     did_create_conin = TRUE;
1777 }
1778 
1779 /*
1780  * Get a keystroke or a mouse event, use a blocking wait.
1781  */
1782     static WCHAR
tgetch(int * pmodifiers,WCHAR * pch2)1783 tgetch(int *pmodifiers, WCHAR *pch2)
1784 {
1785     WCHAR ch;
1786 
1787     for (;;)
1788     {
1789 	INPUT_RECORD ir;
1790 	DWORD cRecords = 0;
1791 
1792 # ifdef FEAT_CLIENTSERVER
1793 	(void)WaitForChar(-1L, FALSE);
1794 	if (input_available())
1795 	    return 0;
1796 	if (g_nMouseClick != -1)
1797 	    return 0;
1798 # endif
1799 	if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
1800 	{
1801 	    if (did_create_conin)
1802 		read_error_exit();
1803 	    create_conin();
1804 	    continue;
1805 	}
1806 
1807 	if (ir.EventType == KEY_EVENT)
1808 	{
1809 	    if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1810 							    pmodifiers, TRUE))
1811 		return ch;
1812 	}
1813 	else if (ir.EventType == FOCUS_EVENT)
1814 	    handle_focus_event(ir);
1815 	else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1816 	    shell_resized();
1817 	else if (ir.EventType == MOUSE_EVENT)
1818 	{
1819 	    if (decode_mouse_event(&ir.Event.MouseEvent))
1820 		return 0;
1821 	}
1822     }
1823 }
1824 #endif // !FEAT_GUI_MSWIN
1825 
1826 
1827 /*
1828  * mch_inchar(): low-level input function.
1829  * Get one or more characters from the keyboard or the mouse.
1830  * If time == 0, do not wait for characters.
1831  * If time == n, wait a short time for characters.
1832  * If time == -1, wait forever for characters.
1833  * Returns the number of characters read into buf.
1834  */
1835     int
mch_inchar(char_u * buf UNUSED,int maxlen UNUSED,long time UNUSED,int tb_change_cnt UNUSED)1836 mch_inchar(
1837     char_u	*buf UNUSED,
1838     int		maxlen UNUSED,
1839     long	time UNUSED,
1840     int		tb_change_cnt UNUSED)
1841 {
1842 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
1843 
1844     int		len;
1845     int		c;
1846 # ifdef VIMDLL
1847 // Extra space for maximum three CSIs. E.g. U+1B6DB -> 0xF0 0x9B 0x9B 0x9B.
1848 #  define TYPEAHEADSPACE    6
1849 # else
1850 #  define TYPEAHEADSPACE    0
1851 # endif
1852 # define TYPEAHEADLEN	    (20 + TYPEAHEADSPACE)
1853     static char_u   typeahead[TYPEAHEADLEN];	// previously typed bytes.
1854     static int	    typeaheadlen = 0;
1855 
1856 # ifdef VIMDLL
1857     if (gui.in_use)
1858 	return 0;
1859 # endif
1860 
1861     // First use any typeahead that was kept because "buf" was too small.
1862     if (typeaheadlen > 0)
1863 	goto theend;
1864 
1865     if (time >= 0)
1866     {
1867 	if (!WaitForChar(time, FALSE))     // no character available
1868 	    return 0;
1869     }
1870     else    // time == -1, wait forever
1871     {
1872 	mch_set_winsize_now();	// Allow winsize changes from now on
1873 
1874 	/*
1875 	 * If there is no character available within 2 seconds (default)
1876 	 * write the autoscript file to disk.  Or cause the CursorHold event
1877 	 * to be triggered.
1878 	 */
1879 	if (!WaitForChar(p_ut, FALSE))
1880 	{
1881 	    if (trigger_cursorhold() && maxlen >= 3)
1882 	    {
1883 		buf[0] = K_SPECIAL;
1884 		buf[1] = KS_EXTRA;
1885 		buf[2] = (int)KE_CURSORHOLD;
1886 		return 3;
1887 	    }
1888 	    before_blocking();
1889 	}
1890     }
1891 
1892     /*
1893      * Try to read as many characters as there are, until the buffer is full.
1894      */
1895 
1896     // we will get at least one key. Get more if they are available.
1897     g_fCBrkPressed = FALSE;
1898 
1899 # ifdef MCH_WRITE_DUMP
1900     if (fdDump)
1901 	fputc('[', fdDump);
1902 # endif
1903 
1904     // Keep looping until there is something in the typeahead buffer and more
1905     // to get and still room in the buffer (up to two bytes for a char and
1906     // three bytes for a modifier).
1907     while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
1908 		         && typeaheadlen + 5 + TYPEAHEADSPACE <= TYPEAHEADLEN)
1909     {
1910 	if (typebuf_changed(tb_change_cnt))
1911 	{
1912 	    // "buf" may be invalid now if a client put something in the
1913 	    // typeahead buffer and "buf" is in the typeahead buffer.
1914 	    typeaheadlen = 0;
1915 	    break;
1916 	}
1917 	if (g_nMouseClick != -1)
1918 	{
1919 # ifdef MCH_WRITE_DUMP
1920 	    if (fdDump)
1921 		fprintf(fdDump, "{%02x @ %d, %d}",
1922 			g_nMouseClick, g_xMouse, g_yMouse);
1923 # endif
1924 	    typeahead[typeaheadlen++] = ESC + 128;
1925 	    typeahead[typeaheadlen++] = 'M';
1926 	    typeahead[typeaheadlen++] = g_nMouseClick;
1927 	    typeahead[typeaheadlen++] = g_xMouse + '!';
1928 	    typeahead[typeaheadlen++] = g_yMouse + '!';
1929 	    g_nMouseClick = -1;
1930 	}
1931 	else
1932 	{
1933 	    WCHAR	ch2 = NUL;
1934 	    int		modifiers = 0;
1935 
1936 	    c = tgetch(&modifiers, &ch2);
1937 
1938 	    if (typebuf_changed(tb_change_cnt))
1939 	    {
1940 		// "buf" may be invalid now if a client put something in the
1941 		// typeahead buffer and "buf" is in the typeahead buffer.
1942 		typeaheadlen = 0;
1943 		break;
1944 	    }
1945 
1946 	    if (c == Ctrl_C && ctrl_c_interrupts)
1947 	    {
1948 # if defined(FEAT_CLIENTSERVER)
1949 		trash_input_buf();
1950 # endif
1951 		got_int = TRUE;
1952 	    }
1953 
1954 	    if (g_nMouseClick == -1)
1955 	    {
1956 		int	n = 1;
1957 
1958 		if (ch2 == NUL)
1959 		{
1960 		    int	    i, j;
1961 		    char_u  *p;
1962 		    WCHAR   ch[2];
1963 
1964 		    ch[0] = c;
1965 		    if (c >= 0xD800 && c <= 0xDBFF)	// High surrogate
1966 		    {
1967 			ch[1] = tgetch(&modifiers, &ch2);
1968 			n++;
1969 		    }
1970 		    p = utf16_to_enc(ch, &n);
1971 		    if (p != NULL)
1972 		    {
1973 			for (i = 0, j = 0; i < n; i++)
1974 			{
1975 			    typeahead[typeaheadlen + j++] = p[i];
1976 # ifdef VIMDLL
1977 			    if (p[i] == CSI)
1978 			    {
1979 				typeahead[typeaheadlen + j++] = KS_EXTRA;
1980 				typeahead[typeaheadlen + j++] = KE_CSI;
1981 			    }
1982 # endif
1983 			}
1984 			n = j;
1985 			vim_free(p);
1986 		    }
1987 		}
1988 		else
1989 		{
1990 		    typeahead[typeaheadlen] = c;
1991 # ifdef VIMDLL
1992 		    if (c == CSI)
1993 		    {
1994 			typeahead[typeaheadlen + 1] = KS_EXTRA;
1995 			typeahead[typeaheadlen + 2] = KE_CSI;
1996 			n = 3;
1997 		    }
1998 # endif
1999 		}
2000 		if (ch2 != NUL)
2001 		{
2002 		    if (c == K_NUL)
2003 		    {
2004 			switch (ch2)
2005 			{
2006 			case (WCHAR)'\324': // SHIFT+Insert
2007 			case (WCHAR)'\325': // CTRL+Insert
2008 			case (WCHAR)'\327': // SHIFT+Delete
2009 			case (WCHAR)'\330': // CTRL+Delete
2010 			    typeahead[typeaheadlen + n] = (char_u)ch2;
2011 			    n++;
2012 			    break;
2013 
2014 			default:
2015 			    typeahead[typeaheadlen + n] = 3;
2016 			    typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2017 			    n += 2;
2018 			    break;
2019 			}
2020 		    }
2021 		    else
2022 		    {
2023 			typeahead[typeaheadlen + n] = 3;
2024 			typeahead[typeaheadlen + n + 1] = (char_u)ch2;
2025 			n += 2;
2026 		    }
2027 		}
2028 
2029 		// Use the ALT key to set the 8th bit of the character
2030 		// when it's one byte, the 8th bit isn't set yet and not
2031 		// using a double-byte encoding (would become a lead
2032 		// byte).
2033 		if ((modifiers & MOD_MASK_ALT)
2034 			&& n == 1
2035 			&& (typeahead[typeaheadlen] & 0x80) == 0
2036 			&& !enc_dbcs
2037 		   )
2038 		{
2039 		    n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
2040 						    typeahead + typeaheadlen);
2041 		    modifiers &= ~MOD_MASK_ALT;
2042 		}
2043 
2044 		if (modifiers != 0)
2045 		{
2046 		    // Prepend modifiers to the character.
2047 		    mch_memmove(typeahead + typeaheadlen + 3,
2048 						 typeahead + typeaheadlen, n);
2049 		    typeahead[typeaheadlen++] = K_SPECIAL;
2050 		    typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
2051 		    typeahead[typeaheadlen++] =  modifiers;
2052 		}
2053 
2054 		typeaheadlen += n;
2055 
2056 # ifdef MCH_WRITE_DUMP
2057 		if (fdDump)
2058 		    fputc(c, fdDump);
2059 # endif
2060 	    }
2061 	}
2062     }
2063 
2064 # ifdef MCH_WRITE_DUMP
2065     if (fdDump)
2066     {
2067 	fputs("]\n", fdDump);
2068 	fflush(fdDump);
2069     }
2070 # endif
2071 
2072 theend:
2073     // Move typeahead to "buf", as much as fits.
2074     len = 0;
2075     while (len < maxlen && typeaheadlen > 0)
2076     {
2077 	buf[len++] = typeahead[0];
2078 	mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2079     }
2080 #  ifdef FEAT_JOB_CHANNEL
2081     if (len > 0)
2082     {
2083 	buf[len] = NUL;
2084 	ch_log(NULL, "raw key input: \"%s\"", buf);
2085     }
2086 #  endif
2087     return len;
2088 
2089 #else // FEAT_GUI_MSWIN
2090     return 0;
2091 #endif // FEAT_GUI_MSWIN
2092 }
2093 
2094 #ifndef PROTO
2095 # ifndef __MINGW32__
2096 #  include <shellapi.h>	// required for FindExecutable()
2097 # endif
2098 #endif
2099 
2100 /*
2101  * Return TRUE if "name" is an executable file, FALSE if not or it doesn't exist.
2102  * When returning TRUE and "path" is not NULL save the path and set "*path" to
2103  * the allocated memory.
2104  * TODO: Should somehow check if it's really executable.
2105  */
2106     static int
executable_file(char * name,char_u ** path)2107 executable_file(char *name, char_u **path)
2108 {
2109     if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
2110     {
2111 	if (path != NULL)
2112 	    *path = FullName_save((char_u *)name, FALSE);
2113 	return TRUE;
2114     }
2115     return FALSE;
2116 }
2117 
2118 /*
2119  * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2120  * If "use_path" is FALSE: Return TRUE if "name" exists.
2121  * If "use_pathext" is TRUE search "name" with extensions in $PATHEXT.
2122  * When returning TRUE and "path" is not NULL save the path and set "*path" to
2123  * the allocated memory.
2124  */
2125     static int
executable_exists(char * name,char_u ** path,int use_path,int use_pathext)2126 executable_exists(char *name, char_u **path, int use_path, int use_pathext)
2127 {
2128     // WinNT and later can use _MAX_PATH wide characters for a pathname, which
2129     // means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
2130     // UTF-8.
2131     char_u	buf[_MAX_PATH * 3];
2132     size_t	len = STRLEN(name);
2133     size_t	tmplen;
2134     char_u	*p, *e, *e2;
2135     char_u	*pathbuf = NULL;
2136     char_u	*pathext = NULL;
2137     char_u	*pathextbuf = NULL;
2138     char_u	*shname = NULL;
2139     int		noext = FALSE;
2140     int		retval = FALSE;
2141 
2142     if (len >= sizeof(buf))	// safety check
2143 	return FALSE;
2144 
2145     // Using the name directly when a Unix-shell like 'shell'.
2146     shname = gettail(p_sh);
2147     if (strstr((char *)shname, "sh") != NULL &&
2148 	!(strstr((char *)shname, "powershell") != NULL
2149 				    || strstr((char *)shname, "pwsh") != NULL))
2150 	noext = TRUE;
2151 
2152     if (use_pathext)
2153     {
2154 	pathext = mch_getenv("PATHEXT");
2155 	if (pathext == NULL)
2156 	    pathext = (char_u *)".com;.exe;.bat;.cmd";
2157 
2158 	if (noext == FALSE)
2159 	{
2160 	    /*
2161 	     * Loop over all extensions in $PATHEXT.
2162 	     * Check "name" ends with extension.
2163 	     */
2164 	    p = pathext;
2165 	    while (*p)
2166 	    {
2167 		if (p[0] == ';'
2168 			    || (p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2169 		{
2170 		    // Skip empty or single ".".
2171 		    ++p;
2172 		    continue;
2173 		}
2174 		e = vim_strchr(p, ';');
2175 		if (e == NULL)
2176 		    e = p + STRLEN(p);
2177 		tmplen = e - p;
2178 
2179 		if (_strnicoll(name + len - tmplen, (char *)p, tmplen) == 0)
2180 		{
2181 		    noext = TRUE;
2182 		    break;
2183 		}
2184 
2185 		p = e;
2186 	    }
2187 	}
2188     }
2189 
2190     // Prepend single "." to pathext, it's means no extension added.
2191     if (pathext == NULL)
2192 	pathext = (char_u *)".";
2193     else if (noext == TRUE)
2194     {
2195 	if (pathextbuf == NULL)
2196 	    pathextbuf = alloc(STRLEN(pathext) + 3);
2197 	if (pathextbuf == NULL)
2198 	{
2199 	    retval = FALSE;
2200 	    goto theend;
2201 	}
2202 	STRCPY(pathextbuf, ".;");
2203 	STRCAT(pathextbuf, pathext);
2204 	pathext = pathextbuf;
2205     }
2206 
2207     // Use $PATH when "use_path" is TRUE and "name" is basename.
2208     if (use_path && gettail((char_u *)name) == (char_u *)name)
2209     {
2210 	p = mch_getenv("PATH");
2211 	if (p != NULL)
2212 	{
2213 	    pathbuf = alloc(STRLEN(p) + 3);
2214 	    if (pathbuf == NULL)
2215 	    {
2216 		retval = FALSE;
2217 		goto theend;
2218 	    }
2219 	    STRCPY(pathbuf, ".;");
2220 	    STRCAT(pathbuf, p);
2221 	}
2222     }
2223 
2224     /*
2225      * Walk through all entries in $PATH to check if "name" exists there and
2226      * is an executable file.
2227      */
2228     p = (pathbuf != NULL) ? pathbuf : (char_u *)".";
2229     while (*p)
2230     {
2231 	if (*p == ';') // Skip empty entry
2232 	{
2233 	    ++p;
2234 	    continue;
2235 	}
2236 	e = vim_strchr(p, ';');
2237 	if (e == NULL)
2238 	    e = p + STRLEN(p);
2239 
2240 	if (e - p + len + 2 > sizeof(buf))
2241 	{
2242 	    retval = FALSE;
2243 	    goto theend;
2244 	}
2245 	// A single "." that means current dir.
2246 	if (e - p == 1 && *p == '.')
2247 	    STRCPY(buf, name);
2248 	else
2249 	{
2250 	    vim_strncpy(buf, p, e - p);
2251 	    add_pathsep(buf);
2252 	    STRCAT(buf, name);
2253 	}
2254 	tmplen = STRLEN(buf);
2255 
2256 	/*
2257 	 * Loop over all extensions in $PATHEXT.
2258 	 * Check "name" with extension added.
2259 	 */
2260 	p = pathext;
2261 	while (*p)
2262 	{
2263 	    if (*p == ';')
2264 	    {
2265 		// Skip empty entry
2266 		++p;
2267 		continue;
2268 	    }
2269 	    e2 = vim_strchr(p, (int)';');
2270 	    if (e2 == NULL)
2271 		e2 = p + STRLEN(p);
2272 
2273 	    if (!(p[0] == '.' && (p[1] == NUL || p[1] == ';')))
2274 	    {
2275 		// Not a single "." that means no extension is added.
2276 		if (e2 - p + tmplen + 1 > sizeof(buf))
2277 		{
2278 		    retval = FALSE;
2279 		    goto theend;
2280 		}
2281 		vim_strncpy(buf + tmplen, p, e2 - p);
2282 	    }
2283 	    if (executable_file((char *)buf, path))
2284 	    {
2285 		retval = TRUE;
2286 		goto theend;
2287 	    }
2288 
2289 	    p = e2;
2290 	}
2291 
2292 	p = e;
2293     }
2294 
2295 theend:
2296     free(pathextbuf);
2297     free(pathbuf);
2298     return retval;
2299 }
2300 
2301 #if (defined(__MINGW32__) && __MSVCRT_VERSION__ >= 0x800) || \
2302 	(defined(_MSC_VER) && _MSC_VER >= 1400)
2303 /*
2304  * Bad parameter handler.
2305  *
2306  * Certain MS CRT functions will intentionally crash when passed invalid
2307  * parameters to highlight possible security holes.  Setting this function as
2308  * the bad parameter handler will prevent the crash.
2309  *
2310  * In debug builds the parameters contain CRT information that might help track
2311  * down the source of a problem, but in non-debug builds the arguments are all
2312  * NULL/0.  Debug builds will also produce assert dialogs from the CRT, it is
2313  * worth allowing these to make debugging of issues easier.
2314  */
2315     static void
bad_param_handler(const wchar_t * expression,const wchar_t * function,const wchar_t * file,unsigned int line,uintptr_t pReserved)2316 bad_param_handler(const wchar_t *expression,
2317     const wchar_t *function,
2318     const wchar_t *file,
2319     unsigned int line,
2320     uintptr_t pReserved)
2321 {
2322 }
2323 
2324 # define SET_INVALID_PARAM_HANDLER \
2325 	((void)_set_invalid_parameter_handler(bad_param_handler))
2326 #else
2327 # define SET_INVALID_PARAM_HANDLER
2328 #endif
2329 
2330 #ifdef FEAT_GUI_MSWIN
2331 
2332 /*
2333  * GUI version of mch_init().
2334  */
2335     static void
mch_init_g(void)2336 mch_init_g(void)
2337 {
2338 # ifndef __MINGW32__
2339     extern int _fmode;
2340 # endif
2341 
2342     // Silently handle invalid parameters to CRT functions
2343     SET_INVALID_PARAM_HANDLER;
2344 
2345     // Let critical errors result in a failure, not in a dialog box.  Required
2346     // for the timestamp test to work on removed floppies.
2347     SetErrorMode(SEM_FAILCRITICALERRORS);
2348 
2349     _fmode = O_BINARY;		// we do our own CR-LF translation
2350 
2351     // Specify window size.  Is there a place to get the default from?
2352     Rows = 25;
2353     Columns = 80;
2354 
2355     // Look for 'vimrun'
2356     {
2357 	char_u vimrun_location[_MAX_PATH + 4];
2358 
2359 	// First try in same directory as gvim.exe
2360 	STRCPY(vimrun_location, exe_name);
2361 	STRCPY(gettail(vimrun_location), "vimrun.exe");
2362 	if (mch_getperm(vimrun_location) >= 0)
2363 	{
2364 	    if (*skiptowhite(vimrun_location) != NUL)
2365 	    {
2366 		// Enclose path with white space in double quotes.
2367 		mch_memmove(vimrun_location + 1, vimrun_location,
2368 						 STRLEN(vimrun_location) + 1);
2369 		*vimrun_location = '"';
2370 		STRCPY(gettail(vimrun_location), "vimrun\" ");
2371 	    }
2372 	    else
2373 		STRCPY(gettail(vimrun_location), "vimrun ");
2374 
2375 	    vimrun_path = (char *)vim_strsave(vimrun_location);
2376 	    s_dont_use_vimrun = FALSE;
2377 	}
2378 	else if (executable_exists("vimrun.exe", NULL, TRUE, FALSE))
2379 	    s_dont_use_vimrun = FALSE;
2380 
2381 	// Don't give the warning for a missing vimrun.exe right now, but only
2382 	// when vimrun was supposed to be used.  Don't bother people that do
2383 	// not need vimrun.exe.
2384 	if (s_dont_use_vimrun)
2385 	    need_vimrun_warning = TRUE;
2386     }
2387 
2388     /*
2389      * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2390      * Otherwise the default "findstr /n" is used.
2391      */
2392     if (!executable_exists("findstr.exe", NULL, TRUE, FALSE))
2393 	set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2394 
2395 # ifdef FEAT_CLIPBOARD
2396     win_clip_init();
2397 # endif
2398 
2399     vtp_flag_init();
2400 }
2401 
2402 
2403 #endif // FEAT_GUI_MSWIN
2404 
2405 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
2406 
2407 # define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2408 # define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2409 
2410 /*
2411  * ClearConsoleBuffer()
2412  * Description:
2413  *  Clears the entire contents of the console screen buffer, using the
2414  *  specified attribute.
2415  * Returns:
2416  *  TRUE on success
2417  */
2418     static BOOL
ClearConsoleBuffer(WORD wAttribute)2419 ClearConsoleBuffer(WORD wAttribute)
2420 {
2421     CONSOLE_SCREEN_BUFFER_INFO csbi;
2422     COORD coord;
2423     DWORD NumCells, dummy;
2424 
2425     if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2426 	return FALSE;
2427 
2428     NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2429     coord.X = 0;
2430     coord.Y = 0;
2431     if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2432 	    coord, &dummy))
2433 	return FALSE;
2434     if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2435 	    coord, &dummy))
2436 	return FALSE;
2437 
2438     return TRUE;
2439 }
2440 
2441 /*
2442  * FitConsoleWindow()
2443  * Description:
2444  *  Checks if the console window will fit within given buffer dimensions.
2445  *  Also, if requested, will shrink the window to fit.
2446  * Returns:
2447  *  TRUE on success
2448  */
2449     static BOOL
FitConsoleWindow(COORD dwBufferSize,BOOL WantAdjust)2450 FitConsoleWindow(
2451     COORD dwBufferSize,
2452     BOOL WantAdjust)
2453 {
2454     CONSOLE_SCREEN_BUFFER_INFO csbi;
2455     COORD dwWindowSize;
2456     BOOL NeedAdjust = FALSE;
2457 
2458     if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2459     {
2460 	/*
2461 	 * A buffer resize will fail if the current console window does
2462 	 * not lie completely within that buffer.  To avoid this, we might
2463 	 * have to move and possibly shrink the window.
2464 	 */
2465 	if (csbi.srWindow.Right >= dwBufferSize.X)
2466 	{
2467 	    dwWindowSize.X = SRWIDTH(csbi.srWindow);
2468 	    if (dwWindowSize.X > dwBufferSize.X)
2469 		dwWindowSize.X = dwBufferSize.X;
2470 	    csbi.srWindow.Right = dwBufferSize.X - 1;
2471 	    csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2472 	    NeedAdjust = TRUE;
2473 	}
2474 	if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2475 	{
2476 	    dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2477 	    if (dwWindowSize.Y > dwBufferSize.Y)
2478 		dwWindowSize.Y = dwBufferSize.Y;
2479 	    csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2480 	    csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2481 	    NeedAdjust = TRUE;
2482 	}
2483 	if (NeedAdjust && WantAdjust)
2484 	{
2485 	    if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2486 		return FALSE;
2487 	}
2488 	return TRUE;
2489     }
2490 
2491     return FALSE;
2492 }
2493 
2494 typedef struct ConsoleBufferStruct
2495 {
2496     BOOL			IsValid;
2497     CONSOLE_SCREEN_BUFFER_INFO	Info;
2498     PCHAR_INFO			Buffer;
2499     COORD			BufferSize;
2500     PSMALL_RECT			Regions;
2501     int				NumRegions;
2502 } ConsoleBuffer;
2503 
2504 /*
2505  * SaveConsoleBuffer()
2506  * Description:
2507  *  Saves important information about the console buffer, including the
2508  *  actual buffer contents.  The saved information is suitable for later
2509  *  restoration by RestoreConsoleBuffer().
2510  * Returns:
2511  *  TRUE if all information was saved; FALSE otherwise
2512  *  If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2513  */
2514     static BOOL
SaveConsoleBuffer(ConsoleBuffer * cb)2515 SaveConsoleBuffer(
2516     ConsoleBuffer *cb)
2517 {
2518     DWORD NumCells;
2519     COORD BufferCoord;
2520     SMALL_RECT ReadRegion;
2521     WORD Y, Y_incr;
2522     int i, numregions;
2523 
2524     if (cb == NULL)
2525 	return FALSE;
2526 
2527     if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2528     {
2529 	cb->IsValid = FALSE;
2530 	return FALSE;
2531     }
2532     cb->IsValid = TRUE;
2533 
2534     /*
2535      * Allocate a buffer large enough to hold the entire console screen
2536      * buffer.  If this ConsoleBuffer structure has already been initialized
2537      * with a buffer of the correct size, then just use that one.
2538      */
2539     if (!cb->IsValid || cb->Buffer == NULL ||
2540 	    cb->BufferSize.X != cb->Info.dwSize.X ||
2541 	    cb->BufferSize.Y != cb->Info.dwSize.Y)
2542     {
2543 	cb->BufferSize.X = cb->Info.dwSize.X;
2544 	cb->BufferSize.Y = cb->Info.dwSize.Y;
2545 	NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2546 	vim_free(cb->Buffer);
2547 	cb->Buffer = ALLOC_MULT(CHAR_INFO, NumCells);
2548 	if (cb->Buffer == NULL)
2549 	    return FALSE;
2550     }
2551 
2552     /*
2553      * We will now copy the console screen buffer into our buffer.
2554      * ReadConsoleOutput() seems to be limited as far as how much you
2555      * can read at a time.  Empirically, this number seems to be about
2556      * 12000 cells (rows * columns).  Start at position (0, 0) and copy
2557      * in chunks until it is all copied.  The chunks will all have the
2558      * same horizontal characteristics, so initialize them now.  The
2559      * height of each chunk will be (12000 / width).
2560      */
2561     BufferCoord.X = 0;
2562     ReadRegion.Left = 0;
2563     ReadRegion.Right = cb->Info.dwSize.X - 1;
2564     Y_incr = 12000 / cb->Info.dwSize.X;
2565 
2566     numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2567     if (cb->Regions == NULL || numregions != cb->NumRegions)
2568     {
2569 	cb->NumRegions = numregions;
2570 	vim_free(cb->Regions);
2571 	cb->Regions = ALLOC_MULT(SMALL_RECT, cb->NumRegions);
2572 	if (cb->Regions == NULL)
2573 	{
2574 	    VIM_CLEAR(cb->Buffer);
2575 	    return FALSE;
2576 	}
2577     }
2578 
2579     for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
2580     {
2581 	/*
2582 	 * Read into position (0, Y) in our buffer.
2583 	 */
2584 	BufferCoord.Y = Y;
2585 	/*
2586 	 * Read the region whose top left corner is (0, Y) and whose bottom
2587 	 * right corner is (width - 1, Y + Y_incr - 1).  This should define
2588 	 * a region of size width by Y_incr.  Don't worry if this region is
2589 	 * too large for the remaining buffer; it will be cropped.
2590 	 */
2591 	ReadRegion.Top = Y;
2592 	ReadRegion.Bottom = Y + Y_incr - 1;
2593 	if (!ReadConsoleOutputW(g_hConOut,	// output handle
2594 		cb->Buffer,			// our buffer
2595 		cb->BufferSize,			// dimensions of our buffer
2596 		BufferCoord,			// offset in our buffer
2597 		&ReadRegion))			// region to save
2598 	{
2599 	    VIM_CLEAR(cb->Buffer);
2600 	    VIM_CLEAR(cb->Regions);
2601 	    return FALSE;
2602 	}
2603 	cb->Regions[i] = ReadRegion;
2604     }
2605 
2606     return TRUE;
2607 }
2608 
2609 /*
2610  * RestoreConsoleBuffer()
2611  * Description:
2612  *  Restores important information about the console buffer, including the
2613  *  actual buffer contents, if desired.  The information to restore is in
2614  *  the same format used by SaveConsoleBuffer().
2615  * Returns:
2616  *  TRUE on success
2617  */
2618     static BOOL
RestoreConsoleBuffer(ConsoleBuffer * cb,BOOL RestoreScreen)2619 RestoreConsoleBuffer(
2620     ConsoleBuffer   *cb,
2621     BOOL	    RestoreScreen)
2622 {
2623     COORD BufferCoord;
2624     SMALL_RECT WriteRegion;
2625     int i;
2626 
2627     if (cb == NULL || !cb->IsValid)
2628 	return FALSE;
2629 
2630     /*
2631      * Before restoring the buffer contents, clear the current buffer, and
2632      * restore the cursor position and window information.  Doing this now
2633      * prevents old buffer contents from "flashing" onto the screen.
2634      */
2635     if (RestoreScreen)
2636 	ClearConsoleBuffer(cb->Info.wAttributes);
2637 
2638     FitConsoleWindow(cb->Info.dwSize, TRUE);
2639     if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2640 	return FALSE;
2641     if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2642 	return FALSE;
2643 
2644     if (!RestoreScreen)
2645     {
2646 	/*
2647 	 * No need to restore the screen buffer contents, so we're done.
2648 	 */
2649 	return TRUE;
2650     }
2651 
2652     if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2653 	return FALSE;
2654     if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2655 	return FALSE;
2656 
2657     /*
2658      * Restore the screen buffer contents.
2659      */
2660     if (cb->Buffer != NULL)
2661     {
2662 	for (i = 0; i < cb->NumRegions; i++)
2663 	{
2664 	    BufferCoord.X = cb->Regions[i].Left;
2665 	    BufferCoord.Y = cb->Regions[i].Top;
2666 	    WriteRegion = cb->Regions[i];
2667 	    if (!WriteConsoleOutputW(g_hConOut,	// output handle
2668 			cb->Buffer,		// our buffer
2669 			cb->BufferSize,		// dimensions of our buffer
2670 			BufferCoord,		// offset in our buffer
2671 			&WriteRegion))		// region to restore
2672 		return FALSE;
2673 	}
2674     }
2675 
2676     return TRUE;
2677 }
2678 
2679 # define FEAT_RESTORE_ORIG_SCREEN
2680 # ifdef FEAT_RESTORE_ORIG_SCREEN
2681 static ConsoleBuffer g_cbOrig = { 0 };
2682 # endif
2683 static ConsoleBuffer g_cbNonTermcap = { 0 };
2684 static ConsoleBuffer g_cbTermcap = { 0 };
2685 
2686 # ifdef FEAT_TITLE
2687 char g_szOrigTitle[256] = { 0 };
2688 HWND g_hWnd = NULL;	// also used in os_mswin.c
2689 static HICON g_hOrigIconSmall = NULL;
2690 static HICON g_hOrigIcon = NULL;
2691 static HICON g_hVimIcon = NULL;
2692 static BOOL g_fCanChangeIcon = FALSE;
2693 
2694 // ICON* are not defined in VC++ 4.0
2695 #  ifndef ICON_SMALL
2696 #   define ICON_SMALL 0
2697 #  endif
2698 #  ifndef ICON_BIG
2699 #   define ICON_BIG 1
2700 #  endif
2701 /*
2702  * GetConsoleIcon()
2703  * Description:
2704  *  Attempts to retrieve the small icon and/or the big icon currently in
2705  *  use by a given window.
2706  * Returns:
2707  *  TRUE on success
2708  */
2709     static BOOL
GetConsoleIcon(HWND hWnd,HICON * phIconSmall,HICON * phIcon)2710 GetConsoleIcon(
2711     HWND	hWnd,
2712     HICON	*phIconSmall,
2713     HICON	*phIcon)
2714 {
2715     if (hWnd == NULL)
2716 	return FALSE;
2717 
2718     if (phIconSmall != NULL)
2719 	*phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2720 					       (WPARAM)ICON_SMALL, (LPARAM)0);
2721     if (phIcon != NULL)
2722 	*phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2723 						 (WPARAM)ICON_BIG, (LPARAM)0);
2724     return TRUE;
2725 }
2726 
2727 /*
2728  * SetConsoleIcon()
2729  * Description:
2730  *  Attempts to change the small icon and/or the big icon currently in
2731  *  use by a given window.
2732  * Returns:
2733  *  TRUE on success
2734  */
2735     static BOOL
SetConsoleIcon(HWND hWnd,HICON hIconSmall,HICON hIcon)2736 SetConsoleIcon(
2737     HWND    hWnd,
2738     HICON   hIconSmall,
2739     HICON   hIcon)
2740 {
2741     if (hWnd == NULL)
2742 	return FALSE;
2743 
2744     if (hIconSmall != NULL)
2745 	SendMessage(hWnd, WM_SETICON,
2746 			    (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
2747     if (hIcon != NULL)
2748 	SendMessage(hWnd, WM_SETICON,
2749 			    (WPARAM)ICON_BIG, (LPARAM) hIcon);
2750     return TRUE;
2751 }
2752 
2753 /*
2754  * SaveConsoleTitleAndIcon()
2755  * Description:
2756  *  Saves the current console window title in g_szOrigTitle, for later
2757  *  restoration.  Also, attempts to obtain a handle to the console window,
2758  *  and use it to save the small and big icons currently in use by the
2759  *  console window.  This is not always possible on some versions of Windows;
2760  *  nor is it possible when running Vim remotely using Telnet (since the
2761  *  console window the user sees is owned by a remote process).
2762  */
2763     static void
SaveConsoleTitleAndIcon(void)2764 SaveConsoleTitleAndIcon(void)
2765 {
2766     // Save the original title.
2767     if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2768 	return;
2769 
2770     /*
2771      * Obtain a handle to the console window using GetConsoleWindow() from
2772      * KERNEL32.DLL; we need to handle in order to change the window icon.
2773      * This function only exists on NT-based Windows, starting with Windows
2774      * 2000.  On older operating systems, we can't change the window icon
2775      * anyway.
2776      */
2777     g_hWnd = GetConsoleWindow();
2778     if (g_hWnd == NULL)
2779 	return;
2780 
2781     // Save the original console window icon.
2782     GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2783     if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2784 	return;
2785 
2786     // Extract the first icon contained in the Vim executable.
2787     if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2788 	g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
2789     if (g_hVimIcon != NULL)
2790 	g_fCanChangeIcon = TRUE;
2791 }
2792 # endif
2793 
2794 static int g_fWindInitCalled = FALSE;
2795 static int g_fTermcapMode = FALSE;
2796 static CONSOLE_CURSOR_INFO g_cci;
2797 
2798 /*
2799  * non-GUI version of mch_init().
2800  */
2801     static void
mch_init_c(void)2802 mch_init_c(void)
2803 {
2804 # ifndef FEAT_RESTORE_ORIG_SCREEN
2805     CONSOLE_SCREEN_BUFFER_INFO csbi;
2806 # endif
2807 # ifndef __MINGW32__
2808     extern int _fmode;
2809 # endif
2810 
2811     // Silently handle invalid parameters to CRT functions
2812     SET_INVALID_PARAM_HANDLER;
2813 
2814     // Let critical errors result in a failure, not in a dialog box.  Required
2815     // for the timestamp test to work on removed floppies.
2816     SetErrorMode(SEM_FAILCRITICALERRORS);
2817 
2818     _fmode = O_BINARY;		// we do our own CR-LF translation
2819     out_flush();
2820 
2821     // Obtain handles for the standard Console I/O devices
2822     if (read_cmd_fd == 0)
2823 	g_hConIn =  GetStdHandle(STD_INPUT_HANDLE);
2824     else
2825 	create_conin();
2826     g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2827 
2828 # ifdef FEAT_RESTORE_ORIG_SCREEN
2829     // Save the initial console buffer for later restoration
2830     SaveConsoleBuffer(&g_cbOrig);
2831     g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2832 # else
2833     // Get current text attributes
2834     GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2835     g_attrCurrent = g_attrDefault = csbi.wAttributes;
2836 # endif
2837     if (cterm_normal_fg_color == 0)
2838 	cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2839     if (cterm_normal_bg_color == 0)
2840 	cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2841 
2842     // Fg and Bg color index number at startup
2843     g_color_index_fg = g_attrDefault & 0xf;
2844     g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2845 
2846     // set termcap codes to current text attributes
2847     update_tcap(g_attrCurrent);
2848 
2849     GetConsoleCursorInfo(g_hConOut, &g_cci);
2850     GetConsoleMode(g_hConIn,  &g_cmodein);
2851     GetConsoleMode(g_hConOut, &g_cmodeout);
2852 
2853 # ifdef FEAT_TITLE
2854     SaveConsoleTitleAndIcon();
2855     /*
2856      * Set both the small and big icons of the console window to Vim's icon.
2857      * Note that Vim presently only has one size of icon (32x32), but it
2858      * automatically gets scaled down to 16x16 when setting the small icon.
2859      */
2860     if (g_fCanChangeIcon)
2861 	SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2862 # endif
2863 
2864     ui_get_shellsize();
2865 
2866 # ifdef MCH_WRITE_DUMP
2867     fdDump = fopen("dump", "wt");
2868 
2869     if (fdDump)
2870     {
2871 	time_t t;
2872 
2873 	time(&t);
2874 	fputs(ctime(&t), fdDump);
2875 	fflush(fdDump);
2876     }
2877 # endif
2878 
2879     g_fWindInitCalled = TRUE;
2880 
2881     g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2882 
2883 # ifdef FEAT_CLIPBOARD
2884     win_clip_init();
2885 # endif
2886 
2887     vtp_flag_init();
2888     vtp_init();
2889     wt_init();
2890 }
2891 
2892 /*
2893  * non-GUI version of mch_exit().
2894  * Shut down and exit with status `r'
2895  * Careful: mch_exit() may be called before mch_init()!
2896  */
2897     static void
mch_exit_c(int r)2898 mch_exit_c(int r)
2899 {
2900     exiting = TRUE;
2901 
2902     vtp_exit();
2903 
2904     stoptermcap();
2905     if (g_fWindInitCalled)
2906 	settmode(TMODE_COOK);
2907 
2908     ml_close_all(TRUE);		// remove all memfiles
2909 
2910     if (g_fWindInitCalled)
2911     {
2912 # ifdef FEAT_TITLE
2913 	mch_restore_title(SAVE_RESTORE_BOTH);
2914 	/*
2915 	 * Restore both the small and big icons of the console window to
2916 	 * what they were at startup.  Don't do this when the window is
2917 	 * closed, Vim would hang here.
2918 	 */
2919 	if (g_fCanChangeIcon && !g_fForceExit)
2920 	    SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2921 # endif
2922 
2923 # ifdef MCH_WRITE_DUMP
2924 	if (fdDump)
2925 	{
2926 	    time_t t;
2927 
2928 	    time(&t);
2929 	    fputs(ctime(&t), fdDump);
2930 	    fclose(fdDump);
2931 	}
2932 	fdDump = NULL;
2933 # endif
2934     }
2935 
2936     SetConsoleCursorInfo(g_hConOut, &g_cci);
2937     SetConsoleMode(g_hConIn,  g_cmodein | ENABLE_EXTENDED_FLAGS);
2938     SetConsoleMode(g_hConOut, g_cmodeout);
2939 
2940 # ifdef DYNAMIC_GETTEXT
2941     dyn_libintl_end();
2942 # endif
2943 
2944     exit(r);
2945 }
2946 #endif // !FEAT_GUI_MSWIN
2947 
2948     void
mch_init(void)2949 mch_init(void)
2950 {
2951 #ifdef VIMDLL
2952     if (gui.starting)
2953 	mch_init_g();
2954     else
2955 	mch_init_c();
2956 #elif defined(FEAT_GUI_MSWIN)
2957     mch_init_g();
2958 #else
2959     mch_init_c();
2960 #endif
2961 }
2962 
2963     void
mch_exit(int r)2964 mch_exit(int r)
2965 {
2966 #ifdef FEAT_NETBEANS_INTG
2967     netbeans_send_disconnect();
2968 #endif
2969 
2970 #ifdef VIMDLL
2971     if (gui.in_use || gui.starting)
2972 	mch_exit_g(r);
2973     else
2974 	mch_exit_c(r);
2975 #elif defined(FEAT_GUI_MSWIN)
2976     mch_exit_g(r);
2977 #else
2978     mch_exit_c(r);
2979 #endif
2980 }
2981 
2982 /*
2983  * Do we have an interactive window?
2984  */
2985     int
mch_check_win(int argc UNUSED,char ** argv UNUSED)2986 mch_check_win(
2987     int argc UNUSED,
2988     char **argv UNUSED)
2989 {
2990     get_exe_name();
2991 
2992 #if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
2993     return OK;	    // GUI always has a tty
2994 #else
2995 # ifdef VIMDLL
2996     if (gui.in_use)
2997 	return OK;
2998 # endif
2999     if (isatty(1))
3000 	return OK;
3001     return FAIL;
3002 #endif
3003 }
3004 
3005 /*
3006  * Set the case of the file name, if it already exists.
3007  * When "len" is > 0, also expand short to long filenames.
3008  */
3009     void
fname_case(char_u * name,int len)3010 fname_case(
3011     char_u	*name,
3012     int		len)
3013 {
3014     int	    flen;
3015     WCHAR   *p;
3016     WCHAR   buf[_MAX_PATH + 1];
3017 
3018     flen = (int)STRLEN(name);
3019     if (flen == 0)
3020 	return;
3021 
3022     slash_adjust(name);
3023 
3024     p = enc_to_utf16(name, NULL);
3025     if (p == NULL)
3026 	return;
3027 
3028     if (GetLongPathNameW(p, buf, _MAX_PATH))
3029     {
3030 	char_u	*q = utf16_to_enc(buf, NULL);
3031 
3032 	if (q != NULL)
3033 	{
3034 	    if (len > 0 || flen >= (int)STRLEN(q))
3035 		vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
3036 	    vim_free(q);
3037 	}
3038     }
3039     vim_free(p);
3040 }
3041 
3042 
3043 /*
3044  * Insert user name in s[len].
3045  */
3046     int
mch_get_user_name(char_u * s,int len)3047 mch_get_user_name(
3048     char_u  *s,
3049     int	    len)
3050 {
3051     WCHAR wszUserName[256 + 1];	// UNLEN is 256
3052     DWORD wcch = ARRAY_LENGTH(wszUserName);
3053 
3054     if (GetUserNameW(wszUserName, &wcch))
3055     {
3056 	char_u  *p = utf16_to_enc(wszUserName, NULL);
3057 
3058 	if (p != NULL)
3059 	{
3060 	    vim_strncpy(s, p, len - 1);
3061 	    vim_free(p);
3062 	    return OK;
3063 	}
3064     }
3065     s[0] = NUL;
3066     return FAIL;
3067 }
3068 
3069 
3070 /*
3071  * Insert host name in s[len].
3072  */
3073     void
mch_get_host_name(char_u * s,int len)3074 mch_get_host_name(
3075     char_u	*s,
3076     int		len)
3077 {
3078     WCHAR wszHostName[256 + 1];
3079     DWORD wcch = ARRAY_LENGTH(wszHostName);
3080 
3081     if (GetComputerNameW(wszHostName, &wcch))
3082     {
3083 	char_u  *p = utf16_to_enc(wszHostName, NULL);
3084 
3085 	if (p != NULL)
3086 	{
3087 	    vim_strncpy(s, p, len - 1);
3088 	    vim_free(p);
3089 	    return;
3090 	}
3091     }
3092 }
3093 
3094 
3095 /*
3096  * return process ID
3097  */
3098     long
mch_get_pid(void)3099 mch_get_pid(void)
3100 {
3101     return (long)GetCurrentProcessId();
3102 }
3103 
3104 /*
3105  * return TRUE if process "pid" is still running
3106  */
3107     int
mch_process_running(long pid)3108 mch_process_running(long pid)
3109 {
3110     HANDLE  hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, 0, (DWORD)pid);
3111     DWORD   status = 0;
3112     int	    ret = FALSE;
3113 
3114     if (hProcess == NULL)
3115 	return FALSE;  // might not have access
3116     if (GetExitCodeProcess(hProcess, &status) )
3117 	ret = status == STILL_ACTIVE;
3118     CloseHandle(hProcess);
3119     return ret;
3120 }
3121 
3122 /*
3123  * Get name of current directory into buffer 'buf' of length 'len' bytes.
3124  * Return OK for success, FAIL for failure.
3125  */
3126     int
mch_dirname(char_u * buf,int len)3127 mch_dirname(
3128     char_u	*buf,
3129     int		len)
3130 {
3131     WCHAR   wbuf[_MAX_PATH + 1];
3132 
3133     /*
3134      * Originally this was:
3135      *    return (getcwd(buf, len) != NULL ? OK : FAIL);
3136      * But the Win32s known bug list says that getcwd() doesn't work
3137      * so use the Win32 system call instead. <Negri>
3138      */
3139     if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3140     {
3141 	WCHAR   wcbuf[_MAX_PATH + 1];
3142 	char_u  *p = NULL;
3143 
3144 	if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
3145 	{
3146 	    p = utf16_to_enc(wcbuf, NULL);
3147 	    if (STRLEN(p) >= (size_t)len)
3148 	    {
3149 		// long path name is too long, fall back to short one
3150 		vim_free(p);
3151 		p = NULL;
3152 	    }
3153 	}
3154 	if (p == NULL)
3155 	    p = utf16_to_enc(wbuf, NULL);
3156 
3157 	if (p != NULL)
3158 	{
3159 	    vim_strncpy(buf, p, len - 1);
3160 	    vim_free(p);
3161 	    return OK;
3162 	}
3163     }
3164     return FAIL;
3165 }
3166 
3167 /*
3168  * Get file permissions for "name".
3169  * Return mode_t or -1 for error.
3170  */
3171     long
mch_getperm(char_u * name)3172 mch_getperm(char_u *name)
3173 {
3174     stat_T	st;
3175     int		n;
3176 
3177     n = mch_stat((char *)name, &st);
3178     return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
3179 }
3180 
3181 
3182 /*
3183  * Set file permission for "name" to "perm".
3184  *
3185  * Return FAIL for failure, OK otherwise.
3186  */
3187     int
mch_setperm(char_u * name,long perm)3188 mch_setperm(char_u *name, long perm)
3189 {
3190     long	n;
3191     WCHAR	*p;
3192 
3193     p = enc_to_utf16(name, NULL);
3194     if (p == NULL)
3195 	return FAIL;
3196 
3197     n = _wchmod(p, perm);
3198     vim_free(p);
3199     if (n == -1)
3200 	return FAIL;
3201 
3202     win32_set_archive(name);
3203 
3204     return OK;
3205 }
3206 
3207 /*
3208  * Set hidden flag for "name".
3209  */
3210     void
mch_hide(char_u * name)3211 mch_hide(char_u *name)
3212 {
3213     int attrs = win32_getattrs(name);
3214     if (attrs == -1)
3215 	return;
3216 
3217     attrs |= FILE_ATTRIBUTE_HIDDEN;
3218     win32_setattrs(name, attrs);
3219 }
3220 
3221 /*
3222  * Return TRUE if file "name" exists and is hidden.
3223  */
3224     int
mch_ishidden(char_u * name)3225 mch_ishidden(char_u *name)
3226 {
3227     int f = win32_getattrs(name);
3228 
3229     if (f == -1)
3230 	return FALSE;		    // file does not exist at all
3231 
3232     return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3233 }
3234 
3235 /*
3236  * return TRUE if "name" is a directory
3237  * return FALSE if "name" is not a directory or upon error
3238  */
3239     int
mch_isdir(char_u * name)3240 mch_isdir(char_u *name)
3241 {
3242     int f = win32_getattrs(name);
3243 
3244     if (f == -1)
3245 	return FALSE;		    // file does not exist at all
3246 
3247     return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3248 }
3249 
3250 /*
3251  * return TRUE if "name" is a directory, NOT a symlink to a directory
3252  * return FALSE if "name" is not a directory
3253  * return FALSE for error
3254  */
3255     int
mch_isrealdir(char_u * name)3256 mch_isrealdir(char_u *name)
3257 {
3258     return mch_isdir(name) && !mch_is_symbolic_link(name);
3259 }
3260 
3261 /*
3262  * Create directory "name".
3263  * Return 0 on success, -1 on error.
3264  */
3265     int
mch_mkdir(char_u * name)3266 mch_mkdir(char_u *name)
3267 {
3268     WCHAR   *p;
3269     int	    retval;
3270 
3271     p = enc_to_utf16(name, NULL);
3272     if (p == NULL)
3273 	return -1;
3274     retval = _wmkdir(p);
3275     vim_free(p);
3276     return retval;
3277 }
3278 
3279 /*
3280  * Delete directory "name".
3281  * Return 0 on success, -1 on error.
3282  */
3283     int
mch_rmdir(char_u * name)3284 mch_rmdir(char_u *name)
3285 {
3286     WCHAR   *p;
3287     int	    retval;
3288 
3289     p = enc_to_utf16(name, NULL);
3290     if (p == NULL)
3291 	return -1;
3292     retval = _wrmdir(p);
3293     vim_free(p);
3294     return retval;
3295 }
3296 
3297 /*
3298  * Return TRUE if file "fname" has more than one link.
3299  */
3300     int
mch_is_hard_link(char_u * fname)3301 mch_is_hard_link(char_u *fname)
3302 {
3303     BY_HANDLE_FILE_INFORMATION info;
3304 
3305     return win32_fileinfo(fname, &info) == FILEINFO_OK
3306 						   && info.nNumberOfLinks > 1;
3307 }
3308 
3309 /*
3310  * Return TRUE if "name" is a symbolic link (or a junction).
3311  */
3312     int
mch_is_symbolic_link(char_u * name)3313 mch_is_symbolic_link(char_u *name)
3314 {
3315     HANDLE		hFind;
3316     int			res = FALSE;
3317     DWORD		fileFlags = 0, reparseTag = 0;
3318     WCHAR		*wn;
3319     WIN32_FIND_DATAW	findDataW;
3320 
3321     wn = enc_to_utf16(name, NULL);
3322     if (wn == NULL)
3323 	return FALSE;
3324 
3325     hFind = FindFirstFileW(wn, &findDataW);
3326     vim_free(wn);
3327     if (hFind != INVALID_HANDLE_VALUE)
3328     {
3329 	fileFlags = findDataW.dwFileAttributes;
3330 	reparseTag = findDataW.dwReserved0;
3331 	FindClose(hFind);
3332     }
3333 
3334     if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3335 	    && (reparseTag == IO_REPARSE_TAG_SYMLINK
3336 		|| reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
3337 	res = TRUE;
3338 
3339     return res;
3340 }
3341 
3342 /*
3343  * Return TRUE if file "fname" has more than one link or if it is a symbolic
3344  * link.
3345  */
3346     int
mch_is_linked(char_u * fname)3347 mch_is_linked(char_u *fname)
3348 {
3349     if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3350 	return TRUE;
3351     return FALSE;
3352 }
3353 
3354 /*
3355  * Get the by-handle-file-information for "fname".
3356  * Returns FILEINFO_OK when OK.
3357  * Returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3358  * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3359  * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3360  */
3361     int
win32_fileinfo(char_u * fname,BY_HANDLE_FILE_INFORMATION * info)3362 win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3363 {
3364     HANDLE	hFile;
3365     int		res = FILEINFO_READ_FAIL;
3366     WCHAR	*wn;
3367 
3368     wn = enc_to_utf16(fname, NULL);
3369     if (wn == NULL)
3370 	return FILEINFO_ENC_FAIL;
3371 
3372     hFile = CreateFileW(wn,	// file name
3373 	    GENERIC_READ,	// access mode
3374 	    FILE_SHARE_READ | FILE_SHARE_WRITE,	// share mode
3375 	    NULL,		// security descriptor
3376 	    OPEN_EXISTING,	// creation disposition
3377 	    FILE_FLAG_BACKUP_SEMANTICS,	// file attributes
3378 	    NULL);		// handle to template file
3379     vim_free(wn);
3380 
3381     if (hFile != INVALID_HANDLE_VALUE)
3382     {
3383 	if (GetFileInformationByHandle(hFile, info) != 0)
3384 	    res = FILEINFO_OK;
3385 	else
3386 	    res = FILEINFO_INFO_FAIL;
3387 	CloseHandle(hFile);
3388     }
3389 
3390     return res;
3391 }
3392 
3393 /*
3394  * get file attributes for `name'
3395  * -1 : error
3396  * else FILE_ATTRIBUTE_* defined in winnt.h
3397  */
3398     static int
win32_getattrs(char_u * name)3399 win32_getattrs(char_u *name)
3400 {
3401     int		attr;
3402     WCHAR	*p;
3403 
3404     p = enc_to_utf16(name, NULL);
3405     if (p == NULL)
3406 	return INVALID_FILE_ATTRIBUTES;
3407 
3408     attr = GetFileAttributesW(p);
3409     vim_free(p);
3410 
3411     return attr;
3412 }
3413 
3414 /*
3415  * set file attributes for `name' to `attrs'
3416  *
3417  * return -1 for failure, 0 otherwise
3418  */
3419     static int
win32_setattrs(char_u * name,int attrs)3420 win32_setattrs(char_u *name, int attrs)
3421 {
3422     int	    res;
3423     WCHAR   *p;
3424 
3425     p = enc_to_utf16(name, NULL);
3426     if (p == NULL)
3427 	return -1;
3428 
3429     res = SetFileAttributesW(p, attrs);
3430     vim_free(p);
3431 
3432     return res ? 0 : -1;
3433 }
3434 
3435 /*
3436  * Set archive flag for "name".
3437  */
3438     static int
win32_set_archive(char_u * name)3439 win32_set_archive(char_u *name)
3440 {
3441     int attrs = win32_getattrs(name);
3442     if (attrs == -1)
3443 	return -1;
3444 
3445     attrs |= FILE_ATTRIBUTE_ARCHIVE;
3446     return win32_setattrs(name, attrs);
3447 }
3448 
3449 /*
3450  * Return TRUE if file or directory "name" is writable (not readonly).
3451  * Strange semantics of Win32: a readonly directory is writable, but you can't
3452  * delete a file.  Let's say this means it is writable.
3453  */
3454     int
mch_writable(char_u * name)3455 mch_writable(char_u *name)
3456 {
3457     int attrs = win32_getattrs(name);
3458 
3459     return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3460 			  || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
3461 }
3462 
3463 /*
3464  * Return TRUE if "name" can be executed, FALSE if not.
3465  * If "use_path" is FALSE only check if "name" is executable.
3466  * When returning TRUE and "path" is not NULL save the path and set "*path" to
3467  * the allocated memory.
3468  */
3469     int
mch_can_exe(char_u * name,char_u ** path,int use_path)3470 mch_can_exe(char_u *name, char_u **path, int use_path)
3471 {
3472     return executable_exists((char *)name, path, TRUE, TRUE);
3473 }
3474 
3475 /*
3476  * Check what "name" is:
3477  * NODE_NORMAL: file or directory (or doesn't exist)
3478  * NODE_WRITABLE: writable device, socket, fifo, etc.
3479  * NODE_OTHER: non-writable things
3480  */
3481     int
mch_nodetype(char_u * name)3482 mch_nodetype(char_u *name)
3483 {
3484     HANDLE	hFile;
3485     int		type;
3486     WCHAR	*wn;
3487 
3488     // We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3489     // read from it later will cause Vim to hang.  Thus return NODE_WRITABLE
3490     // here.
3491     if (STRNCMP(name, "\\\\.\\", 4) == 0)
3492 	return NODE_WRITABLE;
3493 
3494     wn = enc_to_utf16(name, NULL);
3495     if (wn == NULL)
3496 	return NODE_NORMAL;
3497 
3498     hFile = CreateFileW(wn,	    // file name
3499 	    GENERIC_WRITE,	    // access mode
3500 	    0,			    // share mode
3501 	    NULL,		    // security descriptor
3502 	    OPEN_EXISTING,	    // creation disposition
3503 	    0,			    // file attributes
3504 	    NULL);		    // handle to template file
3505     vim_free(wn);
3506     if (hFile == INVALID_HANDLE_VALUE)
3507 	return NODE_NORMAL;
3508 
3509     type = GetFileType(hFile);
3510     CloseHandle(hFile);
3511     if (type == FILE_TYPE_CHAR)
3512 	return NODE_WRITABLE;
3513     if (type == FILE_TYPE_DISK)
3514 	return NODE_NORMAL;
3515     return NODE_OTHER;
3516 }
3517 
3518 #ifdef HAVE_ACL
3519 struct my_acl
3520 {
3521     PSECURITY_DESCRIPTOR    pSecurityDescriptor;
3522     PSID		    pSidOwner;
3523     PSID		    pSidGroup;
3524     PACL		    pDacl;
3525     PACL		    pSacl;
3526 };
3527 #endif
3528 
3529 /*
3530  * Return a pointer to the ACL of file "fname" in allocated memory.
3531  * Return NULL if the ACL is not available for whatever reason.
3532  */
3533     vim_acl_T
mch_get_acl(char_u * fname)3534 mch_get_acl(char_u *fname)
3535 {
3536 #ifndef HAVE_ACL
3537     return (vim_acl_T)NULL;
3538 #else
3539     struct my_acl   *p = NULL;
3540     DWORD   err;
3541 
3542     p = ALLOC_CLEAR_ONE(struct my_acl);
3543     if (p != NULL)
3544     {
3545 	WCHAR	*wn;
3546 
3547 	wn = enc_to_utf16(fname, NULL);
3548 	if (wn == NULL)
3549 	{
3550 	    vim_free(p);
3551 	    return NULL;
3552 	}
3553 
3554 	// Try to retrieve the entire security descriptor.
3555 	err = GetNamedSecurityInfoW(
3556 		wn,			// Abstract filename
3557 		SE_FILE_OBJECT,		// File Object
3558 		OWNER_SECURITY_INFORMATION |
3559 		GROUP_SECURITY_INFORMATION |
3560 		DACL_SECURITY_INFORMATION |
3561 		SACL_SECURITY_INFORMATION,
3562 		&p->pSidOwner,		// Ownership information.
3563 		&p->pSidGroup,		// Group membership.
3564 		&p->pDacl,		// Discretionary information.
3565 		&p->pSacl,		// For auditing purposes.
3566 		&p->pSecurityDescriptor);
3567 	if (err == ERROR_ACCESS_DENIED ||
3568 		err == ERROR_PRIVILEGE_NOT_HELD)
3569 	{
3570 	    // Retrieve only DACL.
3571 	    (void)GetNamedSecurityInfoW(
3572 		    wn,
3573 		    SE_FILE_OBJECT,
3574 		    DACL_SECURITY_INFORMATION,
3575 		    NULL,
3576 		    NULL,
3577 		    &p->pDacl,
3578 		    NULL,
3579 		    &p->pSecurityDescriptor);
3580 	}
3581 	if (p->pSecurityDescriptor == NULL)
3582 	{
3583 	    mch_free_acl((vim_acl_T)p);
3584 	    p = NULL;
3585 	}
3586 	vim_free(wn);
3587     }
3588 
3589     return (vim_acl_T)p;
3590 #endif
3591 }
3592 
3593 #ifdef HAVE_ACL
3594 /*
3595  * Check if "acl" contains inherited ACE.
3596  */
3597     static BOOL
is_acl_inherited(PACL acl)3598 is_acl_inherited(PACL acl)
3599 {
3600     DWORD   i;
3601     ACL_SIZE_INFORMATION    acl_info;
3602     PACCESS_ALLOWED_ACE	    ace;
3603 
3604     acl_info.AceCount = 0;
3605     GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3606     for (i = 0; i < acl_info.AceCount; i++)
3607     {
3608 	GetAce(acl, i, (LPVOID *)&ace);
3609 	if (ace->Header.AceFlags & INHERITED_ACE)
3610 	    return TRUE;
3611     }
3612     return FALSE;
3613 }
3614 #endif
3615 
3616 /*
3617  * Set the ACL of file "fname" to "acl" (unless it's NULL).
3618  * Errors are ignored.
3619  * This must only be called with "acl" equal to what mch_get_acl() returned.
3620  */
3621     void
mch_set_acl(char_u * fname,vim_acl_T acl)3622 mch_set_acl(char_u *fname, vim_acl_T acl)
3623 {
3624 #ifdef HAVE_ACL
3625     struct my_acl   *p = (struct my_acl *)acl;
3626     SECURITY_INFORMATION    sec_info = 0;
3627     WCHAR	    *wn;
3628 
3629     if (p == NULL)
3630 	return;
3631 
3632     wn = enc_to_utf16(fname, NULL);
3633     if (wn == NULL)
3634 	return;
3635 
3636     // Set security flags
3637     if (p->pSidOwner)
3638 	sec_info |= OWNER_SECURITY_INFORMATION;
3639     if (p->pSidGroup)
3640 	sec_info |= GROUP_SECURITY_INFORMATION;
3641     if (p->pDacl)
3642     {
3643 	sec_info |= DACL_SECURITY_INFORMATION;
3644 	// Do not inherit its parent's DACL.
3645 	// If the DACL is inherited, Cygwin permissions would be changed.
3646 	if (!is_acl_inherited(p->pDacl))
3647 	    sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3648     }
3649     if (p->pSacl)
3650 	sec_info |= SACL_SECURITY_INFORMATION;
3651 
3652     (void)SetNamedSecurityInfoW(
3653 	    wn,			// Abstract filename
3654 	    SE_FILE_OBJECT,	// File Object
3655 	    sec_info,
3656 	    p->pSidOwner,	// Ownership information.
3657 	    p->pSidGroup,	// Group membership.
3658 	    p->pDacl,		// Discretionary information.
3659 	    p->pSacl		// For auditing purposes.
3660 	    );
3661     vim_free(wn);
3662 #endif
3663 }
3664 
3665     void
mch_free_acl(vim_acl_T acl)3666 mch_free_acl(vim_acl_T acl)
3667 {
3668 #ifdef HAVE_ACL
3669     struct my_acl   *p = (struct my_acl *)acl;
3670 
3671     if (p != NULL)
3672     {
3673 	LocalFree(p->pSecurityDescriptor);	// Free the memory just in case
3674 	vim_free(p);
3675     }
3676 #endif
3677 }
3678 
3679 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
3680 
3681 /*
3682  * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3683  */
3684     static BOOL WINAPI
handler_routine(DWORD dwCtrlType)3685 handler_routine(
3686     DWORD dwCtrlType)
3687 {
3688     INPUT_RECORD ir;
3689     DWORD out;
3690 
3691     switch (dwCtrlType)
3692     {
3693     case CTRL_C_EVENT:
3694 	if (ctrl_c_interrupts)
3695 	    g_fCtrlCPressed = TRUE;
3696 	return TRUE;
3697 
3698     case CTRL_BREAK_EVENT:
3699 	g_fCBrkPressed	= TRUE;
3700 	ctrl_break_was_pressed = TRUE;
3701 	// ReadConsoleInput is blocking, send a key event to continue.
3702 	ir.EventType = KEY_EVENT;
3703 	ir.Event.KeyEvent.bKeyDown = TRUE;
3704 	ir.Event.KeyEvent.wRepeatCount = 1;
3705 	ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3706 	ir.Event.KeyEvent.wVirtualScanCode = 0;
3707 	ir.Event.KeyEvent.dwControlKeyState = 0;
3708 	ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3709 	WriteConsoleInput(g_hConIn, &ir, 1, &out);
3710 	return TRUE;
3711 
3712     // fatal events: shut down gracefully
3713     case CTRL_CLOSE_EVENT:
3714     case CTRL_LOGOFF_EVENT:
3715     case CTRL_SHUTDOWN_EVENT:
3716 	windgoto((int)Rows - 1, 0);
3717 	g_fForceExit = TRUE;
3718 
3719 	vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
3720 		(dwCtrlType == CTRL_CLOSE_EVENT
3721 		     ? _("close")
3722 		     : dwCtrlType == CTRL_LOGOFF_EVENT
3723 			 ? _("logoff")
3724 			 : _("shutdown")));
3725 # ifdef DEBUG
3726 	OutputDebugString(IObuff);
3727 # endif
3728 
3729 	preserve_exit();	// output IObuff, preserve files and exit
3730 
3731 	return TRUE;		// not reached
3732 
3733     default:
3734 	return FALSE;
3735     }
3736 }
3737 
3738 
3739 /*
3740  * set the tty in (raw) ? "raw" : "cooked" mode
3741  */
3742     void
mch_settmode(tmode_T tmode)3743 mch_settmode(tmode_T tmode)
3744 {
3745     DWORD cmodein;
3746     DWORD cmodeout;
3747     BOOL bEnableHandler;
3748 
3749 # ifdef VIMDLL
3750     if (gui.in_use)
3751 	return;
3752 # endif
3753     GetConsoleMode(g_hConIn, &cmodein);
3754     GetConsoleMode(g_hConOut, &cmodeout);
3755     if (tmode == TMODE_RAW)
3756     {
3757 	cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3758 		     ENABLE_ECHO_INPUT);
3759 	if (g_fMouseActive)
3760 	{
3761 	    cmodein |= ENABLE_MOUSE_INPUT;
3762 	    cmodein &= ~ENABLE_QUICK_EDIT_MODE;
3763 	}
3764 	else
3765 	{
3766 	    cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
3767 	}
3768 	cmodeout &= ~(
3769 # ifdef FEAT_TERMGUICOLORS
3770 	    // Do not turn off the ENABLE_PROCESSED_OUTPUT flag when using
3771 	    // VTP.
3772 	    ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3773 # else
3774 	    ENABLE_PROCESSED_OUTPUT |
3775 # endif
3776 	    ENABLE_WRAP_AT_EOL_OUTPUT);
3777 	bEnableHandler = TRUE;
3778     }
3779     else // cooked
3780     {
3781 	cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3782 		    ENABLE_ECHO_INPUT);
3783 	cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3784 	bEnableHandler = FALSE;
3785     }
3786     SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
3787     SetConsoleMode(g_hConOut, cmodeout);
3788     SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3789 
3790 # ifdef MCH_WRITE_DUMP
3791     if (fdDump)
3792     {
3793 	fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3794 		tmode == TMODE_RAW ? "raw" :
3795 				    tmode == TMODE_COOK ? "cooked" : "normal",
3796 		cmodein, cmodeout);
3797 	fflush(fdDump);
3798     }
3799 # endif
3800 }
3801 
3802 
3803 /*
3804  * Get the size of the current window in `Rows' and `Columns'
3805  * Return OK when size could be determined, FAIL otherwise.
3806  */
3807     int
mch_get_shellsize(void)3808 mch_get_shellsize(void)
3809 {
3810     CONSOLE_SCREEN_BUFFER_INFO csbi;
3811 
3812 # ifdef VIMDLL
3813     if (gui.in_use)
3814 	return OK;
3815 # endif
3816     if (!g_fTermcapMode && g_cbTermcap.IsValid)
3817     {
3818 	/*
3819 	 * For some reason, we are trying to get the screen dimensions
3820 	 * even though we are not in termcap mode.  The 'Rows' and 'Columns'
3821 	 * variables are really intended to mean the size of Vim screen
3822 	 * while in termcap mode.
3823 	 */
3824 	Rows = g_cbTermcap.Info.dwSize.Y;
3825 	Columns = g_cbTermcap.Info.dwSize.X;
3826     }
3827     else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3828     {
3829 	Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3830 	Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3831     }
3832     else
3833     {
3834 	Rows = 25;
3835 	Columns = 80;
3836     }
3837     return OK;
3838 }
3839 
3840 /*
3841  * Resize console buffer to 'COORD'
3842  */
3843     static void
ResizeConBuf(HANDLE hConsole,COORD coordScreen)3844 ResizeConBuf(
3845     HANDLE  hConsole,
3846     COORD   coordScreen)
3847 {
3848     if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3849     {
3850 # ifdef MCH_WRITE_DUMP
3851 	if (fdDump)
3852 	{
3853 	    fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3854 		    GetLastError());
3855 	    fflush(fdDump);
3856 	}
3857 # endif
3858     }
3859 }
3860 
3861 /*
3862  * Resize console window size to 'srWindowRect'
3863  */
3864     static void
ResizeWindow(HANDLE hConsole,SMALL_RECT srWindowRect)3865 ResizeWindow(
3866     HANDLE     hConsole,
3867     SMALL_RECT srWindowRect)
3868 {
3869     if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
3870     {
3871 # ifdef MCH_WRITE_DUMP
3872 	if (fdDump)
3873 	{
3874 	    fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3875 		    GetLastError());
3876 	    fflush(fdDump);
3877 	}
3878 # endif
3879     }
3880 }
3881 
3882 /*
3883  * Set a console window to `xSize' * `ySize'
3884  */
3885     static void
ResizeConBufAndWindow(HANDLE hConsole,int xSize,int ySize)3886 ResizeConBufAndWindow(
3887     HANDLE  hConsole,
3888     int	    xSize,
3889     int	    ySize)
3890 {
3891     CONSOLE_SCREEN_BUFFER_INFO csbi;	// hold current console buffer info
3892     SMALL_RECT	    srWindowRect;	// hold the new console size
3893     COORD	    coordScreen;
3894     COORD	    cursor;
3895     static int	    resized = FALSE;
3896 
3897 # ifdef MCH_WRITE_DUMP
3898     if (fdDump)
3899     {
3900 	fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3901 	fflush(fdDump);
3902     }
3903 # endif
3904 
3905     // get the largest size we can size the console window to
3906     coordScreen = GetLargestConsoleWindowSize(hConsole);
3907 
3908     // define the new console window size and scroll position
3909     srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3910     srWindowRect.Right =  (SHORT) (min(xSize, coordScreen.X) - 1);
3911     srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3912 
3913     if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3914     {
3915 	int sx, sy;
3916 
3917 	sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3918 	sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3919 	if (sy < ySize || sx < xSize)
3920 	{
3921 	    /*
3922 	     * Increasing number of lines/columns, do buffer first.
3923 	     * Use the maximal size in x and y direction.
3924 	     */
3925 	    if (sy < ySize)
3926 		coordScreen.Y = ySize;
3927 	    else
3928 		coordScreen.Y = sy;
3929 	    if (sx < xSize)
3930 		coordScreen.X = xSize;
3931 	    else
3932 		coordScreen.X = sx;
3933 	    SetConsoleScreenBufferSize(hConsole, coordScreen);
3934 	}
3935     }
3936 
3937     // define the new console buffer size
3938     coordScreen.X = xSize;
3939     coordScreen.Y = ySize;
3940 
3941     // In the new console call API, only the first time in reverse order
3942     if (!vtp_working || resized)
3943     {
3944 	ResizeWindow(hConsole, srWindowRect);
3945 	ResizeConBuf(hConsole, coordScreen);
3946     }
3947     else
3948     {
3949 	// Workaround for a Windows 10 bug
3950 	cursor.X = srWindowRect.Left;
3951 	cursor.Y = srWindowRect.Top;
3952 	SetConsoleCursorPosition(hConsole, cursor);
3953 
3954 	ResizeConBuf(hConsole, coordScreen);
3955 	ResizeWindow(hConsole, srWindowRect);
3956 	resized = TRUE;
3957     }
3958 }
3959 
3960 
3961 /*
3962  * Set the console window to `Rows' * `Columns'
3963  */
3964     void
mch_set_shellsize(void)3965 mch_set_shellsize(void)
3966 {
3967     COORD coordScreen;
3968 
3969 # ifdef VIMDLL
3970     if (gui.in_use)
3971 	return;
3972 # endif
3973     // Don't change window size while still starting up
3974     if (suppress_winsize != 0)
3975     {
3976 	suppress_winsize = 2;
3977 	return;
3978     }
3979 
3980     if (term_console)
3981     {
3982 	coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3983 
3984 	// Clamp Rows and Columns to reasonable values
3985 	if (Rows > coordScreen.Y)
3986 	    Rows = coordScreen.Y;
3987 	if (Columns > coordScreen.X)
3988 	    Columns = coordScreen.X;
3989 
3990 	ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3991     }
3992 }
3993 
3994 /*
3995  * Rows and/or Columns has changed.
3996  */
3997     void
mch_new_shellsize(void)3998 mch_new_shellsize(void)
3999 {
4000 # ifdef VIMDLL
4001     if (gui.in_use)
4002 	return;
4003 # endif
4004     set_scroll_region(0, 0, Columns - 1, Rows - 1);
4005 }
4006 
4007 
4008 /*
4009  * Called when started up, to set the winsize that was delayed.
4010  */
4011     void
mch_set_winsize_now(void)4012 mch_set_winsize_now(void)
4013 {
4014     if (suppress_winsize == 2)
4015     {
4016 	suppress_winsize = 0;
4017 	mch_set_shellsize();
4018 	shell_resized();
4019     }
4020     suppress_winsize = 0;
4021 }
4022 #endif // FEAT_GUI_MSWIN
4023 
4024     static BOOL
vim_create_process(char * cmd,BOOL inherit_handles,DWORD flags,STARTUPINFO * si,PROCESS_INFORMATION * pi,LPVOID * env,char * cwd)4025 vim_create_process(
4026     char		*cmd,
4027     BOOL		inherit_handles,
4028     DWORD		flags,
4029     STARTUPINFO		*si,
4030     PROCESS_INFORMATION *pi,
4031     LPVOID		*env,
4032     char		*cwd)
4033 {
4034     BOOL	ret = FALSE;
4035     WCHAR	*wcmd, *wcwd = NULL;
4036 
4037     wcmd = enc_to_utf16((char_u *)cmd, NULL);
4038     if (wcmd == NULL)
4039 	return FALSE;
4040     if (cwd != NULL)
4041     {
4042 	wcwd = enc_to_utf16((char_u *)cwd, NULL);
4043 	if (wcwd == NULL)
4044 	    goto theend;
4045     }
4046 
4047     ret = CreateProcessW(
4048 	    NULL,		// Executable name
4049 	    wcmd,		// Command to execute
4050 	    NULL,		// Process security attributes
4051 	    NULL,		// Thread security attributes
4052 	    inherit_handles,	// Inherit handles
4053 	    flags,		// Creation flags
4054 	    env,		// Environment
4055 	    wcwd,		// Current directory
4056 	    (LPSTARTUPINFOW)si,	// Startup information
4057 	    pi);		// Process information
4058 theend:
4059     vim_free(wcmd);
4060     vim_free(wcwd);
4061     return ret;
4062 }
4063 
4064 
4065     static HINSTANCE
vim_shell_execute(char * cmd,INT n_show_cmd)4066 vim_shell_execute(
4067     char *cmd,
4068     INT	 n_show_cmd)
4069 {
4070     HINSTANCE	ret;
4071     WCHAR	*wcmd;
4072 
4073     wcmd = enc_to_utf16((char_u *)cmd, NULL);
4074     if (wcmd == NULL)
4075 	return (HINSTANCE) 0;
4076 
4077     ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4078     vim_free(wcmd);
4079     return ret;
4080 }
4081 
4082 
4083 #if defined(FEAT_GUI_MSWIN) || defined(PROTO)
4084 
4085 /*
4086  * Specialised version of system() for Win32 GUI mode.
4087  * This version proceeds as follows:
4088  *    1. Create a console window for use by the subprocess
4089  *    2. Run the subprocess (it gets the allocated console by default)
4090  *    3. Wait for the subprocess to terminate and get its exit code
4091  *    4. Prompt the user to press a key to close the console window
4092  */
4093     static int
mch_system_classic(char * cmd,int options)4094 mch_system_classic(char *cmd, int options)
4095 {
4096     STARTUPINFO		si;
4097     PROCESS_INFORMATION pi;
4098     DWORD		ret = 0;
4099     HWND		hwnd = GetFocus();
4100 
4101     si.cb = sizeof(si);
4102     si.lpReserved = NULL;
4103     si.lpDesktop = NULL;
4104     si.lpTitle = NULL;
4105     si.dwFlags = STARTF_USESHOWWINDOW;
4106     /*
4107      * It's nicer to run a filter command in a minimized window.
4108      * Don't activate the window to keep focus on Vim.
4109      */
4110     if (options & SHELL_DOOUT)
4111 	si.wShowWindow = SW_SHOWMINNOACTIVE;
4112     else
4113 	si.wShowWindow = SW_SHOWNORMAL;
4114     si.cbReserved2 = 0;
4115     si.lpReserved2 = NULL;
4116 
4117     // Now, run the command
4118     vim_create_process(cmd, FALSE,
4119 	    CREATE_DEFAULT_ERROR_MODE |	CREATE_NEW_CONSOLE,
4120 	    &si, &pi, NULL, NULL);
4121 
4122     // Wait for the command to terminate before continuing
4123     {
4124 # ifdef FEAT_GUI
4125 	int	    delay = 1;
4126 
4127 	// Keep updating the window while waiting for the shell to finish.
4128 	for (;;)
4129 	{
4130 	    MSG	msg;
4131 
4132 	    if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4133 	    {
4134 		TranslateMessage(&msg);
4135 		pDispatchMessage(&msg);
4136 		delay = 1;
4137 		continue;
4138 	    }
4139 	    if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4140 		break;
4141 
4142 	    // We start waiting for a very short time and then increase it, so
4143 	    // that we respond quickly when the process is quick, and don't
4144 	    // consume too much overhead when it's slow.
4145 	    if (delay < 50)
4146 		delay += 10;
4147 	}
4148 # else
4149 	WaitForSingleObject(pi.hProcess, INFINITE);
4150 # endif
4151 
4152 	// Get the command exit code
4153 	GetExitCodeProcess(pi.hProcess, &ret);
4154     }
4155 
4156     // Close the handles to the subprocess, so that it goes away
4157     CloseHandle(pi.hThread);
4158     CloseHandle(pi.hProcess);
4159 
4160     // Try to get input focus back.  Doesn't always work though.
4161     PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4162 
4163     return ret;
4164 }
4165 
4166 /*
4167  * Thread launched by the gui to send the current buffer data to the
4168  * process. This way avoid to hang up vim totally if the children
4169  * process take a long time to process the lines.
4170  */
4171     static unsigned int __stdcall
sub_process_writer(LPVOID param)4172 sub_process_writer(LPVOID param)
4173 {
4174     HANDLE	    g_hChildStd_IN_Wr = param;
4175     linenr_T	    lnum = curbuf->b_op_start.lnum;
4176     DWORD	    len = 0;
4177     DWORD	    l;
4178     char_u	    *lp = ml_get(lnum);
4179     char_u	    *s;
4180     int		    written = 0;
4181 
4182     for (;;)
4183     {
4184 	l = (DWORD)STRLEN(lp + written);
4185 	if (l == 0)
4186 	    len = 0;
4187 	else if (lp[written] == NL)
4188 	{
4189 	    // NL -> NUL translation
4190 	    WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4191 	}
4192 	else
4193 	{
4194 	    s = vim_strchr(lp + written, NL);
4195 	    WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4196 		      s == NULL ? l : (DWORD)(s - (lp + written)),
4197 		      &len, NULL);
4198 	}
4199 	if (len == (int)l)
4200 	{
4201 	    // Finished a line, add a NL, unless this line should not have
4202 	    // one.
4203 	    if (lnum != curbuf->b_op_end.lnum
4204 		|| (!curbuf->b_p_bin
4205 		    && curbuf->b_p_fixeol)
4206 		|| (lnum != curbuf->b_no_eol_lnum
4207 		    && (lnum != curbuf->b_ml.ml_line_count
4208 			|| curbuf->b_p_eol)))
4209 	    {
4210 		WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4211 						  (LPDWORD)&vim_ignored, NULL);
4212 	    }
4213 
4214 	    ++lnum;
4215 	    if (lnum > curbuf->b_op_end.lnum)
4216 		break;
4217 
4218 	    lp = ml_get(lnum);
4219 	    written = 0;
4220 	}
4221 	else if (len > 0)
4222 	    written += len;
4223     }
4224 
4225     // finished all the lines, close pipe
4226     CloseHandle(g_hChildStd_IN_Wr);
4227     return 0;
4228 }
4229 
4230 
4231 # define BUFLEN 100	// length for buffer, stolen from unix version
4232 
4233 /*
4234  * This function read from the children's stdout and write the
4235  * data on screen or in the buffer accordingly.
4236  */
4237     static void
dump_pipe(int options,HANDLE g_hChildStd_OUT_Rd,garray_T * ga,char_u buffer[],DWORD * buffer_off)4238 dump_pipe(int	    options,
4239 	  HANDLE    g_hChildStd_OUT_Rd,
4240 	  garray_T  *ga,
4241 	  char_u    buffer[],
4242 	  DWORD	    *buffer_off)
4243 {
4244     DWORD	availableBytes = 0;
4245     DWORD	i;
4246     int		ret;
4247     DWORD	len;
4248     DWORD	toRead;
4249     int		repeatCount;
4250 
4251     // we query the pipe to see if there is any data to read
4252     // to avoid to perform a blocking read
4253     ret = PeekNamedPipe(g_hChildStd_OUT_Rd, // pipe to query
4254 			NULL,		    // optional buffer
4255 			0,		    // buffer size
4256 			NULL,		    // number of read bytes
4257 			&availableBytes,    // available bytes total
4258 			NULL);		    // byteLeft
4259 
4260     repeatCount = 0;
4261     // We got real data in the pipe, read it
4262     while (ret != 0 && availableBytes > 0)
4263     {
4264 	repeatCount++;
4265 	toRead = (DWORD)(BUFLEN - *buffer_off);
4266 	toRead = availableBytes < toRead ? availableBytes : toRead;
4267 	ReadFile(g_hChildStd_OUT_Rd, buffer + *buffer_off, toRead , &len, NULL);
4268 
4269 	// If we haven't read anything, there is a problem
4270 	if (len == 0)
4271 	    break;
4272 
4273 	availableBytes -= len;
4274 
4275 	if (options & SHELL_READ)
4276 	{
4277 	    // Do NUL -> NL translation, append NL separated
4278 	    // lines to the current buffer.
4279 	    for (i = 0; i < len; ++i)
4280 	    {
4281 		if (buffer[i] == NL)
4282 		    append_ga_line(ga);
4283 		else if (buffer[i] == NUL)
4284 		    ga_append(ga, NL);
4285 		else
4286 		    ga_append(ga, buffer[i]);
4287 	    }
4288 	}
4289 	else if (has_mbyte)
4290 	{
4291 	    int		l;
4292 	    int		c;
4293 	    char_u	*p;
4294 
4295 	    len += *buffer_off;
4296 	    buffer[len] = NUL;
4297 
4298 	    // Check if the last character in buffer[] is
4299 	    // incomplete, keep these bytes for the next
4300 	    // round.
4301 	    for (p = buffer; p < buffer + len; p += l)
4302 	    {
4303 		l = MB_CPTR2LEN(p);
4304 		if (l == 0)
4305 		    l = 1;  // NUL byte?
4306 		else if (MB_BYTE2LEN(*p) != l)
4307 		    break;
4308 	    }
4309 	    if (p == buffer)	// no complete character
4310 	    {
4311 		// avoid getting stuck at an illegal byte
4312 		if (len >= 12)
4313 		    ++p;
4314 		else
4315 		{
4316 		    *buffer_off = len;
4317 		    return;
4318 		}
4319 	    }
4320 	    c = *p;
4321 	    *p = NUL;
4322 	    msg_puts((char *)buffer);
4323 	    if (p < buffer + len)
4324 	    {
4325 		*p = c;
4326 		*buffer_off = (DWORD)((buffer + len) - p);
4327 		mch_memmove(buffer, p, *buffer_off);
4328 		return;
4329 	    }
4330 	    *buffer_off = 0;
4331 	}
4332 	else
4333 	{
4334 	    buffer[len] = NUL;
4335 	    msg_puts((char *)buffer);
4336 	}
4337 
4338 	windgoto(msg_row, msg_col);
4339 	cursor_on();
4340 	out_flush();
4341     }
4342 }
4343 
4344 /*
4345  * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4346  * for communication and doesn't open any new window.
4347  */
4348     static int
mch_system_piped(char * cmd,int options)4349 mch_system_piped(char *cmd, int options)
4350 {
4351     STARTUPINFO		si;
4352     PROCESS_INFORMATION pi;
4353     DWORD		ret = 0;
4354 
4355     HANDLE g_hChildStd_IN_Rd = NULL;
4356     HANDLE g_hChildStd_IN_Wr = NULL;
4357     HANDLE g_hChildStd_OUT_Rd = NULL;
4358     HANDLE g_hChildStd_OUT_Wr = NULL;
4359 
4360     char_u	buffer[BUFLEN + 1]; // reading buffer + size
4361     DWORD	len;
4362 
4363     // buffer used to receive keys
4364     char_u	ta_buf[BUFLEN + 1];	// TypeAHead
4365     int		ta_len = 0;		// valid bytes in ta_buf[]
4366 
4367     DWORD	i;
4368     int		noread_cnt = 0;
4369     garray_T	ga;
4370     int		delay = 1;
4371     DWORD	buffer_off = 0;	// valid bytes in buffer[]
4372     char	*p = NULL;
4373 
4374     SECURITY_ATTRIBUTES saAttr;
4375 
4376     // Set the bInheritHandle flag so pipe handles are inherited.
4377     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4378     saAttr.bInheritHandle = TRUE;
4379     saAttr.lpSecurityDescriptor = NULL;
4380 
4381     if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4382 	// Ensure the read handle to the pipe for STDOUT is not inherited.
4383        || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4384 	// Create a pipe for the child process's STDIN.
4385        || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4386 	// Ensure the write handle to the pipe for STDIN is not inherited.
4387        || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4388     {
4389 	CloseHandle(g_hChildStd_IN_Rd);
4390 	CloseHandle(g_hChildStd_IN_Wr);
4391 	CloseHandle(g_hChildStd_OUT_Rd);
4392 	CloseHandle(g_hChildStd_OUT_Wr);
4393 	msg_puts(_("\nCannot create pipes\n"));
4394     }
4395 
4396     si.cb = sizeof(si);
4397     si.lpReserved = NULL;
4398     si.lpDesktop = NULL;
4399     si.lpTitle = NULL;
4400     si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4401 
4402     // set-up our file redirection
4403     si.hStdError = g_hChildStd_OUT_Wr;
4404     si.hStdOutput = g_hChildStd_OUT_Wr;
4405     si.hStdInput = g_hChildStd_IN_Rd;
4406     si.wShowWindow = SW_HIDE;
4407     si.cbReserved2 = 0;
4408     si.lpReserved2 = NULL;
4409 
4410     if (options & SHELL_READ)
4411 	ga_init2(&ga, 1, BUFLEN);
4412 
4413     if (cmd != NULL)
4414     {
4415 	p = (char *)vim_strsave((char_u *)cmd);
4416 	if (p != NULL)
4417 	    unescape_shellxquote((char_u *)p, p_sxe);
4418 	else
4419 	    p = cmd;
4420     }
4421 
4422     // Now, run the command.
4423     // About "Inherit handles" being TRUE: this command can be litigious,
4424     // handle inheritance was deactivated for pending temp file, but, if we
4425     // deactivate it, the pipes don't work for some reason.
4426      vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4427 	     &si, &pi, NULL, NULL);
4428 
4429     if (p != cmd)
4430 	vim_free(p);
4431 
4432     // Close our unused side of the pipes
4433     CloseHandle(g_hChildStd_IN_Rd);
4434     CloseHandle(g_hChildStd_OUT_Wr);
4435 
4436     if (options & SHELL_WRITE)
4437     {
4438 	HANDLE thread = (HANDLE)
4439 	 _beginthreadex(NULL,  // security attributes
4440 			0,     // default stack size
4441 			sub_process_writer, // function to be executed
4442 			g_hChildStd_IN_Wr,  // parameter
4443 			0,		 // creation flag, start immediately
4444 			NULL);		    // we don't care about thread id
4445 	CloseHandle(thread);
4446 	g_hChildStd_IN_Wr = NULL;
4447     }
4448 
4449     // Keep updating the window while waiting for the shell to finish.
4450     for (;;)
4451     {
4452 	MSG	msg;
4453 
4454 	if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4455 	{
4456 	    TranslateMessage(&msg);
4457 	    pDispatchMessage(&msg);
4458 	}
4459 
4460 	// write pipe information in the window
4461 	if ((options & (SHELL_READ|SHELL_WRITE))
4462 # ifdef FEAT_GUI
4463 		|| gui.in_use
4464 # endif
4465 	    )
4466 	{
4467 	    len = 0;
4468 	    if (!(options & SHELL_EXPAND)
4469 		&& ((options &
4470 			(SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4471 		    != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4472 # ifdef FEAT_GUI
4473 		    || gui.in_use
4474 # endif
4475 		    )
4476 		&& (ta_len > 0 || noread_cnt > 4))
4477 	    {
4478 		if (ta_len == 0)
4479 		{
4480 		    // Get extra characters when we don't have any.  Reset the
4481 		    // counter and timer.
4482 		    noread_cnt = 0;
4483 		    len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4484 		}
4485 		if (ta_len > 0 || len > 0)
4486 		{
4487 		    /*
4488 		     * For pipes: Check for CTRL-C: send interrupt signal to
4489 		     * child.  Check for CTRL-D: EOF, close pipe to child.
4490 		     */
4491 		    if (len == 1 && cmd != NULL)
4492 		    {
4493 			if (ta_buf[ta_len] == Ctrl_C)
4494 			{
4495 			    // Learn what exit code is expected, for
4496 			// now put 9 as SIGKILL
4497 			    TerminateProcess(pi.hProcess, 9);
4498 			}
4499 			if (ta_buf[ta_len] == Ctrl_D)
4500 			{
4501 			    CloseHandle(g_hChildStd_IN_Wr);
4502 			    g_hChildStd_IN_Wr = NULL;
4503 			}
4504 		    }
4505 
4506 		    term_replace_bs_del_keycode(ta_buf, ta_len, len);
4507 
4508 		    /*
4509 		     * For pipes: echo the typed characters.  For a pty this
4510 		     * does not seem to work.
4511 		     */
4512 		    for (i = ta_len; i < ta_len + len; ++i)
4513 		    {
4514 			if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4515 			    msg_putchar(ta_buf[i]);
4516 			else if (has_mbyte)
4517 			{
4518 			    int l = (*mb_ptr2len)(ta_buf + i);
4519 
4520 			    msg_outtrans_len(ta_buf + i, l);
4521 			    i += l - 1;
4522 			}
4523 			else
4524 			    msg_outtrans_len(ta_buf + i, 1);
4525 		    }
4526 		    windgoto(msg_row, msg_col);
4527 		    out_flush();
4528 
4529 		    ta_len += len;
4530 
4531 		    /*
4532 		     * Write the characters to the child, unless EOF has been
4533 		     * typed for pipes.  Write one character at a time, to
4534 		     * avoid losing too much typeahead.  When writing buffer
4535 		     * lines, drop the typed characters (only check for
4536 		     * CTRL-C).
4537 		     */
4538 		    if (options & SHELL_WRITE)
4539 			ta_len = 0;
4540 		    else if (g_hChildStd_IN_Wr != NULL)
4541 		    {
4542 			WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4543 				    1, &len, NULL);
4544 			// if we are typing in, we want to keep things reactive
4545 			delay = 1;
4546 			if (len > 0)
4547 			{
4548 			    ta_len -= len;
4549 			    mch_memmove(ta_buf, ta_buf + len, ta_len);
4550 			}
4551 		    }
4552 		}
4553 	    }
4554 	}
4555 
4556 	if (ta_len)
4557 	    ui_inchar_undo(ta_buf, ta_len);
4558 
4559 	if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4560 	{
4561 	    dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
4562 	    break;
4563 	}
4564 
4565 	++noread_cnt;
4566 	dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
4567 
4568 	// We start waiting for a very short time and then increase it, so
4569 	// that we respond quickly when the process is quick, and don't
4570 	// consume too much overhead when it's slow.
4571 	if (delay < 50)
4572 	    delay += 10;
4573     }
4574 
4575     // Close the pipe
4576     CloseHandle(g_hChildStd_OUT_Rd);
4577     if (g_hChildStd_IN_Wr != NULL)
4578 	CloseHandle(g_hChildStd_IN_Wr);
4579 
4580     WaitForSingleObject(pi.hProcess, INFINITE);
4581 
4582     // Get the command exit code
4583     GetExitCodeProcess(pi.hProcess, &ret);
4584 
4585     if (options & SHELL_READ)
4586     {
4587 	if (ga.ga_len > 0)
4588 	{
4589 	    append_ga_line(&ga);
4590 	    // remember that the NL was missing
4591 	    curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4592 	}
4593 	else
4594 	    curbuf->b_no_eol_lnum = 0;
4595 	ga_clear(&ga);
4596     }
4597 
4598     // Close the handles to the subprocess, so that it goes away
4599     CloseHandle(pi.hThread);
4600     CloseHandle(pi.hProcess);
4601 
4602     return ret;
4603 }
4604 
4605     static int
mch_system_g(char * cmd,int options)4606 mch_system_g(char *cmd, int options)
4607 {
4608     // if we can pipe and the shelltemp option is off
4609     if (!p_stmp)
4610 	return mch_system_piped(cmd, options);
4611     else
4612 	return mch_system_classic(cmd, options);
4613 }
4614 #endif
4615 
4616 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
4617     static int
mch_system_c(char * cmd,int options UNUSED)4618 mch_system_c(char *cmd, int options UNUSED)
4619 {
4620     int		ret;
4621     WCHAR	*wcmd;
4622     char_u	*buf;
4623     size_t	len;
4624 
4625     // If the command starts and ends with double quotes, enclose the command
4626     // in parentheses.
4627     len = STRLEN(cmd);
4628     if (len >= 2 && cmd[0] == '"' && cmd[len - 1] == '"')
4629     {
4630 	len += 3;
4631 	buf = alloc(len);
4632 	if (buf == NULL)
4633 	    return -1;
4634 	vim_snprintf((char *)buf, len, "(%s)", cmd);
4635 	wcmd = enc_to_utf16(buf, NULL);
4636 	free(buf);
4637     }
4638     else
4639 	wcmd = enc_to_utf16((char_u *)cmd, NULL);
4640 
4641     if (wcmd == NULL)
4642 	return -1;
4643 
4644     ret = _wsystem(wcmd);
4645     vim_free(wcmd);
4646     return ret;
4647 }
4648 
4649 #endif
4650 
4651     static int
mch_system(char * cmd,int options)4652 mch_system(char *cmd, int options)
4653 {
4654 #ifdef VIMDLL
4655     if (gui.in_use || gui.starting)
4656 	return mch_system_g(cmd, options);
4657     else
4658 	return mch_system_c(cmd, options);
4659 #elif defined(FEAT_GUI_MSWIN)
4660     return mch_system_g(cmd, options);
4661 #else
4662     return mch_system_c(cmd, options);
4663 #endif
4664 }
4665 
4666 #if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4667 /*
4668  * Use a terminal window to run a shell command in.
4669  */
4670     static int
mch_call_shell_terminal(char_u * cmd,int options UNUSED)4671 mch_call_shell_terminal(
4672     char_u	*cmd,
4673     int		options UNUSED)	// SHELL_*, see vim.h
4674 {
4675     jobopt_T	opt;
4676     char_u	*newcmd = NULL;
4677     typval_T	argvar[2];
4678     long_u	cmdlen;
4679     int		retval = -1;
4680     buf_T	*buf;
4681     job_T	*job;
4682     aco_save_T	aco;
4683     oparg_T	oa;		// operator arguments
4684 
4685     if (cmd == NULL)
4686 	cmdlen = STRLEN(p_sh) + 1;
4687     else
4688 	cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
4689     newcmd = alloc(cmdlen);
4690     if (newcmd == NULL)
4691 	return 255;
4692     if (cmd == NULL)
4693     {
4694 	STRCPY(newcmd, p_sh);
4695 	ch_log(NULL, "starting terminal to run a shell");
4696     }
4697     else
4698     {
4699 	vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4700 	ch_log(NULL, "starting terminal for system command '%s'", cmd);
4701     }
4702 
4703     init_job_options(&opt);
4704 
4705     argvar[0].v_type = VAR_STRING;
4706     argvar[0].vval.v_string = newcmd;
4707     argvar[1].v_type = VAR_UNKNOWN;
4708     buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
4709     if (buf == NULL)
4710     {
4711 	vim_free(newcmd);
4712 	return 255;
4713     }
4714 
4715     job = term_getjob(buf->b_term);
4716     ++job->jv_refcount;
4717 
4718     // Find a window to make "buf" curbuf.
4719     aucmd_prepbuf(&aco, buf);
4720 
4721     clear_oparg(&oa);
4722     while (term_use_loop())
4723     {
4724 	if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4725 	{
4726 	    // If terminal_loop() returns OK we got a key that is handled
4727 	    // in Normal model. We don't do redrawing anyway.
4728 	    if (terminal_loop(TRUE) == OK)
4729 		normal_cmd(&oa, TRUE);
4730 	}
4731 	else
4732 	    normal_cmd(&oa, TRUE);
4733     }
4734     retval = job->jv_exitval;
4735     ch_log(NULL, "system command finished");
4736 
4737     job_unref(job);
4738 
4739     // restore curwin/curbuf and a few other things
4740     aucmd_restbuf(&aco);
4741 
4742     wait_return(TRUE);
4743     do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4744 
4745     vim_free(newcmd);
4746     return retval;
4747 }
4748 #endif
4749 
4750 /*
4751  * Either execute a command by calling the shell or start a new shell
4752  */
4753     int
mch_call_shell(char_u * cmd,int options)4754 mch_call_shell(
4755     char_u  *cmd,
4756     int	    options)	// SHELL_*, see vim.h
4757 {
4758     int		x = 0;
4759     int		tmode = cur_tmode;
4760 #ifdef FEAT_TITLE
4761     WCHAR	szShellTitle[512];
4762 
4763     // Change the title to reflect that we are in a subshell.
4764     if (GetConsoleTitleW(szShellTitle, ARRAY_LENGTH(szShellTitle) - 4) > 0)
4765     {
4766 	if (cmd == NULL)
4767 	    wcscat(szShellTitle, L" :sh");
4768 	else
4769 	{
4770 	    WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
4771 
4772 	    if (wn != NULL)
4773 	    {
4774 		wcscat(szShellTitle, L" - !");
4775 		if ((wcslen(szShellTitle) + wcslen(wn) <
4776 			    ARRAY_LENGTH(szShellTitle)))
4777 		    wcscat(szShellTitle, wn);
4778 		SetConsoleTitleW(szShellTitle);
4779 		vim_free(wn);
4780 	    }
4781 	}
4782     }
4783 #endif
4784 
4785     out_flush();
4786 
4787 #ifdef MCH_WRITE_DUMP
4788     if (fdDump)
4789     {
4790 	fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4791 	fflush(fdDump);
4792     }
4793 #endif
4794 #if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4795     // TODO: make the terminal window work with input or output redirected.
4796     if (
4797 # ifdef VIMDLL
4798 	    gui.in_use &&
4799 # endif
4800 	    vim_strchr(p_go, GO_TERMINAL) != NULL
4801 	 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4802     {
4803 	char_u	*cmdbase = cmd;
4804 
4805 	if (cmdbase != NULL)
4806 	    // Skip a leading quote and (.
4807 	    while (*cmdbase == '"' || *cmdbase == '(')
4808 		++cmdbase;
4809 
4810 	// Check the command does not begin with "start "
4811 	if (cmdbase == NULL || STRNICMP(cmdbase, "start", 5) != 0
4812 						   || !VIM_ISWHITE(cmdbase[5]))
4813 	{
4814 	    // Use a terminal window to run the command in.
4815 	    x = mch_call_shell_terminal(cmd, options);
4816 # ifdef FEAT_TITLE
4817 	    resettitle();
4818 # endif
4819 	    return x;
4820 	}
4821     }
4822 #endif
4823 
4824     /*
4825      * Catch all deadly signals while running the external command, because a
4826      * CTRL-C, Ctrl-Break or illegal instruction  might otherwise kill us.
4827      */
4828     signal(SIGINT, SIG_IGN);
4829 #if defined(__GNUC__) && !defined(__MINGW32__)
4830     signal(SIGKILL, SIG_IGN);
4831 #else
4832     signal(SIGBREAK, SIG_IGN);
4833 #endif
4834     signal(SIGILL, SIG_IGN);
4835     signal(SIGFPE, SIG_IGN);
4836     signal(SIGSEGV, SIG_IGN);
4837     signal(SIGTERM, SIG_IGN);
4838     signal(SIGABRT, SIG_IGN);
4839 
4840     if (options & SHELL_COOKED)
4841 	settmode(TMODE_COOK);	// set to normal mode
4842 
4843     if (cmd == NULL)
4844     {
4845 	x = mch_system((char *)p_sh, options);
4846     }
4847     else
4848     {
4849 	// we use "command" or "cmd" to start the shell; slow but easy
4850 	char_u	*newcmd = NULL;
4851 	char_u	*cmdbase = cmd;
4852 	long_u	cmdlen;
4853 
4854 	// Skip a leading ", ( and "(.
4855 	if (*cmdbase == '"' )
4856 	    ++cmdbase;
4857 	if (*cmdbase == '(')
4858 	    ++cmdbase;
4859 
4860 	if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
4861 	{
4862 	    STARTUPINFO		si;
4863 	    PROCESS_INFORMATION	pi;
4864 	    DWORD		flags = CREATE_NEW_CONSOLE;
4865 	    INT			n_show_cmd = SW_SHOWNORMAL;
4866 	    char_u		*p;
4867 
4868 	    ZeroMemory(&si, sizeof(si));
4869 	    si.cb = sizeof(si);
4870 	    si.lpReserved = NULL;
4871 	    si.lpDesktop = NULL;
4872 	    si.lpTitle = NULL;
4873 	    si.dwFlags = 0;
4874 	    si.cbReserved2 = 0;
4875 	    si.lpReserved2 = NULL;
4876 
4877 	    cmdbase = skipwhite(cmdbase + 5);
4878 	    if ((STRNICMP(cmdbase, "/min", 4) == 0)
4879 		    && VIM_ISWHITE(cmdbase[4]))
4880 	    {
4881 		cmdbase = skipwhite(cmdbase + 4);
4882 		si.dwFlags = STARTF_USESHOWWINDOW;
4883 		si.wShowWindow = SW_SHOWMINNOACTIVE;
4884 		n_show_cmd = SW_SHOWMINNOACTIVE;
4885 	    }
4886 	    else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4887 		    && VIM_ISWHITE(cmdbase[2]))
4888 	    {
4889 		cmdbase = skipwhite(cmdbase + 2);
4890 		flags = CREATE_NO_WINDOW;
4891 		si.dwFlags = STARTF_USESTDHANDLES;
4892 		si.hStdInput = CreateFile("\\\\.\\NUL",	// File name
4893 		    GENERIC_READ,			// Access flags
4894 		    0,					// Share flags
4895 		    NULL,				// Security att.
4896 		    OPEN_EXISTING,			// Open flags
4897 		    FILE_ATTRIBUTE_NORMAL,		// File att.
4898 		    NULL);				// Temp file
4899 		si.hStdOutput = si.hStdInput;
4900 		si.hStdError = si.hStdInput;
4901 	    }
4902 
4903 	    // Remove a trailing ", ) and )" if they have a match
4904 	    // at the start of the command.
4905 	    if (cmdbase > cmd)
4906 	    {
4907 		p = cmdbase + STRLEN(cmdbase);
4908 		if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4909 		    *--p = NUL;
4910 		if (p > cmdbase && p[-1] == ')'
4911 			&& (*cmd =='(' || cmd[1] == '('))
4912 		    *--p = NUL;
4913 	    }
4914 
4915 	    newcmd = cmdbase;
4916 	    unescape_shellxquote(cmdbase, p_sxe);
4917 
4918 	    /*
4919 	     * If creating new console, arguments are passed to the
4920 	     * 'cmd.exe' as-is. If it's not, arguments are not treated
4921 	     * correctly for current 'cmd.exe'. So unescape characters in
4922 	     * shellxescape except '|' for avoiding to be treated as
4923 	     * argument to them. Pass the arguments to sub-shell.
4924 	     */
4925 	    if (flags != CREATE_NEW_CONSOLE)
4926 	    {
4927 		char_u	*subcmd;
4928 		char_u	*cmd_shell = mch_getenv("COMSPEC");
4929 
4930 		if (cmd_shell == NULL || *cmd_shell == NUL)
4931 		    cmd_shell = (char_u *)default_shell();
4932 
4933 		subcmd = vim_strsave_escaped_ext(cmdbase,
4934 			(char_u *)"|", '^', FALSE);
4935 		if (subcmd != NULL)
4936 		{
4937 		    // make "cmd.exe /c arguments"
4938 		    cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
4939 		    newcmd = alloc(cmdlen);
4940 		    if (newcmd != NULL)
4941 			vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
4942 						       cmd_shell, subcmd);
4943 		    else
4944 			newcmd = cmdbase;
4945 		    vim_free(subcmd);
4946 		}
4947 	    }
4948 
4949 	    /*
4950 	     * Now, start the command as a process, so that it doesn't
4951 	     * inherit our handles which causes unpleasant dangling swap
4952 	     * files if we exit before the spawned process
4953 	     */
4954 	    if (vim_create_process((char *)newcmd, FALSE, flags,
4955 			&si, &pi, NULL, NULL))
4956 		x = 0;
4957 	    else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4958 							       > (HINSTANCE)32)
4959 		x = 0;
4960 	    else
4961 	    {
4962 		x = -1;
4963 #ifdef FEAT_GUI_MSWIN
4964 # ifdef VIMDLL
4965 		if (gui.in_use)
4966 # endif
4967 		    emsg(_("E371: Command not found"));
4968 #endif
4969 	    }
4970 
4971 	    if (newcmd != cmdbase)
4972 		vim_free(newcmd);
4973 
4974 	    if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
4975 	    {
4976 		// Close the handle to \\.\NUL created above.
4977 		CloseHandle(si.hStdInput);
4978 	    }
4979 	    // Close the handles to the subprocess, so that it goes away
4980 	    CloseHandle(pi.hThread);
4981 	    CloseHandle(pi.hProcess);
4982 	}
4983 	else
4984 	{
4985 	    cmdlen =
4986 #ifdef FEAT_GUI_MSWIN
4987 		((gui.in_use || gui.starting) ?
4988 		    (!s_dont_use_vimrun && p_stmp ?
4989 			STRLEN(vimrun_path) : STRLEN(p_sh) + STRLEN(p_shcf))
4990 		    : 0) +
4991 #endif
4992 		STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
4993 
4994 	    newcmd = alloc(cmdlen);
4995 	    if (newcmd != NULL)
4996 	    {
4997 #if defined(FEAT_GUI_MSWIN)
4998 		if (
4999 # ifdef VIMDLL
5000 		    (gui.in_use || gui.starting) &&
5001 # endif
5002 		    need_vimrun_warning)
5003 		{
5004 		    char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5005 			"External commands will not pause after completion.\n"
5006 			"See  :help win32-vimrun  for more information.");
5007 		    char *title = _("Vim Warning");
5008 		    WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5009 		    WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5010 
5011 		    if (wmsg != NULL && wtitle != NULL)
5012 			MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5013 		    vim_free(wmsg);
5014 		    vim_free(wtitle);
5015 		    need_vimrun_warning = FALSE;
5016 		}
5017 		if (
5018 # ifdef VIMDLL
5019 		    (gui.in_use || gui.starting) &&
5020 # endif
5021 		    !s_dont_use_vimrun && p_stmp)
5022 		    // Use vimrun to execute the command.  It opens a console
5023 		    // window, which can be closed without killing Vim.
5024 		    vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
5025 			    vimrun_path,
5026 			    (msg_silent != 0 || (options & SHELL_DOOUT))
5027 								 ? "-s " : "",
5028 			    p_sh, p_shcf, cmd);
5029 		else if (
5030 # ifdef VIMDLL
5031 			(gui.in_use || gui.starting) &&
5032 # endif
5033 			s_dont_use_vimrun && STRCMP(p_shcf, "/c") == 0)
5034 		    // workaround for the case that "vimrun" does not exist
5035 		    vim_snprintf((char *)newcmd, cmdlen, "%s %s %s %s %s",
5036 					   p_sh, p_shcf, p_sh, p_shcf, cmd);
5037 		else
5038 #endif
5039 		    vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
5040 							   p_sh, p_shcf, cmd);
5041 		x = mch_system((char *)newcmd, options);
5042 		vim_free(newcmd);
5043 	    }
5044 	}
5045     }
5046 
5047     if (tmode == TMODE_RAW)
5048     {
5049 	// The shell may have messed with the mode, always set it.
5050 	cur_tmode = TMODE_UNKNOWN;
5051 	settmode(TMODE_RAW);	// set to raw mode
5052     }
5053 
5054     // Print the return value, unless "vimrun" was used.
5055     if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5056 #if defined(FEAT_GUI_MSWIN)
5057 	    && ((gui.in_use || gui.starting) ?
5058 		((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp) : 1)
5059 #endif
5060 	    )
5061     {
5062 	smsg(_("shell returned %d"), x);
5063 	msg_putchar('\n');
5064     }
5065 #ifdef FEAT_TITLE
5066     resettitle();
5067 #endif
5068 
5069     signal(SIGINT, SIG_DFL);
5070 #if defined(__GNUC__) && !defined(__MINGW32__)
5071     signal(SIGKILL, SIG_DFL);
5072 #else
5073     signal(SIGBREAK, SIG_DFL);
5074 #endif
5075     signal(SIGILL, SIG_DFL);
5076     signal(SIGFPE, SIG_DFL);
5077     signal(SIGSEGV, SIG_DFL);
5078     signal(SIGTERM, SIG_DFL);
5079     signal(SIGABRT, SIG_DFL);
5080 
5081     return x;
5082 }
5083 
5084 #if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
5085     static HANDLE
job_io_file_open(char_u * fname,DWORD dwDesiredAccess,DWORD dwShareMode,LPSECURITY_ATTRIBUTES lpSecurityAttributes,DWORD dwCreationDisposition,DWORD dwFlagsAndAttributes)5086 job_io_file_open(
5087 	char_u *fname,
5088 	DWORD dwDesiredAccess,
5089 	DWORD dwShareMode,
5090 	LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5091 	DWORD dwCreationDisposition,
5092 	DWORD dwFlagsAndAttributes)
5093 {
5094     HANDLE h;
5095     WCHAR *wn;
5096 
5097     wn = enc_to_utf16(fname, NULL);
5098     if (wn == NULL)
5099 	return INVALID_HANDLE_VALUE;
5100 
5101     h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5102 	    lpSecurityAttributes, dwCreationDisposition,
5103 	    dwFlagsAndAttributes, NULL);
5104     vim_free(wn);
5105     return h;
5106 }
5107 
5108 /*
5109  * Turn the dictionary "env" into a NUL separated list that can be used as the
5110  * environment argument of vim_create_process().
5111  */
5112     void
win32_build_env(dict_T * env,garray_T * gap,int is_terminal)5113 win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
5114 {
5115     hashitem_T	*hi;
5116     long_u	todo = env != NULL ? env->dv_hashtab.ht_used : 0;
5117     LPVOID	base = GetEnvironmentStringsW();
5118 
5119     // for last \0
5120     if (ga_grow(gap, 1) == FAIL)
5121 	return;
5122 
5123     if (env != NULL)
5124     {
5125 	for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
5126 	{
5127 	    if (!HASHITEM_EMPTY(hi))
5128 	    {
5129 		typval_T *item = &dict_lookup(hi)->di_tv;
5130 		WCHAR   *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5131 		WCHAR   *wval = enc_to_utf16(tv_get_string(item), NULL);
5132 		--todo;
5133 		if (wkey != NULL && wval != NULL)
5134 		{
5135 		    size_t	n;
5136 		    size_t	lkey = wcslen(wkey);
5137 		    size_t	lval = wcslen(wval);
5138 
5139 		    if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5140 			continue;
5141 		    for (n = 0; n < lkey; n++)
5142 			*((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5143 		    *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5144 		    for (n = 0; n < lval; n++)
5145 			*((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5146 		    *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5147 		}
5148 		vim_free(wkey);
5149 		vim_free(wval);
5150 	    }
5151 	}
5152     }
5153 
5154     if (base)
5155     {
5156 	WCHAR	*p = (WCHAR*) base;
5157 
5158 	// for last \0
5159 	if (ga_grow(gap, 1) == FAIL)
5160 	    return;
5161 
5162 	while (*p != 0 || *(p + 1) != 0)
5163 	{
5164 	    if (ga_grow(gap, 1) == OK)
5165 		*((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5166 	    p++;
5167 	}
5168 	FreeEnvironmentStrings(base);
5169 	*((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5170     }
5171 
5172 # if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
5173     {
5174 #  ifdef FEAT_CLIENTSERVER
5175 	char_u	*servername = get_vim_var_str(VV_SEND_SERVER);
5176 	size_t	servername_len = STRLEN(servername);
5177 #  endif
5178 #  ifdef FEAT_TERMINAL
5179 	char_u	*version = get_vim_var_str(VV_VERSION);
5180 	size_t	version_len = STRLEN(version);
5181 #  endif
5182 	// size of "VIM_SERVERNAME=" and value,
5183 	// plus "VIM_TERMINAL=" and value,
5184 	// plus two terminating NULs
5185 	size_t	n = 0
5186 #  ifdef FEAT_CLIENTSERVER
5187 		    + 15 + servername_len
5188 #  endif
5189 #  ifdef FEAT_TERMINAL
5190 		    + 13 + version_len + 2
5191 #  endif
5192 		    ;
5193 
5194 	if (ga_grow(gap, (int)n) == OK)
5195 	{
5196 #  ifdef FEAT_CLIENTSERVER
5197 	    for (n = 0; n < 15; n++)
5198 		*((WCHAR*)gap->ga_data + gap->ga_len++) =
5199 		    (WCHAR)"VIM_SERVERNAME="[n];
5200 	    for (n = 0; n < servername_len; n++)
5201 		*((WCHAR*)gap->ga_data + gap->ga_len++) =
5202 		    (WCHAR)servername[n];
5203 	    *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5204 #  endif
5205 #  ifdef FEAT_TERMINAL
5206 	    if (is_terminal)
5207 	    {
5208 		for (n = 0; n < 13; n++)
5209 		    *((WCHAR*)gap->ga_data + gap->ga_len++) =
5210 			(WCHAR)"VIM_TERMINAL="[n];
5211 		for (n = 0; n < version_len; n++)
5212 		    *((WCHAR*)gap->ga_data + gap->ga_len++) =
5213 			(WCHAR)version[n];
5214 		*((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5215 	    }
5216 #  endif
5217 	}
5218     }
5219 # endif
5220 }
5221 
5222 /*
5223  * Create a pair of pipes.
5224  * Return TRUE for success, FALSE for failure.
5225  */
5226     static BOOL
create_pipe_pair(HANDLE handles[2])5227 create_pipe_pair(HANDLE handles[2])
5228 {
5229     static LONG		s;
5230     char		name[64];
5231     SECURITY_ATTRIBUTES sa;
5232 
5233     sprintf(name, "\\\\?\\pipe\\vim-%08lx-%08lx",
5234 	    GetCurrentProcessId(),
5235 	    InterlockedIncrement(&s));
5236 
5237     // Create named pipe. Max size of named pipe is 65535.
5238     handles[1] = CreateNamedPipe(
5239 	    name,
5240 	    PIPE_ACCESS_OUTBOUND | FILE_FLAG_OVERLAPPED,
5241 	    PIPE_TYPE_BYTE | PIPE_NOWAIT,
5242 	    1, MAX_NAMED_PIPE_SIZE, 0, 0, NULL);
5243 
5244     if (handles[1] == INVALID_HANDLE_VALUE)
5245 	return FALSE;
5246 
5247     sa.nLength = sizeof(sa);
5248     sa.bInheritHandle = TRUE;
5249     sa.lpSecurityDescriptor = NULL;
5250 
5251     handles[0] = CreateFile(name,
5252 	    FILE_GENERIC_READ,
5253 	    FILE_SHARE_READ, &sa,
5254 	    OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
5255 
5256     if (handles[0] == INVALID_HANDLE_VALUE)
5257     {
5258 	CloseHandle(handles[1]);
5259 	return FALSE;
5260     }
5261 
5262     return TRUE;
5263 }
5264 
5265     void
mch_job_start(char * cmd,job_T * job,jobopt_T * options)5266 mch_job_start(char *cmd, job_T *job, jobopt_T *options)
5267 {
5268     STARTUPINFO		si;
5269     PROCESS_INFORMATION	pi;
5270     HANDLE		jo;
5271     SECURITY_ATTRIBUTES saAttr;
5272     channel_T		*channel = NULL;
5273     HANDLE		ifd[2];
5274     HANDLE		ofd[2];
5275     HANDLE		efd[2];
5276     garray_T		ga;
5277 
5278     int		use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5279     int		use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5280     int		use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5281     int		use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5282     int		use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5283     int		use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5284     int		use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5285 
5286     if (use_out_for_err && use_null_for_out)
5287 	use_null_for_err = TRUE;
5288 
5289     ifd[0] = INVALID_HANDLE_VALUE;
5290     ifd[1] = INVALID_HANDLE_VALUE;
5291     ofd[0] = INVALID_HANDLE_VALUE;
5292     ofd[1] = INVALID_HANDLE_VALUE;
5293     efd[0] = INVALID_HANDLE_VALUE;
5294     efd[1] = INVALID_HANDLE_VALUE;
5295     ga_init2(&ga, (int)sizeof(wchar_t), 500);
5296 
5297     jo = CreateJobObject(NULL, NULL);
5298     if (jo == NULL)
5299     {
5300 	job->jv_status = JOB_FAILED;
5301 	goto failed;
5302     }
5303 
5304     if (options->jo_env != NULL)
5305 	win32_build_env(options->jo_env, &ga, FALSE);
5306 
5307     ZeroMemory(&pi, sizeof(pi));
5308     ZeroMemory(&si, sizeof(si));
5309     si.cb = sizeof(si);
5310     si.dwFlags |= STARTF_USESHOWWINDOW;
5311     si.wShowWindow = SW_HIDE;
5312 
5313     saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5314     saAttr.bInheritHandle = TRUE;
5315     saAttr.lpSecurityDescriptor = NULL;
5316 
5317     if (use_file_for_in)
5318     {
5319 	char_u *fname = options->jo_io_name[PART_IN];
5320 
5321 	ifd[0] = job_io_file_open(fname, GENERIC_READ,
5322 		FILE_SHARE_READ | FILE_SHARE_WRITE,
5323 		&saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5324 	if (ifd[0] == INVALID_HANDLE_VALUE)
5325 	{
5326 	    semsg(_(e_notopen), fname);
5327 	    goto failed;
5328 	}
5329     }
5330     else if (!use_null_for_in
5331 	    && (!create_pipe_pair(ifd)
5332 		|| !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
5333 	goto failed;
5334 
5335     if (use_file_for_out)
5336     {
5337 	char_u *fname = options->jo_io_name[PART_OUT];
5338 
5339 	ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5340 		FILE_SHARE_READ | FILE_SHARE_WRITE,
5341 		&saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5342 	if (ofd[1] == INVALID_HANDLE_VALUE)
5343 	{
5344 	    semsg(_(e_notopen), fname);
5345 	    goto failed;
5346 	}
5347     }
5348     else if (!use_null_for_out &&
5349 	    (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
5350 	    || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
5351 	goto failed;
5352 
5353     if (use_file_for_err)
5354     {
5355 	char_u *fname = options->jo_io_name[PART_ERR];
5356 
5357 	efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5358 		FILE_SHARE_READ | FILE_SHARE_WRITE,
5359 		&saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5360 	if (efd[1] == INVALID_HANDLE_VALUE)
5361 	{
5362 	    semsg(_(e_notopen), fname);
5363 	    goto failed;
5364 	}
5365     }
5366     else if (!use_out_for_err && !use_null_for_err &&
5367 	    (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
5368 	    || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
5369 	goto failed;
5370 
5371     si.dwFlags |= STARTF_USESTDHANDLES;
5372     si.hStdInput = ifd[0];
5373     si.hStdOutput = ofd[1];
5374     si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5375 
5376     if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5377     {
5378 	if (options->jo_set & JO_CHANNEL)
5379 	{
5380 	    channel = options->jo_channel;
5381 	    if (channel != NULL)
5382 		++channel->ch_refcount;
5383 	}
5384 	else
5385 	    channel = add_channel();
5386 	if (channel == NULL)
5387 	    goto failed;
5388     }
5389 
5390     if (!vim_create_process(cmd, TRUE,
5391 	    CREATE_SUSPENDED |
5392 	    CREATE_DEFAULT_ERROR_MODE |
5393 	    CREATE_NEW_PROCESS_GROUP |
5394 	    CREATE_UNICODE_ENVIRONMENT |
5395 	    CREATE_NEW_CONSOLE,
5396 	    &si, &pi,
5397 	    ga.ga_data,
5398 	    (char *)options->jo_cwd))
5399     {
5400 	CloseHandle(jo);
5401 	job->jv_status = JOB_FAILED;
5402 	goto failed;
5403     }
5404 
5405     ga_clear(&ga);
5406 
5407     if (!AssignProcessToJobObject(jo, pi.hProcess))
5408     {
5409 	// if failing, switch the way to terminate
5410 	// process with TerminateProcess.
5411 	CloseHandle(jo);
5412 	jo = NULL;
5413     }
5414     ResumeThread(pi.hThread);
5415     CloseHandle(pi.hThread);
5416     job->jv_proc_info = pi;
5417     job->jv_job_object = jo;
5418     job->jv_status = JOB_STARTED;
5419 
5420     CloseHandle(ifd[0]);
5421     CloseHandle(ofd[1]);
5422     if (!use_out_for_err && !use_null_for_err)
5423 	CloseHandle(efd[1]);
5424 
5425     job->jv_channel = channel;
5426     if (channel != NULL)
5427     {
5428 	channel_set_pipes(channel,
5429 		      use_file_for_in || use_null_for_in
5430 					      ? INVALID_FD : (sock_T)ifd[1],
5431 		      use_file_for_out || use_null_for_out
5432 					     ? INVALID_FD : (sock_T)ofd[0],
5433 		      use_out_for_err || use_file_for_err || use_null_for_err
5434 					    ? INVALID_FD : (sock_T)efd[0]);
5435 	channel_set_job(channel, job, options);
5436     }
5437     return;
5438 
5439 failed:
5440     CloseHandle(ifd[0]);
5441     CloseHandle(ofd[0]);
5442     CloseHandle(efd[0]);
5443     CloseHandle(ifd[1]);
5444     CloseHandle(ofd[1]);
5445     CloseHandle(efd[1]);
5446     channel_unref(channel);
5447     ga_clear(&ga);
5448 }
5449 
5450     char *
mch_job_status(job_T * job)5451 mch_job_status(job_T *job)
5452 {
5453     DWORD dwExitCode = 0;
5454 
5455     if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5456 	    || dwExitCode != STILL_ACTIVE)
5457     {
5458 	job->jv_exitval = (int)dwExitCode;
5459 	if (job->jv_status < JOB_ENDED)
5460 	{
5461 	    ch_log(job->jv_channel, "Job ended");
5462 	    job->jv_status = JOB_ENDED;
5463 	}
5464 	return "dead";
5465     }
5466     return "run";
5467 }
5468 
5469     job_T *
mch_detect_ended_job(job_T * job_list)5470 mch_detect_ended_job(job_T *job_list)
5471 {
5472     HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5473     job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5474     job_T *job = job_list;
5475 
5476     while (job != NULL)
5477     {
5478 	DWORD n;
5479 	DWORD result;
5480 
5481 	for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5482 				       && job != NULL; job = job->jv_next)
5483 	{
5484 	    if (job->jv_status == JOB_STARTED)
5485 	    {
5486 		jobHandles[n] = job->jv_proc_info.hProcess;
5487 		jobArray[n] = job;
5488 		++n;
5489 	    }
5490 	}
5491 	if (n == 0)
5492 	    continue;
5493 	result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5494 	if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5495 	{
5496 	    job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5497 
5498 	    if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5499 		return wait_job;
5500 	}
5501     }
5502     return NULL;
5503 }
5504 
5505     static BOOL
terminate_all(HANDLE process,int code)5506 terminate_all(HANDLE process, int code)
5507 {
5508     PROCESSENTRY32  pe;
5509     HANDLE	    h = INVALID_HANDLE_VALUE;
5510     DWORD	    pid = GetProcessId(process);
5511 
5512     if (pid != 0)
5513     {
5514 	h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5515 	if (h != INVALID_HANDLE_VALUE)
5516 	{
5517 	    pe.dwSize = sizeof(PROCESSENTRY32);
5518 	    if (!Process32First(h, &pe))
5519 		goto theend;
5520 
5521 	    do
5522 	    {
5523 		if (pe.th32ParentProcessID == pid)
5524 		{
5525 		    HANDLE ph = OpenProcess(
5526 				  PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5527 		    if (ph != NULL)
5528 		    {
5529 			terminate_all(ph, code);
5530 			CloseHandle(ph);
5531 		    }
5532 		}
5533 	    } while (Process32Next(h, &pe));
5534 
5535 	    CloseHandle(h);
5536 	}
5537     }
5538 
5539 theend:
5540     return TerminateProcess(process, code);
5541 }
5542 
5543 /*
5544  * Send a (deadly) signal to "job".
5545  * Return FAIL if it didn't work.
5546  */
5547     int
mch_signal_job(job_T * job,char_u * how)5548 mch_signal_job(job_T *job, char_u *how)
5549 {
5550     int ret;
5551 
5552     if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
5553     {
5554 	// deadly signal
5555 	if (job->jv_job_object != NULL)
5556 	{
5557 	    if (job->jv_channel != NULL && job->jv_channel->ch_anonymous_pipe)
5558 		job->jv_channel->ch_killing = TRUE;
5559 	    return TerminateJobObject(job->jv_job_object, -1) ? OK : FAIL;
5560 	}
5561 	return terminate_all(job->jv_proc_info.hProcess, -1) ? OK : FAIL;
5562     }
5563 
5564     if (!AttachConsole(job->jv_proc_info.dwProcessId))
5565 	return FAIL;
5566     ret = GenerateConsoleCtrlEvent(
5567 		STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5568 		job->jv_proc_info.dwProcessId)
5569 	    ? OK : FAIL;
5570     FreeConsole();
5571     return ret;
5572 }
5573 
5574 /*
5575  * Clear the data related to "job".
5576  */
5577     void
mch_clear_job(job_T * job)5578 mch_clear_job(job_T *job)
5579 {
5580     if (job->jv_status != JOB_FAILED)
5581     {
5582 	if (job->jv_job_object != NULL)
5583 	    CloseHandle(job->jv_job_object);
5584 	CloseHandle(job->jv_proc_info.hProcess);
5585     }
5586 }
5587 #endif
5588 
5589 
5590 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
5591 
5592 /*
5593  * Start termcap mode
5594  */
5595     static void
termcap_mode_start(void)5596 termcap_mode_start(void)
5597 {
5598     DWORD cmodein;
5599 
5600     if (g_fTermcapMode)
5601 	return;
5602 
5603     if (!p_rs && USE_VTP)
5604 	vtp_printf("\033[?1049h");
5605 
5606     SaveConsoleBuffer(&g_cbNonTermcap);
5607 
5608     if (g_cbTermcap.IsValid)
5609     {
5610 	/*
5611 	 * We've been in termcap mode before.  Restore certain screen
5612 	 * characteristics, including the buffer size and the window
5613 	 * size.  Since we will be redrawing the screen, we don't need
5614 	 * to restore the actual contents of the buffer.
5615 	 */
5616 	RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5617 	reset_console_color_rgb();
5618 	SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5619 	Rows = g_cbTermcap.Info.dwSize.Y;
5620 	Columns = g_cbTermcap.Info.dwSize.X;
5621     }
5622     else
5623     {
5624 	/*
5625 	 * This is our first time entering termcap mode.  Clear the console
5626 	 * screen buffer, and resize the buffer to match the current window
5627 	 * size.  We will use this as the size of our editing environment.
5628 	 */
5629 	ClearConsoleBuffer(g_attrCurrent);
5630 	set_console_color_rgb();
5631 	ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5632     }
5633 
5634 # ifdef FEAT_TITLE
5635     resettitle();
5636 # endif
5637 
5638     GetConsoleMode(g_hConIn, &cmodein);
5639     if (g_fMouseActive)
5640     {
5641 	cmodein |= ENABLE_MOUSE_INPUT;
5642 	cmodein &= ~ENABLE_QUICK_EDIT_MODE;
5643     }
5644     else
5645     {
5646 	cmodein &= ~ENABLE_MOUSE_INPUT;
5647 	cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5648     }
5649     cmodein |= ENABLE_WINDOW_INPUT;
5650     SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
5651 
5652     redraw_later_clear();
5653     g_fTermcapMode = TRUE;
5654 }
5655 
5656 
5657 /*
5658  * End termcap mode
5659  */
5660     static void
termcap_mode_end(void)5661 termcap_mode_end(void)
5662 {
5663     DWORD cmodein;
5664     ConsoleBuffer *cb;
5665     COORD coord;
5666     DWORD dwDummy;
5667 
5668     if (!g_fTermcapMode)
5669 	return;
5670 
5671     SaveConsoleBuffer(&g_cbTermcap);
5672 
5673     GetConsoleMode(g_hConIn, &cmodein);
5674     cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5675     cmodein |= g_cmodein & ENABLE_QUICK_EDIT_MODE;
5676     SetConsoleMode(g_hConIn, cmodein | ENABLE_EXTENDED_FLAGS);
5677 
5678 # ifdef FEAT_RESTORE_ORIG_SCREEN
5679     cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5680 # else
5681     cb = &g_cbNonTermcap;
5682 # endif
5683     RestoreConsoleBuffer(cb, p_rs);
5684     restore_console_color_rgb();
5685     SetConsoleCursorInfo(g_hConOut, &g_cci);
5686 
5687     if (p_rs || exiting)
5688     {
5689 	/*
5690 	 * Clear anything that happens to be on the current line.
5691 	 */
5692 	coord.X = 0;
5693 	coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5694 	FillConsoleOutputCharacter(g_hConOut, ' ',
5695 		cb->Info.dwSize.X, coord, &dwDummy);
5696 	/*
5697 	 * The following is just for aesthetics.  If we are exiting without
5698 	 * restoring the screen, then we want to have a prompt string
5699 	 * appear at the bottom line.  However, the command interpreter
5700 	 * seems to always advance the cursor one line before displaying
5701 	 * the prompt string, which causes the screen to scroll.  To
5702 	 * counter this, move the cursor up one line before exiting.
5703 	 */
5704 	if (exiting && !p_rs)
5705 	    coord.Y--;
5706 	/*
5707 	 * Position the cursor at the leftmost column of the desired row.
5708 	 */
5709 	SetConsoleCursorPosition(g_hConOut, coord);
5710     }
5711 
5712     if (!p_rs && USE_VTP)
5713 	vtp_printf("\033[?1049l");
5714 
5715     g_fTermcapMode = FALSE;
5716 }
5717 #endif // FEAT_GUI_MSWIN
5718 
5719 
5720 #if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
5721     void
mch_write(char_u * s UNUSED,int len UNUSED)5722 mch_write(
5723     char_u  *s UNUSED,
5724     int	    len UNUSED)
5725 {
5726     // never used
5727 }
5728 
5729 #else
5730 
5731 /*
5732  * clear `n' chars, starting from `coord'
5733  */
5734     static void
clear_chars(COORD coord,DWORD n)5735 clear_chars(
5736     COORD coord,
5737     DWORD n)
5738 {
5739     if (!USE_VTP)
5740     {
5741 	DWORD dwDummy;
5742 
5743 	FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5744 	FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord,
5745 								     &dwDummy);
5746     }
5747     else
5748     {
5749 	set_console_color_rgb();
5750 	gotoxy(coord.X + 1, coord.Y + 1);
5751 	vtp_printf("\033[%dX", n);
5752     }
5753 }
5754 
5755 
5756 /*
5757  * Clear the screen
5758  */
5759     static void
clear_screen(void)5760 clear_screen(void)
5761 {
5762     g_coord.X = g_coord.Y = 0;
5763 
5764     if (!USE_VTP)
5765 	clear_chars(g_coord, Rows * Columns);
5766     else
5767     {
5768 	set_console_color_rgb();
5769 	gotoxy(1, 1);
5770 	vtp_printf("\033[2J");
5771     }
5772 }
5773 
5774 
5775 /*
5776  * Clear to end of display
5777  */
5778     static void
clear_to_end_of_display(void)5779 clear_to_end_of_display(void)
5780 {
5781     COORD save = g_coord;
5782 
5783     if (!USE_VTP)
5784 	clear_chars(g_coord, (Rows - g_coord.Y - 1)
5785 					   * Columns + (Columns - g_coord.X));
5786     else
5787     {
5788 	set_console_color_rgb();
5789 	gotoxy(g_coord.X + 1, g_coord.Y + 1);
5790 	vtp_printf("\033[0J");
5791 
5792 	gotoxy(save.X + 1, save.Y + 1);
5793 	g_coord = save;
5794     }
5795 }
5796 
5797 
5798 /*
5799  * Clear to end of line
5800  */
5801     static void
clear_to_end_of_line(void)5802 clear_to_end_of_line(void)
5803 {
5804     COORD save = g_coord;
5805 
5806     if (!USE_VTP)
5807 	clear_chars(g_coord, Columns - g_coord.X);
5808     else
5809     {
5810 	set_console_color_rgb();
5811 	gotoxy(g_coord.X + 1, g_coord.Y + 1);
5812 	vtp_printf("\033[0K");
5813 
5814 	gotoxy(save.X + 1, save.Y + 1);
5815 	g_coord = save;
5816     }
5817 }
5818 
5819 
5820 /*
5821  * Scroll the scroll region up by `cLines' lines
5822  */
5823     static void
scroll(unsigned cLines)5824 scroll(unsigned cLines)
5825 {
5826     COORD oldcoord = g_coord;
5827 
5828     gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5829     delete_lines(cLines);
5830 
5831     g_coord = oldcoord;
5832 }
5833 
5834 
5835 /*
5836  * Set the scroll region
5837  */
5838     static void
set_scroll_region(unsigned left,unsigned top,unsigned right,unsigned bottom)5839 set_scroll_region(
5840     unsigned left,
5841     unsigned top,
5842     unsigned right,
5843     unsigned bottom)
5844 {
5845     if (left >= right
5846 	    || top >= bottom
5847 	    || right > (unsigned) Columns - 1
5848 	    || bottom > (unsigned) Rows - 1)
5849 	return;
5850 
5851     g_srScrollRegion.Left =   left;
5852     g_srScrollRegion.Top =    top;
5853     g_srScrollRegion.Right =  right;
5854     g_srScrollRegion.Bottom = bottom;
5855 }
5856 
5857     static void
set_scroll_region_tb(unsigned top,unsigned bottom)5858 set_scroll_region_tb(
5859     unsigned top,
5860     unsigned bottom)
5861 {
5862     if (top >= bottom || bottom > (unsigned)Rows - 1)
5863 	return;
5864 
5865     g_srScrollRegion.Top = top;
5866     g_srScrollRegion.Bottom = bottom;
5867 }
5868 
5869     static void
set_scroll_region_lr(unsigned left,unsigned right)5870 set_scroll_region_lr(
5871     unsigned left,
5872     unsigned right)
5873 {
5874     if (left >= right || right > (unsigned)Columns - 1)
5875 	return;
5876 
5877     g_srScrollRegion.Left = left;
5878     g_srScrollRegion.Right = right;
5879 }
5880 
5881 
5882 /*
5883  * Insert `cLines' lines at the current cursor position
5884  */
5885     static void
insert_lines(unsigned cLines)5886 insert_lines(unsigned cLines)
5887 {
5888     SMALL_RECT	    source, clip;
5889     COORD	    dest;
5890     CHAR_INFO	    fill;
5891 
5892     gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5893 
5894     dest.X = g_srScrollRegion.Left;
5895     dest.Y = g_coord.Y + cLines;
5896 
5897     source.Left   = g_srScrollRegion.Left;
5898     source.Top	  = g_coord.Y;
5899     source.Right  = g_srScrollRegion.Right;
5900     source.Bottom = g_srScrollRegion.Bottom - cLines;
5901 
5902     clip.Left   = g_srScrollRegion.Left;
5903     clip.Top    = g_coord.Y;
5904     clip.Right  = g_srScrollRegion.Right;
5905     clip.Bottom = g_srScrollRegion.Bottom;
5906 
5907     fill.Char.AsciiChar = ' ';
5908     if (!USE_VTP)
5909 	fill.Attributes = g_attrCurrent;
5910     else
5911 	fill.Attributes = g_attrDefault;
5912 
5913     set_console_color_rgb();
5914 
5915     ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5916 
5917     // Here we have to deal with a win32 console flake: If the scroll
5918     // region looks like abc and we scroll c to a and fill with d we get
5919     // cbd... if we scroll block c one line at a time to a, we get cdd...
5920     // vim expects cdd consistently... So we have to deal with that
5921     // here... (this also occurs scrolling the same way in the other
5922     // direction).
5923 
5924     if (source.Bottom < dest.Y)
5925     {
5926 	COORD coord;
5927 	int   i;
5928 
5929 	coord.X = source.Left;
5930 	for (i = clip.Top; i < dest.Y; ++i)
5931 	{
5932 	    coord.Y = i;
5933 	    clear_chars(coord, source.Right - source.Left + 1);
5934 	}
5935     }
5936 
5937     if (USE_WT)
5938     {
5939 	COORD coord;
5940 	int i;
5941 
5942 	coord.X = source.Left;
5943 	for (i = source.Top; i < dest.Y; ++i)
5944 	{
5945 	    coord.Y = i;
5946 	    clear_chars(coord, source.Right - source.Left + 1);
5947 	}
5948     }
5949 }
5950 
5951 
5952 /*
5953  * Delete `cLines' lines at the current cursor position
5954  */
5955     static void
delete_lines(unsigned cLines)5956 delete_lines(unsigned cLines)
5957 {
5958     SMALL_RECT	    source, clip;
5959     COORD	    dest;
5960     CHAR_INFO	    fill;
5961     int		    nb;
5962 
5963     gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5964 
5965     dest.X = g_srScrollRegion.Left;
5966     dest.Y = g_coord.Y;
5967 
5968     source.Left   = g_srScrollRegion.Left;
5969     source.Top	  = g_coord.Y + cLines;
5970     source.Right  = g_srScrollRegion.Right;
5971     source.Bottom = g_srScrollRegion.Bottom;
5972 
5973     clip.Left   = g_srScrollRegion.Left;
5974     clip.Top    = g_coord.Y;
5975     clip.Right  = g_srScrollRegion.Right;
5976     clip.Bottom = g_srScrollRegion.Bottom;
5977 
5978     fill.Char.AsciiChar = ' ';
5979     if (!USE_VTP)
5980 	fill.Attributes = g_attrCurrent;
5981     else
5982 	fill.Attributes = g_attrDefault;
5983 
5984     set_console_color_rgb();
5985 
5986     ScrollConsoleScreenBuffer(g_hConOut, &source, &clip, dest, &fill);
5987 
5988     // Here we have to deal with a win32 console flake; See insert_lines()
5989     // above.
5990 
5991     nb = dest.Y + (source.Bottom - source.Top) + 1;
5992 
5993     if (nb < source.Top)
5994     {
5995 	COORD coord;
5996 	int   i;
5997 
5998 	coord.X = source.Left;
5999 	for (i = nb; i < clip.Bottom; ++i)
6000 	{
6001 	    coord.Y = i;
6002 	    clear_chars(coord, source.Right - source.Left + 1);
6003 	}
6004     }
6005 
6006     if (USE_WT)
6007     {
6008 	COORD coord;
6009 	int i;
6010 
6011 	coord.X = source.Left;
6012 	for (i = nb; i <= source.Bottom; ++i)
6013 	{
6014 	    coord.Y = i;
6015 	    clear_chars(coord, source.Right - source.Left + 1);
6016 	}
6017     }
6018 }
6019 
6020 
6021 /*
6022  * Set the cursor position to (x,y) (1-based).
6023  */
6024     static void
gotoxy(unsigned x,unsigned y)6025 gotoxy(
6026     unsigned x,
6027     unsigned y)
6028 {
6029     if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6030 	return;
6031 
6032     if (!USE_VTP)
6033     {
6034 	// There are reports of double-width characters not displayed
6035 	// correctly.  This workaround should fix it, similar to how it's done
6036 	// for VTP.
6037 	g_coord.X = 0;
6038 	SetConsoleCursorPosition(g_hConOut, g_coord);
6039 
6040 	// external cursor coords are 1-based; internal are 0-based
6041 	g_coord.X = x - 1;
6042 	g_coord.Y = y - 1;
6043 	SetConsoleCursorPosition(g_hConOut, g_coord);
6044     }
6045     else
6046     {
6047 	// Move the cursor to the left edge of the screen to prevent screen
6048 	// destruction.  Insider build bug.  Always enabled because it's cheap
6049 	// and avoids mistakes with recognizing the build.
6050 	vtp_printf("\033[%d;%dH", g_coord.Y + 1, 1);
6051 
6052 	vtp_printf("\033[%d;%dH", y, x);
6053 
6054 	g_coord.X = x - 1;
6055 	g_coord.Y = y - 1;
6056     }
6057 }
6058 
6059 
6060 /*
6061  * Set the current text attribute = (foreground | background)
6062  * See ../runtime/doc/os_win32.txt for the numbers.
6063  */
6064     static void
textattr(WORD wAttr)6065 textattr(WORD wAttr)
6066 {
6067     g_attrCurrent = wAttr & 0xff;
6068 
6069     SetConsoleTextAttribute(g_hConOut, wAttr);
6070 }
6071 
6072 
6073     static void
textcolor(WORD wAttr)6074 textcolor(WORD wAttr)
6075 {
6076     g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
6077 
6078     if (!USE_VTP)
6079 	SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6080     else
6081 	vtp_sgr_bulk(wAttr);
6082 }
6083 
6084 
6085     static void
textbackground(WORD wAttr)6086 textbackground(WORD wAttr)
6087 {
6088     g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
6089 
6090     if (!USE_VTP)
6091 	SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6092     else
6093 	vtp_sgr_bulk(wAttr);
6094 }
6095 
6096 
6097 /*
6098  * restore the default text attribute (whatever we started with)
6099  */
6100     static void
normvideo(void)6101 normvideo(void)
6102 {
6103     if (!USE_VTP)
6104 	textattr(g_attrDefault);
6105     else
6106 	vtp_sgr_bulk(0);
6107 }
6108 
6109 
6110 static WORD g_attrPreStandout = 0;
6111 
6112 /*
6113  * Make the text standout, by brightening it
6114  */
6115     static void
standout(void)6116 standout(void)
6117 {
6118     g_attrPreStandout = g_attrCurrent;
6119 
6120     textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6121 }
6122 
6123 
6124 /*
6125  * Turn off standout mode
6126  */
6127     static void
standend(void)6128 standend(void)
6129 {
6130     if (g_attrPreStandout)
6131 	textattr(g_attrPreStandout);
6132 
6133     g_attrPreStandout = 0;
6134 }
6135 
6136 
6137 /*
6138  * Set normal fg/bg color, based on T_ME.  Called when t_me has been set.
6139  */
6140     void
mch_set_normal_colors(void)6141 mch_set_normal_colors(void)
6142 {
6143     char_u	*p;
6144     int		n;
6145 
6146     cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6147     cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
6148     if (
6149 # ifdef FEAT_TERMGUICOLORS
6150 	!p_tgc &&
6151 # endif
6152 	T_ME[0] == ESC && T_ME[1] == '|')
6153     {
6154 	p = T_ME + 2;
6155 	n = getdigits(&p);
6156 	if (*p == 'm' && n > 0)
6157 	{
6158 	    cterm_normal_fg_color = (n & 0xf) + 1;
6159 	    cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6160 	}
6161     }
6162 # ifdef FEAT_TERMGUICOLORS
6163     cterm_normal_fg_gui_color = INVALCOLOR;
6164     cterm_normal_bg_gui_color = INVALCOLOR;
6165 # endif
6166 }
6167 
6168 
6169 /*
6170  * visual bell: flash the screen
6171  */
6172     static void
visual_bell(void)6173 visual_bell(void)
6174 {
6175     COORD   coordOrigin = {0, 0};
6176     WORD    attrFlash = ~g_attrCurrent & 0xff;
6177 
6178     DWORD   dwDummy;
6179     LPWORD  oldattrs = ALLOC_MULT(WORD, Rows * Columns);
6180 
6181     if (oldattrs == NULL)
6182 	return;
6183     ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6184 			       coordOrigin, &dwDummy);
6185     FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6186 			       coordOrigin, &dwDummy);
6187 
6188     Sleep(15);	    // wait for 15 msec
6189     if (!USE_VTP)
6190 	WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6191 				coordOrigin, &dwDummy);
6192     vim_free(oldattrs);
6193 }
6194 
6195 
6196 /*
6197  * Make the cursor visible or invisible
6198  */
6199     static void
cursor_visible(BOOL fVisible)6200 cursor_visible(BOOL fVisible)
6201 {
6202     s_cursor_visible = fVisible;
6203 
6204     if (USE_VTP)
6205 	vtp_printf("\033[?25%c", fVisible ? 'h' : 'l');
6206 
6207 # ifdef MCH_CURSOR_SHAPE
6208     mch_update_cursor();
6209 # endif
6210 }
6211 
6212 
6213 /*
6214  * Write "cbToWrite" bytes in `pchBuf' to the screen.
6215  * Returns the number of bytes actually written (at least one).
6216  */
6217     static DWORD
write_chars(char_u * pchBuf,DWORD cbToWrite)6218 write_chars(
6219     char_u *pchBuf,
6220     DWORD  cbToWrite)
6221 {
6222     COORD	    coord = g_coord;
6223     DWORD	    written;
6224     DWORD	    n, cchwritten;
6225     static DWORD    cells;
6226     static WCHAR    *unicodebuf = NULL;
6227     static int	    unibuflen = 0;
6228     static int	    length;
6229     int		    cp = enc_utf8 ? CP_UTF8 : enc_codepage;
6230     static WCHAR    *utf8spbuf = NULL;
6231     static int	    utf8splength;
6232     static DWORD    utf8spcells;
6233     static WCHAR    **utf8usingbuf = &unicodebuf;
6234 
6235     if (cbToWrite != 1 || *pchBuf != ' ' || !enc_utf8)
6236     {
6237 	utf8usingbuf = &unicodebuf;
6238 	do
6239 	{
6240 	    length = MultiByteToWideChar(cp, 0, (LPCSTR)pchBuf, cbToWrite,
6241 							unicodebuf, unibuflen);
6242 	    if (length && length <= unibuflen)
6243 		break;
6244 	    vim_free(unicodebuf);
6245 	    unicodebuf = length ? LALLOC_MULT(WCHAR, length) : NULL;
6246 	    unibuflen = unibuflen ? 0 : length;
6247 	} while(1);
6248 	cells = mb_string2cells(pchBuf, cbToWrite);
6249     }
6250     else // cbToWrite == 1 && *pchBuf == ' ' && enc_utf8
6251     {
6252 	if (utf8usingbuf != &utf8spbuf)
6253 	{
6254 	    if (utf8spbuf == NULL)
6255 	    {
6256 		cells = mb_string2cells((char_u *)" ", 1);
6257 		length = MultiByteToWideChar(CP_UTF8, 0, " ", 1, NULL, 0);
6258 		utf8spbuf = LALLOC_MULT(WCHAR, length);
6259 		if (utf8spbuf != NULL)
6260 		{
6261 		    MultiByteToWideChar(CP_UTF8, 0, " ", 1, utf8spbuf, length);
6262 		    utf8usingbuf = &utf8spbuf;
6263 		    utf8splength = length;
6264 		    utf8spcells = cells;
6265 		}
6266 	    }
6267 	    else
6268 	    {
6269 		utf8usingbuf = &utf8spbuf;
6270 		length = utf8splength;
6271 		cells = utf8spcells;
6272 	    }
6273 	}
6274     }
6275 
6276     if (!USE_VTP)
6277     {
6278 	FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6279 				    coord, &written);
6280 	// When writing fails or didn't write a single character, pretend one
6281 	// character was written, otherwise we get stuck.
6282 	if (WriteConsoleOutputCharacterW(g_hConOut, *utf8usingbuf, length,
6283 		    coord, &cchwritten) == 0
6284 		|| cchwritten == 0 || cchwritten == (DWORD)-1)
6285 	    cchwritten = 1;
6286     }
6287     else
6288     {
6289 	if (WriteConsoleW(g_hConOut, *utf8usingbuf, length, &cchwritten,
6290 		    NULL) == 0 || cchwritten == 0)
6291 	    cchwritten = 1;
6292     }
6293 
6294     if (cchwritten == length)
6295     {
6296 	written = cbToWrite;
6297 	g_coord.X += (SHORT)cells;
6298     }
6299     else
6300     {
6301 	char_u *p = pchBuf;
6302 	for (n = 0; n < cchwritten; n++)
6303 	    MB_CPTR_ADV(p);
6304 	written = p - pchBuf;
6305 	g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6306     }
6307 
6308     while (g_coord.X > g_srScrollRegion.Right)
6309     {
6310 	g_coord.X -= (SHORT) Columns;
6311 	if (g_coord.Y < g_srScrollRegion.Bottom)
6312 	    g_coord.Y++;
6313     }
6314 
6315     // Cursor under VTP is always in the correct position, no need to reset.
6316     if (!USE_VTP)
6317 	gotoxy(g_coord.X + 1, g_coord.Y + 1);
6318 
6319     return written;
6320 }
6321 
6322     static char_u *
get_seq(int * args,int * count,char_u * head)6323 get_seq(
6324     int *args,
6325     int *count,
6326     char_u *head)
6327 {
6328     int argc;
6329     char_u *p;
6330 
6331     if (head == NULL || *head != '\033')
6332 	return NULL;
6333 
6334     argc = 0;
6335     p = head;
6336     ++p;
6337     do
6338     {
6339 	++p;
6340 	args[argc] = getdigits(&p);
6341 	argc += (argc < 15) ? 1 : 0;
6342     } while (*p == ';');
6343     *count = argc;
6344 
6345     return p;
6346 }
6347 
6348     static char_u *
get_sgr(int * args,int * count,char_u * head)6349 get_sgr(
6350     int *args,
6351     int *count,
6352     char_u *head)
6353 {
6354     char_u *p = get_seq(args, count, head);
6355 
6356     return (p && *p == 'm') ? ++p : NULL;
6357 }
6358 
6359 /*
6360  * Pointer to next if SGR (^[[n;2;*;*;*m), NULL otherwise.
6361  */
6362     static char_u *
sgrn2(char_u * head,int n)6363 sgrn2(
6364     char_u *head,
6365     int	   n)
6366 {
6367     int argc;
6368     int args[16];
6369     char_u *p = get_sgr(args, &argc, head);
6370 
6371     return p && argc == 5 && args[0] == n && args[1] == 2 ? p : NULL;
6372 }
6373 
6374 /*
6375  * Pointer to next if SGR(^[[nm)<space>ESC, NULL otherwise.
6376  */
6377     static char_u *
sgrnc(char_u * head,int n)6378 sgrnc(
6379     char_u *head,
6380     int	   n)
6381 {
6382     int argc;
6383     int args[16];
6384     char_u *p = get_sgr(args, &argc, head);
6385 
6386     return p && argc == 1 && args[0] == n && (p = skipwhite(p)) && *p == '\033'
6387 								    ? p : NULL;
6388 }
6389 
6390     static char_u *
skipblank(char_u * q)6391 skipblank(char_u *q)
6392 {
6393     char_u *p = q;
6394 
6395     while (*p == ' ' || *p == '\t' || *p == '\n' || *p == '\r')
6396 	++p;
6397     return p;
6398 }
6399 
6400 /*
6401  * Pointer to the next if any whitespace that may follow SGR is ESC, otherwise
6402  * NULL.
6403  */
6404     static char_u *
sgrn2c(char_u * head,int n)6405 sgrn2c(
6406     char_u *head,
6407     int	   n)
6408 {
6409     char_u *p = sgrn2(head, n);
6410 
6411     return p && *p != NUL && (p = skipblank(p)) && *p == '\033' ? p : NULL;
6412 }
6413 
6414 /*
6415  * If there is only a newline between the sequence immediately following it,
6416  * a pointer to the character following the newline is returned.
6417  * Otherwise NULL.
6418  */
6419     static char_u *
sgrn2cn(char_u * head,int n)6420 sgrn2cn(
6421     char_u *head,
6422     int n)
6423 {
6424     char_u *p = sgrn2(head, n);
6425 
6426     return p && p[0] == 0x0a && p[1] == '\033' ? ++p : NULL;
6427 }
6428 
6429 /*
6430  * mch_write(): write the output buffer to the screen, translating ESC
6431  * sequences into calls to console output routines.
6432  */
6433     void
mch_write(char_u * s,int len)6434 mch_write(
6435     char_u  *s,
6436     int	    len)
6437 {
6438     char_u  *end = s + len;
6439 
6440 # ifdef VIMDLL
6441     if (gui.in_use)
6442 	return;
6443 # endif
6444 
6445     if (!term_console)
6446     {
6447 	write(1, s, (unsigned)len);
6448 	return;
6449     }
6450 
6451     // translate ESC | sequences into faked bios calls
6452     while (len--)
6453     {
6454 	int prefix = -1;
6455 	char_u ch;
6456 
6457 	// While processing a sequence, on rare occasions it seems that another
6458 	// sequence may be inserted asynchronously.
6459 	if (len < 0)
6460 	{
6461 	    redraw_all_later(CLEAR);
6462 	    return;
6463 	}
6464 
6465 	while (s + ++prefix < end)
6466 	{
6467 	    ch = s[prefix];
6468 	    if (ch <= 0x1e && !(ch != '\n' && ch != '\r' && ch != '\b'
6469 						&& ch != '\a' && ch != '\033'))
6470 		break;
6471 	}
6472 
6473 	if (p_wd)
6474 	{
6475 	    WaitForChar(p_wd, FALSE);
6476 	    if (prefix != 0)
6477 		prefix = 1;
6478 	}
6479 
6480 	if (prefix != 0)
6481 	{
6482 	    DWORD nWritten;
6483 
6484 	    nWritten = write_chars(s, prefix);
6485 # ifdef MCH_WRITE_DUMP
6486 	    if (fdDump)
6487 	    {
6488 		fputc('>', fdDump);
6489 		fwrite(s, sizeof(char_u), nWritten, fdDump);
6490 		fputs("<\n", fdDump);
6491 	    }
6492 # endif
6493 	    len -= (nWritten - 1);
6494 	    s += nWritten;
6495 	}
6496 	else if (s[0] == '\n')
6497 	{
6498 	    // \n, newline: go to the beginning of the next line or scroll
6499 	    if (g_coord.Y == g_srScrollRegion.Bottom)
6500 	    {
6501 		scroll(1);
6502 		gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6503 	    }
6504 	    else
6505 	    {
6506 		gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6507 	    }
6508 # ifdef MCH_WRITE_DUMP
6509 	    if (fdDump)
6510 		fputs("\\n\n", fdDump);
6511 # endif
6512 	    s++;
6513 	}
6514 	else if (s[0] == '\r')
6515 	{
6516 	    // \r, carriage return: go to beginning of line
6517 	    gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6518 # ifdef MCH_WRITE_DUMP
6519 	    if (fdDump)
6520 		fputs("\\r\n", fdDump);
6521 # endif
6522 	    s++;
6523 	}
6524 	else if (s[0] == '\b')
6525 	{
6526 	    // \b, backspace: move cursor one position left
6527 	    if (g_coord.X > g_srScrollRegion.Left)
6528 		g_coord.X--;
6529 	    else if (g_coord.Y > g_srScrollRegion.Top)
6530 	    {
6531 		g_coord.X = g_srScrollRegion.Right;
6532 		g_coord.Y--;
6533 	    }
6534 	    gotoxy(g_coord.X + 1, g_coord.Y + 1);
6535 # ifdef MCH_WRITE_DUMP
6536 	    if (fdDump)
6537 		fputs("\\b\n", fdDump);
6538 # endif
6539 	    s++;
6540 	}
6541 	else if (s[0] == '\a')
6542 	{
6543 	    // \a, bell
6544 	    MessageBeep(0xFFFFFFFF);
6545 # ifdef MCH_WRITE_DUMP
6546 	    if (fdDump)
6547 		fputs("\\a\n", fdDump);
6548 # endif
6549 	    s++;
6550 	}
6551 	else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6552 	{
6553 # ifdef MCH_WRITE_DUMP
6554 	    char_u  *old_s = s;
6555 # endif
6556 	    char_u  *p;
6557 	    int	    arg1 = 0, arg2 = 0, argc = 0, args[16];
6558 	    char_u  *sp;
6559 
6560 	    switch (s[2])
6561 	    {
6562 	    case '0': case '1': case '2': case '3': case '4':
6563 	    case '5': case '6': case '7': case '8': case '9':
6564 		if (*(p = get_seq(args, &argc, s)) != 'm')
6565 		    goto notsgr;
6566 
6567 		p = s;
6568 
6569 		// Handling frequent optional sequences.  Output to the screen
6570 		// takes too long, so do not output as much as possible.
6571 
6572 		// If resetFG,FG,BG,<cr>,BG,FG are connected, the preceding
6573 		// resetFG,FG,BG are omitted.
6574 		if (sgrn2(sgrn2(sgrn2cn(sgrn2(sgrnc(p, 39), 38), 48), 48), 38))
6575 		{
6576 		    p = sgrn2(sgrn2(sgrnc(p, 39), 38), 48);
6577 		    len = len + 1 - (int)(p - s);
6578 		    s = p;
6579 		    break;
6580 		}
6581 
6582 		// If FG,BG,BG,FG of SGR are connected, the first FG can be
6583 		// omitted.
6584 		if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 48), 38))
6585 		    p = sp;
6586 
6587 		// If FG,BG,FG,BG of SGR are connected, the first FG can be
6588 		// omitted.
6589 		if (sgrn2(sgrn2(sgrn2c((sp = sgrn2(p, 38)), 48), 38), 48))
6590 		    p = sp;
6591 
6592 		// If BG,BG of SGR are connected, the first BG can be omitted.
6593 		if (sgrn2((sp = sgrn2(p, 48)), 48))
6594 		    p = sp;
6595 
6596 		// If restoreFG and FG are connected, the restoreFG can be
6597 	        // omitted.
6598 		if (sgrn2((sp = sgrnc(p, 39)), 38))
6599 		    p = sp;
6600 
6601 		p = get_seq(args, &argc, p);
6602 
6603 notsgr:
6604 		arg1 = args[0];
6605 		arg2 = args[1];
6606 		if (*p == 'm')
6607 		{
6608 		    if (argc == 1 && args[0] == 0)
6609 			normvideo();
6610 		    else if (argc == 1)
6611 		    {
6612 			if (USE_VTP)
6613 			    textcolor((WORD) arg1);
6614 			else
6615 			    textattr((WORD) arg1);
6616 		    }
6617 		    else if (USE_VTP)
6618 			vtp_sgr_bulks(argc, args);
6619 		}
6620 		else if (argc == 2 && *p == 'H')
6621 		{
6622 		    gotoxy(arg2, arg1);
6623 		}
6624 		else if (argc == 2 && *p == 'r')
6625 		{
6626 		    set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6627 		}
6628 		else if (argc == 2 && *p == 'R')
6629 		{
6630 		    set_scroll_region_tb(arg1, arg2);
6631 		}
6632 		else if (argc == 2 && *p == 'V')
6633 		{
6634 		    set_scroll_region_lr(arg1, arg2);
6635 		}
6636 		else if (argc == 1 && *p == 'A')
6637 		{
6638 		    gotoxy(g_coord.X + 1,
6639 			   max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6640 		}
6641 		else if (argc == 1 && *p == 'b')
6642 		{
6643 		    textbackground((WORD) arg1);
6644 		}
6645 		else if (argc == 1 && *p == 'C')
6646 		{
6647 		    gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6648 			   g_coord.Y + 1);
6649 		}
6650 		else if (argc == 1 && *p == 'f')
6651 		{
6652 		    textcolor((WORD) arg1);
6653 		}
6654 		else if (argc == 1 && *p == 'H')
6655 		{
6656 		    gotoxy(1, arg1);
6657 		}
6658 		else if (argc == 1 && *p == 'L')
6659 		{
6660 		    insert_lines(arg1);
6661 		}
6662 		else if (argc == 1 && *p == 'M')
6663 		{
6664 		    delete_lines(arg1);
6665 		}
6666 
6667 		len -= (int)(p - s);
6668 		s = p + 1;
6669 		break;
6670 
6671 	    case 'A':
6672 		gotoxy(g_coord.X + 1,
6673 		       max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6674 		goto got3;
6675 
6676 	    case 'B':
6677 		visual_bell();
6678 		goto got3;
6679 
6680 	    case 'C':
6681 		gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6682 		       g_coord.Y + 1);
6683 		goto got3;
6684 
6685 	    case 'E':
6686 		termcap_mode_end();
6687 		goto got3;
6688 
6689 	    case 'F':
6690 		standout();
6691 		goto got3;
6692 
6693 	    case 'f':
6694 		standend();
6695 		goto got3;
6696 
6697 	    case 'H':
6698 		gotoxy(1, 1);
6699 		goto got3;
6700 
6701 	    case 'j':
6702 		clear_to_end_of_display();
6703 		goto got3;
6704 
6705 	    case 'J':
6706 		clear_screen();
6707 		goto got3;
6708 
6709 	    case 'K':
6710 		clear_to_end_of_line();
6711 		goto got3;
6712 
6713 	    case 'L':
6714 		insert_lines(1);
6715 		goto got3;
6716 
6717 	    case 'M':
6718 		delete_lines(1);
6719 		goto got3;
6720 
6721 	    case 'S':
6722 		termcap_mode_start();
6723 		goto got3;
6724 
6725 	    case 'V':
6726 		cursor_visible(TRUE);
6727 		goto got3;
6728 
6729 	    case 'v':
6730 		cursor_visible(FALSE);
6731 		goto got3;
6732 
6733 	    got3:
6734 		s += 3;
6735 		len -= 2;
6736 	    }
6737 
6738 # ifdef MCH_WRITE_DUMP
6739 	    if (fdDump)
6740 	    {
6741 		fputs("ESC | ", fdDump);
6742 		fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6743 		fputc('\n', fdDump);
6744 	    }
6745 # endif
6746 	}
6747 	else
6748 	{
6749 	    // Write a single character
6750 	    DWORD nWritten;
6751 
6752 	    nWritten = write_chars(s, 1);
6753 # ifdef MCH_WRITE_DUMP
6754 	    if (fdDump)
6755 	    {
6756 		fputc('>', fdDump);
6757 		fwrite(s, sizeof(char_u), nWritten, fdDump);
6758 		fputs("<\n", fdDump);
6759 	    }
6760 # endif
6761 
6762 	    len -= (nWritten - 1);
6763 	    s += nWritten;
6764 	}
6765     }
6766 
6767 # ifdef MCH_WRITE_DUMP
6768     if (fdDump)
6769 	fflush(fdDump);
6770 # endif
6771 }
6772 
6773 #endif // FEAT_GUI_MSWIN
6774 
6775 
6776 /*
6777  * Delay for "msec" milliseconds.
6778  */
6779     void
mch_delay(long msec,int flags UNUSED)6780 mch_delay(
6781     long    msec,
6782     int	    flags UNUSED)
6783 {
6784 #if defined(FEAT_GUI_MSWIN) && !defined(VIMDLL)
6785     Sleep((int)msec);	    // never wait for input
6786 #else // Console
6787 # ifdef VIMDLL
6788     if (gui.in_use)
6789     {
6790 	Sleep((int)msec);	    // never wait for input
6791 	return;
6792     }
6793 # endif
6794     if (flags & MCH_DELAY_IGNOREINPUT)
6795 # ifdef FEAT_MZSCHEME
6796 	if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6797 	{
6798 	    int towait = p_mzq;
6799 
6800 	    // if msec is large enough, wait by portions in p_mzq
6801 	    while (msec > 0)
6802 	    {
6803 		mzvim_check_threads();
6804 		if (msec < towait)
6805 		    towait = msec;
6806 		Sleep(towait);
6807 		msec -= towait;
6808 	    }
6809 	}
6810 	else
6811 # endif
6812 	    Sleep((int)msec);
6813     else
6814 	WaitForChar(msec, FALSE);
6815 #endif
6816 }
6817 
6818 
6819 /*
6820  * This version of remove is not scared by a readonly (backup) file.
6821  * This can also remove a symbolic link like Unix.
6822  * Return 0 for success, -1 for failure.
6823  */
6824     int
mch_remove(char_u * name)6825 mch_remove(char_u *name)
6826 {
6827     WCHAR	*wn;
6828     int		n;
6829 
6830     /*
6831      * On Windows, deleting a directory's symbolic link is done by
6832      * RemoveDirectory(): mch_rmdir.  It seems unnatural, but it is fact.
6833      */
6834     if (mch_isdir(name) && mch_is_symbolic_link(name))
6835 	return mch_rmdir(name);
6836 
6837     win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6838 
6839     wn = enc_to_utf16(name, NULL);
6840     if (wn == NULL)
6841 	return -1;
6842 
6843     n = DeleteFileW(wn) ? 0 : -1;
6844     vim_free(wn);
6845     return n;
6846 }
6847 
6848 
6849 /*
6850  * Check for an "interrupt signal": CTRL-break or CTRL-C.
6851  */
6852     void
mch_breakcheck(int force UNUSED)6853 mch_breakcheck(int force UNUSED)
6854 {
6855 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
6856 # ifdef VIMDLL
6857     if (!gui.in_use)
6858 # endif
6859 	if (g_fCtrlCPressed || g_fCBrkPressed)
6860 	{
6861 	    ctrl_break_was_pressed = g_fCBrkPressed;
6862 	    g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6863 	    got_int = TRUE;
6864 	}
6865 #endif
6866 }
6867 
6868 // physical RAM to leave for the OS
6869 #define WINNT_RESERVE_BYTES     (256*1024*1024)
6870 
6871 /*
6872  * How much main memory in KiB that can be used by VIM.
6873  */
6874     long_u
mch_total_mem(int special UNUSED)6875 mch_total_mem(int special UNUSED)
6876 {
6877     MEMORYSTATUSEX  ms;
6878 
6879     // Need to use GlobalMemoryStatusEx() when there is more memory than
6880     // what fits in 32 bits.
6881     ms.dwLength = sizeof(MEMORYSTATUSEX);
6882     GlobalMemoryStatusEx(&ms);
6883     if (ms.ullAvailVirtual < ms.ullTotalPhys)
6884     {
6885 	// Process address space fits in physical RAM, use all of it.
6886 	return (long_u)(ms.ullAvailVirtual / 1024);
6887     }
6888     if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6889     {
6890 	// Catch old NT box or perverse hardware setup.
6891 	return (long_u)((ms.ullTotalPhys / 2) / 1024);
6892     }
6893     // Use physical RAM less reserve for OS + data.
6894     return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6895 }
6896 
6897 /*
6898  * mch_wrename() works around a bug in rename (aka MoveFile) in
6899  * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6900  * file whose short file name is "FOO.BAR" (its long file name will
6901  * be correct: "foo.bar~").  Because a file can be accessed by
6902  * either its SFN or its LFN, "foo.bar" has effectively been
6903  * renamed to "foo.bar", which is not at all what was wanted.  This
6904  * seems to happen only when renaming files with three-character
6905  * extensions by appending a suffix that does not include ".".
6906  * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6907  *
6908  * There is another problem, which isn't really a bug but isn't right either:
6909  * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6910  * "abcdef~1.txt" again.  This has been reported on Windows NT 4.0 with
6911  * service pack 6.  Doesn't seem to happen on Windows 98.
6912  *
6913  * Like rename(), returns 0 upon success, non-zero upon failure.
6914  * Should probably set errno appropriately when errors occur.
6915  */
6916     int
mch_wrename(WCHAR * wold,WCHAR * wnew)6917 mch_wrename(WCHAR *wold, WCHAR *wnew)
6918 {
6919     WCHAR	*p;
6920     int		i;
6921     WCHAR	szTempFile[_MAX_PATH + 1];
6922     WCHAR	szNewPath[_MAX_PATH + 1];
6923     HANDLE	hf;
6924 
6925     // No need to play tricks unless the file name contains a "~" as the
6926     // seventh character.
6927     p = wold;
6928     for (i = 0; wold[i] != NUL; ++i)
6929 	if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6930 		&& wold[i + 1] != 0)
6931 	    p = wold + i + 1;
6932     if ((int)(wold + i - p) < 8 || p[6] != '~')
6933 	return (MoveFileW(wold, wnew) == 0);
6934 
6935     // Get base path of new file name.  Undocumented feature: If pszNewFile is
6936     // a directory, no error is returned and pszFilePart will be NULL.
6937     if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6938 	return -1;
6939     *p = NUL;
6940 
6941     // Get (and create) a unique temporary file name in directory of new file
6942     if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6943 	return -2;
6944 
6945     // blow the temp file away
6946     if (!DeleteFileW(szTempFile))
6947 	return -3;
6948 
6949     // rename old file to the temp file
6950     if (!MoveFileW(wold, szTempFile))
6951 	return -4;
6952 
6953     // now create an empty file called pszOldFile; this prevents the operating
6954     // system using pszOldFile as an alias (SFN) if we're renaming within the
6955     // same directory.  For example, we're editing a file called
6956     // filename.asc.txt by its SFN, filena~1.txt.  If we rename filena~1.txt
6957     // to filena~1.txt~ (i.e., we're making a backup while writing it), the
6958     // SFN for filena~1.txt~ will be filena~1.txt, by default, which will
6959     // cause all sorts of problems later in buf_write().  So, we create an
6960     // empty file called filena~1.txt and the system will have to find some
6961     // other SFN for filena~1.txt~, such as filena~2.txt
6962     if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6963 		    FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6964 	return -5;
6965     if (!CloseHandle(hf))
6966 	return -6;
6967 
6968     // rename the temp file to the new file
6969     if (!MoveFileW(szTempFile, wnew))
6970     {
6971 	// Renaming failed.  Rename the file back to its old name, so that it
6972 	// looks like nothing happened.
6973 	(void)MoveFileW(szTempFile, wold);
6974 	return -7;
6975     }
6976 
6977     // Seems to be left around on Novell filesystems
6978     DeleteFileW(szTempFile);
6979 
6980     // finally, remove the empty old file
6981     if (!DeleteFileW(wold))
6982 	return -8;
6983 
6984     return 0;
6985 }
6986 
6987 
6988 /*
6989  * Converts the filenames to UTF-16, then call mch_wrename().
6990  * Like rename(), returns 0 upon success, non-zero upon failure.
6991  */
6992     int
mch_rename(const char * pszOldFile,const char * pszNewFile)6993 mch_rename(
6994     const char	*pszOldFile,
6995     const char	*pszNewFile)
6996 {
6997     WCHAR	*wold = NULL;
6998     WCHAR	*wnew = NULL;
6999     int		retval = -1;
7000 
7001     wold = enc_to_utf16((char_u *)pszOldFile, NULL);
7002     wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
7003     if (wold != NULL && wnew != NULL)
7004 	retval = mch_wrename(wold, wnew);
7005     vim_free(wold);
7006     vim_free(wnew);
7007     return retval;
7008 }
7009 
7010 /*
7011  * Get the default shell for the current hardware platform
7012  */
7013     char *
default_shell(void)7014 default_shell(void)
7015 {
7016     return "cmd.exe";
7017 }
7018 
7019 /*
7020  * mch_access() extends access() to do more detailed check on network drives.
7021  * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
7022  */
7023     int
mch_access(char * n,int p)7024 mch_access(char *n, int p)
7025 {
7026     HANDLE	hFile;
7027     int		retval = -1;	    // default: fail
7028     WCHAR	*wn;
7029 
7030     wn = enc_to_utf16((char_u *)n, NULL);
7031     if (wn == NULL)
7032 	return -1;
7033 
7034     if (mch_isdir((char_u *)n))
7035     {
7036 	WCHAR TempNameW[_MAX_PATH + 16] = L"";
7037 
7038 	if (p & R_OK)
7039 	{
7040 	    // Read check is performed by seeing if we can do a find file on
7041 	    // the directory for any file.
7042 	    int			i;
7043 	    WIN32_FIND_DATAW    d;
7044 
7045 	    for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
7046 		TempNameW[i] = wn[i];
7047 	    if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
7048 		TempNameW[i++] = '\\';
7049 	    TempNameW[i++] = '*';
7050 	    TempNameW[i++] = 0;
7051 
7052 	    hFile = FindFirstFileW(TempNameW, &d);
7053 	    if (hFile == INVALID_HANDLE_VALUE)
7054 		goto getout;
7055 	    else
7056 		(void)FindClose(hFile);
7057 	}
7058 
7059 	if (p & W_OK)
7060 	{
7061 	    // Trying to create a temporary file in the directory should catch
7062 	    // directories on read-only network shares.  However, in
7063 	    // directories whose ACL allows writes but denies deletes will end
7064 	    // up keeping the temporary file :-(.
7065 	    if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
7066 		goto getout;
7067 	    else
7068 		DeleteFileW(TempNameW);
7069 	}
7070     }
7071     else
7072     {
7073 	// Don't consider a file read-only if another process has opened it.
7074 	DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7075 
7076 	// Trying to open the file for the required access does ACL, read-only
7077 	// network share, and file attribute checks.
7078 	DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7079 					     | ((p & R_OK) ? GENERIC_READ : 0);
7080 
7081 	hFile = CreateFileW(wn, access_mode, share_mode,
7082 					     NULL, OPEN_EXISTING, 0, NULL);
7083 	if (hFile == INVALID_HANDLE_VALUE)
7084 	    goto getout;
7085 	CloseHandle(hFile);
7086     }
7087 
7088     retval = 0;	    // success
7089 getout:
7090     vim_free(wn);
7091     return retval;
7092 }
7093 
7094 /*
7095  * Version of open() that may use UTF-16 file name.
7096  */
7097     int
mch_open(const char * name,int flags,int mode)7098 mch_open(const char *name, int flags, int mode)
7099 {
7100     WCHAR	*wn;
7101     int		f;
7102 
7103     wn = enc_to_utf16((char_u *)name, NULL);
7104     if (wn == NULL)
7105 	return -1;
7106 
7107     f = _wopen(wn, flags, mode);
7108     vim_free(wn);
7109     return f;
7110 }
7111 
7112 /*
7113  * Version of fopen() that uses UTF-16 file name.
7114  */
7115     FILE *
mch_fopen(const char * name,const char * mode)7116 mch_fopen(const char *name, const char *mode)
7117 {
7118     WCHAR	*wn, *wm;
7119     FILE	*f = NULL;
7120 
7121 #if defined(DEBUG) && _MSC_VER >= 1400
7122     // Work around an annoying assertion in the Microsoft debug CRT
7123     // when mode's text/binary setting doesn't match _get_fmode().
7124     char newMode = mode[strlen(mode) - 1];
7125     int oldMode = 0;
7126 
7127     _get_fmode(&oldMode);
7128     if (newMode == 't')
7129 	_set_fmode(_O_TEXT);
7130     else if (newMode == 'b')
7131 	_set_fmode(_O_BINARY);
7132 #endif
7133     wn = enc_to_utf16((char_u *)name, NULL);
7134     wm = enc_to_utf16((char_u *)mode, NULL);
7135     if (wn != NULL && wm != NULL)
7136 	f = _wfopen(wn, wm);
7137     vim_free(wn);
7138     vim_free(wm);
7139 
7140 #if defined(DEBUG) && _MSC_VER >= 1400
7141     _set_fmode(oldMode);
7142 #endif
7143     return f;
7144 }
7145 
7146 /*
7147  * SUB STREAM (aka info stream) handling:
7148  *
7149  * NTFS can have sub streams for each file.  The normal contents of a file is
7150  * stored in the main stream, and extra contents (author information, title and
7151  * so on) can be stored in a sub stream.  After Windows 2000, the user can
7152  * access and store this information in sub streams via an explorer's property
7153  * menu item in the right click menu.  This information in sub streams was lost
7154  * when copying only the main stream.  Therefore we have to copy sub streams.
7155  *
7156  * Incomplete explanation:
7157  *	http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7158  * More useful info and an example:
7159  *	http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7160  */
7161 
7162 /*
7163  * Copy info stream data "substream".  Read from the file with BackupRead(sh)
7164  * and write to stream "substream" of file "to".
7165  * Errors are ignored.
7166  */
7167     static void
copy_substream(HANDLE sh,void * context,WCHAR * to,WCHAR * substream,long len)7168 copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7169 {
7170     HANDLE  hTo;
7171     WCHAR   *to_name;
7172 
7173     to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7174     wcscpy(to_name, to);
7175     wcscat(to_name, substream);
7176 
7177     hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7178 						 FILE_ATTRIBUTE_NORMAL, NULL);
7179     if (hTo != INVALID_HANDLE_VALUE)
7180     {
7181 	long	done;
7182 	DWORD	todo;
7183 	DWORD	readcnt, written;
7184 	char	buf[4096];
7185 
7186 	// Copy block of bytes at a time.  Abort when something goes wrong.
7187 	for (done = 0; done < len; done += written)
7188 	{
7189 	    // (size_t) cast for Borland C 5.5
7190 	    todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7191 						       : (size_t)(len - done));
7192 	    if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7193 						       FALSE, FALSE, context)
7194 		    || readcnt != todo
7195 		    || !WriteFile(hTo, buf, todo, &written, NULL)
7196 		    || written != todo)
7197 		break;
7198 	}
7199 	CloseHandle(hTo);
7200     }
7201 
7202     free(to_name);
7203 }
7204 
7205 /*
7206  * Copy info streams from file "from" to file "to".
7207  */
7208     static void
copy_infostreams(char_u * from,char_u * to)7209 copy_infostreams(char_u *from, char_u *to)
7210 {
7211     WCHAR		*fromw;
7212     WCHAR		*tow;
7213     HANDLE		sh;
7214     WIN32_STREAM_ID	sid;
7215     int			headersize;
7216     WCHAR		streamname[_MAX_PATH];
7217     DWORD		readcount;
7218     void		*context = NULL;
7219     DWORD		lo, hi;
7220     int			len;
7221 
7222     // Convert the file names to wide characters.
7223     fromw = enc_to_utf16(from, NULL);
7224     tow = enc_to_utf16(to, NULL);
7225     if (fromw != NULL && tow != NULL)
7226     {
7227 	// Open the file for reading.
7228 	sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7229 			     OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7230 	if (sh != INVALID_HANDLE_VALUE)
7231 	{
7232 	    // Use BackupRead() to find the info streams.  Repeat until we
7233 	    // have done them all.
7234 	    for (;;)
7235 	    {
7236 		// Get the header to find the length of the stream name.  If
7237 		// the "readcount" is zero we have done all info streams.
7238 		ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
7239 		headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
7240 		if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7241 					   &readcount, FALSE, FALSE, &context)
7242 			|| readcount == 0)
7243 		    break;
7244 
7245 		// We only deal with streams that have a name.  The normal
7246 		// file data appears to be without a name, even though docs
7247 		// suggest it is called "::$DATA".
7248 		if (sid.dwStreamNameSize > 0)
7249 		{
7250 		    // Read the stream name.
7251 		    if (!BackupRead(sh, (LPBYTE)streamname,
7252 							 sid.dwStreamNameSize,
7253 					  &readcount, FALSE, FALSE, &context))
7254 			break;
7255 
7256 		    // Copy an info stream with a name ":anything:$DATA".
7257 		    // Skip "::$DATA", it has no stream name (examples suggest
7258 		    // it might be used for the normal file contents).
7259 		    // Note that BackupRead() counts bytes, but the name is in
7260 		    // wide characters.
7261 		    len = readcount / sizeof(WCHAR);
7262 		    streamname[len] = 0;
7263 		    if (len > 7 && wcsicmp(streamname + len - 6,
7264 							      L":$DATA") == 0)
7265 		    {
7266 			streamname[len - 6] = 0;
7267 			copy_substream(sh, &context, tow, streamname,
7268 						    (long)sid.Size.u.LowPart);
7269 		    }
7270 		}
7271 
7272 		// Advance to the next stream.  We might try seeking too far,
7273 		// but BackupSeek() doesn't skip over stream borders, thus
7274 		// that's OK.
7275 		(void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
7276 							  &lo, &hi, &context);
7277 	    }
7278 
7279 	    // Clear the context.
7280 	    (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7281 
7282 	    CloseHandle(sh);
7283 	}
7284     }
7285     vim_free(fromw);
7286     vim_free(tow);
7287 }
7288 
7289 /*
7290  * ntdll.dll definitions
7291  */
7292 #define FileEaInformation   7
7293 #ifndef STATUS_SUCCESS
7294 # define STATUS_SUCCESS	    ((NTSTATUS) 0x00000000L)
7295 #endif
7296 
7297 typedef struct _FILE_FULL_EA_INFORMATION_ {
7298     ULONG  NextEntryOffset;
7299     UCHAR  Flags;
7300     UCHAR  EaNameLength;
7301     USHORT EaValueLength;
7302     CHAR   EaName[1];
7303 } FILE_FULL_EA_INFORMATION_, *PFILE_FULL_EA_INFORMATION_;
7304 
7305 typedef struct _FILE_EA_INFORMATION_ {
7306     ULONG EaSize;
7307 } FILE_EA_INFORMATION_, *PFILE_EA_INFORMATION_;
7308 
7309 typedef NTSTATUS (NTAPI *PfnNtOpenFile)(
7310 	PHANDLE FileHandle,
7311 	ACCESS_MASK DesiredAccess,
7312 	POBJECT_ATTRIBUTES ObjectAttributes,
7313 	PIO_STATUS_BLOCK IoStatusBlock,
7314 	ULONG ShareAccess,
7315 	ULONG OpenOptions);
7316 typedef NTSTATUS (NTAPI *PfnNtClose)(
7317 	HANDLE Handle);
7318 typedef NTSTATUS (NTAPI *PfnNtSetEaFile)(
7319 	HANDLE           FileHandle,
7320 	PIO_STATUS_BLOCK IoStatusBlock,
7321 	PVOID            Buffer,
7322 	ULONG            Length);
7323 typedef NTSTATUS (NTAPI *PfnNtQueryEaFile)(
7324 	HANDLE FileHandle,
7325 	PIO_STATUS_BLOCK IoStatusBlock,
7326 	PVOID Buffer,
7327 	ULONG Length,
7328 	BOOLEAN ReturnSingleEntry,
7329 	PVOID EaList,
7330 	ULONG EaListLength,
7331 	PULONG EaIndex,
7332 	BOOLEAN RestartScan);
7333 typedef NTSTATUS (NTAPI *PfnNtQueryInformationFile)(
7334 	HANDLE                 FileHandle,
7335 	PIO_STATUS_BLOCK       IoStatusBlock,
7336 	PVOID                  FileInformation,
7337 	ULONG                  Length,
7338 	FILE_INFORMATION_CLASS FileInformationClass);
7339 typedef VOID (NTAPI *PfnRtlInitUnicodeString)(
7340 	PUNICODE_STRING DestinationString,
7341 	PCWSTR SourceString);
7342 
7343 PfnNtOpenFile pNtOpenFile = NULL;
7344 PfnNtClose pNtClose = NULL;
7345 PfnNtSetEaFile pNtSetEaFile = NULL;
7346 PfnNtQueryEaFile pNtQueryEaFile = NULL;
7347 PfnNtQueryInformationFile pNtQueryInformationFile = NULL;
7348 PfnRtlInitUnicodeString pRtlInitUnicodeString = NULL;
7349 
7350 /*
7351  * Load ntdll.dll functions.
7352  */
7353     static BOOL
load_ntdll(void)7354 load_ntdll(void)
7355 {
7356     static int	loaded = -1;
7357 
7358     if (loaded == -1)
7359     {
7360 	HMODULE hNtdll = GetModuleHandle("ntdll.dll");
7361 	if (hNtdll != NULL)
7362 	{
7363 	    pNtOpenFile = (PfnNtOpenFile) GetProcAddress(hNtdll, "NtOpenFile");
7364 	    pNtClose = (PfnNtClose) GetProcAddress(hNtdll, "NtClose");
7365 	    pNtSetEaFile = (PfnNtSetEaFile)
7366 		GetProcAddress(hNtdll, "NtSetEaFile");
7367 	    pNtQueryEaFile = (PfnNtQueryEaFile)
7368 		GetProcAddress(hNtdll, "NtQueryEaFile");
7369 	    pNtQueryInformationFile = (PfnNtQueryInformationFile)
7370 		GetProcAddress(hNtdll, "NtQueryInformationFile");
7371 	    pRtlInitUnicodeString = (PfnRtlInitUnicodeString)
7372 		GetProcAddress(hNtdll, "RtlInitUnicodeString");
7373 	}
7374 	if (pNtOpenFile == NULL
7375 		|| pNtClose == NULL
7376 		|| pNtSetEaFile == NULL
7377 		|| pNtQueryEaFile == NULL
7378 		|| pNtQueryInformationFile == NULL
7379 		|| pRtlInitUnicodeString == NULL)
7380 	    loaded = FALSE;
7381 	else
7382 	    loaded = TRUE;
7383     }
7384     return (BOOL) loaded;
7385 }
7386 
7387 /*
7388  * Copy extended attributes (EA) from file "from" to file "to".
7389  */
7390     static void
copy_extattr(char_u * from,char_u * to)7391 copy_extattr(char_u *from, char_u *to)
7392 {
7393     char_u		    *fromf = NULL;
7394     char_u		    *tof = NULL;
7395     WCHAR		    *fromw = NULL;
7396     WCHAR		    *tow = NULL;
7397     UNICODE_STRING	    u;
7398     HANDLE		    h;
7399     OBJECT_ATTRIBUTES	    oa;
7400     IO_STATUS_BLOCK	    iosb;
7401     FILE_EA_INFORMATION_    eainfo = {0};
7402     void		    *ea = NULL;
7403 
7404     if (!load_ntdll())
7405 	return;
7406 
7407     // Convert the file names to the fully qualified object names.
7408     fromf = alloc(STRLEN(from) + 5);
7409     tof = alloc(STRLEN(to) + 5);
7410     if (fromf == NULL || tof == NULL)
7411 	goto theend;
7412     STRCPY(fromf, "\\??\\");
7413     STRCAT(fromf, from);
7414     STRCPY(tof, "\\??\\");
7415     STRCAT(tof, to);
7416 
7417     // Convert the names to wide characters.
7418     fromw = enc_to_utf16(fromf, NULL);
7419     tow = enc_to_utf16(tof, NULL);
7420     if (fromw == NULL || tow == NULL)
7421 	goto theend;
7422 
7423     // Get the EA.
7424     pRtlInitUnicodeString(&u, fromw);
7425     InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7426     if (pNtOpenFile(&h, FILE_READ_EA, &oa, &iosb, 0,
7427 		FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7428 	goto theend;
7429     pNtQueryInformationFile(h, &iosb, &eainfo, sizeof(eainfo),
7430 	    FileEaInformation);
7431     if (eainfo.EaSize != 0)
7432     {
7433 	ea = alloc(eainfo.EaSize);
7434 	if (ea != NULL)
7435 	{
7436 	    if (pNtQueryEaFile(h, &iosb, ea, eainfo.EaSize, FALSE,
7437 			NULL, 0, NULL, TRUE) != STATUS_SUCCESS)
7438 	    {
7439 		vim_free(ea);
7440 		ea = NULL;
7441 	    }
7442 	}
7443     }
7444     pNtClose(h);
7445 
7446     // Set the EA.
7447     if (ea != NULL)
7448     {
7449 	pRtlInitUnicodeString(&u, tow);
7450 	InitializeObjectAttributes(&oa, &u, 0, NULL, NULL);
7451 	if (pNtOpenFile(&h, FILE_WRITE_EA, &oa, &iosb, 0,
7452 		    FILE_NON_DIRECTORY_FILE) != STATUS_SUCCESS)
7453 	    goto theend;
7454 
7455 	pNtSetEaFile(h, &iosb, ea, eainfo.EaSize);
7456 	pNtClose(h);
7457     }
7458 
7459 theend:
7460     vim_free(fromf);
7461     vim_free(tof);
7462     vim_free(fromw);
7463     vim_free(tow);
7464     vim_free(ea);
7465 }
7466 
7467 /*
7468  * Copy file attributes from file "from" to file "to".
7469  * For Windows NT and later we copy info streams.
7470  * Always returns zero, errors are ignored.
7471  */
7472     int
mch_copy_file_attribute(char_u * from,char_u * to)7473 mch_copy_file_attribute(char_u *from, char_u *to)
7474 {
7475     // File streams only work on Windows NT and later.
7476     copy_infostreams(from, to);
7477     copy_extattr(from, to);
7478     return 0;
7479 }
7480 
7481 #if defined(MYRESETSTKOFLW) || defined(PROTO)
7482 /*
7483  * Recreate a destroyed stack guard page in win32.
7484  * Written by Benjamin Peterson.
7485  */
7486 
7487 // These magic numbers are from the MS header files
7488 # define MIN_STACK_WINNT 2
7489 
7490 /*
7491  * This function does the same thing as _resetstkoflw(), which is only
7492  * available in DevStudio .net and later.
7493  * Returns 0 for failure, 1 for success.
7494  */
7495     int
myresetstkoflw(void)7496 myresetstkoflw(void)
7497 {
7498     BYTE	*pStackPtr;
7499     BYTE	*pGuardPage;
7500     BYTE	*pStackBase;
7501     BYTE	*pLowestPossiblePage;
7502     MEMORY_BASIC_INFORMATION mbi;
7503     SYSTEM_INFO si;
7504     DWORD	nPageSize;
7505     DWORD	dummy;
7506 
7507     // We need to know the system page size.
7508     GetSystemInfo(&si);
7509     nPageSize = si.dwPageSize;
7510 
7511     // ...and the current stack pointer
7512     pStackPtr = (BYTE*)_alloca(1);
7513 
7514     // ...and the base of the stack.
7515     if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7516 	return 0;
7517     pStackBase = (BYTE*)mbi.AllocationBase;
7518 
7519     // ...and the page that's min_stack_req pages away from stack base; this is
7520     // the lowest page we could use.
7521     pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
7522 
7523     {
7524 	// We want the first committed page in the stack Start at the stack
7525 	// base and move forward through memory until we find a committed block.
7526 	BYTE *pBlock = pStackBase;
7527 
7528 	for (;;)
7529 	{
7530 	    if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7531 		return 0;
7532 
7533 	    pBlock += mbi.RegionSize;
7534 
7535 	    if (mbi.State & MEM_COMMIT)
7536 		break;
7537 	}
7538 
7539 	// mbi now describes the first committed block in the stack.
7540 	if (mbi.Protect & PAGE_GUARD)
7541 	    return 1;
7542 
7543 	// decide where the guard page should start
7544 	if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7545 	    pGuardPage = pLowestPossiblePage;
7546 	else
7547 	    pGuardPage = (BYTE*)mbi.BaseAddress;
7548 
7549 	// allocate the guard page
7550 	if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7551 	    return 0;
7552 
7553 	// apply the guard attribute to the page
7554 	if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7555 								      &dummy))
7556 	    return 0;
7557     }
7558 
7559     return 1;
7560 }
7561 #endif
7562 
7563 
7564 /*
7565  * The command line arguments in UTF-16
7566  */
7567 static int	nArgsW = 0;
7568 static LPWSTR	*ArglistW = NULL;
7569 static int	global_argc = 0;
7570 static char	**global_argv;
7571 
7572 static int	used_file_argc = 0;	// last argument in global_argv[] used
7573 					// for the argument list.
7574 static int	*used_file_indexes = NULL; // indexes in global_argv[] for
7575 					   // command line arguments added to
7576 					   // the argument list
7577 static int	used_file_count = 0;	// nr of entries in used_file_indexes
7578 static int	used_file_literal = FALSE;  // take file names literally
7579 static int	used_file_full_path = FALSE;  // file name was full path
7580 static int	used_file_diff_mode = FALSE;  // file name was with diff mode
7581 static int	used_alist_count = 0;
7582 
7583 
7584 /*
7585  * Get the command line arguments.  Unicode version.
7586  * Returns argc.  Zero when something fails.
7587  */
7588     int
get_cmd_argsW(char *** argvp)7589 get_cmd_argsW(char ***argvp)
7590 {
7591     char	**argv = NULL;
7592     int		argc = 0;
7593     int		i;
7594 
7595     free_cmd_argsW();
7596     ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7597     if (ArglistW != NULL)
7598     {
7599 	argv = malloc((nArgsW + 1) * sizeof(char *));
7600 	if (argv != NULL)
7601 	{
7602 	    argc = nArgsW;
7603 	    argv[argc] = NULL;
7604 	    for (i = 0; i < argc; ++i)
7605 	    {
7606 		int	len;
7607 
7608 		// Convert each Unicode argument to UTF-8.
7609 		WideCharToMultiByte_alloc(CP_UTF8, 0,
7610 				ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
7611 				(LPSTR *)&argv[i], &len, 0, 0);
7612 		if (argv[i] == NULL)
7613 		{
7614 		    // Out of memory, clear everything.
7615 		    while (i > 0)
7616 			free(argv[--i]);
7617 		    free(argv);
7618 		    argv = NULL;
7619 		    argc = 0;
7620 		}
7621 	    }
7622 	}
7623     }
7624 
7625     global_argc = argc;
7626     global_argv = argv;
7627     if (argc > 0)
7628     {
7629 	if (used_file_indexes != NULL)
7630 	    free(used_file_indexes);
7631 	used_file_indexes = malloc(argc * sizeof(int));
7632     }
7633 
7634     if (argvp != NULL)
7635 	*argvp = argv;
7636     return argc;
7637 }
7638 
7639     void
free_cmd_argsW(void)7640 free_cmd_argsW(void)
7641 {
7642     if (ArglistW != NULL)
7643     {
7644 	GlobalFree(ArglistW);
7645 	ArglistW = NULL;
7646     }
7647 }
7648 
7649 /*
7650  * Remember "name" is an argument that was added to the argument list.
7651  * This avoids that we have to re-parse the argument list when fix_arg_enc()
7652  * is called.
7653  */
7654     void
used_file_arg(char * name,int literal,int full_path,int diff_mode)7655 used_file_arg(char *name, int literal, int full_path, int diff_mode)
7656 {
7657     int		i;
7658 
7659     if (used_file_indexes == NULL)
7660 	return;
7661     for (i = used_file_argc + 1; i < global_argc; ++i)
7662 	if (STRCMP(global_argv[i], name) == 0)
7663 	{
7664 	    used_file_argc = i;
7665 	    used_file_indexes[used_file_count++] = i;
7666 	    break;
7667 	}
7668     used_file_literal = literal;
7669     used_file_full_path = full_path;
7670     used_file_diff_mode = diff_mode;
7671 }
7672 
7673 /*
7674  * Remember the length of the argument list as it was.  If it changes then we
7675  * leave it alone when 'encoding' is set.
7676  */
7677     void
set_alist_count(void)7678 set_alist_count(void)
7679 {
7680     used_alist_count = GARGCOUNT;
7681 }
7682 
7683 /*
7684  * Fix the encoding of the command line arguments.  Invoked when 'encoding'
7685  * has been changed while starting up.  Use the UTF-16 command line arguments
7686  * and convert them to 'encoding'.
7687  */
7688     void
fix_arg_enc(void)7689 fix_arg_enc(void)
7690 {
7691     int		i;
7692     int		idx;
7693     char_u	*str;
7694     int		*fnum_list;
7695 
7696     // Safety checks:
7697     // - if argument count differs between the wide and non-wide argument
7698     //   list, something must be wrong.
7699     // - the file name arguments must have been located.
7700     // - the length of the argument list wasn't changed by the user.
7701     if (global_argc != nArgsW
7702 	    || ArglistW == NULL
7703 	    || used_file_indexes == NULL
7704 	    || used_file_count == 0
7705 	    || used_alist_count != GARGCOUNT)
7706 	return;
7707 
7708     // Remember the buffer numbers for the arguments.
7709     fnum_list = ALLOC_MULT(int, GARGCOUNT);
7710     if (fnum_list == NULL)
7711 	return;		// out of memory
7712     for (i = 0; i < GARGCOUNT; ++i)
7713 	fnum_list[i] = GARGLIST[i].ae_fnum;
7714 
7715     // Clear the argument list.  Make room for the new arguments.
7716     alist_clear(&global_alist);
7717     if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
7718 	return;		// out of memory
7719 
7720     for (i = 0; i < used_file_count; ++i)
7721     {
7722 	idx = used_file_indexes[i];
7723 	str = utf16_to_enc(ArglistW[idx], NULL);
7724 	if (str != NULL)
7725 	{
7726 	    int literal = used_file_literal;
7727 
7728 #ifdef FEAT_DIFF
7729 	    // When using diff mode may need to concatenate file name to
7730 	    // directory name.  Just like it's done in main().
7731 	    if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7732 				      && !mch_isdir(alist_name(&GARGLIST[0])))
7733 	    {
7734 		char_u	    *r;
7735 
7736 		r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7737 		if (r != NULL)
7738 		{
7739 		    vim_free(str);
7740 		    str = r;
7741 		}
7742 	    }
7743 #endif
7744 	    // Re-use the old buffer by renaming it.  When not using literal
7745 	    // names it's done by alist_expand() below.
7746 	    if (used_file_literal)
7747 		buf_set_name(fnum_list[i], str);
7748 
7749 	    // Check backtick literal. backtick literal is already expanded in
7750 	    // main.c, so this part add str as literal.
7751 	    if (literal == FALSE)
7752 	    {
7753 		size_t len = STRLEN(str);
7754 
7755 		if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7756 		    literal = TRUE;
7757 	    }
7758 	    alist_add(&global_alist, str, literal ? 2 : 0);
7759 	}
7760     }
7761 
7762     if (!used_file_literal)
7763     {
7764 	// Now expand wildcards in the arguments.
7765 	// Temporarily add '(' and ')' to 'isfname'.  These are valid
7766 	// filename characters but are excluded from 'isfname' to make
7767 	// "gf" work on a file name in parenthesis (e.g.: see vim.h).
7768 	// Also, unset wildignore to not be influenced by this option.
7769 	// The arguments specified in command-line should be kept even if
7770 	// encoding options were changed.
7771 	// Use :legacy so that it also works when in Vim9 script.
7772 	do_cmdline_cmd((char_u *)":legacy let g:SaVe_ISF = &isf|set isf+=(,)");
7773 	do_cmdline_cmd((char_u *)":legacy let g:SaVe_WIG = &wig|set wig=");
7774 	alist_expand(fnum_list, used_alist_count);
7775 	do_cmdline_cmd(
7776 		(char_u *)":legacy let &isf = g:SaVe_ISF|unlet g:SaVe_ISF");
7777 	do_cmdline_cmd(
7778 		(char_u *)":legacy let &wig = g:SaVe_WIG|unlet g:SaVe_WIG");
7779     }
7780 
7781     // If wildcard expansion failed, we are editing the first file of the
7782     // arglist and there is no file name: Edit the first argument now.
7783     if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7784     {
7785 	do_cmdline_cmd((char_u *)":rewind");
7786 	if (GARGCOUNT == 1 && used_file_full_path
7787 		&& vim_chdirfile(alist_name(&GARGLIST[0]), "drop") == OK)
7788 	    last_chdir_reason = "drop";
7789     }
7790 
7791     set_alist_count();
7792 }
7793 
7794     int
mch_setenv(char * var,char * value,int x UNUSED)7795 mch_setenv(char *var, char *value, int x UNUSED)
7796 {
7797     char_u	*envbuf;
7798     WCHAR	*p;
7799 
7800     envbuf = alloc(STRLEN(var) + STRLEN(value) + 2);
7801     if (envbuf == NULL)
7802 	return -1;
7803 
7804     sprintf((char *)envbuf, "%s=%s", var, value);
7805 
7806     p = enc_to_utf16(envbuf, NULL);
7807 
7808     vim_free(envbuf);
7809     if (p == NULL)
7810 	return -1;
7811     _wputenv(p);
7812 #ifdef libintl_wputenv
7813     libintl_wputenv(p);
7814 #endif
7815     // Unlike Un*x systems, we can free the string for _wputenv().
7816     vim_free(p);
7817 
7818     return 0;
7819 }
7820 
7821 /*
7822  * Support for 256 colors and 24-bit colors was added in Windows 10
7823  * version 1703 (Creators update).
7824  */
7825 #define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7826 
7827 /*
7828  * Support for pseudo-console (ConPTY) was added in windows 10
7829  * version 1809 (October 2018 update).
7830  */
7831 #define CONPTY_FIRST_SUPPORT_BUILD  MAKE_VER(10, 0, 17763)
7832 
7833 /*
7834  * ConPTY differences between versions, need different logic.
7835  * version 1903 (May 2019 update).
7836  */
7837 #define CONPTY_1903_BUILD	    MAKE_VER(10, 0, 18362)
7838 
7839 /*
7840  * version 1909 (November 2019 update).
7841  */
7842 #define CONPTY_1909_BUILD	    MAKE_VER(10, 0, 18363)
7843 
7844 /*
7845  * Stay ahead of the next update, and when it's done, fix this.
7846  * version ? (2020 update, temporarily use the build number of insider preview)
7847  */
7848 #define CONPTY_NEXT_UPDATE_BUILD    MAKE_VER(10, 0, 19587)
7849 
7850 /*
7851  * Confirm until this version.  Also the logic changes.
7852  * insider preview.
7853  */
7854 #define CONPTY_INSIDER_BUILD	    MAKE_VER(10, 0, 18995)
7855 
7856 /*
7857  * Not stable now.
7858  */
7859 #define CONPTY_STABLE_BUILD	    MAKE_VER(10, 0, 32767)  // T.B.D.
7860 
7861     static void
vtp_flag_init(void)7862 vtp_flag_init(void)
7863 {
7864     DWORD   ver = get_build_number();
7865 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL)
7866     DWORD   mode;
7867     HANDLE  out;
7868 
7869 # ifdef VIMDLL
7870     if (!gui.in_use)
7871 # endif
7872     {
7873 	out = GetStdHandle(STD_OUTPUT_HANDLE);
7874 
7875 	vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7876 	GetConsoleMode(out, &mode);
7877 	mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7878 	if (SetConsoleMode(out, mode) == 0)
7879 	    vtp_working = 0;
7880     }
7881 #endif
7882 
7883     if (ver >= CONPTY_FIRST_SUPPORT_BUILD)
7884 	conpty_working = 1;
7885     if (ver >= CONPTY_STABLE_BUILD)
7886 	conpty_stable = 1;
7887 
7888     if (ver <= CONPTY_INSIDER_BUILD)
7889 	conpty_type = 3;
7890     if (ver <= CONPTY_1909_BUILD)
7891 	conpty_type = 2;
7892     if (ver <= CONPTY_1903_BUILD)
7893 	conpty_type = 2;
7894     if (ver < CONPTY_FIRST_SUPPORT_BUILD)
7895 	conpty_type = 1;
7896 
7897     if (ver >= CONPTY_NEXT_UPDATE_BUILD)
7898 	conpty_fix_type = 1;
7899 }
7900 
7901 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
7902 
7903     static void
vtp_init(void)7904 vtp_init(void)
7905 {
7906     HMODULE hKerneldll;
7907     DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7908 # ifdef FEAT_TERMGUICOLORS
7909     COLORREF fg, bg;
7910 # endif
7911 
7912     // Use functions supported from Vista
7913     hKerneldll = GetModuleHandle("kernel32.dll");
7914     if (hKerneldll != NULL)
7915     {
7916 	pGetConsoleScreenBufferInfoEx =
7917 		(PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7918 		hKerneldll, "GetConsoleScreenBufferInfoEx");
7919 	pSetConsoleScreenBufferInfoEx =
7920 		(PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7921 		hKerneldll, "SetConsoleScreenBufferInfoEx");
7922 	if (pGetConsoleScreenBufferInfoEx != NULL
7923 		&& pSetConsoleScreenBufferInfoEx != NULL)
7924 	    has_csbiex = TRUE;
7925     }
7926 
7927     csbi.cbSize = sizeof(csbi);
7928     if (has_csbiex)
7929 	pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7930     save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7931     save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7932     store_console_bg_rgb = save_console_bg_rgb;
7933     store_console_fg_rgb = save_console_fg_rgb;
7934 
7935 # ifdef FEAT_TERMGUICOLORS
7936     bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7937     fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7938     bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7939     fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7940     default_console_color_bg = bg;
7941     default_console_color_fg = fg;
7942 # endif
7943 
7944     set_console_color_rgb();
7945 }
7946 
7947     static void
vtp_exit(void)7948 vtp_exit(void)
7949 {
7950     restore_console_color_rgb();
7951 }
7952 
7953     int
vtp_printf(char * format,...)7954 vtp_printf(
7955     char *format,
7956     ...)
7957 {
7958     char_u  buf[100];
7959     va_list list;
7960     DWORD   result;
7961     int	    len;
7962 
7963     va_start(list, format);
7964     len = vim_vsnprintf((char *)buf, 100, (char *)format, list);
7965     va_end(list);
7966     WriteConsoleA(g_hConOut, buf, (DWORD)len, &result, NULL);
7967     return (int)result;
7968 }
7969 
7970     static void
vtp_sgr_bulk(int arg)7971 vtp_sgr_bulk(
7972     int arg)
7973 {
7974     int args[1];
7975 
7976     args[0] = arg;
7977     vtp_sgr_bulks(1, args);
7978 }
7979 
7980 #define FAST256(x) \
7981     if ((*p-- = "0123456789"[(n = x % 10)]) \
7982 	    && x >= 10 && (*p-- = "0123456789"[((m = x % 100) - n) / 10]) \
7983 	    && x >= 100 && (*p-- = "012"[((x & 0xff) - m) / 100]));
7984 
7985 #define FAST256CASE(x) \
7986     case x: \
7987 	FAST256(newargs[x - 1]);
7988 
7989     static void
vtp_sgr_bulks(int argc,int * args)7990 vtp_sgr_bulks(
7991     int argc,
7992     int *args)
7993 {
7994 #define MAXSGR 16
7995 #define SGRBUFSIZE 2 + 4 * MAXSGR + 1 // '\033[' + SGR + 'm'
7996     char_u  buf[SGRBUFSIZE];
7997     char_u  *p;
7998     int	    in, out;
7999     int	    newargs[16];
8000     static int sgrfgr = -1, sgrfgg, sgrfgb;
8001     static int sgrbgr = -1, sgrbgg, sgrbgb;
8002 
8003     if (argc == 0)
8004     {
8005 	sgrfgr = sgrbgr = -1;
8006 	vtp_printf("033[m");
8007 	return;
8008     }
8009 
8010     in = out = 0;
8011     while (in < argc)
8012     {
8013 	int s = args[in];
8014 	int copylen = 1;
8015 
8016 	if (s == 38)
8017 	{
8018 	    if (argc - in >= 5 && args[in + 1] == 2)
8019 	    {
8020 		if (sgrfgr == args[in + 2] && sgrfgg == args[in + 3]
8021 						     && sgrfgb == args[in + 4])
8022 		{
8023 		    in += 5;
8024 		    copylen = 0;
8025 		}
8026 		else
8027 		{
8028 		    sgrfgr = args[in + 2];
8029 		    sgrfgg = args[in + 3];
8030 		    sgrfgb = args[in + 4];
8031 		    copylen = 5;
8032 		}
8033 	    }
8034 	    else if (argc - in >= 3 && args[in + 1] == 5)
8035 	    {
8036 		sgrfgr = -1;
8037 		copylen = 3;
8038 	    }
8039 	}
8040 	else if (s == 48)
8041 	{
8042 	    if (argc - in >= 5 && args[in + 1] == 2)
8043 	    {
8044 		if (sgrbgr == args[in + 2] && sgrbgg == args[in + 3]
8045 						     && sgrbgb == args[in + 4])
8046 		{
8047 		    in += 5;
8048 		    copylen = 0;
8049 		}
8050 		else
8051 		{
8052 		    sgrbgr = args[in + 2];
8053 		    sgrbgg = args[in + 3];
8054 		    sgrbgb = args[in + 4];
8055 		    copylen = 5;
8056 		}
8057 	    }
8058 	    else if (argc - in >= 3 && args[in + 1] == 5)
8059 	    {
8060 		sgrbgr = -1;
8061 		copylen = 3;
8062 	    }
8063 	}
8064 	else if (30 <= s && s <= 39)
8065 	    sgrfgr = -1;
8066 	else if (90 <= s && s <= 97)
8067 	    sgrfgr = -1;
8068 	else if (40 <= s && s <= 49)
8069 	    sgrbgr = -1;
8070 	else if (100 <= s && s <= 107)
8071 	    sgrbgr = -1;
8072 	else if (s == 0)
8073 	    sgrfgr = sgrbgr = -1;
8074 
8075 	while (copylen--)
8076 	    newargs[out++] = args[in++];
8077     }
8078 
8079     p = &buf[sizeof(buf) - 1];
8080     *p-- = 'm';
8081 
8082     switch (out)
8083     {
8084 	int	n, m;
8085 	DWORD	r;
8086 
8087 	FAST256CASE(16);
8088 	*p-- = ';';
8089 	FAST256CASE(15);
8090 	*p-- = ';';
8091 	FAST256CASE(14);
8092 	*p-- = ';';
8093 	FAST256CASE(13);
8094 	*p-- = ';';
8095 	FAST256CASE(12);
8096 	*p-- = ';';
8097 	FAST256CASE(11);
8098 	*p-- = ';';
8099 	FAST256CASE(10);
8100 	*p-- = ';';
8101 	FAST256CASE(9);
8102 	*p-- = ';';
8103 	FAST256CASE(8);
8104 	*p-- = ';';
8105 	FAST256CASE(7);
8106 	*p-- = ';';
8107 	FAST256CASE(6);
8108 	*p-- = ';';
8109 	FAST256CASE(5);
8110 	*p-- = ';';
8111 	FAST256CASE(4);
8112 	*p-- = ';';
8113 	FAST256CASE(3);
8114 	*p-- = ';';
8115 	FAST256CASE(2);
8116 	*p-- = ';';
8117 	FAST256CASE(1);
8118 	*p-- = '[';
8119 	*p = '\033';
8120 	WriteConsoleA(g_hConOut, p, (DWORD)(&buf[SGRBUFSIZE] - p), &r, NULL);
8121     default:
8122 	break;
8123     }
8124 }
8125 
8126     static void
wt_init(void)8127 wt_init(void)
8128 {
8129     wt_working = (mch_getenv("WT_SESSION") != NULL);
8130 }
8131 
8132     int
use_wt(void)8133 use_wt(void)
8134 {
8135     return USE_WT;
8136 }
8137 
8138 # ifdef FEAT_TERMGUICOLORS
8139     static int
ctermtoxterm(int cterm)8140 ctermtoxterm(
8141     int cterm)
8142 {
8143     char_u r, g, b, idx;
8144 
8145     cterm_color2rgb(cterm, &r, &g, &b, &idx);
8146     return (((int)r << 16) | ((int)g << 8) | (int)b);
8147 }
8148 # endif
8149 
8150     static void
set_console_color_rgb(void)8151 set_console_color_rgb(void)
8152 {
8153 # ifdef FEAT_TERMGUICOLORS
8154     DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8155     guicolor_T	fg, bg;
8156     int		ctermfg, ctermbg;
8157 
8158     if (!USE_VTP)
8159 	return;
8160 
8161     get_default_console_color(&ctermfg, &ctermbg, &fg, &bg);
8162 
8163     if (USE_WT)
8164     {
8165 	term_fg_rgb_color(fg);
8166 	term_bg_rgb_color(bg);
8167 	return;
8168     }
8169 
8170     fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
8171     bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
8172 
8173     csbi.cbSize = sizeof(csbi);
8174     if (has_csbiex)
8175 	pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8176 
8177     csbi.cbSize = sizeof(csbi);
8178     csbi.srWindow.Right += 1;
8179     csbi.srWindow.Bottom += 1;
8180     store_console_bg_rgb = csbi.ColorTable[g_color_index_bg];
8181     store_console_fg_rgb = csbi.ColorTable[g_color_index_fg];
8182     csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
8183     csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
8184     if (has_csbiex)
8185 	pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8186 # endif
8187 }
8188 
8189 # if defined(FEAT_TERMGUICOLORS) || defined(PROTO)
8190     void
get_default_console_color(int * cterm_fg,int * cterm_bg,guicolor_T * gui_fg,guicolor_T * gui_bg)8191 get_default_console_color(
8192     int *cterm_fg,
8193     int *cterm_bg,
8194     guicolor_T *gui_fg,
8195     guicolor_T *gui_bg)
8196 {
8197     int id;
8198     guicolor_T guifg = INVALCOLOR;
8199     guicolor_T guibg = INVALCOLOR;
8200     int ctermfg = 0;
8201     int ctermbg = 0;
8202 
8203     id = syn_name2id((char_u *)"Normal");
8204     if (id > 0 && p_tgc)
8205 	syn_id2colors(id, &guifg, &guibg);
8206     if (guifg == INVALCOLOR)
8207     {
8208 	ctermfg = -1;
8209 	if (id > 0)
8210 	    syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8211 	guifg = ctermfg != -1 ? ctermtoxterm(ctermfg)
8212 						    : default_console_color_fg;
8213 	cterm_normal_fg_gui_color = guifg;
8214 	ctermfg = ctermfg < 0 ? 0 : ctermfg;
8215     }
8216     if (guibg == INVALCOLOR)
8217     {
8218 	ctermbg = -1;
8219 	if (id > 0)
8220 	    syn_id2cterm_bg(id, &ctermfg, &ctermbg);
8221 	guibg = ctermbg != -1 ? ctermtoxterm(ctermbg)
8222 						    : default_console_color_bg;
8223 	cterm_normal_bg_gui_color = guibg;
8224 	ctermbg = ctermbg < 0 ? 0 : ctermbg;
8225     }
8226 
8227     *cterm_fg = ctermfg;
8228     *cterm_bg = ctermbg;
8229     *gui_fg = guifg;
8230     *gui_bg = guibg;
8231 }
8232 # endif
8233 
8234 /*
8235  * Set the console colors to the original colors or the last set colors.
8236  */
8237     static void
reset_console_color_rgb(void)8238 reset_console_color_rgb(void)
8239 {
8240 # ifdef FEAT_TERMGUICOLORS
8241     DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8242 
8243     if (USE_WT)
8244 	return;
8245 
8246     csbi.cbSize = sizeof(csbi);
8247     if (has_csbiex)
8248 	pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8249 
8250     csbi.cbSize = sizeof(csbi);
8251     csbi.srWindow.Right += 1;
8252     csbi.srWindow.Bottom += 1;
8253     csbi.ColorTable[g_color_index_bg] = (COLORREF)store_console_bg_rgb;
8254     csbi.ColorTable[g_color_index_fg] = (COLORREF)store_console_fg_rgb;
8255     if (has_csbiex)
8256 	pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8257 # endif
8258 }
8259 
8260 /*
8261  * Set the console colors to the original colors.
8262  */
8263     static void
restore_console_color_rgb(void)8264 restore_console_color_rgb(void)
8265 {
8266 # ifdef FEAT_TERMGUICOLORS
8267     DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
8268 
8269     csbi.cbSize = sizeof(csbi);
8270     if (has_csbiex)
8271 	pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8272 
8273     csbi.cbSize = sizeof(csbi);
8274     csbi.srWindow.Right += 1;
8275     csbi.srWindow.Bottom += 1;
8276     csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
8277     csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
8278     if (has_csbiex)
8279 	pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
8280 # endif
8281 }
8282 
8283     void
control_console_color_rgb(void)8284 control_console_color_rgb(void)
8285 {
8286     if (USE_VTP)
8287 	set_console_color_rgb();
8288     else
8289 	reset_console_color_rgb();
8290 }
8291 
8292     int
use_vtp(void)8293 use_vtp(void)
8294 {
8295     return USE_VTP;
8296 }
8297 
8298     int
is_term_win32(void)8299 is_term_win32(void)
8300 {
8301     return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
8302 }
8303 
8304     int
has_vtp_working(void)8305 has_vtp_working(void)
8306 {
8307     return vtp_working;
8308 }
8309 
8310 #endif
8311 
8312     int
has_conpty_working(void)8313 has_conpty_working(void)
8314 {
8315     return conpty_working;
8316 }
8317 
8318     int
get_conpty_type(void)8319 get_conpty_type(void)
8320 {
8321     return conpty_type;
8322 }
8323 
8324     int
is_conpty_stable(void)8325 is_conpty_stable(void)
8326 {
8327     return conpty_stable;
8328 }
8329 
8330     int
get_conpty_fix_type(void)8331 get_conpty_fix_type(void)
8332 {
8333     return conpty_fix_type;
8334 }
8335 
8336 #if !defined(FEAT_GUI_MSWIN) || defined(VIMDLL) || defined(PROTO)
8337     void
resize_console_buf(void)8338 resize_console_buf(void)
8339 {
8340     CONSOLE_SCREEN_BUFFER_INFO csbi;
8341     COORD coord;
8342     SMALL_RECT newsize;
8343 
8344     if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
8345     {
8346 	coord.X = SRWIDTH(csbi.srWindow);
8347 	coord.Y = SRHEIGHT(csbi.srWindow);
8348 	SetConsoleScreenBufferSize(g_hConOut, coord);
8349 
8350 	newsize.Left = 0;
8351 	newsize.Top = 0;
8352 	newsize.Right = coord.X - 1;
8353 	newsize.Bottom = coord.Y - 1;
8354 	SetConsoleWindowInfo(g_hConOut, TRUE, &newsize);
8355 
8356 	SetConsoleScreenBufferSize(g_hConOut, coord);
8357     }
8358 }
8359 #endif
8360 
8361     char *
GetWin32Error(void)8362 GetWin32Error(void)
8363 {
8364     char *msg = NULL;
8365     FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
8366 	    NULL, GetLastError(), 0, (LPSTR)&msg, 0, NULL);
8367     if (msg != NULL)
8368     {
8369 	// remove trailing \r\n
8370 	char *pcrlf = strstr(msg, "\r\n");
8371 	if (pcrlf != NULL)
8372 	    *pcrlf = '\0';
8373     }
8374     return msg;
8375 }
8376