blob: a53b7b6270aea337d8e6dfac4889b1120832d7ef [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{
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850/* Key ANSI alone shift ctrl alt */
851 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
852
853 { VK_F1, TRUE, ';', 'T', '^', 'h', },
854 { VK_F2, TRUE, '<', 'U', '_', 'i', },
855 { VK_F3, TRUE, '=', 'V', '`', 'j', },
856 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
857 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
858 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
859 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
860 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
861 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
862 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200863 { VK_F11, TRUE, 0x85, 0x87, 0x89, 0x8B, },
864 { VK_F12, TRUE, 0x86, 0x88, 0x8a, 0x8c, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000865
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200866 { VK_HOME, TRUE, 'G', 0xc2, 'w', 0xc3, },
867 { VK_UP, TRUE, 'H', 0xc4, 0xc5, 0xc6, },
868 { VK_PRIOR, TRUE, 'I', 0xc7, 0x84, 0xc8, }, /*PgUp*/
869 { VK_LEFT, TRUE, 'K', 0xc9, 's', 0xca, },
870 { VK_RIGHT, TRUE, 'M', 0xcb, 't', 0xcc, },
871 { VK_END, TRUE, 'O', 0xcd, 'u', 0xce, },
872 { VK_DOWN, TRUE, 'P', 0xcf, 0xd0, 0xd1, },
873 { VK_NEXT, TRUE, 'Q', 0xd2, 'v', 0xd3, }, /*PgDn*/
874 { VK_INSERT,TRUE, 'R', 0xd4, 0xd5, 0xd6, },
875 { VK_DELETE,TRUE, 'S', 0xd7, 0xd8, 0xd9, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876
877 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
878
879#if 0
880 /* Most people don't have F13-F20, but what the hell... */
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200881 { VK_F13, TRUE, 0xda, 0xdb, 0xdc, 0xdd, },
882 { VK_F14, TRUE, 0xde, 0xdf, 0xe0, 0xe1, },
883 { VK_F15, TRUE, 0xe2, 0xe3, 0xe4, 0xe5, },
884 { VK_F16, TRUE, 0xe6, 0xe7, 0xe8, 0xe9, },
885 { VK_F17, TRUE, 0xea, 0xeb, 0xec, 0xed, },
886 { VK_F18, TRUE, 0xee, 0xef, 0xf0, 0xf1, },
887 { VK_F19, TRUE, 0xf2, 0xf3, 0xf4, 0xf5, },
888 { VK_F20, TRUE, 0xf6, 0xf7, 0xf8, 0xf9, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889#endif
890 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
891 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
892 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
893 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
894
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200895 { VK_NUMPAD0,TRUE, 0xda, 0xdb, 0xdc, 0xdd, },
896 { VK_NUMPAD1,TRUE, 0xde, 0xdf, 0xe0, 0xe1, },
897 { VK_NUMPAD2,TRUE, 0xe2, 0xe3, 0xe4, 0xe5, },
898 { VK_NUMPAD3,TRUE, 0xe6, 0xe7, 0xe8, 0xe9, },
899 { VK_NUMPAD4,TRUE, 0xea, 0xeb, 0xec, 0xed, },
900 { VK_NUMPAD5,TRUE, 0xee, 0xef, 0xf0, 0xf1, },
901 { VK_NUMPAD6,TRUE, 0xf2, 0xf3, 0xf4, 0xf5, },
902 { VK_NUMPAD7,TRUE, 0xf6, 0xf7, 0xf8, 0xf9, },
903 { VK_NUMPAD8,TRUE, 0xfa, 0xfb, 0xfc, 0xfd, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904 /* Sorry, out of number space! <negri>*/
Bram Moolenaar2bc152a2018-10-03 20:44:20 +0200905 { VK_NUMPAD9,TRUE, 0xfe, 0xff, 0xff, 0xf7, },
Bram Moolenaar071d4272004-06-13 20:20:40 +0000906};
907
908
909#ifdef _MSC_VER
910// The ToAscii bug destroys several registers. Need to turn off optimization
911// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000912# pragma warning(push)
913# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914# pragma optimize("", off)
915#endif
916
917#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200918# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200920# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000921#endif
922
923/* The return code indicates key code size. */
924 static int
925#ifdef __BORLANDC__
926 __stdcall
927#endif
928win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000929 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930{
931 UINT uMods = pker->dwControlKeyState;
932 static int s_iIsDead = 0;
933 static WORD awAnsiCode[2];
934 static BYTE abKeystate[256];
935
936
937 if (s_iIsDead == 2)
938 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200939 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940 s_iIsDead = 0;
941 return 1;
942 }
943
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200944 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945 return 1;
946
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200947 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200950 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951
952 if (uMods & SHIFT_PRESSED)
953 abKeystate[VK_SHIFT] = 0x80;
954 if (uMods & CAPSLOCK_ON)
955 abKeystate[VK_CAPITAL] = 1;
956
957 if ((uMods & ALT_GR) == ALT_GR)
958 {
959 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
960 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
961 }
962
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200963 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
964 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965
966 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200967 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968
969 return s_iIsDead;
970}
971
972#ifdef _MSC_VER
973/* MUST switch optimization on again here, otherwise a call to
974 * decode_key_event() may crash (e.g. when hitting caps-lock) */
975# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000976# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000977
978# if (_MSC_VER < 1100)
979/* MUST turn off global optimisation for this next function, or
980 * pressing ctrl-minus in insert mode crashes Vim when built with
981 * VC4.1. -- negri. */
982# pragma optimize("g", off)
983# endif
984#endif
985
986static BOOL g_fJustGotFocus = FALSE;
987
988/*
989 * Decode a KEY_EVENT into one or two keystrokes
990 */
991 static BOOL
992decode_key_event(
993 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200994 WCHAR *pch,
995 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996 int *pmodifiers,
997 BOOL fDoPost)
998{
999 int i;
1000 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1001
1002 *pch = *pch2 = NUL;
1003 g_fJustGotFocus = FALSE;
1004
1005 /* ignore key up events */
1006 if (!pker->bKeyDown)
1007 return FALSE;
1008
1009 /* ignore some keystrokes */
1010 switch (pker->wVirtualKeyCode)
1011 {
1012 /* modifiers */
1013 case VK_SHIFT:
1014 case VK_CONTROL:
1015 case VK_MENU: /* Alt key */
1016 return FALSE;
1017
1018 default:
1019 break;
1020 }
1021
1022 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001023 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001024 {
1025 /* Ctrl-6 is Ctrl-^ */
1026 if (pker->wVirtualKeyCode == '6')
1027 {
1028 *pch = Ctrl_HAT;
1029 return TRUE;
1030 }
1031 /* Ctrl-2 is Ctrl-@ */
1032 else if (pker->wVirtualKeyCode == '2')
1033 {
1034 *pch = NUL;
1035 return TRUE;
1036 }
1037 /* Ctrl-- is Ctrl-_ */
1038 else if (pker->wVirtualKeyCode == 0xBD)
1039 {
1040 *pch = Ctrl__;
1041 return TRUE;
1042 }
1043 }
1044
1045 /* Shift-TAB */
1046 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1047 {
1048 *pch = K_NUL;
1049 *pch2 = '\017';
1050 return TRUE;
1051 }
1052
1053 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1054 {
1055 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1056 {
1057 if (nModifs == 0)
1058 *pch = VirtKeyMap[i].chAlone;
1059 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1060 *pch = VirtKeyMap[i].chShift;
1061 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1062 *pch = VirtKeyMap[i].chCtrl;
1063 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1064 *pch = VirtKeyMap[i].chAlt;
1065
1066 if (*pch != 0)
1067 {
1068 if (VirtKeyMap[i].fAnsiKey)
1069 {
1070 *pch2 = *pch;
1071 *pch = K_NUL;
1072 }
1073
1074 return TRUE;
1075 }
1076 }
1077 }
1078
1079 i = win32_kbd_patch_key(pker);
1080
1081 if (i < 0)
1082 *pch = NUL;
1083 else
1084 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001085 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086
1087 if (pmodifiers != NULL)
1088 {
1089 /* Pass on the ALT key as a modifier, but only when not combined
1090 * with CTRL (which is ALTGR). */
1091 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1092 *pmodifiers |= MOD_MASK_ALT;
1093
1094 /* Pass on SHIFT only for special keys, because we don't know when
1095 * it's already included with the character. */
1096 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1097 *pmodifiers |= MOD_MASK_SHIFT;
1098
1099 /* Pass on CTRL only for non-special keys, because we don't know
1100 * when it's already included with the character. And not when
1101 * combined with ALT (which is ALTGR). */
1102 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1103 && *pch >= 0x20 && *pch < 0x80)
1104 *pmodifiers |= MOD_MASK_CTRL;
1105 }
1106 }
1107
1108 return (*pch != NUL);
1109}
1110
1111#ifdef _MSC_VER
1112# pragma optimize("", on)
1113#endif
1114
1115#endif /* FEAT_GUI_W32 */
1116
1117
1118#ifdef FEAT_MOUSE
1119
1120/*
1121 * For the GUI the mouse handling is in gui_w32.c.
1122 */
1123# ifdef FEAT_GUI_W32
1124 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001125mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126{
1127}
1128# else
1129static int g_fMouseAvail = FALSE; /* mouse present */
1130static int g_fMouseActive = FALSE; /* mouse enabled */
1131static int g_nMouseClick = -1; /* mouse status */
1132static int g_xMouse; /* mouse x coordinate */
1133static int g_yMouse; /* mouse y coordinate */
1134
1135/*
1136 * Enable or disable mouse input
1137 */
1138 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001139mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001140{
1141 DWORD cmodein;
1142
1143 if (!g_fMouseAvail)
1144 return;
1145
1146 g_fMouseActive = on;
1147 GetConsoleMode(g_hConIn, &cmodein);
1148
1149 if (g_fMouseActive)
1150 cmodein |= ENABLE_MOUSE_INPUT;
1151 else
1152 cmodein &= ~ENABLE_MOUSE_INPUT;
1153
1154 SetConsoleMode(g_hConIn, cmodein);
1155}
1156
Bram Moolenaar157d8132018-03-06 17:09:20 +01001157
1158#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1159/*
1160 * Called when 'balloonevalterm' changed.
1161 */
1162 void
1163mch_bevalterm_changed(void)
1164{
1165 mch_setmouse(g_fMouseActive);
1166}
1167#endif
1168
Bram Moolenaar071d4272004-06-13 20:20:40 +00001169/*
1170 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1171 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1172 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1173 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1174 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1175 * and we return the mouse position in g_xMouse and g_yMouse.
1176 *
1177 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1178 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1179 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1180 *
1181 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1182 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1183 *
1184 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1185 * moves, even if it stays within the same character cell. We ignore
1186 * all MOUSE_MOVED messages if the position hasn't really changed, and
1187 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1188 * we're only interested in MOUSE_DRAG).
1189 *
1190 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1191 * 2-button mouses by pressing the left & right buttons simultaneously.
1192 * In practice, it's almost impossible to click both at the same time,
1193 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1194 * in such cases, if the user is clicking quickly.
1195 */
1196 static BOOL
1197decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001198 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001199{
1200 static int s_nOldButton = -1;
1201 static int s_nOldMouseClick = -1;
1202 static int s_xOldMouse = -1;
1203 static int s_yOldMouse = -1;
1204 static linenr_T s_old_topline = 0;
1205#ifdef FEAT_DIFF
1206 static int s_old_topfill = 0;
1207#endif
1208 static int s_cClicks = 1;
1209 static BOOL s_fReleased = TRUE;
1210 static DWORD s_dwLastClickTime = 0;
1211 static BOOL s_fNextIsMiddle = FALSE;
1212
1213 static DWORD cButtons = 0; /* number of buttons supported */
1214
1215 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1216 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1217 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1218 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1219
1220 int nButton;
1221
1222 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1223 cButtons = 2;
1224
1225 if (!g_fMouseAvail || !g_fMouseActive)
1226 {
1227 g_nMouseClick = -1;
1228 return FALSE;
1229 }
1230
1231 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1232 if (g_fJustGotFocus)
1233 {
1234 g_fJustGotFocus = FALSE;
1235 return FALSE;
1236 }
1237
1238 /* unprocessed mouse click? */
1239 if (g_nMouseClick != -1)
1240 return TRUE;
1241
1242 nButton = -1;
1243 g_xMouse = pmer->dwMousePosition.X;
1244 g_yMouse = pmer->dwMousePosition.Y;
1245
1246 if (pmer->dwEventFlags == MOUSE_MOVED)
1247 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001248 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001249 * events even when the mouse moves only within a char cell.) */
1250 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1251 return FALSE;
1252 }
1253
1254 /* If no buttons are pressed... */
1255 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1256 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001257 nButton = MOUSE_RELEASE;
1258
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1260 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001261 {
1262#ifdef FEAT_BEVAL_TERM
1263 /* do return mouse move events when we want them */
1264 if (p_bevalterm)
1265 nButton = MOUSE_DRAG;
1266 else
1267#endif
1268 return FALSE;
1269 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001270
Bram Moolenaar071d4272004-06-13 20:20:40 +00001271 s_fReleased = TRUE;
1272 }
1273 else /* one or more buttons pressed */
1274 {
1275 /* on a 2-button mouse, hold down left and right buttons
1276 * simultaneously to get MIDDLE. */
1277
1278 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1279 {
1280 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1281
1282 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001283 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001284 if (dwLR == LEFT || dwLR == RIGHT)
1285 {
1286 for (;;)
1287 {
1288 /* wait a short time for next input event */
1289 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1290 != WAIT_OBJECT_0)
1291 break;
1292 else
1293 {
1294 DWORD cRecords = 0;
1295 INPUT_RECORD ir;
1296 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1297
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001298 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299
1300 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1301 || !(pmer2->dwButtonState & LEFT_RIGHT))
1302 break;
1303 else
1304 {
1305 if (pmer2->dwEventFlags != MOUSE_MOVED)
1306 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001307 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308
1309 return decode_mouse_event(pmer2);
1310 }
1311 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1312 s_yOldMouse == pmer2->dwMousePosition.Y)
1313 {
1314 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001315 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316
1317 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001318 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001319
1320 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1321 break;
1322 }
1323 else
1324 break;
1325 }
1326 }
1327 }
1328 }
1329 }
1330
1331 if (s_fNextIsMiddle)
1332 {
1333 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1334 ? MOUSE_DRAG : MOUSE_MIDDLE;
1335 s_fNextIsMiddle = FALSE;
1336 }
1337 else if (cButtons == 2 &&
1338 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1339 {
1340 nButton = MOUSE_MIDDLE;
1341
1342 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1343 {
1344 s_fNextIsMiddle = TRUE;
1345 nButton = MOUSE_RELEASE;
1346 }
1347 }
1348 else if ((pmer->dwButtonState & LEFT) == LEFT)
1349 nButton = MOUSE_LEFT;
1350 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1351 nButton = MOUSE_MIDDLE;
1352 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1353 nButton = MOUSE_RIGHT;
1354
1355 if (! s_fReleased && ! s_fNextIsMiddle
1356 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1357 return FALSE;
1358
1359 s_fReleased = s_fNextIsMiddle;
1360 }
1361
1362 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1363 {
1364 /* button pressed or released, without mouse moving */
1365 if (nButton != -1 && nButton != MOUSE_RELEASE)
1366 {
1367 DWORD dwCurrentTime = GetTickCount();
1368
1369 if (s_xOldMouse != g_xMouse
1370 || s_yOldMouse != g_yMouse
1371 || s_nOldButton != nButton
1372 || s_old_topline != curwin->w_topline
1373#ifdef FEAT_DIFF
1374 || s_old_topfill != curwin->w_topfill
1375#endif
1376 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1377 {
1378 s_cClicks = 1;
1379 }
1380 else if (++s_cClicks > 4)
1381 {
1382 s_cClicks = 1;
1383 }
1384
1385 s_dwLastClickTime = dwCurrentTime;
1386 }
1387 }
1388 else if (pmer->dwEventFlags == MOUSE_MOVED)
1389 {
1390 if (nButton != -1 && nButton != MOUSE_RELEASE)
1391 nButton = MOUSE_DRAG;
1392
1393 s_cClicks = 1;
1394 }
1395
1396 if (nButton == -1)
1397 return FALSE;
1398
1399 if (nButton != MOUSE_RELEASE)
1400 s_nOldButton = nButton;
1401
1402 g_nMouseClick = nButton;
1403
1404 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1405 g_nMouseClick |= MOUSE_SHIFT;
1406 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1407 g_nMouseClick |= MOUSE_CTRL;
1408 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1409 g_nMouseClick |= MOUSE_ALT;
1410
1411 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1412 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1413
1414 /* only pass on interesting (i.e., different) mouse events */
1415 if (s_xOldMouse == g_xMouse
1416 && s_yOldMouse == g_yMouse
1417 && s_nOldMouseClick == g_nMouseClick)
1418 {
1419 g_nMouseClick = -1;
1420 return FALSE;
1421 }
1422
1423 s_xOldMouse = g_xMouse;
1424 s_yOldMouse = g_yMouse;
1425 s_old_topline = curwin->w_topline;
1426#ifdef FEAT_DIFF
1427 s_old_topfill = curwin->w_topfill;
1428#endif
1429 s_nOldMouseClick = g_nMouseClick;
1430
1431 return TRUE;
1432}
1433
1434# endif /* FEAT_GUI_W32 */
1435#endif /* FEAT_MOUSE */
1436
1437
1438#ifdef MCH_CURSOR_SHAPE
1439/*
1440 * Set the shape of the cursor.
1441 * 'thickness' can be from 1 (thin) to 99 (block)
1442 */
1443 static void
1444mch_set_cursor_shape(int thickness)
1445{
1446 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1447 ConsoleCursorInfo.dwSize = thickness;
1448 ConsoleCursorInfo.bVisible = s_cursor_visible;
1449
1450 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1451 if (s_cursor_visible)
1452 SetConsoleCursorPosition(g_hConOut, g_coord);
1453}
1454
1455 void
1456mch_update_cursor(void)
1457{
1458 int idx;
1459 int thickness;
1460
1461 /*
1462 * How the cursor is drawn depends on the current mode.
1463 */
1464 idx = get_shape_idx(FALSE);
1465
1466 if (shape_table[idx].shape == SHAPE_BLOCK)
1467 thickness = 99; /* 100 doesn't work on W95 */
1468 else
1469 thickness = shape_table[idx].percentage;
1470 mch_set_cursor_shape(thickness);
1471}
1472#endif
1473
1474#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1475/*
1476 * Handle FOCUS_EVENT.
1477 */
1478 static void
1479handle_focus_event(INPUT_RECORD ir)
1480{
1481 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1482 ui_focus_change((int)g_fJustGotFocus);
1483}
1484
1485/*
1486 * Wait until console input from keyboard or mouse is available,
1487 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001488 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489 * Return TRUE if something is available FALSE if not.
1490 */
1491 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001492WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493{
1494 DWORD dwNow = 0, dwEndTime = 0;
1495 INPUT_RECORD ir;
1496 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001497 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001498#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001499 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001500#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501
1502 if (msec > 0)
1503 /* Wait until the specified time has elapsed. */
1504 dwEndTime = GetTickCount() + msec;
1505 else if (msec < 0)
1506 /* Wait forever. */
1507 dwEndTime = INFINITE;
1508
1509 /* We need to loop until the end of the time period, because
1510 * we might get multiple unusable mouse events in that time.
1511 */
1512 for (;;)
1513 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001514 // Only process messages when waiting.
1515 if (msec != 0)
1516 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001517#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001518 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001519#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001520#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001521 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001522#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001524 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001526 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001527
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528 if (0
1529#ifdef FEAT_MOUSE
1530 || g_nMouseClick != -1
1531#endif
1532#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001533 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534#endif
1535 )
1536 return TRUE;
1537
1538 if (msec > 0)
1539 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001540 /* If the specified wait time has passed, return. Beware that
1541 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001542 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001543 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 break;
1545 }
1546 if (msec != 0)
1547 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001548 DWORD dwWaitTime = dwEndTime - dwNow;
1549
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001550#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001551 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001552 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001553 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001554 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001555 /* If there is readahead then parse_queued_messages() timed out
1556 * and we should call it again soon. */
1557 if (channel_any_readahead())
1558 dwWaitTime = 10;
1559 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001560#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001561#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001562 if (p_beval && dwWaitTime > 100)
1563 /* The 'balloonexpr' may indirectly invoke a callback while
1564 * waiting for a character, need to check often. */
1565 dwWaitTime = 100;
1566#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001567#ifdef FEAT_MZSCHEME
1568 if (mzthreads_allowed() && p_mzq > 0
1569 && (msec < 0 || (long)dwWaitTime > p_mzq))
1570 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1571#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001572#ifdef FEAT_TIMERS
1573 {
1574 long due_time;
1575
1576 /* When waiting very briefly don't trigger timers. */
1577 if (dwWaitTime > 10)
1578 {
1579 /* Trigger timers and then get the time in msec until the
1580 * next one is due. Wait up to that time. */
1581 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001582 if (typebuf.tb_change_cnt != tb_change_cnt)
1583 {
1584 /* timer may have used feedkeys() */
1585 return FALSE;
1586 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001587 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1588 dwWaitTime = due_time;
1589 }
1590 }
1591#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592#ifdef FEAT_CLIENTSERVER
1593 /* Wait for either an event on the console input or a message in
1594 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001595 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001596 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001598 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599#endif
1600 continue;
1601 }
1602
1603 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001604 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605
1606#ifdef FEAT_MBYTE_IME
1607 if (State & CMDLINE && msg_row == Rows - 1)
1608 {
1609 CONSOLE_SCREEN_BUFFER_INFO csbi;
1610
1611 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1612 {
1613 if (csbi.dwCursorPosition.Y != msg_row)
1614 {
1615 /* The screen is now messed up, must redraw the
1616 * command line and later all the windows. */
1617 redraw_all_later(CLEAR);
1618 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1619 redrawcmd();
1620 }
1621 }
1622 }
1623#endif
1624
1625 if (cRecords > 0)
1626 {
1627 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1628 {
1629#ifdef FEAT_MBYTE_IME
1630 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1631 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001632 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1634 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001635 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001636 continue;
1637 }
1638#endif
1639 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1640 NULL, FALSE))
1641 return TRUE;
1642 }
1643
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001644 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645
1646 if (ir.EventType == FOCUS_EVENT)
1647 handle_focus_event(ir);
1648 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001649 {
1650 /* Only call shell_resized() when the size actually change to
1651 * avoid the screen is cleard. */
1652 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1653 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1654 shell_resized();
1655 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001656#ifdef FEAT_MOUSE
1657 else if (ir.EventType == MOUSE_EVENT
1658 && decode_mouse_event(&ir.Event.MouseEvent))
1659 return TRUE;
1660#endif
1661 }
1662 else if (msec == 0)
1663 break;
1664 }
1665
1666#ifdef FEAT_CLIENTSERVER
1667 /* Something might have been received while we were waiting. */
1668 if (input_available())
1669 return TRUE;
1670#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001671
Bram Moolenaar071d4272004-06-13 20:20:40 +00001672 return FALSE;
1673}
1674
1675#ifndef FEAT_GUI_MSWIN
1676/*
1677 * return non-zero if a character is available
1678 */
1679 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001680mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001682 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001683}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001684
1685# if defined(FEAT_TERMINAL) || defined(PROTO)
1686/*
1687 * Check for any pending input or messages.
1688 */
1689 int
1690mch_check_messages(void)
1691{
1692 return WaitForChar(0L, TRUE);
1693}
1694# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695#endif
1696
1697/*
1698 * Create the console input. Used when reading stdin doesn't work.
1699 */
1700 static void
1701create_conin(void)
1702{
1703 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1704 FILE_SHARE_READ|FILE_SHARE_WRITE,
1705 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001706 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001707 did_create_conin = TRUE;
1708}
1709
1710/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001711 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001713 static WCHAR
1714tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001716 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717
1718 for (;;)
1719 {
1720 INPUT_RECORD ir;
1721 DWORD cRecords = 0;
1722
1723#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001724 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 if (input_available())
1726 return 0;
1727# ifdef FEAT_MOUSE
1728 if (g_nMouseClick != -1)
1729 return 0;
1730# endif
1731#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001732 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733 {
1734 if (did_create_conin)
1735 read_error_exit();
1736 create_conin();
1737 continue;
1738 }
1739
1740 if (ir.EventType == KEY_EVENT)
1741 {
1742 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1743 pmodifiers, TRUE))
1744 return ch;
1745 }
1746 else if (ir.EventType == FOCUS_EVENT)
1747 handle_focus_event(ir);
1748 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1749 shell_resized();
1750#ifdef FEAT_MOUSE
1751 else if (ir.EventType == MOUSE_EVENT)
1752 {
1753 if (decode_mouse_event(&ir.Event.MouseEvent))
1754 return 0;
1755 }
1756#endif
1757 }
1758}
1759#endif /* !FEAT_GUI_W32 */
1760
1761
1762/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001763 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764 * Get one or more characters from the keyboard or the mouse.
1765 * If time == 0, do not wait for characters.
1766 * If time == n, wait a short time for characters.
1767 * If time == -1, wait forever for characters.
1768 * Returns the number of characters read into buf.
1769 */
1770 int
1771mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001772 char_u *buf UNUSED,
1773 int maxlen UNUSED,
1774 long time UNUSED,
1775 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776{
1777#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1778
1779 int len;
1780 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781#define TYPEAHEADLEN 20
1782 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1783 static int typeaheadlen = 0;
1784
1785 /* First use any typeahead that was kept because "buf" was too small. */
1786 if (typeaheadlen > 0)
1787 goto theend;
1788
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789 if (time >= 0)
1790 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001791 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793 }
1794 else /* time == -1, wait forever */
1795 {
1796 mch_set_winsize_now(); /* Allow winsize changes from now on */
1797
Bram Moolenaar3918c952005-03-15 22:34:55 +00001798 /*
1799 * If there is no character available within 2 seconds (default)
1800 * write the autoscript file to disk. Or cause the CursorHold event
1801 * to be triggered.
1802 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001803 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001805 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001807 buf[0] = K_SPECIAL;
1808 buf[1] = KS_EXTRA;
1809 buf[2] = (int)KE_CURSORHOLD;
1810 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001812 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001813 }
1814 }
1815
1816 /*
1817 * Try to read as many characters as there are, until the buffer is full.
1818 */
1819
1820 /* we will get at least one key. Get more if they are available. */
1821 g_fCBrkPressed = FALSE;
1822
1823#ifdef MCH_WRITE_DUMP
1824 if (fdDump)
1825 fputc('[', fdDump);
1826#endif
1827
1828 /* Keep looping until there is something in the typeahead buffer and more
1829 * to get and still room in the buffer (up to two bytes for a char and
1830 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001831 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 && typeaheadlen + 5 <= TYPEAHEADLEN)
1833 {
1834 if (typebuf_changed(tb_change_cnt))
1835 {
1836 /* "buf" may be invalid now if a client put something in the
1837 * typeahead buffer and "buf" is in the typeahead buffer. */
1838 typeaheadlen = 0;
1839 break;
1840 }
1841#ifdef FEAT_MOUSE
1842 if (g_nMouseClick != -1)
1843 {
1844# ifdef MCH_WRITE_DUMP
1845 if (fdDump)
1846 fprintf(fdDump, "{%02x @ %d, %d}",
1847 g_nMouseClick, g_xMouse, g_yMouse);
1848# endif
1849 typeahead[typeaheadlen++] = ESC + 128;
1850 typeahead[typeaheadlen++] = 'M';
1851 typeahead[typeaheadlen++] = g_nMouseClick;
1852 typeahead[typeaheadlen++] = g_xMouse + '!';
1853 typeahead[typeaheadlen++] = g_yMouse + '!';
1854 g_nMouseClick = -1;
1855 }
1856 else
1857#endif
1858 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001859 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001860 int modifiers = 0;
1861
1862 c = tgetch(&modifiers, &ch2);
1863
1864 if (typebuf_changed(tb_change_cnt))
1865 {
1866 /* "buf" may be invalid now if a client put something in the
1867 * typeahead buffer and "buf" is in the typeahead buffer. */
1868 typeaheadlen = 0;
1869 break;
1870 }
1871
1872 if (c == Ctrl_C && ctrl_c_interrupts)
1873 {
1874#if defined(FEAT_CLIENTSERVER)
1875 trash_input_buf();
1876#endif
1877 got_int = TRUE;
1878 }
1879
1880#ifdef FEAT_MOUSE
1881 if (g_nMouseClick == -1)
1882#endif
1883 {
1884 int n = 1;
1885
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001886#ifdef FEAT_MBYTE
1887 if (ch2 == NUL)
1888 {
1889 int i;
1890 char_u *p;
1891 WCHAR ch[2];
1892
1893 ch[0] = c;
1894 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1895 {
1896 ch[1] = tgetch(&modifiers, &ch2);
1897 n++;
1898 }
1899 p = utf16_to_enc(ch, &n);
1900 if (p != NULL)
1901 {
1902 for (i = 0; i < n; i++)
1903 typeahead[typeaheadlen + i] = p[i];
1904 vim_free(p);
1905 }
1906 }
1907 else
1908#endif
1909 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 if (ch2 != NUL)
1911 {
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001912 if (c == K_NUL && (ch2 & 0xff00) != 0)
1913 {
1914 /* fAnsiKey with modifier keys */
1915 typeahead[typeaheadlen + n] = (char_u)ch2;
1916 n++;
1917 }
1918 else
1919 {
1920 typeahead[typeaheadlen + n] = 3;
1921 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1922 n += 2;
1923 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001924 }
1925
Bram Moolenaar071d4272004-06-13 20:20:40 +00001926 /* Use the ALT key to set the 8th bit of the character
1927 * when it's one byte, the 8th bit isn't set yet and not
1928 * using a double-byte encoding (would become a lead
1929 * byte). */
1930 if ((modifiers & MOD_MASK_ALT)
1931 && n == 1
1932 && (typeahead[typeaheadlen] & 0x80) == 0
1933#ifdef FEAT_MBYTE
1934 && !enc_dbcs
1935#endif
1936 )
1937 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001938#ifdef FEAT_MBYTE
1939 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1940 typeahead + typeaheadlen);
1941#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001943#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944 modifiers &= ~MOD_MASK_ALT;
1945 }
1946
1947 if (modifiers != 0)
1948 {
1949 /* Prepend modifiers to the character. */
1950 mch_memmove(typeahead + typeaheadlen + 3,
1951 typeahead + typeaheadlen, n);
1952 typeahead[typeaheadlen++] = K_SPECIAL;
1953 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1954 typeahead[typeaheadlen++] = modifiers;
1955 }
1956
1957 typeaheadlen += n;
1958
1959#ifdef MCH_WRITE_DUMP
1960 if (fdDump)
1961 fputc(c, fdDump);
1962#endif
1963 }
1964 }
1965 }
1966
1967#ifdef MCH_WRITE_DUMP
1968 if (fdDump)
1969 {
1970 fputs("]\n", fdDump);
1971 fflush(fdDump);
1972 }
1973#endif
1974
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975theend:
1976 /* Move typeahead to "buf", as much as fits. */
1977 len = 0;
1978 while (len < maxlen && typeaheadlen > 0)
1979 {
1980 buf[len++] = typeahead[0];
1981 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1982 }
1983 return len;
1984
1985#else /* FEAT_GUI_W32 */
1986 return 0;
1987#endif /* FEAT_GUI_W32 */
1988}
1989
Bram Moolenaar82881492012-11-20 16:53:39 +01001990#ifndef PROTO
1991# ifndef __MINGW32__
1992# include <shellapi.h> /* required for FindExecutable() */
1993# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994#endif
1995
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001996/*
Bram Moolenaar43663192017-03-05 14:29:12 +01001997 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
1998 * If "use_path" is FALSE: Return TRUE if "name" exists.
1999 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2000 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002001 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002002 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002004executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002006 char *dum;
2007 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002008 char *curpath, *newpath;
2009 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010
Bram Moolenaar43663192017-03-05 14:29:12 +01002011 if (!use_path)
2012 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002013 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002014 {
2015 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002016 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002017 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002018 *path = vim_strsave((char_u *)name);
2019 else
2020 *path = FullName_save((char_u *)name, FALSE);
2021 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002022 return TRUE;
2023 }
2024 return FALSE;
2025 }
2026
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002027#ifdef FEAT_MBYTE
2028 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002030 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002031 WCHAR fnamew[_MAX_PATH];
2032 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002033 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002034
2035 if (p != NULL)
2036 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002037 wcurpath = _wgetenv(L"PATH");
2038 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2039 * sizeof(WCHAR));
2040 if (wnewpath == NULL)
2041 return FALSE;
2042 wcscpy(wnewpath, L".;");
2043 wcscat(wnewpath, wcurpath);
2044 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2045 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002046 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002047 if (n == 0)
2048 return FALSE;
2049 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2050 return FALSE;
2051 if (path != NULL)
2052 *path = utf16_to_enc(fnamew, NULL);
2053 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002054 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002056#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002057
2058 curpath = getenv("PATH");
2059 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2060 if (newpath == NULL)
2061 return FALSE;
2062 STRCPY(newpath, ".;");
2063 STRCAT(newpath, curpath);
2064 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2065 vim_free(newpath);
2066 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002067 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002068 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002069 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002070 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002071 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002072 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073}
2074
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002075#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002076 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002077/*
2078 * Bad parameter handler.
2079 *
2080 * Certain MS CRT functions will intentionally crash when passed invalid
2081 * parameters to highlight possible security holes. Setting this function as
2082 * the bad parameter handler will prevent the crash.
2083 *
2084 * In debug builds the parameters contain CRT information that might help track
2085 * down the source of a problem, but in non-debug builds the arguments are all
2086 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2087 * worth allowing these to make debugging of issues easier.
2088 */
2089 static void
2090bad_param_handler(const wchar_t *expression,
2091 const wchar_t *function,
2092 const wchar_t *file,
2093 unsigned int line,
2094 uintptr_t pReserved)
2095{
2096}
2097
2098# define SET_INVALID_PARAM_HANDLER \
2099 ((void)_set_invalid_parameter_handler(bad_param_handler))
2100#else
2101# define SET_INVALID_PARAM_HANDLER
2102#endif
2103
Bram Moolenaar071d4272004-06-13 20:20:40 +00002104#ifdef FEAT_GUI_W32
2105
2106/*
2107 * GUI version of mch_init().
2108 */
2109 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002110mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002111{
2112#ifndef __MINGW32__
2113 extern int _fmode;
2114#endif
2115
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002116 /* Silently handle invalid parameters to CRT functions */
2117 SET_INVALID_PARAM_HANDLER;
2118
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119 /* Let critical errors result in a failure, not in a dialog box. Required
2120 * for the timestamp test to work on removed floppies. */
2121 SetErrorMode(SEM_FAILCRITICALERRORS);
2122
2123 _fmode = O_BINARY; /* we do our own CR-LF translation */
2124
2125 /* Specify window size. Is there a place to get the default from? */
2126 Rows = 25;
2127 Columns = 80;
2128
2129 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002130 {
2131 char_u vimrun_location[_MAX_PATH + 4];
2132
2133 /* First try in same directory as gvim.exe */
2134 STRCPY(vimrun_location, exe_name);
2135 STRCPY(gettail(vimrun_location), "vimrun.exe");
2136 if (mch_getperm(vimrun_location) >= 0)
2137 {
2138 if (*skiptowhite(vimrun_location) != NUL)
2139 {
2140 /* Enclose path with white space in double quotes. */
2141 mch_memmove(vimrun_location + 1, vimrun_location,
2142 STRLEN(vimrun_location) + 1);
2143 *vimrun_location = '"';
2144 STRCPY(gettail(vimrun_location), "vimrun\" ");
2145 }
2146 else
2147 STRCPY(gettail(vimrun_location), "vimrun ");
2148
2149 vimrun_path = (char *)vim_strsave(vimrun_location);
2150 s_dont_use_vimrun = FALSE;
2151 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002152 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002153 s_dont_use_vimrun = FALSE;
2154
2155 /* Don't give the warning for a missing vimrun.exe right now, but only
2156 * when vimrun was supposed to be used. Don't bother people that do
2157 * not need vimrun.exe. */
2158 if (s_dont_use_vimrun)
2159 need_vimrun_warning = TRUE;
2160 }
2161
2162 /*
2163 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2164 * Otherwise the default "findstr /n" is used.
2165 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002166 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002167 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2168
2169#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002170 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171#endif
2172}
2173
2174
2175#else /* FEAT_GUI_W32 */
2176
2177#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2178#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2179
2180/*
2181 * ClearConsoleBuffer()
2182 * Description:
2183 * Clears the entire contents of the console screen buffer, using the
2184 * specified attribute.
2185 * Returns:
2186 * TRUE on success
2187 */
2188 static BOOL
2189ClearConsoleBuffer(WORD wAttribute)
2190{
2191 CONSOLE_SCREEN_BUFFER_INFO csbi;
2192 COORD coord;
2193 DWORD NumCells, dummy;
2194
2195 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2196 return FALSE;
2197
2198 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2199 coord.X = 0;
2200 coord.Y = 0;
2201 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2202 coord, &dummy))
2203 {
2204 return FALSE;
2205 }
2206 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2207 coord, &dummy))
2208 {
2209 return FALSE;
2210 }
2211
2212 return TRUE;
2213}
2214
2215/*
2216 * FitConsoleWindow()
2217 * Description:
2218 * Checks if the console window will fit within given buffer dimensions.
2219 * Also, if requested, will shrink the window to fit.
2220 * Returns:
2221 * TRUE on success
2222 */
2223 static BOOL
2224FitConsoleWindow(
2225 COORD dwBufferSize,
2226 BOOL WantAdjust)
2227{
2228 CONSOLE_SCREEN_BUFFER_INFO csbi;
2229 COORD dwWindowSize;
2230 BOOL NeedAdjust = FALSE;
2231
2232 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2233 {
2234 /*
2235 * A buffer resize will fail if the current console window does
2236 * not lie completely within that buffer. To avoid this, we might
2237 * have to move and possibly shrink the window.
2238 */
2239 if (csbi.srWindow.Right >= dwBufferSize.X)
2240 {
2241 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2242 if (dwWindowSize.X > dwBufferSize.X)
2243 dwWindowSize.X = dwBufferSize.X;
2244 csbi.srWindow.Right = dwBufferSize.X - 1;
2245 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2246 NeedAdjust = TRUE;
2247 }
2248 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2249 {
2250 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2251 if (dwWindowSize.Y > dwBufferSize.Y)
2252 dwWindowSize.Y = dwBufferSize.Y;
2253 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2254 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2255 NeedAdjust = TRUE;
2256 }
2257 if (NeedAdjust && WantAdjust)
2258 {
2259 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2260 return FALSE;
2261 }
2262 return TRUE;
2263 }
2264
2265 return FALSE;
2266}
2267
2268typedef struct ConsoleBufferStruct
2269{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002270 BOOL IsValid;
2271 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002272 PCHAR_INFO Buffer;
2273 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002274 PSMALL_RECT Regions;
2275 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276} ConsoleBuffer;
2277
2278/*
2279 * SaveConsoleBuffer()
2280 * Description:
2281 * Saves important information about the console buffer, including the
2282 * actual buffer contents. The saved information is suitable for later
2283 * restoration by RestoreConsoleBuffer().
2284 * Returns:
2285 * TRUE if all information was saved; FALSE otherwise
2286 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2287 */
2288 static BOOL
2289SaveConsoleBuffer(
2290 ConsoleBuffer *cb)
2291{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002292 DWORD NumCells;
2293 COORD BufferCoord;
2294 SMALL_RECT ReadRegion;
2295 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002296 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002297
Bram Moolenaar071d4272004-06-13 20:20:40 +00002298 if (cb == NULL)
2299 return FALSE;
2300
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002301 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302 {
2303 cb->IsValid = FALSE;
2304 return FALSE;
2305 }
2306 cb->IsValid = TRUE;
2307
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002308 /*
2309 * Allocate a buffer large enough to hold the entire console screen
2310 * buffer. If this ConsoleBuffer structure has already been initialized
2311 * with a buffer of the correct size, then just use that one.
2312 */
2313 if (!cb->IsValid || cb->Buffer == NULL ||
2314 cb->BufferSize.X != cb->Info.dwSize.X ||
2315 cb->BufferSize.Y != cb->Info.dwSize.Y)
2316 {
2317 cb->BufferSize.X = cb->Info.dwSize.X;
2318 cb->BufferSize.Y = cb->Info.dwSize.Y;
2319 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2320 vim_free(cb->Buffer);
2321 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2322 if (cb->Buffer == NULL)
2323 return FALSE;
2324 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325
2326 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002327 * We will now copy the console screen buffer into our buffer.
2328 * ReadConsoleOutput() seems to be limited as far as how much you
2329 * can read at a time. Empirically, this number seems to be about
2330 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2331 * in chunks until it is all copied. The chunks will all have the
2332 * same horizontal characteristics, so initialize them now. The
2333 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002334 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002335 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002336 ReadRegion.Left = 0;
2337 ReadRegion.Right = cb->Info.dwSize.X - 1;
2338 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002339
2340 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2341 if (cb->Regions == NULL || numregions != cb->NumRegions)
2342 {
2343 cb->NumRegions = numregions;
2344 vim_free(cb->Regions);
2345 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2346 if (cb->Regions == NULL)
2347 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002348 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002349 return FALSE;
2350 }
2351 }
2352
2353 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002355 /*
2356 * Read into position (0, Y) in our buffer.
2357 */
2358 BufferCoord.Y = Y;
2359 /*
2360 * Read the region whose top left corner is (0, Y) and whose bottom
2361 * right corner is (width - 1, Y + Y_incr - 1). This should define
2362 * a region of size width by Y_incr. Don't worry if this region is
2363 * too large for the remaining buffer; it will be cropped.
2364 */
2365 ReadRegion.Top = Y;
2366 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002367 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002368 cb->Buffer, /* our buffer */
2369 cb->BufferSize, /* dimensions of our buffer */
2370 BufferCoord, /* offset in our buffer */
2371 &ReadRegion)) /* region to save */
2372 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002373 VIM_CLEAR(cb->Buffer);
2374 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002375 return FALSE;
2376 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002377 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002378 }
2379
2380 return TRUE;
2381}
2382
2383/*
2384 * RestoreConsoleBuffer()
2385 * Description:
2386 * Restores important information about the console buffer, including the
2387 * actual buffer contents, if desired. The information to restore is in
2388 * the same format used by SaveConsoleBuffer().
2389 * Returns:
2390 * TRUE on success
2391 */
2392 static BOOL
2393RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002394 ConsoleBuffer *cb,
2395 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002397 COORD BufferCoord;
2398 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002399 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400
2401 if (cb == NULL || !cb->IsValid)
2402 return FALSE;
2403
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002404 /*
2405 * Before restoring the buffer contents, clear the current buffer, and
2406 * restore the cursor position and window information. Doing this now
2407 * prevents old buffer contents from "flashing" onto the screen.
2408 */
2409 if (RestoreScreen)
2410 ClearConsoleBuffer(cb->Info.wAttributes);
2411
2412 FitConsoleWindow(cb->Info.dwSize, TRUE);
2413 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2414 return FALSE;
2415 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2416 return FALSE;
2417
2418 if (!RestoreScreen)
2419 {
2420 /*
2421 * No need to restore the screen buffer contents, so we're done.
2422 */
2423 return TRUE;
2424 }
2425
2426 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2427 return FALSE;
2428 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2429 return FALSE;
2430
2431 /*
2432 * Restore the screen buffer contents.
2433 */
2434 if (cb->Buffer != NULL)
2435 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002436 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002437 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002438 BufferCoord.X = cb->Regions[i].Left;
2439 BufferCoord.Y = cb->Regions[i].Top;
2440 WriteRegion = cb->Regions[i];
2441 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2442 cb->Buffer, /* our buffer */
2443 cb->BufferSize, /* dimensions of our buffer */
2444 BufferCoord, /* offset in our buffer */
2445 &WriteRegion)) /* region to restore */
2446 {
2447 return FALSE;
2448 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002449 }
2450 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451
2452 return TRUE;
2453}
2454
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002455#define FEAT_RESTORE_ORIG_SCREEN
2456#ifdef FEAT_RESTORE_ORIG_SCREEN
2457static ConsoleBuffer g_cbOrig = { 0 };
2458#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002459static ConsoleBuffer g_cbNonTermcap = { 0 };
2460static ConsoleBuffer g_cbTermcap = { 0 };
2461
2462#ifdef FEAT_TITLE
2463#ifdef __BORLANDC__
2464typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2465#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002466typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467#endif
2468char g_szOrigTitle[256] = { 0 };
2469HWND g_hWnd = NULL; /* also used in os_mswin.c */
2470static HICON g_hOrigIconSmall = NULL;
2471static HICON g_hOrigIcon = NULL;
2472static HICON g_hVimIcon = NULL;
2473static BOOL g_fCanChangeIcon = FALSE;
2474
2475/* ICON* are not defined in VC++ 4.0 */
2476#ifndef ICON_SMALL
2477#define ICON_SMALL 0
2478#endif
2479#ifndef ICON_BIG
2480#define ICON_BIG 1
2481#endif
2482/*
2483 * GetConsoleIcon()
2484 * Description:
2485 * Attempts to retrieve the small icon and/or the big icon currently in
2486 * use by a given window.
2487 * Returns:
2488 * TRUE on success
2489 */
2490 static BOOL
2491GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002492 HWND hWnd,
2493 HICON *phIconSmall,
2494 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495{
2496 if (hWnd == NULL)
2497 return FALSE;
2498
2499 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002500 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2501 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002503 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2504 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002505 return TRUE;
2506}
2507
2508/*
2509 * SetConsoleIcon()
2510 * Description:
2511 * Attempts to change the small icon and/or the big icon currently in
2512 * use by a given window.
2513 * Returns:
2514 * TRUE on success
2515 */
2516 static BOOL
2517SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002518 HWND hWnd,
2519 HICON hIconSmall,
2520 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 if (hWnd == NULL)
2523 return FALSE;
2524
2525 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002526 SendMessage(hWnd, WM_SETICON,
2527 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002529 SendMessage(hWnd, WM_SETICON,
2530 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002531 return TRUE;
2532}
2533
2534/*
2535 * SaveConsoleTitleAndIcon()
2536 * Description:
2537 * Saves the current console window title in g_szOrigTitle, for later
2538 * restoration. Also, attempts to obtain a handle to the console window,
2539 * and use it to save the small and big icons currently in use by the
2540 * console window. This is not always possible on some versions of Windows;
2541 * nor is it possible when running Vim remotely using Telnet (since the
2542 * console window the user sees is owned by a remote process).
2543 */
2544 static void
2545SaveConsoleTitleAndIcon(void)
2546{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547 /* Save the original title. */
2548 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2549 return;
2550
2551 /*
2552 * Obtain a handle to the console window using GetConsoleWindow() from
2553 * KERNEL32.DLL; we need to handle in order to change the window icon.
2554 * This function only exists on NT-based Windows, starting with Windows
2555 * 2000. On older operating systems, we can't change the window icon
2556 * anyway.
2557 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002558 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002559 if (g_hWnd == NULL)
2560 return;
2561
2562 /* Save the original console window icon. */
2563 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2564 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2565 return;
2566
2567 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002568 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002569 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002570 if (g_hVimIcon != NULL)
2571 g_fCanChangeIcon = TRUE;
2572}
2573#endif
2574
2575static int g_fWindInitCalled = FALSE;
2576static int g_fTermcapMode = FALSE;
2577static CONSOLE_CURSOR_INFO g_cci;
2578static DWORD g_cmodein = 0;
2579static DWORD g_cmodeout = 0;
2580
2581/*
2582 * non-GUI version of mch_init().
2583 */
2584 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002585mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002586{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002587#ifndef FEAT_RESTORE_ORIG_SCREEN
2588 CONSOLE_SCREEN_BUFFER_INFO csbi;
2589#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590#ifndef __MINGW32__
2591 extern int _fmode;
2592#endif
2593
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002594 /* Silently handle invalid parameters to CRT functions */
2595 SET_INVALID_PARAM_HANDLER;
2596
Bram Moolenaar071d4272004-06-13 20:20:40 +00002597 /* Let critical errors result in a failure, not in a dialog box. Required
2598 * for the timestamp test to work on removed floppies. */
2599 SetErrorMode(SEM_FAILCRITICALERRORS);
2600
2601 _fmode = O_BINARY; /* we do our own CR-LF translation */
2602 out_flush();
2603
2604 /* Obtain handles for the standard Console I/O devices */
2605 if (read_cmd_fd == 0)
2606 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2607 else
2608 create_conin();
2609 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2610
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002611#ifdef FEAT_RESTORE_ORIG_SCREEN
2612 /* Save the initial console buffer for later restoration */
2613 SaveConsoleBuffer(&g_cbOrig);
2614 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2615#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002616 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002617 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2618 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2619#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002620 if (cterm_normal_fg_color == 0)
2621 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2622 if (cterm_normal_bg_color == 0)
2623 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2624
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002625 // Fg and Bg color index nunmber at startup
2626 g_color_index_fg = g_attrDefault & 0xf;
2627 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2628
Bram Moolenaar071d4272004-06-13 20:20:40 +00002629 /* set termcap codes to current text attributes */
2630 update_tcap(g_attrCurrent);
2631
2632 GetConsoleCursorInfo(g_hConOut, &g_cci);
2633 GetConsoleMode(g_hConIn, &g_cmodein);
2634 GetConsoleMode(g_hConOut, &g_cmodeout);
2635
2636#ifdef FEAT_TITLE
2637 SaveConsoleTitleAndIcon();
2638 /*
2639 * Set both the small and big icons of the console window to Vim's icon.
2640 * Note that Vim presently only has one size of icon (32x32), but it
2641 * automatically gets scaled down to 16x16 when setting the small icon.
2642 */
2643 if (g_fCanChangeIcon)
2644 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2645#endif
2646
2647 ui_get_shellsize();
2648
2649#ifdef MCH_WRITE_DUMP
2650 fdDump = fopen("dump", "wt");
2651
2652 if (fdDump)
2653 {
2654 time_t t;
2655
2656 time(&t);
2657 fputs(ctime(&t), fdDump);
2658 fflush(fdDump);
2659 }
2660#endif
2661
2662 g_fWindInitCalled = TRUE;
2663
2664#ifdef FEAT_MOUSE
2665 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2666#endif
2667
2668#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002669 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002671
2672 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002673}
2674
2675/*
2676 * non-GUI version of mch_exit().
2677 * Shut down and exit with status `r'
2678 * Careful: mch_exit() may be called before mch_init()!
2679 */
2680 void
2681mch_exit(int r)
2682{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002683 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002685 vtp_exit();
2686
Bram Moolenaar955f1982017-02-05 15:10:51 +01002687 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688 if (g_fWindInitCalled)
2689 settmode(TMODE_COOK);
2690
2691 ml_close_all(TRUE); /* remove all memfiles */
2692
2693 if (g_fWindInitCalled)
2694 {
2695#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002696 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002697 /*
2698 * Restore both the small and big icons of the console window to
2699 * what they were at startup. Don't do this when the window is
2700 * closed, Vim would hang here.
2701 */
2702 if (g_fCanChangeIcon && !g_fForceExit)
2703 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2704#endif
2705
2706#ifdef MCH_WRITE_DUMP
2707 if (fdDump)
2708 {
2709 time_t t;
2710
2711 time(&t);
2712 fputs(ctime(&t), fdDump);
2713 fclose(fdDump);
2714 }
2715 fdDump = NULL;
2716#endif
2717 }
2718
2719 SetConsoleCursorInfo(g_hConOut, &g_cci);
2720 SetConsoleMode(g_hConIn, g_cmodein);
2721 SetConsoleMode(g_hConOut, g_cmodeout);
2722
2723#ifdef DYNAMIC_GETTEXT
2724 dyn_libintl_end();
2725#endif
2726
2727 exit(r);
2728}
2729#endif /* !FEAT_GUI_W32 */
2730
Bram Moolenaar071d4272004-06-13 20:20:40 +00002731/*
2732 * Do we have an interactive window?
2733 */
2734 int
2735mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002736 int argc UNUSED,
2737 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738{
2739 get_exe_name();
2740
2741#ifdef FEAT_GUI_W32
2742 return OK; /* GUI always has a tty */
2743#else
2744 if (isatty(1))
2745 return OK;
2746 return FAIL;
2747#endif
2748}
2749
2750
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002751#ifdef FEAT_MBYTE
2752/*
2753 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2754 * if it already exists. When "len" is > 0, also expand short to long
2755 * filenames.
2756 * Return FAIL if wide functions are not available, OK otherwise.
2757 * NOTE: much of this is identical to fname_case(), keep in sync!
2758 */
2759 static int
2760fname_casew(
2761 WCHAR *name,
2762 int len)
2763{
2764 WCHAR szTrueName[_MAX_PATH + 2];
2765 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2766 WCHAR *ptrue, *ptruePrev;
2767 WCHAR *porig, *porigPrev;
2768 int flen;
2769 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002770 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002771 int c;
2772 int slen;
2773
2774 flen = (int)wcslen(name);
2775 if (flen > _MAX_PATH)
2776 return OK;
2777
2778 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2779
2780 /* Build the new name in szTrueName[] one component at a time. */
2781 porig = name;
2782 ptrue = szTrueName;
2783
2784 if (iswalpha(porig[0]) && porig[1] == L':')
2785 {
2786 /* copy leading drive letter */
2787 *ptrue++ = *porig++;
2788 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002789 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002790 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002791
2792 while (*porig != NUL)
2793 {
2794 /* copy \ characters */
2795 while (*porig == psepc)
2796 *ptrue++ = *porig++;
2797
2798 ptruePrev = ptrue;
2799 porigPrev = porig;
2800 while (*porig != NUL && *porig != psepc)
2801 {
2802 *ptrue++ = *porig++;
2803 }
2804 *ptrue = NUL;
2805
2806 /* To avoid a slow failure append "\*" when searching a directory,
2807 * server or network share. */
2808 wcscpy(szTrueNameTemp, szTrueName);
2809 slen = (int)wcslen(szTrueNameTemp);
2810 if (*porig == psepc && slen + 2 < _MAX_PATH)
2811 wcscpy(szTrueNameTemp + slen, L"\\*");
2812
2813 /* Skip "", "." and "..". */
2814 if (ptrue > ptruePrev
2815 && (ptruePrev[0] != L'.'
2816 || (ptruePrev[1] != NUL
2817 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2818 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2819 != INVALID_HANDLE_VALUE)
2820 {
2821 c = *porig;
2822 *porig = NUL;
2823
2824 /* Only use the match when it's the same name (ignoring case) or
2825 * expansion is allowed and there is a match with the short name
2826 * and there is enough room. */
2827 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2828 || (len > 0
2829 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2830 && (int)(ptruePrev - szTrueName)
2831 + (int)wcslen(fb.cFileName) < len)))
2832 {
2833 wcscpy(ptruePrev, fb.cFileName);
2834
2835 /* Look for exact match and prefer it if found. Must be a
2836 * long name, otherwise there would be only one match. */
2837 while (FindNextFileW(hFind, &fb))
2838 {
2839 if (*fb.cAlternateFileName != NUL
2840 && (wcscoll(porigPrev, fb.cFileName) == 0
2841 || (len > 0
2842 && (_wcsicoll(porigPrev,
2843 fb.cAlternateFileName) == 0
2844 && (int)(ptruePrev - szTrueName)
2845 + (int)wcslen(fb.cFileName) < len))))
2846 {
2847 wcscpy(ptruePrev, fb.cFileName);
2848 break;
2849 }
2850 }
2851 }
2852 FindClose(hFind);
2853 *porig = c;
2854 ptrue = ptruePrev + wcslen(ptruePrev);
2855 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002856 }
2857
2858 wcscpy(name, szTrueName);
2859 return OK;
2860}
2861#endif
2862
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863/*
2864 * fname_case(): Set the case of the file name, if it already exists.
2865 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002866 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867 */
2868 void
2869fname_case(
2870 char_u *name,
2871 int len)
2872{
2873 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002874 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002875 char *ptrue, *ptruePrev;
2876 char *porig, *porigPrev;
2877 int flen;
2878 WIN32_FIND_DATA fb;
2879 HANDLE hFind;
2880 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002881 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002882
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002883 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002884 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 return;
2886
2887 slash_adjust(name);
2888
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002889#ifdef FEAT_MBYTE
2890 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2891 {
2892 WCHAR *p = enc_to_utf16(name, NULL);
2893
2894 if (p != NULL)
2895 {
2896 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002897 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002898
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002899 wcsncpy(buf, p, _MAX_PATH);
2900 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002901 vim_free(p);
2902
2903 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2904 {
2905 q = utf16_to_enc(buf, NULL);
2906 if (q != NULL)
2907 {
2908 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2909 vim_free(q);
2910 return;
2911 }
2912 }
2913 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002914 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002915 }
2916#endif
2917
2918 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2919 * So we should check this after calling wide function. */
2920 if (flen > _MAX_PATH)
2921 return;
2922
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002924 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925 ptrue = szTrueName;
2926
2927 if (isalpha(porig[0]) && porig[1] == ':')
2928 {
2929 /* copy leading drive letter */
2930 *ptrue++ = *porig++;
2931 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002932 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002933 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934
2935 while (*porig != NUL)
2936 {
2937 /* copy \ characters */
2938 while (*porig == psepc)
2939 *ptrue++ = *porig++;
2940
2941 ptruePrev = ptrue;
2942 porigPrev = porig;
2943 while (*porig != NUL && *porig != psepc)
2944 {
2945#ifdef FEAT_MBYTE
2946 int l;
2947
2948 if (enc_dbcs)
2949 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002950 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002951 while (--l >= 0)
2952 *ptrue++ = *porig++;
2953 }
2954 else
2955#endif
2956 *ptrue++ = *porig++;
2957 }
2958 *ptrue = NUL;
2959
Bram Moolenaar464c9252010-10-13 20:37:41 +02002960 /* To avoid a slow failure append "\*" when searching a directory,
2961 * server or network share. */
2962 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002963 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002964 if (*porig == psepc && slen + 2 < _MAX_PATH)
2965 STRCPY(szTrueNameTemp + slen, "\\*");
2966
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967 /* Skip "", "." and "..". */
2968 if (ptrue > ptruePrev
2969 && (ptruePrev[0] != '.'
2970 || (ptruePrev[1] != NUL
2971 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002972 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973 != INVALID_HANDLE_VALUE)
2974 {
2975 c = *porig;
2976 *porig = NUL;
2977
2978 /* Only use the match when it's the same name (ignoring case) or
2979 * expansion is allowed and there is a match with the short name
2980 * and there is enough room. */
2981 if (_stricoll(porigPrev, fb.cFileName) == 0
2982 || (len > 0
2983 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2984 && (int)(ptruePrev - szTrueName)
2985 + (int)strlen(fb.cFileName) < len)))
2986 {
2987 STRCPY(ptruePrev, fb.cFileName);
2988
2989 /* Look for exact match and prefer it if found. Must be a
2990 * long name, otherwise there would be only one match. */
2991 while (FindNextFile(hFind, &fb))
2992 {
2993 if (*fb.cAlternateFileName != NUL
2994 && (strcoll(porigPrev, fb.cFileName) == 0
2995 || (len > 0
2996 && (_stricoll(porigPrev,
2997 fb.cAlternateFileName) == 0
2998 && (int)(ptruePrev - szTrueName)
2999 + (int)strlen(fb.cFileName) < len))))
3000 {
3001 STRCPY(ptruePrev, fb.cFileName);
3002 break;
3003 }
3004 }
3005 }
3006 FindClose(hFind);
3007 *porig = c;
3008 ptrue = ptruePrev + strlen(ptruePrev);
3009 }
3010 }
3011
3012 STRCPY(name, szTrueName);
3013}
3014
3015
3016/*
3017 * Insert user name in s[len].
3018 */
3019 int
3020mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003021 char_u *s,
3022 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003024 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 DWORD cch = sizeof szUserName;
3026
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003027#ifdef FEAT_MBYTE
3028 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3029 {
3030 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3031 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3032
3033 if (GetUserNameW(wszUserName, &wcch))
3034 {
3035 char_u *p = utf16_to_enc(wszUserName, NULL);
3036
3037 if (p != NULL)
3038 {
3039 vim_strncpy(s, p, len - 1);
3040 vim_free(p);
3041 return OK;
3042 }
3043 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003044 }
3045#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046 if (GetUserName(szUserName, &cch))
3047 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003048 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049 return OK;
3050 }
3051 s[0] = NUL;
3052 return FAIL;
3053}
3054
3055
3056/*
3057 * Insert host name in s[len].
3058 */
3059 void
3060mch_get_host_name(
3061 char_u *s,
3062 int len)
3063{
3064 DWORD cch = len;
3065
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003066#ifdef FEAT_MBYTE
3067 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3068 {
3069 WCHAR wszHostName[256 + 1];
3070 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3071
3072 if (GetComputerNameW(wszHostName, &wcch))
3073 {
3074 char_u *p = utf16_to_enc(wszHostName, NULL);
3075
3076 if (p != NULL)
3077 {
3078 vim_strncpy(s, p, len - 1);
3079 vim_free(p);
3080 return;
3081 }
3082 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003083 }
3084#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003085 if (!GetComputerName((LPSTR)s, &cch))
3086 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087}
3088
3089
3090/*
3091 * return process ID
3092 */
3093 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003094mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095{
3096 return (long)GetCurrentProcessId();
3097}
3098
3099
3100/*
3101 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3102 * Return OK for success, FAIL for failure.
3103 */
3104 int
3105mch_dirname(
3106 char_u *buf,
3107 int len)
3108{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003109 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003110 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003111
Bram Moolenaar071d4272004-06-13 20:20:40 +00003112 /*
3113 * Originally this was:
3114 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3115 * But the Win32s known bug list says that getcwd() doesn't work
3116 * so use the Win32 system call instead. <Negri>
3117 */
3118#ifdef FEAT_MBYTE
3119 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3120 {
3121 WCHAR wbuf[_MAX_PATH + 1];
3122
3123 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3124 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003125 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003126 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003127
3128 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003129 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003130 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003131 if (STRLEN(p) >= (size_t)len)
3132 {
3133 // long path name is too long, fall back to short one
3134 vim_free(p);
3135 p = NULL;
3136 }
3137 }
3138 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003139 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140
3141 if (p != NULL)
3142 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003143 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003144 vim_free(p);
3145 return OK;
3146 }
3147 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003148 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149 }
3150#endif
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003151 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3152 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003153 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3154 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3155 // Failed to get long path name or it's too long: fall back to the
3156 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003157 return OK;
3158
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003159 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003160 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161}
3162
3163/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003164 * Get file permissions for "name".
3165 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166 */
3167 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003168mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003169{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003170 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003171 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003172
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003173 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003174 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003175}
3176
3177
3178/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003179 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003180 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003181 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003182 */
3183 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003184mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003185{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003186 long n = -1;
3187
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188#ifdef FEAT_MBYTE
3189 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3190 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003191 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192
3193 if (p != NULL)
3194 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003195 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003197 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003198 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003199 }
3200 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003201 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003203 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003204 if (n == -1)
3205 return FAIL;
3206
3207 win32_set_archive(name);
3208
3209 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210}
3211
3212/*
3213 * Set hidden flag for "name".
3214 */
3215 void
3216mch_hide(char_u *name)
3217{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003218 int attrs = win32_getattrs(name);
3219 if (attrs == -1)
3220 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003221
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003222 attrs |= FILE_ATTRIBUTE_HIDDEN;
3223 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003224}
3225
3226/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003227 * Return TRUE if file "name" exists and is hidden.
3228 */
3229 int
3230mch_ishidden(char_u *name)
3231{
3232 int f = win32_getattrs(name);
3233
3234 if (f == -1)
3235 return FALSE; /* file does not exist at all */
3236
3237 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3238}
3239
3240/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003241 * return TRUE if "name" is a directory
3242 * return FALSE if "name" is not a directory or upon error
3243 */
3244 int
3245mch_isdir(char_u *name)
3246{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003247 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003248
3249 if (f == -1)
3250 return FALSE; /* file does not exist at all */
3251
3252 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3253}
3254
3255/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003256 * return TRUE if "name" is a directory, NOT a symlink to a directory
3257 * return FALSE if "name" is not a directory
3258 * return FALSE for error
3259 */
3260 int
3261mch_isrealdir(char_u *name)
3262{
3263 return mch_isdir(name) && !mch_is_symbolic_link(name);
3264}
3265
3266/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003267 * Create directory "name".
3268 * Return 0 on success, -1 on error.
3269 */
3270 int
3271mch_mkdir(char_u *name)
3272{
3273#ifdef FEAT_MBYTE
3274 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3275 {
3276 WCHAR *p;
3277 int retval;
3278
3279 p = enc_to_utf16(name, NULL);
3280 if (p == NULL)
3281 return -1;
3282 retval = _wmkdir(p);
3283 vim_free(p);
3284 return retval;
3285 }
3286#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003287 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003288}
3289
3290/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003291 * Delete directory "name".
3292 * Return 0 on success, -1 on error.
3293 */
3294 int
3295mch_rmdir(char_u *name)
3296{
3297#ifdef FEAT_MBYTE
3298 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3299 {
3300 WCHAR *p;
3301 int retval;
3302
3303 p = enc_to_utf16(name, NULL);
3304 if (p == NULL)
3305 return -1;
3306 retval = _wrmdir(p);
3307 vim_free(p);
3308 return retval;
3309 }
3310#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003311 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003312}
3313
3314/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003315 * Return TRUE if file "fname" has more than one link.
3316 */
3317 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003318mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003319{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003320 BY_HANDLE_FILE_INFORMATION info;
3321
3322 return win32_fileinfo(fname, &info) == FILEINFO_OK
3323 && info.nNumberOfLinks > 1;
3324}
3325
3326/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003327 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003328 */
3329 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003330mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003331{
3332 HANDLE hFind;
3333 int res = FALSE;
3334 WIN32_FIND_DATAA findDataA;
3335 DWORD fileFlags = 0, reparseTag = 0;
3336#ifdef FEAT_MBYTE
3337 WCHAR *wn = NULL;
3338 WIN32_FIND_DATAW findDataW;
3339
3340 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003341 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003342 if (wn != NULL)
3343 {
3344 hFind = FindFirstFileW(wn, &findDataW);
3345 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003346 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003347 {
3348 fileFlags = findDataW.dwFileAttributes;
3349 reparseTag = findDataW.dwReserved0;
3350 }
3351 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003352 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003353#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003354 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003355 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003356 if (hFind != INVALID_HANDLE_VALUE)
3357 {
3358 fileFlags = findDataA.dwFileAttributes;
3359 reparseTag = findDataA.dwReserved0;
3360 }
3361 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003362
3363 if (hFind != INVALID_HANDLE_VALUE)
3364 FindClose(hFind);
3365
3366 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003367 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3368 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003369 res = TRUE;
3370
3371 return res;
3372}
3373
3374/*
3375 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3376 * link.
3377 */
3378 int
3379mch_is_linked(char_u *fname)
3380{
3381 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3382 return TRUE;
3383 return FALSE;
3384}
3385
3386/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003387 * Get the by-handle-file-information for "fname".
3388 * Returns FILEINFO_OK when OK.
3389 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3390 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3391 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3392 */
3393 int
3394win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3395{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003396 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003397 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003398#ifdef FEAT_MBYTE
3399 WCHAR *wn = NULL;
3400
3401 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003402 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003403 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003404 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003405 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003406 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003407 if (wn != NULL)
3408 {
3409 hFile = CreateFileW(wn, /* file name */
3410 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003411 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003412 NULL, /* security descriptor */
3413 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003414 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003415 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003416 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003417 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003418 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003419#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003420 hFile = CreateFile((LPCSTR)fname, /* file name */
3421 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003422 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003423 NULL, /* security descriptor */
3424 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003425 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003426 NULL); /* handle to template file */
3427
3428 if (hFile != INVALID_HANDLE_VALUE)
3429 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003430 if (GetFileInformationByHandle(hFile, info) != 0)
3431 res = FILEINFO_OK;
3432 else
3433 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003434 CloseHandle(hFile);
3435 }
3436
Bram Moolenaar03f48552006-02-28 23:52:23 +00003437 return res;
3438}
3439
3440/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003441 * get file attributes for `name'
3442 * -1 : error
3443 * else FILE_ATTRIBUTE_* defined in winnt.h
3444 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003445 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003446win32_getattrs(char_u *name)
3447{
3448 int attr;
3449#ifdef FEAT_MBYTE
3450 WCHAR *p = NULL;
3451
3452 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3453 p = enc_to_utf16(name, NULL);
3454
3455 if (p != NULL)
3456 {
3457 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003458 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003459 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003460 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003461#endif
3462 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003463
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003464 return attr;
3465}
3466
3467/*
3468 * set file attributes for `name' to `attrs'
3469 *
3470 * return -1 for failure, 0 otherwise
3471 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003472 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003473win32_setattrs(char_u *name, int attrs)
3474{
3475 int res;
3476#ifdef FEAT_MBYTE
3477 WCHAR *p = NULL;
3478
3479 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3480 p = enc_to_utf16(name, NULL);
3481
3482 if (p != NULL)
3483 {
3484 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003485 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003486 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003487 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003488#endif
3489 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003490
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003491 return res ? 0 : -1;
3492}
3493
3494/*
3495 * Set archive flag for "name".
3496 */
Bram Moolenaar6dff58f2018-09-30 21:43:26 +02003497 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003498win32_set_archive(char_u *name)
3499{
3500 int attrs = win32_getattrs(name);
3501 if (attrs == -1)
3502 return -1;
3503
3504 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3505 return win32_setattrs(name, attrs);
3506}
3507
3508/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509 * Return TRUE if file or directory "name" is writable (not readonly).
3510 * Strange semantics of Win32: a readonly directory is writable, but you can't
3511 * delete a file. Let's say this means it is writable.
3512 */
3513 int
3514mch_writable(char_u *name)
3515{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003516 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003517
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003518 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3519 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003520}
3521
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003523 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003524 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003525 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3526 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003527 */
3528 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003529mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003530{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003531 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003532 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003533 char_u *p;
3534
3535 if (len >= _MAX_PATH) /* safety check */
3536 return FALSE;
3537
3538 /* If there already is an extension try using the name directly. Also do
3539 * this with a Unix-shell like 'shell'. */
3540 if (vim_strchr(gettail(name), '.') != NULL
3541 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003542 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003543 return TRUE;
3544
3545 /*
3546 * Loop over all extensions in $PATHEXT.
3547 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003548 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003549 p = mch_getenv("PATHEXT");
3550 if (p == NULL)
3551 p = (char_u *)".com;.exe;.bat;.cmd";
3552 while (*p)
3553 {
3554 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3555 {
3556 /* A single "." means no extension is added. */
3557 buf[len] = NUL;
3558 ++p;
3559 if (*p)
3560 ++p;
3561 }
3562 else
3563 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003564 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003565 return TRUE;
3566 }
3567 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003568}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003569
3570/*
3571 * Check what "name" is:
3572 * NODE_NORMAL: file or directory (or doesn't exist)
3573 * NODE_WRITABLE: writable device, socket, fifo, etc.
3574 * NODE_OTHER: non-writable things
3575 */
3576 int
3577mch_nodetype(char_u *name)
3578{
3579 HANDLE hFile;
3580 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003581#ifdef FEAT_MBYTE
3582 WCHAR *wn = NULL;
3583#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584
Bram Moolenaar043545e2006-10-10 16:44:07 +00003585 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3586 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3587 * here. */
3588 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3589 return NODE_WRITABLE;
3590
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003591#ifdef FEAT_MBYTE
3592 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003593 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003594
3595 if (wn != NULL)
3596 {
3597 hFile = CreateFileW(wn, /* file name */
3598 GENERIC_WRITE, /* access mode */
3599 0, /* share mode */
3600 NULL, /* security descriptor */
3601 OPEN_EXISTING, /* creation disposition */
3602 0, /* file attributes */
3603 NULL); /* handle to template file */
3604 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003605 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003606 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003607#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003608 hFile = CreateFile((LPCSTR)name, /* file name */
3609 GENERIC_WRITE, /* access mode */
3610 0, /* share mode */
3611 NULL, /* security descriptor */
3612 OPEN_EXISTING, /* creation disposition */
3613 0, /* file attributes */
3614 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615
3616 if (hFile == INVALID_HANDLE_VALUE)
3617 return NODE_NORMAL;
3618
3619 type = GetFileType(hFile);
3620 CloseHandle(hFile);
3621 if (type == FILE_TYPE_CHAR)
3622 return NODE_WRITABLE;
3623 if (type == FILE_TYPE_DISK)
3624 return NODE_NORMAL;
3625 return NODE_OTHER;
3626}
3627
3628#ifdef HAVE_ACL
3629struct my_acl
3630{
3631 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3632 PSID pSidOwner;
3633 PSID pSidGroup;
3634 PACL pDacl;
3635 PACL pSacl;
3636};
3637#endif
3638
3639/*
3640 * Return a pointer to the ACL of file "fname" in allocated memory.
3641 * Return NULL if the ACL is not available for whatever reason.
3642 */
3643 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003644mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003645{
3646#ifndef HAVE_ACL
3647 return (vim_acl_T)NULL;
3648#else
3649 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003650 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003651
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003652 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3653 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003654 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003655# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003656 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003657
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003658 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3659 wn = enc_to_utf16(fname, NULL);
3660 if (wn != NULL)
3661 {
3662 /* Try to retrieve the entire security descriptor. */
3663 err = GetNamedSecurityInfoW(
3664 wn, // Abstract filename
3665 SE_FILE_OBJECT, // File Object
3666 OWNER_SECURITY_INFORMATION |
3667 GROUP_SECURITY_INFORMATION |
3668 DACL_SECURITY_INFORMATION |
3669 SACL_SECURITY_INFORMATION,
3670 &p->pSidOwner, // Ownership information.
3671 &p->pSidGroup, // Group membership.
3672 &p->pDacl, // Discretionary information.
3673 &p->pSacl, // For auditing purposes.
3674 &p->pSecurityDescriptor);
3675 if (err == ERROR_ACCESS_DENIED ||
3676 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003677 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003678 /* Retrieve only DACL. */
3679 (void)GetNamedSecurityInfoW(
3680 wn,
3681 SE_FILE_OBJECT,
3682 DACL_SECURITY_INFORMATION,
3683 NULL,
3684 NULL,
3685 &p->pDacl,
3686 NULL,
3687 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003688 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003689 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003690 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003691 mch_free_acl((vim_acl_T)p);
3692 p = NULL;
3693 }
3694 vim_free(wn);
3695 }
3696 else
3697# endif
3698 {
3699 /* Try to retrieve the entire security descriptor. */
3700 err = GetNamedSecurityInfo(
3701 (LPSTR)fname, // Abstract filename
3702 SE_FILE_OBJECT, // File Object
3703 OWNER_SECURITY_INFORMATION |
3704 GROUP_SECURITY_INFORMATION |
3705 DACL_SECURITY_INFORMATION |
3706 SACL_SECURITY_INFORMATION,
3707 &p->pSidOwner, // Ownership information.
3708 &p->pSidGroup, // Group membership.
3709 &p->pDacl, // Discretionary information.
3710 &p->pSacl, // For auditing purposes.
3711 &p->pSecurityDescriptor);
3712 if (err == ERROR_ACCESS_DENIED ||
3713 err == ERROR_PRIVILEGE_NOT_HELD)
3714 {
3715 /* Retrieve only DACL. */
3716 (void)GetNamedSecurityInfo(
3717 (LPSTR)fname,
3718 SE_FILE_OBJECT,
3719 DACL_SECURITY_INFORMATION,
3720 NULL,
3721 NULL,
3722 &p->pDacl,
3723 NULL,
3724 &p->pSecurityDescriptor);
3725 }
3726 if (p->pSecurityDescriptor == NULL)
3727 {
3728 mch_free_acl((vim_acl_T)p);
3729 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003730 }
3731 }
3732 }
3733
3734 return (vim_acl_T)p;
3735#endif
3736}
3737
Bram Moolenaar27515922013-06-29 15:36:26 +02003738#ifdef HAVE_ACL
3739/*
3740 * Check if "acl" contains inherited ACE.
3741 */
3742 static BOOL
3743is_acl_inherited(PACL acl)
3744{
3745 DWORD i;
3746 ACL_SIZE_INFORMATION acl_info;
3747 PACCESS_ALLOWED_ACE ace;
3748
3749 acl_info.AceCount = 0;
3750 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3751 for (i = 0; i < acl_info.AceCount; i++)
3752 {
3753 GetAce(acl, i, (LPVOID *)&ace);
3754 if (ace->Header.AceFlags & INHERITED_ACE)
3755 return TRUE;
3756 }
3757 return FALSE;
3758}
3759#endif
3760
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761/*
3762 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3763 * Errors are ignored.
3764 * This must only be called with "acl" equal to what mch_get_acl() returned.
3765 */
3766 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003767mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003768{
3769#ifdef HAVE_ACL
3770 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003771 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003773 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003774 {
3775# ifdef FEAT_MBYTE
3776 WCHAR *wn = NULL;
3777# endif
3778
3779 /* Set security flags */
3780 if (p->pSidOwner)
3781 sec_info |= OWNER_SECURITY_INFORMATION;
3782 if (p->pSidGroup)
3783 sec_info |= GROUP_SECURITY_INFORMATION;
3784 if (p->pDacl)
3785 {
3786 sec_info |= DACL_SECURITY_INFORMATION;
3787 /* Do not inherit its parent's DACL.
3788 * If the DACL is inherited, Cygwin permissions would be changed.
3789 */
3790 if (!is_acl_inherited(p->pDacl))
3791 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3792 }
3793 if (p->pSacl)
3794 sec_info |= SACL_SECURITY_INFORMATION;
3795
3796# ifdef FEAT_MBYTE
3797 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3798 wn = enc_to_utf16(fname, NULL);
3799 if (wn != NULL)
3800 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003801 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003802 wn, // Abstract filename
3803 SE_FILE_OBJECT, // File Object
3804 sec_info,
3805 p->pSidOwner, // Ownership information.
3806 p->pSidGroup, // Group membership.
3807 p->pDacl, // Discretionary information.
3808 p->pSacl // For auditing purposes.
3809 );
3810 vim_free(wn);
3811 }
3812 else
3813# endif
3814 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003815 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003816 (LPSTR)fname, // Abstract filename
3817 SE_FILE_OBJECT, // File Object
3818 sec_info,
3819 p->pSidOwner, // Ownership information.
3820 p->pSidGroup, // Group membership.
3821 p->pDacl, // Discretionary information.
3822 p->pSacl // For auditing purposes.
3823 );
3824 }
3825 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003826#endif
3827}
3828
3829 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003830mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831{
3832#ifdef HAVE_ACL
3833 struct my_acl *p = (struct my_acl *)acl;
3834
3835 if (p != NULL)
3836 {
3837 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3838 vim_free(p);
3839 }
3840#endif
3841}
3842
3843#ifndef FEAT_GUI_W32
3844
3845/*
3846 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3847 */
3848 static BOOL WINAPI
3849handler_routine(
3850 DWORD dwCtrlType)
3851{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003852 INPUT_RECORD ir;
3853 DWORD out;
3854
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855 switch (dwCtrlType)
3856 {
3857 case CTRL_C_EVENT:
3858 if (ctrl_c_interrupts)
3859 g_fCtrlCPressed = TRUE;
3860 return TRUE;
3861
3862 case CTRL_BREAK_EVENT:
3863 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003864 ctrl_break_was_pressed = TRUE;
3865 /* ReadConsoleInput is blocking, send a key event to continue. */
3866 ir.EventType = KEY_EVENT;
3867 ir.Event.KeyEvent.bKeyDown = TRUE;
3868 ir.Event.KeyEvent.wRepeatCount = 1;
3869 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3870 ir.Event.KeyEvent.wVirtualScanCode = 0;
3871 ir.Event.KeyEvent.dwControlKeyState = 0;
3872 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3873 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874 return TRUE;
3875
3876 /* fatal events: shut down gracefully */
3877 case CTRL_CLOSE_EVENT:
3878 case CTRL_LOGOFF_EVENT:
3879 case CTRL_SHUTDOWN_EVENT:
3880 windgoto((int)Rows - 1, 0);
3881 g_fForceExit = TRUE;
3882
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003883 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003884 (dwCtrlType == CTRL_CLOSE_EVENT
3885 ? _("close")
3886 : dwCtrlType == CTRL_LOGOFF_EVENT
3887 ? _("logoff")
3888 : _("shutdown")));
3889#ifdef DEBUG
3890 OutputDebugString(IObuff);
3891#endif
3892
3893 preserve_exit(); /* output IObuff, preserve files and exit */
3894
3895 return TRUE; /* not reached */
3896
3897 default:
3898 return FALSE;
3899 }
3900}
3901
3902
3903/*
3904 * set the tty in (raw) ? "raw" : "cooked" mode
3905 */
3906 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003907mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908{
3909 DWORD cmodein;
3910 DWORD cmodeout;
3911 BOOL bEnableHandler;
3912
3913 GetConsoleMode(g_hConIn, &cmodein);
3914 GetConsoleMode(g_hConOut, &cmodeout);
3915 if (tmode == TMODE_RAW)
3916 {
3917 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3918 ENABLE_ECHO_INPUT);
3919#ifdef FEAT_MOUSE
3920 if (g_fMouseActive)
3921 cmodein |= ENABLE_MOUSE_INPUT;
3922#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003923 cmodeout &= ~(
3924#ifdef FEAT_TERMGUICOLORS
3925 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3926 * VTP. */
3927 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3928#else
3929 ENABLE_PROCESSED_OUTPUT |
3930#endif
3931 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003932 bEnableHandler = TRUE;
3933 }
3934 else /* cooked */
3935 {
3936 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3937 ENABLE_ECHO_INPUT);
3938 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3939 bEnableHandler = FALSE;
3940 }
3941 SetConsoleMode(g_hConIn, cmodein);
3942 SetConsoleMode(g_hConOut, cmodeout);
3943 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3944
3945#ifdef MCH_WRITE_DUMP
3946 if (fdDump)
3947 {
3948 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3949 tmode == TMODE_RAW ? "raw" :
3950 tmode == TMODE_COOK ? "cooked" : "normal",
3951 cmodein, cmodeout);
3952 fflush(fdDump);
3953 }
3954#endif
3955}
3956
3957
3958/*
3959 * Get the size of the current window in `Rows' and `Columns'
3960 * Return OK when size could be determined, FAIL otherwise.
3961 */
3962 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003963mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003964{
3965 CONSOLE_SCREEN_BUFFER_INFO csbi;
3966
3967 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3968 {
3969 /*
3970 * For some reason, we are trying to get the screen dimensions
3971 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3972 * variables are really intended to mean the size of Vim screen
3973 * while in termcap mode.
3974 */
3975 Rows = g_cbTermcap.Info.dwSize.Y;
3976 Columns = g_cbTermcap.Info.dwSize.X;
3977 }
3978 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3979 {
3980 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3981 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3982 }
3983 else
3984 {
3985 Rows = 25;
3986 Columns = 80;
3987 }
3988 return OK;
3989}
3990
3991/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02003992 * Resize console buffer to 'COORD'
3993 */
3994 static void
3995ResizeConBuf(
3996 HANDLE hConsole,
3997 COORD coordScreen)
3998{
3999 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4000 {
4001#ifdef MCH_WRITE_DUMP
4002 if (fdDump)
4003 {
4004 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4005 GetLastError());
4006 fflush(fdDump);
4007 }
4008#endif
4009 }
4010}
4011
4012/*
4013 * Resize console window size to 'srWindowRect'
4014 */
4015 static void
4016ResizeWindow(
4017 HANDLE hConsole,
4018 SMALL_RECT srWindowRect)
4019{
4020 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4021 {
4022#ifdef MCH_WRITE_DUMP
4023 if (fdDump)
4024 {
4025 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4026 GetLastError());
4027 fflush(fdDump);
4028 }
4029#endif
4030 }
4031}
4032
4033/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004034 * Set a console window to `xSize' * `ySize'
4035 */
4036 static void
4037ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004038 HANDLE hConsole,
4039 int xSize,
4040 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041{
4042 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4043 SMALL_RECT srWindowRect; /* hold the new console size */
4044 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004045 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004046
4047#ifdef MCH_WRITE_DUMP
4048 if (fdDump)
4049 {
4050 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4051 fflush(fdDump);
4052 }
4053#endif
4054
4055 /* get the largest size we can size the console window to */
4056 coordScreen = GetLargestConsoleWindowSize(hConsole);
4057
4058 /* define the new console window size and scroll position */
4059 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4060 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4061 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4062
4063 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4064 {
4065 int sx, sy;
4066
4067 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4068 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4069 if (sy < ySize || sx < xSize)
4070 {
4071 /*
4072 * Increasing number of lines/columns, do buffer first.
4073 * Use the maximal size in x and y direction.
4074 */
4075 if (sy < ySize)
4076 coordScreen.Y = ySize;
4077 else
4078 coordScreen.Y = sy;
4079 if (sx < xSize)
4080 coordScreen.X = xSize;
4081 else
4082 coordScreen.X = sx;
4083 SetConsoleScreenBufferSize(hConsole, coordScreen);
4084 }
4085 }
4086
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004087 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088 coordScreen.X = xSize;
4089 coordScreen.Y = ySize;
4090
Bram Moolenaar2551c032018-08-23 22:38:31 +02004091 // In the new console call API, only the first time in reverse order
4092 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004094 ResizeWindow(hConsole, srWindowRect);
4095 ResizeConBuf(hConsole, coordScreen);
4096 }
4097 else
4098 {
4099 ResizeConBuf(hConsole, coordScreen);
4100 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004101 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102 }
4103}
4104
4105
4106/*
4107 * Set the console window to `Rows' * `Columns'
4108 */
4109 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004110mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004111{
4112 COORD coordScreen;
4113
4114 /* Don't change window size while still starting up */
4115 if (suppress_winsize != 0)
4116 {
4117 suppress_winsize = 2;
4118 return;
4119 }
4120
4121 if (term_console)
4122 {
4123 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4124
4125 /* Clamp Rows and Columns to reasonable values */
4126 if (Rows > coordScreen.Y)
4127 Rows = coordScreen.Y;
4128 if (Columns > coordScreen.X)
4129 Columns = coordScreen.X;
4130
4131 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4132 }
4133}
4134
4135/*
4136 * Rows and/or Columns has changed.
4137 */
4138 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004139mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004140{
4141 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4142}
4143
4144
4145/*
4146 * Called when started up, to set the winsize that was delayed.
4147 */
4148 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004149mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150{
4151 if (suppress_winsize == 2)
4152 {
4153 suppress_winsize = 0;
4154 mch_set_shellsize();
4155 shell_resized();
4156 }
4157 suppress_winsize = 0;
4158}
4159#endif /* FEAT_GUI_W32 */
4160
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004161 static BOOL
4162vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004163 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004164 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004165 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004166 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004167 PROCESS_INFORMATION *pi,
4168 LPVOID *env,
4169 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004170{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004171#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004172 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4173 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004174 BOOL ret;
4175 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004176
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004177 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4178 if (wcmd == NULL)
4179 goto fallback;
4180 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004181 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004182 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4183 if (wcwd == NULL)
4184 {
4185 vim_free(wcmd);
4186 goto fallback;
4187 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004188 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004189
4190 ret = CreateProcessW(
4191 NULL, /* Executable name */
4192 wcmd, /* Command to execute */
4193 NULL, /* Process security attributes */
4194 NULL, /* Thread security attributes */
4195 inherit_handles, /* Inherit handles */
4196 flags, /* Creation flags */
4197 env, /* Environment */
4198 wcwd, /* Current directory */
4199 (LPSTARTUPINFOW)si, /* Startup information */
4200 pi); /* Process information */
4201 vim_free(wcmd);
4202 if (wcwd != NULL)
4203 vim_free(wcwd);
4204 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004205 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004206fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004207#endif
4208 return CreateProcess(
4209 NULL, /* Executable name */
4210 cmd, /* Command to execute */
4211 NULL, /* Process security attributes */
4212 NULL, /* Thread security attributes */
4213 inherit_handles, /* Inherit handles */
4214 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004215 env, /* Environment */
4216 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004217 si, /* Startup information */
4218 pi); /* Process information */
4219}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004220
4221
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004222 static HINSTANCE
4223vim_shell_execute(
4224 char *cmd,
4225 INT n_show_cmd)
4226{
4227#ifdef FEAT_MBYTE
4228 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4229 {
4230 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4231 if (wcmd != NULL)
4232 {
4233 HINSTANCE ret;
4234 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4235 vim_free(wcmd);
4236 return ret;
4237 }
4238 }
4239#endif
4240 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4241}
4242
4243
Bram Moolenaar071d4272004-06-13 20:20:40 +00004244#if defined(FEAT_GUI_W32) || defined(PROTO)
4245
4246/*
4247 * Specialised version of system() for Win32 GUI mode.
4248 * This version proceeds as follows:
4249 * 1. Create a console window for use by the subprocess
4250 * 2. Run the subprocess (it gets the allocated console by default)
4251 * 3. Wait for the subprocess to terminate and get its exit code
4252 * 4. Prompt the user to press a key to close the console window
4253 */
4254 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004255mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004256{
4257 STARTUPINFO si;
4258 PROCESS_INFORMATION pi;
4259 DWORD ret = 0;
4260 HWND hwnd = GetFocus();
4261
4262 si.cb = sizeof(si);
4263 si.lpReserved = NULL;
4264 si.lpDesktop = NULL;
4265 si.lpTitle = NULL;
4266 si.dwFlags = STARTF_USESHOWWINDOW;
4267 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004268 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004269 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004270 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004271 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004272 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004273 else
4274 si.wShowWindow = SW_SHOWNORMAL;
4275 si.cbReserved2 = 0;
4276 si.lpReserved2 = NULL;
4277
Bram Moolenaar071d4272004-06-13 20:20:40 +00004278 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004279 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004280 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4281 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004282
4283 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284 {
4285#ifdef FEAT_GUI
4286 int delay = 1;
4287
4288 /* Keep updating the window while waiting for the shell to finish. */
4289 for (;;)
4290 {
4291 MSG msg;
4292
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004293 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004294 {
4295 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004296 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004297 delay = 1;
4298 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004299 }
4300 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4301 break;
4302
4303 /* We start waiting for a very short time and then increase it, so
4304 * that we respond quickly when the process is quick, and don't
4305 * consume too much overhead when it's slow. */
4306 if (delay < 50)
4307 delay += 10;
4308 }
4309#else
4310 WaitForSingleObject(pi.hProcess, INFINITE);
4311#endif
4312
4313 /* Get the command exit code */
4314 GetExitCodeProcess(pi.hProcess, &ret);
4315 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316
4317 /* Close the handles to the subprocess, so that it goes away */
4318 CloseHandle(pi.hThread);
4319 CloseHandle(pi.hProcess);
4320
4321 /* Try to get input focus back. Doesn't always work though. */
4322 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4323
4324 return ret;
4325}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004326
4327/*
4328 * Thread launched by the gui to send the current buffer data to the
4329 * process. This way avoid to hang up vim totally if the children
4330 * process take a long time to process the lines.
4331 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004332 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004333sub_process_writer(LPVOID param)
4334{
4335 HANDLE g_hChildStd_IN_Wr = param;
4336 linenr_T lnum = curbuf->b_op_start.lnum;
4337 DWORD len = 0;
4338 DWORD l;
4339 char_u *lp = ml_get(lnum);
4340 char_u *s;
4341 int written = 0;
4342
4343 for (;;)
4344 {
4345 l = (DWORD)STRLEN(lp + written);
4346 if (l == 0)
4347 len = 0;
4348 else if (lp[written] == NL)
4349 {
4350 /* NL -> NUL translation */
4351 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4352 }
4353 else
4354 {
4355 s = vim_strchr(lp + written, NL);
4356 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4357 s == NULL ? l : (DWORD)(s - (lp + written)),
4358 &len, NULL);
4359 }
4360 if (len == (int)l)
4361 {
4362 /* Finished a line, add a NL, unless this line should not have
4363 * one. */
4364 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004365 || (!curbuf->b_p_bin
4366 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004367 || (lnum != curbuf->b_no_eol_lnum
4368 && (lnum != curbuf->b_ml.ml_line_count
4369 || curbuf->b_p_eol)))
4370 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004371 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4372 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004373 }
4374
4375 ++lnum;
4376 if (lnum > curbuf->b_op_end.lnum)
4377 break;
4378
4379 lp = ml_get(lnum);
4380 written = 0;
4381 }
4382 else if (len > 0)
4383 written += len;
4384 }
4385
4386 /* finished all the lines, close pipe */
4387 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004388 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004389}
4390
4391
4392# define BUFLEN 100 /* length for buffer, stolen from unix version */
4393
4394/*
4395 * This function read from the children's stdout and write the
4396 * data on screen or in the buffer accordingly.
4397 */
4398 static void
4399dump_pipe(int options,
4400 HANDLE g_hChildStd_OUT_Rd,
4401 garray_T *ga,
4402 char_u buffer[],
4403 DWORD *buffer_off)
4404{
4405 DWORD availableBytes = 0;
4406 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004407 int ret;
4408 DWORD len;
4409 DWORD toRead;
4410 int repeatCount;
4411
4412 /* we query the pipe to see if there is any data to read
4413 * to avoid to perform a blocking read */
4414 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4415 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004416 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004417 NULL, /* number of read bytes */
4418 &availableBytes, /* available bytes total */
4419 NULL); /* byteLeft */
4420
4421 repeatCount = 0;
4422 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004423 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004424 {
4425 repeatCount++;
4426 toRead =
4427# ifdef FEAT_MBYTE
4428 (DWORD)(BUFLEN - *buffer_off);
4429# else
4430 (DWORD)BUFLEN;
4431# endif
4432 toRead = availableBytes < toRead ? availableBytes : toRead;
4433 ReadFile(g_hChildStd_OUT_Rd, buffer
4434# ifdef FEAT_MBYTE
4435 + *buffer_off, toRead
4436# else
4437 , toRead
4438# endif
4439 , &len, NULL);
4440
4441 /* If we haven't read anything, there is a problem */
4442 if (len == 0)
4443 break;
4444
4445 availableBytes -= len;
4446
4447 if (options & SHELL_READ)
4448 {
4449 /* Do NUL -> NL translation, append NL separated
4450 * lines to the current buffer. */
4451 for (i = 0; i < len; ++i)
4452 {
4453 if (buffer[i] == NL)
4454 append_ga_line(ga);
4455 else if (buffer[i] == NUL)
4456 ga_append(ga, NL);
4457 else
4458 ga_append(ga, buffer[i]);
4459 }
4460 }
4461# ifdef FEAT_MBYTE
4462 else if (has_mbyte)
4463 {
4464 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004465 int c;
4466 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004467
4468 len += *buffer_off;
4469 buffer[len] = NUL;
4470
4471 /* Check if the last character in buffer[] is
4472 * incomplete, keep these bytes for the next
4473 * round. */
4474 for (p = buffer; p < buffer + len; p += l)
4475 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004476 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004477 if (l == 0)
4478 l = 1; /* NUL byte? */
4479 else if (MB_BYTE2LEN(*p) != l)
4480 break;
4481 }
4482 if (p == buffer) /* no complete character */
4483 {
4484 /* avoid getting stuck at an illegal byte */
4485 if (len >= 12)
4486 ++p;
4487 else
4488 {
4489 *buffer_off = len;
4490 return;
4491 }
4492 }
4493 c = *p;
4494 *p = NUL;
4495 msg_puts(buffer);
4496 if (p < buffer + len)
4497 {
4498 *p = c;
4499 *buffer_off = (DWORD)((buffer + len) - p);
4500 mch_memmove(buffer, p, *buffer_off);
4501 return;
4502 }
4503 *buffer_off = 0;
4504 }
4505# endif /* FEAT_MBYTE */
4506 else
4507 {
4508 buffer[len] = NUL;
4509 msg_puts(buffer);
4510 }
4511
4512 windgoto(msg_row, msg_col);
4513 cursor_on();
4514 out_flush();
4515 }
4516}
4517
4518/*
4519 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4520 * for communication and doesn't open any new window.
4521 */
4522 static int
4523mch_system_piped(char *cmd, int options)
4524{
4525 STARTUPINFO si;
4526 PROCESS_INFORMATION pi;
4527 DWORD ret = 0;
4528
4529 HANDLE g_hChildStd_IN_Rd = NULL;
4530 HANDLE g_hChildStd_IN_Wr = NULL;
4531 HANDLE g_hChildStd_OUT_Rd = NULL;
4532 HANDLE g_hChildStd_OUT_Wr = NULL;
4533
4534 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4535 DWORD len;
4536
4537 /* buffer used to receive keys */
4538 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4539 int ta_len = 0; /* valid bytes in ta_buf[] */
4540
4541 DWORD i;
4542 int c;
4543 int noread_cnt = 0;
4544 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004545 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004546 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004547 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004548
4549 SECURITY_ATTRIBUTES saAttr;
4550
4551 /* Set the bInheritHandle flag so pipe handles are inherited. */
4552 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4553 saAttr.bInheritHandle = TRUE;
4554 saAttr.lpSecurityDescriptor = NULL;
4555
4556 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4557 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004558 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004559 /* Create a pipe for the child process's STDIN. */
4560 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4561 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004562 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004563 {
4564 CloseHandle(g_hChildStd_IN_Rd);
4565 CloseHandle(g_hChildStd_IN_Wr);
4566 CloseHandle(g_hChildStd_OUT_Rd);
4567 CloseHandle(g_hChildStd_OUT_Wr);
4568 MSG_PUTS(_("\nCannot create pipes\n"));
4569 }
4570
4571 si.cb = sizeof(si);
4572 si.lpReserved = NULL;
4573 si.lpDesktop = NULL;
4574 si.lpTitle = NULL;
4575 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4576
4577 /* set-up our file redirection */
4578 si.hStdError = g_hChildStd_OUT_Wr;
4579 si.hStdOutput = g_hChildStd_OUT_Wr;
4580 si.hStdInput = g_hChildStd_IN_Rd;
4581 si.wShowWindow = SW_HIDE;
4582 si.cbReserved2 = 0;
4583 si.lpReserved2 = NULL;
4584
4585 if (options & SHELL_READ)
4586 ga_init2(&ga, 1, BUFLEN);
4587
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004588 if (cmd != NULL)
4589 {
4590 p = (char *)vim_strsave((char_u *)cmd);
4591 if (p != NULL)
4592 unescape_shellxquote((char_u *)p, p_sxe);
4593 else
4594 p = cmd;
4595 }
4596
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004597 /* Now, run the command.
4598 * About "Inherit handles" being TRUE: this command can be litigious,
4599 * handle inheritance was deactivated for pending temp file, but, if we
4600 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004601 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4602 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004603
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004604 if (p != cmd)
4605 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004606
4607 /* Close our unused side of the pipes */
4608 CloseHandle(g_hChildStd_IN_Rd);
4609 CloseHandle(g_hChildStd_OUT_Wr);
4610
4611 if (options & SHELL_WRITE)
4612 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004613 HANDLE thread = (HANDLE)
4614 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004615 0, /* default stack size */
4616 sub_process_writer, /* function to be executed */
4617 g_hChildStd_IN_Wr, /* parameter */
4618 0, /* creation flag, start immediately */
4619 NULL); /* we don't care about thread id */
4620 CloseHandle(thread);
4621 g_hChildStd_IN_Wr = NULL;
4622 }
4623
4624 /* Keep updating the window while waiting for the shell to finish. */
4625 for (;;)
4626 {
4627 MSG msg;
4628
Bram Moolenaar175d0702013-12-11 18:36:33 +01004629 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004630 {
4631 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004632 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004633 }
4634
4635 /* write pipe information in the window */
4636 if ((options & (SHELL_READ|SHELL_WRITE))
4637# ifdef FEAT_GUI
4638 || gui.in_use
4639# endif
4640 )
4641 {
4642 len = 0;
4643 if (!(options & SHELL_EXPAND)
4644 && ((options &
4645 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4646 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4647# ifdef FEAT_GUI
4648 || gui.in_use
4649# endif
4650 )
4651 && (ta_len > 0 || noread_cnt > 4))
4652 {
4653 if (ta_len == 0)
4654 {
4655 /* Get extra characters when we don't have any. Reset the
4656 * counter and timer. */
4657 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004658 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4659 }
4660 if (ta_len > 0 || len > 0)
4661 {
4662 /*
4663 * For pipes: Check for CTRL-C: send interrupt signal to
4664 * child. Check for CTRL-D: EOF, close pipe to child.
4665 */
4666 if (len == 1 && cmd != NULL)
4667 {
4668 if (ta_buf[ta_len] == Ctrl_C)
4669 {
4670 /* Learn what exit code is expected, for
4671 * now put 9 as SIGKILL */
4672 TerminateProcess(pi.hProcess, 9);
4673 }
4674 if (ta_buf[ta_len] == Ctrl_D)
4675 {
4676 CloseHandle(g_hChildStd_IN_Wr);
4677 g_hChildStd_IN_Wr = NULL;
4678 }
4679 }
4680
4681 /* replace K_BS by <BS> and K_DEL by <DEL> */
4682 for (i = ta_len; i < ta_len + len; ++i)
4683 {
4684 if (ta_buf[i] == CSI && len - i > 2)
4685 {
4686 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4687 if (c == K_DEL || c == K_KDEL || c == K_BS)
4688 {
4689 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4690 (size_t)(len - i - 2));
4691 if (c == K_DEL || c == K_KDEL)
4692 ta_buf[i] = DEL;
4693 else
4694 ta_buf[i] = Ctrl_H;
4695 len -= 2;
4696 }
4697 }
4698 else if (ta_buf[i] == '\r')
4699 ta_buf[i] = '\n';
4700# ifdef FEAT_MBYTE
4701 if (has_mbyte)
4702 i += (*mb_ptr2len_len)(ta_buf + i,
4703 ta_len + len - i) - 1;
4704# endif
4705 }
4706
4707 /*
4708 * For pipes: echo the typed characters. For a pty this
4709 * does not seem to work.
4710 */
4711 for (i = ta_len; i < ta_len + len; ++i)
4712 {
4713 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4714 msg_putchar(ta_buf[i]);
4715# ifdef FEAT_MBYTE
4716 else if (has_mbyte)
4717 {
4718 int l = (*mb_ptr2len)(ta_buf + i);
4719
4720 msg_outtrans_len(ta_buf + i, l);
4721 i += l - 1;
4722 }
4723# endif
4724 else
4725 msg_outtrans_len(ta_buf + i, 1);
4726 }
4727 windgoto(msg_row, msg_col);
4728 out_flush();
4729
4730 ta_len += len;
4731
4732 /*
4733 * Write the characters to the child, unless EOF has been
4734 * typed for pipes. Write one character at a time, to
4735 * avoid losing too much typeahead. When writing buffer
4736 * lines, drop the typed characters (only check for
4737 * CTRL-C).
4738 */
4739 if (options & SHELL_WRITE)
4740 ta_len = 0;
4741 else if (g_hChildStd_IN_Wr != NULL)
4742 {
4743 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4744 1, &len, NULL);
4745 // if we are typing in, we want to keep things reactive
4746 delay = 1;
4747 if (len > 0)
4748 {
4749 ta_len -= len;
4750 mch_memmove(ta_buf, ta_buf + len, ta_len);
4751 }
4752 }
4753 }
4754 }
4755 }
4756
4757 if (ta_len)
4758 ui_inchar_undo(ta_buf, ta_len);
4759
4760 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4761 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004762 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004763 break;
4764 }
4765
4766 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004767 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004768
4769 /* We start waiting for a very short time and then increase it, so
4770 * that we respond quickly when the process is quick, and don't
4771 * consume too much overhead when it's slow. */
4772 if (delay < 50)
4773 delay += 10;
4774 }
4775
4776 /* Close the pipe */
4777 CloseHandle(g_hChildStd_OUT_Rd);
4778 if (g_hChildStd_IN_Wr != NULL)
4779 CloseHandle(g_hChildStd_IN_Wr);
4780
4781 WaitForSingleObject(pi.hProcess, INFINITE);
4782
4783 /* Get the command exit code */
4784 GetExitCodeProcess(pi.hProcess, &ret);
4785
4786 if (options & SHELL_READ)
4787 {
4788 if (ga.ga_len > 0)
4789 {
4790 append_ga_line(&ga);
4791 /* remember that the NL was missing */
4792 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4793 }
4794 else
4795 curbuf->b_no_eol_lnum = 0;
4796 ga_clear(&ga);
4797 }
4798
4799 /* Close the handles to the subprocess, so that it goes away */
4800 CloseHandle(pi.hThread);
4801 CloseHandle(pi.hProcess);
4802
4803 return ret;
4804}
4805
4806 static int
4807mch_system(char *cmd, int options)
4808{
4809 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004810 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004811 return mch_system_piped(cmd, options);
4812 else
4813 return mch_system_classic(cmd, options);
4814}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004815#else
4816
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004817# ifdef FEAT_MBYTE
4818 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004819mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004820{
4821 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4822 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004823 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004824 if (wcmd != NULL)
4825 {
4826 int ret = _wsystem(wcmd);
4827 vim_free(wcmd);
4828 return ret;
4829 }
4830 }
4831 return system(cmd);
4832}
4833# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004834# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004835# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836
4837#endif
4838
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004839#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4840/*
4841 * Use a terminal window to run a shell command in.
4842 */
4843 static int
4844mch_call_shell_terminal(
4845 char_u *cmd,
4846 int options UNUSED) /* SHELL_*, see vim.h */
4847{
4848 jobopt_T opt;
4849 char_u *newcmd = NULL;
4850 typval_T argvar[2];
4851 long_u cmdlen;
4852 int retval = -1;
4853 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004854 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004855 aco_save_T aco;
4856 oparg_T oa; /* operator arguments */
4857
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004858 if (cmd == NULL)
4859 cmdlen = STRLEN(p_sh) + 1;
4860 else
4861 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004862 newcmd = lalloc(cmdlen, TRUE);
4863 if (newcmd == NULL)
4864 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004865 if (cmd == NULL)
4866 {
4867 STRCPY(newcmd, p_sh);
4868 ch_log(NULL, "starting terminal to run a shell");
4869 }
4870 else
4871 {
4872 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4873 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4874 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004875
4876 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004877
4878 argvar[0].v_type = VAR_STRING;
4879 argvar[0].vval.v_string = newcmd;
4880 argvar[1].v_type = VAR_UNKNOWN;
4881 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004882 if (buf == NULL)
4883 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004884
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004885 job = term_getjob(buf->b_term);
4886 ++job->jv_refcount;
4887
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004888 /* Find a window to make "buf" curbuf. */
4889 aucmd_prepbuf(&aco, buf);
4890
4891 clear_oparg(&oa);
4892 while (term_use_loop())
4893 {
4894 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4895 {
4896 /* If terminal_loop() returns OK we got a key that is handled
4897 * in Normal model. We don't do redrawing anyway. */
4898 if (terminal_loop(TRUE) == OK)
4899 normal_cmd(&oa, TRUE);
4900 }
4901 else
4902 normal_cmd(&oa, TRUE);
4903 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004904 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004905 ch_log(NULL, "system command finished");
4906
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004907 job_unref(job);
4908
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004909 /* restore curwin/curbuf and a few other things */
4910 aucmd_restbuf(&aco);
4911
4912 wait_return(TRUE);
4913 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4914
4915 vim_free(newcmd);
4916 return retval;
4917}
4918#endif
4919
Bram Moolenaar071d4272004-06-13 20:20:40 +00004920/*
4921 * Either execute a command by calling the shell or start a new shell
4922 */
4923 int
4924mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004925 char_u *cmd,
4926 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004927{
4928 int x = 0;
4929 int tmode = cur_tmode;
4930#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004931 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004932# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004933 int did_set_title = FALSE;
4934
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004935 /* Change the title to reflect that we are in a subshell. */
4936 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4937 {
4938 WCHAR szShellTitle[512];
4939
4940 if (GetConsoleTitleW(szShellTitle,
4941 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4942 {
4943 if (cmd == NULL)
4944 wcscat(szShellTitle, L" :sh");
4945 else
4946 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004947 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004948
4949 if (wn != NULL)
4950 {
4951 wcscat(szShellTitle, L" - !");
4952 if ((wcslen(szShellTitle) + wcslen(wn) <
4953 sizeof(szShellTitle)/sizeof(WCHAR)))
4954 wcscat(szShellTitle, wn);
4955 SetConsoleTitleW(szShellTitle);
4956 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004957 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004958 }
4959 }
4960 }
4961 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004962 if (!did_set_title)
4963# endif
4964 /* Change the title to reflect that we are in a subshell. */
4965 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004966 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004967 if (cmd == NULL)
4968 strcat(szShellTitle, " :sh");
4969 else
4970 {
4971 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004972 if ((strlen(szShellTitle) + strlen((char *)cmd)
4973 < sizeof(szShellTitle)))
4974 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004975 }
4976 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004978#endif
4979
4980 out_flush();
4981
4982#ifdef MCH_WRITE_DUMP
4983 if (fdDump)
4984 {
4985 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4986 fflush(fdDump);
4987 }
4988#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004989#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4990 /* TODO: make the terminal window work with input or output redirected. */
4991 if (vim_strchr(p_go, GO_TERMINAL) != NULL
4992 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
4993 {
4994 /* Use a terminal window to run the command in. */
4995 x = mch_call_shell_terminal(cmd, options);
4996#ifdef FEAT_TITLE
4997 resettitle();
4998#endif
4999 return x;
5000 }
5001#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005002
5003 /*
5004 * Catch all deadly signals while running the external command, because a
5005 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5006 */
5007 signal(SIGINT, SIG_IGN);
5008#if defined(__GNUC__) && !defined(__MINGW32__)
5009 signal(SIGKILL, SIG_IGN);
5010#else
5011 signal(SIGBREAK, SIG_IGN);
5012#endif
5013 signal(SIGILL, SIG_IGN);
5014 signal(SIGFPE, SIG_IGN);
5015 signal(SIGSEGV, SIG_IGN);
5016 signal(SIGTERM, SIG_IGN);
5017 signal(SIGABRT, SIG_IGN);
5018
5019 if (options & SHELL_COOKED)
5020 settmode(TMODE_COOK); /* set to normal mode */
5021
5022 if (cmd == NULL)
5023 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005024 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 }
5026 else
5027 {
5028 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005029 char_u *newcmd = NULL;
5030 char_u *cmdbase = cmd;
5031 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005032
5033 /* Skip a leading ", ( and "(. */
5034 if (*cmdbase == '"' )
5035 ++cmdbase;
5036 if (*cmdbase == '(')
5037 ++cmdbase;
5038
Bram Moolenaar1c465442017-03-12 20:10:05 +01005039 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005040 {
5041 STARTUPINFO si;
5042 PROCESS_INFORMATION pi;
5043 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005044 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005045 char_u *p;
5046
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005047 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005048 si.cb = sizeof(si);
5049 si.lpReserved = NULL;
5050 si.lpDesktop = NULL;
5051 si.lpTitle = NULL;
5052 si.dwFlags = 0;
5053 si.cbReserved2 = 0;
5054 si.lpReserved2 = NULL;
5055
5056 cmdbase = skipwhite(cmdbase + 5);
5057 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005058 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005059 {
5060 cmdbase = skipwhite(cmdbase + 4);
5061 si.dwFlags = STARTF_USESHOWWINDOW;
5062 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005063 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005064 }
5065 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005066 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005067 {
5068 cmdbase = skipwhite(cmdbase + 2);
5069 flags = CREATE_NO_WINDOW;
5070 si.dwFlags = STARTF_USESTDHANDLES;
5071 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005072 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005073 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005074 NULL, // Security att.
5075 OPEN_EXISTING, // Open flags
5076 FILE_ATTRIBUTE_NORMAL, // File att.
5077 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005078 si.hStdOutput = si.hStdInput;
5079 si.hStdError = si.hStdInput;
5080 }
5081
5082 /* Remove a trailing ", ) and )" if they have a match
5083 * at the start of the command. */
5084 if (cmdbase > cmd)
5085 {
5086 p = cmdbase + STRLEN(cmdbase);
5087 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5088 *--p = NUL;
5089 if (p > cmdbase && p[-1] == ')'
5090 && (*cmd =='(' || cmd[1] == '('))
5091 *--p = NUL;
5092 }
5093
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005094 newcmd = cmdbase;
5095 unescape_shellxquote(cmdbase, p_sxe);
5096
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005097 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005098 * If creating new console, arguments are passed to the
5099 * 'cmd.exe' as-is. If it's not, arguments are not treated
5100 * correctly for current 'cmd.exe'. So unescape characters in
5101 * shellxescape except '|' for avoiding to be treated as
5102 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005103 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005104 if (flags != CREATE_NEW_CONSOLE)
5105 {
5106 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005107 char_u *cmd_shell = mch_getenv("COMSPEC");
5108
5109 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005110 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005111
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005112 subcmd = vim_strsave_escaped_ext(cmdbase,
5113 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005114 if (subcmd != NULL)
5115 {
5116 /* make "cmd.exe /c arguments" */
5117 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005118 newcmd = lalloc(cmdlen, TRUE);
5119 if (newcmd != NULL)
5120 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005121 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005122 else
5123 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005124 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005125 }
5126 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005127
5128 /*
5129 * Now, start the command as a process, so that it doesn't
5130 * inherit our handles which causes unpleasant dangling swap
5131 * files if we exit before the spawned process
5132 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005133 if (vim_create_process((char *)newcmd, FALSE, flags,
5134 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005135 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005136 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5137 > (HINSTANCE)32)
5138 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005139 else
5140 {
5141 x = -1;
5142#ifdef FEAT_GUI_W32
5143 EMSG(_("E371: Command not found"));
5144#endif
5145 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005146
5147 if (newcmd != cmdbase)
5148 vim_free(newcmd);
5149
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005150 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005151 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005152 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005153 CloseHandle(si.hStdInput);
5154 }
5155 /* Close the handles to the subprocess, so that it goes away */
5156 CloseHandle(pi.hThread);
5157 CloseHandle(pi.hProcess);
5158 }
5159 else
5160 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005161 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005162#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005163 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005164#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005165 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5166
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005167 newcmd = lalloc(cmdlen, TRUE);
5168 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005169 {
5170#if defined(FEAT_GUI_W32)
5171 if (need_vimrun_warning)
5172 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005173 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5174 "External commands will not pause after completion.\n"
5175 "See :help win32-vimrun for more information.");
5176 char *title = _("Vim Warning");
5177# ifdef FEAT_MBYTE
5178 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5179 {
5180 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5181 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5182
5183 if (wmsg != NULL && wtitle != NULL)
5184 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5185 vim_free(wmsg);
5186 vim_free(wtitle);
5187 }
5188 else
5189# endif
5190 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191 need_vimrun_warning = FALSE;
5192 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005193 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194 /* Use vimrun to execute the command. It opens a console
5195 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005196 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197 vimrun_path,
5198 (msg_silent != 0 || (options & SHELL_DOOUT))
5199 ? "-s " : "",
5200 p_sh, p_shcf, cmd);
5201 else
5202#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005203 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005204 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005205 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005206 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005207 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208 }
5209 }
5210
5211 if (tmode == TMODE_RAW)
5212 settmode(TMODE_RAW); /* set to raw mode */
5213
5214 /* Print the return value, unless "vimrun" was used. */
5215 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5216#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005217 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218#endif
5219 )
5220 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005221 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222 msg_putchar('\n');
5223 }
5224#ifdef FEAT_TITLE
5225 resettitle();
5226#endif
5227
5228 signal(SIGINT, SIG_DFL);
5229#if defined(__GNUC__) && !defined(__MINGW32__)
5230 signal(SIGKILL, SIG_DFL);
5231#else
5232 signal(SIGBREAK, SIG_DFL);
5233#endif
5234 signal(SIGILL, SIG_DFL);
5235 signal(SIGFPE, SIG_DFL);
5236 signal(SIGSEGV, SIG_DFL);
5237 signal(SIGTERM, SIG_DFL);
5238 signal(SIGABRT, SIG_DFL);
5239
5240 return x;
5241}
5242
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005243#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005244 static HANDLE
5245job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005246 char_u *fname,
5247 DWORD dwDesiredAccess,
5248 DWORD dwShareMode,
5249 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5250 DWORD dwCreationDisposition,
5251 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005252{
5253 HANDLE h;
5254# ifdef FEAT_MBYTE
5255 WCHAR *wn = NULL;
5256 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5257 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005258 wn = enc_to_utf16(fname, NULL);
5259 if (wn != NULL)
5260 {
5261 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5262 lpSecurityAttributes, dwCreationDisposition,
5263 dwFlagsAndAttributes, NULL);
5264 vim_free(wn);
5265 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005266 }
5267 if (wn == NULL)
5268# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005269 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5270 lpSecurityAttributes, dwCreationDisposition,
5271 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005272 return h;
5273}
5274
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005275/*
5276 * Turn the dictionary "env" into a NUL separated list that can be used as the
5277 * environment argument of vim_create_process().
5278 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005279 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005280win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005281{
5282 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005283 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005284 LPVOID base = GetEnvironmentStringsW();
5285
5286 /* for last \0 */
5287 if (ga_grow(gap, 1) == FAIL)
5288 return;
5289
5290 if (base)
5291 {
5292 WCHAR *p = (WCHAR*) base;
5293
5294 /* for last \0 */
5295 if (ga_grow(gap, 1) == FAIL)
5296 return;
5297
5298 while (*p != 0 || *(p + 1) != 0)
5299 {
5300 if (ga_grow(gap, 1) == OK)
5301 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5302 p++;
5303 }
5304 FreeEnvironmentStrings(base);
5305 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5306 }
5307
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005308 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005309 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005310 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005311 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005312 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005313 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005314 typval_T *item = &dict_lookup(hi)->di_tv;
5315 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5316 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5317 --todo;
5318 if (wkey != NULL && wval != NULL)
5319 {
5320 size_t n;
5321 size_t lkey = wcslen(wkey);
5322 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005323
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005324 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5325 continue;
5326 for (n = 0; n < lkey; n++)
5327 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5328 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5329 for (n = 0; n < lval; n++)
5330 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5331 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5332 }
5333 if (wkey != NULL) vim_free(wkey);
5334 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005335 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005336 }
5337 }
5338
Bram Moolenaar493359e2018-06-12 20:25:52 +02005339# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005340 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005341# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005342 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005343 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005344# endif
5345# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005346 char_u *version = get_vim_var_str(VV_VERSION);
5347 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005348# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005349 // size of "VIM_SERVERNAME=" and value,
5350 // plus "VIM_TERMINAL=" and value,
5351 // plus two terminating NULs
5352 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005353# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005354 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005355# endif
5356# ifdef FEAT_TERMINAL
5357 + 13 + version_len + 2
5358# endif
5359 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005360
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005361 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005362 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005363# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005364 for (n = 0; n < 15; n++)
5365 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5366 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005367 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005368 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5369 (WCHAR)servername[n];
5370 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005371# endif
5372# ifdef FEAT_TERMINAL
5373 if (is_terminal)
5374 {
5375 for (n = 0; n < 13; n++)
5376 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5377 (WCHAR)"VIM_TERMINAL="[n];
5378 for (n = 0; n < version_len; n++)
5379 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5380 (WCHAR)version[n];
5381 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5382 }
5383# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005384 }
5385 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005386# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005387}
5388
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005389 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005390mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005391{
5392 STARTUPINFO si;
5393 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005394 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005395 SECURITY_ATTRIBUTES saAttr;
5396 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005397 HANDLE ifd[2];
5398 HANDLE ofd[2];
5399 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005400 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005401
5402 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5403 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5404 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5405 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5406 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5407 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5408 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5409
5410 if (use_out_for_err && use_null_for_out)
5411 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005412
5413 ifd[0] = INVALID_HANDLE_VALUE;
5414 ifd[1] = INVALID_HANDLE_VALUE;
5415 ofd[0] = INVALID_HANDLE_VALUE;
5416 ofd[1] = INVALID_HANDLE_VALUE;
5417 efd[0] = INVALID_HANDLE_VALUE;
5418 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005419 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005420
Bram Moolenaar14207f42016-10-27 21:13:10 +02005421 jo = CreateJobObject(NULL, NULL);
5422 if (jo == NULL)
5423 {
5424 job->jv_status = JOB_FAILED;
5425 goto failed;
5426 }
5427
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005428 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005429 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005430
Bram Moolenaar76467df2016-02-12 19:30:26 +01005431 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005432 ZeroMemory(&si, sizeof(si));
5433 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005434 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005435 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005436
Bram Moolenaard8070362016-02-15 21:56:54 +01005437 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5438 saAttr.bInheritHandle = TRUE;
5439 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005440
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005441 if (use_file_for_in)
5442 {
5443 char_u *fname = options->jo_io_name[PART_IN];
5444
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005445 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5446 FILE_SHARE_READ | FILE_SHARE_WRITE,
5447 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5448 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005449 {
5450 EMSG2(_(e_notopen), fname);
5451 goto failed;
5452 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005453 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005454 else if (!use_null_for_in &&
5455 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005456 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005457 goto failed;
5458
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005459 if (use_file_for_out)
5460 {
5461 char_u *fname = options->jo_io_name[PART_OUT];
5462
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005463 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5464 FILE_SHARE_READ | FILE_SHARE_WRITE,
5465 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5466 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005467 {
5468 EMSG2(_(e_notopen), fname);
5469 goto failed;
5470 }
5471 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005472 else if (!use_null_for_out &&
5473 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005474 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005475 goto failed;
5476
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005477 if (use_file_for_err)
5478 {
5479 char_u *fname = options->jo_io_name[PART_ERR];
5480
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005481 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5482 FILE_SHARE_READ | FILE_SHARE_WRITE,
5483 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5484 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005485 {
5486 EMSG2(_(e_notopen), fname);
5487 goto failed;
5488 }
5489 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005490 else if (!use_out_for_err && !use_null_for_err &&
5491 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005492 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005493 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005494
Bram Moolenaard8070362016-02-15 21:56:54 +01005495 si.dwFlags |= STARTF_USESTDHANDLES;
5496 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005497 si.hStdOutput = ofd[1];
5498 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5499
5500 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5501 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005502 if (options->jo_set & JO_CHANNEL)
5503 {
5504 channel = options->jo_channel;
5505 if (channel != NULL)
5506 ++channel->ch_refcount;
5507 }
5508 else
5509 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005510 if (channel == NULL)
5511 goto failed;
5512 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005513
5514 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005515 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005516 CREATE_DEFAULT_ERROR_MODE |
5517 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005518 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005519 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005520 &si, &pi,
5521 ga.ga_data,
5522 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005523 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005524 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005525 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005526 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005527 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005528
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005529 ga_clear(&ga);
5530
Bram Moolenaar14207f42016-10-27 21:13:10 +02005531 if (!AssignProcessToJobObject(jo, pi.hProcess))
5532 {
5533 /* if failing, switch the way to terminate
5534 * process with TerminateProcess. */
5535 CloseHandle(jo);
5536 jo = NULL;
5537 }
5538 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005539 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005540 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005541 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005542 job->jv_status = JOB_STARTED;
5543
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005544 CloseHandle(ifd[0]);
5545 CloseHandle(ofd[1]);
5546 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005547 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005548
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005549 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005550 if (channel != NULL)
5551 {
5552 channel_set_pipes(channel,
5553 use_file_for_in || use_null_for_in
5554 ? INVALID_FD : (sock_T)ifd[1],
5555 use_file_for_out || use_null_for_out
5556 ? INVALID_FD : (sock_T)ofd[0],
5557 use_out_for_err || use_file_for_err || use_null_for_err
5558 ? INVALID_FD : (sock_T)efd[0]);
5559 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005560 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005561 return;
5562
5563failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005564 CloseHandle(ifd[0]);
5565 CloseHandle(ofd[0]);
5566 CloseHandle(efd[0]);
5567 CloseHandle(ifd[1]);
5568 CloseHandle(ofd[1]);
5569 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005570 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005571 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005572}
5573
5574 char *
5575mch_job_status(job_T *job)
5576{
5577 DWORD dwExitCode = 0;
5578
Bram Moolenaar76467df2016-02-12 19:30:26 +01005579 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5580 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005581 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005582 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005583 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005584 {
5585 ch_log(job->jv_channel, "Job ended");
5586 job->jv_status = JOB_ENDED;
5587 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005588 return "dead";
5589 }
5590 return "run";
5591}
5592
Bram Moolenaar97792de2016-10-15 18:36:49 +02005593 job_T *
5594mch_detect_ended_job(job_T *job_list)
5595{
5596 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5597 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5598 job_T *job = job_list;
5599
5600 while (job != NULL)
5601 {
5602 DWORD n;
5603 DWORD result;
5604
5605 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5606 && job != NULL; job = job->jv_next)
5607 {
5608 if (job->jv_status == JOB_STARTED)
5609 {
5610 jobHandles[n] = job->jv_proc_info.hProcess;
5611 jobArray[n] = job;
5612 ++n;
5613 }
5614 }
5615 if (n == 0)
5616 continue;
5617 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5618 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5619 {
5620 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5621
5622 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5623 return wait_job;
5624 }
5625 }
5626 return NULL;
5627}
5628
Bram Moolenaarfb630902016-10-29 14:55:00 +02005629 static BOOL
5630terminate_all(HANDLE process, int code)
5631{
5632 PROCESSENTRY32 pe;
5633 HANDLE h = INVALID_HANDLE_VALUE;
5634 DWORD pid = GetProcessId(process);
5635
5636 if (pid != 0)
5637 {
5638 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5639 if (h != INVALID_HANDLE_VALUE)
5640 {
5641 pe.dwSize = sizeof(PROCESSENTRY32);
5642 if (!Process32First(h, &pe))
5643 goto theend;
5644
5645 do
5646 {
5647 if (pe.th32ParentProcessID == pid)
5648 {
5649 HANDLE ph = OpenProcess(
5650 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5651 if (ph != NULL)
5652 {
5653 terminate_all(ph, code);
5654 CloseHandle(ph);
5655 }
5656 }
5657 } while (Process32Next(h, &pe));
5658
5659 CloseHandle(h);
5660 }
5661 }
5662
5663theend:
5664 return TerminateProcess(process, code);
5665}
5666
5667/*
5668 * Send a (deadly) signal to "job".
5669 * Return FAIL if it didn't work.
5670 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005671 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005672mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005673{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005674 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005675
Bram Moolenaar923d9262016-02-25 20:56:01 +01005676 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005677 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005678 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005679 if (job->jv_job_object != NULL)
5680 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005681 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005682 }
5683
5684 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5685 return FAIL;
5686 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005687 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5688 job->jv_proc_info.dwProcessId)
5689 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005690 FreeConsole();
5691 return ret;
5692}
5693
5694/*
5695 * Clear the data related to "job".
5696 */
5697 void
5698mch_clear_job(job_T *job)
5699{
5700 if (job->jv_status != JOB_FAILED)
5701 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005702 if (job->jv_job_object != NULL)
5703 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005704 CloseHandle(job->jv_proc_info.hProcess);
5705 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005706}
5707#endif
5708
Bram Moolenaar071d4272004-06-13 20:20:40 +00005709
5710#ifndef FEAT_GUI_W32
5711
5712/*
5713 * Start termcap mode
5714 */
5715 static void
5716termcap_mode_start(void)
5717{
5718 DWORD cmodein;
5719
5720 if (g_fTermcapMode)
5721 return;
5722
5723 SaveConsoleBuffer(&g_cbNonTermcap);
5724
5725 if (g_cbTermcap.IsValid)
5726 {
5727 /*
5728 * We've been in termcap mode before. Restore certain screen
5729 * characteristics, including the buffer size and the window
5730 * size. Since we will be redrawing the screen, we don't need
5731 * to restore the actual contents of the buffer.
5732 */
5733 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005734 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005735 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5736 Rows = g_cbTermcap.Info.dwSize.Y;
5737 Columns = g_cbTermcap.Info.dwSize.X;
5738 }
5739 else
5740 {
5741 /*
5742 * This is our first time entering termcap mode. Clear the console
5743 * screen buffer, and resize the buffer to match the current window
5744 * size. We will use this as the size of our editing environment.
5745 */
5746 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005747 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005748 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5749 }
5750
5751#ifdef FEAT_TITLE
5752 resettitle();
5753#endif
5754
5755 GetConsoleMode(g_hConIn, &cmodein);
5756#ifdef FEAT_MOUSE
5757 if (g_fMouseActive)
5758 cmodein |= ENABLE_MOUSE_INPUT;
5759 else
5760 cmodein &= ~ENABLE_MOUSE_INPUT;
5761#endif
5762 cmodein |= ENABLE_WINDOW_INPUT;
5763 SetConsoleMode(g_hConIn, cmodein);
5764
5765 redraw_later_clear();
5766 g_fTermcapMode = TRUE;
5767}
5768
5769
5770/*
5771 * End termcap mode
5772 */
5773 static void
5774termcap_mode_end(void)
5775{
5776 DWORD cmodein;
5777 ConsoleBuffer *cb;
5778 COORD coord;
5779 DWORD dwDummy;
5780
5781 if (!g_fTermcapMode)
5782 return;
5783
5784 SaveConsoleBuffer(&g_cbTermcap);
5785
5786 GetConsoleMode(g_hConIn, &cmodein);
5787 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5788 SetConsoleMode(g_hConIn, cmodein);
5789
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005790#ifdef FEAT_RESTORE_ORIG_SCREEN
5791 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5792#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005794#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005796 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 SetConsoleCursorInfo(g_hConOut, &g_cci);
5798
5799 if (p_rs || exiting)
5800 {
5801 /*
5802 * Clear anything that happens to be on the current line.
5803 */
5804 coord.X = 0;
5805 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5806 FillConsoleOutputCharacter(g_hConOut, ' ',
5807 cb->Info.dwSize.X, coord, &dwDummy);
5808 /*
5809 * The following is just for aesthetics. If we are exiting without
5810 * restoring the screen, then we want to have a prompt string
5811 * appear at the bottom line. However, the command interpreter
5812 * seems to always advance the cursor one line before displaying
5813 * the prompt string, which causes the screen to scroll. To
5814 * counter this, move the cursor up one line before exiting.
5815 */
5816 if (exiting && !p_rs)
5817 coord.Y--;
5818 /*
5819 * Position the cursor at the leftmost column of the desired row.
5820 */
5821 SetConsoleCursorPosition(g_hConOut, coord);
5822 }
5823
5824 g_fTermcapMode = FALSE;
5825}
5826#endif /* FEAT_GUI_W32 */
5827
5828
5829#ifdef FEAT_GUI_W32
5830 void
5831mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005832 char_u *s UNUSED,
5833 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005834{
5835 /* never used */
5836}
5837
5838#else
5839
5840/*
5841 * clear `n' chars, starting from `coord'
5842 */
5843 static void
5844clear_chars(
5845 COORD coord,
5846 DWORD n)
5847{
5848 DWORD dwDummy;
5849
5850 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005851
5852 if (!USE_VTP)
5853 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5854 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005855 {
5856 set_console_color_rgb();
5857 gotoxy(coord.X + 1, coord.Y + 1);
5858 vtp_printf("\033[%dX", n);
5859 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005860}
5861
5862
5863/*
5864 * Clear the screen
5865 */
5866 static void
5867clear_screen(void)
5868{
5869 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005870
5871 if (!USE_VTP)
5872 clear_chars(g_coord, Rows * Columns);
5873 else
5874 {
5875 set_console_color_rgb();
5876 gotoxy(1, 1);
5877 vtp_printf("\033[2J");
5878 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005879}
5880
5881
5882/*
5883 * Clear to end of display
5884 */
5885 static void
5886clear_to_end_of_display(void)
5887{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005888 COORD save = g_coord;
5889
5890 if (!USE_VTP)
5891 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005892 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005893 else
5894 {
5895 set_console_color_rgb();
5896 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5897 vtp_printf("\033[0J");
5898
5899 gotoxy(save.X + 1, save.Y + 1);
5900 g_coord = save;
5901 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902}
5903
5904
5905/*
5906 * Clear to end of line
5907 */
5908 static void
5909clear_to_end_of_line(void)
5910{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005911 COORD save = g_coord;
5912
5913 if (!USE_VTP)
5914 clear_chars(g_coord, Columns - g_coord.X);
5915 else
5916 {
5917 set_console_color_rgb();
5918 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5919 vtp_printf("\033[0K");
5920
5921 gotoxy(save.X + 1, save.Y + 1);
5922 g_coord = save;
5923 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005924}
5925
5926
5927/*
5928 * Scroll the scroll region up by `cLines' lines
5929 */
5930 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005931scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005932{
5933 COORD oldcoord = g_coord;
5934
5935 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5936 delete_lines(cLines);
5937
5938 g_coord = oldcoord;
5939}
5940
5941
5942/*
5943 * Set the scroll region
5944 */
5945 static void
5946set_scroll_region(
5947 unsigned left,
5948 unsigned top,
5949 unsigned right,
5950 unsigned bottom)
5951{
5952 if (left >= right
5953 || top >= bottom
5954 || right > (unsigned) Columns - 1
5955 || bottom > (unsigned) Rows - 1)
5956 return;
5957
5958 g_srScrollRegion.Left = left;
5959 g_srScrollRegion.Top = top;
5960 g_srScrollRegion.Right = right;
5961 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005962
5963 if (USE_VTP)
5964 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965}
5966
5967
5968/*
5969 * Insert `cLines' lines at the current cursor position
5970 */
5971 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005972insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005973{
5974 SMALL_RECT source;
5975 COORD dest;
5976 CHAR_INFO fill;
5977
5978 dest.X = 0;
5979 dest.Y = g_coord.Y + cLines;
5980
5981 source.Left = 0;
5982 source.Top = g_coord.Y;
5983 source.Right = g_srScrollRegion.Right;
5984 source.Bottom = g_srScrollRegion.Bottom - cLines;
5985
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005986 if (!USE_VTP)
5987 {
5988 fill.Char.AsciiChar = ' ';
5989 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005990
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005991 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5992 }
5993 else
5994 {
5995 set_console_color_rgb();
5996
5997 gotoxy(1, source.Top + 1);
5998 vtp_printf("\033[%dT", cLines);
5999 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006000
6001 /* Here we have to deal with a win32 console flake: If the scroll
6002 * region looks like abc and we scroll c to a and fill with d we get
6003 * cbd... if we scroll block c one line at a time to a, we get cdd...
6004 * vim expects cdd consistently... So we have to deal with that
6005 * here... (this also occurs scrolling the same way in the other
6006 * direction). */
6007
6008 if (source.Bottom < dest.Y)
6009 {
6010 COORD coord;
6011
6012 coord.X = 0;
6013 coord.Y = source.Bottom;
6014 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6015 }
6016}
6017
6018
6019/*
6020 * Delete `cLines' lines at the current cursor position
6021 */
6022 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006023delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006024{
6025 SMALL_RECT source;
6026 COORD dest;
6027 CHAR_INFO fill;
6028 int nb;
6029
6030 dest.X = 0;
6031 dest.Y = g_coord.Y;
6032
6033 source.Left = 0;
6034 source.Top = g_coord.Y + cLines;
6035 source.Right = g_srScrollRegion.Right;
6036 source.Bottom = g_srScrollRegion.Bottom;
6037
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006038 if (!USE_VTP)
6039 {
6040 fill.Char.AsciiChar = ' ';
6041 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006042
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006043 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6044 }
6045 else
6046 {
6047 set_console_color_rgb();
6048
6049 gotoxy(1, source.Top + 1);
6050 vtp_printf("\033[%dS", cLines);
6051 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006052
6053 /* Here we have to deal with a win32 console flake: If the scroll
6054 * region looks like abc and we scroll c to a and fill with d we get
6055 * cbd... if we scroll block c one line at a time to a, we get cdd...
6056 * vim expects cdd consistently... So we have to deal with that
6057 * here... (this also occurs scrolling the same way in the other
6058 * direction). */
6059
6060 nb = dest.Y + (source.Bottom - source.Top) + 1;
6061
6062 if (nb < source.Top)
6063 {
6064 COORD coord;
6065
6066 coord.X = 0;
6067 coord.Y = nb;
6068 clear_chars(coord, Columns * (source.Top - nb));
6069 }
6070}
6071
6072
6073/*
6074 * Set the cursor position
6075 */
6076 static void
6077gotoxy(
6078 unsigned x,
6079 unsigned y)
6080{
6081 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6082 return;
6083
6084 /* external cursor coords are 1-based; internal are 0-based */
6085 g_coord.X = x - 1;
6086 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006087
6088 if (!USE_VTP)
6089 SetConsoleCursorPosition(g_hConOut, g_coord);
6090 else
6091 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006092}
6093
6094
6095/*
6096 * Set the current text attribute = (foreground | background)
6097 * See ../doc/os_win32.txt for the numbers.
6098 */
6099 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006100textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006101{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006102 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006103
6104 SetConsoleTextAttribute(g_hConOut, wAttr);
6105}
6106
6107
6108 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006109textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006110{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006111 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006113 if (!USE_VTP)
6114 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6115 else
6116 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117}
6118
6119
6120 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006121textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006123 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006125 if (!USE_VTP)
6126 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6127 else
6128 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129}
6130
6131
6132/*
6133 * restore the default text attribute (whatever we started with)
6134 */
6135 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006136normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006138 if (!USE_VTP)
6139 textattr(g_attrDefault);
6140 else
6141 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142}
6143
6144
6145static WORD g_attrPreStandout = 0;
6146
6147/*
6148 * Make the text standout, by brightening it
6149 */
6150 static void
6151standout(void)
6152{
6153 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006154
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6156}
6157
6158
6159/*
6160 * Turn off standout mode
6161 */
6162 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006163standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006164{
6165 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006166 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006167
6168 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169}
6170
6171
6172/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006173 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 */
6175 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006176mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006177{
6178 char_u *p;
6179 int n;
6180
6181 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6182 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006183 if (
6184#ifdef FEAT_TERMGUICOLORS
6185 !p_tgc &&
6186#endif
6187 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006188 {
6189 p = T_ME + 2;
6190 n = getdigits(&p);
6191 if (*p == 'm' && n > 0)
6192 {
6193 cterm_normal_fg_color = (n & 0xf) + 1;
6194 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6195 }
6196 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006197#ifdef FEAT_TERMGUICOLORS
6198 cterm_normal_fg_gui_color = INVALCOLOR;
6199 cterm_normal_bg_gui_color = INVALCOLOR;
6200#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006201}
6202
6203
6204/*
6205 * visual bell: flash the screen
6206 */
6207 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006208visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006209{
6210 COORD coordOrigin = {0, 0};
6211 WORD attrFlash = ~g_attrCurrent & 0xff;
6212
6213 DWORD dwDummy;
6214 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6215
6216 if (oldattrs == NULL)
6217 return;
6218 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6219 coordOrigin, &dwDummy);
6220 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6221 coordOrigin, &dwDummy);
6222
6223 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006224 if (!USE_VTP)
6225 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226 coordOrigin, &dwDummy);
6227 vim_free(oldattrs);
6228}
6229
6230
6231/*
6232 * Make the cursor visible or invisible
6233 */
6234 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006235cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236{
6237 s_cursor_visible = fVisible;
6238#ifdef MCH_CURSOR_SHAPE
6239 mch_update_cursor();
6240#endif
6241}
6242
6243
6244/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006245 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006246 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006248 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006250 char_u *pchBuf,
6251 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252{
6253 COORD coord = g_coord;
6254 DWORD written;
6255
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006256#ifdef FEAT_MBYTE
6257 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6258 {
6259 static WCHAR *unicodebuf = NULL;
6260 static int unibuflen = 0;
6261 int length;
6262 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006264 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6265 if (unicodebuf == NULL || length > unibuflen)
6266 {
6267 vim_free(unicodebuf);
6268 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6269 unibuflen = length;
6270 }
6271 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6272 unicodebuf, unibuflen);
6273
6274 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006275
6276 if (!USE_VTP)
6277 {
6278 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6279 coord, &written);
6280 /* When writing fails or didn't write a single character, pretend one
6281 * character was written, otherwise we get stuck. */
6282 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6283 coord, &cchwritten) == 0
6284 || cchwritten == 0)
6285 cchwritten = 1;
6286 }
6287 else
6288 {
6289 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6290 NULL) == 0 || cchwritten == 0)
6291 cchwritten = 1;
6292 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006293
6294 if (cchwritten == length)
6295 {
6296 written = cbToWrite;
6297 g_coord.X += (SHORT)cells;
6298 }
6299 else
6300 {
6301 char_u *p = pchBuf;
6302 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006303 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006304 written = p - pchBuf;
6305 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6306 }
6307 }
6308 else
6309#endif
6310 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006311 if (!USE_VTP)
6312 {
6313 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6314 coord, &written);
6315 /* When writing fails or didn't write a single character, pretend one
6316 * character was written, otherwise we get stuck. */
6317 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6318 coord, &written) == 0
6319 || written == 0)
6320 written = 1;
6321 }
6322 else
6323 {
6324 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6325 NULL) == 0 || written == 0)
6326 written = 1;
6327 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006328
6329 g_coord.X += (SHORT) written;
6330 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331
6332 while (g_coord.X > g_srScrollRegion.Right)
6333 {
6334 g_coord.X -= (SHORT) Columns;
6335 if (g_coord.Y < g_srScrollRegion.Bottom)
6336 g_coord.Y++;
6337 }
6338
6339 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6340
6341 return written;
6342}
6343
6344
6345/*
6346 * mch_write(): write the output buffer to the screen, translating ESC
6347 * sequences into calls to console output routines.
6348 */
6349 void
6350mch_write(
6351 char_u *s,
6352 int len)
6353{
6354 s[len] = NUL;
6355
6356 if (!term_console)
6357 {
6358 write(1, s, (unsigned)len);
6359 return;
6360 }
6361
6362 /* translate ESC | sequences into faked bios calls */
6363 while (len--)
6364 {
6365 /* optimization: use one single write_chars for runs of text,
6366 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006367 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006368
6369 if (p_wd)
6370 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006371 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372 if (prefix != 0)
6373 prefix = 1;
6374 }
6375
6376 if (prefix != 0)
6377 {
6378 DWORD nWritten;
6379
6380 nWritten = write_chars(s, prefix);
6381#ifdef MCH_WRITE_DUMP
6382 if (fdDump)
6383 {
6384 fputc('>', fdDump);
6385 fwrite(s, sizeof(char_u), nWritten, fdDump);
6386 fputs("<\n", fdDump);
6387 }
6388#endif
6389 len -= (nWritten - 1);
6390 s += nWritten;
6391 }
6392 else if (s[0] == '\n')
6393 {
6394 /* \n, newline: go to the beginning of the next line or scroll */
6395 if (g_coord.Y == g_srScrollRegion.Bottom)
6396 {
6397 scroll(1);
6398 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6399 }
6400 else
6401 {
6402 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6403 }
6404#ifdef MCH_WRITE_DUMP
6405 if (fdDump)
6406 fputs("\\n\n", fdDump);
6407#endif
6408 s++;
6409 }
6410 else if (s[0] == '\r')
6411 {
6412 /* \r, carriage return: go to beginning of line */
6413 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6414#ifdef MCH_WRITE_DUMP
6415 if (fdDump)
6416 fputs("\\r\n", fdDump);
6417#endif
6418 s++;
6419 }
6420 else if (s[0] == '\b')
6421 {
6422 /* \b, backspace: move cursor one position left */
6423 if (g_coord.X > g_srScrollRegion.Left)
6424 g_coord.X--;
6425 else if (g_coord.Y > g_srScrollRegion.Top)
6426 {
6427 g_coord.X = g_srScrollRegion.Right;
6428 g_coord.Y--;
6429 }
6430 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6431#ifdef MCH_WRITE_DUMP
6432 if (fdDump)
6433 fputs("\\b\n", fdDump);
6434#endif
6435 s++;
6436 }
6437 else if (s[0] == '\a')
6438 {
6439 /* \a, bell */
6440 MessageBeep(0xFFFFFFFF);
6441#ifdef MCH_WRITE_DUMP
6442 if (fdDump)
6443 fputs("\\a\n", fdDump);
6444#endif
6445 s++;
6446 }
6447 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6448 {
6449#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006450 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006451#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006452 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006453 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006454
6455 switch (s[2])
6456 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006457 case '0': case '1': case '2': case '3': case '4':
6458 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006459 p = s + 1;
6460 do
6461 {
6462 ++p;
6463 args[argc] = getdigits(&p);
6464 argc += (argc < 15) ? 1 : 0;
6465 if (p > s + len)
6466 break;
6467 } while (*p == ';');
6468
Bram Moolenaar071d4272004-06-13 20:20:40 +00006469 if (p > s + len)
6470 break;
6471
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006472 arg1 = args[0];
6473 arg2 = args[1];
6474 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006476 if (argc == 1 && args[0] == 0)
6477 normvideo();
6478 else if (argc == 1)
6479 {
6480 if (USE_VTP)
6481 textcolor((WORD) arg1);
6482 else
6483 textattr((WORD) arg1);
6484 }
6485 else if (USE_VTP)
6486 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006488 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006490 gotoxy(arg2, arg1);
6491 }
6492 else if (argc == 2 && *p == 'r')
6493 {
6494 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6495 }
6496 else if (argc == 1 && *p == 'A')
6497 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 gotoxy(g_coord.X + 1,
6499 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6500 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006501 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006502 {
6503 textbackground((WORD) arg1);
6504 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006505 else if (argc == 1 && *p == 'C')
6506 {
6507 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6508 g_coord.Y + 1);
6509 }
6510 else if (argc == 1 && *p == 'f')
6511 {
6512 textcolor((WORD) arg1);
6513 }
6514 else if (argc == 1 && *p == 'H')
6515 {
6516 gotoxy(1, arg1);
6517 }
6518 else if (argc == 1 && *p == 'L')
6519 {
6520 insert_lines(arg1);
6521 }
6522 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006523 {
6524 delete_lines(arg1);
6525 }
6526
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006527 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528 s = p + 1;
6529 break;
6530
Bram Moolenaar071d4272004-06-13 20:20:40 +00006531 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006532 gotoxy(g_coord.X + 1,
6533 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6534 goto got3;
6535
6536 case 'B':
6537 visual_bell();
6538 goto got3;
6539
6540 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6542 g_coord.Y + 1);
6543 goto got3;
6544
6545 case 'E':
6546 termcap_mode_end();
6547 goto got3;
6548
6549 case 'F':
6550 standout();
6551 goto got3;
6552
6553 case 'f':
6554 standend();
6555 goto got3;
6556
6557 case 'H':
6558 gotoxy(1, 1);
6559 goto got3;
6560
6561 case 'j':
6562 clear_to_end_of_display();
6563 goto got3;
6564
6565 case 'J':
6566 clear_screen();
6567 goto got3;
6568
6569 case 'K':
6570 clear_to_end_of_line();
6571 goto got3;
6572
6573 case 'L':
6574 insert_lines(1);
6575 goto got3;
6576
6577 case 'M':
6578 delete_lines(1);
6579 goto got3;
6580
6581 case 'S':
6582 termcap_mode_start();
6583 goto got3;
6584
6585 case 'V':
6586 cursor_visible(TRUE);
6587 goto got3;
6588
6589 case 'v':
6590 cursor_visible(FALSE);
6591 goto got3;
6592
6593 got3:
6594 s += 3;
6595 len -= 2;
6596 }
6597
6598#ifdef MCH_WRITE_DUMP
6599 if (fdDump)
6600 {
6601 fputs("ESC | ", fdDump);
6602 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6603 fputc('\n', fdDump);
6604 }
6605#endif
6606 }
6607 else
6608 {
6609 /* Write a single character */
6610 DWORD nWritten;
6611
6612 nWritten = write_chars(s, 1);
6613#ifdef MCH_WRITE_DUMP
6614 if (fdDump)
6615 {
6616 fputc('>', fdDump);
6617 fwrite(s, sizeof(char_u), nWritten, fdDump);
6618 fputs("<\n", fdDump);
6619 }
6620#endif
6621
6622 len -= (nWritten - 1);
6623 s += nWritten;
6624 }
6625 }
6626
6627#ifdef MCH_WRITE_DUMP
6628 if (fdDump)
6629 fflush(fdDump);
6630#endif
6631}
6632
6633#endif /* FEAT_GUI_W32 */
6634
6635
6636/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006637 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638 */
6639 void
6640mch_delay(
6641 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006642 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643{
6644#ifdef FEAT_GUI_W32
6645 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006646#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006647 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006648# ifdef FEAT_MZSCHEME
6649 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6650 {
6651 int towait = p_mzq;
6652
6653 /* if msec is large enough, wait by portions in p_mzq */
6654 while (msec > 0)
6655 {
6656 mzvim_check_threads();
6657 if (msec < towait)
6658 towait = msec;
6659 Sleep(towait);
6660 msec -= towait;
6661 }
6662 }
6663 else
6664# endif
6665 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006666 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006667 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006668#endif
6669}
6670
6671
6672/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006673 * This version of remove is not scared by a readonly (backup) file.
6674 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006675 * Return 0 for success, -1 for failure.
6676 */
6677 int
6678mch_remove(char_u *name)
6679{
6680#ifdef FEAT_MBYTE
6681 WCHAR *wn = NULL;
6682 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006683#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006684
Bram Moolenaar203258c2016-01-17 22:15:16 +01006685 /*
6686 * On Windows, deleting a directory's symbolic link is done by
6687 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6688 */
6689 if (mch_isdir(name) && mch_is_symbolic_link(name))
6690 return mch_rmdir(name);
6691
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006692 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6693
6694#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6696 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006697 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006698 if (wn != NULL)
6699 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006700 n = DeleteFileW(wn) ? 0 : -1;
6701 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006702 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006703 }
6704 }
6705#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006706 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006707}
6708
6709
6710/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006711 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 */
6713 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006714mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715{
6716#ifndef FEAT_GUI_W32 /* never used */
6717 if (g_fCtrlCPressed || g_fCBrkPressed)
6718 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006719 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6721 got_int = TRUE;
6722 }
6723#endif
6724}
6725
Bram Moolenaaree273972016-01-02 21:11:51 +01006726/* physical RAM to leave for the OS */
6727#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006728
6729/*
6730 * How much main memory in KiB that can be used by VIM.
6731 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006732 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006733mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006734{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006735 MEMORYSTATUSEX ms;
6736
Bram Moolenaaree273972016-01-02 21:11:51 +01006737 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006738 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6739 * what fits in 32 bits. But it's not always available. */
6740 ms.dwLength = sizeof(MEMORYSTATUSEX);
6741 GlobalMemoryStatusEx(&ms);
6742 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006743 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006744 /* Process address space fits in physical RAM, use all of it. */
6745 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006746 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006747 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006748 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006749 /* Catch old NT box or perverse hardware setup. */
6750 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006751 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006752 /* Use physical RAM less reserve for OS + data. */
6753 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006754}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006755
Bram Moolenaar071d4272004-06-13 20:20:40 +00006756#ifdef FEAT_MBYTE
6757/*
6758 * Same code as below, but with wide functions and no comments.
6759 * Return 0 for success, non-zero for failure.
6760 */
6761 int
6762mch_wrename(WCHAR *wold, WCHAR *wnew)
6763{
6764 WCHAR *p;
6765 int i;
6766 WCHAR szTempFile[_MAX_PATH + 1];
6767 WCHAR szNewPath[_MAX_PATH + 1];
6768 HANDLE hf;
6769
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006770 p = wold;
6771 for (i = 0; wold[i] != NUL; ++i)
6772 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6773 && wold[i + 1] != 0)
6774 p = wold + i + 1;
6775 if ((int)(wold + i - p) < 8 || p[6] != '~')
6776 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006777
6778 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6779 return -1;
6780 *p = NUL;
6781
6782 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6783 return -2;
6784
6785 if (!DeleteFileW(szTempFile))
6786 return -3;
6787
6788 if (!MoveFileW(wold, szTempFile))
6789 return -4;
6790
6791 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6792 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6793 return -5;
6794 if (!CloseHandle(hf))
6795 return -6;
6796
6797 if (!MoveFileW(szTempFile, wnew))
6798 {
6799 (void)MoveFileW(szTempFile, wold);
6800 return -7;
6801 }
6802
6803 DeleteFileW(szTempFile);
6804
6805 if (!DeleteFileW(wold))
6806 return -8;
6807
6808 return 0;
6809}
6810#endif
6811
6812
6813/*
6814 * mch_rename() works around a bug in rename (aka MoveFile) in
6815 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6816 * file whose short file name is "FOO.BAR" (its long file name will
6817 * be correct: "foo.bar~"). Because a file can be accessed by
6818 * either its SFN or its LFN, "foo.bar" has effectively been
6819 * renamed to "foo.bar", which is not at all what was wanted. This
6820 * seems to happen only when renaming files with three-character
6821 * extensions by appending a suffix that does not include ".".
6822 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6823 *
6824 * There is another problem, which isn't really a bug but isn't right either:
6825 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6826 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6827 * service pack 6. Doesn't seem to happen on Windows 98.
6828 *
6829 * Like rename(), returns 0 upon success, non-zero upon failure.
6830 * Should probably set errno appropriately when errors occur.
6831 */
6832 int
6833mch_rename(
6834 const char *pszOldFile,
6835 const char *pszNewFile)
6836{
6837 char szTempFile[_MAX_PATH+1];
6838 char szNewPath[_MAX_PATH+1];
6839 char *pszFilePart;
6840 HANDLE hf;
6841#ifdef FEAT_MBYTE
6842 WCHAR *wold = NULL;
6843 WCHAR *wnew = NULL;
6844 int retval = -1;
6845
6846 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6847 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006848 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6849 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850 if (wold != NULL && wnew != NULL)
6851 retval = mch_wrename(wold, wnew);
6852 vim_free(wold);
6853 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006854 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006855 }
6856#endif
6857
6858 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006859 * No need to play tricks unless the file name contains a "~" as the
6860 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006861 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006862 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6863 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6864 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006865
6866 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6867 * a directory, no error is returned and pszFilePart will be NULL. */
6868 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6869 || pszFilePart == NULL)
6870 return -1;
6871 *pszFilePart = NUL;
6872
6873 /* Get (and create) a unique temporary file name in directory of new file */
6874 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6875 return -2;
6876
6877 /* blow the temp file away */
6878 if (!DeleteFile(szTempFile))
6879 return -3;
6880
6881 /* rename old file to the temp file */
6882 if (!MoveFile(pszOldFile, szTempFile))
6883 return -4;
6884
6885 /* now create an empty file called pszOldFile; this prevents the operating
6886 * system using pszOldFile as an alias (SFN) if we're renaming within the
6887 * same directory. For example, we're editing a file called
6888 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6889 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6890 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006891 * cause all sorts of problems later in buf_write(). So, we create an
6892 * empty file called filena~1.txt and the system will have to find some
6893 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006894 */
6895 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6896 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6897 return -5;
6898 if (!CloseHandle(hf))
6899 return -6;
6900
6901 /* rename the temp file to the new file */
6902 if (!MoveFile(szTempFile, pszNewFile))
6903 {
6904 /* Renaming failed. Rename the file back to its old name, so that it
6905 * looks like nothing happened. */
6906 (void)MoveFile(szTempFile, pszOldFile);
6907
6908 return -7;
6909 }
6910
6911 /* Seems to be left around on Novell filesystems */
6912 DeleteFile(szTempFile);
6913
6914 /* finally, remove the empty old file */
6915 if (!DeleteFile(pszOldFile))
6916 return -8;
6917
6918 return 0; /* success */
6919}
6920
6921/*
6922 * Get the default shell for the current hardware platform
6923 */
6924 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006925default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006926{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927 PlatformId();
6928
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006929 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006930}
6931
6932/*
6933 * mch_access() extends access() to do more detailed check on network drives.
6934 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6935 */
6936 int
6937mch_access(char *n, int p)
6938{
6939 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 int retval = -1; /* default: fail */
6941#ifdef FEAT_MBYTE
6942 WCHAR *wn = NULL;
6943
6944 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006945 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946#endif
6947
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006948 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006949 {
6950 char TempName[_MAX_PATH + 16] = "";
6951#ifdef FEAT_MBYTE
6952 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6953#endif
6954
6955 if (p & R_OK)
6956 {
6957 /* Read check is performed by seeing if we can do a find file on
6958 * the directory for any file. */
6959#ifdef FEAT_MBYTE
6960 if (wn != NULL)
6961 {
6962 int i;
6963 WIN32_FIND_DATAW d;
6964
6965 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6966 TempNameW[i] = wn[i];
6967 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6968 TempNameW[i++] = '\\';
6969 TempNameW[i++] = '*';
6970 TempNameW[i++] = 0;
6971
6972 hFile = FindFirstFileW(TempNameW, &d);
6973 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006974 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975 else
6976 (void)FindClose(hFile);
6977 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006978 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979#endif
6980 {
6981 char *pch;
6982 WIN32_FIND_DATA d;
6983
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006984 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006985 pch = TempName + STRLEN(TempName) - 1;
6986 if (*pch != '\\' && *pch != '/')
6987 *++pch = '\\';
6988 *++pch = '*';
6989 *++pch = NUL;
6990
6991 hFile = FindFirstFile(TempName, &d);
6992 if (hFile == INVALID_HANDLE_VALUE)
6993 goto getout;
6994 (void)FindClose(hFile);
6995 }
6996 }
6997
6998 if (p & W_OK)
6999 {
7000 /* Trying to create a temporary file in the directory should catch
7001 * directories on read-only network shares. However, in
7002 * directories whose ACL allows writes but denies deletes will end
7003 * up keeping the temporary file :-(. */
7004#ifdef FEAT_MBYTE
7005 if (wn != NULL)
7006 {
7007 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007008 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007009 else
7010 DeleteFileW(TempNameW);
7011 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007012 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007013#endif
7014 {
7015 if (!GetTempFileName(n, "VIM", 0, TempName))
7016 goto getout;
7017 mch_remove((char_u *)TempName);
7018 }
7019 }
7020 }
7021 else
7022 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007023 // Don't consider a file read-only if another process has opened it.
7024 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7025
Bram Moolenaar071d4272004-06-13 20:20:40 +00007026 /* Trying to open the file for the required access does ACL, read-only
7027 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007028 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7029 | ((p & R_OK) ? GENERIC_READ : 0);
7030
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031#ifdef FEAT_MBYTE
7032 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007033 hFile = CreateFileW(wn, access_mode, share_mode,
7034 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007035 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036#endif
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007037 hFile = CreateFile(n, access_mode, share_mode,
7038 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007039 if (hFile == INVALID_HANDLE_VALUE)
7040 goto getout;
7041 CloseHandle(hFile);
7042 }
7043
7044 retval = 0; /* success */
7045getout:
7046#ifdef FEAT_MBYTE
7047 vim_free(wn);
7048#endif
7049 return retval;
7050}
7051
7052#if defined(FEAT_MBYTE) || defined(PROTO)
7053/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007054 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007055 */
7056 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007057mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007058{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007059 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
7060# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 WCHAR *wn;
7062 int f;
7063
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007064 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007065 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007066 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007067 if (wn != NULL)
7068 {
7069 f = _wopen(wn, flags, mode);
7070 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007071 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007072 }
7073 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007074# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007075
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007076 /* open() can open a file which name is longer than _MAX_PATH bytes
7077 * and shorter than _MAX_PATH characters successfully, but sometimes it
7078 * causes unexpected error in another part. We make it an error explicitly
7079 * here. */
7080 if (strlen(name) >= _MAX_PATH)
7081 return -1;
7082
Bram Moolenaar071d4272004-06-13 20:20:40 +00007083 return open(name, flags, mode);
7084}
7085
7086/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007087 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007088 */
7089 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007090mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007091{
7092 WCHAR *wn, *wm;
7093 FILE *f = NULL;
7094
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007095 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007096 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007097# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007098 /* Work around an annoying assertion in the Microsoft debug CRT
7099 * when mode's text/binary setting doesn't match _get_fmode(). */
7100 char newMode = mode[strlen(mode) - 1];
7101 int oldMode = 0;
7102
7103 _get_fmode(&oldMode);
7104 if (newMode == 't')
7105 _set_fmode(_O_TEXT);
7106 else if (newMode == 'b')
7107 _set_fmode(_O_BINARY);
7108# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007109 wn = enc_to_utf16((char_u *)name, NULL);
7110 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111 if (wn != NULL && wm != NULL)
7112 f = _wfopen(wn, wm);
7113 vim_free(wn);
7114 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007115
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007116# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007117 _set_fmode(oldMode);
7118# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007119 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007120 }
7121
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007122 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7123 * and shorter than _MAX_PATH characters successfully, but sometimes it
7124 * causes unexpected error in another part. We make it an error explicitly
7125 * here. */
7126 if (strlen(name) >= _MAX_PATH)
7127 return NULL;
7128
Bram Moolenaar071d4272004-06-13 20:20:40 +00007129 return fopen(name, mode);
7130}
7131#endif
7132
7133#ifdef FEAT_MBYTE
7134/*
7135 * SUB STREAM (aka info stream) handling:
7136 *
7137 * NTFS can have sub streams for each file. Normal contents of file is
7138 * stored in the main stream, and extra contents (author information and
7139 * title and so on) can be stored in sub stream. After Windows 2000, user
7140 * can access and store those informations in sub streams via explorer's
7141 * property menuitem in right click menu. Those informations in sub streams
7142 * were lost when copying only the main stream. So we have to copy sub
7143 * streams.
7144 *
7145 * Incomplete explanation:
7146 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7147 * More useful info and an example:
7148 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7149 */
7150
7151/*
7152 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7153 * and write to stream "substream" of file "to".
7154 * Errors are ignored.
7155 */
7156 static void
7157copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7158{
7159 HANDLE hTo;
7160 WCHAR *to_name;
7161
7162 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7163 wcscpy(to_name, to);
7164 wcscat(to_name, substream);
7165
7166 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7167 FILE_ATTRIBUTE_NORMAL, NULL);
7168 if (hTo != INVALID_HANDLE_VALUE)
7169 {
7170 long done;
7171 DWORD todo;
7172 DWORD readcnt, written;
7173 char buf[4096];
7174
7175 /* Copy block of bytes at a time. Abort when something goes wrong. */
7176 for (done = 0; done < len; done += written)
7177 {
7178 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007179 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7180 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007181 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7182 FALSE, FALSE, context)
7183 || readcnt != todo
7184 || !WriteFile(hTo, buf, todo, &written, NULL)
7185 || written != todo)
7186 break;
7187 }
7188 CloseHandle(hTo);
7189 }
7190
7191 free(to_name);
7192}
7193
7194/*
7195 * Copy info streams from file "from" to file "to".
7196 */
7197 static void
7198copy_infostreams(char_u *from, char_u *to)
7199{
7200 WCHAR *fromw;
7201 WCHAR *tow;
7202 HANDLE sh;
7203 WIN32_STREAM_ID sid;
7204 int headersize;
7205 WCHAR streamname[_MAX_PATH];
7206 DWORD readcount;
7207 void *context = NULL;
7208 DWORD lo, hi;
7209 int len;
7210
7211 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007212 fromw = enc_to_utf16(from, NULL);
7213 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007214 if (fromw != NULL && tow != NULL)
7215 {
7216 /* Open the file for reading. */
7217 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7218 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7219 if (sh != INVALID_HANDLE_VALUE)
7220 {
7221 /* Use BackupRead() to find the info streams. Repeat until we
7222 * have done them all.*/
7223 for (;;)
7224 {
7225 /* Get the header to find the length of the stream name. If
7226 * the "readcount" is zero we have done all info streams. */
7227 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007228 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007229 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7230 &readcount, FALSE, FALSE, &context)
7231 || readcount == 0)
7232 break;
7233
7234 /* We only deal with streams that have a name. The normal
7235 * file data appears to be without a name, even though docs
7236 * suggest it is called "::$DATA". */
7237 if (sid.dwStreamNameSize > 0)
7238 {
7239 /* Read the stream name. */
7240 if (!BackupRead(sh, (LPBYTE)streamname,
7241 sid.dwStreamNameSize,
7242 &readcount, FALSE, FALSE, &context))
7243 break;
7244
7245 /* Copy an info stream with a name ":anything:$DATA".
7246 * Skip "::$DATA", it has no stream name (examples suggest
7247 * it might be used for the normal file contents).
7248 * Note that BackupRead() counts bytes, but the name is in
7249 * wide characters. */
7250 len = readcount / sizeof(WCHAR);
7251 streamname[len] = 0;
7252 if (len > 7 && wcsicmp(streamname + len - 6,
7253 L":$DATA") == 0)
7254 {
7255 streamname[len - 6] = 0;
7256 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007257 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007258 }
7259 }
7260
7261 /* Advance to the next stream. We might try seeking too far,
7262 * but BackupSeek() doesn't skip over stream borders, thus
7263 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007264 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007265 &lo, &hi, &context);
7266 }
7267
7268 /* Clear the context. */
7269 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7270
7271 CloseHandle(sh);
7272 }
7273 }
7274 vim_free(fromw);
7275 vim_free(tow);
7276}
7277#endif
7278
7279/*
7280 * Copy file attributes from file "from" to file "to".
7281 * For Windows NT and later we copy info streams.
7282 * Always returns zero, errors are ignored.
7283 */
7284 int
7285mch_copy_file_attribute(char_u *from, char_u *to)
7286{
7287#ifdef FEAT_MBYTE
7288 /* File streams only work on Windows NT and later. */
7289 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007290 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007291#endif
7292 return 0;
7293}
7294
7295#if defined(MYRESETSTKOFLW) || defined(PROTO)
7296/*
7297 * Recreate a destroyed stack guard page in win32.
7298 * Written by Benjamin Peterson.
7299 */
7300
7301/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007302#define MIN_STACK_WINNT 2
7303
7304/*
7305 * This function does the same thing as _resetstkoflw(), which is only
7306 * available in DevStudio .net and later.
7307 * Returns 0 for failure, 1 for success.
7308 */
7309 int
7310myresetstkoflw(void)
7311{
7312 BYTE *pStackPtr;
7313 BYTE *pGuardPage;
7314 BYTE *pStackBase;
7315 BYTE *pLowestPossiblePage;
7316 MEMORY_BASIC_INFORMATION mbi;
7317 SYSTEM_INFO si;
7318 DWORD nPageSize;
7319 DWORD dummy;
7320
Bram Moolenaar071d4272004-06-13 20:20:40 +00007321 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322
7323 /* We need to know the system page size. */
7324 GetSystemInfo(&si);
7325 nPageSize = si.dwPageSize;
7326
7327 /* ...and the current stack pointer */
7328 pStackPtr = (BYTE*)_alloca(1);
7329
7330 /* ...and the base of the stack. */
7331 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7332 return 0;
7333 pStackBase = (BYTE*)mbi.AllocationBase;
7334
7335 /* ...and the page thats min_stack_req pages away from stack base; this is
7336 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007337 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007338
Bram Moolenaar071d4272004-06-13 20:20:40 +00007339 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007340 /* We want the first committed page in the stack Start at the stack
7341 * base and move forward through memory until we find a committed block.
7342 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343 BYTE *pBlock = pStackBase;
7344
Bram Moolenaara466c992005-07-09 21:03:22 +00007345 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007346 {
7347 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7348 return 0;
7349
7350 pBlock += mbi.RegionSize;
7351
7352 if (mbi.State & MEM_COMMIT)
7353 break;
7354 }
7355
7356 /* mbi now describes the first committed block in the stack. */
7357 if (mbi.Protect & PAGE_GUARD)
7358 return 1;
7359
7360 /* decide where the guard page should start */
7361 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7362 pGuardPage = pLowestPossiblePage;
7363 else
7364 pGuardPage = (BYTE*)mbi.BaseAddress;
7365
7366 /* allocate the guard page */
7367 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7368 return 0;
7369
7370 /* apply the guard attribute to the page */
7371 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7372 &dummy))
7373 return 0;
7374 }
7375
7376 return 1;
7377}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007378#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007380
7381#if defined(FEAT_MBYTE) || defined(PROTO)
7382/*
7383 * The command line arguments in UCS2
7384 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007385static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007386static LPWSTR *ArglistW = NULL;
7387static int global_argc = 0;
7388static char **global_argv;
7389
7390static int used_file_argc = 0; /* last argument in global_argv[] used
7391 for the argument list. */
7392static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7393 command line arguments added to
7394 the argument list */
7395static int used_file_count = 0; /* nr of entries in used_file_indexes */
7396static int used_file_literal = FALSE; /* take file names literally */
7397static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007398static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007399static int used_alist_count = 0;
7400
7401
7402/*
7403 * Get the command line arguments. Unicode version.
7404 * Returns argc. Zero when something fails.
7405 */
7406 int
7407get_cmd_argsW(char ***argvp)
7408{
7409 char **argv = NULL;
7410 int argc = 0;
7411 int i;
7412
Bram Moolenaar14993322014-09-09 12:25:33 +02007413 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007414 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7415 if (ArglistW != NULL)
7416 {
7417 argv = malloc((nArgsW + 1) * sizeof(char *));
7418 if (argv != NULL)
7419 {
7420 argc = nArgsW;
7421 argv[argc] = NULL;
7422 for (i = 0; i < argc; ++i)
7423 {
7424 int len;
7425
7426 /* Convert each Unicode argument to the current codepage. */
7427 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007428 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007429 (LPSTR *)&argv[i], &len, 0, 0);
7430 if (argv[i] == NULL)
7431 {
7432 /* Out of memory, clear everything. */
7433 while (i > 0)
7434 free(argv[--i]);
7435 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007436 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007437 argc = 0;
7438 }
7439 }
7440 }
7441 }
7442
7443 global_argc = argc;
7444 global_argv = argv;
7445 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007446 {
7447 if (used_file_indexes != NULL)
7448 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007449 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007450 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007451
7452 if (argvp != NULL)
7453 *argvp = argv;
7454 return argc;
7455}
7456
7457 void
7458free_cmd_argsW(void)
7459{
7460 if (ArglistW != NULL)
7461 {
7462 GlobalFree(ArglistW);
7463 ArglistW = NULL;
7464 }
7465}
7466
7467/*
7468 * Remember "name" is an argument that was added to the argument list.
7469 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7470 * is called.
7471 */
7472 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007473used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007474{
7475 int i;
7476
7477 if (used_file_indexes == NULL)
7478 return;
7479 for (i = used_file_argc + 1; i < global_argc; ++i)
7480 if (STRCMP(global_argv[i], name) == 0)
7481 {
7482 used_file_argc = i;
7483 used_file_indexes[used_file_count++] = i;
7484 break;
7485 }
7486 used_file_literal = literal;
7487 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007488 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007489}
7490
7491/*
7492 * Remember the length of the argument list as it was. If it changes then we
7493 * leave it alone when 'encoding' is set.
7494 */
7495 void
7496set_alist_count(void)
7497{
7498 used_alist_count = GARGCOUNT;
7499}
7500
7501/*
7502 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7503 * has been changed while starting up. Use the UCS-2 command line arguments
7504 * and convert them to 'encoding'.
7505 */
7506 void
7507fix_arg_enc(void)
7508{
7509 int i;
7510 int idx;
7511 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007512 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007513
7514 /* Safety checks:
7515 * - if argument count differs between the wide and non-wide argument
7516 * list, something must be wrong.
7517 * - the file name arguments must have been located.
7518 * - the length of the argument list wasn't changed by the user.
7519 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007520 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007521 || ArglistW == NULL
7522 || used_file_indexes == NULL
7523 || used_file_count == 0
7524 || used_alist_count != GARGCOUNT)
7525 return;
7526
Bram Moolenaar86b68352004-12-27 21:59:20 +00007527 /* Remember the buffer numbers for the arguments. */
7528 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7529 if (fnum_list == NULL)
7530 return; /* out of memory */
7531 for (i = 0; i < GARGCOUNT; ++i)
7532 fnum_list[i] = GARGLIST[i].ae_fnum;
7533
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007534 /* Clear the argument list. Make room for the new arguments. */
7535 alist_clear(&global_alist);
7536 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007537 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007538
7539 for (i = 0; i < used_file_count; ++i)
7540 {
7541 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007542 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007543 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007544 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007545 int literal = used_file_literal;
7546
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007547#ifdef FEAT_DIFF
7548 /* When using diff mode may need to concatenate file name to
7549 * directory name. Just like it's done in main(). */
7550 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7551 && !mch_isdir(alist_name(&GARGLIST[0])))
7552 {
7553 char_u *r;
7554
7555 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7556 if (r != NULL)
7557 {
7558 vim_free(str);
7559 str = r;
7560 }
7561 }
7562#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007563 /* Re-use the old buffer by renaming it. When not using literal
7564 * names it's done by alist_expand() below. */
7565 if (used_file_literal)
7566 buf_set_name(fnum_list[i], str);
7567
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007568 /* Check backtick literal. backtick literal is already expanded in
7569 * main.c, so this part add str as literal. */
7570 if (literal == FALSE)
7571 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007572 size_t len = STRLEN(str);
7573
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007574 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7575 literal = TRUE;
7576 }
7577 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007578 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007579 }
7580
7581 if (!used_file_literal)
7582 {
7583 /* Now expand wildcards in the arguments. */
7584 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7585 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007586 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7587 * Also, unset wildignore to not be influenced by this option.
7588 * The arguments specified in command-line should be kept even if
7589 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007590 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007591 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007592 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007593 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007594 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007595 }
7596
7597 /* If wildcard expansion failed, we are editing the first file of the
7598 * arglist and there is no file name: Edit the first argument now. */
7599 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7600 {
7601 do_cmdline_cmd((char_u *)":rewind");
7602 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007603 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007604 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007605
7606 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007607}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007608#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007609
7610 int
7611mch_setenv(char *var, char *value, int x)
7612{
7613 char_u *envbuf;
7614
7615 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7616 if (envbuf == NULL)
7617 return -1;
7618
7619 sprintf((char *)envbuf, "%s=%s", var, value);
7620
7621#ifdef FEAT_MBYTE
7622 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7623 {
7624 WCHAR *p = enc_to_utf16(envbuf, NULL);
7625
7626 vim_free(envbuf);
7627 if (p == NULL)
7628 return -1;
7629 _wputenv(p);
7630# ifdef libintl_wputenv
7631 libintl_wputenv(p);
7632# endif
7633 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7634 vim_free(p);
7635 }
7636 else
7637#endif
7638 {
7639 _putenv((char *)envbuf);
7640# ifdef libintl_putenv
7641 libintl_putenv((char *)envbuf);
7642# endif
7643 /* Unlike Un*x systems, we can free the string for _putenv(). */
7644 vim_free(envbuf);
7645 }
7646
7647 return 0;
7648}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007649
7650#ifndef FEAT_GUI_W32
7651
7652/*
7653 * Support for 256 colors and 24-bit colors was added in Windows 10
7654 * version 1703 (Creators update).
7655 */
7656# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7657
7658 static void
7659vtp_init(void)
7660{
7661 DWORD ver, mode;
7662 HMODULE hKerneldll;
7663 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007664# ifdef FEAT_TERMGUICOLORS
7665 COLORREF fg, bg;
7666# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007667
7668 ver = get_build_number();
7669 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7670 GetConsoleMode(g_hConOut, &mode);
7671 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7672 if (SetConsoleMode(g_hConOut, mode) == 0)
7673 vtp_working = 0;
7674
7675 /* Use functions supported from Vista */
7676 hKerneldll = GetModuleHandle("kernel32.dll");
7677 if (hKerneldll != NULL)
7678 {
7679 pGetConsoleScreenBufferInfoEx =
7680 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7681 hKerneldll, "GetConsoleScreenBufferInfoEx");
7682 pSetConsoleScreenBufferInfoEx =
7683 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7684 hKerneldll, "SetConsoleScreenBufferInfoEx");
7685 if (pGetConsoleScreenBufferInfoEx != NULL
7686 && pSetConsoleScreenBufferInfoEx != NULL)
7687 has_csbiex = TRUE;
7688 }
7689
7690 csbi.cbSize = sizeof(csbi);
7691 if (has_csbiex)
7692 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007693 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7694 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7695
7696# ifdef FEAT_TERMGUICOLORS
7697 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7698 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7699 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7700 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7701 default_console_color_bg = bg;
7702 default_console_color_fg = fg;
7703#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007704
7705 set_console_color_rgb();
7706}
7707
7708 static void
7709vtp_exit(void)
7710{
7711 reset_console_color_rgb();
7712}
7713
7714 static int
7715vtp_printf(
7716 char *format,
7717 ...)
7718{
7719 char_u buf[100];
7720 va_list list;
7721 DWORD result;
7722
7723 va_start(list, format);
7724 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7725 va_end(list);
7726 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7727 return (int)result;
7728}
7729
7730 static void
7731vtp_sgr_bulk(
7732 int arg)
7733{
7734 int args[1];
7735
7736 args[0] = arg;
7737 vtp_sgr_bulks(1, args);
7738}
7739
7740 static void
7741vtp_sgr_bulks(
7742 int argc,
7743 int *args
7744)
7745{
7746 /* 2('\033[') + 4('255.') * 16 + NUL */
7747 char_u buf[2 + (4 * 16) + 1];
7748 char_u *p;
7749 int i;
7750
7751 p = buf;
7752 *p++ = '\033';
7753 *p++ = '[';
7754
7755 for (i = 0; i < argc; ++i)
7756 {
7757 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7758 *p++ = ';';
7759 }
7760 p--;
7761 *p++ = 'm';
7762 *p = NUL;
7763 vtp_printf((char *)buf);
7764}
7765
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007766# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007767 static int
7768ctermtoxterm(
7769 int cterm)
7770{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007771 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007772
7773 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7774 return (((int)r << 16) | ((int)g << 8) | (int)b);
7775}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007776# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007777
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007778 static void
7779set_console_color_rgb(void)
7780{
7781# ifdef FEAT_TERMGUICOLORS
7782 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7783 int id;
7784 guicolor_T fg = INVALCOLOR;
7785 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007786 int ctermfg;
7787 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007788
7789 if (!USE_VTP)
7790 return;
7791
7792 id = syn_name2id((char_u *)"Normal");
7793 if (id > 0)
7794 syn_id2colors(id, &fg, &bg);
7795 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007796 {
7797 ctermfg = -1;
7798 if (id > 0)
7799 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007800 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7801 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007802 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007803 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007804 {
7805 ctermbg = -1;
7806 if (id > 0)
7807 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007808 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7809 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007810 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007811 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7812 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7813
7814 csbi.cbSize = sizeof(csbi);
7815 if (has_csbiex)
7816 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7817
7818 csbi.cbSize = sizeof(csbi);
7819 csbi.srWindow.Right += 1;
7820 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007821 csbi.ColorTable[g_color_index_bg] = (COLORREF)bg;
7822 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007823 if (has_csbiex)
7824 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7825# endif
7826}
7827
7828 static void
7829reset_console_color_rgb(void)
7830{
7831# ifdef FEAT_TERMGUICOLORS
7832 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7833
7834 csbi.cbSize = sizeof(csbi);
7835 if (has_csbiex)
7836 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7837
7838 csbi.cbSize = sizeof(csbi);
7839 csbi.srWindow.Right += 1;
7840 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007841 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7842 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007843 if (has_csbiex)
7844 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7845# endif
7846}
7847
7848 void
7849control_console_color_rgb(void)
7850{
7851 if (USE_VTP)
7852 set_console_color_rgb();
7853 else
7854 reset_console_color_rgb();
7855}
7856
7857 int
7858has_vtp_working(void)
7859{
7860 return vtp_working;
7861}
7862
7863 int
7864use_vtp(void)
7865{
7866 return USE_VTP;
7867}
7868
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007869 int
7870is_term_win32(void)
7871{
7872 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7873}
7874
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007875#endif