blob: 43b811b13d05d8f874ad38b7b8799c6dfa795ba6 [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
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171static void scroll(unsigned cLines);
172static void set_scroll_region(unsigned left, unsigned top,
173 unsigned right, unsigned bottom);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174static void delete_lines(unsigned cLines);
175static void gotoxy(unsigned x, unsigned y);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000176static void standout(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177static int s_cursor_visible = TRUE;
178static int did_create_conin = FALSE;
179#else
180static int s_dont_use_vimrun = TRUE;
181static int need_vimrun_warning = FALSE;
182static char *vimrun_path = "vimrun ";
183#endif
184
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200185static int win32_getattrs(char_u *name);
186static int win32_setattrs(char_u *name, int attrs);
187static int win32_set_archive(char_u *name);
188
Bram Moolenaar071d4272004-06-13 20:20:40 +0000189#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100190static int vtp_working = 0;
191static void vtp_init();
192static void vtp_exit();
193static int vtp_printf(char *format, ...);
194static void vtp_sgr_bulk(int arg);
195static void vtp_sgr_bulks(int argc, int *argv);
196
197static guicolor_T save_console_bg_rgb;
198static guicolor_T save_console_fg_rgb;
199
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200200static int g_color_index_bg = 0;
201static int g_color_index_fg = 7;
202
203# ifdef FEAT_TERMGUICOLORS
204static int default_console_color_bg = 0x000000; // black
205static int default_console_color_fg = 0xc0c0c0; // white
206# endif
207
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100208# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200209# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100210# else
211# define USE_VTP 0
212# endif
213
214static void set_console_color_rgb(void);
215static void reset_console_color_rgb(void);
216#endif
217
218/* This flag is newly created from Windows 10 */
219#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
220# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
221#endif
222
223#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224static int suppress_winsize = 1; /* don't fiddle with console */
225#endif
226
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200227static char_u *exe_path = NULL;
228
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100229static BOOL win8_or_later = FALSE;
230
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100231#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100232/* Dynamic loading for portability */
233typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
234{
235 ULONG cbSize;
236 COORD dwSize;
237 COORD dwCursorPosition;
238 WORD wAttributes;
239 SMALL_RECT srWindow;
240 COORD dwMaximumWindowSize;
241 WORD wPopupAttributes;
242 BOOL bFullscreenSupported;
243 COLORREF ColorTable[16];
244} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
245typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
246static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
247typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
248static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
249static BOOL has_csbiex = FALSE;
250
251/*
252 * Get version number including build number
253 */
254typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
255# define MAKE_VER(major, minor, build) \
256 (((major) << 24) | ((minor) << 16) | (build))
257
258 static DWORD
259get_build_number(void)
260{
261 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
262 HMODULE hNtdll;
263 PfnRtlGetVersion pRtlGetVersion;
264 DWORD ver = MAKE_VER(0, 0, 0);
265
266 hNtdll = GetModuleHandle("ntdll.dll");
267 if (hNtdll != NULL)
268 {
269 pRtlGetVersion =
270 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
271 pRtlGetVersion(&osver);
272 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
273 min(osver.dwMinorVersion, 255),
274 min(osver.dwBuildNumber, 32767));
275 }
276 return ver;
277}
278
279
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280/*
281 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100282 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100283 */
284 static BOOL
285read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100286 HANDLE hInput,
287 INPUT_RECORD *lpBuffer,
288 DWORD nLength,
289 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100290{
291 enum
292 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100293 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100294 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100296 static DWORD s_dwIndex = 0;
297 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100299 int head;
300 int tail;
301 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100302
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200303 if (nLength == -2)
304 return (s_dwMax > 0) ? TRUE : FALSE;
305
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100306 if (!win8_or_later)
307 {
308 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200309 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
310 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100311 }
312
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100313 if (s_dwMax == 0)
314 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100315 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200316 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
317 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100318 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100319 s_dwIndex = 0;
320 s_dwMax = dwEvents;
321 if (dwEvents == 0)
322 {
323 *lpEvents = 0;
324 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100326
327 if (s_dwMax > 1)
328 {
329 head = 0;
330 tail = s_dwMax - 1;
331 while (head != tail)
332 {
333 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
334 && s_irCache[head + 1].EventType
335 == WINDOW_BUFFER_SIZE_EVENT)
336 {
337 /* Remove duplicate event to avoid flicker. */
338 for (i = head; i < tail; ++i)
339 s_irCache[i] = s_irCache[i + 1];
340 --tail;
341 continue;
342 }
343 head++;
344 }
345 s_dwMax = tail + 1;
346 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100347 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100348
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100349 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200350 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100351 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100352 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100353 return TRUE;
354}
355
356/*
357 * Version of PeekConsoleInput() that works with IME.
358 */
359 static BOOL
360peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100361 HANDLE hInput,
362 INPUT_RECORD *lpBuffer,
363 DWORD nLength,
364 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100365{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100366 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367}
368
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100369# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200370 static DWORD
371msg_wait_for_multiple_objects(
372 DWORD nCount,
373 LPHANDLE pHandles,
374 BOOL fWaitAll,
375 DWORD dwMilliseconds,
376 DWORD dwWakeMask)
377{
378 if (read_console_input(NULL, NULL, -2, NULL))
379 return WAIT_OBJECT_0;
380 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
381 dwMilliseconds, dwWakeMask);
382}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100383# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200384
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100385# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200386 static DWORD
387wait_for_single_object(
388 HANDLE hHandle,
389 DWORD dwMilliseconds)
390{
391 if (read_console_input(NULL, NULL, -2, NULL))
392 return WAIT_OBJECT_0;
393 return WaitForSingleObject(hHandle, dwMilliseconds);
394}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100395# endif
396#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200397
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 static void
399get_exe_name(void)
400{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100401 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
402 * as the maximum length that works (plus a NUL byte). */
403#define MAX_ENV_PATH_LEN 8192
404 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200405 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406
407 if (exe_name == NULL)
408 {
409 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100410 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411 if (*temp != NUL)
412 exe_name = FullName_save((char_u *)temp, FALSE);
413 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000414
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200415 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000416 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200417 exe_path = vim_strnsave(exe_name,
418 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200419 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000420 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200421 /* Append our starting directory to $PATH, so that when doing
422 * "!xxd" it's found in our starting directory. Needed because
423 * SearchPath() also looks there. */
424 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100425 if (p == NULL
426 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100428 if (p == NULL || *p == NUL)
429 temp[0] = NUL;
430 else
431 {
432 STRCPY(temp, p);
433 STRCAT(temp, ";");
434 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100436 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200437 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000438 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440}
441
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200442/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100443 * Unescape characters in "p" that appear in "escaped".
444 */
445 static void
446unescape_shellxquote(char_u *p, char_u *escaped)
447{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100448 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100449 int n;
450
451 while (*p != NUL)
452 {
453 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
454 mch_memmove(p, p + 1, l--);
455#ifdef FEAT_MBYTE
456 n = (*mb_ptr2len)(p);
457#else
458 n = 1;
459#endif
460 p += n;
461 l -= n;
462 }
463}
464
465/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200466 * Load library "name".
467 */
468 HINSTANCE
469vimLoadLib(char *name)
470{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200471 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200472
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200473 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
474 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475 if (exe_path == NULL)
476 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200477 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200479 WCHAR old_dirw[MAXPATHL];
480
481 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
482 {
483 /* Change directory to where the executable is, both to make
484 * sure we find a .dll there and to avoid looking for a .dll
485 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100486 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 dll = LoadLibrary(name);
488 SetCurrentDirectoryW(old_dirw);
489 return dll;
490 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200491 }
492 return dll;
493}
494
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100495#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
496/*
497 * Get related information about 'funcname' which is imported by 'hInst'.
498 * If 'info' is 0, return the function address.
499 * If 'info' is 1, return the module name which the function is imported from.
500 */
501 static void *
502get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
503{
504 PBYTE pImage = (PBYTE)hInst;
505 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
506 PIMAGE_NT_HEADERS pPE;
507 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
508 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
509 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
510 PIMAGE_IMPORT_BY_NAME pImpName;
511
512 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
513 return NULL;
514 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
515 if (pPE->Signature != IMAGE_NT_SIGNATURE)
516 return NULL;
517 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
518 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
519 .VirtualAddress);
520 for (; pImpDesc->FirstThunk; ++pImpDesc)
521 {
522 if (!pImpDesc->OriginalFirstThunk)
523 continue;
524 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
525 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
526 for (; pIAT->u1.Function; ++pIAT, ++pINT)
527 {
528 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
529 continue;
530 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
531 + (UINT_PTR)(pINT->u1.AddressOfData));
532 if (strcmp((char *)pImpName->Name, funcname) == 0)
533 {
534 switch (info)
535 {
536 case 0:
537 return (void *)pIAT->u1.Function;
538 case 1:
539 return (void *)(pImage + pImpDesc->Name);
540 default:
541 return NULL;
542 }
543 }
544 }
545 }
546 return NULL;
547}
548
549/*
550 * Get the module handle which 'funcname' in 'hInst' is imported from.
551 */
552 HINSTANCE
553find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
554{
555 char *modulename;
556
557 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
558 if (modulename != NULL)
559 return GetModuleHandleA(modulename);
560 return NULL;
561}
562
563/*
564 * Get the address of 'funcname' which is imported by 'hInst' DLL.
565 */
566 void *
567get_dll_import_func(HINSTANCE hInst, const char *funcname)
568{
569 return get_imported_func_info(hInst, funcname, 0);
570}
571#endif
572
Bram Moolenaar071d4272004-06-13 20:20:40 +0000573#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
574# ifndef GETTEXT_DLL
575# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100576# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000577# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200578/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000579static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200580static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000581static char *null_libintl_textdomain(const char *);
582static char *null_libintl_bindtextdomain(const char *, const char *);
583static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100584static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100585static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000586
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200587static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000588char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200589char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
590 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000591char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
592char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000593 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000594char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
595 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100596int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100597int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598
599 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100600dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601{
602 int i;
603 static struct
604 {
605 char *name;
606 FARPROC *ptr;
607 } libintl_entry[] =
608 {
609 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200610 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
612 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
613 {NULL, NULL}
614 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100615 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616
617 /* No need to initialize twice. */
618 if (hLibintlDLL)
619 return 1;
620 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100621 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100622#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100623 if (!hLibintlDLL)
624 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100625#endif
626 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000627 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200628 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000629 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200630 verbose_enter();
631 EMSG2(_(e_loadlib), GETTEXT_DLL);
632 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200634 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000635 }
636 for (i = 0; libintl_entry[i].name != NULL
637 && libintl_entry[i].ptr != NULL; ++i)
638 {
639 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
640 libintl_entry[i].name)) == NULL)
641 {
642 dyn_libintl_end();
643 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000644 {
645 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000646 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000647 verbose_leave();
648 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000649 return 0;
650 }
651 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000652
653 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000654 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000655 "bind_textdomain_codeset");
656 if (dyn_libintl_bind_textdomain_codeset == NULL)
657 dyn_libintl_bind_textdomain_codeset =
658 null_libintl_bind_textdomain_codeset;
659
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100660 /* _putenv() function for the libintl.dll is optional. */
661 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
662 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100663 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100664 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100665 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
666 }
667 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100668 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100669 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
670 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100671
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672 return 1;
673}
674
675 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100676dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000677{
678 if (hLibintlDLL)
679 FreeLibrary(hLibintlDLL);
680 hLibintlDLL = NULL;
681 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200682 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000683 dyn_libintl_textdomain = null_libintl_textdomain;
684 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000685 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100686 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100687 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688}
689
690 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000691null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692{
693 return (char*)msgid;
694}
695
696 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200697null_libintl_ngettext(
698 const char *msgid,
699 const char *msgid_plural,
700 unsigned long n)
701{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200702 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200703}
704
Bram Moolenaaree695f72016-08-03 22:08:45 +0200705 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100706null_libintl_bindtextdomain(
707 const char *domainname UNUSED,
708 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000709{
710 return NULL;
711}
712
713 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100714null_libintl_bind_textdomain_codeset(
715 const char *domainname UNUSED,
716 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000717{
718 return NULL;
719}
720
721 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100722null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000723{
724 return NULL;
725}
726
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200727 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100728null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100729{
730 return 0;
731}
732
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200733 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100734null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100735{
736 return 0;
737}
738
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739#endif /* DYNAMIC_GETTEXT */
740
741/* This symbol is not defined in older versions of the SDK or Visual C++ */
742
743#ifndef VER_PLATFORM_WIN32_WINDOWS
744# define VER_PLATFORM_WIN32_WINDOWS 1
745#endif
746
747DWORD g_PlatformId;
748
749#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100750# ifndef PROTO
751# include <aclapi.h>
752# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200753# ifndef PROTECTED_DACL_SECURITY_INFORMATION
754# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
755# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000756#endif
757
Bram Moolenaar27515922013-06-29 15:36:26 +0200758#ifdef HAVE_ACL
759/*
760 * Enables or disables the specified privilege.
761 */
762 static BOOL
763win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
764{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100765 BOOL bResult;
766 LUID luid;
767 HANDLE hToken;
768 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200769
770 if (!OpenProcessToken(GetCurrentProcess(),
771 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
772 return FALSE;
773
774 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
775 {
776 CloseHandle(hToken);
777 return FALSE;
778 }
779
Bram Moolenaar45500912014-07-09 20:51:07 +0200780 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200781 tokenPrivileges.Privileges[0].Luid = luid;
782 tokenPrivileges.Privileges[0].Attributes = bEnable ?
783 SE_PRIVILEGE_ENABLED : 0;
784
785 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
786 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
787
788 CloseHandle(hToken);
789
790 return bResult && GetLastError() == ERROR_SUCCESS;
791}
792#endif
793
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794/*
795 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
796 * VER_PLATFORM_WIN32_WINDOWS (Win95).
797 */
798 void
799PlatformId(void)
800{
801 static int done = FALSE;
802
803 if (!done)
804 {
805 OSVERSIONINFO ovi;
806
807 ovi.dwOSVersionInfoSize = sizeof(ovi);
808 GetVersionEx(&ovi);
809
810 g_PlatformId = ovi.dwPlatformId;
811
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100812 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
813 || ovi.dwMajorVersion > 6)
814 win8_or_later = TRUE;
815
Bram Moolenaar071d4272004-06-13 20:20:40 +0000816#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200817 /* Enable privilege for getting or setting SACLs. */
818 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000819#endif
820 done = TRUE;
821 }
822}
823
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824#ifndef FEAT_GUI_W32
825
826#define SHIFT (SHIFT_PRESSED)
827#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
828#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
829#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
830
831
832/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
833 * We map function keys to their ANSI terminal equivalents, as produced
834 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
835 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
836 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
837 * combinations of function/arrow/etc keys.
838 */
839
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000840static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000841{
842 WORD wVirtKey;
843 BOOL fAnsiKey;
844 int chAlone;
845 int chShift;
846 int chCtrl;
847 int chAlt;
848} VirtKeyMap[] =
849{
850
851/* Key ANSI alone shift ctrl alt */
852 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
853
854 { VK_F1, TRUE, ';', 'T', '^', 'h', },
855 { VK_F2, TRUE, '<', 'U', '_', 'i', },
856 { VK_F3, TRUE, '=', 'V', '`', 'j', },
857 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
858 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
859 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
860 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
861 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
862 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
863 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
864 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
865 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
866
867 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
868 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
869 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
870 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
871 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
872 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
873 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
874 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
875 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
876 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
877
878 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
879
880#if 0
881 /* Most people don't have F13-F20, but what the hell... */
882 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
883 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
884 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
885 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
886 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
887 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
888 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
889 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
890#endif
891 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
892 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
893 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
894 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
895
896 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
897 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
898 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
899 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
900 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
901 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
902 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
903 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
904 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
905 /* Sorry, out of number space! <negri>*/
906 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
907
908};
909
910
911#ifdef _MSC_VER
912// The ToAscii bug destroys several registers. Need to turn off optimization
913// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000914# pragma warning(push)
915# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000916# pragma optimize("", off)
917#endif
918
919#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200920# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200922# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000923#endif
924
925/* The return code indicates key code size. */
926 static int
927#ifdef __BORLANDC__
928 __stdcall
929#endif
930win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000931 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932{
933 UINT uMods = pker->dwControlKeyState;
934 static int s_iIsDead = 0;
935 static WORD awAnsiCode[2];
936 static BYTE abKeystate[256];
937
938
939 if (s_iIsDead == 2)
940 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200941 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942 s_iIsDead = 0;
943 return 1;
944 }
945
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200946 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000947 return 1;
948
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200949 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200952 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953
954 if (uMods & SHIFT_PRESSED)
955 abKeystate[VK_SHIFT] = 0x80;
956 if (uMods & CAPSLOCK_ON)
957 abKeystate[VK_CAPITAL] = 1;
958
959 if ((uMods & ALT_GR) == ALT_GR)
960 {
961 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
962 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
963 }
964
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200965 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
966 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967
968 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200969 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970
971 return s_iIsDead;
972}
973
974#ifdef _MSC_VER
975/* MUST switch optimization on again here, otherwise a call to
976 * decode_key_event() may crash (e.g. when hitting caps-lock) */
977# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000978# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979
980# if (_MSC_VER < 1100)
981/* MUST turn off global optimisation for this next function, or
982 * pressing ctrl-minus in insert mode crashes Vim when built with
983 * VC4.1. -- negri. */
984# pragma optimize("g", off)
985# endif
986#endif
987
988static BOOL g_fJustGotFocus = FALSE;
989
990/*
991 * Decode a KEY_EVENT into one or two keystrokes
992 */
993 static BOOL
994decode_key_event(
995 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200996 WCHAR *pch,
997 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998 int *pmodifiers,
999 BOOL fDoPost)
1000{
1001 int i;
1002 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1003
1004 *pch = *pch2 = NUL;
1005 g_fJustGotFocus = FALSE;
1006
1007 /* ignore key up events */
1008 if (!pker->bKeyDown)
1009 return FALSE;
1010
1011 /* ignore some keystrokes */
1012 switch (pker->wVirtualKeyCode)
1013 {
1014 /* modifiers */
1015 case VK_SHIFT:
1016 case VK_CONTROL:
1017 case VK_MENU: /* Alt key */
1018 return FALSE;
1019
1020 default:
1021 break;
1022 }
1023
1024 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001025 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026 {
1027 /* Ctrl-6 is Ctrl-^ */
1028 if (pker->wVirtualKeyCode == '6')
1029 {
1030 *pch = Ctrl_HAT;
1031 return TRUE;
1032 }
1033 /* Ctrl-2 is Ctrl-@ */
1034 else if (pker->wVirtualKeyCode == '2')
1035 {
1036 *pch = NUL;
1037 return TRUE;
1038 }
1039 /* Ctrl-- is Ctrl-_ */
1040 else if (pker->wVirtualKeyCode == 0xBD)
1041 {
1042 *pch = Ctrl__;
1043 return TRUE;
1044 }
1045 }
1046
1047 /* Shift-TAB */
1048 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1049 {
1050 *pch = K_NUL;
1051 *pch2 = '\017';
1052 return TRUE;
1053 }
1054
1055 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1056 {
1057 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1058 {
1059 if (nModifs == 0)
1060 *pch = VirtKeyMap[i].chAlone;
1061 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1062 *pch = VirtKeyMap[i].chShift;
1063 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1064 *pch = VirtKeyMap[i].chCtrl;
1065 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1066 *pch = VirtKeyMap[i].chAlt;
1067
1068 if (*pch != 0)
1069 {
1070 if (VirtKeyMap[i].fAnsiKey)
1071 {
1072 *pch2 = *pch;
1073 *pch = K_NUL;
1074 }
1075
1076 return TRUE;
1077 }
1078 }
1079 }
1080
1081 i = win32_kbd_patch_key(pker);
1082
1083 if (i < 0)
1084 *pch = NUL;
1085 else
1086 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001087 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088
1089 if (pmodifiers != NULL)
1090 {
1091 /* Pass on the ALT key as a modifier, but only when not combined
1092 * with CTRL (which is ALTGR). */
1093 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1094 *pmodifiers |= MOD_MASK_ALT;
1095
1096 /* Pass on SHIFT only for special keys, because we don't know when
1097 * it's already included with the character. */
1098 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1099 *pmodifiers |= MOD_MASK_SHIFT;
1100
1101 /* Pass on CTRL only for non-special keys, because we don't know
1102 * when it's already included with the character. And not when
1103 * combined with ALT (which is ALTGR). */
1104 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1105 && *pch >= 0x20 && *pch < 0x80)
1106 *pmodifiers |= MOD_MASK_CTRL;
1107 }
1108 }
1109
1110 return (*pch != NUL);
1111}
1112
1113#ifdef _MSC_VER
1114# pragma optimize("", on)
1115#endif
1116
1117#endif /* FEAT_GUI_W32 */
1118
1119
1120#ifdef FEAT_MOUSE
1121
1122/*
1123 * For the GUI the mouse handling is in gui_w32.c.
1124 */
1125# ifdef FEAT_GUI_W32
1126 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001127mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128{
1129}
1130# else
1131static int g_fMouseAvail = FALSE; /* mouse present */
1132static int g_fMouseActive = FALSE; /* mouse enabled */
1133static int g_nMouseClick = -1; /* mouse status */
1134static int g_xMouse; /* mouse x coordinate */
1135static int g_yMouse; /* mouse y coordinate */
1136
1137/*
1138 * Enable or disable mouse input
1139 */
1140 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001141mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142{
1143 DWORD cmodein;
1144
1145 if (!g_fMouseAvail)
1146 return;
1147
1148 g_fMouseActive = on;
1149 GetConsoleMode(g_hConIn, &cmodein);
1150
1151 if (g_fMouseActive)
1152 cmodein |= ENABLE_MOUSE_INPUT;
1153 else
1154 cmodein &= ~ENABLE_MOUSE_INPUT;
1155
1156 SetConsoleMode(g_hConIn, cmodein);
1157}
1158
Bram Moolenaar157d8132018-03-06 17:09:20 +01001159
1160#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1161/*
1162 * Called when 'balloonevalterm' changed.
1163 */
1164 void
1165mch_bevalterm_changed(void)
1166{
1167 mch_setmouse(g_fMouseActive);
1168}
1169#endif
1170
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171/*
1172 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1173 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1174 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1175 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1176 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1177 * and we return the mouse position in g_xMouse and g_yMouse.
1178 *
1179 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1180 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1181 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1182 *
1183 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1184 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1185 *
1186 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1187 * moves, even if it stays within the same character cell. We ignore
1188 * all MOUSE_MOVED messages if the position hasn't really changed, and
1189 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1190 * we're only interested in MOUSE_DRAG).
1191 *
1192 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1193 * 2-button mouses by pressing the left & right buttons simultaneously.
1194 * In practice, it's almost impossible to click both at the same time,
1195 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1196 * in such cases, if the user is clicking quickly.
1197 */
1198 static BOOL
1199decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001200 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001201{
1202 static int s_nOldButton = -1;
1203 static int s_nOldMouseClick = -1;
1204 static int s_xOldMouse = -1;
1205 static int s_yOldMouse = -1;
1206 static linenr_T s_old_topline = 0;
1207#ifdef FEAT_DIFF
1208 static int s_old_topfill = 0;
1209#endif
1210 static int s_cClicks = 1;
1211 static BOOL s_fReleased = TRUE;
1212 static DWORD s_dwLastClickTime = 0;
1213 static BOOL s_fNextIsMiddle = FALSE;
1214
1215 static DWORD cButtons = 0; /* number of buttons supported */
1216
1217 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1218 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1219 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1220 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1221
1222 int nButton;
1223
1224 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1225 cButtons = 2;
1226
1227 if (!g_fMouseAvail || !g_fMouseActive)
1228 {
1229 g_nMouseClick = -1;
1230 return FALSE;
1231 }
1232
1233 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1234 if (g_fJustGotFocus)
1235 {
1236 g_fJustGotFocus = FALSE;
1237 return FALSE;
1238 }
1239
1240 /* unprocessed mouse click? */
1241 if (g_nMouseClick != -1)
1242 return TRUE;
1243
1244 nButton = -1;
1245 g_xMouse = pmer->dwMousePosition.X;
1246 g_yMouse = pmer->dwMousePosition.Y;
1247
1248 if (pmer->dwEventFlags == MOUSE_MOVED)
1249 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001250 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251 * events even when the mouse moves only within a char cell.) */
1252 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1253 return FALSE;
1254 }
1255
1256 /* If no buttons are pressed... */
1257 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1258 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001259 nButton = MOUSE_RELEASE;
1260
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1262 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001263 {
1264#ifdef FEAT_BEVAL_TERM
1265 /* do return mouse move events when we want them */
1266 if (p_bevalterm)
1267 nButton = MOUSE_DRAG;
1268 else
1269#endif
1270 return FALSE;
1271 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001272
Bram Moolenaar071d4272004-06-13 20:20:40 +00001273 s_fReleased = TRUE;
1274 }
1275 else /* one or more buttons pressed */
1276 {
1277 /* on a 2-button mouse, hold down left and right buttons
1278 * simultaneously to get MIDDLE. */
1279
1280 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1281 {
1282 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1283
1284 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001285 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001286 if (dwLR == LEFT || dwLR == RIGHT)
1287 {
1288 for (;;)
1289 {
1290 /* wait a short time for next input event */
1291 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1292 != WAIT_OBJECT_0)
1293 break;
1294 else
1295 {
1296 DWORD cRecords = 0;
1297 INPUT_RECORD ir;
1298 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1299
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001300 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001301
1302 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1303 || !(pmer2->dwButtonState & LEFT_RIGHT))
1304 break;
1305 else
1306 {
1307 if (pmer2->dwEventFlags != MOUSE_MOVED)
1308 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001309 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001310
1311 return decode_mouse_event(pmer2);
1312 }
1313 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1314 s_yOldMouse == pmer2->dwMousePosition.Y)
1315 {
1316 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001317 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001318
1319 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001320 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001321
1322 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1323 break;
1324 }
1325 else
1326 break;
1327 }
1328 }
1329 }
1330 }
1331 }
1332
1333 if (s_fNextIsMiddle)
1334 {
1335 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1336 ? MOUSE_DRAG : MOUSE_MIDDLE;
1337 s_fNextIsMiddle = FALSE;
1338 }
1339 else if (cButtons == 2 &&
1340 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1341 {
1342 nButton = MOUSE_MIDDLE;
1343
1344 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1345 {
1346 s_fNextIsMiddle = TRUE;
1347 nButton = MOUSE_RELEASE;
1348 }
1349 }
1350 else if ((pmer->dwButtonState & LEFT) == LEFT)
1351 nButton = MOUSE_LEFT;
1352 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1353 nButton = MOUSE_MIDDLE;
1354 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1355 nButton = MOUSE_RIGHT;
1356
1357 if (! s_fReleased && ! s_fNextIsMiddle
1358 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1359 return FALSE;
1360
1361 s_fReleased = s_fNextIsMiddle;
1362 }
1363
1364 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1365 {
1366 /* button pressed or released, without mouse moving */
1367 if (nButton != -1 && nButton != MOUSE_RELEASE)
1368 {
1369 DWORD dwCurrentTime = GetTickCount();
1370
1371 if (s_xOldMouse != g_xMouse
1372 || s_yOldMouse != g_yMouse
1373 || s_nOldButton != nButton
1374 || s_old_topline != curwin->w_topline
1375#ifdef FEAT_DIFF
1376 || s_old_topfill != curwin->w_topfill
1377#endif
1378 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1379 {
1380 s_cClicks = 1;
1381 }
1382 else if (++s_cClicks > 4)
1383 {
1384 s_cClicks = 1;
1385 }
1386
1387 s_dwLastClickTime = dwCurrentTime;
1388 }
1389 }
1390 else if (pmer->dwEventFlags == MOUSE_MOVED)
1391 {
1392 if (nButton != -1 && nButton != MOUSE_RELEASE)
1393 nButton = MOUSE_DRAG;
1394
1395 s_cClicks = 1;
1396 }
1397
1398 if (nButton == -1)
1399 return FALSE;
1400
1401 if (nButton != MOUSE_RELEASE)
1402 s_nOldButton = nButton;
1403
1404 g_nMouseClick = nButton;
1405
1406 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1407 g_nMouseClick |= MOUSE_SHIFT;
1408 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1409 g_nMouseClick |= MOUSE_CTRL;
1410 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1411 g_nMouseClick |= MOUSE_ALT;
1412
1413 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1414 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1415
1416 /* only pass on interesting (i.e., different) mouse events */
1417 if (s_xOldMouse == g_xMouse
1418 && s_yOldMouse == g_yMouse
1419 && s_nOldMouseClick == g_nMouseClick)
1420 {
1421 g_nMouseClick = -1;
1422 return FALSE;
1423 }
1424
1425 s_xOldMouse = g_xMouse;
1426 s_yOldMouse = g_yMouse;
1427 s_old_topline = curwin->w_topline;
1428#ifdef FEAT_DIFF
1429 s_old_topfill = curwin->w_topfill;
1430#endif
1431 s_nOldMouseClick = g_nMouseClick;
1432
1433 return TRUE;
1434}
1435
1436# endif /* FEAT_GUI_W32 */
1437#endif /* FEAT_MOUSE */
1438
1439
1440#ifdef MCH_CURSOR_SHAPE
1441/*
1442 * Set the shape of the cursor.
1443 * 'thickness' can be from 1 (thin) to 99 (block)
1444 */
1445 static void
1446mch_set_cursor_shape(int thickness)
1447{
1448 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1449 ConsoleCursorInfo.dwSize = thickness;
1450 ConsoleCursorInfo.bVisible = s_cursor_visible;
1451
1452 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1453 if (s_cursor_visible)
1454 SetConsoleCursorPosition(g_hConOut, g_coord);
1455}
1456
1457 void
1458mch_update_cursor(void)
1459{
1460 int idx;
1461 int thickness;
1462
1463 /*
1464 * How the cursor is drawn depends on the current mode.
1465 */
1466 idx = get_shape_idx(FALSE);
1467
1468 if (shape_table[idx].shape == SHAPE_BLOCK)
1469 thickness = 99; /* 100 doesn't work on W95 */
1470 else
1471 thickness = shape_table[idx].percentage;
1472 mch_set_cursor_shape(thickness);
1473}
1474#endif
1475
1476#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1477/*
1478 * Handle FOCUS_EVENT.
1479 */
1480 static void
1481handle_focus_event(INPUT_RECORD ir)
1482{
1483 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1484 ui_focus_change((int)g_fJustGotFocus);
1485}
1486
1487/*
1488 * Wait until console input from keyboard or mouse is available,
1489 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001490 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491 * Return TRUE if something is available FALSE if not.
1492 */
1493 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001494WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495{
1496 DWORD dwNow = 0, dwEndTime = 0;
1497 INPUT_RECORD ir;
1498 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001499 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001500#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001501 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001502#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503
1504 if (msec > 0)
1505 /* Wait until the specified time has elapsed. */
1506 dwEndTime = GetTickCount() + msec;
1507 else if (msec < 0)
1508 /* Wait forever. */
1509 dwEndTime = INFINITE;
1510
1511 /* We need to loop until the end of the time period, because
1512 * we might get multiple unusable mouse events in that time.
1513 */
1514 for (;;)
1515 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001516 // Only process messages when waiting.
1517 if (msec != 0)
1518 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001519#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001520 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001521#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001522#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001523 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001524#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001526 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001527#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001528 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001529
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530 if (0
1531#ifdef FEAT_MOUSE
1532 || g_nMouseClick != -1
1533#endif
1534#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001535 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536#endif
1537 )
1538 return TRUE;
1539
1540 if (msec > 0)
1541 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001542 /* If the specified wait time has passed, return. Beware that
1543 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001545 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 break;
1547 }
1548 if (msec != 0)
1549 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001550 DWORD dwWaitTime = dwEndTime - dwNow;
1551
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001552#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001553 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001554 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001555 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001556 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001557 /* If there is readahead then parse_queued_messages() timed out
1558 * and we should call it again soon. */
1559 if (channel_any_readahead())
1560 dwWaitTime = 10;
1561 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001562#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001563#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001564 if (p_beval && dwWaitTime > 100)
1565 /* The 'balloonexpr' may indirectly invoke a callback while
1566 * waiting for a character, need to check often. */
1567 dwWaitTime = 100;
1568#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001569#ifdef FEAT_MZSCHEME
1570 if (mzthreads_allowed() && p_mzq > 0
1571 && (msec < 0 || (long)dwWaitTime > p_mzq))
1572 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1573#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001574#ifdef FEAT_TIMERS
1575 {
1576 long due_time;
1577
1578 /* When waiting very briefly don't trigger timers. */
1579 if (dwWaitTime > 10)
1580 {
1581 /* Trigger timers and then get the time in msec until the
1582 * next one is due. Wait up to that time. */
1583 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001584 if (typebuf.tb_change_cnt != tb_change_cnt)
1585 {
1586 /* timer may have used feedkeys() */
1587 return FALSE;
1588 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001589 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1590 dwWaitTime = due_time;
1591 }
1592 }
1593#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594#ifdef FEAT_CLIENTSERVER
1595 /* Wait for either an event on the console input or a message in
1596 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001597 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001598 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001600 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001601#endif
1602 continue;
1603 }
1604
1605 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001606 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607
1608#ifdef FEAT_MBYTE_IME
1609 if (State & CMDLINE && msg_row == Rows - 1)
1610 {
1611 CONSOLE_SCREEN_BUFFER_INFO csbi;
1612
1613 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1614 {
1615 if (csbi.dwCursorPosition.Y != msg_row)
1616 {
1617 /* The screen is now messed up, must redraw the
1618 * command line and later all the windows. */
1619 redraw_all_later(CLEAR);
1620 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1621 redrawcmd();
1622 }
1623 }
1624 }
1625#endif
1626
1627 if (cRecords > 0)
1628 {
1629 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1630 {
1631#ifdef FEAT_MBYTE_IME
1632 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1633 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001634 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001635 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1636 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001637 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638 continue;
1639 }
1640#endif
1641 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1642 NULL, FALSE))
1643 return TRUE;
1644 }
1645
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001646 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647
1648 if (ir.EventType == FOCUS_EVENT)
1649 handle_focus_event(ir);
1650 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001651 {
1652 /* Only call shell_resized() when the size actually change to
1653 * avoid the screen is cleard. */
1654 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1655 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1656 shell_resized();
1657 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658#ifdef FEAT_MOUSE
1659 else if (ir.EventType == MOUSE_EVENT
1660 && decode_mouse_event(&ir.Event.MouseEvent))
1661 return TRUE;
1662#endif
1663 }
1664 else if (msec == 0)
1665 break;
1666 }
1667
1668#ifdef FEAT_CLIENTSERVER
1669 /* Something might have been received while we were waiting. */
1670 if (input_available())
1671 return TRUE;
1672#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001673
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674 return FALSE;
1675}
1676
1677#ifndef FEAT_GUI_MSWIN
1678/*
1679 * return non-zero if a character is available
1680 */
1681 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001682mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001684 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001686
1687# if defined(FEAT_TERMINAL) || defined(PROTO)
1688/*
1689 * Check for any pending input or messages.
1690 */
1691 int
1692mch_check_messages(void)
1693{
1694 return WaitForChar(0L, TRUE);
1695}
1696# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697#endif
1698
1699/*
1700 * Create the console input. Used when reading stdin doesn't work.
1701 */
1702 static void
1703create_conin(void)
1704{
1705 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1706 FILE_SHARE_READ|FILE_SHARE_WRITE,
1707 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001708 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 did_create_conin = TRUE;
1710}
1711
1712/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001713 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001714 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001715 static WCHAR
1716tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001718 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001719
1720 for (;;)
1721 {
1722 INPUT_RECORD ir;
1723 DWORD cRecords = 0;
1724
1725#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001726 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001727 if (input_available())
1728 return 0;
1729# ifdef FEAT_MOUSE
1730 if (g_nMouseClick != -1)
1731 return 0;
1732# endif
1733#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001734 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735 {
1736 if (did_create_conin)
1737 read_error_exit();
1738 create_conin();
1739 continue;
1740 }
1741
1742 if (ir.EventType == KEY_EVENT)
1743 {
1744 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1745 pmodifiers, TRUE))
1746 return ch;
1747 }
1748 else if (ir.EventType == FOCUS_EVENT)
1749 handle_focus_event(ir);
1750 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1751 shell_resized();
1752#ifdef FEAT_MOUSE
1753 else if (ir.EventType == MOUSE_EVENT)
1754 {
1755 if (decode_mouse_event(&ir.Event.MouseEvent))
1756 return 0;
1757 }
1758#endif
1759 }
1760}
1761#endif /* !FEAT_GUI_W32 */
1762
1763
1764/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001765 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001766 * Get one or more characters from the keyboard or the mouse.
1767 * If time == 0, do not wait for characters.
1768 * If time == n, wait a short time for characters.
1769 * If time == -1, wait forever for characters.
1770 * Returns the number of characters read into buf.
1771 */
1772 int
1773mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001774 char_u *buf UNUSED,
1775 int maxlen UNUSED,
1776 long time UNUSED,
1777 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001778{
1779#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1780
1781 int len;
1782 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783#define TYPEAHEADLEN 20
1784 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1785 static int typeaheadlen = 0;
1786
1787 /* First use any typeahead that was kept because "buf" was too small. */
1788 if (typeaheadlen > 0)
1789 goto theend;
1790
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 if (time >= 0)
1792 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001793 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795 }
1796 else /* time == -1, wait forever */
1797 {
1798 mch_set_winsize_now(); /* Allow winsize changes from now on */
1799
Bram Moolenaar3918c952005-03-15 22:34:55 +00001800 /*
1801 * If there is no character available within 2 seconds (default)
1802 * write the autoscript file to disk. Or cause the CursorHold event
1803 * to be triggered.
1804 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001805 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001807 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001808 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001809 buf[0] = K_SPECIAL;
1810 buf[1] = KS_EXTRA;
1811 buf[2] = (int)KE_CURSORHOLD;
1812 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001814 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001815 }
1816 }
1817
1818 /*
1819 * Try to read as many characters as there are, until the buffer is full.
1820 */
1821
1822 /* we will get at least one key. Get more if they are available. */
1823 g_fCBrkPressed = FALSE;
1824
1825#ifdef MCH_WRITE_DUMP
1826 if (fdDump)
1827 fputc('[', fdDump);
1828#endif
1829
1830 /* Keep looping until there is something in the typeahead buffer and more
1831 * to get and still room in the buffer (up to two bytes for a char and
1832 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001833 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001834 && typeaheadlen + 5 <= TYPEAHEADLEN)
1835 {
1836 if (typebuf_changed(tb_change_cnt))
1837 {
1838 /* "buf" may be invalid now if a client put something in the
1839 * typeahead buffer and "buf" is in the typeahead buffer. */
1840 typeaheadlen = 0;
1841 break;
1842 }
1843#ifdef FEAT_MOUSE
1844 if (g_nMouseClick != -1)
1845 {
1846# ifdef MCH_WRITE_DUMP
1847 if (fdDump)
1848 fprintf(fdDump, "{%02x @ %d, %d}",
1849 g_nMouseClick, g_xMouse, g_yMouse);
1850# endif
1851 typeahead[typeaheadlen++] = ESC + 128;
1852 typeahead[typeaheadlen++] = 'M';
1853 typeahead[typeaheadlen++] = g_nMouseClick;
1854 typeahead[typeaheadlen++] = g_xMouse + '!';
1855 typeahead[typeaheadlen++] = g_yMouse + '!';
1856 g_nMouseClick = -1;
1857 }
1858 else
1859#endif
1860 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001861 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862 int modifiers = 0;
1863
1864 c = tgetch(&modifiers, &ch2);
1865
1866 if (typebuf_changed(tb_change_cnt))
1867 {
1868 /* "buf" may be invalid now if a client put something in the
1869 * typeahead buffer and "buf" is in the typeahead buffer. */
1870 typeaheadlen = 0;
1871 break;
1872 }
1873
1874 if (c == Ctrl_C && ctrl_c_interrupts)
1875 {
1876#if defined(FEAT_CLIENTSERVER)
1877 trash_input_buf();
1878#endif
1879 got_int = TRUE;
1880 }
1881
1882#ifdef FEAT_MOUSE
1883 if (g_nMouseClick == -1)
1884#endif
1885 {
1886 int n = 1;
1887
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001888#ifdef FEAT_MBYTE
1889 if (ch2 == NUL)
1890 {
1891 int i;
1892 char_u *p;
1893 WCHAR ch[2];
1894
1895 ch[0] = c;
1896 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1897 {
1898 ch[1] = tgetch(&modifiers, &ch2);
1899 n++;
1900 }
1901 p = utf16_to_enc(ch, &n);
1902 if (p != NULL)
1903 {
1904 for (i = 0; i < n; i++)
1905 typeahead[typeaheadlen + i] = p[i];
1906 vim_free(p);
1907 }
1908 }
1909 else
1910#endif
1911 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912 if (ch2 != NUL)
1913 {
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001914 if (c == K_NUL && (ch2 & 0xff00) != 0)
1915 {
1916 /* fAnsiKey with modifier keys */
1917 typeahead[typeaheadlen + n] = (char_u)ch2;
1918 n++;
1919 }
1920 else
1921 {
1922 typeahead[typeaheadlen + n] = 3;
1923 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1924 n += 2;
1925 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001926 }
1927
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 /* Use the ALT key to set the 8th bit of the character
1929 * when it's one byte, the 8th bit isn't set yet and not
1930 * using a double-byte encoding (would become a lead
1931 * byte). */
1932 if ((modifiers & MOD_MASK_ALT)
1933 && n == 1
1934 && (typeahead[typeaheadlen] & 0x80) == 0
1935#ifdef FEAT_MBYTE
1936 && !enc_dbcs
1937#endif
1938 )
1939 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001940#ifdef FEAT_MBYTE
1941 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1942 typeahead + typeaheadlen);
1943#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001945#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001946 modifiers &= ~MOD_MASK_ALT;
1947 }
1948
1949 if (modifiers != 0)
1950 {
1951 /* Prepend modifiers to the character. */
1952 mch_memmove(typeahead + typeaheadlen + 3,
1953 typeahead + typeaheadlen, n);
1954 typeahead[typeaheadlen++] = K_SPECIAL;
1955 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1956 typeahead[typeaheadlen++] = modifiers;
1957 }
1958
1959 typeaheadlen += n;
1960
1961#ifdef MCH_WRITE_DUMP
1962 if (fdDump)
1963 fputc(c, fdDump);
1964#endif
1965 }
1966 }
1967 }
1968
1969#ifdef MCH_WRITE_DUMP
1970 if (fdDump)
1971 {
1972 fputs("]\n", fdDump);
1973 fflush(fdDump);
1974 }
1975#endif
1976
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977theend:
1978 /* Move typeahead to "buf", as much as fits. */
1979 len = 0;
1980 while (len < maxlen && typeaheadlen > 0)
1981 {
1982 buf[len++] = typeahead[0];
1983 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1984 }
1985 return len;
1986
1987#else /* FEAT_GUI_W32 */
1988 return 0;
1989#endif /* FEAT_GUI_W32 */
1990}
1991
Bram Moolenaar82881492012-11-20 16:53:39 +01001992#ifndef PROTO
1993# ifndef __MINGW32__
1994# include <shellapi.h> /* required for FindExecutable() */
1995# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001996#endif
1997
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001998/*
Bram Moolenaar43663192017-03-05 14:29:12 +01001999 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2000 * If "use_path" is FALSE: Return TRUE if "name" exists.
2001 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2002 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002003 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002004 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002006executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002007{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002008 char *dum;
2009 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002010 char *curpath, *newpath;
2011 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002012
Bram Moolenaar43663192017-03-05 14:29:12 +01002013 if (!use_path)
2014 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002015 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002016 {
2017 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002018 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002019 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002020 *path = vim_strsave((char_u *)name);
2021 else
2022 *path = FullName_save((char_u *)name, FALSE);
2023 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002024 return TRUE;
2025 }
2026 return FALSE;
2027 }
2028
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002029#ifdef FEAT_MBYTE
2030 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002031 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002032 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002033 WCHAR fnamew[_MAX_PATH];
2034 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002035 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002036
2037 if (p != NULL)
2038 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002039 wcurpath = _wgetenv(L"PATH");
2040 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2041 * sizeof(WCHAR));
2042 if (wnewpath == NULL)
2043 return FALSE;
2044 wcscpy(wnewpath, L".;");
2045 wcscat(wnewpath, wcurpath);
2046 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2047 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002048 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002049 if (n == 0)
2050 return FALSE;
2051 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2052 return FALSE;
2053 if (path != NULL)
2054 *path = utf16_to_enc(fnamew, NULL);
2055 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002056 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002058#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002059
2060 curpath = getenv("PATH");
2061 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2062 if (newpath == NULL)
2063 return FALSE;
2064 STRCPY(newpath, ".;");
2065 STRCAT(newpath, curpath);
2066 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2067 vim_free(newpath);
2068 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002069 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002070 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002071 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002072 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002073 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002074 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075}
2076
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002077#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002078 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002079/*
2080 * Bad parameter handler.
2081 *
2082 * Certain MS CRT functions will intentionally crash when passed invalid
2083 * parameters to highlight possible security holes. Setting this function as
2084 * the bad parameter handler will prevent the crash.
2085 *
2086 * In debug builds the parameters contain CRT information that might help track
2087 * down the source of a problem, but in non-debug builds the arguments are all
2088 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2089 * worth allowing these to make debugging of issues easier.
2090 */
2091 static void
2092bad_param_handler(const wchar_t *expression,
2093 const wchar_t *function,
2094 const wchar_t *file,
2095 unsigned int line,
2096 uintptr_t pReserved)
2097{
2098}
2099
2100# define SET_INVALID_PARAM_HANDLER \
2101 ((void)_set_invalid_parameter_handler(bad_param_handler))
2102#else
2103# define SET_INVALID_PARAM_HANDLER
2104#endif
2105
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106#ifdef FEAT_GUI_W32
2107
2108/*
2109 * GUI version of mch_init().
2110 */
2111 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002112mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002113{
2114#ifndef __MINGW32__
2115 extern int _fmode;
2116#endif
2117
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002118 /* Silently handle invalid parameters to CRT functions */
2119 SET_INVALID_PARAM_HANDLER;
2120
Bram Moolenaar071d4272004-06-13 20:20:40 +00002121 /* Let critical errors result in a failure, not in a dialog box. Required
2122 * for the timestamp test to work on removed floppies. */
2123 SetErrorMode(SEM_FAILCRITICALERRORS);
2124
2125 _fmode = O_BINARY; /* we do our own CR-LF translation */
2126
2127 /* Specify window size. Is there a place to get the default from? */
2128 Rows = 25;
2129 Columns = 80;
2130
2131 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132 {
2133 char_u vimrun_location[_MAX_PATH + 4];
2134
2135 /* First try in same directory as gvim.exe */
2136 STRCPY(vimrun_location, exe_name);
2137 STRCPY(gettail(vimrun_location), "vimrun.exe");
2138 if (mch_getperm(vimrun_location) >= 0)
2139 {
2140 if (*skiptowhite(vimrun_location) != NUL)
2141 {
2142 /* Enclose path with white space in double quotes. */
2143 mch_memmove(vimrun_location + 1, vimrun_location,
2144 STRLEN(vimrun_location) + 1);
2145 *vimrun_location = '"';
2146 STRCPY(gettail(vimrun_location), "vimrun\" ");
2147 }
2148 else
2149 STRCPY(gettail(vimrun_location), "vimrun ");
2150
2151 vimrun_path = (char *)vim_strsave(vimrun_location);
2152 s_dont_use_vimrun = FALSE;
2153 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002154 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002155 s_dont_use_vimrun = FALSE;
2156
2157 /* Don't give the warning for a missing vimrun.exe right now, but only
2158 * when vimrun was supposed to be used. Don't bother people that do
2159 * not need vimrun.exe. */
2160 if (s_dont_use_vimrun)
2161 need_vimrun_warning = TRUE;
2162 }
2163
2164 /*
2165 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2166 * Otherwise the default "findstr /n" is used.
2167 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002168 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002169 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2170
2171#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002172 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173#endif
2174}
2175
2176
2177#else /* FEAT_GUI_W32 */
2178
2179#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2180#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2181
2182/*
2183 * ClearConsoleBuffer()
2184 * Description:
2185 * Clears the entire contents of the console screen buffer, using the
2186 * specified attribute.
2187 * Returns:
2188 * TRUE on success
2189 */
2190 static BOOL
2191ClearConsoleBuffer(WORD wAttribute)
2192{
2193 CONSOLE_SCREEN_BUFFER_INFO csbi;
2194 COORD coord;
2195 DWORD NumCells, dummy;
2196
2197 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2198 return FALSE;
2199
2200 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2201 coord.X = 0;
2202 coord.Y = 0;
2203 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2204 coord, &dummy))
2205 {
2206 return FALSE;
2207 }
2208 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2209 coord, &dummy))
2210 {
2211 return FALSE;
2212 }
2213
2214 return TRUE;
2215}
2216
2217/*
2218 * FitConsoleWindow()
2219 * Description:
2220 * Checks if the console window will fit within given buffer dimensions.
2221 * Also, if requested, will shrink the window to fit.
2222 * Returns:
2223 * TRUE on success
2224 */
2225 static BOOL
2226FitConsoleWindow(
2227 COORD dwBufferSize,
2228 BOOL WantAdjust)
2229{
2230 CONSOLE_SCREEN_BUFFER_INFO csbi;
2231 COORD dwWindowSize;
2232 BOOL NeedAdjust = FALSE;
2233
2234 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2235 {
2236 /*
2237 * A buffer resize will fail if the current console window does
2238 * not lie completely within that buffer. To avoid this, we might
2239 * have to move and possibly shrink the window.
2240 */
2241 if (csbi.srWindow.Right >= dwBufferSize.X)
2242 {
2243 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2244 if (dwWindowSize.X > dwBufferSize.X)
2245 dwWindowSize.X = dwBufferSize.X;
2246 csbi.srWindow.Right = dwBufferSize.X - 1;
2247 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2248 NeedAdjust = TRUE;
2249 }
2250 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2251 {
2252 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2253 if (dwWindowSize.Y > dwBufferSize.Y)
2254 dwWindowSize.Y = dwBufferSize.Y;
2255 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2256 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2257 NeedAdjust = TRUE;
2258 }
2259 if (NeedAdjust && WantAdjust)
2260 {
2261 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2262 return FALSE;
2263 }
2264 return TRUE;
2265 }
2266
2267 return FALSE;
2268}
2269
2270typedef struct ConsoleBufferStruct
2271{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002272 BOOL IsValid;
2273 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002274 PCHAR_INFO Buffer;
2275 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002276 PSMALL_RECT Regions;
2277 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278} ConsoleBuffer;
2279
2280/*
2281 * SaveConsoleBuffer()
2282 * Description:
2283 * Saves important information about the console buffer, including the
2284 * actual buffer contents. The saved information is suitable for later
2285 * restoration by RestoreConsoleBuffer().
2286 * Returns:
2287 * TRUE if all information was saved; FALSE otherwise
2288 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2289 */
2290 static BOOL
2291SaveConsoleBuffer(
2292 ConsoleBuffer *cb)
2293{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002294 DWORD NumCells;
2295 COORD BufferCoord;
2296 SMALL_RECT ReadRegion;
2297 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002298 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002299
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300 if (cb == NULL)
2301 return FALSE;
2302
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002303 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304 {
2305 cb->IsValid = FALSE;
2306 return FALSE;
2307 }
2308 cb->IsValid = TRUE;
2309
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002310 /*
2311 * Allocate a buffer large enough to hold the entire console screen
2312 * buffer. If this ConsoleBuffer structure has already been initialized
2313 * with a buffer of the correct size, then just use that one.
2314 */
2315 if (!cb->IsValid || cb->Buffer == NULL ||
2316 cb->BufferSize.X != cb->Info.dwSize.X ||
2317 cb->BufferSize.Y != cb->Info.dwSize.Y)
2318 {
2319 cb->BufferSize.X = cb->Info.dwSize.X;
2320 cb->BufferSize.Y = cb->Info.dwSize.Y;
2321 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2322 vim_free(cb->Buffer);
2323 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2324 if (cb->Buffer == NULL)
2325 return FALSE;
2326 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327
2328 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002329 * We will now copy the console screen buffer into our buffer.
2330 * ReadConsoleOutput() seems to be limited as far as how much you
2331 * can read at a time. Empirically, this number seems to be about
2332 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2333 * in chunks until it is all copied. The chunks will all have the
2334 * same horizontal characteristics, so initialize them now. The
2335 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002336 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002337 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002338 ReadRegion.Left = 0;
2339 ReadRegion.Right = cb->Info.dwSize.X - 1;
2340 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002341
2342 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2343 if (cb->Regions == NULL || numregions != cb->NumRegions)
2344 {
2345 cb->NumRegions = numregions;
2346 vim_free(cb->Regions);
2347 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2348 if (cb->Regions == NULL)
2349 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002350 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002351 return FALSE;
2352 }
2353 }
2354
2355 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002357 /*
2358 * Read into position (0, Y) in our buffer.
2359 */
2360 BufferCoord.Y = Y;
2361 /*
2362 * Read the region whose top left corner is (0, Y) and whose bottom
2363 * right corner is (width - 1, Y + Y_incr - 1). This should define
2364 * a region of size width by Y_incr. Don't worry if this region is
2365 * too large for the remaining buffer; it will be cropped.
2366 */
2367 ReadRegion.Top = Y;
2368 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002369 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002370 cb->Buffer, /* our buffer */
2371 cb->BufferSize, /* dimensions of our buffer */
2372 BufferCoord, /* offset in our buffer */
2373 &ReadRegion)) /* region to save */
2374 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002375 VIM_CLEAR(cb->Buffer);
2376 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002377 return FALSE;
2378 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002379 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380 }
2381
2382 return TRUE;
2383}
2384
2385/*
2386 * RestoreConsoleBuffer()
2387 * Description:
2388 * Restores important information about the console buffer, including the
2389 * actual buffer contents, if desired. The information to restore is in
2390 * the same format used by SaveConsoleBuffer().
2391 * Returns:
2392 * TRUE on success
2393 */
2394 static BOOL
2395RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002396 ConsoleBuffer *cb,
2397 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002398{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002399 COORD BufferCoord;
2400 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002401 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002402
2403 if (cb == NULL || !cb->IsValid)
2404 return FALSE;
2405
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002406 /*
2407 * Before restoring the buffer contents, clear the current buffer, and
2408 * restore the cursor position and window information. Doing this now
2409 * prevents old buffer contents from "flashing" onto the screen.
2410 */
2411 if (RestoreScreen)
2412 ClearConsoleBuffer(cb->Info.wAttributes);
2413
2414 FitConsoleWindow(cb->Info.dwSize, TRUE);
2415 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2416 return FALSE;
2417 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2418 return FALSE;
2419
2420 if (!RestoreScreen)
2421 {
2422 /*
2423 * No need to restore the screen buffer contents, so we're done.
2424 */
2425 return TRUE;
2426 }
2427
2428 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2429 return FALSE;
2430 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2431 return FALSE;
2432
2433 /*
2434 * Restore the screen buffer contents.
2435 */
2436 if (cb->Buffer != NULL)
2437 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002438 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002439 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002440 BufferCoord.X = cb->Regions[i].Left;
2441 BufferCoord.Y = cb->Regions[i].Top;
2442 WriteRegion = cb->Regions[i];
2443 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2444 cb->Buffer, /* our buffer */
2445 cb->BufferSize, /* dimensions of our buffer */
2446 BufferCoord, /* offset in our buffer */
2447 &WriteRegion)) /* region to restore */
2448 {
2449 return FALSE;
2450 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002451 }
2452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002453
2454 return TRUE;
2455}
2456
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002457#define FEAT_RESTORE_ORIG_SCREEN
2458#ifdef FEAT_RESTORE_ORIG_SCREEN
2459static ConsoleBuffer g_cbOrig = { 0 };
2460#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461static ConsoleBuffer g_cbNonTermcap = { 0 };
2462static ConsoleBuffer g_cbTermcap = { 0 };
2463
2464#ifdef FEAT_TITLE
2465#ifdef __BORLANDC__
2466typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2467#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002468typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469#endif
2470char g_szOrigTitle[256] = { 0 };
2471HWND g_hWnd = NULL; /* also used in os_mswin.c */
2472static HICON g_hOrigIconSmall = NULL;
2473static HICON g_hOrigIcon = NULL;
2474static HICON g_hVimIcon = NULL;
2475static BOOL g_fCanChangeIcon = FALSE;
2476
2477/* ICON* are not defined in VC++ 4.0 */
2478#ifndef ICON_SMALL
2479#define ICON_SMALL 0
2480#endif
2481#ifndef ICON_BIG
2482#define ICON_BIG 1
2483#endif
2484/*
2485 * GetConsoleIcon()
2486 * Description:
2487 * Attempts to retrieve the small icon and/or the big icon currently in
2488 * use by a given window.
2489 * Returns:
2490 * TRUE on success
2491 */
2492 static BOOL
2493GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002494 HWND hWnd,
2495 HICON *phIconSmall,
2496 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497{
2498 if (hWnd == NULL)
2499 return FALSE;
2500
2501 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002502 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2503 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002505 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2506 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507 return TRUE;
2508}
2509
2510/*
2511 * SetConsoleIcon()
2512 * Description:
2513 * Attempts to change the small icon and/or the big icon currently in
2514 * use by a given window.
2515 * Returns:
2516 * TRUE on success
2517 */
2518 static BOOL
2519SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002520 HWND hWnd,
2521 HICON hIconSmall,
2522 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002524 if (hWnd == NULL)
2525 return FALSE;
2526
2527 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002528 SendMessage(hWnd, WM_SETICON,
2529 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002531 SendMessage(hWnd, WM_SETICON,
2532 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002533 return TRUE;
2534}
2535
2536/*
2537 * SaveConsoleTitleAndIcon()
2538 * Description:
2539 * Saves the current console window title in g_szOrigTitle, for later
2540 * restoration. Also, attempts to obtain a handle to the console window,
2541 * and use it to save the small and big icons currently in use by the
2542 * console window. This is not always possible on some versions of Windows;
2543 * nor is it possible when running Vim remotely using Telnet (since the
2544 * console window the user sees is owned by a remote process).
2545 */
2546 static void
2547SaveConsoleTitleAndIcon(void)
2548{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549 /* Save the original title. */
2550 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2551 return;
2552
2553 /*
2554 * Obtain a handle to the console window using GetConsoleWindow() from
2555 * KERNEL32.DLL; we need to handle in order to change the window icon.
2556 * This function only exists on NT-based Windows, starting with Windows
2557 * 2000. On older operating systems, we can't change the window icon
2558 * anyway.
2559 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002560 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002561 if (g_hWnd == NULL)
2562 return;
2563
2564 /* Save the original console window icon. */
2565 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2566 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2567 return;
2568
2569 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002570 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002571 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 if (g_hVimIcon != NULL)
2573 g_fCanChangeIcon = TRUE;
2574}
2575#endif
2576
2577static int g_fWindInitCalled = FALSE;
2578static int g_fTermcapMode = FALSE;
2579static CONSOLE_CURSOR_INFO g_cci;
2580static DWORD g_cmodein = 0;
2581static DWORD g_cmodeout = 0;
2582
2583/*
2584 * non-GUI version of mch_init().
2585 */
2586 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002587mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002589#ifndef FEAT_RESTORE_ORIG_SCREEN
2590 CONSOLE_SCREEN_BUFFER_INFO csbi;
2591#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592#ifndef __MINGW32__
2593 extern int _fmode;
2594#endif
2595
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002596 /* Silently handle invalid parameters to CRT functions */
2597 SET_INVALID_PARAM_HANDLER;
2598
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599 /* Let critical errors result in a failure, not in a dialog box. Required
2600 * for the timestamp test to work on removed floppies. */
2601 SetErrorMode(SEM_FAILCRITICALERRORS);
2602
2603 _fmode = O_BINARY; /* we do our own CR-LF translation */
2604 out_flush();
2605
2606 /* Obtain handles for the standard Console I/O devices */
2607 if (read_cmd_fd == 0)
2608 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2609 else
2610 create_conin();
2611 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2612
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002613#ifdef FEAT_RESTORE_ORIG_SCREEN
2614 /* Save the initial console buffer for later restoration */
2615 SaveConsoleBuffer(&g_cbOrig);
2616 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2617#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002619 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2620 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2621#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 if (cterm_normal_fg_color == 0)
2623 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2624 if (cterm_normal_bg_color == 0)
2625 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2626
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002627 // Fg and Bg color index nunmber at startup
2628 g_color_index_fg = g_attrDefault & 0xf;
2629 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2630
Bram Moolenaar071d4272004-06-13 20:20:40 +00002631 /* set termcap codes to current text attributes */
2632 update_tcap(g_attrCurrent);
2633
2634 GetConsoleCursorInfo(g_hConOut, &g_cci);
2635 GetConsoleMode(g_hConIn, &g_cmodein);
2636 GetConsoleMode(g_hConOut, &g_cmodeout);
2637
2638#ifdef FEAT_TITLE
2639 SaveConsoleTitleAndIcon();
2640 /*
2641 * Set both the small and big icons of the console window to Vim's icon.
2642 * Note that Vim presently only has one size of icon (32x32), but it
2643 * automatically gets scaled down to 16x16 when setting the small icon.
2644 */
2645 if (g_fCanChangeIcon)
2646 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2647#endif
2648
2649 ui_get_shellsize();
2650
2651#ifdef MCH_WRITE_DUMP
2652 fdDump = fopen("dump", "wt");
2653
2654 if (fdDump)
2655 {
2656 time_t t;
2657
2658 time(&t);
2659 fputs(ctime(&t), fdDump);
2660 fflush(fdDump);
2661 }
2662#endif
2663
2664 g_fWindInitCalled = TRUE;
2665
2666#ifdef FEAT_MOUSE
2667 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2668#endif
2669
2670#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002671 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002672#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002673
2674 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675}
2676
2677/*
2678 * non-GUI version of mch_exit().
2679 * Shut down and exit with status `r'
2680 * Careful: mch_exit() may be called before mch_init()!
2681 */
2682 void
2683mch_exit(int r)
2684{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002685 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002687 vtp_exit();
2688
Bram Moolenaar955f1982017-02-05 15:10:51 +01002689 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690 if (g_fWindInitCalled)
2691 settmode(TMODE_COOK);
2692
2693 ml_close_all(TRUE); /* remove all memfiles */
2694
2695 if (g_fWindInitCalled)
2696 {
2697#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002698 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002699 /*
2700 * Restore both the small and big icons of the console window to
2701 * what they were at startup. Don't do this when the window is
2702 * closed, Vim would hang here.
2703 */
2704 if (g_fCanChangeIcon && !g_fForceExit)
2705 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2706#endif
2707
2708#ifdef MCH_WRITE_DUMP
2709 if (fdDump)
2710 {
2711 time_t t;
2712
2713 time(&t);
2714 fputs(ctime(&t), fdDump);
2715 fclose(fdDump);
2716 }
2717 fdDump = NULL;
2718#endif
2719 }
2720
2721 SetConsoleCursorInfo(g_hConOut, &g_cci);
2722 SetConsoleMode(g_hConIn, g_cmodein);
2723 SetConsoleMode(g_hConOut, g_cmodeout);
2724
2725#ifdef DYNAMIC_GETTEXT
2726 dyn_libintl_end();
2727#endif
2728
2729 exit(r);
2730}
2731#endif /* !FEAT_GUI_W32 */
2732
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733/*
2734 * Do we have an interactive window?
2735 */
2736 int
2737mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002738 int argc UNUSED,
2739 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002740{
2741 get_exe_name();
2742
2743#ifdef FEAT_GUI_W32
2744 return OK; /* GUI always has a tty */
2745#else
2746 if (isatty(1))
2747 return OK;
2748 return FAIL;
2749#endif
2750}
2751
2752
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002753#ifdef FEAT_MBYTE
2754/*
2755 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2756 * if it already exists. When "len" is > 0, also expand short to long
2757 * filenames.
2758 * Return FAIL if wide functions are not available, OK otherwise.
2759 * NOTE: much of this is identical to fname_case(), keep in sync!
2760 */
2761 static int
2762fname_casew(
2763 WCHAR *name,
2764 int len)
2765{
2766 WCHAR szTrueName[_MAX_PATH + 2];
2767 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2768 WCHAR *ptrue, *ptruePrev;
2769 WCHAR *porig, *porigPrev;
2770 int flen;
2771 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002772 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002773 int c;
2774 int slen;
2775
2776 flen = (int)wcslen(name);
2777 if (flen > _MAX_PATH)
2778 return OK;
2779
2780 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2781
2782 /* Build the new name in szTrueName[] one component at a time. */
2783 porig = name;
2784 ptrue = szTrueName;
2785
2786 if (iswalpha(porig[0]) && porig[1] == L':')
2787 {
2788 /* copy leading drive letter */
2789 *ptrue++ = *porig++;
2790 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002791 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002792 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002793
2794 while (*porig != NUL)
2795 {
2796 /* copy \ characters */
2797 while (*porig == psepc)
2798 *ptrue++ = *porig++;
2799
2800 ptruePrev = ptrue;
2801 porigPrev = porig;
2802 while (*porig != NUL && *porig != psepc)
2803 {
2804 *ptrue++ = *porig++;
2805 }
2806 *ptrue = NUL;
2807
2808 /* To avoid a slow failure append "\*" when searching a directory,
2809 * server or network share. */
2810 wcscpy(szTrueNameTemp, szTrueName);
2811 slen = (int)wcslen(szTrueNameTemp);
2812 if (*porig == psepc && slen + 2 < _MAX_PATH)
2813 wcscpy(szTrueNameTemp + slen, L"\\*");
2814
2815 /* Skip "", "." and "..". */
2816 if (ptrue > ptruePrev
2817 && (ptruePrev[0] != L'.'
2818 || (ptruePrev[1] != NUL
2819 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2820 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2821 != INVALID_HANDLE_VALUE)
2822 {
2823 c = *porig;
2824 *porig = NUL;
2825
2826 /* Only use the match when it's the same name (ignoring case) or
2827 * expansion is allowed and there is a match with the short name
2828 * and there is enough room. */
2829 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2830 || (len > 0
2831 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2832 && (int)(ptruePrev - szTrueName)
2833 + (int)wcslen(fb.cFileName) < len)))
2834 {
2835 wcscpy(ptruePrev, fb.cFileName);
2836
2837 /* Look for exact match and prefer it if found. Must be a
2838 * long name, otherwise there would be only one match. */
2839 while (FindNextFileW(hFind, &fb))
2840 {
2841 if (*fb.cAlternateFileName != NUL
2842 && (wcscoll(porigPrev, fb.cFileName) == 0
2843 || (len > 0
2844 && (_wcsicoll(porigPrev,
2845 fb.cAlternateFileName) == 0
2846 && (int)(ptruePrev - szTrueName)
2847 + (int)wcslen(fb.cFileName) < len))))
2848 {
2849 wcscpy(ptruePrev, fb.cFileName);
2850 break;
2851 }
2852 }
2853 }
2854 FindClose(hFind);
2855 *porig = c;
2856 ptrue = ptruePrev + wcslen(ptruePrev);
2857 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002858 }
2859
2860 wcscpy(name, szTrueName);
2861 return OK;
2862}
2863#endif
2864
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865/*
2866 * fname_case(): Set the case of the file name, if it already exists.
2867 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002868 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869 */
2870 void
2871fname_case(
2872 char_u *name,
2873 int len)
2874{
2875 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002876 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 char *ptrue, *ptruePrev;
2878 char *porig, *porigPrev;
2879 int flen;
2880 WIN32_FIND_DATA fb;
2881 HANDLE hFind;
2882 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002883 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002885 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002886 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887 return;
2888
2889 slash_adjust(name);
2890
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002891#ifdef FEAT_MBYTE
2892 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2893 {
2894 WCHAR *p = enc_to_utf16(name, NULL);
2895
2896 if (p != NULL)
2897 {
2898 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002899 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002900
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002901 wcsncpy(buf, p, _MAX_PATH);
2902 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002903 vim_free(p);
2904
2905 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2906 {
2907 q = utf16_to_enc(buf, NULL);
2908 if (q != NULL)
2909 {
2910 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2911 vim_free(q);
2912 return;
2913 }
2914 }
2915 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002916 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002917 }
2918#endif
2919
2920 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2921 * So we should check this after calling wide function. */
2922 if (flen > _MAX_PATH)
2923 return;
2924
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002926 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 ptrue = szTrueName;
2928
2929 if (isalpha(porig[0]) && porig[1] == ':')
2930 {
2931 /* copy leading drive letter */
2932 *ptrue++ = *porig++;
2933 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002935 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936
2937 while (*porig != NUL)
2938 {
2939 /* copy \ characters */
2940 while (*porig == psepc)
2941 *ptrue++ = *porig++;
2942
2943 ptruePrev = ptrue;
2944 porigPrev = porig;
2945 while (*porig != NUL && *porig != psepc)
2946 {
2947#ifdef FEAT_MBYTE
2948 int l;
2949
2950 if (enc_dbcs)
2951 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002952 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953 while (--l >= 0)
2954 *ptrue++ = *porig++;
2955 }
2956 else
2957#endif
2958 *ptrue++ = *porig++;
2959 }
2960 *ptrue = NUL;
2961
Bram Moolenaar464c9252010-10-13 20:37:41 +02002962 /* To avoid a slow failure append "\*" when searching a directory,
2963 * server or network share. */
2964 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002965 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002966 if (*porig == psepc && slen + 2 < _MAX_PATH)
2967 STRCPY(szTrueNameTemp + slen, "\\*");
2968
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 /* Skip "", "." and "..". */
2970 if (ptrue > ptruePrev
2971 && (ptruePrev[0] != '.'
2972 || (ptruePrev[1] != NUL
2973 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002974 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002975 != INVALID_HANDLE_VALUE)
2976 {
2977 c = *porig;
2978 *porig = NUL;
2979
2980 /* Only use the match when it's the same name (ignoring case) or
2981 * expansion is allowed and there is a match with the short name
2982 * and there is enough room. */
2983 if (_stricoll(porigPrev, fb.cFileName) == 0
2984 || (len > 0
2985 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2986 && (int)(ptruePrev - szTrueName)
2987 + (int)strlen(fb.cFileName) < len)))
2988 {
2989 STRCPY(ptruePrev, fb.cFileName);
2990
2991 /* Look for exact match and prefer it if found. Must be a
2992 * long name, otherwise there would be only one match. */
2993 while (FindNextFile(hFind, &fb))
2994 {
2995 if (*fb.cAlternateFileName != NUL
2996 && (strcoll(porigPrev, fb.cFileName) == 0
2997 || (len > 0
2998 && (_stricoll(porigPrev,
2999 fb.cAlternateFileName) == 0
3000 && (int)(ptruePrev - szTrueName)
3001 + (int)strlen(fb.cFileName) < len))))
3002 {
3003 STRCPY(ptruePrev, fb.cFileName);
3004 break;
3005 }
3006 }
3007 }
3008 FindClose(hFind);
3009 *porig = c;
3010 ptrue = ptruePrev + strlen(ptruePrev);
3011 }
3012 }
3013
3014 STRCPY(name, szTrueName);
3015}
3016
3017
3018/*
3019 * Insert user name in s[len].
3020 */
3021 int
3022mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003023 char_u *s,
3024 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003026 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003027 DWORD cch = sizeof szUserName;
3028
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003029#ifdef FEAT_MBYTE
3030 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3031 {
3032 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3033 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3034
3035 if (GetUserNameW(wszUserName, &wcch))
3036 {
3037 char_u *p = utf16_to_enc(wszUserName, NULL);
3038
3039 if (p != NULL)
3040 {
3041 vim_strncpy(s, p, len - 1);
3042 vim_free(p);
3043 return OK;
3044 }
3045 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003046 }
3047#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 if (GetUserName(szUserName, &cch))
3049 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003050 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051 return OK;
3052 }
3053 s[0] = NUL;
3054 return FAIL;
3055}
3056
3057
3058/*
3059 * Insert host name in s[len].
3060 */
3061 void
3062mch_get_host_name(
3063 char_u *s,
3064 int len)
3065{
3066 DWORD cch = len;
3067
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003068#ifdef FEAT_MBYTE
3069 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3070 {
3071 WCHAR wszHostName[256 + 1];
3072 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3073
3074 if (GetComputerNameW(wszHostName, &wcch))
3075 {
3076 char_u *p = utf16_to_enc(wszHostName, NULL);
3077
3078 if (p != NULL)
3079 {
3080 vim_strncpy(s, p, len - 1);
3081 vim_free(p);
3082 return;
3083 }
3084 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003085 }
3086#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003087 if (!GetComputerName((LPSTR)s, &cch))
3088 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089}
3090
3091
3092/*
3093 * return process ID
3094 */
3095 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003096mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097{
3098 return (long)GetCurrentProcessId();
3099}
3100
3101
3102/*
3103 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3104 * Return OK for success, FAIL for failure.
3105 */
3106 int
3107mch_dirname(
3108 char_u *buf,
3109 int len)
3110{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003111 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003112 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003113
Bram Moolenaar071d4272004-06-13 20:20:40 +00003114 /*
3115 * Originally this was:
3116 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3117 * But the Win32s known bug list says that getcwd() doesn't work
3118 * so use the Win32 system call instead. <Negri>
3119 */
3120#ifdef FEAT_MBYTE
3121 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3122 {
3123 WCHAR wbuf[_MAX_PATH + 1];
3124
3125 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3126 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003127 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003128 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003129
3130 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003131 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003132 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003133 if (STRLEN(p) >= (size_t)len)
3134 {
3135 // long path name is too long, fall back to short one
3136 vim_free(p);
3137 p = NULL;
3138 }
3139 }
3140 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003141 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142
3143 if (p != NULL)
3144 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003145 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146 vim_free(p);
3147 return OK;
3148 }
3149 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003150 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151 }
3152#endif
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003153 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3154 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003155 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3156 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3157 // Failed to get long path name or it's too long: fall back to the
3158 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003159 return OK;
3160
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003161 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003162 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163}
3164
3165/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003166 * Get file permissions for "name".
3167 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003168 */
3169 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003170mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003172 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003173 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003175 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003176 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003177}
3178
3179
3180/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003181 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003182 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003183 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184 */
3185 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003186mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003188 long n = -1;
3189
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190#ifdef FEAT_MBYTE
3191 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3192 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003193 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194
3195 if (p != NULL)
3196 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003197 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003199 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003200 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003201 }
3202 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003203 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003204#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003205 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003206 if (n == -1)
3207 return FAIL;
3208
3209 win32_set_archive(name);
3210
3211 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212}
3213
3214/*
3215 * Set hidden flag for "name".
3216 */
3217 void
3218mch_hide(char_u *name)
3219{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003220 int attrs = win32_getattrs(name);
3221 if (attrs == -1)
3222 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003224 attrs |= FILE_ATTRIBUTE_HIDDEN;
3225 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226}
3227
3228/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003229 * Return TRUE if file "name" exists and is hidden.
3230 */
3231 int
3232mch_ishidden(char_u *name)
3233{
3234 int f = win32_getattrs(name);
3235
3236 if (f == -1)
3237 return FALSE; /* file does not exist at all */
3238
3239 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3240}
3241
3242/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 * return TRUE if "name" is a directory
3244 * return FALSE if "name" is not a directory or upon error
3245 */
3246 int
3247mch_isdir(char_u *name)
3248{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003249 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250
3251 if (f == -1)
3252 return FALSE; /* file does not exist at all */
3253
3254 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3255}
3256
3257/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003258 * return TRUE if "name" is a directory, NOT a symlink to a directory
3259 * return FALSE if "name" is not a directory
3260 * return FALSE for error
3261 */
3262 int
3263mch_isrealdir(char_u *name)
3264{
3265 return mch_isdir(name) && !mch_is_symbolic_link(name);
3266}
3267
3268/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003269 * Create directory "name".
3270 * Return 0 on success, -1 on error.
3271 */
3272 int
3273mch_mkdir(char_u *name)
3274{
3275#ifdef FEAT_MBYTE
3276 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3277 {
3278 WCHAR *p;
3279 int retval;
3280
3281 p = enc_to_utf16(name, NULL);
3282 if (p == NULL)
3283 return -1;
3284 retval = _wmkdir(p);
3285 vim_free(p);
3286 return retval;
3287 }
3288#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003289 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003290}
3291
3292/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003293 * Delete directory "name".
3294 * Return 0 on success, -1 on error.
3295 */
3296 int
3297mch_rmdir(char_u *name)
3298{
3299#ifdef FEAT_MBYTE
3300 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3301 {
3302 WCHAR *p;
3303 int retval;
3304
3305 p = enc_to_utf16(name, NULL);
3306 if (p == NULL)
3307 return -1;
3308 retval = _wrmdir(p);
3309 vim_free(p);
3310 return retval;
3311 }
3312#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003313 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003314}
3315
3316/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003317 * Return TRUE if file "fname" has more than one link.
3318 */
3319 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003320mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003321{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003322 BY_HANDLE_FILE_INFORMATION info;
3323
3324 return win32_fileinfo(fname, &info) == FILEINFO_OK
3325 && info.nNumberOfLinks > 1;
3326}
3327
3328/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003329 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003330 */
3331 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003332mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003333{
3334 HANDLE hFind;
3335 int res = FALSE;
3336 WIN32_FIND_DATAA findDataA;
3337 DWORD fileFlags = 0, reparseTag = 0;
3338#ifdef FEAT_MBYTE
3339 WCHAR *wn = NULL;
3340 WIN32_FIND_DATAW findDataW;
3341
3342 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003343 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003344 if (wn != NULL)
3345 {
3346 hFind = FindFirstFileW(wn, &findDataW);
3347 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003348 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003349 {
3350 fileFlags = findDataW.dwFileAttributes;
3351 reparseTag = findDataW.dwReserved0;
3352 }
3353 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003354 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003355#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003356 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003357 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003358 if (hFind != INVALID_HANDLE_VALUE)
3359 {
3360 fileFlags = findDataA.dwFileAttributes;
3361 reparseTag = findDataA.dwReserved0;
3362 }
3363 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003364
3365 if (hFind != INVALID_HANDLE_VALUE)
3366 FindClose(hFind);
3367
3368 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003369 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3370 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003371 res = TRUE;
3372
3373 return res;
3374}
3375
3376/*
3377 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3378 * link.
3379 */
3380 int
3381mch_is_linked(char_u *fname)
3382{
3383 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3384 return TRUE;
3385 return FALSE;
3386}
3387
3388/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003389 * Get the by-handle-file-information for "fname".
3390 * Returns FILEINFO_OK when OK.
3391 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3392 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3393 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3394 */
3395 int
3396win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3397{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003398 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003399 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003400#ifdef FEAT_MBYTE
3401 WCHAR *wn = NULL;
3402
3403 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003404 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003405 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003406 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003407 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003408 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003409 if (wn != NULL)
3410 {
3411 hFile = CreateFileW(wn, /* file name */
3412 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003413 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003414 NULL, /* security descriptor */
3415 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003416 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003417 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003418 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003419 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003420 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003421#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003422 hFile = CreateFile((LPCSTR)fname, /* file name */
3423 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003424 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003425 NULL, /* security descriptor */
3426 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003427 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003428 NULL); /* handle to template file */
3429
3430 if (hFile != INVALID_HANDLE_VALUE)
3431 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003432 if (GetFileInformationByHandle(hFile, info) != 0)
3433 res = FILEINFO_OK;
3434 else
3435 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003436 CloseHandle(hFile);
3437 }
3438
Bram Moolenaar03f48552006-02-28 23:52:23 +00003439 return res;
3440}
3441
3442/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003443 * get file attributes for `name'
3444 * -1 : error
3445 * else FILE_ATTRIBUTE_* defined in winnt.h
3446 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003447 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003448win32_getattrs(char_u *name)
3449{
3450 int attr;
3451#ifdef FEAT_MBYTE
3452 WCHAR *p = NULL;
3453
3454 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3455 p = enc_to_utf16(name, NULL);
3456
3457 if (p != NULL)
3458 {
3459 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003460 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003461 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003462 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003463#endif
3464 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003465
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466 return attr;
3467}
3468
3469/*
3470 * set file attributes for `name' to `attrs'
3471 *
3472 * return -1 for failure, 0 otherwise
3473 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003474 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003475win32_setattrs(char_u *name, int attrs)
3476{
3477 int res;
3478#ifdef FEAT_MBYTE
3479 WCHAR *p = NULL;
3480
3481 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3482 p = enc_to_utf16(name, NULL);
3483
3484 if (p != NULL)
3485 {
3486 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003487 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003488 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003489 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003490#endif
3491 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003492
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003493 return res ? 0 : -1;
3494}
3495
3496/*
3497 * Set archive flag for "name".
3498 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003499 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003500win32_set_archive(char_u *name)
3501{
3502 int attrs = win32_getattrs(name);
3503 if (attrs == -1)
3504 return -1;
3505
3506 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3507 return win32_setattrs(name, attrs);
3508}
3509
3510/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511 * Return TRUE if file or directory "name" is writable (not readonly).
3512 * Strange semantics of Win32: a readonly directory is writable, but you can't
3513 * delete a file. Let's say this means it is writable.
3514 */
3515 int
3516mch_writable(char_u *name)
3517{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003518 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003520 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3521 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522}
3523
Bram Moolenaar071d4272004-06-13 20:20:40 +00003524/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003525 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003526 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003527 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3528 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529 */
3530 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003531mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003533 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003534 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003535 char_u *p;
3536
3537 if (len >= _MAX_PATH) /* safety check */
3538 return FALSE;
3539
3540 /* If there already is an extension try using the name directly. Also do
3541 * this with a Unix-shell like 'shell'. */
3542 if (vim_strchr(gettail(name), '.') != NULL
3543 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003544 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003545 return TRUE;
3546
3547 /*
3548 * Loop over all extensions in $PATHEXT.
3549 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003550 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003551 p = mch_getenv("PATHEXT");
3552 if (p == NULL)
3553 p = (char_u *)".com;.exe;.bat;.cmd";
3554 while (*p)
3555 {
3556 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3557 {
3558 /* A single "." means no extension is added. */
3559 buf[len] = NUL;
3560 ++p;
3561 if (*p)
3562 ++p;
3563 }
3564 else
3565 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003566 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003567 return TRUE;
3568 }
3569 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003570}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003571
3572/*
3573 * Check what "name" is:
3574 * NODE_NORMAL: file or directory (or doesn't exist)
3575 * NODE_WRITABLE: writable device, socket, fifo, etc.
3576 * NODE_OTHER: non-writable things
3577 */
3578 int
3579mch_nodetype(char_u *name)
3580{
3581 HANDLE hFile;
3582 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003583#ifdef FEAT_MBYTE
3584 WCHAR *wn = NULL;
3585#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003586
Bram Moolenaar043545e2006-10-10 16:44:07 +00003587 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3588 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3589 * here. */
3590 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3591 return NODE_WRITABLE;
3592
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003593#ifdef FEAT_MBYTE
3594 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003595 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003596
3597 if (wn != NULL)
3598 {
3599 hFile = CreateFileW(wn, /* file name */
3600 GENERIC_WRITE, /* access mode */
3601 0, /* share mode */
3602 NULL, /* security descriptor */
3603 OPEN_EXISTING, /* creation disposition */
3604 0, /* file attributes */
3605 NULL); /* handle to template file */
3606 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003607 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003608 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003609#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003610 hFile = CreateFile((LPCSTR)name, /* file name */
3611 GENERIC_WRITE, /* access mode */
3612 0, /* share mode */
3613 NULL, /* security descriptor */
3614 OPEN_EXISTING, /* creation disposition */
3615 0, /* file attributes */
3616 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003617
3618 if (hFile == INVALID_HANDLE_VALUE)
3619 return NODE_NORMAL;
3620
3621 type = GetFileType(hFile);
3622 CloseHandle(hFile);
3623 if (type == FILE_TYPE_CHAR)
3624 return NODE_WRITABLE;
3625 if (type == FILE_TYPE_DISK)
3626 return NODE_NORMAL;
3627 return NODE_OTHER;
3628}
3629
3630#ifdef HAVE_ACL
3631struct my_acl
3632{
3633 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3634 PSID pSidOwner;
3635 PSID pSidGroup;
3636 PACL pDacl;
3637 PACL pSacl;
3638};
3639#endif
3640
3641/*
3642 * Return a pointer to the ACL of file "fname" in allocated memory.
3643 * Return NULL if the ACL is not available for whatever reason.
3644 */
3645 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003646mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003647{
3648#ifndef HAVE_ACL
3649 return (vim_acl_T)NULL;
3650#else
3651 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003652 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003653
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003654 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3655 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003657# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003658 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003659
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003660 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3661 wn = enc_to_utf16(fname, NULL);
3662 if (wn != NULL)
3663 {
3664 /* Try to retrieve the entire security descriptor. */
3665 err = GetNamedSecurityInfoW(
3666 wn, // Abstract filename
3667 SE_FILE_OBJECT, // File Object
3668 OWNER_SECURITY_INFORMATION |
3669 GROUP_SECURITY_INFORMATION |
3670 DACL_SECURITY_INFORMATION |
3671 SACL_SECURITY_INFORMATION,
3672 &p->pSidOwner, // Ownership information.
3673 &p->pSidGroup, // Group membership.
3674 &p->pDacl, // Discretionary information.
3675 &p->pSacl, // For auditing purposes.
3676 &p->pSecurityDescriptor);
3677 if (err == ERROR_ACCESS_DENIED ||
3678 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003680 /* Retrieve only DACL. */
3681 (void)GetNamedSecurityInfoW(
3682 wn,
3683 SE_FILE_OBJECT,
3684 DACL_SECURITY_INFORMATION,
3685 NULL,
3686 NULL,
3687 &p->pDacl,
3688 NULL,
3689 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003690 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003691 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003692 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003693 mch_free_acl((vim_acl_T)p);
3694 p = NULL;
3695 }
3696 vim_free(wn);
3697 }
3698 else
3699# endif
3700 {
3701 /* Try to retrieve the entire security descriptor. */
3702 err = GetNamedSecurityInfo(
3703 (LPSTR)fname, // Abstract filename
3704 SE_FILE_OBJECT, // File Object
3705 OWNER_SECURITY_INFORMATION |
3706 GROUP_SECURITY_INFORMATION |
3707 DACL_SECURITY_INFORMATION |
3708 SACL_SECURITY_INFORMATION,
3709 &p->pSidOwner, // Ownership information.
3710 &p->pSidGroup, // Group membership.
3711 &p->pDacl, // Discretionary information.
3712 &p->pSacl, // For auditing purposes.
3713 &p->pSecurityDescriptor);
3714 if (err == ERROR_ACCESS_DENIED ||
3715 err == ERROR_PRIVILEGE_NOT_HELD)
3716 {
3717 /* Retrieve only DACL. */
3718 (void)GetNamedSecurityInfo(
3719 (LPSTR)fname,
3720 SE_FILE_OBJECT,
3721 DACL_SECURITY_INFORMATION,
3722 NULL,
3723 NULL,
3724 &p->pDacl,
3725 NULL,
3726 &p->pSecurityDescriptor);
3727 }
3728 if (p->pSecurityDescriptor == NULL)
3729 {
3730 mch_free_acl((vim_acl_T)p);
3731 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 }
3733 }
3734 }
3735
3736 return (vim_acl_T)p;
3737#endif
3738}
3739
Bram Moolenaar27515922013-06-29 15:36:26 +02003740#ifdef HAVE_ACL
3741/*
3742 * Check if "acl" contains inherited ACE.
3743 */
3744 static BOOL
3745is_acl_inherited(PACL acl)
3746{
3747 DWORD i;
3748 ACL_SIZE_INFORMATION acl_info;
3749 PACCESS_ALLOWED_ACE ace;
3750
3751 acl_info.AceCount = 0;
3752 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3753 for (i = 0; i < acl_info.AceCount; i++)
3754 {
3755 GetAce(acl, i, (LPVOID *)&ace);
3756 if (ace->Header.AceFlags & INHERITED_ACE)
3757 return TRUE;
3758 }
3759 return FALSE;
3760}
3761#endif
3762
Bram Moolenaar071d4272004-06-13 20:20:40 +00003763/*
3764 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3765 * Errors are ignored.
3766 * This must only be called with "acl" equal to what mch_get_acl() returned.
3767 */
3768 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003769mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770{
3771#ifdef HAVE_ACL
3772 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003773 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003775 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003776 {
3777# ifdef FEAT_MBYTE
3778 WCHAR *wn = NULL;
3779# endif
3780
3781 /* Set security flags */
3782 if (p->pSidOwner)
3783 sec_info |= OWNER_SECURITY_INFORMATION;
3784 if (p->pSidGroup)
3785 sec_info |= GROUP_SECURITY_INFORMATION;
3786 if (p->pDacl)
3787 {
3788 sec_info |= DACL_SECURITY_INFORMATION;
3789 /* Do not inherit its parent's DACL.
3790 * If the DACL is inherited, Cygwin permissions would be changed.
3791 */
3792 if (!is_acl_inherited(p->pDacl))
3793 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3794 }
3795 if (p->pSacl)
3796 sec_info |= SACL_SECURITY_INFORMATION;
3797
3798# ifdef FEAT_MBYTE
3799 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3800 wn = enc_to_utf16(fname, NULL);
3801 if (wn != NULL)
3802 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003803 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003804 wn, // Abstract filename
3805 SE_FILE_OBJECT, // File Object
3806 sec_info,
3807 p->pSidOwner, // Ownership information.
3808 p->pSidGroup, // Group membership.
3809 p->pDacl, // Discretionary information.
3810 p->pSacl // For auditing purposes.
3811 );
3812 vim_free(wn);
3813 }
3814 else
3815# endif
3816 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003817 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003818 (LPSTR)fname, // 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 }
3827 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828#endif
3829}
3830
3831 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003832mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003833{
3834#ifdef HAVE_ACL
3835 struct my_acl *p = (struct my_acl *)acl;
3836
3837 if (p != NULL)
3838 {
3839 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3840 vim_free(p);
3841 }
3842#endif
3843}
3844
3845#ifndef FEAT_GUI_W32
3846
3847/*
3848 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3849 */
3850 static BOOL WINAPI
3851handler_routine(
3852 DWORD dwCtrlType)
3853{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003854 INPUT_RECORD ir;
3855 DWORD out;
3856
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857 switch (dwCtrlType)
3858 {
3859 case CTRL_C_EVENT:
3860 if (ctrl_c_interrupts)
3861 g_fCtrlCPressed = TRUE;
3862 return TRUE;
3863
3864 case CTRL_BREAK_EVENT:
3865 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003866 ctrl_break_was_pressed = TRUE;
3867 /* ReadConsoleInput is blocking, send a key event to continue. */
3868 ir.EventType = KEY_EVENT;
3869 ir.Event.KeyEvent.bKeyDown = TRUE;
3870 ir.Event.KeyEvent.wRepeatCount = 1;
3871 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3872 ir.Event.KeyEvent.wVirtualScanCode = 0;
3873 ir.Event.KeyEvent.dwControlKeyState = 0;
3874 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3875 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876 return TRUE;
3877
3878 /* fatal events: shut down gracefully */
3879 case CTRL_CLOSE_EVENT:
3880 case CTRL_LOGOFF_EVENT:
3881 case CTRL_SHUTDOWN_EVENT:
3882 windgoto((int)Rows - 1, 0);
3883 g_fForceExit = TRUE;
3884
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003885 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886 (dwCtrlType == CTRL_CLOSE_EVENT
3887 ? _("close")
3888 : dwCtrlType == CTRL_LOGOFF_EVENT
3889 ? _("logoff")
3890 : _("shutdown")));
3891#ifdef DEBUG
3892 OutputDebugString(IObuff);
3893#endif
3894
3895 preserve_exit(); /* output IObuff, preserve files and exit */
3896
3897 return TRUE; /* not reached */
3898
3899 default:
3900 return FALSE;
3901 }
3902}
3903
3904
3905/*
3906 * set the tty in (raw) ? "raw" : "cooked" mode
3907 */
3908 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003909mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003910{
3911 DWORD cmodein;
3912 DWORD cmodeout;
3913 BOOL bEnableHandler;
3914
3915 GetConsoleMode(g_hConIn, &cmodein);
3916 GetConsoleMode(g_hConOut, &cmodeout);
3917 if (tmode == TMODE_RAW)
3918 {
3919 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3920 ENABLE_ECHO_INPUT);
3921#ifdef FEAT_MOUSE
3922 if (g_fMouseActive)
3923 cmodein |= ENABLE_MOUSE_INPUT;
3924#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003925 cmodeout &= ~(
3926#ifdef FEAT_TERMGUICOLORS
3927 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3928 * VTP. */
3929 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3930#else
3931 ENABLE_PROCESSED_OUTPUT |
3932#endif
3933 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 bEnableHandler = TRUE;
3935 }
3936 else /* cooked */
3937 {
3938 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3939 ENABLE_ECHO_INPUT);
3940 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3941 bEnableHandler = FALSE;
3942 }
3943 SetConsoleMode(g_hConIn, cmodein);
3944 SetConsoleMode(g_hConOut, cmodeout);
3945 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3946
3947#ifdef MCH_WRITE_DUMP
3948 if (fdDump)
3949 {
3950 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3951 tmode == TMODE_RAW ? "raw" :
3952 tmode == TMODE_COOK ? "cooked" : "normal",
3953 cmodein, cmodeout);
3954 fflush(fdDump);
3955 }
3956#endif
3957}
3958
3959
3960/*
3961 * Get the size of the current window in `Rows' and `Columns'
3962 * Return OK when size could be determined, FAIL otherwise.
3963 */
3964 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003965mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966{
3967 CONSOLE_SCREEN_BUFFER_INFO csbi;
3968
3969 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3970 {
3971 /*
3972 * For some reason, we are trying to get the screen dimensions
3973 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3974 * variables are really intended to mean the size of Vim screen
3975 * while in termcap mode.
3976 */
3977 Rows = g_cbTermcap.Info.dwSize.Y;
3978 Columns = g_cbTermcap.Info.dwSize.X;
3979 }
3980 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3981 {
3982 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3983 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3984 }
3985 else
3986 {
3987 Rows = 25;
3988 Columns = 80;
3989 }
3990 return OK;
3991}
3992
3993/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003994 * Resize console buffer to 'COORD'
3995 */
3996 static void
3997ResizeConBuf(
3998 HANDLE hConsole,
3999 COORD coordScreen)
4000{
4001 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4002 {
4003#ifdef MCH_WRITE_DUMP
4004 if (fdDump)
4005 {
4006 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4007 GetLastError());
4008 fflush(fdDump);
4009 }
4010#endif
4011 }
4012}
4013
4014/*
4015 * Resize console window size to 'srWindowRect'
4016 */
4017 static void
4018ResizeWindow(
4019 HANDLE hConsole,
4020 SMALL_RECT srWindowRect)
4021{
4022 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4023 {
4024#ifdef MCH_WRITE_DUMP
4025 if (fdDump)
4026 {
4027 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4028 GetLastError());
4029 fflush(fdDump);
4030 }
4031#endif
4032 }
4033}
4034
4035/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004036 * Set a console window to `xSize' * `ySize'
4037 */
4038 static void
4039ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004040 HANDLE hConsole,
4041 int xSize,
4042 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004043{
4044 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4045 SMALL_RECT srWindowRect; /* hold the new console size */
4046 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004047 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004048
4049#ifdef MCH_WRITE_DUMP
4050 if (fdDump)
4051 {
4052 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4053 fflush(fdDump);
4054 }
4055#endif
4056
4057 /* get the largest size we can size the console window to */
4058 coordScreen = GetLargestConsoleWindowSize(hConsole);
4059
4060 /* define the new console window size and scroll position */
4061 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4062 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4063 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4064
4065 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4066 {
4067 int sx, sy;
4068
4069 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4070 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4071 if (sy < ySize || sx < xSize)
4072 {
4073 /*
4074 * Increasing number of lines/columns, do buffer first.
4075 * Use the maximal size in x and y direction.
4076 */
4077 if (sy < ySize)
4078 coordScreen.Y = ySize;
4079 else
4080 coordScreen.Y = sy;
4081 if (sx < xSize)
4082 coordScreen.X = xSize;
4083 else
4084 coordScreen.X = sx;
4085 SetConsoleScreenBufferSize(hConsole, coordScreen);
4086 }
4087 }
4088
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004089 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004090 coordScreen.X = xSize;
4091 coordScreen.Y = ySize;
4092
Bram Moolenaar2551c032018-08-23 22:38:31 +02004093 // In the new console call API, only the first time in reverse order
4094 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004096 ResizeWindow(hConsole, srWindowRect);
4097 ResizeConBuf(hConsole, coordScreen);
4098 }
4099 else
4100 {
4101 ResizeConBuf(hConsole, coordScreen);
4102 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004103 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004104 }
4105}
4106
4107
4108/*
4109 * Set the console window to `Rows' * `Columns'
4110 */
4111 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004112mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113{
4114 COORD coordScreen;
4115
4116 /* Don't change window size while still starting up */
4117 if (suppress_winsize != 0)
4118 {
4119 suppress_winsize = 2;
4120 return;
4121 }
4122
4123 if (term_console)
4124 {
4125 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4126
4127 /* Clamp Rows and Columns to reasonable values */
4128 if (Rows > coordScreen.Y)
4129 Rows = coordScreen.Y;
4130 if (Columns > coordScreen.X)
4131 Columns = coordScreen.X;
4132
4133 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4134 }
4135}
4136
4137/*
4138 * Rows and/or Columns has changed.
4139 */
4140 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004141mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142{
4143 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4144}
4145
4146
4147/*
4148 * Called when started up, to set the winsize that was delayed.
4149 */
4150 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004151mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152{
4153 if (suppress_winsize == 2)
4154 {
4155 suppress_winsize = 0;
4156 mch_set_shellsize();
4157 shell_resized();
4158 }
4159 suppress_winsize = 0;
4160}
4161#endif /* FEAT_GUI_W32 */
4162
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004163 static BOOL
4164vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004165 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004166 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004167 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004168 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004169 PROCESS_INFORMATION *pi,
4170 LPVOID *env,
4171 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004172{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004173#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004174 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4175 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004176 BOOL ret;
4177 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004178
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004179 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4180 if (wcmd == NULL)
4181 goto fallback;
4182 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004183 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004184 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4185 if (wcwd == NULL)
4186 {
4187 vim_free(wcmd);
4188 goto fallback;
4189 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004190 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004191
4192 ret = CreateProcessW(
4193 NULL, /* Executable name */
4194 wcmd, /* Command to execute */
4195 NULL, /* Process security attributes */
4196 NULL, /* Thread security attributes */
4197 inherit_handles, /* Inherit handles */
4198 flags, /* Creation flags */
4199 env, /* Environment */
4200 wcwd, /* Current directory */
4201 (LPSTARTUPINFOW)si, /* Startup information */
4202 pi); /* Process information */
4203 vim_free(wcmd);
4204 if (wcwd != NULL)
4205 vim_free(wcwd);
4206 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004207 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004208fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004209#endif
4210 return CreateProcess(
4211 NULL, /* Executable name */
4212 cmd, /* Command to execute */
4213 NULL, /* Process security attributes */
4214 NULL, /* Thread security attributes */
4215 inherit_handles, /* Inherit handles */
4216 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004217 env, /* Environment */
4218 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004219 si, /* Startup information */
4220 pi); /* Process information */
4221}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004222
4223
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004224 static HINSTANCE
4225vim_shell_execute(
4226 char *cmd,
4227 INT n_show_cmd)
4228{
4229#ifdef FEAT_MBYTE
4230 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4231 {
4232 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4233 if (wcmd != NULL)
4234 {
4235 HINSTANCE ret;
4236 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4237 vim_free(wcmd);
4238 return ret;
4239 }
4240 }
4241#endif
4242 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4243}
4244
4245
Bram Moolenaar071d4272004-06-13 20:20:40 +00004246#if defined(FEAT_GUI_W32) || defined(PROTO)
4247
4248/*
4249 * Specialised version of system() for Win32 GUI mode.
4250 * This version proceeds as follows:
4251 * 1. Create a console window for use by the subprocess
4252 * 2. Run the subprocess (it gets the allocated console by default)
4253 * 3. Wait for the subprocess to terminate and get its exit code
4254 * 4. Prompt the user to press a key to close the console window
4255 */
4256 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004257mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004258{
4259 STARTUPINFO si;
4260 PROCESS_INFORMATION pi;
4261 DWORD ret = 0;
4262 HWND hwnd = GetFocus();
4263
4264 si.cb = sizeof(si);
4265 si.lpReserved = NULL;
4266 si.lpDesktop = NULL;
4267 si.lpTitle = NULL;
4268 si.dwFlags = STARTF_USESHOWWINDOW;
4269 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004270 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004271 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004272 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004273 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004274 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004275 else
4276 si.wShowWindow = SW_SHOWNORMAL;
4277 si.cbReserved2 = 0;
4278 si.lpReserved2 = NULL;
4279
Bram Moolenaar071d4272004-06-13 20:20:40 +00004280 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004281 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004282 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4283 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284
4285 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004286 {
4287#ifdef FEAT_GUI
4288 int delay = 1;
4289
4290 /* Keep updating the window while waiting for the shell to finish. */
4291 for (;;)
4292 {
4293 MSG msg;
4294
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004295 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004296 {
4297 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004298 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004299 delay = 1;
4300 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004301 }
4302 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4303 break;
4304
4305 /* We start waiting for a very short time and then increase it, so
4306 * that we respond quickly when the process is quick, and don't
4307 * consume too much overhead when it's slow. */
4308 if (delay < 50)
4309 delay += 10;
4310 }
4311#else
4312 WaitForSingleObject(pi.hProcess, INFINITE);
4313#endif
4314
4315 /* Get the command exit code */
4316 GetExitCodeProcess(pi.hProcess, &ret);
4317 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004318
4319 /* Close the handles to the subprocess, so that it goes away */
4320 CloseHandle(pi.hThread);
4321 CloseHandle(pi.hProcess);
4322
4323 /* Try to get input focus back. Doesn't always work though. */
4324 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4325
4326 return ret;
4327}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004328
4329/*
4330 * Thread launched by the gui to send the current buffer data to the
4331 * process. This way avoid to hang up vim totally if the children
4332 * process take a long time to process the lines.
4333 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004334 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004335sub_process_writer(LPVOID param)
4336{
4337 HANDLE g_hChildStd_IN_Wr = param;
4338 linenr_T lnum = curbuf->b_op_start.lnum;
4339 DWORD len = 0;
4340 DWORD l;
4341 char_u *lp = ml_get(lnum);
4342 char_u *s;
4343 int written = 0;
4344
4345 for (;;)
4346 {
4347 l = (DWORD)STRLEN(lp + written);
4348 if (l == 0)
4349 len = 0;
4350 else if (lp[written] == NL)
4351 {
4352 /* NL -> NUL translation */
4353 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4354 }
4355 else
4356 {
4357 s = vim_strchr(lp + written, NL);
4358 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4359 s == NULL ? l : (DWORD)(s - (lp + written)),
4360 &len, NULL);
4361 }
4362 if (len == (int)l)
4363 {
4364 /* Finished a line, add a NL, unless this line should not have
4365 * one. */
4366 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004367 || (!curbuf->b_p_bin
4368 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004369 || (lnum != curbuf->b_no_eol_lnum
4370 && (lnum != curbuf->b_ml.ml_line_count
4371 || curbuf->b_p_eol)))
4372 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004373 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4374 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004375 }
4376
4377 ++lnum;
4378 if (lnum > curbuf->b_op_end.lnum)
4379 break;
4380
4381 lp = ml_get(lnum);
4382 written = 0;
4383 }
4384 else if (len > 0)
4385 written += len;
4386 }
4387
4388 /* finished all the lines, close pipe */
4389 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004390 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004391}
4392
4393
4394# define BUFLEN 100 /* length for buffer, stolen from unix version */
4395
4396/*
4397 * This function read from the children's stdout and write the
4398 * data on screen or in the buffer accordingly.
4399 */
4400 static void
4401dump_pipe(int options,
4402 HANDLE g_hChildStd_OUT_Rd,
4403 garray_T *ga,
4404 char_u buffer[],
4405 DWORD *buffer_off)
4406{
4407 DWORD availableBytes = 0;
4408 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004409 int ret;
4410 DWORD len;
4411 DWORD toRead;
4412 int repeatCount;
4413
4414 /* we query the pipe to see if there is any data to read
4415 * to avoid to perform a blocking read */
4416 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4417 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004418 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004419 NULL, /* number of read bytes */
4420 &availableBytes, /* available bytes total */
4421 NULL); /* byteLeft */
4422
4423 repeatCount = 0;
4424 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004425 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004426 {
4427 repeatCount++;
4428 toRead =
4429# ifdef FEAT_MBYTE
4430 (DWORD)(BUFLEN - *buffer_off);
4431# else
4432 (DWORD)BUFLEN;
4433# endif
4434 toRead = availableBytes < toRead ? availableBytes : toRead;
4435 ReadFile(g_hChildStd_OUT_Rd, buffer
4436# ifdef FEAT_MBYTE
4437 + *buffer_off, toRead
4438# else
4439 , toRead
4440# endif
4441 , &len, NULL);
4442
4443 /* If we haven't read anything, there is a problem */
4444 if (len == 0)
4445 break;
4446
4447 availableBytes -= len;
4448
4449 if (options & SHELL_READ)
4450 {
4451 /* Do NUL -> NL translation, append NL separated
4452 * lines to the current buffer. */
4453 for (i = 0; i < len; ++i)
4454 {
4455 if (buffer[i] == NL)
4456 append_ga_line(ga);
4457 else if (buffer[i] == NUL)
4458 ga_append(ga, NL);
4459 else
4460 ga_append(ga, buffer[i]);
4461 }
4462 }
4463# ifdef FEAT_MBYTE
4464 else if (has_mbyte)
4465 {
4466 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004467 int c;
4468 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004469
4470 len += *buffer_off;
4471 buffer[len] = NUL;
4472
4473 /* Check if the last character in buffer[] is
4474 * incomplete, keep these bytes for the next
4475 * round. */
4476 for (p = buffer; p < buffer + len; p += l)
4477 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004478 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004479 if (l == 0)
4480 l = 1; /* NUL byte? */
4481 else if (MB_BYTE2LEN(*p) != l)
4482 break;
4483 }
4484 if (p == buffer) /* no complete character */
4485 {
4486 /* avoid getting stuck at an illegal byte */
4487 if (len >= 12)
4488 ++p;
4489 else
4490 {
4491 *buffer_off = len;
4492 return;
4493 }
4494 }
4495 c = *p;
4496 *p = NUL;
4497 msg_puts(buffer);
4498 if (p < buffer + len)
4499 {
4500 *p = c;
4501 *buffer_off = (DWORD)((buffer + len) - p);
4502 mch_memmove(buffer, p, *buffer_off);
4503 return;
4504 }
4505 *buffer_off = 0;
4506 }
4507# endif /* FEAT_MBYTE */
4508 else
4509 {
4510 buffer[len] = NUL;
4511 msg_puts(buffer);
4512 }
4513
4514 windgoto(msg_row, msg_col);
4515 cursor_on();
4516 out_flush();
4517 }
4518}
4519
4520/*
4521 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4522 * for communication and doesn't open any new window.
4523 */
4524 static int
4525mch_system_piped(char *cmd, int options)
4526{
4527 STARTUPINFO si;
4528 PROCESS_INFORMATION pi;
4529 DWORD ret = 0;
4530
4531 HANDLE g_hChildStd_IN_Rd = NULL;
4532 HANDLE g_hChildStd_IN_Wr = NULL;
4533 HANDLE g_hChildStd_OUT_Rd = NULL;
4534 HANDLE g_hChildStd_OUT_Wr = NULL;
4535
4536 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4537 DWORD len;
4538
4539 /* buffer used to receive keys */
4540 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4541 int ta_len = 0; /* valid bytes in ta_buf[] */
4542
4543 DWORD i;
4544 int c;
4545 int noread_cnt = 0;
4546 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004547 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004548 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004549 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004550
4551 SECURITY_ATTRIBUTES saAttr;
4552
4553 /* Set the bInheritHandle flag so pipe handles are inherited. */
4554 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4555 saAttr.bInheritHandle = TRUE;
4556 saAttr.lpSecurityDescriptor = NULL;
4557
4558 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4559 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004560 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004561 /* Create a pipe for the child process's STDIN. */
4562 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4563 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004564 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004565 {
4566 CloseHandle(g_hChildStd_IN_Rd);
4567 CloseHandle(g_hChildStd_IN_Wr);
4568 CloseHandle(g_hChildStd_OUT_Rd);
4569 CloseHandle(g_hChildStd_OUT_Wr);
4570 MSG_PUTS(_("\nCannot create pipes\n"));
4571 }
4572
4573 si.cb = sizeof(si);
4574 si.lpReserved = NULL;
4575 si.lpDesktop = NULL;
4576 si.lpTitle = NULL;
4577 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4578
4579 /* set-up our file redirection */
4580 si.hStdError = g_hChildStd_OUT_Wr;
4581 si.hStdOutput = g_hChildStd_OUT_Wr;
4582 si.hStdInput = g_hChildStd_IN_Rd;
4583 si.wShowWindow = SW_HIDE;
4584 si.cbReserved2 = 0;
4585 si.lpReserved2 = NULL;
4586
4587 if (options & SHELL_READ)
4588 ga_init2(&ga, 1, BUFLEN);
4589
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004590 if (cmd != NULL)
4591 {
4592 p = (char *)vim_strsave((char_u *)cmd);
4593 if (p != NULL)
4594 unescape_shellxquote((char_u *)p, p_sxe);
4595 else
4596 p = cmd;
4597 }
4598
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004599 /* Now, run the command.
4600 * About "Inherit handles" being TRUE: this command can be litigious,
4601 * handle inheritance was deactivated for pending temp file, but, if we
4602 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004603 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4604 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004605
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004606 if (p != cmd)
4607 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004608
4609 /* Close our unused side of the pipes */
4610 CloseHandle(g_hChildStd_IN_Rd);
4611 CloseHandle(g_hChildStd_OUT_Wr);
4612
4613 if (options & SHELL_WRITE)
4614 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004615 HANDLE thread = (HANDLE)
4616 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004617 0, /* default stack size */
4618 sub_process_writer, /* function to be executed */
4619 g_hChildStd_IN_Wr, /* parameter */
4620 0, /* creation flag, start immediately */
4621 NULL); /* we don't care about thread id */
4622 CloseHandle(thread);
4623 g_hChildStd_IN_Wr = NULL;
4624 }
4625
4626 /* Keep updating the window while waiting for the shell to finish. */
4627 for (;;)
4628 {
4629 MSG msg;
4630
Bram Moolenaar175d0702013-12-11 18:36:33 +01004631 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004632 {
4633 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004634 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004635 }
4636
4637 /* write pipe information in the window */
4638 if ((options & (SHELL_READ|SHELL_WRITE))
4639# ifdef FEAT_GUI
4640 || gui.in_use
4641# endif
4642 )
4643 {
4644 len = 0;
4645 if (!(options & SHELL_EXPAND)
4646 && ((options &
4647 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4648 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4649# ifdef FEAT_GUI
4650 || gui.in_use
4651# endif
4652 )
4653 && (ta_len > 0 || noread_cnt > 4))
4654 {
4655 if (ta_len == 0)
4656 {
4657 /* Get extra characters when we don't have any. Reset the
4658 * counter and timer. */
4659 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004660 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4661 }
4662 if (ta_len > 0 || len > 0)
4663 {
4664 /*
4665 * For pipes: Check for CTRL-C: send interrupt signal to
4666 * child. Check for CTRL-D: EOF, close pipe to child.
4667 */
4668 if (len == 1 && cmd != NULL)
4669 {
4670 if (ta_buf[ta_len] == Ctrl_C)
4671 {
4672 /* Learn what exit code is expected, for
4673 * now put 9 as SIGKILL */
4674 TerminateProcess(pi.hProcess, 9);
4675 }
4676 if (ta_buf[ta_len] == Ctrl_D)
4677 {
4678 CloseHandle(g_hChildStd_IN_Wr);
4679 g_hChildStd_IN_Wr = NULL;
4680 }
4681 }
4682
4683 /* replace K_BS by <BS> and K_DEL by <DEL> */
4684 for (i = ta_len; i < ta_len + len; ++i)
4685 {
4686 if (ta_buf[i] == CSI && len - i > 2)
4687 {
4688 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4689 if (c == K_DEL || c == K_KDEL || c == K_BS)
4690 {
4691 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4692 (size_t)(len - i - 2));
4693 if (c == K_DEL || c == K_KDEL)
4694 ta_buf[i] = DEL;
4695 else
4696 ta_buf[i] = Ctrl_H;
4697 len -= 2;
4698 }
4699 }
4700 else if (ta_buf[i] == '\r')
4701 ta_buf[i] = '\n';
4702# ifdef FEAT_MBYTE
4703 if (has_mbyte)
4704 i += (*mb_ptr2len_len)(ta_buf + i,
4705 ta_len + len - i) - 1;
4706# endif
4707 }
4708
4709 /*
4710 * For pipes: echo the typed characters. For a pty this
4711 * does not seem to work.
4712 */
4713 for (i = ta_len; i < ta_len + len; ++i)
4714 {
4715 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4716 msg_putchar(ta_buf[i]);
4717# ifdef FEAT_MBYTE
4718 else if (has_mbyte)
4719 {
4720 int l = (*mb_ptr2len)(ta_buf + i);
4721
4722 msg_outtrans_len(ta_buf + i, l);
4723 i += l - 1;
4724 }
4725# endif
4726 else
4727 msg_outtrans_len(ta_buf + i, 1);
4728 }
4729 windgoto(msg_row, msg_col);
4730 out_flush();
4731
4732 ta_len += len;
4733
4734 /*
4735 * Write the characters to the child, unless EOF has been
4736 * typed for pipes. Write one character at a time, to
4737 * avoid losing too much typeahead. When writing buffer
4738 * lines, drop the typed characters (only check for
4739 * CTRL-C).
4740 */
4741 if (options & SHELL_WRITE)
4742 ta_len = 0;
4743 else if (g_hChildStd_IN_Wr != NULL)
4744 {
4745 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4746 1, &len, NULL);
4747 // if we are typing in, we want to keep things reactive
4748 delay = 1;
4749 if (len > 0)
4750 {
4751 ta_len -= len;
4752 mch_memmove(ta_buf, ta_buf + len, ta_len);
4753 }
4754 }
4755 }
4756 }
4757 }
4758
4759 if (ta_len)
4760 ui_inchar_undo(ta_buf, ta_len);
4761
4762 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4763 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004764 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004765 break;
4766 }
4767
4768 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004769 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004770
4771 /* We start waiting for a very short time and then increase it, so
4772 * that we respond quickly when the process is quick, and don't
4773 * consume too much overhead when it's slow. */
4774 if (delay < 50)
4775 delay += 10;
4776 }
4777
4778 /* Close the pipe */
4779 CloseHandle(g_hChildStd_OUT_Rd);
4780 if (g_hChildStd_IN_Wr != NULL)
4781 CloseHandle(g_hChildStd_IN_Wr);
4782
4783 WaitForSingleObject(pi.hProcess, INFINITE);
4784
4785 /* Get the command exit code */
4786 GetExitCodeProcess(pi.hProcess, &ret);
4787
4788 if (options & SHELL_READ)
4789 {
4790 if (ga.ga_len > 0)
4791 {
4792 append_ga_line(&ga);
4793 /* remember that the NL was missing */
4794 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4795 }
4796 else
4797 curbuf->b_no_eol_lnum = 0;
4798 ga_clear(&ga);
4799 }
4800
4801 /* Close the handles to the subprocess, so that it goes away */
4802 CloseHandle(pi.hThread);
4803 CloseHandle(pi.hProcess);
4804
4805 return ret;
4806}
4807
4808 static int
4809mch_system(char *cmd, int options)
4810{
4811 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004812 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004813 return mch_system_piped(cmd, options);
4814 else
4815 return mch_system_classic(cmd, options);
4816}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004817#else
4818
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004819# ifdef FEAT_MBYTE
4820 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004821mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004822{
4823 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4824 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004825 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004826 if (wcmd != NULL)
4827 {
4828 int ret = _wsystem(wcmd);
4829 vim_free(wcmd);
4830 return ret;
4831 }
4832 }
4833 return system(cmd);
4834}
4835# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004836# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004837# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004838
4839#endif
4840
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004841#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4842/*
4843 * Use a terminal window to run a shell command in.
4844 */
4845 static int
4846mch_call_shell_terminal(
4847 char_u *cmd,
4848 int options UNUSED) /* SHELL_*, see vim.h */
4849{
4850 jobopt_T opt;
4851 char_u *newcmd = NULL;
4852 typval_T argvar[2];
4853 long_u cmdlen;
4854 int retval = -1;
4855 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004856 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004857 aco_save_T aco;
4858 oparg_T oa; /* operator arguments */
4859
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004860 if (cmd == NULL)
4861 cmdlen = STRLEN(p_sh) + 1;
4862 else
4863 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004864 newcmd = lalloc(cmdlen, TRUE);
4865 if (newcmd == NULL)
4866 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004867 if (cmd == NULL)
4868 {
4869 STRCPY(newcmd, p_sh);
4870 ch_log(NULL, "starting terminal to run a shell");
4871 }
4872 else
4873 {
4874 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4875 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4876 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004877
4878 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004879
4880 argvar[0].v_type = VAR_STRING;
4881 argvar[0].vval.v_string = newcmd;
4882 argvar[1].v_type = VAR_UNKNOWN;
4883 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004884 if (buf == NULL)
4885 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004886
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004887 job = term_getjob(buf->b_term);
4888 ++job->jv_refcount;
4889
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004890 /* Find a window to make "buf" curbuf. */
4891 aucmd_prepbuf(&aco, buf);
4892
4893 clear_oparg(&oa);
4894 while (term_use_loop())
4895 {
4896 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4897 {
4898 /* If terminal_loop() returns OK we got a key that is handled
4899 * in Normal model. We don't do redrawing anyway. */
4900 if (terminal_loop(TRUE) == OK)
4901 normal_cmd(&oa, TRUE);
4902 }
4903 else
4904 normal_cmd(&oa, TRUE);
4905 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004906 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004907 ch_log(NULL, "system command finished");
4908
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004909 job_unref(job);
4910
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004911 /* restore curwin/curbuf and a few other things */
4912 aucmd_restbuf(&aco);
4913
4914 wait_return(TRUE);
4915 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4916
4917 vim_free(newcmd);
4918 return retval;
4919}
4920#endif
4921
Bram Moolenaar071d4272004-06-13 20:20:40 +00004922/*
4923 * Either execute a command by calling the shell or start a new shell
4924 */
4925 int
4926mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004927 char_u *cmd,
4928 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004929{
4930 int x = 0;
4931 int tmode = cur_tmode;
4932#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004933 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004934# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004935 int did_set_title = FALSE;
4936
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004937 /* Change the title to reflect that we are in a subshell. */
4938 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4939 {
4940 WCHAR szShellTitle[512];
4941
4942 if (GetConsoleTitleW(szShellTitle,
4943 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4944 {
4945 if (cmd == NULL)
4946 wcscat(szShellTitle, L" :sh");
4947 else
4948 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004949 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004950
4951 if (wn != NULL)
4952 {
4953 wcscat(szShellTitle, L" - !");
4954 if ((wcslen(szShellTitle) + wcslen(wn) <
4955 sizeof(szShellTitle)/sizeof(WCHAR)))
4956 wcscat(szShellTitle, wn);
4957 SetConsoleTitleW(szShellTitle);
4958 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004959 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004960 }
4961 }
4962 }
4963 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004964 if (!did_set_title)
4965# endif
4966 /* Change the title to reflect that we are in a subshell. */
4967 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004968 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004969 if (cmd == NULL)
4970 strcat(szShellTitle, " :sh");
4971 else
4972 {
4973 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004974 if ((strlen(szShellTitle) + strlen((char *)cmd)
4975 < sizeof(szShellTitle)))
4976 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004977 }
4978 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004980#endif
4981
4982 out_flush();
4983
4984#ifdef MCH_WRITE_DUMP
4985 if (fdDump)
4986 {
4987 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4988 fflush(fdDump);
4989 }
4990#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004991#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4992 /* TODO: make the terminal window work with input or output redirected. */
4993 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4994 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4995 {
4996 /* Use a terminal window to run the command in. */
4997 x = mch_call_shell_terminal(cmd, options);
4998#ifdef FEAT_TITLE
4999 resettitle();
5000#endif
5001 return x;
5002 }
5003#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005004
5005 /*
5006 * Catch all deadly signals while running the external command, because a
5007 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5008 */
5009 signal(SIGINT, SIG_IGN);
5010#if defined(__GNUC__) && !defined(__MINGW32__)
5011 signal(SIGKILL, SIG_IGN);
5012#else
5013 signal(SIGBREAK, SIG_IGN);
5014#endif
5015 signal(SIGILL, SIG_IGN);
5016 signal(SIGFPE, SIG_IGN);
5017 signal(SIGSEGV, SIG_IGN);
5018 signal(SIGTERM, SIG_IGN);
5019 signal(SIGABRT, SIG_IGN);
5020
5021 if (options & SHELL_COOKED)
5022 settmode(TMODE_COOK); /* set to normal mode */
5023
5024 if (cmd == NULL)
5025 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005026 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005027 }
5028 else
5029 {
5030 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005031 char_u *newcmd = NULL;
5032 char_u *cmdbase = cmd;
5033 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005034
5035 /* Skip a leading ", ( and "(. */
5036 if (*cmdbase == '"' )
5037 ++cmdbase;
5038 if (*cmdbase == '(')
5039 ++cmdbase;
5040
Bram Moolenaar1c465442017-03-12 20:10:05 +01005041 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005042 {
5043 STARTUPINFO si;
5044 PROCESS_INFORMATION pi;
5045 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005046 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005047 char_u *p;
5048
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005049 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005050 si.cb = sizeof(si);
5051 si.lpReserved = NULL;
5052 si.lpDesktop = NULL;
5053 si.lpTitle = NULL;
5054 si.dwFlags = 0;
5055 si.cbReserved2 = 0;
5056 si.lpReserved2 = NULL;
5057
5058 cmdbase = skipwhite(cmdbase + 5);
5059 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005060 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005061 {
5062 cmdbase = skipwhite(cmdbase + 4);
5063 si.dwFlags = STARTF_USESHOWWINDOW;
5064 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005065 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005066 }
5067 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005068 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005069 {
5070 cmdbase = skipwhite(cmdbase + 2);
5071 flags = CREATE_NO_WINDOW;
5072 si.dwFlags = STARTF_USESTDHANDLES;
5073 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005074 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005075 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005076 NULL, // Security att.
5077 OPEN_EXISTING, // Open flags
5078 FILE_ATTRIBUTE_NORMAL, // File att.
5079 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005080 si.hStdOutput = si.hStdInput;
5081 si.hStdError = si.hStdInput;
5082 }
5083
5084 /* Remove a trailing ", ) and )" if they have a match
5085 * at the start of the command. */
5086 if (cmdbase > cmd)
5087 {
5088 p = cmdbase + STRLEN(cmdbase);
5089 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5090 *--p = NUL;
5091 if (p > cmdbase && p[-1] == ')'
5092 && (*cmd =='(' || cmd[1] == '('))
5093 *--p = NUL;
5094 }
5095
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005096 newcmd = cmdbase;
5097 unescape_shellxquote(cmdbase, p_sxe);
5098
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005099 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005100 * If creating new console, arguments are passed to the
5101 * 'cmd.exe' as-is. If it's not, arguments are not treated
5102 * correctly for current 'cmd.exe'. So unescape characters in
5103 * shellxescape except '|' for avoiding to be treated as
5104 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005105 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005106 if (flags != CREATE_NEW_CONSOLE)
5107 {
5108 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005109 char_u *cmd_shell = mch_getenv("COMSPEC");
5110
5111 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005112 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005113
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005114 subcmd = vim_strsave_escaped_ext(cmdbase,
5115 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005116 if (subcmd != NULL)
5117 {
5118 /* make "cmd.exe /c arguments" */
5119 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005120 newcmd = lalloc(cmdlen, TRUE);
5121 if (newcmd != NULL)
5122 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005123 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005124 else
5125 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005126 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005127 }
5128 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005129
5130 /*
5131 * Now, start the command as a process, so that it doesn't
5132 * inherit our handles which causes unpleasant dangling swap
5133 * files if we exit before the spawned process
5134 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005135 if (vim_create_process((char *)newcmd, FALSE, flags,
5136 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005137 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005138 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5139 > (HINSTANCE)32)
5140 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005141 else
5142 {
5143 x = -1;
5144#ifdef FEAT_GUI_W32
5145 EMSG(_("E371: Command not found"));
5146#endif
5147 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005148
5149 if (newcmd != cmdbase)
5150 vim_free(newcmd);
5151
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005152 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005153 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005154 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005155 CloseHandle(si.hStdInput);
5156 }
5157 /* Close the handles to the subprocess, so that it goes away */
5158 CloseHandle(pi.hThread);
5159 CloseHandle(pi.hProcess);
5160 }
5161 else
5162 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005163 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005164#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005165 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005166#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005167 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5168
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005169 newcmd = lalloc(cmdlen, TRUE);
5170 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005171 {
5172#if defined(FEAT_GUI_W32)
5173 if (need_vimrun_warning)
5174 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005175 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5176 "External commands will not pause after completion.\n"
5177 "See :help win32-vimrun for more information.");
5178 char *title = _("Vim Warning");
5179# ifdef FEAT_MBYTE
5180 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5181 {
5182 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5183 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5184
5185 if (wmsg != NULL && wtitle != NULL)
5186 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5187 vim_free(wmsg);
5188 vim_free(wtitle);
5189 }
5190 else
5191# endif
5192 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005193 need_vimrun_warning = FALSE;
5194 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005195 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005196 /* Use vimrun to execute the command. It opens a console
5197 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005198 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005199 vimrun_path,
5200 (msg_silent != 0 || (options & SHELL_DOOUT))
5201 ? "-s " : "",
5202 p_sh, p_shcf, cmd);
5203 else
5204#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005205 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005206 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005208 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005209 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005210 }
5211 }
5212
5213 if (tmode == TMODE_RAW)
5214 settmode(TMODE_RAW); /* set to raw mode */
5215
5216 /* Print the return value, unless "vimrun" was used. */
5217 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5218#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005219 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005220#endif
5221 )
5222 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005223 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005224 msg_putchar('\n');
5225 }
5226#ifdef FEAT_TITLE
5227 resettitle();
5228#endif
5229
5230 signal(SIGINT, SIG_DFL);
5231#if defined(__GNUC__) && !defined(__MINGW32__)
5232 signal(SIGKILL, SIG_DFL);
5233#else
5234 signal(SIGBREAK, SIG_DFL);
5235#endif
5236 signal(SIGILL, SIG_DFL);
5237 signal(SIGFPE, SIG_DFL);
5238 signal(SIGSEGV, SIG_DFL);
5239 signal(SIGTERM, SIG_DFL);
5240 signal(SIGABRT, SIG_DFL);
5241
5242 return x;
5243}
5244
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005245#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005246 static HANDLE
5247job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005248 char_u *fname,
5249 DWORD dwDesiredAccess,
5250 DWORD dwShareMode,
5251 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5252 DWORD dwCreationDisposition,
5253 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005254{
5255 HANDLE h;
5256# ifdef FEAT_MBYTE
5257 WCHAR *wn = NULL;
5258 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5259 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005260 wn = enc_to_utf16(fname, NULL);
5261 if (wn != NULL)
5262 {
5263 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5264 lpSecurityAttributes, dwCreationDisposition,
5265 dwFlagsAndAttributes, NULL);
5266 vim_free(wn);
5267 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005268 }
5269 if (wn == NULL)
5270# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005271 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5272 lpSecurityAttributes, dwCreationDisposition,
5273 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005274 return h;
5275}
5276
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005277/*
5278 * Turn the dictionary "env" into a NUL separated list that can be used as the
5279 * environment argument of vim_create_process().
5280 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005281 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005282win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005283{
5284 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005285 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005286 LPVOID base = GetEnvironmentStringsW();
5287
5288 /* for last \0 */
5289 if (ga_grow(gap, 1) == FAIL)
5290 return;
5291
5292 if (base)
5293 {
5294 WCHAR *p = (WCHAR*) base;
5295
5296 /* for last \0 */
5297 if (ga_grow(gap, 1) == FAIL)
5298 return;
5299
5300 while (*p != 0 || *(p + 1) != 0)
5301 {
5302 if (ga_grow(gap, 1) == OK)
5303 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5304 p++;
5305 }
5306 FreeEnvironmentStrings(base);
5307 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5308 }
5309
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005310 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005311 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005312 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005313 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005314 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005315 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005316 typval_T *item = &dict_lookup(hi)->di_tv;
5317 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5318 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5319 --todo;
5320 if (wkey != NULL && wval != NULL)
5321 {
5322 size_t n;
5323 size_t lkey = wcslen(wkey);
5324 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005325
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005326 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5327 continue;
5328 for (n = 0; n < lkey; n++)
5329 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5330 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5331 for (n = 0; n < lval; n++)
5332 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5333 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5334 }
5335 if (wkey != NULL) vim_free(wkey);
5336 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005337 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005338 }
5339 }
5340
Bram Moolenaar493359e2018-06-12 20:25:52 +02005341# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005342 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005343# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005344 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005345 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005346# endif
5347# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005348 char_u *version = get_vim_var_str(VV_VERSION);
5349 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005350# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005351 // size of "VIM_SERVERNAME=" and value,
5352 // plus "VIM_TERMINAL=" and value,
5353 // plus two terminating NULs
5354 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005355# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005356 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005357# endif
5358# ifdef FEAT_TERMINAL
5359 + 13 + version_len + 2
5360# endif
5361 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005362
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005363 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005364 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005365# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005366 for (n = 0; n < 15; n++)
5367 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5368 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005369 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005370 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5371 (WCHAR)servername[n];
5372 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005373# endif
5374# ifdef FEAT_TERMINAL
5375 if (is_terminal)
5376 {
5377 for (n = 0; n < 13; n++)
5378 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5379 (WCHAR)"VIM_TERMINAL="[n];
5380 for (n = 0; n < version_len; n++)
5381 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5382 (WCHAR)version[n];
5383 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5384 }
5385# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005386 }
5387 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005388# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005389}
5390
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005391 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005392mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005393{
5394 STARTUPINFO si;
5395 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005396 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005397 SECURITY_ATTRIBUTES saAttr;
5398 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005399 HANDLE ifd[2];
5400 HANDLE ofd[2];
5401 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005402 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005403
5404 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5405 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5406 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5407 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5408 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5409 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5410 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5411
5412 if (use_out_for_err && use_null_for_out)
5413 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005414
5415 ifd[0] = INVALID_HANDLE_VALUE;
5416 ifd[1] = INVALID_HANDLE_VALUE;
5417 ofd[0] = INVALID_HANDLE_VALUE;
5418 ofd[1] = INVALID_HANDLE_VALUE;
5419 efd[0] = INVALID_HANDLE_VALUE;
5420 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005421 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005422
Bram Moolenaar14207f42016-10-27 21:13:10 +02005423 jo = CreateJobObject(NULL, NULL);
5424 if (jo == NULL)
5425 {
5426 job->jv_status = JOB_FAILED;
5427 goto failed;
5428 }
5429
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005430 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005431 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005432
Bram Moolenaar76467df2016-02-12 19:30:26 +01005433 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005434 ZeroMemory(&si, sizeof(si));
5435 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005436 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005437 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005438
Bram Moolenaard8070362016-02-15 21:56:54 +01005439 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5440 saAttr.bInheritHandle = TRUE;
5441 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005442
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005443 if (use_file_for_in)
5444 {
5445 char_u *fname = options->jo_io_name[PART_IN];
5446
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005447 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5448 FILE_SHARE_READ | FILE_SHARE_WRITE,
5449 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5450 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005451 {
5452 EMSG2(_(e_notopen), fname);
5453 goto failed;
5454 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005455 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005456 else if (!use_null_for_in &&
5457 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005458 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005459 goto failed;
5460
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005461 if (use_file_for_out)
5462 {
5463 char_u *fname = options->jo_io_name[PART_OUT];
5464
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005465 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5466 FILE_SHARE_READ | FILE_SHARE_WRITE,
5467 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5468 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005469 {
5470 EMSG2(_(e_notopen), fname);
5471 goto failed;
5472 }
5473 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005474 else if (!use_null_for_out &&
5475 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005476 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005477 goto failed;
5478
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005479 if (use_file_for_err)
5480 {
5481 char_u *fname = options->jo_io_name[PART_ERR];
5482
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005483 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5484 FILE_SHARE_READ | FILE_SHARE_WRITE,
5485 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5486 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005487 {
5488 EMSG2(_(e_notopen), fname);
5489 goto failed;
5490 }
5491 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005492 else if (!use_out_for_err && !use_null_for_err &&
5493 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005494 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005495 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005496
Bram Moolenaard8070362016-02-15 21:56:54 +01005497 si.dwFlags |= STARTF_USESTDHANDLES;
5498 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005499 si.hStdOutput = ofd[1];
5500 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5501
5502 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5503 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005504 if (options->jo_set & JO_CHANNEL)
5505 {
5506 channel = options->jo_channel;
5507 if (channel != NULL)
5508 ++channel->ch_refcount;
5509 }
5510 else
5511 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005512 if (channel == NULL)
5513 goto failed;
5514 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005515
5516 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005517 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005518 CREATE_DEFAULT_ERROR_MODE |
5519 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005520 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005521 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005522 &si, &pi,
5523 ga.ga_data,
5524 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005525 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005526 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005527 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005528 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005529 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005530
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005531 ga_clear(&ga);
5532
Bram Moolenaar14207f42016-10-27 21:13:10 +02005533 if (!AssignProcessToJobObject(jo, pi.hProcess))
5534 {
5535 /* if failing, switch the way to terminate
5536 * process with TerminateProcess. */
5537 CloseHandle(jo);
5538 jo = NULL;
5539 }
5540 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005541 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005542 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005543 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005544 job->jv_status = JOB_STARTED;
5545
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005546 CloseHandle(ifd[0]);
5547 CloseHandle(ofd[1]);
5548 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005549 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005550
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005551 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005552 if (channel != NULL)
5553 {
5554 channel_set_pipes(channel,
5555 use_file_for_in || use_null_for_in
5556 ? INVALID_FD : (sock_T)ifd[1],
5557 use_file_for_out || use_null_for_out
5558 ? INVALID_FD : (sock_T)ofd[0],
5559 use_out_for_err || use_file_for_err || use_null_for_err
5560 ? INVALID_FD : (sock_T)efd[0]);
5561 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005562 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005563 return;
5564
5565failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005566 CloseHandle(ifd[0]);
5567 CloseHandle(ofd[0]);
5568 CloseHandle(efd[0]);
5569 CloseHandle(ifd[1]);
5570 CloseHandle(ofd[1]);
5571 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005572 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005573 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005574}
5575
5576 char *
5577mch_job_status(job_T *job)
5578{
5579 DWORD dwExitCode = 0;
5580
Bram Moolenaar76467df2016-02-12 19:30:26 +01005581 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5582 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005583 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005584 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005585 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005586 {
5587 ch_log(job->jv_channel, "Job ended");
5588 job->jv_status = JOB_ENDED;
5589 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005590 return "dead";
5591 }
5592 return "run";
5593}
5594
Bram Moolenaar97792de2016-10-15 18:36:49 +02005595 job_T *
5596mch_detect_ended_job(job_T *job_list)
5597{
5598 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5599 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5600 job_T *job = job_list;
5601
5602 while (job != NULL)
5603 {
5604 DWORD n;
5605 DWORD result;
5606
5607 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5608 && job != NULL; job = job->jv_next)
5609 {
5610 if (job->jv_status == JOB_STARTED)
5611 {
5612 jobHandles[n] = job->jv_proc_info.hProcess;
5613 jobArray[n] = job;
5614 ++n;
5615 }
5616 }
5617 if (n == 0)
5618 continue;
5619 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5620 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5621 {
5622 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5623
5624 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5625 return wait_job;
5626 }
5627 }
5628 return NULL;
5629}
5630
Bram Moolenaarfb630902016-10-29 14:55:00 +02005631 static BOOL
5632terminate_all(HANDLE process, int code)
5633{
5634 PROCESSENTRY32 pe;
5635 HANDLE h = INVALID_HANDLE_VALUE;
5636 DWORD pid = GetProcessId(process);
5637
5638 if (pid != 0)
5639 {
5640 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5641 if (h != INVALID_HANDLE_VALUE)
5642 {
5643 pe.dwSize = sizeof(PROCESSENTRY32);
5644 if (!Process32First(h, &pe))
5645 goto theend;
5646
5647 do
5648 {
5649 if (pe.th32ParentProcessID == pid)
5650 {
5651 HANDLE ph = OpenProcess(
5652 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5653 if (ph != NULL)
5654 {
5655 terminate_all(ph, code);
5656 CloseHandle(ph);
5657 }
5658 }
5659 } while (Process32Next(h, &pe));
5660
5661 CloseHandle(h);
5662 }
5663 }
5664
5665theend:
5666 return TerminateProcess(process, code);
5667}
5668
5669/*
5670 * Send a (deadly) signal to "job".
5671 * Return FAIL if it didn't work.
5672 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005673 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005674mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005675{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005676 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005677
Bram Moolenaar923d9262016-02-25 20:56:01 +01005678 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005679 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005680 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005681 if (job->jv_job_object != NULL)
5682 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005683 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005684 }
5685
5686 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5687 return FAIL;
5688 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005689 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5690 job->jv_proc_info.dwProcessId)
5691 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005692 FreeConsole();
5693 return ret;
5694}
5695
5696/*
5697 * Clear the data related to "job".
5698 */
5699 void
5700mch_clear_job(job_T *job)
5701{
5702 if (job->jv_status != JOB_FAILED)
5703 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005704 if (job->jv_job_object != NULL)
5705 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005706 CloseHandle(job->jv_proc_info.hProcess);
5707 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005708}
5709#endif
5710
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711
5712#ifndef FEAT_GUI_W32
5713
5714/*
5715 * Start termcap mode
5716 */
5717 static void
5718termcap_mode_start(void)
5719{
5720 DWORD cmodein;
5721
5722 if (g_fTermcapMode)
5723 return;
5724
5725 SaveConsoleBuffer(&g_cbNonTermcap);
5726
5727 if (g_cbTermcap.IsValid)
5728 {
5729 /*
5730 * We've been in termcap mode before. Restore certain screen
5731 * characteristics, including the buffer size and the window
5732 * size. Since we will be redrawing the screen, we don't need
5733 * to restore the actual contents of the buffer.
5734 */
5735 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005736 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005737 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5738 Rows = g_cbTermcap.Info.dwSize.Y;
5739 Columns = g_cbTermcap.Info.dwSize.X;
5740 }
5741 else
5742 {
5743 /*
5744 * This is our first time entering termcap mode. Clear the console
5745 * screen buffer, and resize the buffer to match the current window
5746 * size. We will use this as the size of our editing environment.
5747 */
5748 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005749 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005750 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5751 }
5752
5753#ifdef FEAT_TITLE
5754 resettitle();
5755#endif
5756
5757 GetConsoleMode(g_hConIn, &cmodein);
5758#ifdef FEAT_MOUSE
5759 if (g_fMouseActive)
5760 cmodein |= ENABLE_MOUSE_INPUT;
5761 else
5762 cmodein &= ~ENABLE_MOUSE_INPUT;
5763#endif
5764 cmodein |= ENABLE_WINDOW_INPUT;
5765 SetConsoleMode(g_hConIn, cmodein);
5766
5767 redraw_later_clear();
5768 g_fTermcapMode = TRUE;
5769}
5770
5771
5772/*
5773 * End termcap mode
5774 */
5775 static void
5776termcap_mode_end(void)
5777{
5778 DWORD cmodein;
5779 ConsoleBuffer *cb;
5780 COORD coord;
5781 DWORD dwDummy;
5782
5783 if (!g_fTermcapMode)
5784 return;
5785
5786 SaveConsoleBuffer(&g_cbTermcap);
5787
5788 GetConsoleMode(g_hConIn, &cmodein);
5789 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5790 SetConsoleMode(g_hConIn, cmodein);
5791
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005792#ifdef FEAT_RESTORE_ORIG_SCREEN
5793 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5794#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005796#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005798 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799 SetConsoleCursorInfo(g_hConOut, &g_cci);
5800
5801 if (p_rs || exiting)
5802 {
5803 /*
5804 * Clear anything that happens to be on the current line.
5805 */
5806 coord.X = 0;
5807 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5808 FillConsoleOutputCharacter(g_hConOut, ' ',
5809 cb->Info.dwSize.X, coord, &dwDummy);
5810 /*
5811 * The following is just for aesthetics. If we are exiting without
5812 * restoring the screen, then we want to have a prompt string
5813 * appear at the bottom line. However, the command interpreter
5814 * seems to always advance the cursor one line before displaying
5815 * the prompt string, which causes the screen to scroll. To
5816 * counter this, move the cursor up one line before exiting.
5817 */
5818 if (exiting && !p_rs)
5819 coord.Y--;
5820 /*
5821 * Position the cursor at the leftmost column of the desired row.
5822 */
5823 SetConsoleCursorPosition(g_hConOut, coord);
5824 }
5825
5826 g_fTermcapMode = FALSE;
5827}
5828#endif /* FEAT_GUI_W32 */
5829
5830
5831#ifdef FEAT_GUI_W32
5832 void
5833mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005834 char_u *s UNUSED,
5835 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005836{
5837 /* never used */
5838}
5839
5840#else
5841
5842/*
5843 * clear `n' chars, starting from `coord'
5844 */
5845 static void
5846clear_chars(
5847 COORD coord,
5848 DWORD n)
5849{
5850 DWORD dwDummy;
5851
5852 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005853
5854 if (!USE_VTP)
5855 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5856 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005857 {
5858 set_console_color_rgb();
5859 gotoxy(coord.X + 1, coord.Y + 1);
5860 vtp_printf("\033[%dX", n);
5861 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862}
5863
5864
5865/*
5866 * Clear the screen
5867 */
5868 static void
5869clear_screen(void)
5870{
5871 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005872
5873 if (!USE_VTP)
5874 clear_chars(g_coord, Rows * Columns);
5875 else
5876 {
5877 set_console_color_rgb();
5878 gotoxy(1, 1);
5879 vtp_printf("\033[2J");
5880 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005881}
5882
5883
5884/*
5885 * Clear to end of display
5886 */
5887 static void
5888clear_to_end_of_display(void)
5889{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005890 COORD save = g_coord;
5891
5892 if (!USE_VTP)
5893 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005894 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005895 else
5896 {
5897 set_console_color_rgb();
5898 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5899 vtp_printf("\033[0J");
5900
5901 gotoxy(save.X + 1, save.Y + 1);
5902 g_coord = save;
5903 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005904}
5905
5906
5907/*
5908 * Clear to end of line
5909 */
5910 static void
5911clear_to_end_of_line(void)
5912{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005913 COORD save = g_coord;
5914
5915 if (!USE_VTP)
5916 clear_chars(g_coord, Columns - g_coord.X);
5917 else
5918 {
5919 set_console_color_rgb();
5920 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5921 vtp_printf("\033[0K");
5922
5923 gotoxy(save.X + 1, save.Y + 1);
5924 g_coord = save;
5925 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005926}
5927
5928
5929/*
5930 * Scroll the scroll region up by `cLines' lines
5931 */
5932 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005933scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005934{
5935 COORD oldcoord = g_coord;
5936
5937 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5938 delete_lines(cLines);
5939
5940 g_coord = oldcoord;
5941}
5942
5943
5944/*
5945 * Set the scroll region
5946 */
5947 static void
5948set_scroll_region(
5949 unsigned left,
5950 unsigned top,
5951 unsigned right,
5952 unsigned bottom)
5953{
5954 if (left >= right
5955 || top >= bottom
5956 || right > (unsigned) Columns - 1
5957 || bottom > (unsigned) Rows - 1)
5958 return;
5959
5960 g_srScrollRegion.Left = left;
5961 g_srScrollRegion.Top = top;
5962 g_srScrollRegion.Right = right;
5963 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005964
5965 if (USE_VTP)
5966 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005967}
5968
5969
5970/*
5971 * Insert `cLines' lines at the current cursor position
5972 */
5973 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005974insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005975{
5976 SMALL_RECT source;
5977 COORD dest;
5978 CHAR_INFO fill;
5979
5980 dest.X = 0;
5981 dest.Y = g_coord.Y + cLines;
5982
5983 source.Left = 0;
5984 source.Top = g_coord.Y;
5985 source.Right = g_srScrollRegion.Right;
5986 source.Bottom = g_srScrollRegion.Bottom - cLines;
5987
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005988 if (!USE_VTP)
5989 {
5990 fill.Char.AsciiChar = ' ';
5991 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005993 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5994 }
5995 else
5996 {
5997 set_console_color_rgb();
5998
5999 gotoxy(1, source.Top + 1);
6000 vtp_printf("\033[%dT", cLines);
6001 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002
6003 /* Here we have to deal with a win32 console flake: If the scroll
6004 * region looks like abc and we scroll c to a and fill with d we get
6005 * cbd... if we scroll block c one line at a time to a, we get cdd...
6006 * vim expects cdd consistently... So we have to deal with that
6007 * here... (this also occurs scrolling the same way in the other
6008 * direction). */
6009
6010 if (source.Bottom < dest.Y)
6011 {
6012 COORD coord;
6013
6014 coord.X = 0;
6015 coord.Y = source.Bottom;
6016 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6017 }
6018}
6019
6020
6021/*
6022 * Delete `cLines' lines at the current cursor position
6023 */
6024 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006025delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026{
6027 SMALL_RECT source;
6028 COORD dest;
6029 CHAR_INFO fill;
6030 int nb;
6031
6032 dest.X = 0;
6033 dest.Y = g_coord.Y;
6034
6035 source.Left = 0;
6036 source.Top = g_coord.Y + cLines;
6037 source.Right = g_srScrollRegion.Right;
6038 source.Bottom = g_srScrollRegion.Bottom;
6039
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006040 if (!USE_VTP)
6041 {
6042 fill.Char.AsciiChar = ' ';
6043 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006045 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6046 }
6047 else
6048 {
6049 set_console_color_rgb();
6050
6051 gotoxy(1, source.Top + 1);
6052 vtp_printf("\033[%dS", cLines);
6053 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054
6055 /* Here we have to deal with a win32 console flake: If the scroll
6056 * region looks like abc and we scroll c to a and fill with d we get
6057 * cbd... if we scroll block c one line at a time to a, we get cdd...
6058 * vim expects cdd consistently... So we have to deal with that
6059 * here... (this also occurs scrolling the same way in the other
6060 * direction). */
6061
6062 nb = dest.Y + (source.Bottom - source.Top) + 1;
6063
6064 if (nb < source.Top)
6065 {
6066 COORD coord;
6067
6068 coord.X = 0;
6069 coord.Y = nb;
6070 clear_chars(coord, Columns * (source.Top - nb));
6071 }
6072}
6073
6074
6075/*
6076 * Set the cursor position
6077 */
6078 static void
6079gotoxy(
6080 unsigned x,
6081 unsigned y)
6082{
6083 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6084 return;
6085
6086 /* external cursor coords are 1-based; internal are 0-based */
6087 g_coord.X = x - 1;
6088 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006089
6090 if (!USE_VTP)
6091 SetConsoleCursorPosition(g_hConOut, g_coord);
6092 else
6093 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006094}
6095
6096
6097/*
6098 * Set the current text attribute = (foreground | background)
6099 * See ../doc/os_win32.txt for the numbers.
6100 */
6101 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006102textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006104 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006105
6106 SetConsoleTextAttribute(g_hConOut, wAttr);
6107}
6108
6109
6110 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006111textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006113 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006115 if (!USE_VTP)
6116 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6117 else
6118 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006119}
6120
6121
6122 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006123textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006125 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006127 if (!USE_VTP)
6128 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6129 else
6130 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131}
6132
6133
6134/*
6135 * restore the default text attribute (whatever we started with)
6136 */
6137 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006138normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006140 if (!USE_VTP)
6141 textattr(g_attrDefault);
6142 else
6143 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144}
6145
6146
6147static WORD g_attrPreStandout = 0;
6148
6149/*
6150 * Make the text standout, by brightening it
6151 */
6152 static void
6153standout(void)
6154{
6155 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006156
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6158}
6159
6160
6161/*
6162 * Turn off standout mode
6163 */
6164 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006165standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166{
6167 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006169
6170 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006171}
6172
6173
6174/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006175 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176 */
6177 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006178mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179{
6180 char_u *p;
6181 int n;
6182
6183 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6184 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006185 if (
6186#ifdef FEAT_TERMGUICOLORS
6187 !p_tgc &&
6188#endif
6189 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006190 {
6191 p = T_ME + 2;
6192 n = getdigits(&p);
6193 if (*p == 'm' && n > 0)
6194 {
6195 cterm_normal_fg_color = (n & 0xf) + 1;
6196 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6197 }
6198 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006199#ifdef FEAT_TERMGUICOLORS
6200 cterm_normal_fg_gui_color = INVALCOLOR;
6201 cterm_normal_bg_gui_color = INVALCOLOR;
6202#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203}
6204
6205
6206/*
6207 * visual bell: flash the screen
6208 */
6209 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006210visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006211{
6212 COORD coordOrigin = {0, 0};
6213 WORD attrFlash = ~g_attrCurrent & 0xff;
6214
6215 DWORD dwDummy;
6216 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6217
6218 if (oldattrs == NULL)
6219 return;
6220 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6221 coordOrigin, &dwDummy);
6222 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6223 coordOrigin, &dwDummy);
6224
6225 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006226 if (!USE_VTP)
6227 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006228 coordOrigin, &dwDummy);
6229 vim_free(oldattrs);
6230}
6231
6232
6233/*
6234 * Make the cursor visible or invisible
6235 */
6236 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006237cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238{
6239 s_cursor_visible = fVisible;
6240#ifdef MCH_CURSOR_SHAPE
6241 mch_update_cursor();
6242#endif
6243}
6244
6245
6246/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006247 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006248 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006250 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006252 char_u *pchBuf,
6253 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254{
6255 COORD coord = g_coord;
6256 DWORD written;
6257
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006258#ifdef FEAT_MBYTE
6259 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6260 {
6261 static WCHAR *unicodebuf = NULL;
6262 static int unibuflen = 0;
6263 int length;
6264 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006266 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6267 if (unicodebuf == NULL || length > unibuflen)
6268 {
6269 vim_free(unicodebuf);
6270 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6271 unibuflen = length;
6272 }
6273 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6274 unicodebuf, unibuflen);
6275
6276 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006277
6278 if (!USE_VTP)
6279 {
6280 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6281 coord, &written);
6282 /* When writing fails or didn't write a single character, pretend one
6283 * character was written, otherwise we get stuck. */
6284 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6285 coord, &cchwritten) == 0
6286 || cchwritten == 0)
6287 cchwritten = 1;
6288 }
6289 else
6290 {
6291 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6292 NULL) == 0 || cchwritten == 0)
6293 cchwritten = 1;
6294 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006295
6296 if (cchwritten == length)
6297 {
6298 written = cbToWrite;
6299 g_coord.X += (SHORT)cells;
6300 }
6301 else
6302 {
6303 char_u *p = pchBuf;
6304 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006305 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006306 written = p - pchBuf;
6307 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6308 }
6309 }
6310 else
6311#endif
6312 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006313 if (!USE_VTP)
6314 {
6315 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6316 coord, &written);
6317 /* When writing fails or didn't write a single character, pretend one
6318 * character was written, otherwise we get stuck. */
6319 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6320 coord, &written) == 0
6321 || written == 0)
6322 written = 1;
6323 }
6324 else
6325 {
6326 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6327 NULL) == 0 || written == 0)
6328 written = 1;
6329 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006330
6331 g_coord.X += (SHORT) written;
6332 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333
6334 while (g_coord.X > g_srScrollRegion.Right)
6335 {
6336 g_coord.X -= (SHORT) Columns;
6337 if (g_coord.Y < g_srScrollRegion.Bottom)
6338 g_coord.Y++;
6339 }
6340
6341 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6342
6343 return written;
6344}
6345
6346
6347/*
6348 * mch_write(): write the output buffer to the screen, translating ESC
6349 * sequences into calls to console output routines.
6350 */
6351 void
6352mch_write(
6353 char_u *s,
6354 int len)
6355{
6356 s[len] = NUL;
6357
6358 if (!term_console)
6359 {
6360 write(1, s, (unsigned)len);
6361 return;
6362 }
6363
6364 /* translate ESC | sequences into faked bios calls */
6365 while (len--)
6366 {
6367 /* optimization: use one single write_chars for runs of text,
6368 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006369 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006370
6371 if (p_wd)
6372 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006373 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006374 if (prefix != 0)
6375 prefix = 1;
6376 }
6377
6378 if (prefix != 0)
6379 {
6380 DWORD nWritten;
6381
6382 nWritten = write_chars(s, prefix);
6383#ifdef MCH_WRITE_DUMP
6384 if (fdDump)
6385 {
6386 fputc('>', fdDump);
6387 fwrite(s, sizeof(char_u), nWritten, fdDump);
6388 fputs("<\n", fdDump);
6389 }
6390#endif
6391 len -= (nWritten - 1);
6392 s += nWritten;
6393 }
6394 else if (s[0] == '\n')
6395 {
6396 /* \n, newline: go to the beginning of the next line or scroll */
6397 if (g_coord.Y == g_srScrollRegion.Bottom)
6398 {
6399 scroll(1);
6400 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6401 }
6402 else
6403 {
6404 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6405 }
6406#ifdef MCH_WRITE_DUMP
6407 if (fdDump)
6408 fputs("\\n\n", fdDump);
6409#endif
6410 s++;
6411 }
6412 else if (s[0] == '\r')
6413 {
6414 /* \r, carriage return: go to beginning of line */
6415 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6416#ifdef MCH_WRITE_DUMP
6417 if (fdDump)
6418 fputs("\\r\n", fdDump);
6419#endif
6420 s++;
6421 }
6422 else if (s[0] == '\b')
6423 {
6424 /* \b, backspace: move cursor one position left */
6425 if (g_coord.X > g_srScrollRegion.Left)
6426 g_coord.X--;
6427 else if (g_coord.Y > g_srScrollRegion.Top)
6428 {
6429 g_coord.X = g_srScrollRegion.Right;
6430 g_coord.Y--;
6431 }
6432 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6433#ifdef MCH_WRITE_DUMP
6434 if (fdDump)
6435 fputs("\\b\n", fdDump);
6436#endif
6437 s++;
6438 }
6439 else if (s[0] == '\a')
6440 {
6441 /* \a, bell */
6442 MessageBeep(0xFFFFFFFF);
6443#ifdef MCH_WRITE_DUMP
6444 if (fdDump)
6445 fputs("\\a\n", fdDump);
6446#endif
6447 s++;
6448 }
6449 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6450 {
6451#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006452 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006453#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006454 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006455 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456
6457 switch (s[2])
6458 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459 case '0': case '1': case '2': case '3': case '4':
6460 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006461 p = s + 1;
6462 do
6463 {
6464 ++p;
6465 args[argc] = getdigits(&p);
6466 argc += (argc < 15) ? 1 : 0;
6467 if (p > s + len)
6468 break;
6469 } while (*p == ';');
6470
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471 if (p > s + len)
6472 break;
6473
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006474 arg1 = args[0];
6475 arg2 = args[1];
6476 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006478 if (argc == 1 && args[0] == 0)
6479 normvideo();
6480 else if (argc == 1)
6481 {
6482 if (USE_VTP)
6483 textcolor((WORD) arg1);
6484 else
6485 textattr((WORD) arg1);
6486 }
6487 else if (USE_VTP)
6488 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006490 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006492 gotoxy(arg2, arg1);
6493 }
6494 else if (argc == 2 && *p == 'r')
6495 {
6496 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6497 }
6498 else if (argc == 1 && *p == 'A')
6499 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006500 gotoxy(g_coord.X + 1,
6501 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6502 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006503 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504 {
6505 textbackground((WORD) arg1);
6506 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006507 else if (argc == 1 && *p == 'C')
6508 {
6509 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6510 g_coord.Y + 1);
6511 }
6512 else if (argc == 1 && *p == 'f')
6513 {
6514 textcolor((WORD) arg1);
6515 }
6516 else if (argc == 1 && *p == 'H')
6517 {
6518 gotoxy(1, arg1);
6519 }
6520 else if (argc == 1 && *p == 'L')
6521 {
6522 insert_lines(arg1);
6523 }
6524 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006525 {
6526 delete_lines(arg1);
6527 }
6528
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006529 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006530 s = p + 1;
6531 break;
6532
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006534 gotoxy(g_coord.X + 1,
6535 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6536 goto got3;
6537
6538 case 'B':
6539 visual_bell();
6540 goto got3;
6541
6542 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6544 g_coord.Y + 1);
6545 goto got3;
6546
6547 case 'E':
6548 termcap_mode_end();
6549 goto got3;
6550
6551 case 'F':
6552 standout();
6553 goto got3;
6554
6555 case 'f':
6556 standend();
6557 goto got3;
6558
6559 case 'H':
6560 gotoxy(1, 1);
6561 goto got3;
6562
6563 case 'j':
6564 clear_to_end_of_display();
6565 goto got3;
6566
6567 case 'J':
6568 clear_screen();
6569 goto got3;
6570
6571 case 'K':
6572 clear_to_end_of_line();
6573 goto got3;
6574
6575 case 'L':
6576 insert_lines(1);
6577 goto got3;
6578
6579 case 'M':
6580 delete_lines(1);
6581 goto got3;
6582
6583 case 'S':
6584 termcap_mode_start();
6585 goto got3;
6586
6587 case 'V':
6588 cursor_visible(TRUE);
6589 goto got3;
6590
6591 case 'v':
6592 cursor_visible(FALSE);
6593 goto got3;
6594
6595 got3:
6596 s += 3;
6597 len -= 2;
6598 }
6599
6600#ifdef MCH_WRITE_DUMP
6601 if (fdDump)
6602 {
6603 fputs("ESC | ", fdDump);
6604 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6605 fputc('\n', fdDump);
6606 }
6607#endif
6608 }
6609 else
6610 {
6611 /* Write a single character */
6612 DWORD nWritten;
6613
6614 nWritten = write_chars(s, 1);
6615#ifdef MCH_WRITE_DUMP
6616 if (fdDump)
6617 {
6618 fputc('>', fdDump);
6619 fwrite(s, sizeof(char_u), nWritten, fdDump);
6620 fputs("<\n", fdDump);
6621 }
6622#endif
6623
6624 len -= (nWritten - 1);
6625 s += nWritten;
6626 }
6627 }
6628
6629#ifdef MCH_WRITE_DUMP
6630 if (fdDump)
6631 fflush(fdDump);
6632#endif
6633}
6634
6635#endif /* FEAT_GUI_W32 */
6636
6637
6638/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006639 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006640 */
6641 void
6642mch_delay(
6643 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006644 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645{
6646#ifdef FEAT_GUI_W32
6647 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006648#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006650# ifdef FEAT_MZSCHEME
6651 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6652 {
6653 int towait = p_mzq;
6654
6655 /* if msec is large enough, wait by portions in p_mzq */
6656 while (msec > 0)
6657 {
6658 mzvim_check_threads();
6659 if (msec < towait)
6660 towait = msec;
6661 Sleep(towait);
6662 msec -= towait;
6663 }
6664 }
6665 else
6666# endif
6667 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006669 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006670#endif
6671}
6672
6673
6674/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006675 * This version of remove is not scared by a readonly (backup) file.
6676 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006677 * Return 0 for success, -1 for failure.
6678 */
6679 int
6680mch_remove(char_u *name)
6681{
6682#ifdef FEAT_MBYTE
6683 WCHAR *wn = NULL;
6684 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006685#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686
Bram Moolenaar203258c2016-01-17 22:15:16 +01006687 /*
6688 * On Windows, deleting a directory's symbolic link is done by
6689 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6690 */
6691 if (mch_isdir(name) && mch_is_symbolic_link(name))
6692 return mch_rmdir(name);
6693
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006694 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6695
6696#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006697 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6698 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006699 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700 if (wn != NULL)
6701 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006702 n = DeleteFileW(wn) ? 0 : -1;
6703 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006704 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006705 }
6706 }
6707#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006708 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709}
6710
6711
6712/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006713 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006714 */
6715 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006716mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006717{
6718#ifndef FEAT_GUI_W32 /* never used */
6719 if (g_fCtrlCPressed || g_fCBrkPressed)
6720 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006721 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006722 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6723 got_int = TRUE;
6724 }
6725#endif
6726}
6727
Bram Moolenaaree273972016-01-02 21:11:51 +01006728/* physical RAM to leave for the OS */
6729#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006730
6731/*
6732 * How much main memory in KiB that can be used by VIM.
6733 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006734 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006735mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006736{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006737 MEMORYSTATUSEX ms;
6738
Bram Moolenaaree273972016-01-02 21:11:51 +01006739 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006740 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6741 * what fits in 32 bits. But it's not always available. */
6742 ms.dwLength = sizeof(MEMORYSTATUSEX);
6743 GlobalMemoryStatusEx(&ms);
6744 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006745 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006746 /* Process address space fits in physical RAM, use all of it. */
6747 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006748 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006749 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006750 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006751 /* Catch old NT box or perverse hardware setup. */
6752 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006753 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006754 /* Use physical RAM less reserve for OS + data. */
6755 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006756}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006757
Bram Moolenaar071d4272004-06-13 20:20:40 +00006758#ifdef FEAT_MBYTE
6759/*
6760 * Same code as below, but with wide functions and no comments.
6761 * Return 0 for success, non-zero for failure.
6762 */
6763 int
6764mch_wrename(WCHAR *wold, WCHAR *wnew)
6765{
6766 WCHAR *p;
6767 int i;
6768 WCHAR szTempFile[_MAX_PATH + 1];
6769 WCHAR szNewPath[_MAX_PATH + 1];
6770 HANDLE hf;
6771
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006772 p = wold;
6773 for (i = 0; wold[i] != NUL; ++i)
6774 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6775 && wold[i + 1] != 0)
6776 p = wold + i + 1;
6777 if ((int)(wold + i - p) < 8 || p[6] != '~')
6778 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779
6780 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6781 return -1;
6782 *p = NUL;
6783
6784 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6785 return -2;
6786
6787 if (!DeleteFileW(szTempFile))
6788 return -3;
6789
6790 if (!MoveFileW(wold, szTempFile))
6791 return -4;
6792
6793 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6794 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6795 return -5;
6796 if (!CloseHandle(hf))
6797 return -6;
6798
6799 if (!MoveFileW(szTempFile, wnew))
6800 {
6801 (void)MoveFileW(szTempFile, wold);
6802 return -7;
6803 }
6804
6805 DeleteFileW(szTempFile);
6806
6807 if (!DeleteFileW(wold))
6808 return -8;
6809
6810 return 0;
6811}
6812#endif
6813
6814
6815/*
6816 * mch_rename() works around a bug in rename (aka MoveFile) in
6817 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6818 * file whose short file name is "FOO.BAR" (its long file name will
6819 * be correct: "foo.bar~"). Because a file can be accessed by
6820 * either its SFN or its LFN, "foo.bar" has effectively been
6821 * renamed to "foo.bar", which is not at all what was wanted. This
6822 * seems to happen only when renaming files with three-character
6823 * extensions by appending a suffix that does not include ".".
6824 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6825 *
6826 * There is another problem, which isn't really a bug but isn't right either:
6827 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6828 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6829 * service pack 6. Doesn't seem to happen on Windows 98.
6830 *
6831 * Like rename(), returns 0 upon success, non-zero upon failure.
6832 * Should probably set errno appropriately when errors occur.
6833 */
6834 int
6835mch_rename(
6836 const char *pszOldFile,
6837 const char *pszNewFile)
6838{
6839 char szTempFile[_MAX_PATH+1];
6840 char szNewPath[_MAX_PATH+1];
6841 char *pszFilePart;
6842 HANDLE hf;
6843#ifdef FEAT_MBYTE
6844 WCHAR *wold = NULL;
6845 WCHAR *wnew = NULL;
6846 int retval = -1;
6847
6848 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6849 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006850 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6851 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852 if (wold != NULL && wnew != NULL)
6853 retval = mch_wrename(wold, wnew);
6854 vim_free(wold);
6855 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006856 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006857 }
6858#endif
6859
6860 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006861 * No need to play tricks unless the file name contains a "~" as the
6862 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006864 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6865 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6866 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006867
6868 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6869 * a directory, no error is returned and pszFilePart will be NULL. */
6870 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6871 || pszFilePart == NULL)
6872 return -1;
6873 *pszFilePart = NUL;
6874
6875 /* Get (and create) a unique temporary file name in directory of new file */
6876 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6877 return -2;
6878
6879 /* blow the temp file away */
6880 if (!DeleteFile(szTempFile))
6881 return -3;
6882
6883 /* rename old file to the temp file */
6884 if (!MoveFile(pszOldFile, szTempFile))
6885 return -4;
6886
6887 /* now create an empty file called pszOldFile; this prevents the operating
6888 * system using pszOldFile as an alias (SFN) if we're renaming within the
6889 * same directory. For example, we're editing a file called
6890 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6891 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6892 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006893 * cause all sorts of problems later in buf_write(). So, we create an
6894 * empty file called filena~1.txt and the system will have to find some
6895 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006896 */
6897 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6898 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6899 return -5;
6900 if (!CloseHandle(hf))
6901 return -6;
6902
6903 /* rename the temp file to the new file */
6904 if (!MoveFile(szTempFile, pszNewFile))
6905 {
6906 /* Renaming failed. Rename the file back to its old name, so that it
6907 * looks like nothing happened. */
6908 (void)MoveFile(szTempFile, pszOldFile);
6909
6910 return -7;
6911 }
6912
6913 /* Seems to be left around on Novell filesystems */
6914 DeleteFile(szTempFile);
6915
6916 /* finally, remove the empty old file */
6917 if (!DeleteFile(pszOldFile))
6918 return -8;
6919
6920 return 0; /* success */
6921}
6922
6923/*
6924 * Get the default shell for the current hardware platform
6925 */
6926 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006927default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929 PlatformId();
6930
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006931 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932}
6933
6934/*
6935 * mch_access() extends access() to do more detailed check on network drives.
6936 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6937 */
6938 int
6939mch_access(char *n, int p)
6940{
6941 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 int retval = -1; /* default: fail */
6943#ifdef FEAT_MBYTE
6944 WCHAR *wn = NULL;
6945
6946 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006947 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006948#endif
6949
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006950 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006951 {
6952 char TempName[_MAX_PATH + 16] = "";
6953#ifdef FEAT_MBYTE
6954 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6955#endif
6956
6957 if (p & R_OK)
6958 {
6959 /* Read check is performed by seeing if we can do a find file on
6960 * the directory for any file. */
6961#ifdef FEAT_MBYTE
6962 if (wn != NULL)
6963 {
6964 int i;
6965 WIN32_FIND_DATAW d;
6966
6967 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6968 TempNameW[i] = wn[i];
6969 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6970 TempNameW[i++] = '\\';
6971 TempNameW[i++] = '*';
6972 TempNameW[i++] = 0;
6973
6974 hFile = FindFirstFileW(TempNameW, &d);
6975 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006976 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006977 else
6978 (void)FindClose(hFile);
6979 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006980 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006981#endif
6982 {
6983 char *pch;
6984 WIN32_FIND_DATA d;
6985
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006986 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006987 pch = TempName + STRLEN(TempName) - 1;
6988 if (*pch != '\\' && *pch != '/')
6989 *++pch = '\\';
6990 *++pch = '*';
6991 *++pch = NUL;
6992
6993 hFile = FindFirstFile(TempName, &d);
6994 if (hFile == INVALID_HANDLE_VALUE)
6995 goto getout;
6996 (void)FindClose(hFile);
6997 }
6998 }
6999
7000 if (p & W_OK)
7001 {
7002 /* Trying to create a temporary file in the directory should catch
7003 * directories on read-only network shares. However, in
7004 * directories whose ACL allows writes but denies deletes will end
7005 * up keeping the temporary file :-(. */
7006#ifdef FEAT_MBYTE
7007 if (wn != NULL)
7008 {
7009 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007010 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011 else
7012 DeleteFileW(TempNameW);
7013 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007014 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007015#endif
7016 {
7017 if (!GetTempFileName(n, "VIM", 0, TempName))
7018 goto getout;
7019 mch_remove((char_u *)TempName);
7020 }
7021 }
7022 }
7023 else
7024 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007025 // Don't consider a file read-only if another process has opened it.
7026 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7027
Bram Moolenaar071d4272004-06-13 20:20:40 +00007028 /* Trying to open the file for the required access does ACL, read-only
7029 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007030 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7031 | ((p & R_OK) ? GENERIC_READ : 0);
7032
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033#ifdef FEAT_MBYTE
7034 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007035 hFile = CreateFileW(wn, access_mode, share_mode,
7036 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007037 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007038#endif
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007039 hFile = CreateFile(n, access_mode, share_mode,
7040 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007041 if (hFile == INVALID_HANDLE_VALUE)
7042 goto getout;
7043 CloseHandle(hFile);
7044 }
7045
7046 retval = 0; /* success */
7047getout:
7048#ifdef FEAT_MBYTE
7049 vim_free(wn);
7050#endif
7051 return retval;
7052}
7053
7054#if defined(FEAT_MBYTE) || defined(PROTO)
7055/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007056 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007057 */
7058 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007059mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007060{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007061 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
7062# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063 WCHAR *wn;
7064 int f;
7065
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007066 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007068 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069 if (wn != NULL)
7070 {
7071 f = _wopen(wn, flags, mode);
7072 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007073 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007074 }
7075 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007076# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007077
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007078 /* open() can open a file which name is longer than _MAX_PATH bytes
7079 * and shorter than _MAX_PATH characters successfully, but sometimes it
7080 * causes unexpected error in another part. We make it an error explicitly
7081 * here. */
7082 if (strlen(name) >= _MAX_PATH)
7083 return -1;
7084
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085 return open(name, flags, mode);
7086}
7087
7088/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007089 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007090 */
7091 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007092mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007093{
7094 WCHAR *wn, *wm;
7095 FILE *f = NULL;
7096
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007097 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007098 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007099# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007100 /* Work around an annoying assertion in the Microsoft debug CRT
7101 * when mode's text/binary setting doesn't match _get_fmode(). */
7102 char newMode = mode[strlen(mode) - 1];
7103 int oldMode = 0;
7104
7105 _get_fmode(&oldMode);
7106 if (newMode == 't')
7107 _set_fmode(_O_TEXT);
7108 else if (newMode == 'b')
7109 _set_fmode(_O_BINARY);
7110# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007111 wn = enc_to_utf16((char_u *)name, NULL);
7112 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007113 if (wn != NULL && wm != NULL)
7114 f = _wfopen(wn, wm);
7115 vim_free(wn);
7116 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007117
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007118# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007119 _set_fmode(oldMode);
7120# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007121 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007122 }
7123
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007124 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7125 * and shorter than _MAX_PATH characters successfully, but sometimes it
7126 * causes unexpected error in another part. We make it an error explicitly
7127 * here. */
7128 if (strlen(name) >= _MAX_PATH)
7129 return NULL;
7130
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131 return fopen(name, mode);
7132}
7133#endif
7134
7135#ifdef FEAT_MBYTE
7136/*
7137 * SUB STREAM (aka info stream) handling:
7138 *
7139 * NTFS can have sub streams for each file. Normal contents of file is
7140 * stored in the main stream, and extra contents (author information and
7141 * title and so on) can be stored in sub stream. After Windows 2000, user
7142 * can access and store those informations in sub streams via explorer's
7143 * property menuitem in right click menu. Those informations in sub streams
7144 * were lost when copying only the main stream. So we have to copy sub
7145 * streams.
7146 *
7147 * Incomplete explanation:
7148 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7149 * More useful info and an example:
7150 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7151 */
7152
7153/*
7154 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7155 * and write to stream "substream" of file "to".
7156 * Errors are ignored.
7157 */
7158 static void
7159copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7160{
7161 HANDLE hTo;
7162 WCHAR *to_name;
7163
7164 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7165 wcscpy(to_name, to);
7166 wcscat(to_name, substream);
7167
7168 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7169 FILE_ATTRIBUTE_NORMAL, NULL);
7170 if (hTo != INVALID_HANDLE_VALUE)
7171 {
7172 long done;
7173 DWORD todo;
7174 DWORD readcnt, written;
7175 char buf[4096];
7176
7177 /* Copy block of bytes at a time. Abort when something goes wrong. */
7178 for (done = 0; done < len; done += written)
7179 {
7180 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007181 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7182 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007183 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7184 FALSE, FALSE, context)
7185 || readcnt != todo
7186 || !WriteFile(hTo, buf, todo, &written, NULL)
7187 || written != todo)
7188 break;
7189 }
7190 CloseHandle(hTo);
7191 }
7192
7193 free(to_name);
7194}
7195
7196/*
7197 * Copy info streams from file "from" to file "to".
7198 */
7199 static void
7200copy_infostreams(char_u *from, char_u *to)
7201{
7202 WCHAR *fromw;
7203 WCHAR *tow;
7204 HANDLE sh;
7205 WIN32_STREAM_ID sid;
7206 int headersize;
7207 WCHAR streamname[_MAX_PATH];
7208 DWORD readcount;
7209 void *context = NULL;
7210 DWORD lo, hi;
7211 int len;
7212
7213 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007214 fromw = enc_to_utf16(from, NULL);
7215 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007216 if (fromw != NULL && tow != NULL)
7217 {
7218 /* Open the file for reading. */
7219 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7220 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7221 if (sh != INVALID_HANDLE_VALUE)
7222 {
7223 /* Use BackupRead() to find the info streams. Repeat until we
7224 * have done them all.*/
7225 for (;;)
7226 {
7227 /* Get the header to find the length of the stream name. If
7228 * the "readcount" is zero we have done all info streams. */
7229 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007230 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007231 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7232 &readcount, FALSE, FALSE, &context)
7233 || readcount == 0)
7234 break;
7235
7236 /* We only deal with streams that have a name. The normal
7237 * file data appears to be without a name, even though docs
7238 * suggest it is called "::$DATA". */
7239 if (sid.dwStreamNameSize > 0)
7240 {
7241 /* Read the stream name. */
7242 if (!BackupRead(sh, (LPBYTE)streamname,
7243 sid.dwStreamNameSize,
7244 &readcount, FALSE, FALSE, &context))
7245 break;
7246
7247 /* Copy an info stream with a name ":anything:$DATA".
7248 * Skip "::$DATA", it has no stream name (examples suggest
7249 * it might be used for the normal file contents).
7250 * Note that BackupRead() counts bytes, but the name is in
7251 * wide characters. */
7252 len = readcount / sizeof(WCHAR);
7253 streamname[len] = 0;
7254 if (len > 7 && wcsicmp(streamname + len - 6,
7255 L":$DATA") == 0)
7256 {
7257 streamname[len - 6] = 0;
7258 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007259 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260 }
7261 }
7262
7263 /* Advance to the next stream. We might try seeking too far,
7264 * but BackupSeek() doesn't skip over stream borders, thus
7265 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007266 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007267 &lo, &hi, &context);
7268 }
7269
7270 /* Clear the context. */
7271 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7272
7273 CloseHandle(sh);
7274 }
7275 }
7276 vim_free(fromw);
7277 vim_free(tow);
7278}
7279#endif
7280
7281/*
7282 * Copy file attributes from file "from" to file "to".
7283 * For Windows NT and later we copy info streams.
7284 * Always returns zero, errors are ignored.
7285 */
7286 int
7287mch_copy_file_attribute(char_u *from, char_u *to)
7288{
7289#ifdef FEAT_MBYTE
7290 /* File streams only work on Windows NT and later. */
7291 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007292 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007293#endif
7294 return 0;
7295}
7296
7297#if defined(MYRESETSTKOFLW) || defined(PROTO)
7298/*
7299 * Recreate a destroyed stack guard page in win32.
7300 * Written by Benjamin Peterson.
7301 */
7302
7303/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007304#define MIN_STACK_WINNT 2
7305
7306/*
7307 * This function does the same thing as _resetstkoflw(), which is only
7308 * available in DevStudio .net and later.
7309 * Returns 0 for failure, 1 for success.
7310 */
7311 int
7312myresetstkoflw(void)
7313{
7314 BYTE *pStackPtr;
7315 BYTE *pGuardPage;
7316 BYTE *pStackBase;
7317 BYTE *pLowestPossiblePage;
7318 MEMORY_BASIC_INFORMATION mbi;
7319 SYSTEM_INFO si;
7320 DWORD nPageSize;
7321 DWORD dummy;
7322
Bram Moolenaar071d4272004-06-13 20:20:40 +00007323 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007324
7325 /* We need to know the system page size. */
7326 GetSystemInfo(&si);
7327 nPageSize = si.dwPageSize;
7328
7329 /* ...and the current stack pointer */
7330 pStackPtr = (BYTE*)_alloca(1);
7331
7332 /* ...and the base of the stack. */
7333 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7334 return 0;
7335 pStackBase = (BYTE*)mbi.AllocationBase;
7336
7337 /* ...and the page thats min_stack_req pages away from stack base; this is
7338 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007339 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340
Bram Moolenaar071d4272004-06-13 20:20:40 +00007341 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007342 /* We want the first committed page in the stack Start at the stack
7343 * base and move forward through memory until we find a committed block.
7344 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007345 BYTE *pBlock = pStackBase;
7346
Bram Moolenaara466c992005-07-09 21:03:22 +00007347 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007348 {
7349 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7350 return 0;
7351
7352 pBlock += mbi.RegionSize;
7353
7354 if (mbi.State & MEM_COMMIT)
7355 break;
7356 }
7357
7358 /* mbi now describes the first committed block in the stack. */
7359 if (mbi.Protect & PAGE_GUARD)
7360 return 1;
7361
7362 /* decide where the guard page should start */
7363 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7364 pGuardPage = pLowestPossiblePage;
7365 else
7366 pGuardPage = (BYTE*)mbi.BaseAddress;
7367
7368 /* allocate the guard page */
7369 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7370 return 0;
7371
7372 /* apply the guard attribute to the page */
7373 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7374 &dummy))
7375 return 0;
7376 }
7377
7378 return 1;
7379}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007380#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007381
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007382
7383#if defined(FEAT_MBYTE) || defined(PROTO)
7384/*
7385 * The command line arguments in UCS2
7386 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007387static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007388static LPWSTR *ArglistW = NULL;
7389static int global_argc = 0;
7390static char **global_argv;
7391
7392static int used_file_argc = 0; /* last argument in global_argv[] used
7393 for the argument list. */
7394static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7395 command line arguments added to
7396 the argument list */
7397static int used_file_count = 0; /* nr of entries in used_file_indexes */
7398static int used_file_literal = FALSE; /* take file names literally */
7399static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007400static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007401static int used_alist_count = 0;
7402
7403
7404/*
7405 * Get the command line arguments. Unicode version.
7406 * Returns argc. Zero when something fails.
7407 */
7408 int
7409get_cmd_argsW(char ***argvp)
7410{
7411 char **argv = NULL;
7412 int argc = 0;
7413 int i;
7414
Bram Moolenaar14993322014-09-09 12:25:33 +02007415 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007416 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7417 if (ArglistW != NULL)
7418 {
7419 argv = malloc((nArgsW + 1) * sizeof(char *));
7420 if (argv != NULL)
7421 {
7422 argc = nArgsW;
7423 argv[argc] = NULL;
7424 for (i = 0; i < argc; ++i)
7425 {
7426 int len;
7427
7428 /* Convert each Unicode argument to the current codepage. */
7429 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007430 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007431 (LPSTR *)&argv[i], &len, 0, 0);
7432 if (argv[i] == NULL)
7433 {
7434 /* Out of memory, clear everything. */
7435 while (i > 0)
7436 free(argv[--i]);
7437 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007438 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007439 argc = 0;
7440 }
7441 }
7442 }
7443 }
7444
7445 global_argc = argc;
7446 global_argv = argv;
7447 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007448 {
7449 if (used_file_indexes != NULL)
7450 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007451 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007452 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007453
7454 if (argvp != NULL)
7455 *argvp = argv;
7456 return argc;
7457}
7458
7459 void
7460free_cmd_argsW(void)
7461{
7462 if (ArglistW != NULL)
7463 {
7464 GlobalFree(ArglistW);
7465 ArglistW = NULL;
7466 }
7467}
7468
7469/*
7470 * Remember "name" is an argument that was added to the argument list.
7471 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7472 * is called.
7473 */
7474 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007475used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007476{
7477 int i;
7478
7479 if (used_file_indexes == NULL)
7480 return;
7481 for (i = used_file_argc + 1; i < global_argc; ++i)
7482 if (STRCMP(global_argv[i], name) == 0)
7483 {
7484 used_file_argc = i;
7485 used_file_indexes[used_file_count++] = i;
7486 break;
7487 }
7488 used_file_literal = literal;
7489 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007490 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007491}
7492
7493/*
7494 * Remember the length of the argument list as it was. If it changes then we
7495 * leave it alone when 'encoding' is set.
7496 */
7497 void
7498set_alist_count(void)
7499{
7500 used_alist_count = GARGCOUNT;
7501}
7502
7503/*
7504 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7505 * has been changed while starting up. Use the UCS-2 command line arguments
7506 * and convert them to 'encoding'.
7507 */
7508 void
7509fix_arg_enc(void)
7510{
7511 int i;
7512 int idx;
7513 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007514 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007515
7516 /* Safety checks:
7517 * - if argument count differs between the wide and non-wide argument
7518 * list, something must be wrong.
7519 * - the file name arguments must have been located.
7520 * - the length of the argument list wasn't changed by the user.
7521 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007522 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007523 || ArglistW == NULL
7524 || used_file_indexes == NULL
7525 || used_file_count == 0
7526 || used_alist_count != GARGCOUNT)
7527 return;
7528
Bram Moolenaar86b68352004-12-27 21:59:20 +00007529 /* Remember the buffer numbers for the arguments. */
7530 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7531 if (fnum_list == NULL)
7532 return; /* out of memory */
7533 for (i = 0; i < GARGCOUNT; ++i)
7534 fnum_list[i] = GARGLIST[i].ae_fnum;
7535
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007536 /* Clear the argument list. Make room for the new arguments. */
7537 alist_clear(&global_alist);
7538 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007539 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007540
7541 for (i = 0; i < used_file_count; ++i)
7542 {
7543 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007544 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007545 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007546 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007547 int literal = used_file_literal;
7548
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007549#ifdef FEAT_DIFF
7550 /* When using diff mode may need to concatenate file name to
7551 * directory name. Just like it's done in main(). */
7552 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7553 && !mch_isdir(alist_name(&GARGLIST[0])))
7554 {
7555 char_u *r;
7556
7557 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7558 if (r != NULL)
7559 {
7560 vim_free(str);
7561 str = r;
7562 }
7563 }
7564#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007565 /* Re-use the old buffer by renaming it. When not using literal
7566 * names it's done by alist_expand() below. */
7567 if (used_file_literal)
7568 buf_set_name(fnum_list[i], str);
7569
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007570 /* Check backtick literal. backtick literal is already expanded in
7571 * main.c, so this part add str as literal. */
7572 if (literal == FALSE)
7573 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007574 size_t len = STRLEN(str);
7575
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007576 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7577 literal = TRUE;
7578 }
7579 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007580 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007581 }
7582
7583 if (!used_file_literal)
7584 {
7585 /* Now expand wildcards in the arguments. */
7586 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7587 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007588 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7589 * Also, unset wildignore to not be influenced by this option.
7590 * The arguments specified in command-line should be kept even if
7591 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007592 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007593 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007594 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007595 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007596 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007597 }
7598
7599 /* If wildcard expansion failed, we are editing the first file of the
7600 * arglist and there is no file name: Edit the first argument now. */
7601 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7602 {
7603 do_cmdline_cmd((char_u *)":rewind");
7604 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007605 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007606 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007607
7608 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007609}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007610#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007611
7612 int
7613mch_setenv(char *var, char *value, int x)
7614{
7615 char_u *envbuf;
7616
7617 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7618 if (envbuf == NULL)
7619 return -1;
7620
7621 sprintf((char *)envbuf, "%s=%s", var, value);
7622
7623#ifdef FEAT_MBYTE
7624 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7625 {
7626 WCHAR *p = enc_to_utf16(envbuf, NULL);
7627
7628 vim_free(envbuf);
7629 if (p == NULL)
7630 return -1;
7631 _wputenv(p);
7632# ifdef libintl_wputenv
7633 libintl_wputenv(p);
7634# endif
7635 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7636 vim_free(p);
7637 }
7638 else
7639#endif
7640 {
7641 _putenv((char *)envbuf);
7642# ifdef libintl_putenv
7643 libintl_putenv((char *)envbuf);
7644# endif
7645 /* Unlike Un*x systems, we can free the string for _putenv(). */
7646 vim_free(envbuf);
7647 }
7648
7649 return 0;
7650}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007651
7652#ifndef FEAT_GUI_W32
7653
7654/*
7655 * Support for 256 colors and 24-bit colors was added in Windows 10
7656 * version 1703 (Creators update).
7657 */
7658# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7659
7660 static void
7661vtp_init(void)
7662{
7663 DWORD ver, mode;
7664 HMODULE hKerneldll;
7665 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007666# ifdef FEAT_TERMGUICOLORS
7667 COLORREF fg, bg;
7668# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007669
7670 ver = get_build_number();
7671 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7672 GetConsoleMode(g_hConOut, &mode);
7673 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7674 if (SetConsoleMode(g_hConOut, mode) == 0)
7675 vtp_working = 0;
7676
7677 /* Use functions supported from Vista */
7678 hKerneldll = GetModuleHandle("kernel32.dll");
7679 if (hKerneldll != NULL)
7680 {
7681 pGetConsoleScreenBufferInfoEx =
7682 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7683 hKerneldll, "GetConsoleScreenBufferInfoEx");
7684 pSetConsoleScreenBufferInfoEx =
7685 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7686 hKerneldll, "SetConsoleScreenBufferInfoEx");
7687 if (pGetConsoleScreenBufferInfoEx != NULL
7688 && pSetConsoleScreenBufferInfoEx != NULL)
7689 has_csbiex = TRUE;
7690 }
7691
7692 csbi.cbSize = sizeof(csbi);
7693 if (has_csbiex)
7694 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007695 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7696 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7697
7698# ifdef FEAT_TERMGUICOLORS
7699 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7700 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7701 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7702 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7703 default_console_color_bg = bg;
7704 default_console_color_fg = fg;
7705#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007706
7707 set_console_color_rgb();
7708}
7709
7710 static void
7711vtp_exit(void)
7712{
7713 reset_console_color_rgb();
7714}
7715
7716 static int
7717vtp_printf(
7718 char *format,
7719 ...)
7720{
7721 char_u buf[100];
7722 va_list list;
7723 DWORD result;
7724
7725 va_start(list, format);
7726 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7727 va_end(list);
7728 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7729 return (int)result;
7730}
7731
7732 static void
7733vtp_sgr_bulk(
7734 int arg)
7735{
7736 int args[1];
7737
7738 args[0] = arg;
7739 vtp_sgr_bulks(1, args);
7740}
7741
7742 static void
7743vtp_sgr_bulks(
7744 int argc,
7745 int *args
7746)
7747{
7748 /* 2('\033[') + 4('255.') * 16 + NUL */
7749 char_u buf[2 + (4 * 16) + 1];
7750 char_u *p;
7751 int i;
7752
7753 p = buf;
7754 *p++ = '\033';
7755 *p++ = '[';
7756
7757 for (i = 0; i < argc; ++i)
7758 {
7759 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7760 *p++ = ';';
7761 }
7762 p--;
7763 *p++ = 'm';
7764 *p = NUL;
7765 vtp_printf((char *)buf);
7766}
7767
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007768# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007769 static int
7770ctermtoxterm(
7771 int cterm)
7772{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007773 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007774
7775 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7776 return (((int)r << 16) | ((int)g << 8) | (int)b);
7777}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007778# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007779
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007780 static void
7781set_console_color_rgb(void)
7782{
7783# ifdef FEAT_TERMGUICOLORS
7784 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7785 int id;
7786 guicolor_T fg = INVALCOLOR;
7787 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007788 int ctermfg;
7789 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007790
7791 if (!USE_VTP)
7792 return;
7793
7794 id = syn_name2id((char_u *)"Normal");
7795 if (id > 0)
7796 syn_id2colors(id, &fg, &bg);
7797 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007798 {
7799 ctermfg = -1;
7800 if (id > 0)
7801 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007802 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7803 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007804 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007805 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007806 {
7807 ctermbg = -1;
7808 if (id > 0)
7809 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007810 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7811 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007812 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007813 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7814 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7815
7816 csbi.cbSize = sizeof(csbi);
7817 if (has_csbiex)
7818 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7819
7820 csbi.cbSize = sizeof(csbi);
7821 csbi.srWindow.Right += 1;
7822 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007823 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7824 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007825 if (has_csbiex)
7826 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7827# endif
7828}
7829
7830 static void
7831reset_console_color_rgb(void)
7832{
7833# ifdef FEAT_TERMGUICOLORS
7834 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7835
7836 csbi.cbSize = sizeof(csbi);
7837 if (has_csbiex)
7838 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7839
7840 csbi.cbSize = sizeof(csbi);
7841 csbi.srWindow.Right += 1;
7842 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007843 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7844 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007845 if (has_csbiex)
7846 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7847# endif
7848}
7849
7850 void
7851control_console_color_rgb(void)
7852{
7853 if (USE_VTP)
7854 set_console_color_rgb();
7855 else
7856 reset_console_color_rgb();
7857}
7858
7859 int
7860has_vtp_working(void)
7861{
7862 return vtp_working;
7863}
7864
7865 int
7866use_vtp(void)
7867{
7868 return USE_VTP;
7869}
7870
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007871 int
7872is_term_win32(void)
7873{
7874 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7875}
7876
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007877#endif