blob: 02bcaaede9cf6db52c334a6ee433eb89b84d214c [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
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 <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149#if defined(__BORLANDC__)
150/* Strangely Borland uses a non-standard name. */
151# define wcsicmp(a, b) wcscmpi((a), (b))
152#endif
153
154#ifndef FEAT_GUI_W32
155/* Win32 Console handles for input and output */
156static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
157static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
158
159/* Win32 Screen buffer,coordinate,console I/O information */
160static SMALL_RECT g_srScrollRegion;
161static COORD g_coord; /* 0-based, but external coords are 1-based */
162
163/* The attribute of the screen when the editor was started */
164static WORD g_attrDefault = 7; /* lightgray text on black background */
165static WORD g_attrCurrent;
166
167static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
168static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
169static int g_fForceExit = FALSE; /* set when forcefully exiting */
170
171static void termcap_mode_start(void);
172static void termcap_mode_end(void);
173static void clear_chars(COORD coord, DWORD n);
174static void clear_screen(void);
175static void clear_to_end_of_display(void);
176static void clear_to_end_of_line(void);
177static void scroll(unsigned cLines);
178static void set_scroll_region(unsigned left, unsigned top,
179 unsigned right, unsigned bottom);
180static void insert_lines(unsigned cLines);
181static void delete_lines(unsigned cLines);
182static void gotoxy(unsigned x, unsigned y);
183static void normvideo(void);
184static void textattr(WORD wAttr);
185static void textcolor(WORD wAttr);
186static void textbackground(WORD wAttr);
187static void standout(void);
188static void standend(void);
189static void visual_bell(void);
190static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200191static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000192static void create_conin(void);
193static int s_cursor_visible = TRUE;
194static int did_create_conin = FALSE;
195#else
196static int s_dont_use_vimrun = TRUE;
197static int need_vimrun_warning = FALSE;
198static char *vimrun_path = "vimrun ";
199#endif
200
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200201static int win32_getattrs(char_u *name);
202static int win32_setattrs(char_u *name, int attrs);
203static int win32_set_archive(char_u *name);
204
Bram Moolenaar071d4272004-06-13 20:20:40 +0000205#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100206static int vtp_working = 0;
207static void vtp_init();
208static void vtp_exit();
209static int vtp_printf(char *format, ...);
210static void vtp_sgr_bulk(int arg);
211static void vtp_sgr_bulks(int argc, int *argv);
212
213static guicolor_T save_console_bg_rgb;
214static guicolor_T save_console_fg_rgb;
215
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200216static int g_color_index_bg = 0;
217static int g_color_index_fg = 7;
218
219# ifdef FEAT_TERMGUICOLORS
220static int default_console_color_bg = 0x000000; // black
221static int default_console_color_fg = 0xc0c0c0; // white
222# endif
223
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100224# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200225# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100226# else
227# define USE_VTP 0
228# endif
229
230static void set_console_color_rgb(void);
231static void reset_console_color_rgb(void);
232#endif
233
234/* This flag is newly created from Windows 10 */
235#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
236# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
237#endif
238
239#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240static int suppress_winsize = 1; /* don't fiddle with console */
241#endif
242
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200243static char_u *exe_path = NULL;
244
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100245static BOOL win8_or_later = FALSE;
246
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100247#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248/* Dynamic loading for portability */
249typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
250{
251 ULONG cbSize;
252 COORD dwSize;
253 COORD dwCursorPosition;
254 WORD wAttributes;
255 SMALL_RECT srWindow;
256 COORD dwMaximumWindowSize;
257 WORD wPopupAttributes;
258 BOOL bFullscreenSupported;
259 COLORREF ColorTable[16];
260} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
261typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
262static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
263typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
264static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
265static BOOL has_csbiex = FALSE;
266
267/*
268 * Get version number including build number
269 */
270typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
271# define MAKE_VER(major, minor, build) \
272 (((major) << 24) | ((minor) << 16) | (build))
273
274 static DWORD
275get_build_number(void)
276{
277 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
278 HMODULE hNtdll;
279 PfnRtlGetVersion pRtlGetVersion;
280 DWORD ver = MAKE_VER(0, 0, 0);
281
282 hNtdll = GetModuleHandle("ntdll.dll");
283 if (hNtdll != NULL)
284 {
285 pRtlGetVersion =
286 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
287 pRtlGetVersion(&osver);
288 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
289 min(osver.dwMinorVersion, 255),
290 min(osver.dwBuildNumber, 32767));
291 }
292 return ver;
293}
294
295
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100296/*
297 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299 */
300 static BOOL
301read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100302 HANDLE hInput,
303 INPUT_RECORD *lpBuffer,
304 DWORD nLength,
305 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100306{
307 enum
308 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100309 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100311 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100312 static DWORD s_dwIndex = 0;
313 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100314 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100315 int head;
316 int tail;
317 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100318
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200319 if (nLength == -2)
320 return (s_dwMax > 0) ? TRUE : FALSE;
321
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100322 if (!win8_or_later)
323 {
324 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200325 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
326 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100327 }
328
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100329 if (s_dwMax == 0)
330 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100331 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200332 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
333 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100334 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100335 s_dwIndex = 0;
336 s_dwMax = dwEvents;
337 if (dwEvents == 0)
338 {
339 *lpEvents = 0;
340 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100341 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100342
343 if (s_dwMax > 1)
344 {
345 head = 0;
346 tail = s_dwMax - 1;
347 while (head != tail)
348 {
349 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
350 && s_irCache[head + 1].EventType
351 == WINDOW_BUFFER_SIZE_EVENT)
352 {
353 /* Remove duplicate event to avoid flicker. */
354 for (i = head; i < tail; ++i)
355 s_irCache[i] = s_irCache[i + 1];
356 --tail;
357 continue;
358 }
359 head++;
360 }
361 s_dwMax = tail + 1;
362 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100363 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100364
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100365 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200366 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100368 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100369 return TRUE;
370}
371
372/*
373 * Version of PeekConsoleInput() that works with IME.
374 */
375 static BOOL
376peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100377 HANDLE hInput,
378 INPUT_RECORD *lpBuffer,
379 DWORD nLength,
380 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100381{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100382 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100383}
384
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100385# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200386 static DWORD
387msg_wait_for_multiple_objects(
388 DWORD nCount,
389 LPHANDLE pHandles,
390 BOOL fWaitAll,
391 DWORD dwMilliseconds,
392 DWORD dwWakeMask)
393{
394 if (read_console_input(NULL, NULL, -2, NULL))
395 return WAIT_OBJECT_0;
396 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
397 dwMilliseconds, dwWakeMask);
398}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100399# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200400
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100401# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200402 static DWORD
403wait_for_single_object(
404 HANDLE hHandle,
405 DWORD dwMilliseconds)
406{
407 if (read_console_input(NULL, NULL, -2, NULL))
408 return WAIT_OBJECT_0;
409 return WaitForSingleObject(hHandle, dwMilliseconds);
410}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100411# endif
412#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200413
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414 static void
415get_exe_name(void)
416{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100417 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
418 * as the maximum length that works (plus a NUL byte). */
419#define MAX_ENV_PATH_LEN 8192
420 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200421 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000422
423 if (exe_name == NULL)
424 {
425 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100426 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427 if (*temp != NUL)
428 exe_name = FullName_save((char_u *)temp, FALSE);
429 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000430
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200431 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000432 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200433 exe_path = vim_strnsave(exe_name,
434 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000436 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200437 /* Append our starting directory to $PATH, so that when doing
438 * "!xxd" it's found in our starting directory. Needed because
439 * SearchPath() also looks there. */
440 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100441 if (p == NULL
442 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100444 if (p == NULL || *p == NUL)
445 temp[0] = NUL;
446 else
447 {
448 STRCPY(temp, p);
449 STRCAT(temp, ";");
450 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200451 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100452 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200453 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000454 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000455 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000456}
457
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200458/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100459 * Unescape characters in "p" that appear in "escaped".
460 */
461 static void
462unescape_shellxquote(char_u *p, char_u *escaped)
463{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100464 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100465 int n;
466
467 while (*p != NUL)
468 {
469 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
470 mch_memmove(p, p + 1, l--);
471#ifdef FEAT_MBYTE
472 n = (*mb_ptr2len)(p);
473#else
474 n = 1;
475#endif
476 p += n;
477 l -= n;
478 }
479}
480
481/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 * Load library "name".
483 */
484 HINSTANCE
485vimLoadLib(char *name)
486{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200488
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200489 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
490 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200491 if (exe_path == NULL)
492 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200493 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200494 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200495 WCHAR old_dirw[MAXPATHL];
496
497 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
498 {
499 /* Change directory to where the executable is, both to make
500 * sure we find a .dll there and to avoid looking for a .dll
501 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100502 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200503 dll = LoadLibrary(name);
504 SetCurrentDirectoryW(old_dirw);
505 return dll;
506 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200507 }
508 return dll;
509}
510
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100511#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
512/*
513 * Get related information about 'funcname' which is imported by 'hInst'.
514 * If 'info' is 0, return the function address.
515 * If 'info' is 1, return the module name which the function is imported from.
516 */
517 static void *
518get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
519{
520 PBYTE pImage = (PBYTE)hInst;
521 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
522 PIMAGE_NT_HEADERS pPE;
523 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
524 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
525 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
526 PIMAGE_IMPORT_BY_NAME pImpName;
527
528 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
529 return NULL;
530 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
531 if (pPE->Signature != IMAGE_NT_SIGNATURE)
532 return NULL;
533 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
534 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
535 .VirtualAddress);
536 for (; pImpDesc->FirstThunk; ++pImpDesc)
537 {
538 if (!pImpDesc->OriginalFirstThunk)
539 continue;
540 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
541 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
542 for (; pIAT->u1.Function; ++pIAT, ++pINT)
543 {
544 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
545 continue;
546 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
547 + (UINT_PTR)(pINT->u1.AddressOfData));
548 if (strcmp((char *)pImpName->Name, funcname) == 0)
549 {
550 switch (info)
551 {
552 case 0:
553 return (void *)pIAT->u1.Function;
554 case 1:
555 return (void *)(pImage + pImpDesc->Name);
556 default:
557 return NULL;
558 }
559 }
560 }
561 }
562 return NULL;
563}
564
565/*
566 * Get the module handle which 'funcname' in 'hInst' is imported from.
567 */
568 HINSTANCE
569find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
570{
571 char *modulename;
572
573 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
574 if (modulename != NULL)
575 return GetModuleHandleA(modulename);
576 return NULL;
577}
578
579/*
580 * Get the address of 'funcname' which is imported by 'hInst' DLL.
581 */
582 void *
583get_dll_import_func(HINSTANCE hInst, const char *funcname)
584{
585 return get_imported_func_info(hInst, funcname, 0);
586}
587#endif
588
Bram Moolenaar071d4272004-06-13 20:20:40 +0000589#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
590# ifndef GETTEXT_DLL
591# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100592# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000593# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200594/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000595static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200596static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000597static char *null_libintl_textdomain(const char *);
598static char *null_libintl_bindtextdomain(const char *, const char *);
599static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100600static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100601static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200603static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000604char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200605char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
606 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000607char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
608char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000610char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
611 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100612int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100613int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614
615 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100616dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617{
618 int i;
619 static struct
620 {
621 char *name;
622 FARPROC *ptr;
623 } libintl_entry[] =
624 {
625 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200626 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000627 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
628 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
629 {NULL, NULL}
630 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100631 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632
633 /* No need to initialize twice. */
634 if (hLibintlDLL)
635 return 1;
636 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100637 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100638#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100639 if (!hLibintlDLL)
640 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100641#endif
642 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200644 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000645 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200646 verbose_enter();
647 EMSG2(_(e_loadlib), GETTEXT_DLL);
648 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000649 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200650 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651 }
652 for (i = 0; libintl_entry[i].name != NULL
653 && libintl_entry[i].ptr != NULL; ++i)
654 {
655 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
656 libintl_entry[i].name)) == NULL)
657 {
658 dyn_libintl_end();
659 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000660 {
661 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000662 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000663 verbose_leave();
664 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665 return 0;
666 }
667 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000668
669 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000670 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000671 "bind_textdomain_codeset");
672 if (dyn_libintl_bind_textdomain_codeset == NULL)
673 dyn_libintl_bind_textdomain_codeset =
674 null_libintl_bind_textdomain_codeset;
675
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100676 /* _putenv() function for the libintl.dll is optional. */
677 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
678 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100679 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100680 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100681 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
682 }
683 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100684 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100685 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
686 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100687
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 return 1;
689}
690
691 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100692dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693{
694 if (hLibintlDLL)
695 FreeLibrary(hLibintlDLL);
696 hLibintlDLL = NULL;
697 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200698 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699 dyn_libintl_textdomain = null_libintl_textdomain;
700 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000701 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100702 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100703 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704}
705
706 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000707null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708{
709 return (char*)msgid;
710}
711
712 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200713null_libintl_ngettext(
714 const char *msgid,
715 const char *msgid_plural,
716 unsigned long n)
717{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200718 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200719}
720
Bram Moolenaaree695f72016-08-03 22:08:45 +0200721 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100722null_libintl_bindtextdomain(
723 const char *domainname UNUSED,
724 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725{
726 return NULL;
727}
728
729 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100730null_libintl_bind_textdomain_codeset(
731 const char *domainname UNUSED,
732 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000733{
734 return NULL;
735}
736
737 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100738null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739{
740 return NULL;
741}
742
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200743 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100744null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100745{
746 return 0;
747}
748
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200749 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100750null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100751{
752 return 0;
753}
754
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755#endif /* DYNAMIC_GETTEXT */
756
757/* This symbol is not defined in older versions of the SDK or Visual C++ */
758
759#ifndef VER_PLATFORM_WIN32_WINDOWS
760# define VER_PLATFORM_WIN32_WINDOWS 1
761#endif
762
763DWORD g_PlatformId;
764
765#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100766# ifndef PROTO
767# include <aclapi.h>
768# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200769# ifndef PROTECTED_DACL_SECURITY_INFORMATION
770# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
771# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772#endif
773
Bram Moolenaar27515922013-06-29 15:36:26 +0200774#ifdef HAVE_ACL
775/*
776 * Enables or disables the specified privilege.
777 */
778 static BOOL
779win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
780{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100781 BOOL bResult;
782 LUID luid;
783 HANDLE hToken;
784 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200785
786 if (!OpenProcessToken(GetCurrentProcess(),
787 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
788 return FALSE;
789
790 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
791 {
792 CloseHandle(hToken);
793 return FALSE;
794 }
795
Bram Moolenaar45500912014-07-09 20:51:07 +0200796 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200797 tokenPrivileges.Privileges[0].Luid = luid;
798 tokenPrivileges.Privileges[0].Attributes = bEnable ?
799 SE_PRIVILEGE_ENABLED : 0;
800
801 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
802 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
803
804 CloseHandle(hToken);
805
806 return bResult && GetLastError() == ERROR_SUCCESS;
807}
808#endif
809
Bram Moolenaar071d4272004-06-13 20:20:40 +0000810/*
811 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
812 * VER_PLATFORM_WIN32_WINDOWS (Win95).
813 */
814 void
815PlatformId(void)
816{
817 static int done = FALSE;
818
819 if (!done)
820 {
821 OSVERSIONINFO ovi;
822
823 ovi.dwOSVersionInfoSize = sizeof(ovi);
824 GetVersionEx(&ovi);
825
826 g_PlatformId = ovi.dwPlatformId;
827
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100828 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
829 || ovi.dwMajorVersion > 6)
830 win8_or_later = TRUE;
831
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200833 /* Enable privilege for getting or setting SACLs. */
834 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835#endif
836 done = TRUE;
837 }
838}
839
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840#ifndef FEAT_GUI_W32
841
842#define SHIFT (SHIFT_PRESSED)
843#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
844#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
845#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
846
847
848/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
849 * We map function keys to their ANSI terminal equivalents, as produced
850 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
851 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
852 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
853 * combinations of function/arrow/etc keys.
854 */
855
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000856static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000857{
858 WORD wVirtKey;
859 BOOL fAnsiKey;
860 int chAlone;
861 int chShift;
862 int chCtrl;
863 int chAlt;
864} VirtKeyMap[] =
865{
866
867/* Key ANSI alone shift ctrl alt */
868 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
869
870 { VK_F1, TRUE, ';', 'T', '^', 'h', },
871 { VK_F2, TRUE, '<', 'U', '_', 'i', },
872 { VK_F3, TRUE, '=', 'V', '`', 'j', },
873 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
874 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
875 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
876 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
877 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
878 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
879 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
880 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
881 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
882
883 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
884 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
885 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
886 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
887 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
888 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
889 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
890 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
891 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
892 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
893
894 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
895
896#if 0
897 /* Most people don't have F13-F20, but what the hell... */
898 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
899 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
900 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
901 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
902 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
903 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
904 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
905 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
906#endif
907 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
908 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
909 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
910 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
911
912 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
913 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
914 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
915 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
916 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
917 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
918 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
919 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
920 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
921 /* Sorry, out of number space! <negri>*/
922 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
923
924};
925
926
927#ifdef _MSC_VER
928// The ToAscii bug destroys several registers. Need to turn off optimization
929// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000930# pragma warning(push)
931# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932# pragma optimize("", off)
933#endif
934
935#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200936# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200938# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939#endif
940
941/* The return code indicates key code size. */
942 static int
943#ifdef __BORLANDC__
944 __stdcall
945#endif
946win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000947 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948{
949 UINT uMods = pker->dwControlKeyState;
950 static int s_iIsDead = 0;
951 static WORD awAnsiCode[2];
952 static BYTE abKeystate[256];
953
954
955 if (s_iIsDead == 2)
956 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200957 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958 s_iIsDead = 0;
959 return 1;
960 }
961
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200962 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963 return 1;
964
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200965 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200968 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969
970 if (uMods & SHIFT_PRESSED)
971 abKeystate[VK_SHIFT] = 0x80;
972 if (uMods & CAPSLOCK_ON)
973 abKeystate[VK_CAPITAL] = 1;
974
975 if ((uMods & ALT_GR) == ALT_GR)
976 {
977 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
978 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
979 }
980
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200981 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
982 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983
984 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200985 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986
987 return s_iIsDead;
988}
989
990#ifdef _MSC_VER
991/* MUST switch optimization on again here, otherwise a call to
992 * decode_key_event() may crash (e.g. when hitting caps-lock) */
993# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000994# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995
996# if (_MSC_VER < 1100)
997/* MUST turn off global optimisation for this next function, or
998 * pressing ctrl-minus in insert mode crashes Vim when built with
999 * VC4.1. -- negri. */
1000# pragma optimize("g", off)
1001# endif
1002#endif
1003
1004static BOOL g_fJustGotFocus = FALSE;
1005
1006/*
1007 * Decode a KEY_EVENT into one or two keystrokes
1008 */
1009 static BOOL
1010decode_key_event(
1011 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001012 WCHAR *pch,
1013 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014 int *pmodifiers,
1015 BOOL fDoPost)
1016{
1017 int i;
1018 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1019
1020 *pch = *pch2 = NUL;
1021 g_fJustGotFocus = FALSE;
1022
1023 /* ignore key up events */
1024 if (!pker->bKeyDown)
1025 return FALSE;
1026
1027 /* ignore some keystrokes */
1028 switch (pker->wVirtualKeyCode)
1029 {
1030 /* modifiers */
1031 case VK_SHIFT:
1032 case VK_CONTROL:
1033 case VK_MENU: /* Alt key */
1034 return FALSE;
1035
1036 default:
1037 break;
1038 }
1039
1040 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001041 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 {
1043 /* Ctrl-6 is Ctrl-^ */
1044 if (pker->wVirtualKeyCode == '6')
1045 {
1046 *pch = Ctrl_HAT;
1047 return TRUE;
1048 }
1049 /* Ctrl-2 is Ctrl-@ */
1050 else if (pker->wVirtualKeyCode == '2')
1051 {
1052 *pch = NUL;
1053 return TRUE;
1054 }
1055 /* Ctrl-- is Ctrl-_ */
1056 else if (pker->wVirtualKeyCode == 0xBD)
1057 {
1058 *pch = Ctrl__;
1059 return TRUE;
1060 }
1061 }
1062
1063 /* Shift-TAB */
1064 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1065 {
1066 *pch = K_NUL;
1067 *pch2 = '\017';
1068 return TRUE;
1069 }
1070
1071 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1072 {
1073 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1074 {
1075 if (nModifs == 0)
1076 *pch = VirtKeyMap[i].chAlone;
1077 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1078 *pch = VirtKeyMap[i].chShift;
1079 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1080 *pch = VirtKeyMap[i].chCtrl;
1081 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1082 *pch = VirtKeyMap[i].chAlt;
1083
1084 if (*pch != 0)
1085 {
1086 if (VirtKeyMap[i].fAnsiKey)
1087 {
1088 *pch2 = *pch;
1089 *pch = K_NUL;
1090 }
1091
1092 return TRUE;
1093 }
1094 }
1095 }
1096
1097 i = win32_kbd_patch_key(pker);
1098
1099 if (i < 0)
1100 *pch = NUL;
1101 else
1102 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001103 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104
1105 if (pmodifiers != NULL)
1106 {
1107 /* Pass on the ALT key as a modifier, but only when not combined
1108 * with CTRL (which is ALTGR). */
1109 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1110 *pmodifiers |= MOD_MASK_ALT;
1111
1112 /* Pass on SHIFT only for special keys, because we don't know when
1113 * it's already included with the character. */
1114 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1115 *pmodifiers |= MOD_MASK_SHIFT;
1116
1117 /* Pass on CTRL only for non-special keys, because we don't know
1118 * when it's already included with the character. And not when
1119 * combined with ALT (which is ALTGR). */
1120 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1121 && *pch >= 0x20 && *pch < 0x80)
1122 *pmodifiers |= MOD_MASK_CTRL;
1123 }
1124 }
1125
1126 return (*pch != NUL);
1127}
1128
1129#ifdef _MSC_VER
1130# pragma optimize("", on)
1131#endif
1132
1133#endif /* FEAT_GUI_W32 */
1134
1135
1136#ifdef FEAT_MOUSE
1137
1138/*
1139 * For the GUI the mouse handling is in gui_w32.c.
1140 */
1141# ifdef FEAT_GUI_W32
1142 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001143mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144{
1145}
1146# else
1147static int g_fMouseAvail = FALSE; /* mouse present */
1148static int g_fMouseActive = FALSE; /* mouse enabled */
1149static int g_nMouseClick = -1; /* mouse status */
1150static int g_xMouse; /* mouse x coordinate */
1151static int g_yMouse; /* mouse y coordinate */
1152
1153/*
1154 * Enable or disable mouse input
1155 */
1156 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001157mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158{
1159 DWORD cmodein;
1160
1161 if (!g_fMouseAvail)
1162 return;
1163
1164 g_fMouseActive = on;
1165 GetConsoleMode(g_hConIn, &cmodein);
1166
1167 if (g_fMouseActive)
1168 cmodein |= ENABLE_MOUSE_INPUT;
1169 else
1170 cmodein &= ~ENABLE_MOUSE_INPUT;
1171
1172 SetConsoleMode(g_hConIn, cmodein);
1173}
1174
Bram Moolenaar157d8132018-03-06 17:09:20 +01001175
1176#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1177/*
1178 * Called when 'balloonevalterm' changed.
1179 */
1180 void
1181mch_bevalterm_changed(void)
1182{
1183 mch_setmouse(g_fMouseActive);
1184}
1185#endif
1186
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187/*
1188 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1189 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1190 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1191 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1192 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1193 * and we return the mouse position in g_xMouse and g_yMouse.
1194 *
1195 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1196 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1197 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1198 *
1199 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1200 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1201 *
1202 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1203 * moves, even if it stays within the same character cell. We ignore
1204 * all MOUSE_MOVED messages if the position hasn't really changed, and
1205 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1206 * we're only interested in MOUSE_DRAG).
1207 *
1208 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1209 * 2-button mouses by pressing the left & right buttons simultaneously.
1210 * In practice, it's almost impossible to click both at the same time,
1211 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1212 * in such cases, if the user is clicking quickly.
1213 */
1214 static BOOL
1215decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001216 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001217{
1218 static int s_nOldButton = -1;
1219 static int s_nOldMouseClick = -1;
1220 static int s_xOldMouse = -1;
1221 static int s_yOldMouse = -1;
1222 static linenr_T s_old_topline = 0;
1223#ifdef FEAT_DIFF
1224 static int s_old_topfill = 0;
1225#endif
1226 static int s_cClicks = 1;
1227 static BOOL s_fReleased = TRUE;
1228 static DWORD s_dwLastClickTime = 0;
1229 static BOOL s_fNextIsMiddle = FALSE;
1230
1231 static DWORD cButtons = 0; /* number of buttons supported */
1232
1233 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1234 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1235 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1236 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1237
1238 int nButton;
1239
1240 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1241 cButtons = 2;
1242
1243 if (!g_fMouseAvail || !g_fMouseActive)
1244 {
1245 g_nMouseClick = -1;
1246 return FALSE;
1247 }
1248
1249 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1250 if (g_fJustGotFocus)
1251 {
1252 g_fJustGotFocus = FALSE;
1253 return FALSE;
1254 }
1255
1256 /* unprocessed mouse click? */
1257 if (g_nMouseClick != -1)
1258 return TRUE;
1259
1260 nButton = -1;
1261 g_xMouse = pmer->dwMousePosition.X;
1262 g_yMouse = pmer->dwMousePosition.Y;
1263
1264 if (pmer->dwEventFlags == MOUSE_MOVED)
1265 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001266 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001267 * events even when the mouse moves only within a char cell.) */
1268 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1269 return FALSE;
1270 }
1271
1272 /* If no buttons are pressed... */
1273 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1274 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001275 nButton = MOUSE_RELEASE;
1276
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1278 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001279 {
1280#ifdef FEAT_BEVAL_TERM
1281 /* do return mouse move events when we want them */
1282 if (p_bevalterm)
1283 nButton = MOUSE_DRAG;
1284 else
1285#endif
1286 return FALSE;
1287 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001288
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289 s_fReleased = TRUE;
1290 }
1291 else /* one or more buttons pressed */
1292 {
1293 /* on a 2-button mouse, hold down left and right buttons
1294 * simultaneously to get MIDDLE. */
1295
1296 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1297 {
1298 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1299
1300 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001301 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001302 if (dwLR == LEFT || dwLR == RIGHT)
1303 {
1304 for (;;)
1305 {
1306 /* wait a short time for next input event */
1307 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1308 != WAIT_OBJECT_0)
1309 break;
1310 else
1311 {
1312 DWORD cRecords = 0;
1313 INPUT_RECORD ir;
1314 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1315
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001316 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317
1318 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1319 || !(pmer2->dwButtonState & LEFT_RIGHT))
1320 break;
1321 else
1322 {
1323 if (pmer2->dwEventFlags != MOUSE_MOVED)
1324 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001325 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001326
1327 return decode_mouse_event(pmer2);
1328 }
1329 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1330 s_yOldMouse == pmer2->dwMousePosition.Y)
1331 {
1332 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001333 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001334
1335 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001336 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337
1338 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1339 break;
1340 }
1341 else
1342 break;
1343 }
1344 }
1345 }
1346 }
1347 }
1348
1349 if (s_fNextIsMiddle)
1350 {
1351 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1352 ? MOUSE_DRAG : MOUSE_MIDDLE;
1353 s_fNextIsMiddle = FALSE;
1354 }
1355 else if (cButtons == 2 &&
1356 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1357 {
1358 nButton = MOUSE_MIDDLE;
1359
1360 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1361 {
1362 s_fNextIsMiddle = TRUE;
1363 nButton = MOUSE_RELEASE;
1364 }
1365 }
1366 else if ((pmer->dwButtonState & LEFT) == LEFT)
1367 nButton = MOUSE_LEFT;
1368 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1369 nButton = MOUSE_MIDDLE;
1370 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1371 nButton = MOUSE_RIGHT;
1372
1373 if (! s_fReleased && ! s_fNextIsMiddle
1374 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1375 return FALSE;
1376
1377 s_fReleased = s_fNextIsMiddle;
1378 }
1379
1380 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1381 {
1382 /* button pressed or released, without mouse moving */
1383 if (nButton != -1 && nButton != MOUSE_RELEASE)
1384 {
1385 DWORD dwCurrentTime = GetTickCount();
1386
1387 if (s_xOldMouse != g_xMouse
1388 || s_yOldMouse != g_yMouse
1389 || s_nOldButton != nButton
1390 || s_old_topline != curwin->w_topline
1391#ifdef FEAT_DIFF
1392 || s_old_topfill != curwin->w_topfill
1393#endif
1394 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1395 {
1396 s_cClicks = 1;
1397 }
1398 else if (++s_cClicks > 4)
1399 {
1400 s_cClicks = 1;
1401 }
1402
1403 s_dwLastClickTime = dwCurrentTime;
1404 }
1405 }
1406 else if (pmer->dwEventFlags == MOUSE_MOVED)
1407 {
1408 if (nButton != -1 && nButton != MOUSE_RELEASE)
1409 nButton = MOUSE_DRAG;
1410
1411 s_cClicks = 1;
1412 }
1413
1414 if (nButton == -1)
1415 return FALSE;
1416
1417 if (nButton != MOUSE_RELEASE)
1418 s_nOldButton = nButton;
1419
1420 g_nMouseClick = nButton;
1421
1422 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1423 g_nMouseClick |= MOUSE_SHIFT;
1424 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1425 g_nMouseClick |= MOUSE_CTRL;
1426 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1427 g_nMouseClick |= MOUSE_ALT;
1428
1429 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1430 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1431
1432 /* only pass on interesting (i.e., different) mouse events */
1433 if (s_xOldMouse == g_xMouse
1434 && s_yOldMouse == g_yMouse
1435 && s_nOldMouseClick == g_nMouseClick)
1436 {
1437 g_nMouseClick = -1;
1438 return FALSE;
1439 }
1440
1441 s_xOldMouse = g_xMouse;
1442 s_yOldMouse = g_yMouse;
1443 s_old_topline = curwin->w_topline;
1444#ifdef FEAT_DIFF
1445 s_old_topfill = curwin->w_topfill;
1446#endif
1447 s_nOldMouseClick = g_nMouseClick;
1448
1449 return TRUE;
1450}
1451
1452# endif /* FEAT_GUI_W32 */
1453#endif /* FEAT_MOUSE */
1454
1455
1456#ifdef MCH_CURSOR_SHAPE
1457/*
1458 * Set the shape of the cursor.
1459 * 'thickness' can be from 1 (thin) to 99 (block)
1460 */
1461 static void
1462mch_set_cursor_shape(int thickness)
1463{
1464 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1465 ConsoleCursorInfo.dwSize = thickness;
1466 ConsoleCursorInfo.bVisible = s_cursor_visible;
1467
1468 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1469 if (s_cursor_visible)
1470 SetConsoleCursorPosition(g_hConOut, g_coord);
1471}
1472
1473 void
1474mch_update_cursor(void)
1475{
1476 int idx;
1477 int thickness;
1478
1479 /*
1480 * How the cursor is drawn depends on the current mode.
1481 */
1482 idx = get_shape_idx(FALSE);
1483
1484 if (shape_table[idx].shape == SHAPE_BLOCK)
1485 thickness = 99; /* 100 doesn't work on W95 */
1486 else
1487 thickness = shape_table[idx].percentage;
1488 mch_set_cursor_shape(thickness);
1489}
1490#endif
1491
1492#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1493/*
1494 * Handle FOCUS_EVENT.
1495 */
1496 static void
1497handle_focus_event(INPUT_RECORD ir)
1498{
1499 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1500 ui_focus_change((int)g_fJustGotFocus);
1501}
1502
1503/*
1504 * Wait until console input from keyboard or mouse is available,
1505 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001506 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507 * Return TRUE if something is available FALSE if not.
1508 */
1509 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001510WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511{
1512 DWORD dwNow = 0, dwEndTime = 0;
1513 INPUT_RECORD ir;
1514 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001515 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001516#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001517 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001518#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519
1520 if (msec > 0)
1521 /* Wait until the specified time has elapsed. */
1522 dwEndTime = GetTickCount() + msec;
1523 else if (msec < 0)
1524 /* Wait forever. */
1525 dwEndTime = INFINITE;
1526
1527 /* We need to loop until the end of the time period, because
1528 * we might get multiple unusable mouse events in that time.
1529 */
1530 for (;;)
1531 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001532#ifdef MESSAGE_QUEUE
1533 parse_queued_messages();
1534#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001535#ifdef FEAT_MZSCHEME
1536 mzvim_check_threads();
1537#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538#ifdef FEAT_CLIENTSERVER
1539 serverProcessPendingMessages();
1540#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001541
Bram Moolenaar071d4272004-06-13 20:20:40 +00001542 if (0
1543#ifdef FEAT_MOUSE
1544 || g_nMouseClick != -1
1545#endif
1546#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001547 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548#endif
1549 )
1550 return TRUE;
1551
1552 if (msec > 0)
1553 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001554 /* If the specified wait time has passed, return. Beware that
1555 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001556 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001557 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001558 break;
1559 }
1560 if (msec != 0)
1561 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001562 DWORD dwWaitTime = dwEndTime - dwNow;
1563
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001564#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001565 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001566 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001567 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001568 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001569 /* If there is readahead then parse_queued_messages() timed out
1570 * and we should call it again soon. */
1571 if (channel_any_readahead())
1572 dwWaitTime = 10;
1573 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001574#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001575#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001576 if (p_beval && dwWaitTime > 100)
1577 /* The 'balloonexpr' may indirectly invoke a callback while
1578 * waiting for a character, need to check often. */
1579 dwWaitTime = 100;
1580#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001581#ifdef FEAT_MZSCHEME
1582 if (mzthreads_allowed() && p_mzq > 0
1583 && (msec < 0 || (long)dwWaitTime > p_mzq))
1584 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1585#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001586#ifdef FEAT_TIMERS
1587 {
1588 long due_time;
1589
1590 /* When waiting very briefly don't trigger timers. */
1591 if (dwWaitTime > 10)
1592 {
1593 /* Trigger timers and then get the time in msec until the
1594 * next one is due. Wait up to that time. */
1595 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001596 if (typebuf.tb_change_cnt != tb_change_cnt)
1597 {
1598 /* timer may have used feedkeys() */
1599 return FALSE;
1600 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001601 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1602 dwWaitTime = due_time;
1603 }
1604 }
1605#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606#ifdef FEAT_CLIENTSERVER
1607 /* Wait for either an event on the console input or a message in
1608 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001609 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001610 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001612 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613#endif
1614 continue;
1615 }
1616
1617 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001618 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001619
1620#ifdef FEAT_MBYTE_IME
1621 if (State & CMDLINE && msg_row == Rows - 1)
1622 {
1623 CONSOLE_SCREEN_BUFFER_INFO csbi;
1624
1625 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1626 {
1627 if (csbi.dwCursorPosition.Y != msg_row)
1628 {
1629 /* The screen is now messed up, must redraw the
1630 * command line and later all the windows. */
1631 redraw_all_later(CLEAR);
1632 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1633 redrawcmd();
1634 }
1635 }
1636 }
1637#endif
1638
1639 if (cRecords > 0)
1640 {
1641 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1642 {
1643#ifdef FEAT_MBYTE_IME
1644 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1645 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001646 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1648 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001649 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001650 continue;
1651 }
1652#endif
1653 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1654 NULL, FALSE))
1655 return TRUE;
1656 }
1657
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001658 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659
1660 if (ir.EventType == FOCUS_EVENT)
1661 handle_focus_event(ir);
1662 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001663 {
1664 /* Only call shell_resized() when the size actually change to
1665 * avoid the screen is cleard. */
1666 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1667 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1668 shell_resized();
1669 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001670#ifdef FEAT_MOUSE
1671 else if (ir.EventType == MOUSE_EVENT
1672 && decode_mouse_event(&ir.Event.MouseEvent))
1673 return TRUE;
1674#endif
1675 }
1676 else if (msec == 0)
1677 break;
1678 }
1679
1680#ifdef FEAT_CLIENTSERVER
1681 /* Something might have been received while we were waiting. */
1682 if (input_available())
1683 return TRUE;
1684#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001685
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 return FALSE;
1687}
1688
1689#ifndef FEAT_GUI_MSWIN
1690/*
1691 * return non-zero if a character is available
1692 */
1693 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001694mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001696 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001698
1699# if defined(FEAT_TERMINAL) || defined(PROTO)
1700/*
1701 * Check for any pending input or messages.
1702 */
1703 int
1704mch_check_messages(void)
1705{
1706 return WaitForChar(0L, TRUE);
1707}
1708# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709#endif
1710
1711/*
1712 * Create the console input. Used when reading stdin doesn't work.
1713 */
1714 static void
1715create_conin(void)
1716{
1717 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1718 FILE_SHARE_READ|FILE_SHARE_WRITE,
1719 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001720 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 did_create_conin = TRUE;
1722}
1723
1724/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001725 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001727 static WCHAR
1728tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001730 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731
1732 for (;;)
1733 {
1734 INPUT_RECORD ir;
1735 DWORD cRecords = 0;
1736
1737#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001738 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 if (input_available())
1740 return 0;
1741# ifdef FEAT_MOUSE
1742 if (g_nMouseClick != -1)
1743 return 0;
1744# endif
1745#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001746 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001747 {
1748 if (did_create_conin)
1749 read_error_exit();
1750 create_conin();
1751 continue;
1752 }
1753
1754 if (ir.EventType == KEY_EVENT)
1755 {
1756 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1757 pmodifiers, TRUE))
1758 return ch;
1759 }
1760 else if (ir.EventType == FOCUS_EVENT)
1761 handle_focus_event(ir);
1762 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1763 shell_resized();
1764#ifdef FEAT_MOUSE
1765 else if (ir.EventType == MOUSE_EVENT)
1766 {
1767 if (decode_mouse_event(&ir.Event.MouseEvent))
1768 return 0;
1769 }
1770#endif
1771 }
1772}
1773#endif /* !FEAT_GUI_W32 */
1774
1775
1776/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001777 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778 * Get one or more characters from the keyboard or the mouse.
1779 * If time == 0, do not wait for characters.
1780 * If time == n, wait a short time for characters.
1781 * If time == -1, wait forever for characters.
1782 * Returns the number of characters read into buf.
1783 */
1784 int
1785mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001786 char_u *buf UNUSED,
1787 int maxlen UNUSED,
1788 long time UNUSED,
1789 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001790{
1791#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1792
1793 int len;
1794 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795#define TYPEAHEADLEN 20
1796 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1797 static int typeaheadlen = 0;
1798
1799 /* First use any typeahead that was kept because "buf" was too small. */
1800 if (typeaheadlen > 0)
1801 goto theend;
1802
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803 if (time >= 0)
1804 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001805 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 }
1808 else /* time == -1, wait forever */
1809 {
1810 mch_set_winsize_now(); /* Allow winsize changes from now on */
1811
Bram Moolenaar3918c952005-03-15 22:34:55 +00001812 /*
1813 * If there is no character available within 2 seconds (default)
1814 * write the autoscript file to disk. Or cause the CursorHold event
1815 * to be triggered.
1816 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001817 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001819 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001821 buf[0] = K_SPECIAL;
1822 buf[1] = KS_EXTRA;
1823 buf[2] = (int)KE_CURSORHOLD;
1824 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001826 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001827 }
1828 }
1829
1830 /*
1831 * Try to read as many characters as there are, until the buffer is full.
1832 */
1833
1834 /* we will get at least one key. Get more if they are available. */
1835 g_fCBrkPressed = FALSE;
1836
1837#ifdef MCH_WRITE_DUMP
1838 if (fdDump)
1839 fputc('[', fdDump);
1840#endif
1841
1842 /* Keep looping until there is something in the typeahead buffer and more
1843 * to get and still room in the buffer (up to two bytes for a char and
1844 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001845 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846 && typeaheadlen + 5 <= TYPEAHEADLEN)
1847 {
1848 if (typebuf_changed(tb_change_cnt))
1849 {
1850 /* "buf" may be invalid now if a client put something in the
1851 * typeahead buffer and "buf" is in the typeahead buffer. */
1852 typeaheadlen = 0;
1853 break;
1854 }
1855#ifdef FEAT_MOUSE
1856 if (g_nMouseClick != -1)
1857 {
1858# ifdef MCH_WRITE_DUMP
1859 if (fdDump)
1860 fprintf(fdDump, "{%02x @ %d, %d}",
1861 g_nMouseClick, g_xMouse, g_yMouse);
1862# endif
1863 typeahead[typeaheadlen++] = ESC + 128;
1864 typeahead[typeaheadlen++] = 'M';
1865 typeahead[typeaheadlen++] = g_nMouseClick;
1866 typeahead[typeaheadlen++] = g_xMouse + '!';
1867 typeahead[typeaheadlen++] = g_yMouse + '!';
1868 g_nMouseClick = -1;
1869 }
1870 else
1871#endif
1872 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001873 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001874 int modifiers = 0;
1875
1876 c = tgetch(&modifiers, &ch2);
1877
1878 if (typebuf_changed(tb_change_cnt))
1879 {
1880 /* "buf" may be invalid now if a client put something in the
1881 * typeahead buffer and "buf" is in the typeahead buffer. */
1882 typeaheadlen = 0;
1883 break;
1884 }
1885
1886 if (c == Ctrl_C && ctrl_c_interrupts)
1887 {
1888#if defined(FEAT_CLIENTSERVER)
1889 trash_input_buf();
1890#endif
1891 got_int = TRUE;
1892 }
1893
1894#ifdef FEAT_MOUSE
1895 if (g_nMouseClick == -1)
1896#endif
1897 {
1898 int n = 1;
1899
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001900#ifdef FEAT_MBYTE
1901 if (ch2 == NUL)
1902 {
1903 int i;
1904 char_u *p;
1905 WCHAR ch[2];
1906
1907 ch[0] = c;
1908 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1909 {
1910 ch[1] = tgetch(&modifiers, &ch2);
1911 n++;
1912 }
1913 p = utf16_to_enc(ch, &n);
1914 if (p != NULL)
1915 {
1916 for (i = 0; i < n; i++)
1917 typeahead[typeaheadlen + i] = p[i];
1918 vim_free(p);
1919 }
1920 }
1921 else
1922#endif
1923 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 if (ch2 != NUL)
1925 {
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001926 if (c == K_NUL && (ch2 & 0xff00) != 0)
1927 {
1928 /* fAnsiKey with modifier keys */
1929 typeahead[typeaheadlen + n] = (char_u)ch2;
1930 n++;
1931 }
1932 else
1933 {
1934 typeahead[typeaheadlen + n] = 3;
1935 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1936 n += 2;
1937 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001938 }
1939
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940 /* Use the ALT key to set the 8th bit of the character
1941 * when it's one byte, the 8th bit isn't set yet and not
1942 * using a double-byte encoding (would become a lead
1943 * byte). */
1944 if ((modifiers & MOD_MASK_ALT)
1945 && n == 1
1946 && (typeahead[typeaheadlen] & 0x80) == 0
1947#ifdef FEAT_MBYTE
1948 && !enc_dbcs
1949#endif
1950 )
1951 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001952#ifdef FEAT_MBYTE
1953 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1954 typeahead + typeaheadlen);
1955#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001957#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001958 modifiers &= ~MOD_MASK_ALT;
1959 }
1960
1961 if (modifiers != 0)
1962 {
1963 /* Prepend modifiers to the character. */
1964 mch_memmove(typeahead + typeaheadlen + 3,
1965 typeahead + typeaheadlen, n);
1966 typeahead[typeaheadlen++] = K_SPECIAL;
1967 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1968 typeahead[typeaheadlen++] = modifiers;
1969 }
1970
1971 typeaheadlen += n;
1972
1973#ifdef MCH_WRITE_DUMP
1974 if (fdDump)
1975 fputc(c, fdDump);
1976#endif
1977 }
1978 }
1979 }
1980
1981#ifdef MCH_WRITE_DUMP
1982 if (fdDump)
1983 {
1984 fputs("]\n", fdDump);
1985 fflush(fdDump);
1986 }
1987#endif
1988
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989theend:
1990 /* Move typeahead to "buf", as much as fits. */
1991 len = 0;
1992 while (len < maxlen && typeaheadlen > 0)
1993 {
1994 buf[len++] = typeahead[0];
1995 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1996 }
1997 return len;
1998
1999#else /* FEAT_GUI_W32 */
2000 return 0;
2001#endif /* FEAT_GUI_W32 */
2002}
2003
Bram Moolenaar82881492012-11-20 16:53:39 +01002004#ifndef PROTO
2005# ifndef __MINGW32__
2006# include <shellapi.h> /* required for FindExecutable() */
2007# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008#endif
2009
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002010/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002011 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2012 * If "use_path" is FALSE: Return TRUE if "name" exists.
2013 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2014 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002015 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002016 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002017 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002018executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002020 char *dum;
2021 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002022 char *curpath, *newpath;
2023 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002024
Bram Moolenaar43663192017-03-05 14:29:12 +01002025 if (!use_path)
2026 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002027 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002028 {
2029 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002030 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002031 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002032 *path = vim_strsave((char_u *)name);
2033 else
2034 *path = FullName_save((char_u *)name, FALSE);
2035 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002036 return TRUE;
2037 }
2038 return FALSE;
2039 }
2040
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002041#ifdef FEAT_MBYTE
2042 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002044 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002045 WCHAR fnamew[_MAX_PATH];
2046 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002047 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002048
2049 if (p != NULL)
2050 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002051 wcurpath = _wgetenv(L"PATH");
2052 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2053 * sizeof(WCHAR));
2054 if (wnewpath == NULL)
2055 return FALSE;
2056 wcscpy(wnewpath, L".;");
2057 wcscat(wnewpath, wcurpath);
2058 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2059 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002060 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002061 if (n == 0)
2062 return FALSE;
2063 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2064 return FALSE;
2065 if (path != NULL)
2066 *path = utf16_to_enc(fnamew, NULL);
2067 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002068 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002070#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002071
2072 curpath = getenv("PATH");
2073 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2074 if (newpath == NULL)
2075 return FALSE;
2076 STRCPY(newpath, ".;");
2077 STRCAT(newpath, curpath);
2078 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2079 vim_free(newpath);
2080 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002081 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002082 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002083 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002084 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002085 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002086 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087}
2088
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002089#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002090 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002091/*
2092 * Bad parameter handler.
2093 *
2094 * Certain MS CRT functions will intentionally crash when passed invalid
2095 * parameters to highlight possible security holes. Setting this function as
2096 * the bad parameter handler will prevent the crash.
2097 *
2098 * In debug builds the parameters contain CRT information that might help track
2099 * down the source of a problem, but in non-debug builds the arguments are all
2100 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2101 * worth allowing these to make debugging of issues easier.
2102 */
2103 static void
2104bad_param_handler(const wchar_t *expression,
2105 const wchar_t *function,
2106 const wchar_t *file,
2107 unsigned int line,
2108 uintptr_t pReserved)
2109{
2110}
2111
2112# define SET_INVALID_PARAM_HANDLER \
2113 ((void)_set_invalid_parameter_handler(bad_param_handler))
2114#else
2115# define SET_INVALID_PARAM_HANDLER
2116#endif
2117
Bram Moolenaar071d4272004-06-13 20:20:40 +00002118#ifdef FEAT_GUI_W32
2119
2120/*
2121 * GUI version of mch_init().
2122 */
2123 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002124mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002125{
2126#ifndef __MINGW32__
2127 extern int _fmode;
2128#endif
2129
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002130 /* Silently handle invalid parameters to CRT functions */
2131 SET_INVALID_PARAM_HANDLER;
2132
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133 /* Let critical errors result in a failure, not in a dialog box. Required
2134 * for the timestamp test to work on removed floppies. */
2135 SetErrorMode(SEM_FAILCRITICALERRORS);
2136
2137 _fmode = O_BINARY; /* we do our own CR-LF translation */
2138
2139 /* Specify window size. Is there a place to get the default from? */
2140 Rows = 25;
2141 Columns = 80;
2142
2143 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002144 {
2145 char_u vimrun_location[_MAX_PATH + 4];
2146
2147 /* First try in same directory as gvim.exe */
2148 STRCPY(vimrun_location, exe_name);
2149 STRCPY(gettail(vimrun_location), "vimrun.exe");
2150 if (mch_getperm(vimrun_location) >= 0)
2151 {
2152 if (*skiptowhite(vimrun_location) != NUL)
2153 {
2154 /* Enclose path with white space in double quotes. */
2155 mch_memmove(vimrun_location + 1, vimrun_location,
2156 STRLEN(vimrun_location) + 1);
2157 *vimrun_location = '"';
2158 STRCPY(gettail(vimrun_location), "vimrun\" ");
2159 }
2160 else
2161 STRCPY(gettail(vimrun_location), "vimrun ");
2162
2163 vimrun_path = (char *)vim_strsave(vimrun_location);
2164 s_dont_use_vimrun = FALSE;
2165 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002166 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002167 s_dont_use_vimrun = FALSE;
2168
2169 /* Don't give the warning for a missing vimrun.exe right now, but only
2170 * when vimrun was supposed to be used. Don't bother people that do
2171 * not need vimrun.exe. */
2172 if (s_dont_use_vimrun)
2173 need_vimrun_warning = TRUE;
2174 }
2175
2176 /*
2177 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2178 * Otherwise the default "findstr /n" is used.
2179 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002180 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002181 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2182
2183#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002184 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185#endif
2186}
2187
2188
2189#else /* FEAT_GUI_W32 */
2190
2191#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2192#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2193
2194/*
2195 * ClearConsoleBuffer()
2196 * Description:
2197 * Clears the entire contents of the console screen buffer, using the
2198 * specified attribute.
2199 * Returns:
2200 * TRUE on success
2201 */
2202 static BOOL
2203ClearConsoleBuffer(WORD wAttribute)
2204{
2205 CONSOLE_SCREEN_BUFFER_INFO csbi;
2206 COORD coord;
2207 DWORD NumCells, dummy;
2208
2209 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2210 return FALSE;
2211
2212 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2213 coord.X = 0;
2214 coord.Y = 0;
2215 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2216 coord, &dummy))
2217 {
2218 return FALSE;
2219 }
2220 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2221 coord, &dummy))
2222 {
2223 return FALSE;
2224 }
2225
2226 return TRUE;
2227}
2228
2229/*
2230 * FitConsoleWindow()
2231 * Description:
2232 * Checks if the console window will fit within given buffer dimensions.
2233 * Also, if requested, will shrink the window to fit.
2234 * Returns:
2235 * TRUE on success
2236 */
2237 static BOOL
2238FitConsoleWindow(
2239 COORD dwBufferSize,
2240 BOOL WantAdjust)
2241{
2242 CONSOLE_SCREEN_BUFFER_INFO csbi;
2243 COORD dwWindowSize;
2244 BOOL NeedAdjust = FALSE;
2245
2246 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2247 {
2248 /*
2249 * A buffer resize will fail if the current console window does
2250 * not lie completely within that buffer. To avoid this, we might
2251 * have to move and possibly shrink the window.
2252 */
2253 if (csbi.srWindow.Right >= dwBufferSize.X)
2254 {
2255 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2256 if (dwWindowSize.X > dwBufferSize.X)
2257 dwWindowSize.X = dwBufferSize.X;
2258 csbi.srWindow.Right = dwBufferSize.X - 1;
2259 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2260 NeedAdjust = TRUE;
2261 }
2262 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2263 {
2264 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2265 if (dwWindowSize.Y > dwBufferSize.Y)
2266 dwWindowSize.Y = dwBufferSize.Y;
2267 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2268 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2269 NeedAdjust = TRUE;
2270 }
2271 if (NeedAdjust && WantAdjust)
2272 {
2273 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2274 return FALSE;
2275 }
2276 return TRUE;
2277 }
2278
2279 return FALSE;
2280}
2281
2282typedef struct ConsoleBufferStruct
2283{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002284 BOOL IsValid;
2285 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002286 PCHAR_INFO Buffer;
2287 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002288 PSMALL_RECT Regions;
2289 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290} ConsoleBuffer;
2291
2292/*
2293 * SaveConsoleBuffer()
2294 * Description:
2295 * Saves important information about the console buffer, including the
2296 * actual buffer contents. The saved information is suitable for later
2297 * restoration by RestoreConsoleBuffer().
2298 * Returns:
2299 * TRUE if all information was saved; FALSE otherwise
2300 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2301 */
2302 static BOOL
2303SaveConsoleBuffer(
2304 ConsoleBuffer *cb)
2305{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002306 DWORD NumCells;
2307 COORD BufferCoord;
2308 SMALL_RECT ReadRegion;
2309 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002310 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002311
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312 if (cb == NULL)
2313 return FALSE;
2314
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002315 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316 {
2317 cb->IsValid = FALSE;
2318 return FALSE;
2319 }
2320 cb->IsValid = TRUE;
2321
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002322 /*
2323 * Allocate a buffer large enough to hold the entire console screen
2324 * buffer. If this ConsoleBuffer structure has already been initialized
2325 * with a buffer of the correct size, then just use that one.
2326 */
2327 if (!cb->IsValid || cb->Buffer == NULL ||
2328 cb->BufferSize.X != cb->Info.dwSize.X ||
2329 cb->BufferSize.Y != cb->Info.dwSize.Y)
2330 {
2331 cb->BufferSize.X = cb->Info.dwSize.X;
2332 cb->BufferSize.Y = cb->Info.dwSize.Y;
2333 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2334 vim_free(cb->Buffer);
2335 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2336 if (cb->Buffer == NULL)
2337 return FALSE;
2338 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339
2340 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002341 * We will now copy the console screen buffer into our buffer.
2342 * ReadConsoleOutput() seems to be limited as far as how much you
2343 * can read at a time. Empirically, this number seems to be about
2344 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2345 * in chunks until it is all copied. The chunks will all have the
2346 * same horizontal characteristics, so initialize them now. The
2347 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002349 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002350 ReadRegion.Left = 0;
2351 ReadRegion.Right = cb->Info.dwSize.X - 1;
2352 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002353
2354 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2355 if (cb->Regions == NULL || numregions != cb->NumRegions)
2356 {
2357 cb->NumRegions = numregions;
2358 vim_free(cb->Regions);
2359 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2360 if (cb->Regions == NULL)
2361 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002362 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002363 return FALSE;
2364 }
2365 }
2366
2367 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002369 /*
2370 * Read into position (0, Y) in our buffer.
2371 */
2372 BufferCoord.Y = Y;
2373 /*
2374 * Read the region whose top left corner is (0, Y) and whose bottom
2375 * right corner is (width - 1, Y + Y_incr - 1). This should define
2376 * a region of size width by Y_incr. Don't worry if this region is
2377 * too large for the remaining buffer; it will be cropped.
2378 */
2379 ReadRegion.Top = Y;
2380 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002381 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002382 cb->Buffer, /* our buffer */
2383 cb->BufferSize, /* dimensions of our buffer */
2384 BufferCoord, /* offset in our buffer */
2385 &ReadRegion)) /* region to save */
2386 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002387 VIM_CLEAR(cb->Buffer);
2388 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002389 return FALSE;
2390 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002391 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392 }
2393
2394 return TRUE;
2395}
2396
2397/*
2398 * RestoreConsoleBuffer()
2399 * Description:
2400 * Restores important information about the console buffer, including the
2401 * actual buffer contents, if desired. The information to restore is in
2402 * the same format used by SaveConsoleBuffer().
2403 * Returns:
2404 * TRUE on success
2405 */
2406 static BOOL
2407RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002408 ConsoleBuffer *cb,
2409 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002410{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002411 COORD BufferCoord;
2412 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002413 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414
2415 if (cb == NULL || !cb->IsValid)
2416 return FALSE;
2417
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002418 /*
2419 * Before restoring the buffer contents, clear the current buffer, and
2420 * restore the cursor position and window information. Doing this now
2421 * prevents old buffer contents from "flashing" onto the screen.
2422 */
2423 if (RestoreScreen)
2424 ClearConsoleBuffer(cb->Info.wAttributes);
2425
2426 FitConsoleWindow(cb->Info.dwSize, TRUE);
2427 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2428 return FALSE;
2429 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2430 return FALSE;
2431
2432 if (!RestoreScreen)
2433 {
2434 /*
2435 * No need to restore the screen buffer contents, so we're done.
2436 */
2437 return TRUE;
2438 }
2439
2440 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2441 return FALSE;
2442 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2443 return FALSE;
2444
2445 /*
2446 * Restore the screen buffer contents.
2447 */
2448 if (cb->Buffer != NULL)
2449 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002450 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002451 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002452 BufferCoord.X = cb->Regions[i].Left;
2453 BufferCoord.Y = cb->Regions[i].Top;
2454 WriteRegion = cb->Regions[i];
2455 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2456 cb->Buffer, /* our buffer */
2457 cb->BufferSize, /* dimensions of our buffer */
2458 BufferCoord, /* offset in our buffer */
2459 &WriteRegion)) /* region to restore */
2460 {
2461 return FALSE;
2462 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002463 }
2464 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465
2466 return TRUE;
2467}
2468
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002469#define FEAT_RESTORE_ORIG_SCREEN
2470#ifdef FEAT_RESTORE_ORIG_SCREEN
2471static ConsoleBuffer g_cbOrig = { 0 };
2472#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473static ConsoleBuffer g_cbNonTermcap = { 0 };
2474static ConsoleBuffer g_cbTermcap = { 0 };
2475
2476#ifdef FEAT_TITLE
2477#ifdef __BORLANDC__
2478typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2479#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002480typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481#endif
2482char g_szOrigTitle[256] = { 0 };
2483HWND g_hWnd = NULL; /* also used in os_mswin.c */
2484static HICON g_hOrigIconSmall = NULL;
2485static HICON g_hOrigIcon = NULL;
2486static HICON g_hVimIcon = NULL;
2487static BOOL g_fCanChangeIcon = FALSE;
2488
2489/* ICON* are not defined in VC++ 4.0 */
2490#ifndef ICON_SMALL
2491#define ICON_SMALL 0
2492#endif
2493#ifndef ICON_BIG
2494#define ICON_BIG 1
2495#endif
2496/*
2497 * GetConsoleIcon()
2498 * Description:
2499 * Attempts to retrieve the small icon and/or the big icon currently in
2500 * use by a given window.
2501 * Returns:
2502 * TRUE on success
2503 */
2504 static BOOL
2505GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002506 HWND hWnd,
2507 HICON *phIconSmall,
2508 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509{
2510 if (hWnd == NULL)
2511 return FALSE;
2512
2513 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002514 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2515 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002517 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2518 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 return TRUE;
2520}
2521
2522/*
2523 * SetConsoleIcon()
2524 * Description:
2525 * Attempts to change the small icon and/or the big icon currently in
2526 * use by a given window.
2527 * Returns:
2528 * TRUE on success
2529 */
2530 static BOOL
2531SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002532 HWND hWnd,
2533 HICON hIconSmall,
2534 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002536 if (hWnd == NULL)
2537 return FALSE;
2538
2539 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002540 SendMessage(hWnd, WM_SETICON,
2541 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002543 SendMessage(hWnd, WM_SETICON,
2544 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002545 return TRUE;
2546}
2547
2548/*
2549 * SaveConsoleTitleAndIcon()
2550 * Description:
2551 * Saves the current console window title in g_szOrigTitle, for later
2552 * restoration. Also, attempts to obtain a handle to the console window,
2553 * and use it to save the small and big icons currently in use by the
2554 * console window. This is not always possible on some versions of Windows;
2555 * nor is it possible when running Vim remotely using Telnet (since the
2556 * console window the user sees is owned by a remote process).
2557 */
2558 static void
2559SaveConsoleTitleAndIcon(void)
2560{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561 /* Save the original title. */
2562 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2563 return;
2564
2565 /*
2566 * Obtain a handle to the console window using GetConsoleWindow() from
2567 * KERNEL32.DLL; we need to handle in order to change the window icon.
2568 * This function only exists on NT-based Windows, starting with Windows
2569 * 2000. On older operating systems, we can't change the window icon
2570 * anyway.
2571 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002572 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573 if (g_hWnd == NULL)
2574 return;
2575
2576 /* Save the original console window icon. */
2577 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2578 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2579 return;
2580
2581 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002582 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002583 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 if (g_hVimIcon != NULL)
2585 g_fCanChangeIcon = TRUE;
2586}
2587#endif
2588
2589static int g_fWindInitCalled = FALSE;
2590static int g_fTermcapMode = FALSE;
2591static CONSOLE_CURSOR_INFO g_cci;
2592static DWORD g_cmodein = 0;
2593static DWORD g_cmodeout = 0;
2594
2595/*
2596 * non-GUI version of mch_init().
2597 */
2598 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002599mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002601#ifndef FEAT_RESTORE_ORIG_SCREEN
2602 CONSOLE_SCREEN_BUFFER_INFO csbi;
2603#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604#ifndef __MINGW32__
2605 extern int _fmode;
2606#endif
2607
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002608 /* Silently handle invalid parameters to CRT functions */
2609 SET_INVALID_PARAM_HANDLER;
2610
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 /* Let critical errors result in a failure, not in a dialog box. Required
2612 * for the timestamp test to work on removed floppies. */
2613 SetErrorMode(SEM_FAILCRITICALERRORS);
2614
2615 _fmode = O_BINARY; /* we do our own CR-LF translation */
2616 out_flush();
2617
2618 /* Obtain handles for the standard Console I/O devices */
2619 if (read_cmd_fd == 0)
2620 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2621 else
2622 create_conin();
2623 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2624
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002625#ifdef FEAT_RESTORE_ORIG_SCREEN
2626 /* Save the initial console buffer for later restoration */
2627 SaveConsoleBuffer(&g_cbOrig);
2628 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2629#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002631 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2632 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2633#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 if (cterm_normal_fg_color == 0)
2635 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2636 if (cterm_normal_bg_color == 0)
2637 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2638
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002639 // Fg and Bg color index nunmber at startup
2640 g_color_index_fg = g_attrDefault & 0xf;
2641 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2642
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643 /* set termcap codes to current text attributes */
2644 update_tcap(g_attrCurrent);
2645
2646 GetConsoleCursorInfo(g_hConOut, &g_cci);
2647 GetConsoleMode(g_hConIn, &g_cmodein);
2648 GetConsoleMode(g_hConOut, &g_cmodeout);
2649
2650#ifdef FEAT_TITLE
2651 SaveConsoleTitleAndIcon();
2652 /*
2653 * Set both the small and big icons of the console window to Vim's icon.
2654 * Note that Vim presently only has one size of icon (32x32), but it
2655 * automatically gets scaled down to 16x16 when setting the small icon.
2656 */
2657 if (g_fCanChangeIcon)
2658 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2659#endif
2660
2661 ui_get_shellsize();
2662
2663#ifdef MCH_WRITE_DUMP
2664 fdDump = fopen("dump", "wt");
2665
2666 if (fdDump)
2667 {
2668 time_t t;
2669
2670 time(&t);
2671 fputs(ctime(&t), fdDump);
2672 fflush(fdDump);
2673 }
2674#endif
2675
2676 g_fWindInitCalled = TRUE;
2677
2678#ifdef FEAT_MOUSE
2679 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2680#endif
2681
2682#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002683 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002685
2686 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002687}
2688
2689/*
2690 * non-GUI version of mch_exit().
2691 * Shut down and exit with status `r'
2692 * Careful: mch_exit() may be called before mch_init()!
2693 */
2694 void
2695mch_exit(int r)
2696{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002697 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002698
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002699 vtp_exit();
2700
Bram Moolenaar955f1982017-02-05 15:10:51 +01002701 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702 if (g_fWindInitCalled)
2703 settmode(TMODE_COOK);
2704
2705 ml_close_all(TRUE); /* remove all memfiles */
2706
2707 if (g_fWindInitCalled)
2708 {
2709#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002710 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 /*
2712 * Restore both the small and big icons of the console window to
2713 * what they were at startup. Don't do this when the window is
2714 * closed, Vim would hang here.
2715 */
2716 if (g_fCanChangeIcon && !g_fForceExit)
2717 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2718#endif
2719
2720#ifdef MCH_WRITE_DUMP
2721 if (fdDump)
2722 {
2723 time_t t;
2724
2725 time(&t);
2726 fputs(ctime(&t), fdDump);
2727 fclose(fdDump);
2728 }
2729 fdDump = NULL;
2730#endif
2731 }
2732
2733 SetConsoleCursorInfo(g_hConOut, &g_cci);
2734 SetConsoleMode(g_hConIn, g_cmodein);
2735 SetConsoleMode(g_hConOut, g_cmodeout);
2736
2737#ifdef DYNAMIC_GETTEXT
2738 dyn_libintl_end();
2739#endif
2740
2741 exit(r);
2742}
2743#endif /* !FEAT_GUI_W32 */
2744
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745/*
2746 * Do we have an interactive window?
2747 */
2748 int
2749mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002750 int argc UNUSED,
2751 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002752{
2753 get_exe_name();
2754
2755#ifdef FEAT_GUI_W32
2756 return OK; /* GUI always has a tty */
2757#else
2758 if (isatty(1))
2759 return OK;
2760 return FAIL;
2761#endif
2762}
2763
2764
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002765#ifdef FEAT_MBYTE
2766/*
2767 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2768 * if it already exists. When "len" is > 0, also expand short to long
2769 * filenames.
2770 * Return FAIL if wide functions are not available, OK otherwise.
2771 * NOTE: much of this is identical to fname_case(), keep in sync!
2772 */
2773 static int
2774fname_casew(
2775 WCHAR *name,
2776 int len)
2777{
2778 WCHAR szTrueName[_MAX_PATH + 2];
2779 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2780 WCHAR *ptrue, *ptruePrev;
2781 WCHAR *porig, *porigPrev;
2782 int flen;
2783 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002784 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002785 int c;
2786 int slen;
2787
2788 flen = (int)wcslen(name);
2789 if (flen > _MAX_PATH)
2790 return OK;
2791
2792 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2793
2794 /* Build the new name in szTrueName[] one component at a time. */
2795 porig = name;
2796 ptrue = szTrueName;
2797
2798 if (iswalpha(porig[0]) && porig[1] == L':')
2799 {
2800 /* copy leading drive letter */
2801 *ptrue++ = *porig++;
2802 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002803 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002804 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002805
2806 while (*porig != NUL)
2807 {
2808 /* copy \ characters */
2809 while (*porig == psepc)
2810 *ptrue++ = *porig++;
2811
2812 ptruePrev = ptrue;
2813 porigPrev = porig;
2814 while (*porig != NUL && *porig != psepc)
2815 {
2816 *ptrue++ = *porig++;
2817 }
2818 *ptrue = NUL;
2819
2820 /* To avoid a slow failure append "\*" when searching a directory,
2821 * server or network share. */
2822 wcscpy(szTrueNameTemp, szTrueName);
2823 slen = (int)wcslen(szTrueNameTemp);
2824 if (*porig == psepc && slen + 2 < _MAX_PATH)
2825 wcscpy(szTrueNameTemp + slen, L"\\*");
2826
2827 /* Skip "", "." and "..". */
2828 if (ptrue > ptruePrev
2829 && (ptruePrev[0] != L'.'
2830 || (ptruePrev[1] != NUL
2831 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2832 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2833 != INVALID_HANDLE_VALUE)
2834 {
2835 c = *porig;
2836 *porig = NUL;
2837
2838 /* Only use the match when it's the same name (ignoring case) or
2839 * expansion is allowed and there is a match with the short name
2840 * and there is enough room. */
2841 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2842 || (len > 0
2843 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2844 && (int)(ptruePrev - szTrueName)
2845 + (int)wcslen(fb.cFileName) < len)))
2846 {
2847 wcscpy(ptruePrev, fb.cFileName);
2848
2849 /* Look for exact match and prefer it if found. Must be a
2850 * long name, otherwise there would be only one match. */
2851 while (FindNextFileW(hFind, &fb))
2852 {
2853 if (*fb.cAlternateFileName != NUL
2854 && (wcscoll(porigPrev, fb.cFileName) == 0
2855 || (len > 0
2856 && (_wcsicoll(porigPrev,
2857 fb.cAlternateFileName) == 0
2858 && (int)(ptruePrev - szTrueName)
2859 + (int)wcslen(fb.cFileName) < len))))
2860 {
2861 wcscpy(ptruePrev, fb.cFileName);
2862 break;
2863 }
2864 }
2865 }
2866 FindClose(hFind);
2867 *porig = c;
2868 ptrue = ptruePrev + wcslen(ptruePrev);
2869 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002870 }
2871
2872 wcscpy(name, szTrueName);
2873 return OK;
2874}
2875#endif
2876
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877/*
2878 * fname_case(): Set the case of the file name, if it already exists.
2879 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002880 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 */
2882 void
2883fname_case(
2884 char_u *name,
2885 int len)
2886{
2887 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002888 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889 char *ptrue, *ptruePrev;
2890 char *porig, *porigPrev;
2891 int flen;
2892 WIN32_FIND_DATA fb;
2893 HANDLE hFind;
2894 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002895 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002897 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002898 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 return;
2900
2901 slash_adjust(name);
2902
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002903#ifdef FEAT_MBYTE
2904 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2905 {
2906 WCHAR *p = enc_to_utf16(name, NULL);
2907
2908 if (p != NULL)
2909 {
2910 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002911 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002912
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002913 wcsncpy(buf, p, _MAX_PATH);
2914 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002915 vim_free(p);
2916
2917 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2918 {
2919 q = utf16_to_enc(buf, NULL);
2920 if (q != NULL)
2921 {
2922 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2923 vim_free(q);
2924 return;
2925 }
2926 }
2927 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002928 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002929 }
2930#endif
2931
2932 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2933 * So we should check this after calling wide function. */
2934 if (flen > _MAX_PATH)
2935 return;
2936
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002938 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 ptrue = szTrueName;
2940
2941 if (isalpha(porig[0]) && porig[1] == ':')
2942 {
2943 /* copy leading drive letter */
2944 *ptrue++ = *porig++;
2945 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002947 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948
2949 while (*porig != NUL)
2950 {
2951 /* copy \ characters */
2952 while (*porig == psepc)
2953 *ptrue++ = *porig++;
2954
2955 ptruePrev = ptrue;
2956 porigPrev = porig;
2957 while (*porig != NUL && *porig != psepc)
2958 {
2959#ifdef FEAT_MBYTE
2960 int l;
2961
2962 if (enc_dbcs)
2963 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002964 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002965 while (--l >= 0)
2966 *ptrue++ = *porig++;
2967 }
2968 else
2969#endif
2970 *ptrue++ = *porig++;
2971 }
2972 *ptrue = NUL;
2973
Bram Moolenaar464c9252010-10-13 20:37:41 +02002974 /* To avoid a slow failure append "\*" when searching a directory,
2975 * server or network share. */
2976 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002977 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002978 if (*porig == psepc && slen + 2 < _MAX_PATH)
2979 STRCPY(szTrueNameTemp + slen, "\\*");
2980
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981 /* Skip "", "." and "..". */
2982 if (ptrue > ptruePrev
2983 && (ptruePrev[0] != '.'
2984 || (ptruePrev[1] != NUL
2985 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002986 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002987 != INVALID_HANDLE_VALUE)
2988 {
2989 c = *porig;
2990 *porig = NUL;
2991
2992 /* Only use the match when it's the same name (ignoring case) or
2993 * expansion is allowed and there is a match with the short name
2994 * and there is enough room. */
2995 if (_stricoll(porigPrev, fb.cFileName) == 0
2996 || (len > 0
2997 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2998 && (int)(ptruePrev - szTrueName)
2999 + (int)strlen(fb.cFileName) < len)))
3000 {
3001 STRCPY(ptruePrev, fb.cFileName);
3002
3003 /* Look for exact match and prefer it if found. Must be a
3004 * long name, otherwise there would be only one match. */
3005 while (FindNextFile(hFind, &fb))
3006 {
3007 if (*fb.cAlternateFileName != NUL
3008 && (strcoll(porigPrev, fb.cFileName) == 0
3009 || (len > 0
3010 && (_stricoll(porigPrev,
3011 fb.cAlternateFileName) == 0
3012 && (int)(ptruePrev - szTrueName)
3013 + (int)strlen(fb.cFileName) < len))))
3014 {
3015 STRCPY(ptruePrev, fb.cFileName);
3016 break;
3017 }
3018 }
3019 }
3020 FindClose(hFind);
3021 *porig = c;
3022 ptrue = ptruePrev + strlen(ptruePrev);
3023 }
3024 }
3025
3026 STRCPY(name, szTrueName);
3027}
3028
3029
3030/*
3031 * Insert user name in s[len].
3032 */
3033 int
3034mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003035 char_u *s,
3036 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003038 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003039 DWORD cch = sizeof szUserName;
3040
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003041#ifdef FEAT_MBYTE
3042 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3043 {
3044 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3045 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3046
3047 if (GetUserNameW(wszUserName, &wcch))
3048 {
3049 char_u *p = utf16_to_enc(wszUserName, NULL);
3050
3051 if (p != NULL)
3052 {
3053 vim_strncpy(s, p, len - 1);
3054 vim_free(p);
3055 return OK;
3056 }
3057 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003058 }
3059#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060 if (GetUserName(szUserName, &cch))
3061 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003062 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063 return OK;
3064 }
3065 s[0] = NUL;
3066 return FAIL;
3067}
3068
3069
3070/*
3071 * Insert host name in s[len].
3072 */
3073 void
3074mch_get_host_name(
3075 char_u *s,
3076 int len)
3077{
3078 DWORD cch = len;
3079
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003080#ifdef FEAT_MBYTE
3081 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3082 {
3083 WCHAR wszHostName[256 + 1];
3084 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3085
3086 if (GetComputerNameW(wszHostName, &wcch))
3087 {
3088 char_u *p = utf16_to_enc(wszHostName, NULL);
3089
3090 if (p != NULL)
3091 {
3092 vim_strncpy(s, p, len - 1);
3093 vim_free(p);
3094 return;
3095 }
3096 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003097 }
3098#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003099 if (!GetComputerName((LPSTR)s, &cch))
3100 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101}
3102
3103
3104/*
3105 * return process ID
3106 */
3107 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003108mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003109{
3110 return (long)GetCurrentProcessId();
3111}
3112
3113
3114/*
3115 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3116 * Return OK for success, FAIL for failure.
3117 */
3118 int
3119mch_dirname(
3120 char_u *buf,
3121 int len)
3122{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003123 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003124 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003125
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126 /*
3127 * Originally this was:
3128 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3129 * But the Win32s known bug list says that getcwd() doesn't work
3130 * so use the Win32 system call instead. <Negri>
3131 */
3132#ifdef FEAT_MBYTE
3133 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3134 {
3135 WCHAR wbuf[_MAX_PATH + 1];
3136
3137 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3138 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003139 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003140 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003141
3142 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003143 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003144 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003145 if (STRLEN(p) >= (size_t)len)
3146 {
3147 // long path name is too long, fall back to short one
3148 vim_free(p);
3149 p = NULL;
3150 }
3151 }
3152 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003153 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154
3155 if (p != NULL)
3156 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003157 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158 vim_free(p);
3159 return OK;
3160 }
3161 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003162 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163 }
3164#endif
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003165 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3166 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003167 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3168 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3169 // Failed to get long path name or it's too long: fall back to the
3170 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003171 return OK;
3172
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003173 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003174 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175}
3176
3177/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003178 * Get file permissions for "name".
3179 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 */
3181 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003182mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003184 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003185 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003186
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003187 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003188 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189}
3190
3191
3192/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003193 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003194 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003195 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196 */
3197 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003198mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003200 long n = -1;
3201
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202#ifdef FEAT_MBYTE
3203 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3204 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003205 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206
3207 if (p != NULL)
3208 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003209 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003211 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003212 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213 }
3214 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003215 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003216#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003217 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003218 if (n == -1)
3219 return FAIL;
3220
3221 win32_set_archive(name);
3222
3223 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224}
3225
3226/*
3227 * Set hidden flag for "name".
3228 */
3229 void
3230mch_hide(char_u *name)
3231{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003232 int attrs = win32_getattrs(name);
3233 if (attrs == -1)
3234 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003236 attrs |= FILE_ATTRIBUTE_HIDDEN;
3237 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238}
3239
3240/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003241 * Return TRUE if file "name" exists and is hidden.
3242 */
3243 int
3244mch_ishidden(char_u *name)
3245{
3246 int f = win32_getattrs(name);
3247
3248 if (f == -1)
3249 return FALSE; /* file does not exist at all */
3250
3251 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3252}
3253
3254/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003255 * return TRUE if "name" is a directory
3256 * return FALSE if "name" is not a directory or upon error
3257 */
3258 int
3259mch_isdir(char_u *name)
3260{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003261 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262
3263 if (f == -1)
3264 return FALSE; /* file does not exist at all */
3265
3266 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3267}
3268
3269/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003270 * return TRUE if "name" is a directory, NOT a symlink to a directory
3271 * return FALSE if "name" is not a directory
3272 * return FALSE for error
3273 */
3274 int
3275mch_isrealdir(char_u *name)
3276{
3277 return mch_isdir(name) && !mch_is_symbolic_link(name);
3278}
3279
3280/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003281 * Create directory "name".
3282 * Return 0 on success, -1 on error.
3283 */
3284 int
3285mch_mkdir(char_u *name)
3286{
3287#ifdef FEAT_MBYTE
3288 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3289 {
3290 WCHAR *p;
3291 int retval;
3292
3293 p = enc_to_utf16(name, NULL);
3294 if (p == NULL)
3295 return -1;
3296 retval = _wmkdir(p);
3297 vim_free(p);
3298 return retval;
3299 }
3300#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003301 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003302}
3303
3304/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003305 * Delete directory "name".
3306 * Return 0 on success, -1 on error.
3307 */
3308 int
3309mch_rmdir(char_u *name)
3310{
3311#ifdef FEAT_MBYTE
3312 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3313 {
3314 WCHAR *p;
3315 int retval;
3316
3317 p = enc_to_utf16(name, NULL);
3318 if (p == NULL)
3319 return -1;
3320 retval = _wrmdir(p);
3321 vim_free(p);
3322 return retval;
3323 }
3324#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003325 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003326}
3327
3328/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003329 * Return TRUE if file "fname" has more than one link.
3330 */
3331 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003332mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003333{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003334 BY_HANDLE_FILE_INFORMATION info;
3335
3336 return win32_fileinfo(fname, &info) == FILEINFO_OK
3337 && info.nNumberOfLinks > 1;
3338}
3339
3340/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003341 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003342 */
3343 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003344mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003345{
3346 HANDLE hFind;
3347 int res = FALSE;
3348 WIN32_FIND_DATAA findDataA;
3349 DWORD fileFlags = 0, reparseTag = 0;
3350#ifdef FEAT_MBYTE
3351 WCHAR *wn = NULL;
3352 WIN32_FIND_DATAW findDataW;
3353
3354 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003355 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003356 if (wn != NULL)
3357 {
3358 hFind = FindFirstFileW(wn, &findDataW);
3359 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003360 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003361 {
3362 fileFlags = findDataW.dwFileAttributes;
3363 reparseTag = findDataW.dwReserved0;
3364 }
3365 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003366 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003367#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003368 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003369 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003370 if (hFind != INVALID_HANDLE_VALUE)
3371 {
3372 fileFlags = findDataA.dwFileAttributes;
3373 reparseTag = findDataA.dwReserved0;
3374 }
3375 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003376
3377 if (hFind != INVALID_HANDLE_VALUE)
3378 FindClose(hFind);
3379
3380 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003381 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3382 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003383 res = TRUE;
3384
3385 return res;
3386}
3387
3388/*
3389 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3390 * link.
3391 */
3392 int
3393mch_is_linked(char_u *fname)
3394{
3395 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3396 return TRUE;
3397 return FALSE;
3398}
3399
3400/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003401 * Get the by-handle-file-information for "fname".
3402 * Returns FILEINFO_OK when OK.
3403 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3404 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3405 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3406 */
3407 int
3408win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3409{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003410 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003411 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003412#ifdef FEAT_MBYTE
3413 WCHAR *wn = NULL;
3414
3415 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003416 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003417 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003418 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003419 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003420 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003421 if (wn != NULL)
3422 {
3423 hFile = CreateFileW(wn, /* file name */
3424 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003425 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003426 NULL, /* security descriptor */
3427 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003428 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003429 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003430 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003431 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003432 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003433#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003434 hFile = CreateFile((LPCSTR)fname, /* file name */
3435 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003436 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003437 NULL, /* security descriptor */
3438 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003439 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003440 NULL); /* handle to template file */
3441
3442 if (hFile != INVALID_HANDLE_VALUE)
3443 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003444 if (GetFileInformationByHandle(hFile, info) != 0)
3445 res = FILEINFO_OK;
3446 else
3447 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003448 CloseHandle(hFile);
3449 }
3450
Bram Moolenaar03f48552006-02-28 23:52:23 +00003451 return res;
3452}
3453
3454/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003455 * get file attributes for `name'
3456 * -1 : error
3457 * else FILE_ATTRIBUTE_* defined in winnt.h
3458 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003459 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003460win32_getattrs(char_u *name)
3461{
3462 int attr;
3463#ifdef FEAT_MBYTE
3464 WCHAR *p = NULL;
3465
3466 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3467 p = enc_to_utf16(name, NULL);
3468
3469 if (p != NULL)
3470 {
3471 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003472 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003473 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003474 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003475#endif
3476 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003477
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003478 return attr;
3479}
3480
3481/*
3482 * set file attributes for `name' to `attrs'
3483 *
3484 * return -1 for failure, 0 otherwise
3485 */
3486 static
3487 int
3488win32_setattrs(char_u *name, int attrs)
3489{
3490 int res;
3491#ifdef FEAT_MBYTE
3492 WCHAR *p = NULL;
3493
3494 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3495 p = enc_to_utf16(name, NULL);
3496
3497 if (p != NULL)
3498 {
3499 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003500 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003501 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003502 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003503#endif
3504 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003505
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003506 return res ? 0 : -1;
3507}
3508
3509/*
3510 * Set archive flag for "name".
3511 */
3512 static
3513 int
3514win32_set_archive(char_u *name)
3515{
3516 int attrs = win32_getattrs(name);
3517 if (attrs == -1)
3518 return -1;
3519
3520 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3521 return win32_setattrs(name, attrs);
3522}
3523
3524/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003525 * Return TRUE if file or directory "name" is writable (not readonly).
3526 * Strange semantics of Win32: a readonly directory is writable, but you can't
3527 * delete a file. Let's say this means it is writable.
3528 */
3529 int
3530mch_writable(char_u *name)
3531{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003532 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003533
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003534 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3535 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003536}
3537
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003539 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003540 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003541 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3542 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543 */
3544 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003545mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003546{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003547 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003548 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003549 char_u *p;
3550
3551 if (len >= _MAX_PATH) /* safety check */
3552 return FALSE;
3553
3554 /* If there already is an extension try using the name directly. Also do
3555 * this with a Unix-shell like 'shell'. */
3556 if (vim_strchr(gettail(name), '.') != NULL
3557 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003558 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003559 return TRUE;
3560
3561 /*
3562 * Loop over all extensions in $PATHEXT.
3563 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003564 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003565 p = mch_getenv("PATHEXT");
3566 if (p == NULL)
3567 p = (char_u *)".com;.exe;.bat;.cmd";
3568 while (*p)
3569 {
3570 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3571 {
3572 /* A single "." means no extension is added. */
3573 buf[len] = NUL;
3574 ++p;
3575 if (*p)
3576 ++p;
3577 }
3578 else
3579 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003580 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003581 return TRUE;
3582 }
3583 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585
3586/*
3587 * Check what "name" is:
3588 * NODE_NORMAL: file or directory (or doesn't exist)
3589 * NODE_WRITABLE: writable device, socket, fifo, etc.
3590 * NODE_OTHER: non-writable things
3591 */
3592 int
3593mch_nodetype(char_u *name)
3594{
3595 HANDLE hFile;
3596 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003597#ifdef FEAT_MBYTE
3598 WCHAR *wn = NULL;
3599#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600
Bram Moolenaar043545e2006-10-10 16:44:07 +00003601 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3602 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3603 * here. */
3604 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3605 return NODE_WRITABLE;
3606
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003607#ifdef FEAT_MBYTE
3608 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003609 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003610
3611 if (wn != NULL)
3612 {
3613 hFile = CreateFileW(wn, /* file name */
3614 GENERIC_WRITE, /* access mode */
3615 0, /* share mode */
3616 NULL, /* security descriptor */
3617 OPEN_EXISTING, /* creation disposition */
3618 0, /* file attributes */
3619 NULL); /* handle to template file */
3620 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003621 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003622 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003623#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003624 hFile = CreateFile((LPCSTR)name, /* file name */
3625 GENERIC_WRITE, /* access mode */
3626 0, /* share mode */
3627 NULL, /* security descriptor */
3628 OPEN_EXISTING, /* creation disposition */
3629 0, /* file attributes */
3630 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631
3632 if (hFile == INVALID_HANDLE_VALUE)
3633 return NODE_NORMAL;
3634
3635 type = GetFileType(hFile);
3636 CloseHandle(hFile);
3637 if (type == FILE_TYPE_CHAR)
3638 return NODE_WRITABLE;
3639 if (type == FILE_TYPE_DISK)
3640 return NODE_NORMAL;
3641 return NODE_OTHER;
3642}
3643
3644#ifdef HAVE_ACL
3645struct my_acl
3646{
3647 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3648 PSID pSidOwner;
3649 PSID pSidGroup;
3650 PACL pDacl;
3651 PACL pSacl;
3652};
3653#endif
3654
3655/*
3656 * Return a pointer to the ACL of file "fname" in allocated memory.
3657 * Return NULL if the ACL is not available for whatever reason.
3658 */
3659 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003660mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003661{
3662#ifndef HAVE_ACL
3663 return (vim_acl_T)NULL;
3664#else
3665 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003666 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003667
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003668 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3669 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003671# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003672 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003673
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003674 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3675 wn = enc_to_utf16(fname, NULL);
3676 if (wn != NULL)
3677 {
3678 /* Try to retrieve the entire security descriptor. */
3679 err = GetNamedSecurityInfoW(
3680 wn, // Abstract filename
3681 SE_FILE_OBJECT, // File Object
3682 OWNER_SECURITY_INFORMATION |
3683 GROUP_SECURITY_INFORMATION |
3684 DACL_SECURITY_INFORMATION |
3685 SACL_SECURITY_INFORMATION,
3686 &p->pSidOwner, // Ownership information.
3687 &p->pSidGroup, // Group membership.
3688 &p->pDacl, // Discretionary information.
3689 &p->pSacl, // For auditing purposes.
3690 &p->pSecurityDescriptor);
3691 if (err == ERROR_ACCESS_DENIED ||
3692 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003694 /* Retrieve only DACL. */
3695 (void)GetNamedSecurityInfoW(
3696 wn,
3697 SE_FILE_OBJECT,
3698 DACL_SECURITY_INFORMATION,
3699 NULL,
3700 NULL,
3701 &p->pDacl,
3702 NULL,
3703 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003704 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003705 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003706 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003707 mch_free_acl((vim_acl_T)p);
3708 p = NULL;
3709 }
3710 vim_free(wn);
3711 }
3712 else
3713# endif
3714 {
3715 /* Try to retrieve the entire security descriptor. */
3716 err = GetNamedSecurityInfo(
3717 (LPSTR)fname, // Abstract filename
3718 SE_FILE_OBJECT, // File Object
3719 OWNER_SECURITY_INFORMATION |
3720 GROUP_SECURITY_INFORMATION |
3721 DACL_SECURITY_INFORMATION |
3722 SACL_SECURITY_INFORMATION,
3723 &p->pSidOwner, // Ownership information.
3724 &p->pSidGroup, // Group membership.
3725 &p->pDacl, // Discretionary information.
3726 &p->pSacl, // For auditing purposes.
3727 &p->pSecurityDescriptor);
3728 if (err == ERROR_ACCESS_DENIED ||
3729 err == ERROR_PRIVILEGE_NOT_HELD)
3730 {
3731 /* Retrieve only DACL. */
3732 (void)GetNamedSecurityInfo(
3733 (LPSTR)fname,
3734 SE_FILE_OBJECT,
3735 DACL_SECURITY_INFORMATION,
3736 NULL,
3737 NULL,
3738 &p->pDacl,
3739 NULL,
3740 &p->pSecurityDescriptor);
3741 }
3742 if (p->pSecurityDescriptor == NULL)
3743 {
3744 mch_free_acl((vim_acl_T)p);
3745 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003746 }
3747 }
3748 }
3749
3750 return (vim_acl_T)p;
3751#endif
3752}
3753
Bram Moolenaar27515922013-06-29 15:36:26 +02003754#ifdef HAVE_ACL
3755/*
3756 * Check if "acl" contains inherited ACE.
3757 */
3758 static BOOL
3759is_acl_inherited(PACL acl)
3760{
3761 DWORD i;
3762 ACL_SIZE_INFORMATION acl_info;
3763 PACCESS_ALLOWED_ACE ace;
3764
3765 acl_info.AceCount = 0;
3766 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3767 for (i = 0; i < acl_info.AceCount; i++)
3768 {
3769 GetAce(acl, i, (LPVOID *)&ace);
3770 if (ace->Header.AceFlags & INHERITED_ACE)
3771 return TRUE;
3772 }
3773 return FALSE;
3774}
3775#endif
3776
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777/*
3778 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3779 * Errors are ignored.
3780 * This must only be called with "acl" equal to what mch_get_acl() returned.
3781 */
3782 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003783mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003784{
3785#ifdef HAVE_ACL
3786 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003787 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003789 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003790 {
3791# ifdef FEAT_MBYTE
3792 WCHAR *wn = NULL;
3793# endif
3794
3795 /* Set security flags */
3796 if (p->pSidOwner)
3797 sec_info |= OWNER_SECURITY_INFORMATION;
3798 if (p->pSidGroup)
3799 sec_info |= GROUP_SECURITY_INFORMATION;
3800 if (p->pDacl)
3801 {
3802 sec_info |= DACL_SECURITY_INFORMATION;
3803 /* Do not inherit its parent's DACL.
3804 * If the DACL is inherited, Cygwin permissions would be changed.
3805 */
3806 if (!is_acl_inherited(p->pDacl))
3807 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3808 }
3809 if (p->pSacl)
3810 sec_info |= SACL_SECURITY_INFORMATION;
3811
3812# ifdef FEAT_MBYTE
3813 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3814 wn = enc_to_utf16(fname, NULL);
3815 if (wn != NULL)
3816 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003817 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003818 wn, // Abstract filename
3819 SE_FILE_OBJECT, // File Object
3820 sec_info,
3821 p->pSidOwner, // Ownership information.
3822 p->pSidGroup, // Group membership.
3823 p->pDacl, // Discretionary information.
3824 p->pSacl // For auditing purposes.
3825 );
3826 vim_free(wn);
3827 }
3828 else
3829# endif
3830 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003831 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003832 (LPSTR)fname, // Abstract filename
3833 SE_FILE_OBJECT, // File Object
3834 sec_info,
3835 p->pSidOwner, // Ownership information.
3836 p->pSidGroup, // Group membership.
3837 p->pDacl, // Discretionary information.
3838 p->pSacl // For auditing purposes.
3839 );
3840 }
3841 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842#endif
3843}
3844
3845 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003846mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847{
3848#ifdef HAVE_ACL
3849 struct my_acl *p = (struct my_acl *)acl;
3850
3851 if (p != NULL)
3852 {
3853 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3854 vim_free(p);
3855 }
3856#endif
3857}
3858
3859#ifndef FEAT_GUI_W32
3860
3861/*
3862 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3863 */
3864 static BOOL WINAPI
3865handler_routine(
3866 DWORD dwCtrlType)
3867{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003868 INPUT_RECORD ir;
3869 DWORD out;
3870
Bram Moolenaar071d4272004-06-13 20:20:40 +00003871 switch (dwCtrlType)
3872 {
3873 case CTRL_C_EVENT:
3874 if (ctrl_c_interrupts)
3875 g_fCtrlCPressed = TRUE;
3876 return TRUE;
3877
3878 case CTRL_BREAK_EVENT:
3879 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003880 ctrl_break_was_pressed = TRUE;
3881 /* ReadConsoleInput is blocking, send a key event to continue. */
3882 ir.EventType = KEY_EVENT;
3883 ir.Event.KeyEvent.bKeyDown = TRUE;
3884 ir.Event.KeyEvent.wRepeatCount = 1;
3885 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3886 ir.Event.KeyEvent.wVirtualScanCode = 0;
3887 ir.Event.KeyEvent.dwControlKeyState = 0;
3888 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3889 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890 return TRUE;
3891
3892 /* fatal events: shut down gracefully */
3893 case CTRL_CLOSE_EVENT:
3894 case CTRL_LOGOFF_EVENT:
3895 case CTRL_SHUTDOWN_EVENT:
3896 windgoto((int)Rows - 1, 0);
3897 g_fForceExit = TRUE;
3898
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003899 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003900 (dwCtrlType == CTRL_CLOSE_EVENT
3901 ? _("close")
3902 : dwCtrlType == CTRL_LOGOFF_EVENT
3903 ? _("logoff")
3904 : _("shutdown")));
3905#ifdef DEBUG
3906 OutputDebugString(IObuff);
3907#endif
3908
3909 preserve_exit(); /* output IObuff, preserve files and exit */
3910
3911 return TRUE; /* not reached */
3912
3913 default:
3914 return FALSE;
3915 }
3916}
3917
3918
3919/*
3920 * set the tty in (raw) ? "raw" : "cooked" mode
3921 */
3922 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003923mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924{
3925 DWORD cmodein;
3926 DWORD cmodeout;
3927 BOOL bEnableHandler;
3928
3929 GetConsoleMode(g_hConIn, &cmodein);
3930 GetConsoleMode(g_hConOut, &cmodeout);
3931 if (tmode == TMODE_RAW)
3932 {
3933 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3934 ENABLE_ECHO_INPUT);
3935#ifdef FEAT_MOUSE
3936 if (g_fMouseActive)
3937 cmodein |= ENABLE_MOUSE_INPUT;
3938#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003939 cmodeout &= ~(
3940#ifdef FEAT_TERMGUICOLORS
3941 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3942 * VTP. */
3943 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3944#else
3945 ENABLE_PROCESSED_OUTPUT |
3946#endif
3947 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003948 bEnableHandler = TRUE;
3949 }
3950 else /* cooked */
3951 {
3952 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3953 ENABLE_ECHO_INPUT);
3954 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3955 bEnableHandler = FALSE;
3956 }
3957 SetConsoleMode(g_hConIn, cmodein);
3958 SetConsoleMode(g_hConOut, cmodeout);
3959 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3960
3961#ifdef MCH_WRITE_DUMP
3962 if (fdDump)
3963 {
3964 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3965 tmode == TMODE_RAW ? "raw" :
3966 tmode == TMODE_COOK ? "cooked" : "normal",
3967 cmodein, cmodeout);
3968 fflush(fdDump);
3969 }
3970#endif
3971}
3972
3973
3974/*
3975 * Get the size of the current window in `Rows' and `Columns'
3976 * Return OK when size could be determined, FAIL otherwise.
3977 */
3978 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003979mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003980{
3981 CONSOLE_SCREEN_BUFFER_INFO csbi;
3982
3983 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3984 {
3985 /*
3986 * For some reason, we are trying to get the screen dimensions
3987 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3988 * variables are really intended to mean the size of Vim screen
3989 * while in termcap mode.
3990 */
3991 Rows = g_cbTermcap.Info.dwSize.Y;
3992 Columns = g_cbTermcap.Info.dwSize.X;
3993 }
3994 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3995 {
3996 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3997 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3998 }
3999 else
4000 {
4001 Rows = 25;
4002 Columns = 80;
4003 }
4004 return OK;
4005}
4006
4007/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004008 * Resize console buffer to 'COORD'
4009 */
4010 static void
4011ResizeConBuf(
4012 HANDLE hConsole,
4013 COORD coordScreen)
4014{
4015 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4016 {
4017#ifdef MCH_WRITE_DUMP
4018 if (fdDump)
4019 {
4020 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4021 GetLastError());
4022 fflush(fdDump);
4023 }
4024#endif
4025 }
4026}
4027
4028/*
4029 * Resize console window size to 'srWindowRect'
4030 */
4031 static void
4032ResizeWindow(
4033 HANDLE hConsole,
4034 SMALL_RECT srWindowRect)
4035{
4036 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4037 {
4038#ifdef MCH_WRITE_DUMP
4039 if (fdDump)
4040 {
4041 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4042 GetLastError());
4043 fflush(fdDump);
4044 }
4045#endif
4046 }
4047}
4048
4049/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004050 * Set a console window to `xSize' * `ySize'
4051 */
4052 static void
4053ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004054 HANDLE hConsole,
4055 int xSize,
4056 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057{
4058 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4059 SMALL_RECT srWindowRect; /* hold the new console size */
4060 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004061 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062
4063#ifdef MCH_WRITE_DUMP
4064 if (fdDump)
4065 {
4066 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4067 fflush(fdDump);
4068 }
4069#endif
4070
4071 /* get the largest size we can size the console window to */
4072 coordScreen = GetLargestConsoleWindowSize(hConsole);
4073
4074 /* define the new console window size and scroll position */
4075 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4076 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4077 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4078
4079 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4080 {
4081 int sx, sy;
4082
4083 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4084 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4085 if (sy < ySize || sx < xSize)
4086 {
4087 /*
4088 * Increasing number of lines/columns, do buffer first.
4089 * Use the maximal size in x and y direction.
4090 */
4091 if (sy < ySize)
4092 coordScreen.Y = ySize;
4093 else
4094 coordScreen.Y = sy;
4095 if (sx < xSize)
4096 coordScreen.X = xSize;
4097 else
4098 coordScreen.X = sx;
4099 SetConsoleScreenBufferSize(hConsole, coordScreen);
4100 }
4101 }
4102
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004103 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104 coordScreen.X = xSize;
4105 coordScreen.Y = ySize;
4106
Bram Moolenaar2551c032018-08-23 22:38:31 +02004107 // In the new console call API, only the first time in reverse order
4108 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004109 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004110 ResizeWindow(hConsole, srWindowRect);
4111 ResizeConBuf(hConsole, coordScreen);
4112 }
4113 else
4114 {
4115 ResizeConBuf(hConsole, coordScreen);
4116 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004117 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004118 }
4119}
4120
4121
4122/*
4123 * Set the console window to `Rows' * `Columns'
4124 */
4125 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004126mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127{
4128 COORD coordScreen;
4129
4130 /* Don't change window size while still starting up */
4131 if (suppress_winsize != 0)
4132 {
4133 suppress_winsize = 2;
4134 return;
4135 }
4136
4137 if (term_console)
4138 {
4139 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4140
4141 /* Clamp Rows and Columns to reasonable values */
4142 if (Rows > coordScreen.Y)
4143 Rows = coordScreen.Y;
4144 if (Columns > coordScreen.X)
4145 Columns = coordScreen.X;
4146
4147 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4148 }
4149}
4150
4151/*
4152 * Rows and/or Columns has changed.
4153 */
4154 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004155mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004156{
4157 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4158}
4159
4160
4161/*
4162 * Called when started up, to set the winsize that was delayed.
4163 */
4164 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004165mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004166{
4167 if (suppress_winsize == 2)
4168 {
4169 suppress_winsize = 0;
4170 mch_set_shellsize();
4171 shell_resized();
4172 }
4173 suppress_winsize = 0;
4174}
4175#endif /* FEAT_GUI_W32 */
4176
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004177 static BOOL
4178vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004179 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004180 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004181 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004182 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004183 PROCESS_INFORMATION *pi,
4184 LPVOID *env,
4185 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004186{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004187#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004188 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4189 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004190 BOOL ret;
4191 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004192
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004193 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4194 if (wcmd == NULL)
4195 goto fallback;
4196 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004197 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004198 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4199 if (wcwd == NULL)
4200 {
4201 vim_free(wcmd);
4202 goto fallback;
4203 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004204 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004205
4206 ret = CreateProcessW(
4207 NULL, /* Executable name */
4208 wcmd, /* Command to execute */
4209 NULL, /* Process security attributes */
4210 NULL, /* Thread security attributes */
4211 inherit_handles, /* Inherit handles */
4212 flags, /* Creation flags */
4213 env, /* Environment */
4214 wcwd, /* Current directory */
4215 (LPSTARTUPINFOW)si, /* Startup information */
4216 pi); /* Process information */
4217 vim_free(wcmd);
4218 if (wcwd != NULL)
4219 vim_free(wcwd);
4220 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004221 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004222fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004223#endif
4224 return CreateProcess(
4225 NULL, /* Executable name */
4226 cmd, /* Command to execute */
4227 NULL, /* Process security attributes */
4228 NULL, /* Thread security attributes */
4229 inherit_handles, /* Inherit handles */
4230 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004231 env, /* Environment */
4232 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004233 si, /* Startup information */
4234 pi); /* Process information */
4235}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004236
4237
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004238 static HINSTANCE
4239vim_shell_execute(
4240 char *cmd,
4241 INT n_show_cmd)
4242{
4243#ifdef FEAT_MBYTE
4244 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4245 {
4246 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4247 if (wcmd != NULL)
4248 {
4249 HINSTANCE ret;
4250 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4251 vim_free(wcmd);
4252 return ret;
4253 }
4254 }
4255#endif
4256 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4257}
4258
4259
Bram Moolenaar071d4272004-06-13 20:20:40 +00004260#if defined(FEAT_GUI_W32) || defined(PROTO)
4261
4262/*
4263 * Specialised version of system() for Win32 GUI mode.
4264 * This version proceeds as follows:
4265 * 1. Create a console window for use by the subprocess
4266 * 2. Run the subprocess (it gets the allocated console by default)
4267 * 3. Wait for the subprocess to terminate and get its exit code
4268 * 4. Prompt the user to press a key to close the console window
4269 */
4270 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004271mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272{
4273 STARTUPINFO si;
4274 PROCESS_INFORMATION pi;
4275 DWORD ret = 0;
4276 HWND hwnd = GetFocus();
4277
4278 si.cb = sizeof(si);
4279 si.lpReserved = NULL;
4280 si.lpDesktop = NULL;
4281 si.lpTitle = NULL;
4282 si.dwFlags = STARTF_USESHOWWINDOW;
4283 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004284 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004285 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004286 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004287 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004288 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004289 else
4290 si.wShowWindow = SW_SHOWNORMAL;
4291 si.cbReserved2 = 0;
4292 si.lpReserved2 = NULL;
4293
Bram Moolenaar071d4272004-06-13 20:20:40 +00004294 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004295 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004296 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4297 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298
4299 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 {
4301#ifdef FEAT_GUI
4302 int delay = 1;
4303
4304 /* Keep updating the window while waiting for the shell to finish. */
4305 for (;;)
4306 {
4307 MSG msg;
4308
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004309 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004310 {
4311 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004312 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004313 delay = 1;
4314 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004315 }
4316 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4317 break;
4318
4319 /* We start waiting for a very short time and then increase it, so
4320 * that we respond quickly when the process is quick, and don't
4321 * consume too much overhead when it's slow. */
4322 if (delay < 50)
4323 delay += 10;
4324 }
4325#else
4326 WaitForSingleObject(pi.hProcess, INFINITE);
4327#endif
4328
4329 /* Get the command exit code */
4330 GetExitCodeProcess(pi.hProcess, &ret);
4331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004332
4333 /* Close the handles to the subprocess, so that it goes away */
4334 CloseHandle(pi.hThread);
4335 CloseHandle(pi.hProcess);
4336
4337 /* Try to get input focus back. Doesn't always work though. */
4338 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4339
4340 return ret;
4341}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004342
4343/*
4344 * Thread launched by the gui to send the current buffer data to the
4345 * process. This way avoid to hang up vim totally if the children
4346 * process take a long time to process the lines.
4347 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004348 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004349sub_process_writer(LPVOID param)
4350{
4351 HANDLE g_hChildStd_IN_Wr = param;
4352 linenr_T lnum = curbuf->b_op_start.lnum;
4353 DWORD len = 0;
4354 DWORD l;
4355 char_u *lp = ml_get(lnum);
4356 char_u *s;
4357 int written = 0;
4358
4359 for (;;)
4360 {
4361 l = (DWORD)STRLEN(lp + written);
4362 if (l == 0)
4363 len = 0;
4364 else if (lp[written] == NL)
4365 {
4366 /* NL -> NUL translation */
4367 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4368 }
4369 else
4370 {
4371 s = vim_strchr(lp + written, NL);
4372 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4373 s == NULL ? l : (DWORD)(s - (lp + written)),
4374 &len, NULL);
4375 }
4376 if (len == (int)l)
4377 {
4378 /* Finished a line, add a NL, unless this line should not have
4379 * one. */
4380 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004381 || (!curbuf->b_p_bin
4382 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004383 || (lnum != curbuf->b_no_eol_lnum
4384 && (lnum != curbuf->b_ml.ml_line_count
4385 || curbuf->b_p_eol)))
4386 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004387 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004388 }
4389
4390 ++lnum;
4391 if (lnum > curbuf->b_op_end.lnum)
4392 break;
4393
4394 lp = ml_get(lnum);
4395 written = 0;
4396 }
4397 else if (len > 0)
4398 written += len;
4399 }
4400
4401 /* finished all the lines, close pipe */
4402 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004403 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004404}
4405
4406
4407# define BUFLEN 100 /* length for buffer, stolen from unix version */
4408
4409/*
4410 * This function read from the children's stdout and write the
4411 * data on screen or in the buffer accordingly.
4412 */
4413 static void
4414dump_pipe(int options,
4415 HANDLE g_hChildStd_OUT_Rd,
4416 garray_T *ga,
4417 char_u buffer[],
4418 DWORD *buffer_off)
4419{
4420 DWORD availableBytes = 0;
4421 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004422 int ret;
4423 DWORD len;
4424 DWORD toRead;
4425 int repeatCount;
4426
4427 /* we query the pipe to see if there is any data to read
4428 * to avoid to perform a blocking read */
4429 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4430 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004431 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004432 NULL, /* number of read bytes */
4433 &availableBytes, /* available bytes total */
4434 NULL); /* byteLeft */
4435
4436 repeatCount = 0;
4437 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004438 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004439 {
4440 repeatCount++;
4441 toRead =
4442# ifdef FEAT_MBYTE
4443 (DWORD)(BUFLEN - *buffer_off);
4444# else
4445 (DWORD)BUFLEN;
4446# endif
4447 toRead = availableBytes < toRead ? availableBytes : toRead;
4448 ReadFile(g_hChildStd_OUT_Rd, buffer
4449# ifdef FEAT_MBYTE
4450 + *buffer_off, toRead
4451# else
4452 , toRead
4453# endif
4454 , &len, NULL);
4455
4456 /* If we haven't read anything, there is a problem */
4457 if (len == 0)
4458 break;
4459
4460 availableBytes -= len;
4461
4462 if (options & SHELL_READ)
4463 {
4464 /* Do NUL -> NL translation, append NL separated
4465 * lines to the current buffer. */
4466 for (i = 0; i < len; ++i)
4467 {
4468 if (buffer[i] == NL)
4469 append_ga_line(ga);
4470 else if (buffer[i] == NUL)
4471 ga_append(ga, NL);
4472 else
4473 ga_append(ga, buffer[i]);
4474 }
4475 }
4476# ifdef FEAT_MBYTE
4477 else if (has_mbyte)
4478 {
4479 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004480 int c;
4481 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004482
4483 len += *buffer_off;
4484 buffer[len] = NUL;
4485
4486 /* Check if the last character in buffer[] is
4487 * incomplete, keep these bytes for the next
4488 * round. */
4489 for (p = buffer; p < buffer + len; p += l)
4490 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004491 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004492 if (l == 0)
4493 l = 1; /* NUL byte? */
4494 else if (MB_BYTE2LEN(*p) != l)
4495 break;
4496 }
4497 if (p == buffer) /* no complete character */
4498 {
4499 /* avoid getting stuck at an illegal byte */
4500 if (len >= 12)
4501 ++p;
4502 else
4503 {
4504 *buffer_off = len;
4505 return;
4506 }
4507 }
4508 c = *p;
4509 *p = NUL;
4510 msg_puts(buffer);
4511 if (p < buffer + len)
4512 {
4513 *p = c;
4514 *buffer_off = (DWORD)((buffer + len) - p);
4515 mch_memmove(buffer, p, *buffer_off);
4516 return;
4517 }
4518 *buffer_off = 0;
4519 }
4520# endif /* FEAT_MBYTE */
4521 else
4522 {
4523 buffer[len] = NUL;
4524 msg_puts(buffer);
4525 }
4526
4527 windgoto(msg_row, msg_col);
4528 cursor_on();
4529 out_flush();
4530 }
4531}
4532
4533/*
4534 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4535 * for communication and doesn't open any new window.
4536 */
4537 static int
4538mch_system_piped(char *cmd, int options)
4539{
4540 STARTUPINFO si;
4541 PROCESS_INFORMATION pi;
4542 DWORD ret = 0;
4543
4544 HANDLE g_hChildStd_IN_Rd = NULL;
4545 HANDLE g_hChildStd_IN_Wr = NULL;
4546 HANDLE g_hChildStd_OUT_Rd = NULL;
4547 HANDLE g_hChildStd_OUT_Wr = NULL;
4548
4549 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4550 DWORD len;
4551
4552 /* buffer used to receive keys */
4553 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4554 int ta_len = 0; /* valid bytes in ta_buf[] */
4555
4556 DWORD i;
4557 int c;
4558 int noread_cnt = 0;
4559 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004560 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004561 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004562 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004563
4564 SECURITY_ATTRIBUTES saAttr;
4565
4566 /* Set the bInheritHandle flag so pipe handles are inherited. */
4567 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4568 saAttr.bInheritHandle = TRUE;
4569 saAttr.lpSecurityDescriptor = NULL;
4570
4571 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4572 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004573 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004574 /* Create a pipe for the child process's STDIN. */
4575 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4576 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004577 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004578 {
4579 CloseHandle(g_hChildStd_IN_Rd);
4580 CloseHandle(g_hChildStd_IN_Wr);
4581 CloseHandle(g_hChildStd_OUT_Rd);
4582 CloseHandle(g_hChildStd_OUT_Wr);
4583 MSG_PUTS(_("\nCannot create pipes\n"));
4584 }
4585
4586 si.cb = sizeof(si);
4587 si.lpReserved = NULL;
4588 si.lpDesktop = NULL;
4589 si.lpTitle = NULL;
4590 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4591
4592 /* set-up our file redirection */
4593 si.hStdError = g_hChildStd_OUT_Wr;
4594 si.hStdOutput = g_hChildStd_OUT_Wr;
4595 si.hStdInput = g_hChildStd_IN_Rd;
4596 si.wShowWindow = SW_HIDE;
4597 si.cbReserved2 = 0;
4598 si.lpReserved2 = NULL;
4599
4600 if (options & SHELL_READ)
4601 ga_init2(&ga, 1, BUFLEN);
4602
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004603 if (cmd != NULL)
4604 {
4605 p = (char *)vim_strsave((char_u *)cmd);
4606 if (p != NULL)
4607 unescape_shellxquote((char_u *)p, p_sxe);
4608 else
4609 p = cmd;
4610 }
4611
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004612 /* Now, run the command.
4613 * About "Inherit handles" being TRUE: this command can be litigious,
4614 * handle inheritance was deactivated for pending temp file, but, if we
4615 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004616 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4617 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004618
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004619 if (p != cmd)
4620 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004621
4622 /* Close our unused side of the pipes */
4623 CloseHandle(g_hChildStd_IN_Rd);
4624 CloseHandle(g_hChildStd_OUT_Wr);
4625
4626 if (options & SHELL_WRITE)
4627 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004628 HANDLE thread = (HANDLE)
4629 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004630 0, /* default stack size */
4631 sub_process_writer, /* function to be executed */
4632 g_hChildStd_IN_Wr, /* parameter */
4633 0, /* creation flag, start immediately */
4634 NULL); /* we don't care about thread id */
4635 CloseHandle(thread);
4636 g_hChildStd_IN_Wr = NULL;
4637 }
4638
4639 /* Keep updating the window while waiting for the shell to finish. */
4640 for (;;)
4641 {
4642 MSG msg;
4643
Bram Moolenaar175d0702013-12-11 18:36:33 +01004644 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004645 {
4646 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004647 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004648 }
4649
4650 /* write pipe information in the window */
4651 if ((options & (SHELL_READ|SHELL_WRITE))
4652# ifdef FEAT_GUI
4653 || gui.in_use
4654# endif
4655 )
4656 {
4657 len = 0;
4658 if (!(options & SHELL_EXPAND)
4659 && ((options &
4660 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4661 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4662# ifdef FEAT_GUI
4663 || gui.in_use
4664# endif
4665 )
4666 && (ta_len > 0 || noread_cnt > 4))
4667 {
4668 if (ta_len == 0)
4669 {
4670 /* Get extra characters when we don't have any. Reset the
4671 * counter and timer. */
4672 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004673 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4674 }
4675 if (ta_len > 0 || len > 0)
4676 {
4677 /*
4678 * For pipes: Check for CTRL-C: send interrupt signal to
4679 * child. Check for CTRL-D: EOF, close pipe to child.
4680 */
4681 if (len == 1 && cmd != NULL)
4682 {
4683 if (ta_buf[ta_len] == Ctrl_C)
4684 {
4685 /* Learn what exit code is expected, for
4686 * now put 9 as SIGKILL */
4687 TerminateProcess(pi.hProcess, 9);
4688 }
4689 if (ta_buf[ta_len] == Ctrl_D)
4690 {
4691 CloseHandle(g_hChildStd_IN_Wr);
4692 g_hChildStd_IN_Wr = NULL;
4693 }
4694 }
4695
4696 /* replace K_BS by <BS> and K_DEL by <DEL> */
4697 for (i = ta_len; i < ta_len + len; ++i)
4698 {
4699 if (ta_buf[i] == CSI && len - i > 2)
4700 {
4701 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4702 if (c == K_DEL || c == K_KDEL || c == K_BS)
4703 {
4704 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4705 (size_t)(len - i - 2));
4706 if (c == K_DEL || c == K_KDEL)
4707 ta_buf[i] = DEL;
4708 else
4709 ta_buf[i] = Ctrl_H;
4710 len -= 2;
4711 }
4712 }
4713 else if (ta_buf[i] == '\r')
4714 ta_buf[i] = '\n';
4715# ifdef FEAT_MBYTE
4716 if (has_mbyte)
4717 i += (*mb_ptr2len_len)(ta_buf + i,
4718 ta_len + len - i) - 1;
4719# endif
4720 }
4721
4722 /*
4723 * For pipes: echo the typed characters. For a pty this
4724 * does not seem to work.
4725 */
4726 for (i = ta_len; i < ta_len + len; ++i)
4727 {
4728 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4729 msg_putchar(ta_buf[i]);
4730# ifdef FEAT_MBYTE
4731 else if (has_mbyte)
4732 {
4733 int l = (*mb_ptr2len)(ta_buf + i);
4734
4735 msg_outtrans_len(ta_buf + i, l);
4736 i += l - 1;
4737 }
4738# endif
4739 else
4740 msg_outtrans_len(ta_buf + i, 1);
4741 }
4742 windgoto(msg_row, msg_col);
4743 out_flush();
4744
4745 ta_len += len;
4746
4747 /*
4748 * Write the characters to the child, unless EOF has been
4749 * typed for pipes. Write one character at a time, to
4750 * avoid losing too much typeahead. When writing buffer
4751 * lines, drop the typed characters (only check for
4752 * CTRL-C).
4753 */
4754 if (options & SHELL_WRITE)
4755 ta_len = 0;
4756 else if (g_hChildStd_IN_Wr != NULL)
4757 {
4758 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4759 1, &len, NULL);
4760 // if we are typing in, we want to keep things reactive
4761 delay = 1;
4762 if (len > 0)
4763 {
4764 ta_len -= len;
4765 mch_memmove(ta_buf, ta_buf + len, ta_len);
4766 }
4767 }
4768 }
4769 }
4770 }
4771
4772 if (ta_len)
4773 ui_inchar_undo(ta_buf, ta_len);
4774
4775 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4776 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004777 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004778 break;
4779 }
4780
4781 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004782 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004783
4784 /* We start waiting for a very short time and then increase it, so
4785 * that we respond quickly when the process is quick, and don't
4786 * consume too much overhead when it's slow. */
4787 if (delay < 50)
4788 delay += 10;
4789 }
4790
4791 /* Close the pipe */
4792 CloseHandle(g_hChildStd_OUT_Rd);
4793 if (g_hChildStd_IN_Wr != NULL)
4794 CloseHandle(g_hChildStd_IN_Wr);
4795
4796 WaitForSingleObject(pi.hProcess, INFINITE);
4797
4798 /* Get the command exit code */
4799 GetExitCodeProcess(pi.hProcess, &ret);
4800
4801 if (options & SHELL_READ)
4802 {
4803 if (ga.ga_len > 0)
4804 {
4805 append_ga_line(&ga);
4806 /* remember that the NL was missing */
4807 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4808 }
4809 else
4810 curbuf->b_no_eol_lnum = 0;
4811 ga_clear(&ga);
4812 }
4813
4814 /* Close the handles to the subprocess, so that it goes away */
4815 CloseHandle(pi.hThread);
4816 CloseHandle(pi.hProcess);
4817
4818 return ret;
4819}
4820
4821 static int
4822mch_system(char *cmd, int options)
4823{
4824 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004825 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004826 return mch_system_piped(cmd, options);
4827 else
4828 return mch_system_classic(cmd, options);
4829}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004830#else
4831
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004832# ifdef FEAT_MBYTE
4833 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004834mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004835{
4836 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4837 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004838 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004839 if (wcmd != NULL)
4840 {
4841 int ret = _wsystem(wcmd);
4842 vim_free(wcmd);
4843 return ret;
4844 }
4845 }
4846 return system(cmd);
4847}
4848# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004849# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004850# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004851
4852#endif
4853
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004854#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4855/*
4856 * Use a terminal window to run a shell command in.
4857 */
4858 static int
4859mch_call_shell_terminal(
4860 char_u *cmd,
4861 int options UNUSED) /* SHELL_*, see vim.h */
4862{
4863 jobopt_T opt;
4864 char_u *newcmd = NULL;
4865 typval_T argvar[2];
4866 long_u cmdlen;
4867 int retval = -1;
4868 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004869 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004870 aco_save_T aco;
4871 oparg_T oa; /* operator arguments */
4872
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004873 if (cmd == NULL)
4874 cmdlen = STRLEN(p_sh) + 1;
4875 else
4876 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004877 newcmd = lalloc(cmdlen, TRUE);
4878 if (newcmd == NULL)
4879 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004880 if (cmd == NULL)
4881 {
4882 STRCPY(newcmd, p_sh);
4883 ch_log(NULL, "starting terminal to run a shell");
4884 }
4885 else
4886 {
4887 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4888 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4889 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004890
4891 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004892
4893 argvar[0].v_type = VAR_STRING;
4894 argvar[0].vval.v_string = newcmd;
4895 argvar[1].v_type = VAR_UNKNOWN;
4896 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004897 if (buf == NULL)
4898 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004899
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004900 job = term_getjob(buf->b_term);
4901 ++job->jv_refcount;
4902
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004903 /* Find a window to make "buf" curbuf. */
4904 aucmd_prepbuf(&aco, buf);
4905
4906 clear_oparg(&oa);
4907 while (term_use_loop())
4908 {
4909 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4910 {
4911 /* If terminal_loop() returns OK we got a key that is handled
4912 * in Normal model. We don't do redrawing anyway. */
4913 if (terminal_loop(TRUE) == OK)
4914 normal_cmd(&oa, TRUE);
4915 }
4916 else
4917 normal_cmd(&oa, TRUE);
4918 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004919 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004920 ch_log(NULL, "system command finished");
4921
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004922 job_unref(job);
4923
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004924 /* restore curwin/curbuf and a few other things */
4925 aucmd_restbuf(&aco);
4926
4927 wait_return(TRUE);
4928 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4929
4930 vim_free(newcmd);
4931 return retval;
4932}
4933#endif
4934
Bram Moolenaar071d4272004-06-13 20:20:40 +00004935/*
4936 * Either execute a command by calling the shell or start a new shell
4937 */
4938 int
4939mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004940 char_u *cmd,
4941 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004942{
4943 int x = 0;
4944 int tmode = cur_tmode;
4945#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004946 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004947# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004948 int did_set_title = FALSE;
4949
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004950 /* Change the title to reflect that we are in a subshell. */
4951 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4952 {
4953 WCHAR szShellTitle[512];
4954
4955 if (GetConsoleTitleW(szShellTitle,
4956 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4957 {
4958 if (cmd == NULL)
4959 wcscat(szShellTitle, L" :sh");
4960 else
4961 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004962 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004963
4964 if (wn != NULL)
4965 {
4966 wcscat(szShellTitle, L" - !");
4967 if ((wcslen(szShellTitle) + wcslen(wn) <
4968 sizeof(szShellTitle)/sizeof(WCHAR)))
4969 wcscat(szShellTitle, wn);
4970 SetConsoleTitleW(szShellTitle);
4971 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004972 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004973 }
4974 }
4975 }
4976 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004977 if (!did_set_title)
4978# endif
4979 /* Change the title to reflect that we are in a subshell. */
4980 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004981 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004982 if (cmd == NULL)
4983 strcat(szShellTitle, " :sh");
4984 else
4985 {
4986 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004987 if ((strlen(szShellTitle) + strlen((char *)cmd)
4988 < sizeof(szShellTitle)))
4989 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004990 }
4991 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004992 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993#endif
4994
4995 out_flush();
4996
4997#ifdef MCH_WRITE_DUMP
4998 if (fdDump)
4999 {
5000 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5001 fflush(fdDump);
5002 }
5003#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005004#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5005 /* TODO: make the terminal window work with input or output redirected. */
5006 if (vim_strchr(p_go, GO_TERMINAL) != NULL
5007 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5008 {
5009 /* Use a terminal window to run the command in. */
5010 x = mch_call_shell_terminal(cmd, options);
5011#ifdef FEAT_TITLE
5012 resettitle();
5013#endif
5014 return x;
5015 }
5016#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005017
5018 /*
5019 * Catch all deadly signals while running the external command, because a
5020 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5021 */
5022 signal(SIGINT, SIG_IGN);
5023#if defined(__GNUC__) && !defined(__MINGW32__)
5024 signal(SIGKILL, SIG_IGN);
5025#else
5026 signal(SIGBREAK, SIG_IGN);
5027#endif
5028 signal(SIGILL, SIG_IGN);
5029 signal(SIGFPE, SIG_IGN);
5030 signal(SIGSEGV, SIG_IGN);
5031 signal(SIGTERM, SIG_IGN);
5032 signal(SIGABRT, SIG_IGN);
5033
5034 if (options & SHELL_COOKED)
5035 settmode(TMODE_COOK); /* set to normal mode */
5036
5037 if (cmd == NULL)
5038 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005039 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 }
5041 else
5042 {
5043 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005044 char_u *newcmd = NULL;
5045 char_u *cmdbase = cmd;
5046 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005047
5048 /* Skip a leading ", ( and "(. */
5049 if (*cmdbase == '"' )
5050 ++cmdbase;
5051 if (*cmdbase == '(')
5052 ++cmdbase;
5053
Bram Moolenaar1c465442017-03-12 20:10:05 +01005054 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005055 {
5056 STARTUPINFO si;
5057 PROCESS_INFORMATION pi;
5058 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005059 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005060 char_u *p;
5061
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005062 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005063 si.cb = sizeof(si);
5064 si.lpReserved = NULL;
5065 si.lpDesktop = NULL;
5066 si.lpTitle = NULL;
5067 si.dwFlags = 0;
5068 si.cbReserved2 = 0;
5069 si.lpReserved2 = NULL;
5070
5071 cmdbase = skipwhite(cmdbase + 5);
5072 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005073 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005074 {
5075 cmdbase = skipwhite(cmdbase + 4);
5076 si.dwFlags = STARTF_USESHOWWINDOW;
5077 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005078 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005079 }
5080 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005081 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005082 {
5083 cmdbase = skipwhite(cmdbase + 2);
5084 flags = CREATE_NO_WINDOW;
5085 si.dwFlags = STARTF_USESTDHANDLES;
5086 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005087 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005088 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005089 NULL, // Security att.
5090 OPEN_EXISTING, // Open flags
5091 FILE_ATTRIBUTE_NORMAL, // File att.
5092 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005093 si.hStdOutput = si.hStdInput;
5094 si.hStdError = si.hStdInput;
5095 }
5096
5097 /* Remove a trailing ", ) and )" if they have a match
5098 * at the start of the command. */
5099 if (cmdbase > cmd)
5100 {
5101 p = cmdbase + STRLEN(cmdbase);
5102 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5103 *--p = NUL;
5104 if (p > cmdbase && p[-1] == ')'
5105 && (*cmd =='(' || cmd[1] == '('))
5106 *--p = NUL;
5107 }
5108
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005109 newcmd = cmdbase;
5110 unescape_shellxquote(cmdbase, p_sxe);
5111
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005112 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005113 * If creating new console, arguments are passed to the
5114 * 'cmd.exe' as-is. If it's not, arguments are not treated
5115 * correctly for current 'cmd.exe'. So unescape characters in
5116 * shellxescape except '|' for avoiding to be treated as
5117 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005118 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005119 if (flags != CREATE_NEW_CONSOLE)
5120 {
5121 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005122 char_u *cmd_shell = mch_getenv("COMSPEC");
5123
5124 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005125 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005126
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005127 subcmd = vim_strsave_escaped_ext(cmdbase,
5128 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005129 if (subcmd != NULL)
5130 {
5131 /* make "cmd.exe /c arguments" */
5132 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005133 newcmd = lalloc(cmdlen, TRUE);
5134 if (newcmd != NULL)
5135 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005136 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005137 else
5138 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005139 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005140 }
5141 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005142
5143 /*
5144 * Now, start the command as a process, so that it doesn't
5145 * inherit our handles which causes unpleasant dangling swap
5146 * files if we exit before the spawned process
5147 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005148 if (vim_create_process((char *)newcmd, FALSE, flags,
5149 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005150 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005151 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5152 > (HINSTANCE)32)
5153 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005154 else
5155 {
5156 x = -1;
5157#ifdef FEAT_GUI_W32
5158 EMSG(_("E371: Command not found"));
5159#endif
5160 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005161
5162 if (newcmd != cmdbase)
5163 vim_free(newcmd);
5164
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005165 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005166 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005167 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005168 CloseHandle(si.hStdInput);
5169 }
5170 /* Close the handles to the subprocess, so that it goes away */
5171 CloseHandle(pi.hThread);
5172 CloseHandle(pi.hProcess);
5173 }
5174 else
5175 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005176 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005177#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005178 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005179#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005180 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5181
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005182 newcmd = lalloc(cmdlen, TRUE);
5183 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184 {
5185#if defined(FEAT_GUI_W32)
5186 if (need_vimrun_warning)
5187 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005188 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5189 "External commands will not pause after completion.\n"
5190 "See :help win32-vimrun for more information.");
5191 char *title = _("Vim Warning");
5192# ifdef FEAT_MBYTE
5193 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5194 {
5195 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5196 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5197
5198 if (wmsg != NULL && wtitle != NULL)
5199 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5200 vim_free(wmsg);
5201 vim_free(wtitle);
5202 }
5203 else
5204# endif
5205 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206 need_vimrun_warning = FALSE;
5207 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005208 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 /* Use vimrun to execute the command. It opens a console
5210 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005211 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005212 vimrun_path,
5213 (msg_silent != 0 || (options & SHELL_DOOUT))
5214 ? "-s " : "",
5215 p_sh, p_shcf, cmd);
5216 else
5217#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005218 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005219 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005220 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005221 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005223 }
5224 }
5225
5226 if (tmode == TMODE_RAW)
5227 settmode(TMODE_RAW); /* set to raw mode */
5228
5229 /* Print the return value, unless "vimrun" was used. */
5230 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5231#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005232 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233#endif
5234 )
5235 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005236 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237 msg_putchar('\n');
5238 }
5239#ifdef FEAT_TITLE
5240 resettitle();
5241#endif
5242
5243 signal(SIGINT, SIG_DFL);
5244#if defined(__GNUC__) && !defined(__MINGW32__)
5245 signal(SIGKILL, SIG_DFL);
5246#else
5247 signal(SIGBREAK, SIG_DFL);
5248#endif
5249 signal(SIGILL, SIG_DFL);
5250 signal(SIGFPE, SIG_DFL);
5251 signal(SIGSEGV, SIG_DFL);
5252 signal(SIGTERM, SIG_DFL);
5253 signal(SIGABRT, SIG_DFL);
5254
5255 return x;
5256}
5257
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005258#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005259 static HANDLE
5260job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005261 char_u *fname,
5262 DWORD dwDesiredAccess,
5263 DWORD dwShareMode,
5264 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5265 DWORD dwCreationDisposition,
5266 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005267{
5268 HANDLE h;
5269# ifdef FEAT_MBYTE
5270 WCHAR *wn = NULL;
5271 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5272 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005273 wn = enc_to_utf16(fname, NULL);
5274 if (wn != NULL)
5275 {
5276 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5277 lpSecurityAttributes, dwCreationDisposition,
5278 dwFlagsAndAttributes, NULL);
5279 vim_free(wn);
5280 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005281 }
5282 if (wn == NULL)
5283# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005284 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5285 lpSecurityAttributes, dwCreationDisposition,
5286 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005287 return h;
5288}
5289
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005290/*
5291 * Turn the dictionary "env" into a NUL separated list that can be used as the
5292 * environment argument of vim_create_process().
5293 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005294 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005295win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005296{
5297 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005298 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005299 LPVOID base = GetEnvironmentStringsW();
5300
5301 /* for last \0 */
5302 if (ga_grow(gap, 1) == FAIL)
5303 return;
5304
5305 if (base)
5306 {
5307 WCHAR *p = (WCHAR*) base;
5308
5309 /* for last \0 */
5310 if (ga_grow(gap, 1) == FAIL)
5311 return;
5312
5313 while (*p != 0 || *(p + 1) != 0)
5314 {
5315 if (ga_grow(gap, 1) == OK)
5316 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5317 p++;
5318 }
5319 FreeEnvironmentStrings(base);
5320 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5321 }
5322
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005323 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005324 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005325 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005326 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005327 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005328 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005329 typval_T *item = &dict_lookup(hi)->di_tv;
5330 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5331 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5332 --todo;
5333 if (wkey != NULL && wval != NULL)
5334 {
5335 size_t n;
5336 size_t lkey = wcslen(wkey);
5337 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005338
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005339 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5340 continue;
5341 for (n = 0; n < lkey; n++)
5342 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5343 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5344 for (n = 0; n < lval; n++)
5345 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5346 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5347 }
5348 if (wkey != NULL) vim_free(wkey);
5349 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005350 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005351 }
5352 }
5353
Bram Moolenaar493359e2018-06-12 20:25:52 +02005354# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005355 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005356# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005357 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005358 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005359# endif
5360# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005361 char_u *version = get_vim_var_str(VV_VERSION);
5362 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005363# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005364 // size of "VIM_SERVERNAME=" and value,
5365 // plus "VIM_TERMINAL=" and value,
5366 // plus two terminating NULs
5367 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005368# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005369 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005370# endif
5371# ifdef FEAT_TERMINAL
5372 + 13 + version_len + 2
5373# endif
5374 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005375
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005376 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005377 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005378# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005379 for (n = 0; n < 15; n++)
5380 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5381 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005382 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005383 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5384 (WCHAR)servername[n];
5385 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005386# endif
5387# ifdef FEAT_TERMINAL
5388 if (is_terminal)
5389 {
5390 for (n = 0; n < 13; n++)
5391 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5392 (WCHAR)"VIM_TERMINAL="[n];
5393 for (n = 0; n < version_len; n++)
5394 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5395 (WCHAR)version[n];
5396 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5397 }
5398# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005399 }
5400 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005401# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005402}
5403
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005404 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005405mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005406{
5407 STARTUPINFO si;
5408 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005409 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005410 SECURITY_ATTRIBUTES saAttr;
5411 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005412 HANDLE ifd[2];
5413 HANDLE ofd[2];
5414 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005415 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005416
5417 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5418 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5419 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5420 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5421 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5422 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5423 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5424
5425 if (use_out_for_err && use_null_for_out)
5426 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005427
5428 ifd[0] = INVALID_HANDLE_VALUE;
5429 ifd[1] = INVALID_HANDLE_VALUE;
5430 ofd[0] = INVALID_HANDLE_VALUE;
5431 ofd[1] = INVALID_HANDLE_VALUE;
5432 efd[0] = INVALID_HANDLE_VALUE;
5433 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005434 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005435
Bram Moolenaar14207f42016-10-27 21:13:10 +02005436 jo = CreateJobObject(NULL, NULL);
5437 if (jo == NULL)
5438 {
5439 job->jv_status = JOB_FAILED;
5440 goto failed;
5441 }
5442
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005443 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005444 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005445
Bram Moolenaar76467df2016-02-12 19:30:26 +01005446 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005447 ZeroMemory(&si, sizeof(si));
5448 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005449 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005450 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005451
Bram Moolenaard8070362016-02-15 21:56:54 +01005452 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5453 saAttr.bInheritHandle = TRUE;
5454 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005455
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005456 if (use_file_for_in)
5457 {
5458 char_u *fname = options->jo_io_name[PART_IN];
5459
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005460 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5461 FILE_SHARE_READ | FILE_SHARE_WRITE,
5462 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5463 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005464 {
5465 EMSG2(_(e_notopen), fname);
5466 goto failed;
5467 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005468 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005469 else if (!use_null_for_in &&
5470 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005471 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005472 goto failed;
5473
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005474 if (use_file_for_out)
5475 {
5476 char_u *fname = options->jo_io_name[PART_OUT];
5477
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005478 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5479 FILE_SHARE_READ | FILE_SHARE_WRITE,
5480 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5481 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005482 {
5483 EMSG2(_(e_notopen), fname);
5484 goto failed;
5485 }
5486 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005487 else if (!use_null_for_out &&
5488 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005489 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005490 goto failed;
5491
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005492 if (use_file_for_err)
5493 {
5494 char_u *fname = options->jo_io_name[PART_ERR];
5495
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005496 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5497 FILE_SHARE_READ | FILE_SHARE_WRITE,
5498 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5499 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005500 {
5501 EMSG2(_(e_notopen), fname);
5502 goto failed;
5503 }
5504 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005505 else if (!use_out_for_err && !use_null_for_err &&
5506 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005507 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005508 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005509
Bram Moolenaard8070362016-02-15 21:56:54 +01005510 si.dwFlags |= STARTF_USESTDHANDLES;
5511 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005512 si.hStdOutput = ofd[1];
5513 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5514
5515 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5516 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005517 if (options->jo_set & JO_CHANNEL)
5518 {
5519 channel = options->jo_channel;
5520 if (channel != NULL)
5521 ++channel->ch_refcount;
5522 }
5523 else
5524 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005525 if (channel == NULL)
5526 goto failed;
5527 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005528
5529 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005530 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005531 CREATE_DEFAULT_ERROR_MODE |
5532 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005533 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005534 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005535 &si, &pi,
5536 ga.ga_data,
5537 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005538 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005539 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005540 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005541 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005542 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005543
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005544 ga_clear(&ga);
5545
Bram Moolenaar14207f42016-10-27 21:13:10 +02005546 if (!AssignProcessToJobObject(jo, pi.hProcess))
5547 {
5548 /* if failing, switch the way to terminate
5549 * process with TerminateProcess. */
5550 CloseHandle(jo);
5551 jo = NULL;
5552 }
5553 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005554 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005555 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005556 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005557 job->jv_status = JOB_STARTED;
5558
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005559 CloseHandle(ifd[0]);
5560 CloseHandle(ofd[1]);
5561 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005562 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005563
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005564 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005565 if (channel != NULL)
5566 {
5567 channel_set_pipes(channel,
5568 use_file_for_in || use_null_for_in
5569 ? INVALID_FD : (sock_T)ifd[1],
5570 use_file_for_out || use_null_for_out
5571 ? INVALID_FD : (sock_T)ofd[0],
5572 use_out_for_err || use_file_for_err || use_null_for_err
5573 ? INVALID_FD : (sock_T)efd[0]);
5574 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005575 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005576 return;
5577
5578failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005579 CloseHandle(ifd[0]);
5580 CloseHandle(ofd[0]);
5581 CloseHandle(efd[0]);
5582 CloseHandle(ifd[1]);
5583 CloseHandle(ofd[1]);
5584 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005585 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005586 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005587}
5588
5589 char *
5590mch_job_status(job_T *job)
5591{
5592 DWORD dwExitCode = 0;
5593
Bram Moolenaar76467df2016-02-12 19:30:26 +01005594 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5595 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005596 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005597 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005598 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005599 {
5600 ch_log(job->jv_channel, "Job ended");
5601 job->jv_status = JOB_ENDED;
5602 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005603 return "dead";
5604 }
5605 return "run";
5606}
5607
Bram Moolenaar97792de2016-10-15 18:36:49 +02005608 job_T *
5609mch_detect_ended_job(job_T *job_list)
5610{
5611 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5612 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5613 job_T *job = job_list;
5614
5615 while (job != NULL)
5616 {
5617 DWORD n;
5618 DWORD result;
5619
5620 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5621 && job != NULL; job = job->jv_next)
5622 {
5623 if (job->jv_status == JOB_STARTED)
5624 {
5625 jobHandles[n] = job->jv_proc_info.hProcess;
5626 jobArray[n] = job;
5627 ++n;
5628 }
5629 }
5630 if (n == 0)
5631 continue;
5632 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5633 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5634 {
5635 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5636
5637 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5638 return wait_job;
5639 }
5640 }
5641 return NULL;
5642}
5643
Bram Moolenaarfb630902016-10-29 14:55:00 +02005644 static BOOL
5645terminate_all(HANDLE process, int code)
5646{
5647 PROCESSENTRY32 pe;
5648 HANDLE h = INVALID_HANDLE_VALUE;
5649 DWORD pid = GetProcessId(process);
5650
5651 if (pid != 0)
5652 {
5653 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5654 if (h != INVALID_HANDLE_VALUE)
5655 {
5656 pe.dwSize = sizeof(PROCESSENTRY32);
5657 if (!Process32First(h, &pe))
5658 goto theend;
5659
5660 do
5661 {
5662 if (pe.th32ParentProcessID == pid)
5663 {
5664 HANDLE ph = OpenProcess(
5665 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5666 if (ph != NULL)
5667 {
5668 terminate_all(ph, code);
5669 CloseHandle(ph);
5670 }
5671 }
5672 } while (Process32Next(h, &pe));
5673
5674 CloseHandle(h);
5675 }
5676 }
5677
5678theend:
5679 return TerminateProcess(process, code);
5680}
5681
5682/*
5683 * Send a (deadly) signal to "job".
5684 * Return FAIL if it didn't work.
5685 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005686 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005687mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005688{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005689 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005690
Bram Moolenaar923d9262016-02-25 20:56:01 +01005691 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005692 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005693 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005694 if (job->jv_job_object != NULL)
5695 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005696 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005697 }
5698
5699 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5700 return FAIL;
5701 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005702 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5703 job->jv_proc_info.dwProcessId)
5704 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005705 FreeConsole();
5706 return ret;
5707}
5708
5709/*
5710 * Clear the data related to "job".
5711 */
5712 void
5713mch_clear_job(job_T *job)
5714{
5715 if (job->jv_status != JOB_FAILED)
5716 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005717 if (job->jv_job_object != NULL)
5718 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005719 CloseHandle(job->jv_proc_info.hProcess);
5720 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005721}
5722#endif
5723
Bram Moolenaar071d4272004-06-13 20:20:40 +00005724
5725#ifndef FEAT_GUI_W32
5726
5727/*
5728 * Start termcap mode
5729 */
5730 static void
5731termcap_mode_start(void)
5732{
5733 DWORD cmodein;
5734
5735 if (g_fTermcapMode)
5736 return;
5737
5738 SaveConsoleBuffer(&g_cbNonTermcap);
5739
5740 if (g_cbTermcap.IsValid)
5741 {
5742 /*
5743 * We've been in termcap mode before. Restore certain screen
5744 * characteristics, including the buffer size and the window
5745 * size. Since we will be redrawing the screen, we don't need
5746 * to restore the actual contents of the buffer.
5747 */
5748 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005749 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5751 Rows = g_cbTermcap.Info.dwSize.Y;
5752 Columns = g_cbTermcap.Info.dwSize.X;
5753 }
5754 else
5755 {
5756 /*
5757 * This is our first time entering termcap mode. Clear the console
5758 * screen buffer, and resize the buffer to match the current window
5759 * size. We will use this as the size of our editing environment.
5760 */
5761 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005762 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005763 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5764 }
5765
5766#ifdef FEAT_TITLE
5767 resettitle();
5768#endif
5769
5770 GetConsoleMode(g_hConIn, &cmodein);
5771#ifdef FEAT_MOUSE
5772 if (g_fMouseActive)
5773 cmodein |= ENABLE_MOUSE_INPUT;
5774 else
5775 cmodein &= ~ENABLE_MOUSE_INPUT;
5776#endif
5777 cmodein |= ENABLE_WINDOW_INPUT;
5778 SetConsoleMode(g_hConIn, cmodein);
5779
5780 redraw_later_clear();
5781 g_fTermcapMode = TRUE;
5782}
5783
5784
5785/*
5786 * End termcap mode
5787 */
5788 static void
5789termcap_mode_end(void)
5790{
5791 DWORD cmodein;
5792 ConsoleBuffer *cb;
5793 COORD coord;
5794 DWORD dwDummy;
5795
5796 if (!g_fTermcapMode)
5797 return;
5798
5799 SaveConsoleBuffer(&g_cbTermcap);
5800
5801 GetConsoleMode(g_hConIn, &cmodein);
5802 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5803 SetConsoleMode(g_hConIn, cmodein);
5804
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005805#ifdef FEAT_RESTORE_ORIG_SCREEN
5806 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5807#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005808 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005809#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005810 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005811 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005812 SetConsoleCursorInfo(g_hConOut, &g_cci);
5813
5814 if (p_rs || exiting)
5815 {
5816 /*
5817 * Clear anything that happens to be on the current line.
5818 */
5819 coord.X = 0;
5820 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5821 FillConsoleOutputCharacter(g_hConOut, ' ',
5822 cb->Info.dwSize.X, coord, &dwDummy);
5823 /*
5824 * The following is just for aesthetics. If we are exiting without
5825 * restoring the screen, then we want to have a prompt string
5826 * appear at the bottom line. However, the command interpreter
5827 * seems to always advance the cursor one line before displaying
5828 * the prompt string, which causes the screen to scroll. To
5829 * counter this, move the cursor up one line before exiting.
5830 */
5831 if (exiting && !p_rs)
5832 coord.Y--;
5833 /*
5834 * Position the cursor at the leftmost column of the desired row.
5835 */
5836 SetConsoleCursorPosition(g_hConOut, coord);
5837 }
5838
5839 g_fTermcapMode = FALSE;
5840}
5841#endif /* FEAT_GUI_W32 */
5842
5843
5844#ifdef FEAT_GUI_W32
5845 void
5846mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005847 char_u *s UNUSED,
5848 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005849{
5850 /* never used */
5851}
5852
5853#else
5854
5855/*
5856 * clear `n' chars, starting from `coord'
5857 */
5858 static void
5859clear_chars(
5860 COORD coord,
5861 DWORD n)
5862{
5863 DWORD dwDummy;
5864
5865 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005866
5867 if (!USE_VTP)
5868 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5869 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005870 {
5871 set_console_color_rgb();
5872 gotoxy(coord.X + 1, coord.Y + 1);
5873 vtp_printf("\033[%dX", n);
5874 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875}
5876
5877
5878/*
5879 * Clear the screen
5880 */
5881 static void
5882clear_screen(void)
5883{
5884 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005885
5886 if (!USE_VTP)
5887 clear_chars(g_coord, Rows * Columns);
5888 else
5889 {
5890 set_console_color_rgb();
5891 gotoxy(1, 1);
5892 vtp_printf("\033[2J");
5893 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894}
5895
5896
5897/*
5898 * Clear to end of display
5899 */
5900 static void
5901clear_to_end_of_display(void)
5902{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005903 COORD save = g_coord;
5904
5905 if (!USE_VTP)
5906 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005908 else
5909 {
5910 set_console_color_rgb();
5911 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5912 vtp_printf("\033[0J");
5913
5914 gotoxy(save.X + 1, save.Y + 1);
5915 g_coord = save;
5916 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917}
5918
5919
5920/*
5921 * Clear to end of line
5922 */
5923 static void
5924clear_to_end_of_line(void)
5925{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005926 COORD save = g_coord;
5927
5928 if (!USE_VTP)
5929 clear_chars(g_coord, Columns - g_coord.X);
5930 else
5931 {
5932 set_console_color_rgb();
5933 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5934 vtp_printf("\033[0K");
5935
5936 gotoxy(save.X + 1, save.Y + 1);
5937 g_coord = save;
5938 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939}
5940
5941
5942/*
5943 * Scroll the scroll region up by `cLines' lines
5944 */
5945 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005946scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005947{
5948 COORD oldcoord = g_coord;
5949
5950 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5951 delete_lines(cLines);
5952
5953 g_coord = oldcoord;
5954}
5955
5956
5957/*
5958 * Set the scroll region
5959 */
5960 static void
5961set_scroll_region(
5962 unsigned left,
5963 unsigned top,
5964 unsigned right,
5965 unsigned bottom)
5966{
5967 if (left >= right
5968 || top >= bottom
5969 || right > (unsigned) Columns - 1
5970 || bottom > (unsigned) Rows - 1)
5971 return;
5972
5973 g_srScrollRegion.Left = left;
5974 g_srScrollRegion.Top = top;
5975 g_srScrollRegion.Right = right;
5976 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005977
5978 if (USE_VTP)
5979 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980}
5981
5982
5983/*
5984 * Insert `cLines' lines at the current cursor position
5985 */
5986 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005987insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005988{
5989 SMALL_RECT source;
5990 COORD dest;
5991 CHAR_INFO fill;
5992
5993 dest.X = 0;
5994 dest.Y = g_coord.Y + cLines;
5995
5996 source.Left = 0;
5997 source.Top = g_coord.Y;
5998 source.Right = g_srScrollRegion.Right;
5999 source.Bottom = g_srScrollRegion.Bottom - cLines;
6000
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006001 if (!USE_VTP)
6002 {
6003 fill.Char.AsciiChar = ' ';
6004 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006005
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006006 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6007 }
6008 else
6009 {
6010 set_console_color_rgb();
6011
6012 gotoxy(1, source.Top + 1);
6013 vtp_printf("\033[%dT", cLines);
6014 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006015
6016 /* Here we have to deal with a win32 console flake: If the scroll
6017 * region looks like abc and we scroll c to a and fill with d we get
6018 * cbd... if we scroll block c one line at a time to a, we get cdd...
6019 * vim expects cdd consistently... So we have to deal with that
6020 * here... (this also occurs scrolling the same way in the other
6021 * direction). */
6022
6023 if (source.Bottom < dest.Y)
6024 {
6025 COORD coord;
6026
6027 coord.X = 0;
6028 coord.Y = source.Bottom;
6029 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6030 }
6031}
6032
6033
6034/*
6035 * Delete `cLines' lines at the current cursor position
6036 */
6037 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006038delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006039{
6040 SMALL_RECT source;
6041 COORD dest;
6042 CHAR_INFO fill;
6043 int nb;
6044
6045 dest.X = 0;
6046 dest.Y = g_coord.Y;
6047
6048 source.Left = 0;
6049 source.Top = g_coord.Y + cLines;
6050 source.Right = g_srScrollRegion.Right;
6051 source.Bottom = g_srScrollRegion.Bottom;
6052
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006053 if (!USE_VTP)
6054 {
6055 fill.Char.AsciiChar = ' ';
6056 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006057
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006058 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6059 }
6060 else
6061 {
6062 set_console_color_rgb();
6063
6064 gotoxy(1, source.Top + 1);
6065 vtp_printf("\033[%dS", cLines);
6066 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006067
6068 /* Here we have to deal with a win32 console flake: If the scroll
6069 * region looks like abc and we scroll c to a and fill with d we get
6070 * cbd... if we scroll block c one line at a time to a, we get cdd...
6071 * vim expects cdd consistently... So we have to deal with that
6072 * here... (this also occurs scrolling the same way in the other
6073 * direction). */
6074
6075 nb = dest.Y + (source.Bottom - source.Top) + 1;
6076
6077 if (nb < source.Top)
6078 {
6079 COORD coord;
6080
6081 coord.X = 0;
6082 coord.Y = nb;
6083 clear_chars(coord, Columns * (source.Top - nb));
6084 }
6085}
6086
6087
6088/*
6089 * Set the cursor position
6090 */
6091 static void
6092gotoxy(
6093 unsigned x,
6094 unsigned y)
6095{
6096 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6097 return;
6098
6099 /* external cursor coords are 1-based; internal are 0-based */
6100 g_coord.X = x - 1;
6101 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006102
6103 if (!USE_VTP)
6104 SetConsoleCursorPosition(g_hConOut, g_coord);
6105 else
6106 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006107}
6108
6109
6110/*
6111 * Set the current text attribute = (foreground | background)
6112 * See ../doc/os_win32.txt for the numbers.
6113 */
6114 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006115textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006117 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006118
6119 SetConsoleTextAttribute(g_hConOut, wAttr);
6120}
6121
6122
6123 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006124textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006126 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006127
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006128 if (!USE_VTP)
6129 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6130 else
6131 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006132}
6133
6134
6135 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006136textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006138 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006140 if (!USE_VTP)
6141 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6142 else
6143 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144}
6145
6146
6147/*
6148 * restore the default text attribute (whatever we started with)
6149 */
6150 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006151normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006153 if (!USE_VTP)
6154 textattr(g_attrDefault);
6155 else
6156 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157}
6158
6159
6160static WORD g_attrPreStandout = 0;
6161
6162/*
6163 * Make the text standout, by brightening it
6164 */
6165 static void
6166standout(void)
6167{
6168 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006169
Bram Moolenaar071d4272004-06-13 20:20:40 +00006170 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6171}
6172
6173
6174/*
6175 * Turn off standout mode
6176 */
6177 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006178standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179{
6180 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006182
6183 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184}
6185
6186
6187/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006188 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 */
6190 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006191mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006192{
6193 char_u *p;
6194 int n;
6195
6196 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6197 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006198 if (
6199#ifdef FEAT_TERMGUICOLORS
6200 !p_tgc &&
6201#endif
6202 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 {
6204 p = T_ME + 2;
6205 n = getdigits(&p);
6206 if (*p == 'm' && n > 0)
6207 {
6208 cterm_normal_fg_color = (n & 0xf) + 1;
6209 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6210 }
6211 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006212#ifdef FEAT_TERMGUICOLORS
6213 cterm_normal_fg_gui_color = INVALCOLOR;
6214 cterm_normal_bg_gui_color = INVALCOLOR;
6215#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216}
6217
6218
6219/*
6220 * visual bell: flash the screen
6221 */
6222 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006223visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006224{
6225 COORD coordOrigin = {0, 0};
6226 WORD attrFlash = ~g_attrCurrent & 0xff;
6227
6228 DWORD dwDummy;
6229 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6230
6231 if (oldattrs == NULL)
6232 return;
6233 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6234 coordOrigin, &dwDummy);
6235 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6236 coordOrigin, &dwDummy);
6237
6238 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006239 if (!USE_VTP)
6240 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 coordOrigin, &dwDummy);
6242 vim_free(oldattrs);
6243}
6244
6245
6246/*
6247 * Make the cursor visible or invisible
6248 */
6249 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006250cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251{
6252 s_cursor_visible = fVisible;
6253#ifdef MCH_CURSOR_SHAPE
6254 mch_update_cursor();
6255#endif
6256}
6257
6258
6259/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006260 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006261 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006263 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006265 char_u *pchBuf,
6266 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267{
6268 COORD coord = g_coord;
6269 DWORD written;
6270
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006271#ifdef FEAT_MBYTE
6272 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6273 {
6274 static WCHAR *unicodebuf = NULL;
6275 static int unibuflen = 0;
6276 int length;
6277 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006278
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006279 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6280 if (unicodebuf == NULL || length > unibuflen)
6281 {
6282 vim_free(unicodebuf);
6283 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6284 unibuflen = length;
6285 }
6286 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6287 unicodebuf, unibuflen);
6288
6289 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006290
6291 if (!USE_VTP)
6292 {
6293 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6294 coord, &written);
6295 /* When writing fails or didn't write a single character, pretend one
6296 * character was written, otherwise we get stuck. */
6297 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6298 coord, &cchwritten) == 0
6299 || cchwritten == 0)
6300 cchwritten = 1;
6301 }
6302 else
6303 {
6304 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6305 NULL) == 0 || cchwritten == 0)
6306 cchwritten = 1;
6307 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006308
6309 if (cchwritten == length)
6310 {
6311 written = cbToWrite;
6312 g_coord.X += (SHORT)cells;
6313 }
6314 else
6315 {
6316 char_u *p = pchBuf;
6317 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006318 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006319 written = p - pchBuf;
6320 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6321 }
6322 }
6323 else
6324#endif
6325 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006326 if (!USE_VTP)
6327 {
6328 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6329 coord, &written);
6330 /* When writing fails or didn't write a single character, pretend one
6331 * character was written, otherwise we get stuck. */
6332 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6333 coord, &written) == 0
6334 || written == 0)
6335 written = 1;
6336 }
6337 else
6338 {
6339 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6340 NULL) == 0 || written == 0)
6341 written = 1;
6342 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006343
6344 g_coord.X += (SHORT) written;
6345 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346
6347 while (g_coord.X > g_srScrollRegion.Right)
6348 {
6349 g_coord.X -= (SHORT) Columns;
6350 if (g_coord.Y < g_srScrollRegion.Bottom)
6351 g_coord.Y++;
6352 }
6353
6354 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6355
6356 return written;
6357}
6358
6359
6360/*
6361 * mch_write(): write the output buffer to the screen, translating ESC
6362 * sequences into calls to console output routines.
6363 */
6364 void
6365mch_write(
6366 char_u *s,
6367 int len)
6368{
6369 s[len] = NUL;
6370
6371 if (!term_console)
6372 {
6373 write(1, s, (unsigned)len);
6374 return;
6375 }
6376
6377 /* translate ESC | sequences into faked bios calls */
6378 while (len--)
6379 {
6380 /* optimization: use one single write_chars for runs of text,
6381 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006382 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006383
6384 if (p_wd)
6385 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006386 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387 if (prefix != 0)
6388 prefix = 1;
6389 }
6390
6391 if (prefix != 0)
6392 {
6393 DWORD nWritten;
6394
6395 nWritten = write_chars(s, prefix);
6396#ifdef MCH_WRITE_DUMP
6397 if (fdDump)
6398 {
6399 fputc('>', fdDump);
6400 fwrite(s, sizeof(char_u), nWritten, fdDump);
6401 fputs("<\n", fdDump);
6402 }
6403#endif
6404 len -= (nWritten - 1);
6405 s += nWritten;
6406 }
6407 else if (s[0] == '\n')
6408 {
6409 /* \n, newline: go to the beginning of the next line or scroll */
6410 if (g_coord.Y == g_srScrollRegion.Bottom)
6411 {
6412 scroll(1);
6413 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6414 }
6415 else
6416 {
6417 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6418 }
6419#ifdef MCH_WRITE_DUMP
6420 if (fdDump)
6421 fputs("\\n\n", fdDump);
6422#endif
6423 s++;
6424 }
6425 else if (s[0] == '\r')
6426 {
6427 /* \r, carriage return: go to beginning of line */
6428 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6429#ifdef MCH_WRITE_DUMP
6430 if (fdDump)
6431 fputs("\\r\n", fdDump);
6432#endif
6433 s++;
6434 }
6435 else if (s[0] == '\b')
6436 {
6437 /* \b, backspace: move cursor one position left */
6438 if (g_coord.X > g_srScrollRegion.Left)
6439 g_coord.X--;
6440 else if (g_coord.Y > g_srScrollRegion.Top)
6441 {
6442 g_coord.X = g_srScrollRegion.Right;
6443 g_coord.Y--;
6444 }
6445 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6446#ifdef MCH_WRITE_DUMP
6447 if (fdDump)
6448 fputs("\\b\n", fdDump);
6449#endif
6450 s++;
6451 }
6452 else if (s[0] == '\a')
6453 {
6454 /* \a, bell */
6455 MessageBeep(0xFFFFFFFF);
6456#ifdef MCH_WRITE_DUMP
6457 if (fdDump)
6458 fputs("\\a\n", fdDump);
6459#endif
6460 s++;
6461 }
6462 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6463 {
6464#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006465 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006466#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006467 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006468 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469
6470 switch (s[2])
6471 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006472 case '0': case '1': case '2': case '3': case '4':
6473 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006474 p = s + 1;
6475 do
6476 {
6477 ++p;
6478 args[argc] = getdigits(&p);
6479 argc += (argc < 15) ? 1 : 0;
6480 if (p > s + len)
6481 break;
6482 } while (*p == ';');
6483
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484 if (p > s + len)
6485 break;
6486
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006487 arg1 = args[0];
6488 arg2 = args[1];
6489 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006490 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006491 if (argc == 1 && args[0] == 0)
6492 normvideo();
6493 else if (argc == 1)
6494 {
6495 if (USE_VTP)
6496 textcolor((WORD) arg1);
6497 else
6498 textattr((WORD) arg1);
6499 }
6500 else if (USE_VTP)
6501 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006503 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006505 gotoxy(arg2, arg1);
6506 }
6507 else if (argc == 2 && *p == 'r')
6508 {
6509 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6510 }
6511 else if (argc == 1 && *p == 'A')
6512 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 gotoxy(g_coord.X + 1,
6514 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6515 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006516 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 {
6518 textbackground((WORD) arg1);
6519 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006520 else if (argc == 1 && *p == 'C')
6521 {
6522 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6523 g_coord.Y + 1);
6524 }
6525 else if (argc == 1 && *p == 'f')
6526 {
6527 textcolor((WORD) arg1);
6528 }
6529 else if (argc == 1 && *p == 'H')
6530 {
6531 gotoxy(1, arg1);
6532 }
6533 else if (argc == 1 && *p == 'L')
6534 {
6535 insert_lines(arg1);
6536 }
6537 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006538 {
6539 delete_lines(arg1);
6540 }
6541
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006542 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 s = p + 1;
6544 break;
6545
Bram Moolenaar071d4272004-06-13 20:20:40 +00006546 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006547 gotoxy(g_coord.X + 1,
6548 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6549 goto got3;
6550
6551 case 'B':
6552 visual_bell();
6553 goto got3;
6554
6555 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6557 g_coord.Y + 1);
6558 goto got3;
6559
6560 case 'E':
6561 termcap_mode_end();
6562 goto got3;
6563
6564 case 'F':
6565 standout();
6566 goto got3;
6567
6568 case 'f':
6569 standend();
6570 goto got3;
6571
6572 case 'H':
6573 gotoxy(1, 1);
6574 goto got3;
6575
6576 case 'j':
6577 clear_to_end_of_display();
6578 goto got3;
6579
6580 case 'J':
6581 clear_screen();
6582 goto got3;
6583
6584 case 'K':
6585 clear_to_end_of_line();
6586 goto got3;
6587
6588 case 'L':
6589 insert_lines(1);
6590 goto got3;
6591
6592 case 'M':
6593 delete_lines(1);
6594 goto got3;
6595
6596 case 'S':
6597 termcap_mode_start();
6598 goto got3;
6599
6600 case 'V':
6601 cursor_visible(TRUE);
6602 goto got3;
6603
6604 case 'v':
6605 cursor_visible(FALSE);
6606 goto got3;
6607
6608 got3:
6609 s += 3;
6610 len -= 2;
6611 }
6612
6613#ifdef MCH_WRITE_DUMP
6614 if (fdDump)
6615 {
6616 fputs("ESC | ", fdDump);
6617 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6618 fputc('\n', fdDump);
6619 }
6620#endif
6621 }
6622 else
6623 {
6624 /* Write a single character */
6625 DWORD nWritten;
6626
6627 nWritten = write_chars(s, 1);
6628#ifdef MCH_WRITE_DUMP
6629 if (fdDump)
6630 {
6631 fputc('>', fdDump);
6632 fwrite(s, sizeof(char_u), nWritten, fdDump);
6633 fputs("<\n", fdDump);
6634 }
6635#endif
6636
6637 len -= (nWritten - 1);
6638 s += nWritten;
6639 }
6640 }
6641
6642#ifdef MCH_WRITE_DUMP
6643 if (fdDump)
6644 fflush(fdDump);
6645#endif
6646}
6647
6648#endif /* FEAT_GUI_W32 */
6649
6650
6651/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006652 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006653 */
6654 void
6655mch_delay(
6656 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006657 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658{
6659#ifdef FEAT_GUI_W32
6660 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006661#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006663# ifdef FEAT_MZSCHEME
6664 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6665 {
6666 int towait = p_mzq;
6667
6668 /* if msec is large enough, wait by portions in p_mzq */
6669 while (msec > 0)
6670 {
6671 mzvim_check_threads();
6672 if (msec < towait)
6673 towait = msec;
6674 Sleep(towait);
6675 msec -= towait;
6676 }
6677 }
6678 else
6679# endif
6680 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006681 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006682 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006683#endif
6684}
6685
6686
6687/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006688 * This version of remove is not scared by a readonly (backup) file.
6689 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006690 * Return 0 for success, -1 for failure.
6691 */
6692 int
6693mch_remove(char_u *name)
6694{
6695#ifdef FEAT_MBYTE
6696 WCHAR *wn = NULL;
6697 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006698#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006699
Bram Moolenaar203258c2016-01-17 22:15:16 +01006700 /*
6701 * On Windows, deleting a directory's symbolic link is done by
6702 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6703 */
6704 if (mch_isdir(name) && mch_is_symbolic_link(name))
6705 return mch_rmdir(name);
6706
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006707 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6708
6709#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6711 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006712 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006713 if (wn != NULL)
6714 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 n = DeleteFileW(wn) ? 0 : -1;
6716 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006717 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718 }
6719 }
6720#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006721 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722}
6723
6724
6725/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006726 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006727 */
6728 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006729mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730{
6731#ifndef FEAT_GUI_W32 /* never used */
6732 if (g_fCtrlCPressed || g_fCBrkPressed)
6733 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006734 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6736 got_int = TRUE;
6737 }
6738#endif
6739}
6740
Bram Moolenaaree273972016-01-02 21:11:51 +01006741/* physical RAM to leave for the OS */
6742#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006743
6744/*
6745 * How much main memory in KiB that can be used by VIM.
6746 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006747 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006748mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006749{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006750 MEMORYSTATUSEX ms;
6751
Bram Moolenaaree273972016-01-02 21:11:51 +01006752 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006753 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6754 * what fits in 32 bits. But it's not always available. */
6755 ms.dwLength = sizeof(MEMORYSTATUSEX);
6756 GlobalMemoryStatusEx(&ms);
6757 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006758 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006759 /* Process address space fits in physical RAM, use all of it. */
6760 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006761 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006762 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006763 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006764 /* Catch old NT box or perverse hardware setup. */
6765 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006766 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006767 /* Use physical RAM less reserve for OS + data. */
6768 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006769}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006770
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771#ifdef FEAT_MBYTE
6772/*
6773 * Same code as below, but with wide functions and no comments.
6774 * Return 0 for success, non-zero for failure.
6775 */
6776 int
6777mch_wrename(WCHAR *wold, WCHAR *wnew)
6778{
6779 WCHAR *p;
6780 int i;
6781 WCHAR szTempFile[_MAX_PATH + 1];
6782 WCHAR szNewPath[_MAX_PATH + 1];
6783 HANDLE hf;
6784
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006785 p = wold;
6786 for (i = 0; wold[i] != NUL; ++i)
6787 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6788 && wold[i + 1] != 0)
6789 p = wold + i + 1;
6790 if ((int)(wold + i - p) < 8 || p[6] != '~')
6791 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006792
6793 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6794 return -1;
6795 *p = NUL;
6796
6797 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6798 return -2;
6799
6800 if (!DeleteFileW(szTempFile))
6801 return -3;
6802
6803 if (!MoveFileW(wold, szTempFile))
6804 return -4;
6805
6806 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6807 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6808 return -5;
6809 if (!CloseHandle(hf))
6810 return -6;
6811
6812 if (!MoveFileW(szTempFile, wnew))
6813 {
6814 (void)MoveFileW(szTempFile, wold);
6815 return -7;
6816 }
6817
6818 DeleteFileW(szTempFile);
6819
6820 if (!DeleteFileW(wold))
6821 return -8;
6822
6823 return 0;
6824}
6825#endif
6826
6827
6828/*
6829 * mch_rename() works around a bug in rename (aka MoveFile) in
6830 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6831 * file whose short file name is "FOO.BAR" (its long file name will
6832 * be correct: "foo.bar~"). Because a file can be accessed by
6833 * either its SFN or its LFN, "foo.bar" has effectively been
6834 * renamed to "foo.bar", which is not at all what was wanted. This
6835 * seems to happen only when renaming files with three-character
6836 * extensions by appending a suffix that does not include ".".
6837 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6838 *
6839 * There is another problem, which isn't really a bug but isn't right either:
6840 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6841 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6842 * service pack 6. Doesn't seem to happen on Windows 98.
6843 *
6844 * Like rename(), returns 0 upon success, non-zero upon failure.
6845 * Should probably set errno appropriately when errors occur.
6846 */
6847 int
6848mch_rename(
6849 const char *pszOldFile,
6850 const char *pszNewFile)
6851{
6852 char szTempFile[_MAX_PATH+1];
6853 char szNewPath[_MAX_PATH+1];
6854 char *pszFilePart;
6855 HANDLE hf;
6856#ifdef FEAT_MBYTE
6857 WCHAR *wold = NULL;
6858 WCHAR *wnew = NULL;
6859 int retval = -1;
6860
6861 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6862 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006863 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6864 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006865 if (wold != NULL && wnew != NULL)
6866 retval = mch_wrename(wold, wnew);
6867 vim_free(wold);
6868 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006869 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870 }
6871#endif
6872
6873 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006874 * No need to play tricks unless the file name contains a "~" as the
6875 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006877 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6878 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6879 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006880
6881 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6882 * a directory, no error is returned and pszFilePart will be NULL. */
6883 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6884 || pszFilePart == NULL)
6885 return -1;
6886 *pszFilePart = NUL;
6887
6888 /* Get (and create) a unique temporary file name in directory of new file */
6889 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6890 return -2;
6891
6892 /* blow the temp file away */
6893 if (!DeleteFile(szTempFile))
6894 return -3;
6895
6896 /* rename old file to the temp file */
6897 if (!MoveFile(pszOldFile, szTempFile))
6898 return -4;
6899
6900 /* now create an empty file called pszOldFile; this prevents the operating
6901 * system using pszOldFile as an alias (SFN) if we're renaming within the
6902 * same directory. For example, we're editing a file called
6903 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6904 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6905 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006906 * cause all sorts of problems later in buf_write(). So, we create an
6907 * empty file called filena~1.txt and the system will have to find some
6908 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006909 */
6910 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6911 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6912 return -5;
6913 if (!CloseHandle(hf))
6914 return -6;
6915
6916 /* rename the temp file to the new file */
6917 if (!MoveFile(szTempFile, pszNewFile))
6918 {
6919 /* Renaming failed. Rename the file back to its old name, so that it
6920 * looks like nothing happened. */
6921 (void)MoveFile(szTempFile, pszOldFile);
6922
6923 return -7;
6924 }
6925
6926 /* Seems to be left around on Novell filesystems */
6927 DeleteFile(szTempFile);
6928
6929 /* finally, remove the empty old file */
6930 if (!DeleteFile(pszOldFile))
6931 return -8;
6932
6933 return 0; /* success */
6934}
6935
6936/*
6937 * Get the default shell for the current hardware platform
6938 */
6939 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006940default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006941{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 PlatformId();
6943
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006944 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945}
6946
6947/*
6948 * mch_access() extends access() to do more detailed check on network drives.
6949 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6950 */
6951 int
6952mch_access(char *n, int p)
6953{
6954 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955 int retval = -1; /* default: fail */
6956#ifdef FEAT_MBYTE
6957 WCHAR *wn = NULL;
6958
6959 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006960 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006961#endif
6962
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006963 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 {
6965 char TempName[_MAX_PATH + 16] = "";
6966#ifdef FEAT_MBYTE
6967 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6968#endif
6969
6970 if (p & R_OK)
6971 {
6972 /* Read check is performed by seeing if we can do a find file on
6973 * the directory for any file. */
6974#ifdef FEAT_MBYTE
6975 if (wn != NULL)
6976 {
6977 int i;
6978 WIN32_FIND_DATAW d;
6979
6980 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6981 TempNameW[i] = wn[i];
6982 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6983 TempNameW[i++] = '\\';
6984 TempNameW[i++] = '*';
6985 TempNameW[i++] = 0;
6986
6987 hFile = FindFirstFileW(TempNameW, &d);
6988 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006989 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006990 else
6991 (void)FindClose(hFile);
6992 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006993 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006994#endif
6995 {
6996 char *pch;
6997 WIN32_FIND_DATA d;
6998
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006999 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007000 pch = TempName + STRLEN(TempName) - 1;
7001 if (*pch != '\\' && *pch != '/')
7002 *++pch = '\\';
7003 *++pch = '*';
7004 *++pch = NUL;
7005
7006 hFile = FindFirstFile(TempName, &d);
7007 if (hFile == INVALID_HANDLE_VALUE)
7008 goto getout;
7009 (void)FindClose(hFile);
7010 }
7011 }
7012
7013 if (p & W_OK)
7014 {
7015 /* Trying to create a temporary file in the directory should catch
7016 * directories on read-only network shares. However, in
7017 * directories whose ACL allows writes but denies deletes will end
7018 * up keeping the temporary file :-(. */
7019#ifdef FEAT_MBYTE
7020 if (wn != NULL)
7021 {
7022 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007023 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007024 else
7025 DeleteFileW(TempNameW);
7026 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007027 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028#endif
7029 {
7030 if (!GetTempFileName(n, "VIM", 0, TempName))
7031 goto getout;
7032 mch_remove((char_u *)TempName);
7033 }
7034 }
7035 }
7036 else
7037 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007038 // Don't consider a file read-only if another process has opened it.
7039 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7040
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041 /* Trying to open the file for the required access does ACL, read-only
7042 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007043 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7044 | ((p & R_OK) ? GENERIC_READ : 0);
7045
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046#ifdef FEAT_MBYTE
7047 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007048 hFile = CreateFileW(wn, access_mode, share_mode,
7049 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007050 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051#endif
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007052 hFile = CreateFile(n, access_mode, share_mode,
7053 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007054 if (hFile == INVALID_HANDLE_VALUE)
7055 goto getout;
7056 CloseHandle(hFile);
7057 }
7058
7059 retval = 0; /* success */
7060getout:
7061#ifdef FEAT_MBYTE
7062 vim_free(wn);
7063#endif
7064 return retval;
7065}
7066
7067#if defined(FEAT_MBYTE) || defined(PROTO)
7068/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007069 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070 */
7071 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007072mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007073{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007074 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
7075# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076 WCHAR *wn;
7077 int f;
7078
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007079 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007080 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007081 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007082 if (wn != NULL)
7083 {
7084 f = _wopen(wn, flags, mode);
7085 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007086 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087 }
7088 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007089# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007091 /* open() can open a file which name is longer than _MAX_PATH bytes
7092 * and shorter than _MAX_PATH characters successfully, but sometimes it
7093 * causes unexpected error in another part. We make it an error explicitly
7094 * here. */
7095 if (strlen(name) >= _MAX_PATH)
7096 return -1;
7097
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098 return open(name, flags, mode);
7099}
7100
7101/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007102 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103 */
7104 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007105mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007106{
7107 WCHAR *wn, *wm;
7108 FILE *f = NULL;
7109
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007110 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007112# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007113 /* Work around an annoying assertion in the Microsoft debug CRT
7114 * when mode's text/binary setting doesn't match _get_fmode(). */
7115 char newMode = mode[strlen(mode) - 1];
7116 int oldMode = 0;
7117
7118 _get_fmode(&oldMode);
7119 if (newMode == 't')
7120 _set_fmode(_O_TEXT);
7121 else if (newMode == 'b')
7122 _set_fmode(_O_BINARY);
7123# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007124 wn = enc_to_utf16((char_u *)name, NULL);
7125 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007126 if (wn != NULL && wm != NULL)
7127 f = _wfopen(wn, wm);
7128 vim_free(wn);
7129 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007130
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007131# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007132 _set_fmode(oldMode);
7133# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007134 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007135 }
7136
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007137 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7138 * and shorter than _MAX_PATH characters successfully, but sometimes it
7139 * causes unexpected error in another part. We make it an error explicitly
7140 * here. */
7141 if (strlen(name) >= _MAX_PATH)
7142 return NULL;
7143
Bram Moolenaar071d4272004-06-13 20:20:40 +00007144 return fopen(name, mode);
7145}
7146#endif
7147
7148#ifdef FEAT_MBYTE
7149/*
7150 * SUB STREAM (aka info stream) handling:
7151 *
7152 * NTFS can have sub streams for each file. Normal contents of file is
7153 * stored in the main stream, and extra contents (author information and
7154 * title and so on) can be stored in sub stream. After Windows 2000, user
7155 * can access and store those informations in sub streams via explorer's
7156 * property menuitem in right click menu. Those informations in sub streams
7157 * were lost when copying only the main stream. So we have to copy sub
7158 * streams.
7159 *
7160 * Incomplete explanation:
7161 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7162 * More useful info and an example:
7163 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7164 */
7165
7166/*
7167 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7168 * and write to stream "substream" of file "to".
7169 * Errors are ignored.
7170 */
7171 static void
7172copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7173{
7174 HANDLE hTo;
7175 WCHAR *to_name;
7176
7177 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7178 wcscpy(to_name, to);
7179 wcscat(to_name, substream);
7180
7181 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7182 FILE_ATTRIBUTE_NORMAL, NULL);
7183 if (hTo != INVALID_HANDLE_VALUE)
7184 {
7185 long done;
7186 DWORD todo;
7187 DWORD readcnt, written;
7188 char buf[4096];
7189
7190 /* Copy block of bytes at a time. Abort when something goes wrong. */
7191 for (done = 0; done < len; done += written)
7192 {
7193 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007194 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7195 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007196 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7197 FALSE, FALSE, context)
7198 || readcnt != todo
7199 || !WriteFile(hTo, buf, todo, &written, NULL)
7200 || written != todo)
7201 break;
7202 }
7203 CloseHandle(hTo);
7204 }
7205
7206 free(to_name);
7207}
7208
7209/*
7210 * Copy info streams from file "from" to file "to".
7211 */
7212 static void
7213copy_infostreams(char_u *from, char_u *to)
7214{
7215 WCHAR *fromw;
7216 WCHAR *tow;
7217 HANDLE sh;
7218 WIN32_STREAM_ID sid;
7219 int headersize;
7220 WCHAR streamname[_MAX_PATH];
7221 DWORD readcount;
7222 void *context = NULL;
7223 DWORD lo, hi;
7224 int len;
7225
7226 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007227 fromw = enc_to_utf16(from, NULL);
7228 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007229 if (fromw != NULL && tow != NULL)
7230 {
7231 /* Open the file for reading. */
7232 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7233 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7234 if (sh != INVALID_HANDLE_VALUE)
7235 {
7236 /* Use BackupRead() to find the info streams. Repeat until we
7237 * have done them all.*/
7238 for (;;)
7239 {
7240 /* Get the header to find the length of the stream name. If
7241 * the "readcount" is zero we have done all info streams. */
7242 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007243 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7245 &readcount, FALSE, FALSE, &context)
7246 || readcount == 0)
7247 break;
7248
7249 /* We only deal with streams that have a name. The normal
7250 * file data appears to be without a name, even though docs
7251 * suggest it is called "::$DATA". */
7252 if (sid.dwStreamNameSize > 0)
7253 {
7254 /* Read the stream name. */
7255 if (!BackupRead(sh, (LPBYTE)streamname,
7256 sid.dwStreamNameSize,
7257 &readcount, FALSE, FALSE, &context))
7258 break;
7259
7260 /* Copy an info stream with a name ":anything:$DATA".
7261 * Skip "::$DATA", it has no stream name (examples suggest
7262 * it might be used for the normal file contents).
7263 * Note that BackupRead() counts bytes, but the name is in
7264 * wide characters. */
7265 len = readcount / sizeof(WCHAR);
7266 streamname[len] = 0;
7267 if (len > 7 && wcsicmp(streamname + len - 6,
7268 L":$DATA") == 0)
7269 {
7270 streamname[len - 6] = 0;
7271 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007272 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007273 }
7274 }
7275
7276 /* Advance to the next stream. We might try seeking too far,
7277 * but BackupSeek() doesn't skip over stream borders, thus
7278 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007279 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007280 &lo, &hi, &context);
7281 }
7282
7283 /* Clear the context. */
7284 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7285
7286 CloseHandle(sh);
7287 }
7288 }
7289 vim_free(fromw);
7290 vim_free(tow);
7291}
7292#endif
7293
7294/*
7295 * Copy file attributes from file "from" to file "to".
7296 * For Windows NT and later we copy info streams.
7297 * Always returns zero, errors are ignored.
7298 */
7299 int
7300mch_copy_file_attribute(char_u *from, char_u *to)
7301{
7302#ifdef FEAT_MBYTE
7303 /* File streams only work on Windows NT and later. */
7304 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007305 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007306#endif
7307 return 0;
7308}
7309
7310#if defined(MYRESETSTKOFLW) || defined(PROTO)
7311/*
7312 * Recreate a destroyed stack guard page in win32.
7313 * Written by Benjamin Peterson.
7314 */
7315
7316/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007317#define MIN_STACK_WINNT 2
7318
7319/*
7320 * This function does the same thing as _resetstkoflw(), which is only
7321 * available in DevStudio .net and later.
7322 * Returns 0 for failure, 1 for success.
7323 */
7324 int
7325myresetstkoflw(void)
7326{
7327 BYTE *pStackPtr;
7328 BYTE *pGuardPage;
7329 BYTE *pStackBase;
7330 BYTE *pLowestPossiblePage;
7331 MEMORY_BASIC_INFORMATION mbi;
7332 SYSTEM_INFO si;
7333 DWORD nPageSize;
7334 DWORD dummy;
7335
Bram Moolenaar071d4272004-06-13 20:20:40 +00007336 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007337
7338 /* We need to know the system page size. */
7339 GetSystemInfo(&si);
7340 nPageSize = si.dwPageSize;
7341
7342 /* ...and the current stack pointer */
7343 pStackPtr = (BYTE*)_alloca(1);
7344
7345 /* ...and the base of the stack. */
7346 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7347 return 0;
7348 pStackBase = (BYTE*)mbi.AllocationBase;
7349
7350 /* ...and the page thats min_stack_req pages away from stack base; this is
7351 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007352 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007353
Bram Moolenaar071d4272004-06-13 20:20:40 +00007354 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007355 /* We want the first committed page in the stack Start at the stack
7356 * base and move forward through memory until we find a committed block.
7357 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358 BYTE *pBlock = pStackBase;
7359
Bram Moolenaara466c992005-07-09 21:03:22 +00007360 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007361 {
7362 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7363 return 0;
7364
7365 pBlock += mbi.RegionSize;
7366
7367 if (mbi.State & MEM_COMMIT)
7368 break;
7369 }
7370
7371 /* mbi now describes the first committed block in the stack. */
7372 if (mbi.Protect & PAGE_GUARD)
7373 return 1;
7374
7375 /* decide where the guard page should start */
7376 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7377 pGuardPage = pLowestPossiblePage;
7378 else
7379 pGuardPage = (BYTE*)mbi.BaseAddress;
7380
7381 /* allocate the guard page */
7382 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7383 return 0;
7384
7385 /* apply the guard attribute to the page */
7386 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7387 &dummy))
7388 return 0;
7389 }
7390
7391 return 1;
7392}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007393#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007394
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007395
7396#if defined(FEAT_MBYTE) || defined(PROTO)
7397/*
7398 * The command line arguments in UCS2
7399 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007400static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007401static LPWSTR *ArglistW = NULL;
7402static int global_argc = 0;
7403static char **global_argv;
7404
7405static int used_file_argc = 0; /* last argument in global_argv[] used
7406 for the argument list. */
7407static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7408 command line arguments added to
7409 the argument list */
7410static int used_file_count = 0; /* nr of entries in used_file_indexes */
7411static int used_file_literal = FALSE; /* take file names literally */
7412static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007413static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007414static int used_alist_count = 0;
7415
7416
7417/*
7418 * Get the command line arguments. Unicode version.
7419 * Returns argc. Zero when something fails.
7420 */
7421 int
7422get_cmd_argsW(char ***argvp)
7423{
7424 char **argv = NULL;
7425 int argc = 0;
7426 int i;
7427
Bram Moolenaar14993322014-09-09 12:25:33 +02007428 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007429 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7430 if (ArglistW != NULL)
7431 {
7432 argv = malloc((nArgsW + 1) * sizeof(char *));
7433 if (argv != NULL)
7434 {
7435 argc = nArgsW;
7436 argv[argc] = NULL;
7437 for (i = 0; i < argc; ++i)
7438 {
7439 int len;
7440
7441 /* Convert each Unicode argument to the current codepage. */
7442 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007443 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007444 (LPSTR *)&argv[i], &len, 0, 0);
7445 if (argv[i] == NULL)
7446 {
7447 /* Out of memory, clear everything. */
7448 while (i > 0)
7449 free(argv[--i]);
7450 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007451 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007452 argc = 0;
7453 }
7454 }
7455 }
7456 }
7457
7458 global_argc = argc;
7459 global_argv = argv;
7460 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007461 {
7462 if (used_file_indexes != NULL)
7463 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007464 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007465 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007466
7467 if (argvp != NULL)
7468 *argvp = argv;
7469 return argc;
7470}
7471
7472 void
7473free_cmd_argsW(void)
7474{
7475 if (ArglistW != NULL)
7476 {
7477 GlobalFree(ArglistW);
7478 ArglistW = NULL;
7479 }
7480}
7481
7482/*
7483 * Remember "name" is an argument that was added to the argument list.
7484 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7485 * is called.
7486 */
7487 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007488used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007489{
7490 int i;
7491
7492 if (used_file_indexes == NULL)
7493 return;
7494 for (i = used_file_argc + 1; i < global_argc; ++i)
7495 if (STRCMP(global_argv[i], name) == 0)
7496 {
7497 used_file_argc = i;
7498 used_file_indexes[used_file_count++] = i;
7499 break;
7500 }
7501 used_file_literal = literal;
7502 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007503 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007504}
7505
7506/*
7507 * Remember the length of the argument list as it was. If it changes then we
7508 * leave it alone when 'encoding' is set.
7509 */
7510 void
7511set_alist_count(void)
7512{
7513 used_alist_count = GARGCOUNT;
7514}
7515
7516/*
7517 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7518 * has been changed while starting up. Use the UCS-2 command line arguments
7519 * and convert them to 'encoding'.
7520 */
7521 void
7522fix_arg_enc(void)
7523{
7524 int i;
7525 int idx;
7526 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007527 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007528
7529 /* Safety checks:
7530 * - if argument count differs between the wide and non-wide argument
7531 * list, something must be wrong.
7532 * - the file name arguments must have been located.
7533 * - the length of the argument list wasn't changed by the user.
7534 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007535 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007536 || ArglistW == NULL
7537 || used_file_indexes == NULL
7538 || used_file_count == 0
7539 || used_alist_count != GARGCOUNT)
7540 return;
7541
Bram Moolenaar86b68352004-12-27 21:59:20 +00007542 /* Remember the buffer numbers for the arguments. */
7543 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7544 if (fnum_list == NULL)
7545 return; /* out of memory */
7546 for (i = 0; i < GARGCOUNT; ++i)
7547 fnum_list[i] = GARGLIST[i].ae_fnum;
7548
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007549 /* Clear the argument list. Make room for the new arguments. */
7550 alist_clear(&global_alist);
7551 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007552 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007553
7554 for (i = 0; i < used_file_count; ++i)
7555 {
7556 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007557 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007558 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007559 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007560 int literal = used_file_literal;
7561
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007562#ifdef FEAT_DIFF
7563 /* When using diff mode may need to concatenate file name to
7564 * directory name. Just like it's done in main(). */
7565 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7566 && !mch_isdir(alist_name(&GARGLIST[0])))
7567 {
7568 char_u *r;
7569
7570 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7571 if (r != NULL)
7572 {
7573 vim_free(str);
7574 str = r;
7575 }
7576 }
7577#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007578 /* Re-use the old buffer by renaming it. When not using literal
7579 * names it's done by alist_expand() below. */
7580 if (used_file_literal)
7581 buf_set_name(fnum_list[i], str);
7582
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007583 /* Check backtick literal. backtick literal is already expanded in
7584 * main.c, so this part add str as literal. */
7585 if (literal == FALSE)
7586 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007587 size_t len = STRLEN(str);
7588
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007589 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7590 literal = TRUE;
7591 }
7592 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007593 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007594 }
7595
7596 if (!used_file_literal)
7597 {
7598 /* Now expand wildcards in the arguments. */
7599 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7600 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007601 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7602 * Also, unset wildignore to not be influenced by this option.
7603 * The arguments specified in command-line should be kept even if
7604 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007605 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007606 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007607 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007608 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007609 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007610 }
7611
7612 /* If wildcard expansion failed, we are editing the first file of the
7613 * arglist and there is no file name: Edit the first argument now. */
7614 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7615 {
7616 do_cmdline_cmd((char_u *)":rewind");
7617 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007618 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007619 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007620
7621 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007622}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007623#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007624
7625 int
7626mch_setenv(char *var, char *value, int x)
7627{
7628 char_u *envbuf;
7629
7630 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7631 if (envbuf == NULL)
7632 return -1;
7633
7634 sprintf((char *)envbuf, "%s=%s", var, value);
7635
7636#ifdef FEAT_MBYTE
7637 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7638 {
7639 WCHAR *p = enc_to_utf16(envbuf, NULL);
7640
7641 vim_free(envbuf);
7642 if (p == NULL)
7643 return -1;
7644 _wputenv(p);
7645# ifdef libintl_wputenv
7646 libintl_wputenv(p);
7647# endif
7648 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7649 vim_free(p);
7650 }
7651 else
7652#endif
7653 {
7654 _putenv((char *)envbuf);
7655# ifdef libintl_putenv
7656 libintl_putenv((char *)envbuf);
7657# endif
7658 /* Unlike Un*x systems, we can free the string for _putenv(). */
7659 vim_free(envbuf);
7660 }
7661
7662 return 0;
7663}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007664
7665#ifndef FEAT_GUI_W32
7666
7667/*
7668 * Support for 256 colors and 24-bit colors was added in Windows 10
7669 * version 1703 (Creators update).
7670 */
7671# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7672
7673 static void
7674vtp_init(void)
7675{
7676 DWORD ver, mode;
7677 HMODULE hKerneldll;
7678 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007679# ifdef FEAT_TERMGUICOLORS
7680 COLORREF fg, bg;
7681# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007682
7683 ver = get_build_number();
7684 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7685 GetConsoleMode(g_hConOut, &mode);
7686 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7687 if (SetConsoleMode(g_hConOut, mode) == 0)
7688 vtp_working = 0;
7689
7690 /* Use functions supported from Vista */
7691 hKerneldll = GetModuleHandle("kernel32.dll");
7692 if (hKerneldll != NULL)
7693 {
7694 pGetConsoleScreenBufferInfoEx =
7695 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7696 hKerneldll, "GetConsoleScreenBufferInfoEx");
7697 pSetConsoleScreenBufferInfoEx =
7698 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7699 hKerneldll, "SetConsoleScreenBufferInfoEx");
7700 if (pGetConsoleScreenBufferInfoEx != NULL
7701 && pSetConsoleScreenBufferInfoEx != NULL)
7702 has_csbiex = TRUE;
7703 }
7704
7705 csbi.cbSize = sizeof(csbi);
7706 if (has_csbiex)
7707 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007708 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7709 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7710
7711# ifdef FEAT_TERMGUICOLORS
7712 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7713 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7714 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7715 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7716 default_console_color_bg = bg;
7717 default_console_color_fg = fg;
7718#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007719
7720 set_console_color_rgb();
7721}
7722
7723 static void
7724vtp_exit(void)
7725{
7726 reset_console_color_rgb();
7727}
7728
7729 static int
7730vtp_printf(
7731 char *format,
7732 ...)
7733{
7734 char_u buf[100];
7735 va_list list;
7736 DWORD result;
7737
7738 va_start(list, format);
7739 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7740 va_end(list);
7741 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7742 return (int)result;
7743}
7744
7745 static void
7746vtp_sgr_bulk(
7747 int arg)
7748{
7749 int args[1];
7750
7751 args[0] = arg;
7752 vtp_sgr_bulks(1, args);
7753}
7754
7755 static void
7756vtp_sgr_bulks(
7757 int argc,
7758 int *args
7759)
7760{
7761 /* 2('\033[') + 4('255.') * 16 + NUL */
7762 char_u buf[2 + (4 * 16) + 1];
7763 char_u *p;
7764 int i;
7765
7766 p = buf;
7767 *p++ = '\033';
7768 *p++ = '[';
7769
7770 for (i = 0; i < argc; ++i)
7771 {
7772 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7773 *p++ = ';';
7774 }
7775 p--;
7776 *p++ = 'm';
7777 *p = NUL;
7778 vtp_printf((char *)buf);
7779}
7780
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007781# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007782 static int
7783ctermtoxterm(
7784 int cterm)
7785{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007786 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007787
7788 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7789 return (((int)r << 16) | ((int)g << 8) | (int)b);
7790}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007791# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007792
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007793 static void
7794set_console_color_rgb(void)
7795{
7796# ifdef FEAT_TERMGUICOLORS
7797 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7798 int id;
7799 guicolor_T fg = INVALCOLOR;
7800 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007801 int ctermfg;
7802 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007803
7804 if (!USE_VTP)
7805 return;
7806
7807 id = syn_name2id((char_u *)"Normal");
7808 if (id > 0)
7809 syn_id2colors(id, &fg, &bg);
7810 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007811 {
7812 ctermfg = -1;
7813 if (id > 0)
7814 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007815 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7816 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007817 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007818 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007819 {
7820 ctermbg = -1;
7821 if (id > 0)
7822 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007823 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7824 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007825 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007826 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7827 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7828
7829 csbi.cbSize = sizeof(csbi);
7830 if (has_csbiex)
7831 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7832
7833 csbi.cbSize = sizeof(csbi);
7834 csbi.srWindow.Right += 1;
7835 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007836 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7837 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007838 if (has_csbiex)
7839 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7840# endif
7841}
7842
7843 static void
7844reset_console_color_rgb(void)
7845{
7846# ifdef FEAT_TERMGUICOLORS
7847 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7848
7849 csbi.cbSize = sizeof(csbi);
7850 if (has_csbiex)
7851 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7852
7853 csbi.cbSize = sizeof(csbi);
7854 csbi.srWindow.Right += 1;
7855 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007856 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7857 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007858 if (has_csbiex)
7859 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7860# endif
7861}
7862
7863 void
7864control_console_color_rgb(void)
7865{
7866 if (USE_VTP)
7867 set_console_color_rgb();
7868 else
7869 reset_console_color_rgb();
7870}
7871
7872 int
7873has_vtp_working(void)
7874{
7875 return vtp_working;
7876}
7877
7878 int
7879use_vtp(void)
7880{
7881 return USE_VTP;
7882}
7883
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007884 int
7885is_term_win32(void)
7886{
7887 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7888}
7889
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007890#endif