blob: b665815f802ebf344edd0849aa6740146bf20219 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149#if defined(__BORLANDC__)
150/* Strangely Borland uses a non-standard name. */
151# define wcsicmp(a, b) wcscmpi((a), (b))
152#endif
153
154#ifndef FEAT_GUI_W32
155/* Win32 Console handles for input and output */
156static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
157static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
158
159/* Win32 Screen buffer,coordinate,console I/O information */
160static SMALL_RECT g_srScrollRegion;
161static COORD g_coord; /* 0-based, but external coords are 1-based */
162
163/* The attribute of the screen when the editor was started */
164static WORD g_attrDefault = 7; /* lightgray text on black background */
165static WORD g_attrCurrent;
166
167static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
168static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
169static int g_fForceExit = FALSE; /* set when forcefully exiting */
170
171static void termcap_mode_start(void);
172static void termcap_mode_end(void);
173static void clear_chars(COORD coord, DWORD n);
174static void clear_screen(void);
175static void clear_to_end_of_display(void);
176static void clear_to_end_of_line(void);
177static void scroll(unsigned cLines);
178static void set_scroll_region(unsigned left, unsigned top,
179 unsigned right, unsigned bottom);
180static void insert_lines(unsigned cLines);
181static void delete_lines(unsigned cLines);
182static void gotoxy(unsigned x, unsigned y);
183static void normvideo(void);
184static void textattr(WORD wAttr);
185static void textcolor(WORD wAttr);
186static void textbackground(WORD wAttr);
187static void standout(void);
188static void standend(void);
189static void visual_bell(void);
190static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200191static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000192static void create_conin(void);
193static int s_cursor_visible = TRUE;
194static int did_create_conin = FALSE;
195#else
196static int s_dont_use_vimrun = TRUE;
197static int need_vimrun_warning = FALSE;
198static char *vimrun_path = "vimrun ";
199#endif
200
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200201static int win32_getattrs(char_u *name);
202static int win32_setattrs(char_u *name, int attrs);
203static int win32_set_archive(char_u *name);
204
Bram Moolenaar071d4272004-06-13 20:20:40 +0000205#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100206static int vtp_working = 0;
207static void vtp_init();
208static void vtp_exit();
209static int vtp_printf(char *format, ...);
210static void vtp_sgr_bulk(int arg);
211static void vtp_sgr_bulks(int argc, int *argv);
212
213static guicolor_T save_console_bg_rgb;
214static guicolor_T save_console_fg_rgb;
215
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +0200216static int g_color_index_bg = 0;
217static int g_color_index_fg = 7;
218
219# ifdef FEAT_TERMGUICOLORS
220static int default_console_color_bg = 0x000000; // black
221static int default_console_color_fg = 0xc0c0c0; // white
222# endif
223
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100224# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +0200225# define USE_VTP (vtp_working && is_term_win32() && (p_tgc || (!p_tgc && t_colors >= 256)))
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100226# else
227# define USE_VTP 0
228# endif
229
230static void set_console_color_rgb(void);
231static void reset_console_color_rgb(void);
232#endif
233
234/* This flag is newly created from Windows 10 */
235#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
236# define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
237#endif
238
239#ifndef FEAT_GUI_W32
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240static int suppress_winsize = 1; /* don't fiddle with console */
241#endif
242
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200243static char_u *exe_path = NULL;
244
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100245static BOOL win8_or_later = FALSE;
246
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100247#ifndef FEAT_GUI_W32
Bram Moolenaarcafafb32018-02-22 21:07:09 +0100248/* Dynamic loading for portability */
249typedef struct _DYN_CONSOLE_SCREEN_BUFFER_INFOEX
250{
251 ULONG cbSize;
252 COORD dwSize;
253 COORD dwCursorPosition;
254 WORD wAttributes;
255 SMALL_RECT srWindow;
256 COORD dwMaximumWindowSize;
257 WORD wPopupAttributes;
258 BOOL bFullscreenSupported;
259 COLORREF ColorTable[16];
260} DYN_CONSOLE_SCREEN_BUFFER_INFOEX, *PDYN_CONSOLE_SCREEN_BUFFER_INFOEX;
261typedef BOOL (WINAPI *PfnGetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
262static PfnGetConsoleScreenBufferInfoEx pGetConsoleScreenBufferInfoEx;
263typedef BOOL (WINAPI *PfnSetConsoleScreenBufferInfoEx)(HANDLE, PDYN_CONSOLE_SCREEN_BUFFER_INFOEX);
264static PfnSetConsoleScreenBufferInfoEx pSetConsoleScreenBufferInfoEx;
265static BOOL has_csbiex = FALSE;
266
267/*
268 * Get version number including build number
269 */
270typedef BOOL (WINAPI *PfnRtlGetVersion)(LPOSVERSIONINFOW);
271# define MAKE_VER(major, minor, build) \
272 (((major) << 24) | ((minor) << 16) | (build))
273
274 static DWORD
275get_build_number(void)
276{
277 OSVERSIONINFOW osver = {sizeof(OSVERSIONINFOW)};
278 HMODULE hNtdll;
279 PfnRtlGetVersion pRtlGetVersion;
280 DWORD ver = MAKE_VER(0, 0, 0);
281
282 hNtdll = GetModuleHandle("ntdll.dll");
283 if (hNtdll != NULL)
284 {
285 pRtlGetVersion =
286 (PfnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion");
287 pRtlGetVersion(&osver);
288 ver = MAKE_VER(min(osver.dwMajorVersion, 255),
289 min(osver.dwMinorVersion, 255),
290 min(osver.dwBuildNumber, 32767));
291 }
292 return ver;
293}
294
295
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100296/*
297 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100298 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299 */
300 static BOOL
301read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100302 HANDLE hInput,
303 INPUT_RECORD *lpBuffer,
304 DWORD nLength,
305 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100306{
307 enum
308 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100309 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100311 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100312 static DWORD s_dwIndex = 0;
313 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100314 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100315 int head;
316 int tail;
317 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100318
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200319 if (nLength == -2)
320 return (s_dwMax > 0) ? TRUE : FALSE;
321
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100322 if (!win8_or_later)
323 {
324 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200325 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
326 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100327 }
328
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100329 if (s_dwMax == 0)
330 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100331 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200332 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
333 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100334 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100335 s_dwIndex = 0;
336 s_dwMax = dwEvents;
337 if (dwEvents == 0)
338 {
339 *lpEvents = 0;
340 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100341 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100342
343 if (s_dwMax > 1)
344 {
345 head = 0;
346 tail = s_dwMax - 1;
347 while (head != tail)
348 {
349 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
350 && s_irCache[head + 1].EventType
351 == WINDOW_BUFFER_SIZE_EVENT)
352 {
353 /* Remove duplicate event to avoid flicker. */
354 for (i = head; i < tail; ++i)
355 s_irCache[i] = s_irCache[i + 1];
356 --tail;
357 continue;
358 }
359 head++;
360 }
361 s_dwMax = tail + 1;
362 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100363 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100364
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100365 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200366 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100367 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100368 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100369 return TRUE;
370}
371
372/*
373 * Version of PeekConsoleInput() that works with IME.
374 */
375 static BOOL
376peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100377 HANDLE hInput,
378 INPUT_RECORD *lpBuffer,
379 DWORD nLength,
380 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100381{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100382 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100383}
384
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100385# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200386 static DWORD
387msg_wait_for_multiple_objects(
388 DWORD nCount,
389 LPHANDLE pHandles,
390 BOOL fWaitAll,
391 DWORD dwMilliseconds,
392 DWORD dwWakeMask)
393{
394 if (read_console_input(NULL, NULL, -2, NULL))
395 return WAIT_OBJECT_0;
396 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
397 dwMilliseconds, dwWakeMask);
398}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100399# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200400
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100401# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200402 static DWORD
403wait_for_single_object(
404 HANDLE hHandle,
405 DWORD dwMilliseconds)
406{
407 if (read_console_input(NULL, NULL, -2, NULL))
408 return WAIT_OBJECT_0;
409 return WaitForSingleObject(hHandle, dwMilliseconds);
410}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100411# endif
412#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200413
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414 static void
415get_exe_name(void)
416{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100417 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
418 * as the maximum length that works (plus a NUL byte). */
419#define MAX_ENV_PATH_LEN 8192
420 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200421 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000422
423 if (exe_name == NULL)
424 {
425 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100426 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427 if (*temp != NUL)
428 exe_name = FullName_save((char_u *)temp, FALSE);
429 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000430
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200431 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000432 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200433 exe_path = vim_strnsave(exe_name,
434 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200435 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000436 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200437 /* Append our starting directory to $PATH, so that when doing
438 * "!xxd" it's found in our starting directory. Needed because
439 * SearchPath() also looks there. */
440 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100441 if (p == NULL
442 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200443 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100444 if (p == NULL || *p == NUL)
445 temp[0] = NUL;
446 else
447 {
448 STRCPY(temp, p);
449 STRCAT(temp, ";");
450 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200451 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100452 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200453 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000454 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000455 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000456}
457
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200458/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100459 * Unescape characters in "p" that appear in "escaped".
460 */
461 static void
462unescape_shellxquote(char_u *p, char_u *escaped)
463{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100464 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100465 int n;
466
467 while (*p != NUL)
468 {
469 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
470 mch_memmove(p, p + 1, l--);
471#ifdef FEAT_MBYTE
472 n = (*mb_ptr2len)(p);
473#else
474 n = 1;
475#endif
476 p += n;
477 l -= n;
478 }
479}
480
481/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200482 * Load library "name".
483 */
484 HINSTANCE
485vimLoadLib(char *name)
486{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200487 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200488
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200489 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
490 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200491 if (exe_path == NULL)
492 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200493 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200494 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200495 WCHAR old_dirw[MAXPATHL];
496
497 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
498 {
499 /* Change directory to where the executable is, both to make
500 * sure we find a .dll there and to avoid looking for a .dll
501 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100502 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200503 dll = LoadLibrary(name);
504 SetCurrentDirectoryW(old_dirw);
505 return dll;
506 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200507 }
508 return dll;
509}
510
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100511#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
512/*
513 * Get related information about 'funcname' which is imported by 'hInst'.
514 * If 'info' is 0, return the function address.
515 * If 'info' is 1, return the module name which the function is imported from.
516 */
517 static void *
518get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
519{
520 PBYTE pImage = (PBYTE)hInst;
521 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
522 PIMAGE_NT_HEADERS pPE;
523 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
524 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
525 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
526 PIMAGE_IMPORT_BY_NAME pImpName;
527
528 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
529 return NULL;
530 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
531 if (pPE->Signature != IMAGE_NT_SIGNATURE)
532 return NULL;
533 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
534 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
535 .VirtualAddress);
536 for (; pImpDesc->FirstThunk; ++pImpDesc)
537 {
538 if (!pImpDesc->OriginalFirstThunk)
539 continue;
540 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
541 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
542 for (; pIAT->u1.Function; ++pIAT, ++pINT)
543 {
544 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
545 continue;
546 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
547 + (UINT_PTR)(pINT->u1.AddressOfData));
548 if (strcmp((char *)pImpName->Name, funcname) == 0)
549 {
550 switch (info)
551 {
552 case 0:
553 return (void *)pIAT->u1.Function;
554 case 1:
555 return (void *)(pImage + pImpDesc->Name);
556 default:
557 return NULL;
558 }
559 }
560 }
561 }
562 return NULL;
563}
564
565/*
566 * Get the module handle which 'funcname' in 'hInst' is imported from.
567 */
568 HINSTANCE
569find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
570{
571 char *modulename;
572
573 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
574 if (modulename != NULL)
575 return GetModuleHandleA(modulename);
576 return NULL;
577}
578
579/*
580 * Get the address of 'funcname' which is imported by 'hInst' DLL.
581 */
582 void *
583get_dll_import_func(HINSTANCE hInst, const char *funcname)
584{
585 return get_imported_func_info(hInst, funcname, 0);
586}
587#endif
588
Bram Moolenaar071d4272004-06-13 20:20:40 +0000589#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
590# ifndef GETTEXT_DLL
591# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100592# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000593# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200594/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000595static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200596static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000597static char *null_libintl_textdomain(const char *);
598static char *null_libintl_bindtextdomain(const char *, const char *);
599static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100600static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100601static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000602
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200603static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000604char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200605char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
606 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000607char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
608char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000610char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
611 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100612int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100613int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614
615 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100616dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617{
618 int i;
619 static struct
620 {
621 char *name;
622 FARPROC *ptr;
623 } libintl_entry[] =
624 {
625 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200626 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000627 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
628 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
629 {NULL, NULL}
630 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100631 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632
633 /* No need to initialize twice. */
634 if (hLibintlDLL)
635 return 1;
636 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100637 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100638#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100639 if (!hLibintlDLL)
640 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100641#endif
642 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200644 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000645 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200646 verbose_enter();
647 EMSG2(_(e_loadlib), GETTEXT_DLL);
648 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000649 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200650 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651 }
652 for (i = 0; libintl_entry[i].name != NULL
653 && libintl_entry[i].ptr != NULL; ++i)
654 {
655 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
656 libintl_entry[i].name)) == NULL)
657 {
658 dyn_libintl_end();
659 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000660 {
661 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000662 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000663 verbose_leave();
664 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665 return 0;
666 }
667 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000668
669 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000670 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000671 "bind_textdomain_codeset");
672 if (dyn_libintl_bind_textdomain_codeset == NULL)
673 dyn_libintl_bind_textdomain_codeset =
674 null_libintl_bind_textdomain_codeset;
675
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100676 /* _putenv() function for the libintl.dll is optional. */
677 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
678 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100679 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100680 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100681 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
682 }
683 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100684 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100685 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
686 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100687
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 return 1;
689}
690
691 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100692dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693{
694 if (hLibintlDLL)
695 FreeLibrary(hLibintlDLL);
696 hLibintlDLL = NULL;
697 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200698 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699 dyn_libintl_textdomain = null_libintl_textdomain;
700 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000701 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100702 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100703 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704}
705
706 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000707null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708{
709 return (char*)msgid;
710}
711
712 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200713null_libintl_ngettext(
714 const char *msgid,
715 const char *msgid_plural,
716 unsigned long n)
717{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200718 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200719}
720
Bram Moolenaaree695f72016-08-03 22:08:45 +0200721 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100722null_libintl_bindtextdomain(
723 const char *domainname UNUSED,
724 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725{
726 return NULL;
727}
728
729 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100730null_libintl_bind_textdomain_codeset(
731 const char *domainname UNUSED,
732 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000733{
734 return NULL;
735}
736
737 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100738null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000739{
740 return NULL;
741}
742
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200743 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100744null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100745{
746 return 0;
747}
748
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200749 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100750null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100751{
752 return 0;
753}
754
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755#endif /* DYNAMIC_GETTEXT */
756
757/* This symbol is not defined in older versions of the SDK or Visual C++ */
758
759#ifndef VER_PLATFORM_WIN32_WINDOWS
760# define VER_PLATFORM_WIN32_WINDOWS 1
761#endif
762
763DWORD g_PlatformId;
764
765#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100766# ifndef PROTO
767# include <aclapi.h>
768# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200769# ifndef PROTECTED_DACL_SECURITY_INFORMATION
770# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
771# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772#endif
773
Bram Moolenaar27515922013-06-29 15:36:26 +0200774#ifdef HAVE_ACL
775/*
776 * Enables or disables the specified privilege.
777 */
778 static BOOL
779win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
780{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100781 BOOL bResult;
782 LUID luid;
783 HANDLE hToken;
784 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200785
786 if (!OpenProcessToken(GetCurrentProcess(),
787 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
788 return FALSE;
789
790 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
791 {
792 CloseHandle(hToken);
793 return FALSE;
794 }
795
Bram Moolenaar45500912014-07-09 20:51:07 +0200796 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200797 tokenPrivileges.Privileges[0].Luid = luid;
798 tokenPrivileges.Privileges[0].Attributes = bEnable ?
799 SE_PRIVILEGE_ENABLED : 0;
800
801 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
802 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
803
804 CloseHandle(hToken);
805
806 return bResult && GetLastError() == ERROR_SUCCESS;
807}
808#endif
809
Bram Moolenaar071d4272004-06-13 20:20:40 +0000810/*
811 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
812 * VER_PLATFORM_WIN32_WINDOWS (Win95).
813 */
814 void
815PlatformId(void)
816{
817 static int done = FALSE;
818
819 if (!done)
820 {
821 OSVERSIONINFO ovi;
822
823 ovi.dwOSVersionInfoSize = sizeof(ovi);
824 GetVersionEx(&ovi);
825
826 g_PlatformId = ovi.dwPlatformId;
827
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100828 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
829 || ovi.dwMajorVersion > 6)
830 win8_or_later = TRUE;
831
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200833 /* Enable privilege for getting or setting SACLs. */
834 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835#endif
836 done = TRUE;
837 }
838}
839
Bram Moolenaar071d4272004-06-13 20:20:40 +0000840#ifndef FEAT_GUI_W32
841
842#define SHIFT (SHIFT_PRESSED)
843#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
844#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
845#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
846
847
848/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
849 * We map function keys to their ANSI terminal equivalents, as produced
850 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
851 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
852 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
853 * combinations of function/arrow/etc keys.
854 */
855
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000856static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000857{
858 WORD wVirtKey;
859 BOOL fAnsiKey;
860 int chAlone;
861 int chShift;
862 int chCtrl;
863 int chAlt;
864} VirtKeyMap[] =
865{
866
867/* Key ANSI alone shift ctrl alt */
868 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
869
870 { VK_F1, TRUE, ';', 'T', '^', 'h', },
871 { VK_F2, TRUE, '<', 'U', '_', 'i', },
872 { VK_F3, TRUE, '=', 'V', '`', 'j', },
873 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
874 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
875 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
876 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
877 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
878 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
879 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
880 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
881 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
882
883 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
884 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
885 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
886 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
887 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
888 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
889 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
890 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
891 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
892 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
893
894 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
895
896#if 0
897 /* Most people don't have F13-F20, but what the hell... */
898 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
899 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
900 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
901 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
902 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
903 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
904 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
905 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
906#endif
907 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
908 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
909 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
910 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
911
912 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
913 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
914 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
915 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
916 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
917 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
918 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
919 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
920 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
921 /* Sorry, out of number space! <negri>*/
922 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
923
924};
925
926
927#ifdef _MSC_VER
928// The ToAscii bug destroys several registers. Need to turn off optimization
929// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000930# pragma warning(push)
931# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932# pragma optimize("", off)
933#endif
934
935#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200936# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200938# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939#endif
940
941/* The return code indicates key code size. */
942 static int
943#ifdef __BORLANDC__
944 __stdcall
945#endif
946win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000947 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948{
949 UINT uMods = pker->dwControlKeyState;
950 static int s_iIsDead = 0;
951 static WORD awAnsiCode[2];
952 static BYTE abKeystate[256];
953
954
955 if (s_iIsDead == 2)
956 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200957 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958 s_iIsDead = 0;
959 return 1;
960 }
961
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200962 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963 return 1;
964
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200965 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200968 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969
970 if (uMods & SHIFT_PRESSED)
971 abKeystate[VK_SHIFT] = 0x80;
972 if (uMods & CAPSLOCK_ON)
973 abKeystate[VK_CAPITAL] = 1;
974
975 if ((uMods & ALT_GR) == ALT_GR)
976 {
977 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
978 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
979 }
980
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200981 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
982 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983
984 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200985 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986
987 return s_iIsDead;
988}
989
990#ifdef _MSC_VER
991/* MUST switch optimization on again here, otherwise a call to
992 * decode_key_event() may crash (e.g. when hitting caps-lock) */
993# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000994# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995
996# if (_MSC_VER < 1100)
997/* MUST turn off global optimisation for this next function, or
998 * pressing ctrl-minus in insert mode crashes Vim when built with
999 * VC4.1. -- negri. */
1000# pragma optimize("g", off)
1001# endif
1002#endif
1003
1004static BOOL g_fJustGotFocus = FALSE;
1005
1006/*
1007 * Decode a KEY_EVENT into one or two keystrokes
1008 */
1009 static BOOL
1010decode_key_event(
1011 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001012 WCHAR *pch,
1013 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001014 int *pmodifiers,
1015 BOOL fDoPost)
1016{
1017 int i;
1018 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
1019
1020 *pch = *pch2 = NUL;
1021 g_fJustGotFocus = FALSE;
1022
1023 /* ignore key up events */
1024 if (!pker->bKeyDown)
1025 return FALSE;
1026
1027 /* ignore some keystrokes */
1028 switch (pker->wVirtualKeyCode)
1029 {
1030 /* modifiers */
1031 case VK_SHIFT:
1032 case VK_CONTROL:
1033 case VK_MENU: /* Alt key */
1034 return FALSE;
1035
1036 default:
1037 break;
1038 }
1039
1040 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001041 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001042 {
1043 /* Ctrl-6 is Ctrl-^ */
1044 if (pker->wVirtualKeyCode == '6')
1045 {
1046 *pch = Ctrl_HAT;
1047 return TRUE;
1048 }
1049 /* Ctrl-2 is Ctrl-@ */
1050 else if (pker->wVirtualKeyCode == '2')
1051 {
1052 *pch = NUL;
1053 return TRUE;
1054 }
1055 /* Ctrl-- is Ctrl-_ */
1056 else if (pker->wVirtualKeyCode == 0xBD)
1057 {
1058 *pch = Ctrl__;
1059 return TRUE;
1060 }
1061 }
1062
1063 /* Shift-TAB */
1064 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1065 {
1066 *pch = K_NUL;
1067 *pch2 = '\017';
1068 return TRUE;
1069 }
1070
1071 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1072 {
1073 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1074 {
1075 if (nModifs == 0)
1076 *pch = VirtKeyMap[i].chAlone;
1077 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1078 *pch = VirtKeyMap[i].chShift;
1079 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1080 *pch = VirtKeyMap[i].chCtrl;
1081 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1082 *pch = VirtKeyMap[i].chAlt;
1083
1084 if (*pch != 0)
1085 {
1086 if (VirtKeyMap[i].fAnsiKey)
1087 {
1088 *pch2 = *pch;
1089 *pch = K_NUL;
1090 }
1091
1092 return TRUE;
1093 }
1094 }
1095 }
1096
1097 i = win32_kbd_patch_key(pker);
1098
1099 if (i < 0)
1100 *pch = NUL;
1101 else
1102 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001103 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001104
1105 if (pmodifiers != NULL)
1106 {
1107 /* Pass on the ALT key as a modifier, but only when not combined
1108 * with CTRL (which is ALTGR). */
1109 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1110 *pmodifiers |= MOD_MASK_ALT;
1111
1112 /* Pass on SHIFT only for special keys, because we don't know when
1113 * it's already included with the character. */
1114 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1115 *pmodifiers |= MOD_MASK_SHIFT;
1116
1117 /* Pass on CTRL only for non-special keys, because we don't know
1118 * when it's already included with the character. And not when
1119 * combined with ALT (which is ALTGR). */
1120 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1121 && *pch >= 0x20 && *pch < 0x80)
1122 *pmodifiers |= MOD_MASK_CTRL;
1123 }
1124 }
1125
1126 return (*pch != NUL);
1127}
1128
1129#ifdef _MSC_VER
1130# pragma optimize("", on)
1131#endif
1132
1133#endif /* FEAT_GUI_W32 */
1134
1135
1136#ifdef FEAT_MOUSE
1137
1138/*
1139 * For the GUI the mouse handling is in gui_w32.c.
1140 */
1141# ifdef FEAT_GUI_W32
1142 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001143mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144{
1145}
1146# else
1147static int g_fMouseAvail = FALSE; /* mouse present */
1148static int g_fMouseActive = FALSE; /* mouse enabled */
1149static int g_nMouseClick = -1; /* mouse status */
1150static int g_xMouse; /* mouse x coordinate */
1151static int g_yMouse; /* mouse y coordinate */
1152
1153/*
1154 * Enable or disable mouse input
1155 */
1156 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001157mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158{
1159 DWORD cmodein;
1160
1161 if (!g_fMouseAvail)
1162 return;
1163
1164 g_fMouseActive = on;
1165 GetConsoleMode(g_hConIn, &cmodein);
1166
1167 if (g_fMouseActive)
1168 cmodein |= ENABLE_MOUSE_INPUT;
1169 else
1170 cmodein &= ~ENABLE_MOUSE_INPUT;
1171
1172 SetConsoleMode(g_hConIn, cmodein);
1173}
1174
Bram Moolenaar157d8132018-03-06 17:09:20 +01001175
1176#if defined(FEAT_BEVAL_TERM) || defined(PROTO)
1177/*
1178 * Called when 'balloonevalterm' changed.
1179 */
1180 void
1181mch_bevalterm_changed(void)
1182{
1183 mch_setmouse(g_fMouseActive);
1184}
1185#endif
1186
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187/*
1188 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1189 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1190 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1191 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1192 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1193 * and we return the mouse position in g_xMouse and g_yMouse.
1194 *
1195 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1196 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1197 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1198 *
1199 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1200 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1201 *
1202 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1203 * moves, even if it stays within the same character cell. We ignore
1204 * all MOUSE_MOVED messages if the position hasn't really changed, and
1205 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1206 * we're only interested in MOUSE_DRAG).
1207 *
1208 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1209 * 2-button mouses by pressing the left & right buttons simultaneously.
1210 * In practice, it's almost impossible to click both at the same time,
1211 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1212 * in such cases, if the user is clicking quickly.
1213 */
1214 static BOOL
1215decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001216 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001217{
1218 static int s_nOldButton = -1;
1219 static int s_nOldMouseClick = -1;
1220 static int s_xOldMouse = -1;
1221 static int s_yOldMouse = -1;
1222 static linenr_T s_old_topline = 0;
1223#ifdef FEAT_DIFF
1224 static int s_old_topfill = 0;
1225#endif
1226 static int s_cClicks = 1;
1227 static BOOL s_fReleased = TRUE;
1228 static DWORD s_dwLastClickTime = 0;
1229 static BOOL s_fNextIsMiddle = FALSE;
1230
1231 static DWORD cButtons = 0; /* number of buttons supported */
1232
1233 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1234 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1235 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1236 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1237
1238 int nButton;
1239
1240 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1241 cButtons = 2;
1242
1243 if (!g_fMouseAvail || !g_fMouseActive)
1244 {
1245 g_nMouseClick = -1;
1246 return FALSE;
1247 }
1248
1249 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1250 if (g_fJustGotFocus)
1251 {
1252 g_fJustGotFocus = FALSE;
1253 return FALSE;
1254 }
1255
1256 /* unprocessed mouse click? */
1257 if (g_nMouseClick != -1)
1258 return TRUE;
1259
1260 nButton = -1;
1261 g_xMouse = pmer->dwMousePosition.X;
1262 g_yMouse = pmer->dwMousePosition.Y;
1263
1264 if (pmer->dwEventFlags == MOUSE_MOVED)
1265 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001266 /* Ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
Bram Moolenaar071d4272004-06-13 20:20:40 +00001267 * events even when the mouse moves only within a char cell.) */
1268 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1269 return FALSE;
1270 }
1271
1272 /* If no buttons are pressed... */
1273 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1274 {
Bram Moolenaar157d8132018-03-06 17:09:20 +01001275 nButton = MOUSE_RELEASE;
1276
Bram Moolenaar071d4272004-06-13 20:20:40 +00001277 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1278 if (s_fReleased)
Bram Moolenaar157d8132018-03-06 17:09:20 +01001279 {
1280#ifdef FEAT_BEVAL_TERM
1281 /* do return mouse move events when we want them */
1282 if (p_bevalterm)
1283 nButton = MOUSE_DRAG;
1284 else
1285#endif
1286 return FALSE;
1287 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001288
Bram Moolenaar071d4272004-06-13 20:20:40 +00001289 s_fReleased = TRUE;
1290 }
1291 else /* one or more buttons pressed */
1292 {
1293 /* on a 2-button mouse, hold down left and right buttons
1294 * simultaneously to get MIDDLE. */
1295
1296 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1297 {
1298 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1299
1300 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001301 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001302 if (dwLR == LEFT || dwLR == RIGHT)
1303 {
1304 for (;;)
1305 {
1306 /* wait a short time for next input event */
1307 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1308 != WAIT_OBJECT_0)
1309 break;
1310 else
1311 {
1312 DWORD cRecords = 0;
1313 INPUT_RECORD ir;
1314 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1315
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001316 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001317
1318 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1319 || !(pmer2->dwButtonState & LEFT_RIGHT))
1320 break;
1321 else
1322 {
1323 if (pmer2->dwEventFlags != MOUSE_MOVED)
1324 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001325 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001326
1327 return decode_mouse_event(pmer2);
1328 }
1329 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1330 s_yOldMouse == pmer2->dwMousePosition.Y)
1331 {
1332 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001333 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001334
1335 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001336 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001337
1338 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1339 break;
1340 }
1341 else
1342 break;
1343 }
1344 }
1345 }
1346 }
1347 }
1348
1349 if (s_fNextIsMiddle)
1350 {
1351 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1352 ? MOUSE_DRAG : MOUSE_MIDDLE;
1353 s_fNextIsMiddle = FALSE;
1354 }
1355 else if (cButtons == 2 &&
1356 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1357 {
1358 nButton = MOUSE_MIDDLE;
1359
1360 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1361 {
1362 s_fNextIsMiddle = TRUE;
1363 nButton = MOUSE_RELEASE;
1364 }
1365 }
1366 else if ((pmer->dwButtonState & LEFT) == LEFT)
1367 nButton = MOUSE_LEFT;
1368 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1369 nButton = MOUSE_MIDDLE;
1370 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1371 nButton = MOUSE_RIGHT;
1372
1373 if (! s_fReleased && ! s_fNextIsMiddle
1374 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1375 return FALSE;
1376
1377 s_fReleased = s_fNextIsMiddle;
1378 }
1379
1380 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1381 {
1382 /* button pressed or released, without mouse moving */
1383 if (nButton != -1 && nButton != MOUSE_RELEASE)
1384 {
1385 DWORD dwCurrentTime = GetTickCount();
1386
1387 if (s_xOldMouse != g_xMouse
1388 || s_yOldMouse != g_yMouse
1389 || s_nOldButton != nButton
1390 || s_old_topline != curwin->w_topline
1391#ifdef FEAT_DIFF
1392 || s_old_topfill != curwin->w_topfill
1393#endif
1394 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1395 {
1396 s_cClicks = 1;
1397 }
1398 else if (++s_cClicks > 4)
1399 {
1400 s_cClicks = 1;
1401 }
1402
1403 s_dwLastClickTime = dwCurrentTime;
1404 }
1405 }
1406 else if (pmer->dwEventFlags == MOUSE_MOVED)
1407 {
1408 if (nButton != -1 && nButton != MOUSE_RELEASE)
1409 nButton = MOUSE_DRAG;
1410
1411 s_cClicks = 1;
1412 }
1413
1414 if (nButton == -1)
1415 return FALSE;
1416
1417 if (nButton != MOUSE_RELEASE)
1418 s_nOldButton = nButton;
1419
1420 g_nMouseClick = nButton;
1421
1422 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1423 g_nMouseClick |= MOUSE_SHIFT;
1424 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1425 g_nMouseClick |= MOUSE_CTRL;
1426 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1427 g_nMouseClick |= MOUSE_ALT;
1428
1429 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1430 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1431
1432 /* only pass on interesting (i.e., different) mouse events */
1433 if (s_xOldMouse == g_xMouse
1434 && s_yOldMouse == g_yMouse
1435 && s_nOldMouseClick == g_nMouseClick)
1436 {
1437 g_nMouseClick = -1;
1438 return FALSE;
1439 }
1440
1441 s_xOldMouse = g_xMouse;
1442 s_yOldMouse = g_yMouse;
1443 s_old_topline = curwin->w_topline;
1444#ifdef FEAT_DIFF
1445 s_old_topfill = curwin->w_topfill;
1446#endif
1447 s_nOldMouseClick = g_nMouseClick;
1448
1449 return TRUE;
1450}
1451
1452# endif /* FEAT_GUI_W32 */
1453#endif /* FEAT_MOUSE */
1454
1455
1456#ifdef MCH_CURSOR_SHAPE
1457/*
1458 * Set the shape of the cursor.
1459 * 'thickness' can be from 1 (thin) to 99 (block)
1460 */
1461 static void
1462mch_set_cursor_shape(int thickness)
1463{
1464 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1465 ConsoleCursorInfo.dwSize = thickness;
1466 ConsoleCursorInfo.bVisible = s_cursor_visible;
1467
1468 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1469 if (s_cursor_visible)
1470 SetConsoleCursorPosition(g_hConOut, g_coord);
1471}
1472
1473 void
1474mch_update_cursor(void)
1475{
1476 int idx;
1477 int thickness;
1478
1479 /*
1480 * How the cursor is drawn depends on the current mode.
1481 */
1482 idx = get_shape_idx(FALSE);
1483
1484 if (shape_table[idx].shape == SHAPE_BLOCK)
1485 thickness = 99; /* 100 doesn't work on W95 */
1486 else
1487 thickness = shape_table[idx].percentage;
1488 mch_set_cursor_shape(thickness);
1489}
1490#endif
1491
1492#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1493/*
1494 * Handle FOCUS_EVENT.
1495 */
1496 static void
1497handle_focus_event(INPUT_RECORD ir)
1498{
1499 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1500 ui_focus_change((int)g_fJustGotFocus);
1501}
1502
1503/*
1504 * Wait until console input from keyboard or mouse is available,
1505 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001506 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507 * Return TRUE if something is available FALSE if not.
1508 */
1509 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001510WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511{
1512 DWORD dwNow = 0, dwEndTime = 0;
1513 INPUT_RECORD ir;
1514 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001515 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001516#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001517 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001518#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519
1520 if (msec > 0)
1521 /* Wait until the specified time has elapsed. */
1522 dwEndTime = GetTickCount() + msec;
1523 else if (msec < 0)
1524 /* Wait forever. */
1525 dwEndTime = INFINITE;
1526
1527 /* We need to loop until the end of the time period, because
1528 * we might get multiple unusable mouse events in that time.
1529 */
1530 for (;;)
1531 {
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001532 // Only process messages when waiting.
1533 if (msec != 0)
1534 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001535#ifdef MESSAGE_QUEUE
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001536 parse_queued_messages();
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001537#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001538#ifdef FEAT_MZSCHEME
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001539 mzvim_check_threads();
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001540#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541#ifdef FEAT_CLIENTSERVER
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001542 serverProcessPendingMessages();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543#endif
Bram Moolenaared5a9d62018-09-06 13:14:43 +02001544 }
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001545
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546 if (0
1547#ifdef FEAT_MOUSE
1548 || g_nMouseClick != -1
1549#endif
1550#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001551 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552#endif
1553 )
1554 return TRUE;
1555
1556 if (msec > 0)
1557 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001558 /* If the specified wait time has passed, return. Beware that
1559 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001561 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001562 break;
1563 }
1564 if (msec != 0)
1565 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001566 DWORD dwWaitTime = dwEndTime - dwNow;
1567
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001568#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001569 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001570 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001571 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001572 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001573 /* If there is readahead then parse_queued_messages() timed out
1574 * and we should call it again soon. */
1575 if (channel_any_readahead())
1576 dwWaitTime = 10;
1577 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001578#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001579#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001580 if (p_beval && dwWaitTime > 100)
1581 /* The 'balloonexpr' may indirectly invoke a callback while
1582 * waiting for a character, need to check often. */
1583 dwWaitTime = 100;
1584#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001585#ifdef FEAT_MZSCHEME
1586 if (mzthreads_allowed() && p_mzq > 0
1587 && (msec < 0 || (long)dwWaitTime > p_mzq))
1588 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1589#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001590#ifdef FEAT_TIMERS
1591 {
1592 long due_time;
1593
1594 /* When waiting very briefly don't trigger timers. */
1595 if (dwWaitTime > 10)
1596 {
1597 /* Trigger timers and then get the time in msec until the
1598 * next one is due. Wait up to that time. */
1599 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001600 if (typebuf.tb_change_cnt != tb_change_cnt)
1601 {
1602 /* timer may have used feedkeys() */
1603 return FALSE;
1604 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001605 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1606 dwWaitTime = due_time;
1607 }
1608 }
1609#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610#ifdef FEAT_CLIENTSERVER
1611 /* Wait for either an event on the console input or a message in
1612 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001613 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001614 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001616 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617#endif
1618 continue;
1619 }
1620
1621 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001622 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623
1624#ifdef FEAT_MBYTE_IME
1625 if (State & CMDLINE && msg_row == Rows - 1)
1626 {
1627 CONSOLE_SCREEN_BUFFER_INFO csbi;
1628
1629 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1630 {
1631 if (csbi.dwCursorPosition.Y != msg_row)
1632 {
1633 /* The screen is now messed up, must redraw the
1634 * command line and later all the windows. */
1635 redraw_all_later(CLEAR);
1636 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1637 redrawcmd();
1638 }
1639 }
1640 }
1641#endif
1642
1643 if (cRecords > 0)
1644 {
1645 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1646 {
1647#ifdef FEAT_MBYTE_IME
1648 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1649 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001650 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001651 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1652 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001653 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001654 continue;
1655 }
1656#endif
1657 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1658 NULL, FALSE))
1659 return TRUE;
1660 }
1661
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001662 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663
1664 if (ir.EventType == FOCUS_EVENT)
1665 handle_focus_event(ir);
1666 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
Bram Moolenaarc33ecb22018-02-11 16:40:45 +01001667 {
1668 /* Only call shell_resized() when the size actually change to
1669 * avoid the screen is cleard. */
1670 if (ir.Event.WindowBufferSizeEvent.dwSize.X != Columns
1671 || ir.Event.WindowBufferSizeEvent.dwSize.Y != Rows)
1672 shell_resized();
1673 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674#ifdef FEAT_MOUSE
1675 else if (ir.EventType == MOUSE_EVENT
1676 && decode_mouse_event(&ir.Event.MouseEvent))
1677 return TRUE;
1678#endif
1679 }
1680 else if (msec == 0)
1681 break;
1682 }
1683
1684#ifdef FEAT_CLIENTSERVER
1685 /* Something might have been received while we were waiting. */
1686 if (input_available())
1687 return TRUE;
1688#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001689
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 return FALSE;
1691}
1692
1693#ifndef FEAT_GUI_MSWIN
1694/*
1695 * return non-zero if a character is available
1696 */
1697 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001698mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001700 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001701}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001702
1703# if defined(FEAT_TERMINAL) || defined(PROTO)
1704/*
1705 * Check for any pending input or messages.
1706 */
1707 int
1708mch_check_messages(void)
1709{
1710 return WaitForChar(0L, TRUE);
1711}
1712# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713#endif
1714
1715/*
1716 * Create the console input. Used when reading stdin doesn't work.
1717 */
1718 static void
1719create_conin(void)
1720{
1721 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1722 FILE_SHARE_READ|FILE_SHARE_WRITE,
1723 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001724 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 did_create_conin = TRUE;
1726}
1727
1728/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001729 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001731 static WCHAR
1732tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001734 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735
1736 for (;;)
1737 {
1738 INPUT_RECORD ir;
1739 DWORD cRecords = 0;
1740
1741#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001742 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743 if (input_available())
1744 return 0;
1745# ifdef FEAT_MOUSE
1746 if (g_nMouseClick != -1)
1747 return 0;
1748# endif
1749#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001750 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001751 {
1752 if (did_create_conin)
1753 read_error_exit();
1754 create_conin();
1755 continue;
1756 }
1757
1758 if (ir.EventType == KEY_EVENT)
1759 {
1760 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1761 pmodifiers, TRUE))
1762 return ch;
1763 }
1764 else if (ir.EventType == FOCUS_EVENT)
1765 handle_focus_event(ir);
1766 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1767 shell_resized();
1768#ifdef FEAT_MOUSE
1769 else if (ir.EventType == MOUSE_EVENT)
1770 {
1771 if (decode_mouse_event(&ir.Event.MouseEvent))
1772 return 0;
1773 }
1774#endif
1775 }
1776}
1777#endif /* !FEAT_GUI_W32 */
1778
1779
1780/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001781 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 * Get one or more characters from the keyboard or the mouse.
1783 * If time == 0, do not wait for characters.
1784 * If time == n, wait a short time for characters.
1785 * If time == -1, wait forever for characters.
1786 * Returns the number of characters read into buf.
1787 */
1788 int
1789mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001790 char_u *buf UNUSED,
1791 int maxlen UNUSED,
1792 long time UNUSED,
1793 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794{
1795#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1796
1797 int len;
1798 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799#define TYPEAHEADLEN 20
1800 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1801 static int typeaheadlen = 0;
1802
1803 /* First use any typeahead that was kept because "buf" was too small. */
1804 if (typeaheadlen > 0)
1805 goto theend;
1806
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 if (time >= 0)
1808 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001809 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 }
1812 else /* time == -1, wait forever */
1813 {
1814 mch_set_winsize_now(); /* Allow winsize changes from now on */
1815
Bram Moolenaar3918c952005-03-15 22:34:55 +00001816 /*
1817 * If there is no character available within 2 seconds (default)
1818 * write the autoscript file to disk. Or cause the CursorHold event
1819 * to be triggered.
1820 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001821 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001822 {
Bram Moolenaard35f9712005-12-18 22:02:33 +00001823 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001824 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001825 buf[0] = K_SPECIAL;
1826 buf[1] = KS_EXTRA;
1827 buf[2] = (int)KE_CURSORHOLD;
1828 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001829 }
Bram Moolenaar702517d2005-06-27 22:34:07 +00001830 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831 }
1832 }
1833
1834 /*
1835 * Try to read as many characters as there are, until the buffer is full.
1836 */
1837
1838 /* we will get at least one key. Get more if they are available. */
1839 g_fCBrkPressed = FALSE;
1840
1841#ifdef MCH_WRITE_DUMP
1842 if (fdDump)
1843 fputc('[', fdDump);
1844#endif
1845
1846 /* Keep looping until there is something in the typeahead buffer and more
1847 * to get and still room in the buffer (up to two bytes for a char and
1848 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001849 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 && typeaheadlen + 5 <= TYPEAHEADLEN)
1851 {
1852 if (typebuf_changed(tb_change_cnt))
1853 {
1854 /* "buf" may be invalid now if a client put something in the
1855 * typeahead buffer and "buf" is in the typeahead buffer. */
1856 typeaheadlen = 0;
1857 break;
1858 }
1859#ifdef FEAT_MOUSE
1860 if (g_nMouseClick != -1)
1861 {
1862# ifdef MCH_WRITE_DUMP
1863 if (fdDump)
1864 fprintf(fdDump, "{%02x @ %d, %d}",
1865 g_nMouseClick, g_xMouse, g_yMouse);
1866# endif
1867 typeahead[typeaheadlen++] = ESC + 128;
1868 typeahead[typeaheadlen++] = 'M';
1869 typeahead[typeaheadlen++] = g_nMouseClick;
1870 typeahead[typeaheadlen++] = g_xMouse + '!';
1871 typeahead[typeaheadlen++] = g_yMouse + '!';
1872 g_nMouseClick = -1;
1873 }
1874 else
1875#endif
1876 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001877 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001878 int modifiers = 0;
1879
1880 c = tgetch(&modifiers, &ch2);
1881
1882 if (typebuf_changed(tb_change_cnt))
1883 {
1884 /* "buf" may be invalid now if a client put something in the
1885 * typeahead buffer and "buf" is in the typeahead buffer. */
1886 typeaheadlen = 0;
1887 break;
1888 }
1889
1890 if (c == Ctrl_C && ctrl_c_interrupts)
1891 {
1892#if defined(FEAT_CLIENTSERVER)
1893 trash_input_buf();
1894#endif
1895 got_int = TRUE;
1896 }
1897
1898#ifdef FEAT_MOUSE
1899 if (g_nMouseClick == -1)
1900#endif
1901 {
1902 int n = 1;
1903
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001904#ifdef FEAT_MBYTE
1905 if (ch2 == NUL)
1906 {
1907 int i;
1908 char_u *p;
1909 WCHAR ch[2];
1910
1911 ch[0] = c;
1912 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1913 {
1914 ch[1] = tgetch(&modifiers, &ch2);
1915 n++;
1916 }
1917 p = utf16_to_enc(ch, &n);
1918 if (p != NULL)
1919 {
1920 for (i = 0; i < n; i++)
1921 typeahead[typeaheadlen + i] = p[i];
1922 vim_free(p);
1923 }
1924 }
1925 else
1926#endif
1927 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928 if (ch2 != NUL)
1929 {
Bram Moolenaarfeeb4d02017-12-05 15:14:46 +01001930 if (c == K_NUL && (ch2 & 0xff00) != 0)
1931 {
1932 /* fAnsiKey with modifier keys */
1933 typeahead[typeaheadlen + n] = (char_u)ch2;
1934 n++;
1935 }
1936 else
1937 {
1938 typeahead[typeaheadlen + n] = 3;
1939 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1940 n += 2;
1941 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001942 }
1943
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944 /* Use the ALT key to set the 8th bit of the character
1945 * when it's one byte, the 8th bit isn't set yet and not
1946 * using a double-byte encoding (would become a lead
1947 * byte). */
1948 if ((modifiers & MOD_MASK_ALT)
1949 && n == 1
1950 && (typeahead[typeaheadlen] & 0x80) == 0
1951#ifdef FEAT_MBYTE
1952 && !enc_dbcs
1953#endif
1954 )
1955 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001956#ifdef FEAT_MBYTE
1957 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1958 typeahead + typeaheadlen);
1959#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001961#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962 modifiers &= ~MOD_MASK_ALT;
1963 }
1964
1965 if (modifiers != 0)
1966 {
1967 /* Prepend modifiers to the character. */
1968 mch_memmove(typeahead + typeaheadlen + 3,
1969 typeahead + typeaheadlen, n);
1970 typeahead[typeaheadlen++] = K_SPECIAL;
1971 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1972 typeahead[typeaheadlen++] = modifiers;
1973 }
1974
1975 typeaheadlen += n;
1976
1977#ifdef MCH_WRITE_DUMP
1978 if (fdDump)
1979 fputc(c, fdDump);
1980#endif
1981 }
1982 }
1983 }
1984
1985#ifdef MCH_WRITE_DUMP
1986 if (fdDump)
1987 {
1988 fputs("]\n", fdDump);
1989 fflush(fdDump);
1990 }
1991#endif
1992
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993theend:
1994 /* Move typeahead to "buf", as much as fits. */
1995 len = 0;
1996 while (len < maxlen && typeaheadlen > 0)
1997 {
1998 buf[len++] = typeahead[0];
1999 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
2000 }
2001 return len;
2002
2003#else /* FEAT_GUI_W32 */
2004 return 0;
2005#endif /* FEAT_GUI_W32 */
2006}
2007
Bram Moolenaar82881492012-11-20 16:53:39 +01002008#ifndef PROTO
2009# ifndef __MINGW32__
2010# include <shellapi.h> /* required for FindExecutable() */
2011# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002012#endif
2013
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002014/*
Bram Moolenaar43663192017-03-05 14:29:12 +01002015 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
2016 * If "use_path" is FALSE: Return TRUE if "name" exists.
2017 * When returning TRUE and "path" is not NULL save the path and set "*path" to
2018 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002019 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002020 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002021 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01002022executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002024 char *dum;
2025 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002026 char *curpath, *newpath;
2027 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028
Bram Moolenaar43663192017-03-05 14:29:12 +01002029 if (!use_path)
2030 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002031 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01002032 {
2033 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01002034 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01002035 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01002036 *path = vim_strsave((char_u *)name);
2037 else
2038 *path = FullName_save((char_u *)name, FALSE);
2039 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002040 return TRUE;
2041 }
2042 return FALSE;
2043 }
2044
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002045#ifdef FEAT_MBYTE
2046 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002048 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002049 WCHAR fnamew[_MAX_PATH];
2050 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002051 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002052
2053 if (p != NULL)
2054 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002055 wcurpath = _wgetenv(L"PATH");
2056 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
2057 * sizeof(WCHAR));
2058 if (wnewpath == NULL)
2059 return FALSE;
2060 wcscpy(wnewpath, L".;");
2061 wcscat(wnewpath, wcurpath);
2062 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
2063 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002064 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002065 if (n == 0)
2066 return FALSE;
2067 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
2068 return FALSE;
2069 if (path != NULL)
2070 *path = utf16_to_enc(fnamew, NULL);
2071 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002072 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002074#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02002075
2076 curpath = getenv("PATH");
2077 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
2078 if (newpath == NULL)
2079 return FALSE;
2080 STRCPY(newpath, ".;");
2081 STRCAT(newpath, curpath);
2082 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2083 vim_free(newpath);
2084 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002085 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002086 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002087 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002088 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002089 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002090 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091}
2092
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002093#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002094 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002095/*
2096 * Bad parameter handler.
2097 *
2098 * Certain MS CRT functions will intentionally crash when passed invalid
2099 * parameters to highlight possible security holes. Setting this function as
2100 * the bad parameter handler will prevent the crash.
2101 *
2102 * In debug builds the parameters contain CRT information that might help track
2103 * down the source of a problem, but in non-debug builds the arguments are all
2104 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2105 * worth allowing these to make debugging of issues easier.
2106 */
2107 static void
2108bad_param_handler(const wchar_t *expression,
2109 const wchar_t *function,
2110 const wchar_t *file,
2111 unsigned int line,
2112 uintptr_t pReserved)
2113{
2114}
2115
2116# define SET_INVALID_PARAM_HANDLER \
2117 ((void)_set_invalid_parameter_handler(bad_param_handler))
2118#else
2119# define SET_INVALID_PARAM_HANDLER
2120#endif
2121
Bram Moolenaar071d4272004-06-13 20:20:40 +00002122#ifdef FEAT_GUI_W32
2123
2124/*
2125 * GUI version of mch_init().
2126 */
2127 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002128mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002129{
2130#ifndef __MINGW32__
2131 extern int _fmode;
2132#endif
2133
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002134 /* Silently handle invalid parameters to CRT functions */
2135 SET_INVALID_PARAM_HANDLER;
2136
Bram Moolenaar071d4272004-06-13 20:20:40 +00002137 /* Let critical errors result in a failure, not in a dialog box. Required
2138 * for the timestamp test to work on removed floppies. */
2139 SetErrorMode(SEM_FAILCRITICALERRORS);
2140
2141 _fmode = O_BINARY; /* we do our own CR-LF translation */
2142
2143 /* Specify window size. Is there a place to get the default from? */
2144 Rows = 25;
2145 Columns = 80;
2146
2147 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002148 {
2149 char_u vimrun_location[_MAX_PATH + 4];
2150
2151 /* First try in same directory as gvim.exe */
2152 STRCPY(vimrun_location, exe_name);
2153 STRCPY(gettail(vimrun_location), "vimrun.exe");
2154 if (mch_getperm(vimrun_location) >= 0)
2155 {
2156 if (*skiptowhite(vimrun_location) != NUL)
2157 {
2158 /* Enclose path with white space in double quotes. */
2159 mch_memmove(vimrun_location + 1, vimrun_location,
2160 STRLEN(vimrun_location) + 1);
2161 *vimrun_location = '"';
2162 STRCPY(gettail(vimrun_location), "vimrun\" ");
2163 }
2164 else
2165 STRCPY(gettail(vimrun_location), "vimrun ");
2166
2167 vimrun_path = (char *)vim_strsave(vimrun_location);
2168 s_dont_use_vimrun = FALSE;
2169 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002170 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 s_dont_use_vimrun = FALSE;
2172
2173 /* Don't give the warning for a missing vimrun.exe right now, but only
2174 * when vimrun was supposed to be used. Don't bother people that do
2175 * not need vimrun.exe. */
2176 if (s_dont_use_vimrun)
2177 need_vimrun_warning = TRUE;
2178 }
2179
2180 /*
2181 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2182 * Otherwise the default "findstr /n" is used.
2183 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002184 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002185 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2186
2187#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002188 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189#endif
2190}
2191
2192
2193#else /* FEAT_GUI_W32 */
2194
2195#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2196#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2197
2198/*
2199 * ClearConsoleBuffer()
2200 * Description:
2201 * Clears the entire contents of the console screen buffer, using the
2202 * specified attribute.
2203 * Returns:
2204 * TRUE on success
2205 */
2206 static BOOL
2207ClearConsoleBuffer(WORD wAttribute)
2208{
2209 CONSOLE_SCREEN_BUFFER_INFO csbi;
2210 COORD coord;
2211 DWORD NumCells, dummy;
2212
2213 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2214 return FALSE;
2215
2216 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2217 coord.X = 0;
2218 coord.Y = 0;
2219 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2220 coord, &dummy))
2221 {
2222 return FALSE;
2223 }
2224 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2225 coord, &dummy))
2226 {
2227 return FALSE;
2228 }
2229
2230 return TRUE;
2231}
2232
2233/*
2234 * FitConsoleWindow()
2235 * Description:
2236 * Checks if the console window will fit within given buffer dimensions.
2237 * Also, if requested, will shrink the window to fit.
2238 * Returns:
2239 * TRUE on success
2240 */
2241 static BOOL
2242FitConsoleWindow(
2243 COORD dwBufferSize,
2244 BOOL WantAdjust)
2245{
2246 CONSOLE_SCREEN_BUFFER_INFO csbi;
2247 COORD dwWindowSize;
2248 BOOL NeedAdjust = FALSE;
2249
2250 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2251 {
2252 /*
2253 * A buffer resize will fail if the current console window does
2254 * not lie completely within that buffer. To avoid this, we might
2255 * have to move and possibly shrink the window.
2256 */
2257 if (csbi.srWindow.Right >= dwBufferSize.X)
2258 {
2259 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2260 if (dwWindowSize.X > dwBufferSize.X)
2261 dwWindowSize.X = dwBufferSize.X;
2262 csbi.srWindow.Right = dwBufferSize.X - 1;
2263 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2264 NeedAdjust = TRUE;
2265 }
2266 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2267 {
2268 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2269 if (dwWindowSize.Y > dwBufferSize.Y)
2270 dwWindowSize.Y = dwBufferSize.Y;
2271 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2272 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2273 NeedAdjust = TRUE;
2274 }
2275 if (NeedAdjust && WantAdjust)
2276 {
2277 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2278 return FALSE;
2279 }
2280 return TRUE;
2281 }
2282
2283 return FALSE;
2284}
2285
2286typedef struct ConsoleBufferStruct
2287{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002288 BOOL IsValid;
2289 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002290 PCHAR_INFO Buffer;
2291 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002292 PSMALL_RECT Regions;
2293 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002294} ConsoleBuffer;
2295
2296/*
2297 * SaveConsoleBuffer()
2298 * Description:
2299 * Saves important information about the console buffer, including the
2300 * actual buffer contents. The saved information is suitable for later
2301 * restoration by RestoreConsoleBuffer().
2302 * Returns:
2303 * TRUE if all information was saved; FALSE otherwise
2304 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2305 */
2306 static BOOL
2307SaveConsoleBuffer(
2308 ConsoleBuffer *cb)
2309{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002310 DWORD NumCells;
2311 COORD BufferCoord;
2312 SMALL_RECT ReadRegion;
2313 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002314 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002315
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316 if (cb == NULL)
2317 return FALSE;
2318
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002319 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320 {
2321 cb->IsValid = FALSE;
2322 return FALSE;
2323 }
2324 cb->IsValid = TRUE;
2325
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002326 /*
2327 * Allocate a buffer large enough to hold the entire console screen
2328 * buffer. If this ConsoleBuffer structure has already been initialized
2329 * with a buffer of the correct size, then just use that one.
2330 */
2331 if (!cb->IsValid || cb->Buffer == NULL ||
2332 cb->BufferSize.X != cb->Info.dwSize.X ||
2333 cb->BufferSize.Y != cb->Info.dwSize.Y)
2334 {
2335 cb->BufferSize.X = cb->Info.dwSize.X;
2336 cb->BufferSize.Y = cb->Info.dwSize.Y;
2337 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2338 vim_free(cb->Buffer);
2339 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2340 if (cb->Buffer == NULL)
2341 return FALSE;
2342 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002343
2344 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002345 * We will now copy the console screen buffer into our buffer.
2346 * ReadConsoleOutput() seems to be limited as far as how much you
2347 * can read at a time. Empirically, this number seems to be about
2348 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2349 * in chunks until it is all copied. The chunks will all have the
2350 * same horizontal characteristics, so initialize them now. The
2351 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002353 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002354 ReadRegion.Left = 0;
2355 ReadRegion.Right = cb->Info.dwSize.X - 1;
2356 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002357
2358 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2359 if (cb->Regions == NULL || numregions != cb->NumRegions)
2360 {
2361 cb->NumRegions = numregions;
2362 vim_free(cb->Regions);
2363 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2364 if (cb->Regions == NULL)
2365 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002366 VIM_CLEAR(cb->Buffer);
Bram Moolenaar444fda22017-08-11 20:37:00 +02002367 return FALSE;
2368 }
2369 }
2370
2371 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002372 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002373 /*
2374 * Read into position (0, Y) in our buffer.
2375 */
2376 BufferCoord.Y = Y;
2377 /*
2378 * Read the region whose top left corner is (0, Y) and whose bottom
2379 * right corner is (width - 1, Y + Y_incr - 1). This should define
2380 * a region of size width by Y_incr. Don't worry if this region is
2381 * too large for the remaining buffer; it will be cropped.
2382 */
2383 ReadRegion.Top = Y;
2384 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002385 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002386 cb->Buffer, /* our buffer */
2387 cb->BufferSize, /* dimensions of our buffer */
2388 BufferCoord, /* offset in our buffer */
2389 &ReadRegion)) /* region to save */
2390 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01002391 VIM_CLEAR(cb->Buffer);
2392 VIM_CLEAR(cb->Regions);
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002393 return FALSE;
2394 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002395 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396 }
2397
2398 return TRUE;
2399}
2400
2401/*
2402 * RestoreConsoleBuffer()
2403 * Description:
2404 * Restores important information about the console buffer, including the
2405 * actual buffer contents, if desired. The information to restore is in
2406 * the same format used by SaveConsoleBuffer().
2407 * Returns:
2408 * TRUE on success
2409 */
2410 static BOOL
2411RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002412 ConsoleBuffer *cb,
2413 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002415 COORD BufferCoord;
2416 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002417 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418
2419 if (cb == NULL || !cb->IsValid)
2420 return FALSE;
2421
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002422 /*
2423 * Before restoring the buffer contents, clear the current buffer, and
2424 * restore the cursor position and window information. Doing this now
2425 * prevents old buffer contents from "flashing" onto the screen.
2426 */
2427 if (RestoreScreen)
2428 ClearConsoleBuffer(cb->Info.wAttributes);
2429
2430 FitConsoleWindow(cb->Info.dwSize, TRUE);
2431 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2432 return FALSE;
2433 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2434 return FALSE;
2435
2436 if (!RestoreScreen)
2437 {
2438 /*
2439 * No need to restore the screen buffer contents, so we're done.
2440 */
2441 return TRUE;
2442 }
2443
2444 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2445 return FALSE;
2446 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2447 return FALSE;
2448
2449 /*
2450 * Restore the screen buffer contents.
2451 */
2452 if (cb->Buffer != NULL)
2453 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002454 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002455 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002456 BufferCoord.X = cb->Regions[i].Left;
2457 BufferCoord.Y = cb->Regions[i].Top;
2458 WriteRegion = cb->Regions[i];
2459 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2460 cb->Buffer, /* our buffer */
2461 cb->BufferSize, /* dimensions of our buffer */
2462 BufferCoord, /* offset in our buffer */
2463 &WriteRegion)) /* region to restore */
2464 {
2465 return FALSE;
2466 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002467 }
2468 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469
2470 return TRUE;
2471}
2472
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002473#define FEAT_RESTORE_ORIG_SCREEN
2474#ifdef FEAT_RESTORE_ORIG_SCREEN
2475static ConsoleBuffer g_cbOrig = { 0 };
2476#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477static ConsoleBuffer g_cbNonTermcap = { 0 };
2478static ConsoleBuffer g_cbTermcap = { 0 };
2479
2480#ifdef FEAT_TITLE
2481#ifdef __BORLANDC__
2482typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2483#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002484typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485#endif
2486char g_szOrigTitle[256] = { 0 };
2487HWND g_hWnd = NULL; /* also used in os_mswin.c */
2488static HICON g_hOrigIconSmall = NULL;
2489static HICON g_hOrigIcon = NULL;
2490static HICON g_hVimIcon = NULL;
2491static BOOL g_fCanChangeIcon = FALSE;
2492
2493/* ICON* are not defined in VC++ 4.0 */
2494#ifndef ICON_SMALL
2495#define ICON_SMALL 0
2496#endif
2497#ifndef ICON_BIG
2498#define ICON_BIG 1
2499#endif
2500/*
2501 * GetConsoleIcon()
2502 * Description:
2503 * Attempts to retrieve the small icon and/or the big icon currently in
2504 * use by a given window.
2505 * Returns:
2506 * TRUE on success
2507 */
2508 static BOOL
2509GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002510 HWND hWnd,
2511 HICON *phIconSmall,
2512 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513{
2514 if (hWnd == NULL)
2515 return FALSE;
2516
2517 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002518 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2519 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002521 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2522 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 return TRUE;
2524}
2525
2526/*
2527 * SetConsoleIcon()
2528 * Description:
2529 * Attempts to change the small icon and/or the big icon currently in
2530 * use by a given window.
2531 * Returns:
2532 * TRUE on success
2533 */
2534 static BOOL
2535SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002536 HWND hWnd,
2537 HICON hIconSmall,
2538 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 if (hWnd == NULL)
2541 return FALSE;
2542
2543 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002544 SendMessage(hWnd, WM_SETICON,
2545 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002547 SendMessage(hWnd, WM_SETICON,
2548 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549 return TRUE;
2550}
2551
2552/*
2553 * SaveConsoleTitleAndIcon()
2554 * Description:
2555 * Saves the current console window title in g_szOrigTitle, for later
2556 * restoration. Also, attempts to obtain a handle to the console window,
2557 * and use it to save the small and big icons currently in use by the
2558 * console window. This is not always possible on some versions of Windows;
2559 * nor is it possible when running Vim remotely using Telnet (since the
2560 * console window the user sees is owned by a remote process).
2561 */
2562 static void
2563SaveConsoleTitleAndIcon(void)
2564{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565 /* Save the original title. */
2566 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2567 return;
2568
2569 /*
2570 * Obtain a handle to the console window using GetConsoleWindow() from
2571 * KERNEL32.DLL; we need to handle in order to change the window icon.
2572 * This function only exists on NT-based Windows, starting with Windows
2573 * 2000. On older operating systems, we can't change the window icon
2574 * anyway.
2575 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002576 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 if (g_hWnd == NULL)
2578 return;
2579
2580 /* Save the original console window icon. */
2581 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2582 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2583 return;
2584
2585 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002586 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002587 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002588 if (g_hVimIcon != NULL)
2589 g_fCanChangeIcon = TRUE;
2590}
2591#endif
2592
2593static int g_fWindInitCalled = FALSE;
2594static int g_fTermcapMode = FALSE;
2595static CONSOLE_CURSOR_INFO g_cci;
2596static DWORD g_cmodein = 0;
2597static DWORD g_cmodeout = 0;
2598
2599/*
2600 * non-GUI version of mch_init().
2601 */
2602 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002603mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002605#ifndef FEAT_RESTORE_ORIG_SCREEN
2606 CONSOLE_SCREEN_BUFFER_INFO csbi;
2607#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608#ifndef __MINGW32__
2609 extern int _fmode;
2610#endif
2611
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002612 /* Silently handle invalid parameters to CRT functions */
2613 SET_INVALID_PARAM_HANDLER;
2614
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615 /* Let critical errors result in a failure, not in a dialog box. Required
2616 * for the timestamp test to work on removed floppies. */
2617 SetErrorMode(SEM_FAILCRITICALERRORS);
2618
2619 _fmode = O_BINARY; /* we do our own CR-LF translation */
2620 out_flush();
2621
2622 /* Obtain handles for the standard Console I/O devices */
2623 if (read_cmd_fd == 0)
2624 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2625 else
2626 create_conin();
2627 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2628
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002629#ifdef FEAT_RESTORE_ORIG_SCREEN
2630 /* Save the initial console buffer for later restoration */
2631 SaveConsoleBuffer(&g_cbOrig);
2632 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2633#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002635 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2636 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2637#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002638 if (cterm_normal_fg_color == 0)
2639 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2640 if (cterm_normal_bg_color == 0)
2641 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2642
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02002643 // Fg and Bg color index nunmber at startup
2644 g_color_index_fg = g_attrDefault & 0xf;
2645 g_color_index_bg = (g_attrDefault >> 4) & 0xf;
2646
Bram Moolenaar071d4272004-06-13 20:20:40 +00002647 /* set termcap codes to current text attributes */
2648 update_tcap(g_attrCurrent);
2649
2650 GetConsoleCursorInfo(g_hConOut, &g_cci);
2651 GetConsoleMode(g_hConIn, &g_cmodein);
2652 GetConsoleMode(g_hConOut, &g_cmodeout);
2653
2654#ifdef FEAT_TITLE
2655 SaveConsoleTitleAndIcon();
2656 /*
2657 * Set both the small and big icons of the console window to Vim's icon.
2658 * Note that Vim presently only has one size of icon (32x32), but it
2659 * automatically gets scaled down to 16x16 when setting the small icon.
2660 */
2661 if (g_fCanChangeIcon)
2662 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2663#endif
2664
2665 ui_get_shellsize();
2666
2667#ifdef MCH_WRITE_DUMP
2668 fdDump = fopen("dump", "wt");
2669
2670 if (fdDump)
2671 {
2672 time_t t;
2673
2674 time(&t);
2675 fputs(ctime(&t), fdDump);
2676 fflush(fdDump);
2677 }
2678#endif
2679
2680 g_fWindInitCalled = TRUE;
2681
2682#ifdef FEAT_MOUSE
2683 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2684#endif
2685
2686#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002687 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002688#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002689
2690 vtp_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002691}
2692
2693/*
2694 * non-GUI version of mch_exit().
2695 * Shut down and exit with status `r'
2696 * Careful: mch_exit() may be called before mch_init()!
2697 */
2698 void
2699mch_exit(int r)
2700{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002701 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702
Bram Moolenaarcafafb32018-02-22 21:07:09 +01002703 vtp_exit();
2704
Bram Moolenaar955f1982017-02-05 15:10:51 +01002705 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002706 if (g_fWindInitCalled)
2707 settmode(TMODE_COOK);
2708
2709 ml_close_all(TRUE); /* remove all memfiles */
2710
2711 if (g_fWindInitCalled)
2712 {
2713#ifdef FEAT_TITLE
Bram Moolenaar40385db2018-08-07 22:31:44 +02002714 mch_restore_title(SAVE_RESTORE_BOTH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715 /*
2716 * Restore both the small and big icons of the console window to
2717 * what they were at startup. Don't do this when the window is
2718 * closed, Vim would hang here.
2719 */
2720 if (g_fCanChangeIcon && !g_fForceExit)
2721 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2722#endif
2723
2724#ifdef MCH_WRITE_DUMP
2725 if (fdDump)
2726 {
2727 time_t t;
2728
2729 time(&t);
2730 fputs(ctime(&t), fdDump);
2731 fclose(fdDump);
2732 }
2733 fdDump = NULL;
2734#endif
2735 }
2736
2737 SetConsoleCursorInfo(g_hConOut, &g_cci);
2738 SetConsoleMode(g_hConIn, g_cmodein);
2739 SetConsoleMode(g_hConOut, g_cmodeout);
2740
2741#ifdef DYNAMIC_GETTEXT
2742 dyn_libintl_end();
2743#endif
2744
2745 exit(r);
2746}
2747#endif /* !FEAT_GUI_W32 */
2748
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749/*
2750 * Do we have an interactive window?
2751 */
2752 int
2753mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002754 int argc UNUSED,
2755 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002756{
2757 get_exe_name();
2758
2759#ifdef FEAT_GUI_W32
2760 return OK; /* GUI always has a tty */
2761#else
2762 if (isatty(1))
2763 return OK;
2764 return FAIL;
2765#endif
2766}
2767
2768
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002769#ifdef FEAT_MBYTE
2770/*
2771 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2772 * if it already exists. When "len" is > 0, also expand short to long
2773 * filenames.
2774 * Return FAIL if wide functions are not available, OK otherwise.
2775 * NOTE: much of this is identical to fname_case(), keep in sync!
2776 */
2777 static int
2778fname_casew(
2779 WCHAR *name,
2780 int len)
2781{
2782 WCHAR szTrueName[_MAX_PATH + 2];
2783 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2784 WCHAR *ptrue, *ptruePrev;
2785 WCHAR *porig, *porigPrev;
2786 int flen;
2787 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002788 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002789 int c;
2790 int slen;
2791
2792 flen = (int)wcslen(name);
2793 if (flen > _MAX_PATH)
2794 return OK;
2795
2796 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2797
2798 /* Build the new name in szTrueName[] one component at a time. */
2799 porig = name;
2800 ptrue = szTrueName;
2801
2802 if (iswalpha(porig[0]) && porig[1] == L':')
2803 {
2804 /* copy leading drive letter */
2805 *ptrue++ = *porig++;
2806 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002807 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002808 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002809
2810 while (*porig != NUL)
2811 {
2812 /* copy \ characters */
2813 while (*porig == psepc)
2814 *ptrue++ = *porig++;
2815
2816 ptruePrev = ptrue;
2817 porigPrev = porig;
2818 while (*porig != NUL && *porig != psepc)
2819 {
2820 *ptrue++ = *porig++;
2821 }
2822 *ptrue = NUL;
2823
2824 /* To avoid a slow failure append "\*" when searching a directory,
2825 * server or network share. */
2826 wcscpy(szTrueNameTemp, szTrueName);
2827 slen = (int)wcslen(szTrueNameTemp);
2828 if (*porig == psepc && slen + 2 < _MAX_PATH)
2829 wcscpy(szTrueNameTemp + slen, L"\\*");
2830
2831 /* Skip "", "." and "..". */
2832 if (ptrue > ptruePrev
2833 && (ptruePrev[0] != L'.'
2834 || (ptruePrev[1] != NUL
2835 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2836 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2837 != INVALID_HANDLE_VALUE)
2838 {
2839 c = *porig;
2840 *porig = NUL;
2841
2842 /* Only use the match when it's the same name (ignoring case) or
2843 * expansion is allowed and there is a match with the short name
2844 * and there is enough room. */
2845 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2846 || (len > 0
2847 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2848 && (int)(ptruePrev - szTrueName)
2849 + (int)wcslen(fb.cFileName) < len)))
2850 {
2851 wcscpy(ptruePrev, fb.cFileName);
2852
2853 /* Look for exact match and prefer it if found. Must be a
2854 * long name, otherwise there would be only one match. */
2855 while (FindNextFileW(hFind, &fb))
2856 {
2857 if (*fb.cAlternateFileName != NUL
2858 && (wcscoll(porigPrev, fb.cFileName) == 0
2859 || (len > 0
2860 && (_wcsicoll(porigPrev,
2861 fb.cAlternateFileName) == 0
2862 && (int)(ptruePrev - szTrueName)
2863 + (int)wcslen(fb.cFileName) < len))))
2864 {
2865 wcscpy(ptruePrev, fb.cFileName);
2866 break;
2867 }
2868 }
2869 }
2870 FindClose(hFind);
2871 *porig = c;
2872 ptrue = ptruePrev + wcslen(ptruePrev);
2873 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002874 }
2875
2876 wcscpy(name, szTrueName);
2877 return OK;
2878}
2879#endif
2880
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881/*
2882 * fname_case(): Set the case of the file name, if it already exists.
2883 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002884 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 */
2886 void
2887fname_case(
2888 char_u *name,
2889 int len)
2890{
2891 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002892 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893 char *ptrue, *ptruePrev;
2894 char *porig, *porigPrev;
2895 int flen;
2896 WIN32_FIND_DATA fb;
2897 HANDLE hFind;
2898 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002899 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002901 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002902 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903 return;
2904
2905 slash_adjust(name);
2906
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002907#ifdef FEAT_MBYTE
2908 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2909 {
2910 WCHAR *p = enc_to_utf16(name, NULL);
2911
2912 if (p != NULL)
2913 {
2914 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002915 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002916
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002917 wcsncpy(buf, p, _MAX_PATH);
2918 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002919 vim_free(p);
2920
2921 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2922 {
2923 q = utf16_to_enc(buf, NULL);
2924 if (q != NULL)
2925 {
2926 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2927 vim_free(q);
2928 return;
2929 }
2930 }
2931 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002932 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002933 }
2934#endif
2935
2936 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2937 * So we should check this after calling wide function. */
2938 if (flen > _MAX_PATH)
2939 return;
2940
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002942 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943 ptrue = szTrueName;
2944
2945 if (isalpha(porig[0]) && porig[1] == ':')
2946 {
2947 /* copy leading drive letter */
2948 *ptrue++ = *porig++;
2949 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002951 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952
2953 while (*porig != NUL)
2954 {
2955 /* copy \ characters */
2956 while (*porig == psepc)
2957 *ptrue++ = *porig++;
2958
2959 ptruePrev = ptrue;
2960 porigPrev = porig;
2961 while (*porig != NUL && *porig != psepc)
2962 {
2963#ifdef FEAT_MBYTE
2964 int l;
2965
2966 if (enc_dbcs)
2967 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002968 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 while (--l >= 0)
2970 *ptrue++ = *porig++;
2971 }
2972 else
2973#endif
2974 *ptrue++ = *porig++;
2975 }
2976 *ptrue = NUL;
2977
Bram Moolenaar464c9252010-10-13 20:37:41 +02002978 /* To avoid a slow failure append "\*" when searching a directory,
2979 * server or network share. */
2980 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002981 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002982 if (*porig == psepc && slen + 2 < _MAX_PATH)
2983 STRCPY(szTrueNameTemp + slen, "\\*");
2984
Bram Moolenaar071d4272004-06-13 20:20:40 +00002985 /* Skip "", "." and "..". */
2986 if (ptrue > ptruePrev
2987 && (ptruePrev[0] != '.'
2988 || (ptruePrev[1] != NUL
2989 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002990 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991 != INVALID_HANDLE_VALUE)
2992 {
2993 c = *porig;
2994 *porig = NUL;
2995
2996 /* Only use the match when it's the same name (ignoring case) or
2997 * expansion is allowed and there is a match with the short name
2998 * and there is enough room. */
2999 if (_stricoll(porigPrev, fb.cFileName) == 0
3000 || (len > 0
3001 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
3002 && (int)(ptruePrev - szTrueName)
3003 + (int)strlen(fb.cFileName) < len)))
3004 {
3005 STRCPY(ptruePrev, fb.cFileName);
3006
3007 /* Look for exact match and prefer it if found. Must be a
3008 * long name, otherwise there would be only one match. */
3009 while (FindNextFile(hFind, &fb))
3010 {
3011 if (*fb.cAlternateFileName != NUL
3012 && (strcoll(porigPrev, fb.cFileName) == 0
3013 || (len > 0
3014 && (_stricoll(porigPrev,
3015 fb.cAlternateFileName) == 0
3016 && (int)(ptruePrev - szTrueName)
3017 + (int)strlen(fb.cFileName) < len))))
3018 {
3019 STRCPY(ptruePrev, fb.cFileName);
3020 break;
3021 }
3022 }
3023 }
3024 FindClose(hFind);
3025 *porig = c;
3026 ptrue = ptruePrev + strlen(ptruePrev);
3027 }
3028 }
3029
3030 STRCPY(name, szTrueName);
3031}
3032
3033
3034/*
3035 * Insert user name in s[len].
3036 */
3037 int
3038mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003039 char_u *s,
3040 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041{
Bram Moolenaar41a09032007-10-01 18:34:34 +00003042 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043 DWORD cch = sizeof szUserName;
3044
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003045#ifdef FEAT_MBYTE
3046 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3047 {
3048 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
3049 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
3050
3051 if (GetUserNameW(wszUserName, &wcch))
3052 {
3053 char_u *p = utf16_to_enc(wszUserName, NULL);
3054
3055 if (p != NULL)
3056 {
3057 vim_strncpy(s, p, len - 1);
3058 vim_free(p);
3059 return OK;
3060 }
3061 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01003062 }
3063#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 if (GetUserName(szUserName, &cch))
3065 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003066 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067 return OK;
3068 }
3069 s[0] = NUL;
3070 return FAIL;
3071}
3072
3073
3074/*
3075 * Insert host name in s[len].
3076 */
3077 void
3078mch_get_host_name(
3079 char_u *s,
3080 int len)
3081{
3082 DWORD cch = len;
3083
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003084#ifdef FEAT_MBYTE
3085 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3086 {
3087 WCHAR wszHostName[256 + 1];
3088 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3089
3090 if (GetComputerNameW(wszHostName, &wcch))
3091 {
3092 char_u *p = utf16_to_enc(wszHostName, NULL);
3093
3094 if (p != NULL)
3095 {
3096 vim_strncpy(s, p, len - 1);
3097 vim_free(p);
3098 return;
3099 }
3100 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003101 }
3102#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003103 if (!GetComputerName((LPSTR)s, &cch))
3104 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003105}
3106
3107
3108/*
3109 * return process ID
3110 */
3111 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003112mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113{
3114 return (long)GetCurrentProcessId();
3115}
3116
3117
3118/*
3119 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3120 * Return OK for success, FAIL for failure.
3121 */
3122 int
3123mch_dirname(
3124 char_u *buf,
3125 int len)
3126{
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003127 char_u abuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003128 DWORD lfnlen;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003129
Bram Moolenaar071d4272004-06-13 20:20:40 +00003130 /*
3131 * Originally this was:
3132 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3133 * But the Win32s known bug list says that getcwd() doesn't work
3134 * so use the Win32 system call instead. <Negri>
3135 */
3136#ifdef FEAT_MBYTE
3137 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3138 {
3139 WCHAR wbuf[_MAX_PATH + 1];
3140
3141 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3142 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003143 WCHAR wcbuf[_MAX_PATH + 1];
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003144 char_u *p = NULL;
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003145
3146 if (GetLongPathNameW(wbuf, wcbuf, _MAX_PATH) != 0)
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003147 {
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003148 p = utf16_to_enc(wcbuf, NULL);
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003149 if (STRLEN(p) >= (size_t)len)
3150 {
3151 // long path name is too long, fall back to short one
3152 vim_free(p);
3153 p = NULL;
3154 }
3155 }
3156 if (p == NULL)
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003157 p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158
3159 if (p != NULL)
3160 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003161 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003162 vim_free(p);
3163 return OK;
3164 }
3165 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003166 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167 }
3168#endif
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003169 if (GetCurrentDirectory(len, (LPSTR)buf) == 0)
3170 return FAIL;
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003171 lfnlen = GetLongPathNameA((LPCSTR)buf, (LPSTR)abuf, _MAX_PATH);
3172 if (lfnlen == 0 || lfnlen >= (DWORD)len)
3173 // Failed to get long path name or it's too long: fall back to the
3174 // short path name.
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003175 return OK;
3176
Bram Moolenaarcea1f9e2018-08-19 14:38:42 +02003177 STRCPY(buf, abuf);
Bram Moolenaar3b9fcfc2018-08-18 20:20:27 +02003178 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179}
3180
3181/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003182 * Get file permissions for "name".
3183 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184 */
3185 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003186mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003188 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003189 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003191 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003192 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193}
3194
3195
3196/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003197 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003198 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003199 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 */
3201 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003202mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003204 long n = -1;
3205
Bram Moolenaar071d4272004-06-13 20:20:40 +00003206#ifdef FEAT_MBYTE
3207 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3208 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003209 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210
3211 if (p != NULL)
3212 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003213 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003214 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003215 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003216 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217 }
3218 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003219 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003220#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003221 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003222 if (n == -1)
3223 return FAIL;
3224
3225 win32_set_archive(name);
3226
3227 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228}
3229
3230/*
3231 * Set hidden flag for "name".
3232 */
3233 void
3234mch_hide(char_u *name)
3235{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003236 int attrs = win32_getattrs(name);
3237 if (attrs == -1)
3238 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003239
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003240 attrs |= FILE_ATTRIBUTE_HIDDEN;
3241 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242}
3243
3244/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003245 * Return TRUE if file "name" exists and is hidden.
3246 */
3247 int
3248mch_ishidden(char_u *name)
3249{
3250 int f = win32_getattrs(name);
3251
3252 if (f == -1)
3253 return FALSE; /* file does not exist at all */
3254
3255 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3256}
3257
3258/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 * return TRUE if "name" is a directory
3260 * return FALSE if "name" is not a directory or upon error
3261 */
3262 int
3263mch_isdir(char_u *name)
3264{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003265 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266
3267 if (f == -1)
3268 return FALSE; /* file does not exist at all */
3269
3270 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3271}
3272
3273/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003274 * return TRUE if "name" is a directory, NOT a symlink to a directory
3275 * return FALSE if "name" is not a directory
3276 * return FALSE for error
3277 */
3278 int
3279mch_isrealdir(char_u *name)
3280{
3281 return mch_isdir(name) && !mch_is_symbolic_link(name);
3282}
3283
3284/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003285 * Create directory "name".
3286 * Return 0 on success, -1 on error.
3287 */
3288 int
3289mch_mkdir(char_u *name)
3290{
3291#ifdef FEAT_MBYTE
3292 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3293 {
3294 WCHAR *p;
3295 int retval;
3296
3297 p = enc_to_utf16(name, NULL);
3298 if (p == NULL)
3299 return -1;
3300 retval = _wmkdir(p);
3301 vim_free(p);
3302 return retval;
3303 }
3304#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003305 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003306}
3307
3308/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003309 * Delete directory "name".
3310 * Return 0 on success, -1 on error.
3311 */
3312 int
3313mch_rmdir(char_u *name)
3314{
3315#ifdef FEAT_MBYTE
3316 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3317 {
3318 WCHAR *p;
3319 int retval;
3320
3321 p = enc_to_utf16(name, NULL);
3322 if (p == NULL)
3323 return -1;
3324 retval = _wrmdir(p);
3325 vim_free(p);
3326 return retval;
3327 }
3328#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003329 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003330}
3331
3332/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003333 * Return TRUE if file "fname" has more than one link.
3334 */
3335 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003336mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003337{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003338 BY_HANDLE_FILE_INFORMATION info;
3339
3340 return win32_fileinfo(fname, &info) == FILEINFO_OK
3341 && info.nNumberOfLinks > 1;
3342}
3343
3344/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003345 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003346 */
3347 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003348mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003349{
3350 HANDLE hFind;
3351 int res = FALSE;
3352 WIN32_FIND_DATAA findDataA;
3353 DWORD fileFlags = 0, reparseTag = 0;
3354#ifdef FEAT_MBYTE
3355 WCHAR *wn = NULL;
3356 WIN32_FIND_DATAW findDataW;
3357
3358 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003359 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003360 if (wn != NULL)
3361 {
3362 hFind = FindFirstFileW(wn, &findDataW);
3363 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003364 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003365 {
3366 fileFlags = findDataW.dwFileAttributes;
3367 reparseTag = findDataW.dwReserved0;
3368 }
3369 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003370 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003371#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003372 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003373 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003374 if (hFind != INVALID_HANDLE_VALUE)
3375 {
3376 fileFlags = findDataA.dwFileAttributes;
3377 reparseTag = findDataA.dwReserved0;
3378 }
3379 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003380
3381 if (hFind != INVALID_HANDLE_VALUE)
3382 FindClose(hFind);
3383
3384 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003385 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3386 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003387 res = TRUE;
3388
3389 return res;
3390}
3391
3392/*
3393 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3394 * link.
3395 */
3396 int
3397mch_is_linked(char_u *fname)
3398{
3399 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3400 return TRUE;
3401 return FALSE;
3402}
3403
3404/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003405 * Get the by-handle-file-information for "fname".
3406 * Returns FILEINFO_OK when OK.
3407 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3408 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3409 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3410 */
3411 int
3412win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3413{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003414 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003415 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003416#ifdef FEAT_MBYTE
3417 WCHAR *wn = NULL;
3418
3419 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003420 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003421 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003422 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003423 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003424 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003425 if (wn != NULL)
3426 {
3427 hFile = CreateFileW(wn, /* file name */
3428 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003429 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003430 NULL, /* security descriptor */
3431 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003432 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003433 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003434 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003435 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003436 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003437#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003438 hFile = CreateFile((LPCSTR)fname, /* file name */
3439 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003440 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003441 NULL, /* security descriptor */
3442 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003443 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003444 NULL); /* handle to template file */
3445
3446 if (hFile != INVALID_HANDLE_VALUE)
3447 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003448 if (GetFileInformationByHandle(hFile, info) != 0)
3449 res = FILEINFO_OK;
3450 else
3451 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003452 CloseHandle(hFile);
3453 }
3454
Bram Moolenaar03f48552006-02-28 23:52:23 +00003455 return res;
3456}
3457
3458/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003459 * get file attributes for `name'
3460 * -1 : error
3461 * else FILE_ATTRIBUTE_* defined in winnt.h
3462 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003463 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003464win32_getattrs(char_u *name)
3465{
3466 int attr;
3467#ifdef FEAT_MBYTE
3468 WCHAR *p = NULL;
3469
3470 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3471 p = enc_to_utf16(name, NULL);
3472
3473 if (p != NULL)
3474 {
3475 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003476 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003477 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003478 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003479#endif
3480 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003481
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003482 return attr;
3483}
3484
3485/*
3486 * set file attributes for `name' to `attrs'
3487 *
3488 * return -1 for failure, 0 otherwise
3489 */
3490 static
3491 int
3492win32_setattrs(char_u *name, int attrs)
3493{
3494 int res;
3495#ifdef FEAT_MBYTE
3496 WCHAR *p = NULL;
3497
3498 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3499 p = enc_to_utf16(name, NULL);
3500
3501 if (p != NULL)
3502 {
3503 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003504 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003505 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003506 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003507#endif
3508 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003509
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003510 return res ? 0 : -1;
3511}
3512
3513/*
3514 * Set archive flag for "name".
3515 */
3516 static
3517 int
3518win32_set_archive(char_u *name)
3519{
3520 int attrs = win32_getattrs(name);
3521 if (attrs == -1)
3522 return -1;
3523
3524 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3525 return win32_setattrs(name, attrs);
3526}
3527
3528/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529 * Return TRUE if file or directory "name" is writable (not readonly).
3530 * Strange semantics of Win32: a readonly directory is writable, but you can't
3531 * delete a file. Let's say this means it is writable.
3532 */
3533 int
3534mch_writable(char_u *name)
3535{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003536 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003538 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3539 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540}
3541
Bram Moolenaar071d4272004-06-13 20:20:40 +00003542/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003543 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003544 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003545 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3546 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 */
3548 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003549mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003551 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003552 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003553 char_u *p;
3554
3555 if (len >= _MAX_PATH) /* safety check */
3556 return FALSE;
3557
3558 /* If there already is an extension try using the name directly. Also do
3559 * this with a Unix-shell like 'shell'. */
3560 if (vim_strchr(gettail(name), '.') != NULL
3561 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003562 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003563 return TRUE;
3564
3565 /*
3566 * Loop over all extensions in $PATHEXT.
3567 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003568 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003569 p = mch_getenv("PATHEXT");
3570 if (p == NULL)
3571 p = (char_u *)".com;.exe;.bat;.cmd";
3572 while (*p)
3573 {
3574 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3575 {
3576 /* A single "." means no extension is added. */
3577 buf[len] = NUL;
3578 ++p;
3579 if (*p)
3580 ++p;
3581 }
3582 else
3583 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003584 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003585 return TRUE;
3586 }
3587 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003588}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003589
3590/*
3591 * Check what "name" is:
3592 * NODE_NORMAL: file or directory (or doesn't exist)
3593 * NODE_WRITABLE: writable device, socket, fifo, etc.
3594 * NODE_OTHER: non-writable things
3595 */
3596 int
3597mch_nodetype(char_u *name)
3598{
3599 HANDLE hFile;
3600 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003601#ifdef FEAT_MBYTE
3602 WCHAR *wn = NULL;
3603#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604
Bram Moolenaar043545e2006-10-10 16:44:07 +00003605 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3606 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3607 * here. */
3608 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3609 return NODE_WRITABLE;
3610
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003611#ifdef FEAT_MBYTE
3612 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003613 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003614
3615 if (wn != NULL)
3616 {
3617 hFile = CreateFileW(wn, /* file name */
3618 GENERIC_WRITE, /* access mode */
3619 0, /* share mode */
3620 NULL, /* security descriptor */
3621 OPEN_EXISTING, /* creation disposition */
3622 0, /* file attributes */
3623 NULL); /* handle to template file */
3624 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003625 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003626 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003627#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003628 hFile = CreateFile((LPCSTR)name, /* file name */
3629 GENERIC_WRITE, /* access mode */
3630 0, /* share mode */
3631 NULL, /* security descriptor */
3632 OPEN_EXISTING, /* creation disposition */
3633 0, /* file attributes */
3634 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635
3636 if (hFile == INVALID_HANDLE_VALUE)
3637 return NODE_NORMAL;
3638
3639 type = GetFileType(hFile);
3640 CloseHandle(hFile);
3641 if (type == FILE_TYPE_CHAR)
3642 return NODE_WRITABLE;
3643 if (type == FILE_TYPE_DISK)
3644 return NODE_NORMAL;
3645 return NODE_OTHER;
3646}
3647
3648#ifdef HAVE_ACL
3649struct my_acl
3650{
3651 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3652 PSID pSidOwner;
3653 PSID pSidGroup;
3654 PACL pDacl;
3655 PACL pSacl;
3656};
3657#endif
3658
3659/*
3660 * Return a pointer to the ACL of file "fname" in allocated memory.
3661 * Return NULL if the ACL is not available for whatever reason.
3662 */
3663 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003664mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003665{
3666#ifndef HAVE_ACL
3667 return (vim_acl_T)NULL;
3668#else
3669 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003670 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003671
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003672 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3673 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003675# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003676 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003677
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003678 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3679 wn = enc_to_utf16(fname, NULL);
3680 if (wn != NULL)
3681 {
3682 /* Try to retrieve the entire security descriptor. */
3683 err = GetNamedSecurityInfoW(
3684 wn, // Abstract filename
3685 SE_FILE_OBJECT, // File Object
3686 OWNER_SECURITY_INFORMATION |
3687 GROUP_SECURITY_INFORMATION |
3688 DACL_SECURITY_INFORMATION |
3689 SACL_SECURITY_INFORMATION,
3690 &p->pSidOwner, // Ownership information.
3691 &p->pSidGroup, // Group membership.
3692 &p->pDacl, // Discretionary information.
3693 &p->pSacl, // For auditing purposes.
3694 &p->pSecurityDescriptor);
3695 if (err == ERROR_ACCESS_DENIED ||
3696 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003698 /* Retrieve only DACL. */
3699 (void)GetNamedSecurityInfoW(
3700 wn,
3701 SE_FILE_OBJECT,
3702 DACL_SECURITY_INFORMATION,
3703 NULL,
3704 NULL,
3705 &p->pDacl,
3706 NULL,
3707 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003708 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003709 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003710 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003711 mch_free_acl((vim_acl_T)p);
3712 p = NULL;
3713 }
3714 vim_free(wn);
3715 }
3716 else
3717# endif
3718 {
3719 /* Try to retrieve the entire security descriptor. */
3720 err = GetNamedSecurityInfo(
3721 (LPSTR)fname, // Abstract filename
3722 SE_FILE_OBJECT, // File Object
3723 OWNER_SECURITY_INFORMATION |
3724 GROUP_SECURITY_INFORMATION |
3725 DACL_SECURITY_INFORMATION |
3726 SACL_SECURITY_INFORMATION,
3727 &p->pSidOwner, // Ownership information.
3728 &p->pSidGroup, // Group membership.
3729 &p->pDacl, // Discretionary information.
3730 &p->pSacl, // For auditing purposes.
3731 &p->pSecurityDescriptor);
3732 if (err == ERROR_ACCESS_DENIED ||
3733 err == ERROR_PRIVILEGE_NOT_HELD)
3734 {
3735 /* Retrieve only DACL. */
3736 (void)GetNamedSecurityInfo(
3737 (LPSTR)fname,
3738 SE_FILE_OBJECT,
3739 DACL_SECURITY_INFORMATION,
3740 NULL,
3741 NULL,
3742 &p->pDacl,
3743 NULL,
3744 &p->pSecurityDescriptor);
3745 }
3746 if (p->pSecurityDescriptor == NULL)
3747 {
3748 mch_free_acl((vim_acl_T)p);
3749 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003750 }
3751 }
3752 }
3753
3754 return (vim_acl_T)p;
3755#endif
3756}
3757
Bram Moolenaar27515922013-06-29 15:36:26 +02003758#ifdef HAVE_ACL
3759/*
3760 * Check if "acl" contains inherited ACE.
3761 */
3762 static BOOL
3763is_acl_inherited(PACL acl)
3764{
3765 DWORD i;
3766 ACL_SIZE_INFORMATION acl_info;
3767 PACCESS_ALLOWED_ACE ace;
3768
3769 acl_info.AceCount = 0;
3770 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3771 for (i = 0; i < acl_info.AceCount; i++)
3772 {
3773 GetAce(acl, i, (LPVOID *)&ace);
3774 if (ace->Header.AceFlags & INHERITED_ACE)
3775 return TRUE;
3776 }
3777 return FALSE;
3778}
3779#endif
3780
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781/*
3782 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3783 * Errors are ignored.
3784 * This must only be called with "acl" equal to what mch_get_acl() returned.
3785 */
3786 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003787mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788{
3789#ifdef HAVE_ACL
3790 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003791 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003792
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003793 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003794 {
3795# ifdef FEAT_MBYTE
3796 WCHAR *wn = NULL;
3797# endif
3798
3799 /* Set security flags */
3800 if (p->pSidOwner)
3801 sec_info |= OWNER_SECURITY_INFORMATION;
3802 if (p->pSidGroup)
3803 sec_info |= GROUP_SECURITY_INFORMATION;
3804 if (p->pDacl)
3805 {
3806 sec_info |= DACL_SECURITY_INFORMATION;
3807 /* Do not inherit its parent's DACL.
3808 * If the DACL is inherited, Cygwin permissions would be changed.
3809 */
3810 if (!is_acl_inherited(p->pDacl))
3811 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3812 }
3813 if (p->pSacl)
3814 sec_info |= SACL_SECURITY_INFORMATION;
3815
3816# ifdef FEAT_MBYTE
3817 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3818 wn = enc_to_utf16(fname, NULL);
3819 if (wn != NULL)
3820 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003821 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003822 wn, // Abstract filename
3823 SE_FILE_OBJECT, // File Object
3824 sec_info,
3825 p->pSidOwner, // Ownership information.
3826 p->pSidGroup, // Group membership.
3827 p->pDacl, // Discretionary information.
3828 p->pSacl // For auditing purposes.
3829 );
3830 vim_free(wn);
3831 }
3832 else
3833# endif
3834 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003835 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003836 (LPSTR)fname, // Abstract filename
3837 SE_FILE_OBJECT, // File Object
3838 sec_info,
3839 p->pSidOwner, // Ownership information.
3840 p->pSidGroup, // Group membership.
3841 p->pDacl, // Discretionary information.
3842 p->pSacl // For auditing purposes.
3843 );
3844 }
3845 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003846#endif
3847}
3848
3849 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003850mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003851{
3852#ifdef HAVE_ACL
3853 struct my_acl *p = (struct my_acl *)acl;
3854
3855 if (p != NULL)
3856 {
3857 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3858 vim_free(p);
3859 }
3860#endif
3861}
3862
3863#ifndef FEAT_GUI_W32
3864
3865/*
3866 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3867 */
3868 static BOOL WINAPI
3869handler_routine(
3870 DWORD dwCtrlType)
3871{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003872 INPUT_RECORD ir;
3873 DWORD out;
3874
Bram Moolenaar071d4272004-06-13 20:20:40 +00003875 switch (dwCtrlType)
3876 {
3877 case CTRL_C_EVENT:
3878 if (ctrl_c_interrupts)
3879 g_fCtrlCPressed = TRUE;
3880 return TRUE;
3881
3882 case CTRL_BREAK_EVENT:
3883 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003884 ctrl_break_was_pressed = TRUE;
3885 /* ReadConsoleInput is blocking, send a key event to continue. */
3886 ir.EventType = KEY_EVENT;
3887 ir.Event.KeyEvent.bKeyDown = TRUE;
3888 ir.Event.KeyEvent.wRepeatCount = 1;
3889 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3890 ir.Event.KeyEvent.wVirtualScanCode = 0;
3891 ir.Event.KeyEvent.dwControlKeyState = 0;
3892 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3893 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003894 return TRUE;
3895
3896 /* fatal events: shut down gracefully */
3897 case CTRL_CLOSE_EVENT:
3898 case CTRL_LOGOFF_EVENT:
3899 case CTRL_SHUTDOWN_EVENT:
3900 windgoto((int)Rows - 1, 0);
3901 g_fForceExit = TRUE;
3902
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003903 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003904 (dwCtrlType == CTRL_CLOSE_EVENT
3905 ? _("close")
3906 : dwCtrlType == CTRL_LOGOFF_EVENT
3907 ? _("logoff")
3908 : _("shutdown")));
3909#ifdef DEBUG
3910 OutputDebugString(IObuff);
3911#endif
3912
3913 preserve_exit(); /* output IObuff, preserve files and exit */
3914
3915 return TRUE; /* not reached */
3916
3917 default:
3918 return FALSE;
3919 }
3920}
3921
3922
3923/*
3924 * set the tty in (raw) ? "raw" : "cooked" mode
3925 */
3926 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003927mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928{
3929 DWORD cmodein;
3930 DWORD cmodeout;
3931 BOOL bEnableHandler;
3932
3933 GetConsoleMode(g_hConIn, &cmodein);
3934 GetConsoleMode(g_hConOut, &cmodeout);
3935 if (tmode == TMODE_RAW)
3936 {
3937 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3938 ENABLE_ECHO_INPUT);
3939#ifdef FEAT_MOUSE
3940 if (g_fMouseActive)
3941 cmodein |= ENABLE_MOUSE_INPUT;
3942#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01003943 cmodeout &= ~(
3944#ifdef FEAT_TERMGUICOLORS
3945 /* Do not turn off the ENABLE_PROCESSRD_OUTPUT flag when using
3946 * VTP. */
3947 ((vtp_working) ? 0 : ENABLE_PROCESSED_OUTPUT) |
3948#else
3949 ENABLE_PROCESSED_OUTPUT |
3950#endif
3951 ENABLE_WRAP_AT_EOL_OUTPUT);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003952 bEnableHandler = TRUE;
3953 }
3954 else /* cooked */
3955 {
3956 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3957 ENABLE_ECHO_INPUT);
3958 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3959 bEnableHandler = FALSE;
3960 }
3961 SetConsoleMode(g_hConIn, cmodein);
3962 SetConsoleMode(g_hConOut, cmodeout);
3963 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3964
3965#ifdef MCH_WRITE_DUMP
3966 if (fdDump)
3967 {
3968 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3969 tmode == TMODE_RAW ? "raw" :
3970 tmode == TMODE_COOK ? "cooked" : "normal",
3971 cmodein, cmodeout);
3972 fflush(fdDump);
3973 }
3974#endif
3975}
3976
3977
3978/*
3979 * Get the size of the current window in `Rows' and `Columns'
3980 * Return OK when size could be determined, FAIL otherwise.
3981 */
3982 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003983mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984{
3985 CONSOLE_SCREEN_BUFFER_INFO csbi;
3986
3987 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3988 {
3989 /*
3990 * For some reason, we are trying to get the screen dimensions
3991 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3992 * variables are really intended to mean the size of Vim screen
3993 * while in termcap mode.
3994 */
3995 Rows = g_cbTermcap.Info.dwSize.Y;
3996 Columns = g_cbTermcap.Info.dwSize.X;
3997 }
3998 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3999 {
4000 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4001 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4002 }
4003 else
4004 {
4005 Rows = 25;
4006 Columns = 80;
4007 }
4008 return OK;
4009}
4010
4011/*
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004012 * Resize console buffer to 'COORD'
4013 */
4014 static void
4015ResizeConBuf(
4016 HANDLE hConsole,
4017 COORD coordScreen)
4018{
4019 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4020 {
4021#ifdef MCH_WRITE_DUMP
4022 if (fdDump)
4023 {
4024 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4025 GetLastError());
4026 fflush(fdDump);
4027 }
4028#endif
4029 }
4030}
4031
4032/*
4033 * Resize console window size to 'srWindowRect'
4034 */
4035 static void
4036ResizeWindow(
4037 HANDLE hConsole,
4038 SMALL_RECT srWindowRect)
4039{
4040 if (!SetConsoleWindowInfo(hConsole, TRUE, &srWindowRect))
4041 {
4042#ifdef MCH_WRITE_DUMP
4043 if (fdDump)
4044 {
4045 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
4046 GetLastError());
4047 fflush(fdDump);
4048 }
4049#endif
4050 }
4051}
4052
4053/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 * Set a console window to `xSize' * `ySize'
4055 */
4056 static void
4057ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004058 HANDLE hConsole,
4059 int xSize,
4060 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004061{
4062 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
4063 SMALL_RECT srWindowRect; /* hold the new console size */
4064 COORD coordScreen;
Bram Moolenaar2551c032018-08-23 22:38:31 +02004065 static int resized = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004066
4067#ifdef MCH_WRITE_DUMP
4068 if (fdDump)
4069 {
4070 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
4071 fflush(fdDump);
4072 }
4073#endif
4074
4075 /* get the largest size we can size the console window to */
4076 coordScreen = GetLargestConsoleWindowSize(hConsole);
4077
4078 /* define the new console window size and scroll position */
4079 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
4080 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
4081 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
4082
4083 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
4084 {
4085 int sx, sy;
4086
4087 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
4088 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
4089 if (sy < ySize || sx < xSize)
4090 {
4091 /*
4092 * Increasing number of lines/columns, do buffer first.
4093 * Use the maximal size in x and y direction.
4094 */
4095 if (sy < ySize)
4096 coordScreen.Y = ySize;
4097 else
4098 coordScreen.Y = sy;
4099 if (sx < xSize)
4100 coordScreen.X = xSize;
4101 else
4102 coordScreen.X = sx;
4103 SetConsoleScreenBufferSize(hConsole, coordScreen);
4104 }
4105 }
4106
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004107 // define the new console buffer size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 coordScreen.X = xSize;
4109 coordScreen.Y = ySize;
4110
Bram Moolenaar2551c032018-08-23 22:38:31 +02004111 // In the new console call API, only the first time in reverse order
4112 if (!vtp_working || resized)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113 {
Bram Moolenaarb1cf1612018-08-07 20:47:16 +02004114 ResizeWindow(hConsole, srWindowRect);
4115 ResizeConBuf(hConsole, coordScreen);
4116 }
4117 else
4118 {
4119 ResizeConBuf(hConsole, coordScreen);
4120 ResizeWindow(hConsole, srWindowRect);
Bram Moolenaar2551c032018-08-23 22:38:31 +02004121 resized = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004122 }
4123}
4124
4125
4126/*
4127 * Set the console window to `Rows' * `Columns'
4128 */
4129 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004130mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131{
4132 COORD coordScreen;
4133
4134 /* Don't change window size while still starting up */
4135 if (suppress_winsize != 0)
4136 {
4137 suppress_winsize = 2;
4138 return;
4139 }
4140
4141 if (term_console)
4142 {
4143 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4144
4145 /* Clamp Rows and Columns to reasonable values */
4146 if (Rows > coordScreen.Y)
4147 Rows = coordScreen.Y;
4148 if (Columns > coordScreen.X)
4149 Columns = coordScreen.X;
4150
4151 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4152 }
4153}
4154
4155/*
4156 * Rows and/or Columns has changed.
4157 */
4158 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004159mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160{
4161 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4162}
4163
4164
4165/*
4166 * Called when started up, to set the winsize that was delayed.
4167 */
4168 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004169mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004170{
4171 if (suppress_winsize == 2)
4172 {
4173 suppress_winsize = 0;
4174 mch_set_shellsize();
4175 shell_resized();
4176 }
4177 suppress_winsize = 0;
4178}
4179#endif /* FEAT_GUI_W32 */
4180
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004181 static BOOL
4182vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004183 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004184 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004185 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004186 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004187 PROCESS_INFORMATION *pi,
4188 LPVOID *env,
4189 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004190{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004191#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004192 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4193 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004194 BOOL ret;
4195 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004196
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004197 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4198 if (wcmd == NULL)
4199 goto fallback;
4200 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004201 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004202 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4203 if (wcwd == NULL)
4204 {
4205 vim_free(wcmd);
4206 goto fallback;
4207 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004208 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004209
4210 ret = CreateProcessW(
4211 NULL, /* Executable name */
4212 wcmd, /* Command to execute */
4213 NULL, /* Process security attributes */
4214 NULL, /* Thread security attributes */
4215 inherit_handles, /* Inherit handles */
4216 flags, /* Creation flags */
4217 env, /* Environment */
4218 wcwd, /* Current directory */
4219 (LPSTARTUPINFOW)si, /* Startup information */
4220 pi); /* Process information */
4221 vim_free(wcmd);
4222 if (wcwd != NULL)
4223 vim_free(wcwd);
4224 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004225 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004226fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004227#endif
4228 return CreateProcess(
4229 NULL, /* Executable name */
4230 cmd, /* Command to execute */
4231 NULL, /* Process security attributes */
4232 NULL, /* Thread security attributes */
4233 inherit_handles, /* Inherit handles */
4234 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004235 env, /* Environment */
4236 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004237 si, /* Startup information */
4238 pi); /* Process information */
4239}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004240
4241
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004242 static HINSTANCE
4243vim_shell_execute(
4244 char *cmd,
4245 INT n_show_cmd)
4246{
4247#ifdef FEAT_MBYTE
4248 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4249 {
4250 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4251 if (wcmd != NULL)
4252 {
4253 HINSTANCE ret;
4254 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4255 vim_free(wcmd);
4256 return ret;
4257 }
4258 }
4259#endif
4260 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4261}
4262
4263
Bram Moolenaar071d4272004-06-13 20:20:40 +00004264#if defined(FEAT_GUI_W32) || defined(PROTO)
4265
4266/*
4267 * Specialised version of system() for Win32 GUI mode.
4268 * This version proceeds as follows:
4269 * 1. Create a console window for use by the subprocess
4270 * 2. Run the subprocess (it gets the allocated console by default)
4271 * 3. Wait for the subprocess to terminate and get its exit code
4272 * 4. Prompt the user to press a key to close the console window
4273 */
4274 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004275mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004276{
4277 STARTUPINFO si;
4278 PROCESS_INFORMATION pi;
4279 DWORD ret = 0;
4280 HWND hwnd = GetFocus();
4281
4282 si.cb = sizeof(si);
4283 si.lpReserved = NULL;
4284 si.lpDesktop = NULL;
4285 si.lpTitle = NULL;
4286 si.dwFlags = STARTF_USESHOWWINDOW;
4287 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004288 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004289 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004290 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004291 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004292 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004293 else
4294 si.wShowWindow = SW_SHOWNORMAL;
4295 si.cbReserved2 = 0;
4296 si.lpReserved2 = NULL;
4297
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004299 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004300 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4301 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004302
4303 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004304 {
4305#ifdef FEAT_GUI
4306 int delay = 1;
4307
4308 /* Keep updating the window while waiting for the shell to finish. */
4309 for (;;)
4310 {
4311 MSG msg;
4312
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004313 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004314 {
4315 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004316 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004317 delay = 1;
4318 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319 }
4320 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4321 break;
4322
4323 /* We start waiting for a very short time and then increase it, so
4324 * that we respond quickly when the process is quick, and don't
4325 * consume too much overhead when it's slow. */
4326 if (delay < 50)
4327 delay += 10;
4328 }
4329#else
4330 WaitForSingleObject(pi.hProcess, INFINITE);
4331#endif
4332
4333 /* Get the command exit code */
4334 GetExitCodeProcess(pi.hProcess, &ret);
4335 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004336
4337 /* Close the handles to the subprocess, so that it goes away */
4338 CloseHandle(pi.hThread);
4339 CloseHandle(pi.hProcess);
4340
4341 /* Try to get input focus back. Doesn't always work though. */
4342 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4343
4344 return ret;
4345}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004346
4347/*
4348 * Thread launched by the gui to send the current buffer data to the
4349 * process. This way avoid to hang up vim totally if the children
4350 * process take a long time to process the lines.
4351 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004352 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004353sub_process_writer(LPVOID param)
4354{
4355 HANDLE g_hChildStd_IN_Wr = param;
4356 linenr_T lnum = curbuf->b_op_start.lnum;
4357 DWORD len = 0;
4358 DWORD l;
4359 char_u *lp = ml_get(lnum);
4360 char_u *s;
4361 int written = 0;
4362
4363 for (;;)
4364 {
4365 l = (DWORD)STRLEN(lp + written);
4366 if (l == 0)
4367 len = 0;
4368 else if (lp[written] == NL)
4369 {
4370 /* NL -> NUL translation */
4371 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4372 }
4373 else
4374 {
4375 s = vim_strchr(lp + written, NL);
4376 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4377 s == NULL ? l : (DWORD)(s - (lp + written)),
4378 &len, NULL);
4379 }
4380 if (len == (int)l)
4381 {
4382 /* Finished a line, add a NL, unless this line should not have
4383 * one. */
4384 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004385 || (!curbuf->b_p_bin
4386 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004387 || (lnum != curbuf->b_no_eol_lnum
4388 && (lnum != curbuf->b_ml.ml_line_count
4389 || curbuf->b_p_eol)))
4390 {
Bram Moolenaar42335f52018-09-13 15:33:43 +02004391 WriteFile(g_hChildStd_IN_Wr, "\n", 1,
4392 (LPDWORD)&vim_ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004393 }
4394
4395 ++lnum;
4396 if (lnum > curbuf->b_op_end.lnum)
4397 break;
4398
4399 lp = ml_get(lnum);
4400 written = 0;
4401 }
4402 else if (len > 0)
4403 written += len;
4404 }
4405
4406 /* finished all the lines, close pipe */
4407 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004408 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004409}
4410
4411
4412# define BUFLEN 100 /* length for buffer, stolen from unix version */
4413
4414/*
4415 * This function read from the children's stdout and write the
4416 * data on screen or in the buffer accordingly.
4417 */
4418 static void
4419dump_pipe(int options,
4420 HANDLE g_hChildStd_OUT_Rd,
4421 garray_T *ga,
4422 char_u buffer[],
4423 DWORD *buffer_off)
4424{
4425 DWORD availableBytes = 0;
4426 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004427 int ret;
4428 DWORD len;
4429 DWORD toRead;
4430 int repeatCount;
4431
4432 /* we query the pipe to see if there is any data to read
4433 * to avoid to perform a blocking read */
4434 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4435 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004436 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004437 NULL, /* number of read bytes */
4438 &availableBytes, /* available bytes total */
4439 NULL); /* byteLeft */
4440
4441 repeatCount = 0;
4442 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004443 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004444 {
4445 repeatCount++;
4446 toRead =
4447# ifdef FEAT_MBYTE
4448 (DWORD)(BUFLEN - *buffer_off);
4449# else
4450 (DWORD)BUFLEN;
4451# endif
4452 toRead = availableBytes < toRead ? availableBytes : toRead;
4453 ReadFile(g_hChildStd_OUT_Rd, buffer
4454# ifdef FEAT_MBYTE
4455 + *buffer_off, toRead
4456# else
4457 , toRead
4458# endif
4459 , &len, NULL);
4460
4461 /* If we haven't read anything, there is a problem */
4462 if (len == 0)
4463 break;
4464
4465 availableBytes -= len;
4466
4467 if (options & SHELL_READ)
4468 {
4469 /* Do NUL -> NL translation, append NL separated
4470 * lines to the current buffer. */
4471 for (i = 0; i < len; ++i)
4472 {
4473 if (buffer[i] == NL)
4474 append_ga_line(ga);
4475 else if (buffer[i] == NUL)
4476 ga_append(ga, NL);
4477 else
4478 ga_append(ga, buffer[i]);
4479 }
4480 }
4481# ifdef FEAT_MBYTE
4482 else if (has_mbyte)
4483 {
4484 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004485 int c;
4486 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004487
4488 len += *buffer_off;
4489 buffer[len] = NUL;
4490
4491 /* Check if the last character in buffer[] is
4492 * incomplete, keep these bytes for the next
4493 * round. */
4494 for (p = buffer; p < buffer + len; p += l)
4495 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004496 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004497 if (l == 0)
4498 l = 1; /* NUL byte? */
4499 else if (MB_BYTE2LEN(*p) != l)
4500 break;
4501 }
4502 if (p == buffer) /* no complete character */
4503 {
4504 /* avoid getting stuck at an illegal byte */
4505 if (len >= 12)
4506 ++p;
4507 else
4508 {
4509 *buffer_off = len;
4510 return;
4511 }
4512 }
4513 c = *p;
4514 *p = NUL;
4515 msg_puts(buffer);
4516 if (p < buffer + len)
4517 {
4518 *p = c;
4519 *buffer_off = (DWORD)((buffer + len) - p);
4520 mch_memmove(buffer, p, *buffer_off);
4521 return;
4522 }
4523 *buffer_off = 0;
4524 }
4525# endif /* FEAT_MBYTE */
4526 else
4527 {
4528 buffer[len] = NUL;
4529 msg_puts(buffer);
4530 }
4531
4532 windgoto(msg_row, msg_col);
4533 cursor_on();
4534 out_flush();
4535 }
4536}
4537
4538/*
4539 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4540 * for communication and doesn't open any new window.
4541 */
4542 static int
4543mch_system_piped(char *cmd, int options)
4544{
4545 STARTUPINFO si;
4546 PROCESS_INFORMATION pi;
4547 DWORD ret = 0;
4548
4549 HANDLE g_hChildStd_IN_Rd = NULL;
4550 HANDLE g_hChildStd_IN_Wr = NULL;
4551 HANDLE g_hChildStd_OUT_Rd = NULL;
4552 HANDLE g_hChildStd_OUT_Wr = NULL;
4553
4554 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4555 DWORD len;
4556
4557 /* buffer used to receive keys */
4558 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4559 int ta_len = 0; /* valid bytes in ta_buf[] */
4560
4561 DWORD i;
4562 int c;
4563 int noread_cnt = 0;
4564 garray_T ga;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004565 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004566 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004567 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004568
4569 SECURITY_ATTRIBUTES saAttr;
4570
4571 /* Set the bInheritHandle flag so pipe handles are inherited. */
4572 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4573 saAttr.bInheritHandle = TRUE;
4574 saAttr.lpSecurityDescriptor = NULL;
4575
4576 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4577 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004578 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004579 /* Create a pipe for the child process's STDIN. */
4580 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4581 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004582 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004583 {
4584 CloseHandle(g_hChildStd_IN_Rd);
4585 CloseHandle(g_hChildStd_IN_Wr);
4586 CloseHandle(g_hChildStd_OUT_Rd);
4587 CloseHandle(g_hChildStd_OUT_Wr);
4588 MSG_PUTS(_("\nCannot create pipes\n"));
4589 }
4590
4591 si.cb = sizeof(si);
4592 si.lpReserved = NULL;
4593 si.lpDesktop = NULL;
4594 si.lpTitle = NULL;
4595 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4596
4597 /* set-up our file redirection */
4598 si.hStdError = g_hChildStd_OUT_Wr;
4599 si.hStdOutput = g_hChildStd_OUT_Wr;
4600 si.hStdInput = g_hChildStd_IN_Rd;
4601 si.wShowWindow = SW_HIDE;
4602 si.cbReserved2 = 0;
4603 si.lpReserved2 = NULL;
4604
4605 if (options & SHELL_READ)
4606 ga_init2(&ga, 1, BUFLEN);
4607
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004608 if (cmd != NULL)
4609 {
4610 p = (char *)vim_strsave((char_u *)cmd);
4611 if (p != NULL)
4612 unescape_shellxquote((char_u *)p, p_sxe);
4613 else
4614 p = cmd;
4615 }
4616
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004617 /* Now, run the command.
4618 * About "Inherit handles" being TRUE: this command can be litigious,
4619 * handle inheritance was deactivated for pending temp file, but, if we
4620 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004621 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4622 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004623
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004624 if (p != cmd)
4625 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004626
4627 /* Close our unused side of the pipes */
4628 CloseHandle(g_hChildStd_IN_Rd);
4629 CloseHandle(g_hChildStd_OUT_Wr);
4630
4631 if (options & SHELL_WRITE)
4632 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004633 HANDLE thread = (HANDLE)
4634 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004635 0, /* default stack size */
4636 sub_process_writer, /* function to be executed */
4637 g_hChildStd_IN_Wr, /* parameter */
4638 0, /* creation flag, start immediately */
4639 NULL); /* we don't care about thread id */
4640 CloseHandle(thread);
4641 g_hChildStd_IN_Wr = NULL;
4642 }
4643
4644 /* Keep updating the window while waiting for the shell to finish. */
4645 for (;;)
4646 {
4647 MSG msg;
4648
Bram Moolenaar175d0702013-12-11 18:36:33 +01004649 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004650 {
4651 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004652 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004653 }
4654
4655 /* write pipe information in the window */
4656 if ((options & (SHELL_READ|SHELL_WRITE))
4657# ifdef FEAT_GUI
4658 || gui.in_use
4659# endif
4660 )
4661 {
4662 len = 0;
4663 if (!(options & SHELL_EXPAND)
4664 && ((options &
4665 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4666 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4667# ifdef FEAT_GUI
4668 || gui.in_use
4669# endif
4670 )
4671 && (ta_len > 0 || noread_cnt > 4))
4672 {
4673 if (ta_len == 0)
4674 {
4675 /* Get extra characters when we don't have any. Reset the
4676 * counter and timer. */
4677 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004678 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4679 }
4680 if (ta_len > 0 || len > 0)
4681 {
4682 /*
4683 * For pipes: Check for CTRL-C: send interrupt signal to
4684 * child. Check for CTRL-D: EOF, close pipe to child.
4685 */
4686 if (len == 1 && cmd != NULL)
4687 {
4688 if (ta_buf[ta_len] == Ctrl_C)
4689 {
4690 /* Learn what exit code is expected, for
4691 * now put 9 as SIGKILL */
4692 TerminateProcess(pi.hProcess, 9);
4693 }
4694 if (ta_buf[ta_len] == Ctrl_D)
4695 {
4696 CloseHandle(g_hChildStd_IN_Wr);
4697 g_hChildStd_IN_Wr = NULL;
4698 }
4699 }
4700
4701 /* replace K_BS by <BS> and K_DEL by <DEL> */
4702 for (i = ta_len; i < ta_len + len; ++i)
4703 {
4704 if (ta_buf[i] == CSI && len - i > 2)
4705 {
4706 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4707 if (c == K_DEL || c == K_KDEL || c == K_BS)
4708 {
4709 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4710 (size_t)(len - i - 2));
4711 if (c == K_DEL || c == K_KDEL)
4712 ta_buf[i] = DEL;
4713 else
4714 ta_buf[i] = Ctrl_H;
4715 len -= 2;
4716 }
4717 }
4718 else if (ta_buf[i] == '\r')
4719 ta_buf[i] = '\n';
4720# ifdef FEAT_MBYTE
4721 if (has_mbyte)
4722 i += (*mb_ptr2len_len)(ta_buf + i,
4723 ta_len + len - i) - 1;
4724# endif
4725 }
4726
4727 /*
4728 * For pipes: echo the typed characters. For a pty this
4729 * does not seem to work.
4730 */
4731 for (i = ta_len; i < ta_len + len; ++i)
4732 {
4733 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4734 msg_putchar(ta_buf[i]);
4735# ifdef FEAT_MBYTE
4736 else if (has_mbyte)
4737 {
4738 int l = (*mb_ptr2len)(ta_buf + i);
4739
4740 msg_outtrans_len(ta_buf + i, l);
4741 i += l - 1;
4742 }
4743# endif
4744 else
4745 msg_outtrans_len(ta_buf + i, 1);
4746 }
4747 windgoto(msg_row, msg_col);
4748 out_flush();
4749
4750 ta_len += len;
4751
4752 /*
4753 * Write the characters to the child, unless EOF has been
4754 * typed for pipes. Write one character at a time, to
4755 * avoid losing too much typeahead. When writing buffer
4756 * lines, drop the typed characters (only check for
4757 * CTRL-C).
4758 */
4759 if (options & SHELL_WRITE)
4760 ta_len = 0;
4761 else if (g_hChildStd_IN_Wr != NULL)
4762 {
4763 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4764 1, &len, NULL);
4765 // if we are typing in, we want to keep things reactive
4766 delay = 1;
4767 if (len > 0)
4768 {
4769 ta_len -= len;
4770 mch_memmove(ta_buf, ta_buf + len, ta_len);
4771 }
4772 }
4773 }
4774 }
4775 }
4776
4777 if (ta_len)
4778 ui_inchar_undo(ta_buf, ta_len);
4779
4780 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4781 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004782 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004783 break;
4784 }
4785
4786 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004787 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004788
4789 /* We start waiting for a very short time and then increase it, so
4790 * that we respond quickly when the process is quick, and don't
4791 * consume too much overhead when it's slow. */
4792 if (delay < 50)
4793 delay += 10;
4794 }
4795
4796 /* Close the pipe */
4797 CloseHandle(g_hChildStd_OUT_Rd);
4798 if (g_hChildStd_IN_Wr != NULL)
4799 CloseHandle(g_hChildStd_IN_Wr);
4800
4801 WaitForSingleObject(pi.hProcess, INFINITE);
4802
4803 /* Get the command exit code */
4804 GetExitCodeProcess(pi.hProcess, &ret);
4805
4806 if (options & SHELL_READ)
4807 {
4808 if (ga.ga_len > 0)
4809 {
4810 append_ga_line(&ga);
4811 /* remember that the NL was missing */
4812 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4813 }
4814 else
4815 curbuf->b_no_eol_lnum = 0;
4816 ga_clear(&ga);
4817 }
4818
4819 /* Close the handles to the subprocess, so that it goes away */
4820 CloseHandle(pi.hThread);
4821 CloseHandle(pi.hProcess);
4822
4823 return ret;
4824}
4825
4826 static int
4827mch_system(char *cmd, int options)
4828{
4829 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004830 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004831 return mch_system_piped(cmd, options);
4832 else
4833 return mch_system_classic(cmd, options);
4834}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004835#else
4836
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004837# ifdef FEAT_MBYTE
4838 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004839mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004840{
4841 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4842 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004843 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004844 if (wcmd != NULL)
4845 {
4846 int ret = _wsystem(wcmd);
4847 vim_free(wcmd);
4848 return ret;
4849 }
4850 }
4851 return system(cmd);
4852}
4853# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004854# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004855# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004856
4857#endif
4858
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004859#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
4860/*
4861 * Use a terminal window to run a shell command in.
4862 */
4863 static int
4864mch_call_shell_terminal(
4865 char_u *cmd,
4866 int options UNUSED) /* SHELL_*, see vim.h */
4867{
4868 jobopt_T opt;
4869 char_u *newcmd = NULL;
4870 typval_T argvar[2];
4871 long_u cmdlen;
4872 int retval = -1;
4873 buf_T *buf;
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004874 job_T *job;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004875 aco_save_T aco;
4876 oparg_T oa; /* operator arguments */
4877
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004878 if (cmd == NULL)
4879 cmdlen = STRLEN(p_sh) + 1;
4880 else
4881 cmdlen = STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004882 newcmd = lalloc(cmdlen, TRUE);
4883 if (newcmd == NULL)
4884 return 255;
Bram Moolenaar42f652f2018-03-19 21:44:37 +01004885 if (cmd == NULL)
4886 {
4887 STRCPY(newcmd, p_sh);
4888 ch_log(NULL, "starting terminal to run a shell");
4889 }
4890 else
4891 {
4892 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s", p_sh, p_shcf, cmd);
4893 ch_log(NULL, "starting terminal for system command '%s'", cmd);
4894 }
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004895
4896 init_job_options(&opt);
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004897
4898 argvar[0].v_type = VAR_STRING;
4899 argvar[0].vval.v_string = newcmd;
4900 argvar[1].v_type = VAR_UNKNOWN;
4901 buf = term_start(argvar, NULL, &opt, TERM_START_SYSTEM);
Bram Moolenaar81c3c89a2018-03-20 11:41:44 +01004902 if (buf == NULL)
4903 return 255;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004904
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004905 job = term_getjob(buf->b_term);
4906 ++job->jv_refcount;
4907
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004908 /* Find a window to make "buf" curbuf. */
4909 aucmd_prepbuf(&aco, buf);
4910
4911 clear_oparg(&oa);
4912 while (term_use_loop())
4913 {
4914 if (oa.op_type == OP_NOP && oa.regname == NUL && !VIsual_active)
4915 {
4916 /* If terminal_loop() returns OK we got a key that is handled
4917 * in Normal model. We don't do redrawing anyway. */
4918 if (terminal_loop(TRUE) == OK)
4919 normal_cmd(&oa, TRUE);
4920 }
4921 else
4922 normal_cmd(&oa, TRUE);
4923 }
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004924 retval = job->jv_exitval;
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004925 ch_log(NULL, "system command finished");
4926
Bram Moolenaarf9c38832018-06-19 19:59:20 +02004927 job_unref(job);
4928
Bram Moolenaarf05fa372018-03-18 19:29:34 +01004929 /* restore curwin/curbuf and a few other things */
4930 aucmd_restbuf(&aco);
4931
4932 wait_return(TRUE);
4933 do_buffer(DOBUF_WIPE, DOBUF_FIRST, FORWARD, buf->b_fnum, TRUE);
4934
4935 vim_free(newcmd);
4936 return retval;
4937}
4938#endif
4939
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940/*
4941 * Either execute a command by calling the shell or start a new shell
4942 */
4943 int
4944mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004945 char_u *cmd,
4946 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004947{
4948 int x = 0;
4949 int tmode = cur_tmode;
4950#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004951 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004952# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004953 int did_set_title = FALSE;
4954
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004955 /* Change the title to reflect that we are in a subshell. */
4956 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4957 {
4958 WCHAR szShellTitle[512];
4959
4960 if (GetConsoleTitleW(szShellTitle,
4961 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4962 {
4963 if (cmd == NULL)
4964 wcscat(szShellTitle, L" :sh");
4965 else
4966 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004967 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004968
4969 if (wn != NULL)
4970 {
4971 wcscat(szShellTitle, L" - !");
4972 if ((wcslen(szShellTitle) + wcslen(wn) <
4973 sizeof(szShellTitle)/sizeof(WCHAR)))
4974 wcscat(szShellTitle, wn);
4975 SetConsoleTitleW(szShellTitle);
4976 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004977 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004978 }
4979 }
4980 }
4981 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004982 if (!did_set_title)
4983# endif
4984 /* Change the title to reflect that we are in a subshell. */
4985 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004986 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004987 if (cmd == NULL)
4988 strcat(szShellTitle, " :sh");
4989 else
4990 {
4991 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004992 if ((strlen(szShellTitle) + strlen((char *)cmd)
4993 < sizeof(szShellTitle)))
4994 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004995 }
4996 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004998#endif
4999
5000 out_flush();
5001
5002#ifdef MCH_WRITE_DUMP
5003 if (fdDump)
5004 {
5005 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
5006 fflush(fdDump);
5007 }
5008#endif
Bram Moolenaarf05fa372018-03-18 19:29:34 +01005009#if defined(FEAT_GUI) && defined(FEAT_TERMINAL)
5010 /* TODO: make the terminal window work with input or output redirected. */
5011 if (vim_strchr(p_go, GO_TERMINAL) != NULL
5012 && (options & (SHELL_FILTER|SHELL_DOOUT|SHELL_WRITE|SHELL_READ)) == 0)
5013 {
5014 /* Use a terminal window to run the command in. */
5015 x = mch_call_shell_terminal(cmd, options);
5016#ifdef FEAT_TITLE
5017 resettitle();
5018#endif
5019 return x;
5020 }
5021#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005022
5023 /*
5024 * Catch all deadly signals while running the external command, because a
5025 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
5026 */
5027 signal(SIGINT, SIG_IGN);
5028#if defined(__GNUC__) && !defined(__MINGW32__)
5029 signal(SIGKILL, SIG_IGN);
5030#else
5031 signal(SIGBREAK, SIG_IGN);
5032#endif
5033 signal(SIGILL, SIG_IGN);
5034 signal(SIGFPE, SIG_IGN);
5035 signal(SIGSEGV, SIG_IGN);
5036 signal(SIGTERM, SIG_IGN);
5037 signal(SIGABRT, SIG_IGN);
5038
5039 if (options & SHELL_COOKED)
5040 settmode(TMODE_COOK); /* set to normal mode */
5041
5042 if (cmd == NULL)
5043 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005044 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045 }
5046 else
5047 {
5048 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005049 char_u *newcmd = NULL;
5050 char_u *cmdbase = cmd;
5051 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005052
5053 /* Skip a leading ", ( and "(. */
5054 if (*cmdbase == '"' )
5055 ++cmdbase;
5056 if (*cmdbase == '(')
5057 ++cmdbase;
5058
Bram Moolenaar1c465442017-03-12 20:10:05 +01005059 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005060 {
5061 STARTUPINFO si;
5062 PROCESS_INFORMATION pi;
5063 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005064 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005065 char_u *p;
5066
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005067 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005068 si.cb = sizeof(si);
5069 si.lpReserved = NULL;
5070 si.lpDesktop = NULL;
5071 si.lpTitle = NULL;
5072 si.dwFlags = 0;
5073 si.cbReserved2 = 0;
5074 si.lpReserved2 = NULL;
5075
5076 cmdbase = skipwhite(cmdbase + 5);
5077 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005078 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005079 {
5080 cmdbase = skipwhite(cmdbase + 4);
5081 si.dwFlags = STARTF_USESHOWWINDOW;
5082 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005083 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005084 }
5085 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01005086 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005087 {
5088 cmdbase = skipwhite(cmdbase + 2);
5089 flags = CREATE_NO_WINDOW;
5090 si.dwFlags = STARTF_USESTDHANDLES;
5091 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005092 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005093 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005094 NULL, // Security att.
5095 OPEN_EXISTING, // Open flags
5096 FILE_ATTRIBUTE_NORMAL, // File att.
5097 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005098 si.hStdOutput = si.hStdInput;
5099 si.hStdError = si.hStdInput;
5100 }
5101
5102 /* Remove a trailing ", ) and )" if they have a match
5103 * at the start of the command. */
5104 if (cmdbase > cmd)
5105 {
5106 p = cmdbase + STRLEN(cmdbase);
5107 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
5108 *--p = NUL;
5109 if (p > cmdbase && p[-1] == ')'
5110 && (*cmd =='(' || cmd[1] == '('))
5111 *--p = NUL;
5112 }
5113
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005114 newcmd = cmdbase;
5115 unescape_shellxquote(cmdbase, p_sxe);
5116
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005117 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005118 * If creating new console, arguments are passed to the
5119 * 'cmd.exe' as-is. If it's not, arguments are not treated
5120 * correctly for current 'cmd.exe'. So unescape characters in
5121 * shellxescape except '|' for avoiding to be treated as
5122 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005123 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005124 if (flags != CREATE_NEW_CONSOLE)
5125 {
5126 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005127 char_u *cmd_shell = mch_getenv("COMSPEC");
5128
5129 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005130 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005131
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005132 subcmd = vim_strsave_escaped_ext(cmdbase,
5133 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005134 if (subcmd != NULL)
5135 {
5136 /* make "cmd.exe /c arguments" */
5137 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005138 newcmd = lalloc(cmdlen, TRUE);
5139 if (newcmd != NULL)
5140 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005141 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005142 else
5143 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01005144 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005145 }
5146 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005147
5148 /*
5149 * Now, start the command as a process, so that it doesn't
5150 * inherit our handles which causes unpleasant dangling swap
5151 * files if we exit before the spawned process
5152 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005153 if (vim_create_process((char *)newcmd, FALSE, flags,
5154 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005155 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01005156 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
5157 > (HINSTANCE)32)
5158 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005159 else
5160 {
5161 x = -1;
5162#ifdef FEAT_GUI_W32
5163 EMSG(_("E371: Command not found"));
5164#endif
5165 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005166
5167 if (newcmd != cmdbase)
5168 vim_free(newcmd);
5169
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005170 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005171 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01005172 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005173 CloseHandle(si.hStdInput);
5174 }
5175 /* Close the handles to the subprocess, so that it goes away */
5176 CloseHandle(pi.hThread);
5177 CloseHandle(pi.hProcess);
5178 }
5179 else
5180 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01005181 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00005182#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005183 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00005184#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005185 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
5186
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005187 newcmd = lalloc(cmdlen, TRUE);
5188 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005189 {
5190#if defined(FEAT_GUI_W32)
5191 if (need_vimrun_warning)
5192 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01005193 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
5194 "External commands will not pause after completion.\n"
5195 "See :help win32-vimrun for more information.");
5196 char *title = _("Vim Warning");
5197# ifdef FEAT_MBYTE
5198 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5199 {
5200 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
5201 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
5202
5203 if (wmsg != NULL && wtitle != NULL)
5204 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
5205 vim_free(wmsg);
5206 vim_free(wtitle);
5207 }
5208 else
5209# endif
5210 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005211 need_vimrun_warning = FALSE;
5212 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005213 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005214 /* Use vimrun to execute the command. It opens a console
5215 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005216 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00005217 vimrun_path,
5218 (msg_silent != 0 || (options & SHELL_DOOUT))
5219 ? "-s " : "",
5220 p_sh, p_shcf, cmd);
5221 else
5222#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02005223 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005224 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005225 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01005226 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005227 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005228 }
5229 }
5230
5231 if (tmode == TMODE_RAW)
5232 settmode(TMODE_RAW); /* set to raw mode */
5233
5234 /* Print the return value, unless "vimrun" was used. */
5235 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5236#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005237 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238#endif
5239 )
5240 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005241 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005242 msg_putchar('\n');
5243 }
5244#ifdef FEAT_TITLE
5245 resettitle();
5246#endif
5247
5248 signal(SIGINT, SIG_DFL);
5249#if defined(__GNUC__) && !defined(__MINGW32__)
5250 signal(SIGKILL, SIG_DFL);
5251#else
5252 signal(SIGBREAK, SIG_DFL);
5253#endif
5254 signal(SIGILL, SIG_DFL);
5255 signal(SIGFPE, SIG_DFL);
5256 signal(SIGSEGV, SIG_DFL);
5257 signal(SIGTERM, SIG_DFL);
5258 signal(SIGABRT, SIG_DFL);
5259
5260 return x;
5261}
5262
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005263#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005264 static HANDLE
5265job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005266 char_u *fname,
5267 DWORD dwDesiredAccess,
5268 DWORD dwShareMode,
5269 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5270 DWORD dwCreationDisposition,
5271 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005272{
5273 HANDLE h;
5274# ifdef FEAT_MBYTE
5275 WCHAR *wn = NULL;
5276 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5277 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005278 wn = enc_to_utf16(fname, NULL);
5279 if (wn != NULL)
5280 {
5281 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5282 lpSecurityAttributes, dwCreationDisposition,
5283 dwFlagsAndAttributes, NULL);
5284 vim_free(wn);
5285 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005286 }
5287 if (wn == NULL)
5288# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005289 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5290 lpSecurityAttributes, dwCreationDisposition,
5291 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005292 return h;
5293}
5294
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005295/*
5296 * Turn the dictionary "env" into a NUL separated list that can be used as the
5297 * environment argument of vim_create_process().
5298 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005299 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005300win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005301{
5302 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005303 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005304 LPVOID base = GetEnvironmentStringsW();
5305
5306 /* for last \0 */
5307 if (ga_grow(gap, 1) == FAIL)
5308 return;
5309
5310 if (base)
5311 {
5312 WCHAR *p = (WCHAR*) base;
5313
5314 /* for last \0 */
5315 if (ga_grow(gap, 1) == FAIL)
5316 return;
5317
5318 while (*p != 0 || *(p + 1) != 0)
5319 {
5320 if (ga_grow(gap, 1) == OK)
5321 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5322 p++;
5323 }
5324 FreeEnvironmentStrings(base);
5325 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5326 }
5327
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005328 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005329 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005330 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005331 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005332 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005333 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005334 typval_T *item = &dict_lookup(hi)->di_tv;
5335 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5336 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5337 --todo;
5338 if (wkey != NULL && wval != NULL)
5339 {
5340 size_t n;
5341 size_t lkey = wcslen(wkey);
5342 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005343
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005344 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5345 continue;
5346 for (n = 0; n < lkey; n++)
5347 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5348 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5349 for (n = 0; n < lval; n++)
5350 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5351 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5352 }
5353 if (wkey != NULL) vim_free(wkey);
5354 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005355 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005356 }
5357 }
5358
Bram Moolenaar493359e2018-06-12 20:25:52 +02005359# if defined(FEAT_CLIENTSERVER) || defined(FEAT_TERMINAL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005360 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005361# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005362 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005363 size_t servername_len = STRLEN(servername);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005364# endif
5365# ifdef FEAT_TERMINAL
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005366 char_u *version = get_vim_var_str(VV_VERSION);
5367 size_t version_len = STRLEN(version);
Bram Moolenaar493359e2018-06-12 20:25:52 +02005368# endif
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005369 // size of "VIM_SERVERNAME=" and value,
5370 // plus "VIM_TERMINAL=" and value,
5371 // plus two terminating NULs
5372 size_t n = 0
Bram Moolenaar493359e2018-06-12 20:25:52 +02005373# ifdef FEAT_CLIENTSERVER
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005374 + 15 + servername_len
Bram Moolenaar493359e2018-06-12 20:25:52 +02005375# endif
5376# ifdef FEAT_TERMINAL
5377 + 13 + version_len + 2
5378# endif
5379 ;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005380
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005381 if (ga_grow(gap, (int)n) == OK)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005382 {
Bram Moolenaar493359e2018-06-12 20:25:52 +02005383# ifdef FEAT_CLIENTSERVER
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005384 for (n = 0; n < 15; n++)
5385 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5386 (WCHAR)"VIM_SERVERNAME="[n];
Bram Moolenaard7a137f2018-06-12 18:05:24 +02005387 for (n = 0; n < servername_len; n++)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005388 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5389 (WCHAR)servername[n];
5390 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
Bram Moolenaar493359e2018-06-12 20:25:52 +02005391# endif
5392# ifdef FEAT_TERMINAL
5393 if (is_terminal)
5394 {
5395 for (n = 0; n < 13; n++)
5396 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5397 (WCHAR)"VIM_TERMINAL="[n];
5398 for (n = 0; n < version_len; n++)
5399 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5400 (WCHAR)version[n];
5401 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5402 }
5403# endif
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005404 }
5405 }
Bram Moolenaar79c6b512018-06-12 21:11:12 +02005406# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005407}
5408
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005409 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005410mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005411{
5412 STARTUPINFO si;
5413 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005414 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005415 SECURITY_ATTRIBUTES saAttr;
5416 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005417 HANDLE ifd[2];
5418 HANDLE ofd[2];
5419 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005420 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005421
5422 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5423 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5424 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5425 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5426 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5427 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5428 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5429
5430 if (use_out_for_err && use_null_for_out)
5431 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005432
5433 ifd[0] = INVALID_HANDLE_VALUE;
5434 ifd[1] = INVALID_HANDLE_VALUE;
5435 ofd[0] = INVALID_HANDLE_VALUE;
5436 ofd[1] = INVALID_HANDLE_VALUE;
5437 efd[0] = INVALID_HANDLE_VALUE;
5438 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005439 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005440
Bram Moolenaar14207f42016-10-27 21:13:10 +02005441 jo = CreateJobObject(NULL, NULL);
5442 if (jo == NULL)
5443 {
5444 job->jv_status = JOB_FAILED;
5445 goto failed;
5446 }
5447
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005448 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005449 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005450
Bram Moolenaar76467df2016-02-12 19:30:26 +01005451 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005452 ZeroMemory(&si, sizeof(si));
5453 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005454 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005455 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005456
Bram Moolenaard8070362016-02-15 21:56:54 +01005457 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5458 saAttr.bInheritHandle = TRUE;
5459 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005460
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005461 if (use_file_for_in)
5462 {
5463 char_u *fname = options->jo_io_name[PART_IN];
5464
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005465 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5466 FILE_SHARE_READ | FILE_SHARE_WRITE,
5467 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5468 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005469 {
5470 EMSG2(_(e_notopen), fname);
5471 goto failed;
5472 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005473 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005474 else if (!use_null_for_in &&
5475 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005476 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005477 goto failed;
5478
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005479 if (use_file_for_out)
5480 {
5481 char_u *fname = options->jo_io_name[PART_OUT];
5482
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005483 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5484 FILE_SHARE_READ | FILE_SHARE_WRITE,
5485 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5486 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005487 {
5488 EMSG2(_(e_notopen), fname);
5489 goto failed;
5490 }
5491 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005492 else if (!use_null_for_out &&
5493 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005494 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005495 goto failed;
5496
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005497 if (use_file_for_err)
5498 {
5499 char_u *fname = options->jo_io_name[PART_ERR];
5500
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005501 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5502 FILE_SHARE_READ | FILE_SHARE_WRITE,
5503 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5504 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005505 {
5506 EMSG2(_(e_notopen), fname);
5507 goto failed;
5508 }
5509 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005510 else if (!use_out_for_err && !use_null_for_err &&
5511 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005512 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005513 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005514
Bram Moolenaard8070362016-02-15 21:56:54 +01005515 si.dwFlags |= STARTF_USESTDHANDLES;
5516 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005517 si.hStdOutput = ofd[1];
5518 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5519
5520 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5521 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005522 if (options->jo_set & JO_CHANNEL)
5523 {
5524 channel = options->jo_channel;
5525 if (channel != NULL)
5526 ++channel->ch_refcount;
5527 }
5528 else
5529 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005530 if (channel == NULL)
5531 goto failed;
5532 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005533
5534 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005535 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005536 CREATE_DEFAULT_ERROR_MODE |
5537 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005538 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005539 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005540 &si, &pi,
5541 ga.ga_data,
5542 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005543 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005544 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005545 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005546 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005547 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005548
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005549 ga_clear(&ga);
5550
Bram Moolenaar14207f42016-10-27 21:13:10 +02005551 if (!AssignProcessToJobObject(jo, pi.hProcess))
5552 {
5553 /* if failing, switch the way to terminate
5554 * process with TerminateProcess. */
5555 CloseHandle(jo);
5556 jo = NULL;
5557 }
5558 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005559 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005560 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005561 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005562 job->jv_status = JOB_STARTED;
5563
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005564 CloseHandle(ifd[0]);
5565 CloseHandle(ofd[1]);
5566 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005567 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005568
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005569 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005570 if (channel != NULL)
5571 {
5572 channel_set_pipes(channel,
5573 use_file_for_in || use_null_for_in
5574 ? INVALID_FD : (sock_T)ifd[1],
5575 use_file_for_out || use_null_for_out
5576 ? INVALID_FD : (sock_T)ofd[0],
5577 use_out_for_err || use_file_for_err || use_null_for_err
5578 ? INVALID_FD : (sock_T)efd[0]);
5579 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005580 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005581 return;
5582
5583failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005584 CloseHandle(ifd[0]);
5585 CloseHandle(ofd[0]);
5586 CloseHandle(efd[0]);
5587 CloseHandle(ifd[1]);
5588 CloseHandle(ofd[1]);
5589 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005590 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005591 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005592}
5593
5594 char *
5595mch_job_status(job_T *job)
5596{
5597 DWORD dwExitCode = 0;
5598
Bram Moolenaar76467df2016-02-12 19:30:26 +01005599 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5600 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005601 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005602 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005603 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005604 {
5605 ch_log(job->jv_channel, "Job ended");
5606 job->jv_status = JOB_ENDED;
5607 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005608 return "dead";
5609 }
5610 return "run";
5611}
5612
Bram Moolenaar97792de2016-10-15 18:36:49 +02005613 job_T *
5614mch_detect_ended_job(job_T *job_list)
5615{
5616 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5617 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5618 job_T *job = job_list;
5619
5620 while (job != NULL)
5621 {
5622 DWORD n;
5623 DWORD result;
5624
5625 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5626 && job != NULL; job = job->jv_next)
5627 {
5628 if (job->jv_status == JOB_STARTED)
5629 {
5630 jobHandles[n] = job->jv_proc_info.hProcess;
5631 jobArray[n] = job;
5632 ++n;
5633 }
5634 }
5635 if (n == 0)
5636 continue;
5637 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5638 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5639 {
5640 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5641
5642 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5643 return wait_job;
5644 }
5645 }
5646 return NULL;
5647}
5648
Bram Moolenaarfb630902016-10-29 14:55:00 +02005649 static BOOL
5650terminate_all(HANDLE process, int code)
5651{
5652 PROCESSENTRY32 pe;
5653 HANDLE h = INVALID_HANDLE_VALUE;
5654 DWORD pid = GetProcessId(process);
5655
5656 if (pid != 0)
5657 {
5658 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5659 if (h != INVALID_HANDLE_VALUE)
5660 {
5661 pe.dwSize = sizeof(PROCESSENTRY32);
5662 if (!Process32First(h, &pe))
5663 goto theend;
5664
5665 do
5666 {
5667 if (pe.th32ParentProcessID == pid)
5668 {
5669 HANDLE ph = OpenProcess(
5670 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5671 if (ph != NULL)
5672 {
5673 terminate_all(ph, code);
5674 CloseHandle(ph);
5675 }
5676 }
5677 } while (Process32Next(h, &pe));
5678
5679 CloseHandle(h);
5680 }
5681 }
5682
5683theend:
5684 return TerminateProcess(process, code);
5685}
5686
5687/*
5688 * Send a (deadly) signal to "job".
5689 * Return FAIL if it didn't work.
5690 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005691 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005692mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005693{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005694 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005695
Bram Moolenaar923d9262016-02-25 20:56:01 +01005696 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005697 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005698 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005699 if (job->jv_job_object != NULL)
5700 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005701 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005702 }
5703
5704 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5705 return FAIL;
5706 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005707 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5708 job->jv_proc_info.dwProcessId)
5709 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005710 FreeConsole();
5711 return ret;
5712}
5713
5714/*
5715 * Clear the data related to "job".
5716 */
5717 void
5718mch_clear_job(job_T *job)
5719{
5720 if (job->jv_status != JOB_FAILED)
5721 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005722 if (job->jv_job_object != NULL)
5723 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005724 CloseHandle(job->jv_proc_info.hProcess);
5725 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005726}
5727#endif
5728
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729
5730#ifndef FEAT_GUI_W32
5731
5732/*
5733 * Start termcap mode
5734 */
5735 static void
5736termcap_mode_start(void)
5737{
5738 DWORD cmodein;
5739
5740 if (g_fTermcapMode)
5741 return;
5742
5743 SaveConsoleBuffer(&g_cbNonTermcap);
5744
5745 if (g_cbTermcap.IsValid)
5746 {
5747 /*
5748 * We've been in termcap mode before. Restore certain screen
5749 * characteristics, including the buffer size and the window
5750 * size. Since we will be redrawing the screen, we don't need
5751 * to restore the actual contents of the buffer.
5752 */
5753 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005754 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005755 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5756 Rows = g_cbTermcap.Info.dwSize.Y;
5757 Columns = g_cbTermcap.Info.dwSize.X;
5758 }
5759 else
5760 {
5761 /*
5762 * This is our first time entering termcap mode. Clear the console
5763 * screen buffer, and resize the buffer to match the current window
5764 * size. We will use this as the size of our editing environment.
5765 */
5766 ClearConsoleBuffer(g_attrCurrent);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005767 set_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5769 }
5770
5771#ifdef FEAT_TITLE
5772 resettitle();
5773#endif
5774
5775 GetConsoleMode(g_hConIn, &cmodein);
5776#ifdef FEAT_MOUSE
5777 if (g_fMouseActive)
5778 cmodein |= ENABLE_MOUSE_INPUT;
5779 else
5780 cmodein &= ~ENABLE_MOUSE_INPUT;
5781#endif
5782 cmodein |= ENABLE_WINDOW_INPUT;
5783 SetConsoleMode(g_hConIn, cmodein);
5784
5785 redraw_later_clear();
5786 g_fTermcapMode = TRUE;
5787}
5788
5789
5790/*
5791 * End termcap mode
5792 */
5793 static void
5794termcap_mode_end(void)
5795{
5796 DWORD cmodein;
5797 ConsoleBuffer *cb;
5798 COORD coord;
5799 DWORD dwDummy;
5800
5801 if (!g_fTermcapMode)
5802 return;
5803
5804 SaveConsoleBuffer(&g_cbTermcap);
5805
5806 GetConsoleMode(g_hConIn, &cmodein);
5807 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5808 SetConsoleMode(g_hConIn, cmodein);
5809
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005810#ifdef FEAT_RESTORE_ORIG_SCREEN
5811 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5812#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005813 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005814#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005815 RestoreConsoleBuffer(cb, p_rs);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005816 reset_console_color_rgb();
Bram Moolenaar071d4272004-06-13 20:20:40 +00005817 SetConsoleCursorInfo(g_hConOut, &g_cci);
5818
5819 if (p_rs || exiting)
5820 {
5821 /*
5822 * Clear anything that happens to be on the current line.
5823 */
5824 coord.X = 0;
5825 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5826 FillConsoleOutputCharacter(g_hConOut, ' ',
5827 cb->Info.dwSize.X, coord, &dwDummy);
5828 /*
5829 * The following is just for aesthetics. If we are exiting without
5830 * restoring the screen, then we want to have a prompt string
5831 * appear at the bottom line. However, the command interpreter
5832 * seems to always advance the cursor one line before displaying
5833 * the prompt string, which causes the screen to scroll. To
5834 * counter this, move the cursor up one line before exiting.
5835 */
5836 if (exiting && !p_rs)
5837 coord.Y--;
5838 /*
5839 * Position the cursor at the leftmost column of the desired row.
5840 */
5841 SetConsoleCursorPosition(g_hConOut, coord);
5842 }
5843
5844 g_fTermcapMode = FALSE;
5845}
5846#endif /* FEAT_GUI_W32 */
5847
5848
5849#ifdef FEAT_GUI_W32
5850 void
5851mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005852 char_u *s UNUSED,
5853 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005854{
5855 /* never used */
5856}
5857
5858#else
5859
5860/*
5861 * clear `n' chars, starting from `coord'
5862 */
5863 static void
5864clear_chars(
5865 COORD coord,
5866 DWORD n)
5867{
5868 DWORD dwDummy;
5869
5870 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005871
5872 if (!USE_VTP)
5873 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5874 else
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02005875 {
5876 set_console_color_rgb();
5877 gotoxy(coord.X + 1, coord.Y + 1);
5878 vtp_printf("\033[%dX", n);
5879 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005880}
5881
5882
5883/*
5884 * Clear the screen
5885 */
5886 static void
5887clear_screen(void)
5888{
5889 g_coord.X = g_coord.Y = 0;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005890
5891 if (!USE_VTP)
5892 clear_chars(g_coord, Rows * Columns);
5893 else
5894 {
5895 set_console_color_rgb();
5896 gotoxy(1, 1);
5897 vtp_printf("\033[2J");
5898 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005899}
5900
5901
5902/*
5903 * Clear to end of display
5904 */
5905 static void
5906clear_to_end_of_display(void)
5907{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005908 COORD save = g_coord;
5909
5910 if (!USE_VTP)
5911 clear_chars(g_coord, (Rows - g_coord.Y - 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912 * Columns + (Columns - g_coord.X));
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005913 else
5914 {
5915 set_console_color_rgb();
5916 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5917 vtp_printf("\033[0J");
5918
5919 gotoxy(save.X + 1, save.Y + 1);
5920 g_coord = save;
5921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005922}
5923
5924
5925/*
5926 * Clear to end of line
5927 */
5928 static void
5929clear_to_end_of_line(void)
5930{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005931 COORD save = g_coord;
5932
5933 if (!USE_VTP)
5934 clear_chars(g_coord, Columns - g_coord.X);
5935 else
5936 {
5937 set_console_color_rgb();
5938 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5939 vtp_printf("\033[0K");
5940
5941 gotoxy(save.X + 1, save.Y + 1);
5942 g_coord = save;
5943 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944}
5945
5946
5947/*
5948 * Scroll the scroll region up by `cLines' lines
5949 */
5950 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005951scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952{
5953 COORD oldcoord = g_coord;
5954
5955 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5956 delete_lines(cLines);
5957
5958 g_coord = oldcoord;
5959}
5960
5961
5962/*
5963 * Set the scroll region
5964 */
5965 static void
5966set_scroll_region(
5967 unsigned left,
5968 unsigned top,
5969 unsigned right,
5970 unsigned bottom)
5971{
5972 if (left >= right
5973 || top >= bottom
5974 || right > (unsigned) Columns - 1
5975 || bottom > (unsigned) Rows - 1)
5976 return;
5977
5978 g_srScrollRegion.Left = left;
5979 g_srScrollRegion.Top = top;
5980 g_srScrollRegion.Right = right;
5981 g_srScrollRegion.Bottom = bottom;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01005982
5983 if (USE_VTP)
5984 vtp_printf("\033[%d;%dr", top + 1, bottom + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005985}
5986
5987
5988/*
5989 * Insert `cLines' lines at the current cursor position
5990 */
5991 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005992insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993{
5994 SMALL_RECT source;
5995 COORD dest;
5996 CHAR_INFO fill;
5997
5998 dest.X = 0;
5999 dest.Y = g_coord.Y + cLines;
6000
6001 source.Left = 0;
6002 source.Top = g_coord.Y;
6003 source.Right = g_srScrollRegion.Right;
6004 source.Bottom = g_srScrollRegion.Bottom - cLines;
6005
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006006 if (!USE_VTP)
6007 {
6008 fill.Char.AsciiChar = ' ';
6009 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006010
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006011 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6012 }
6013 else
6014 {
6015 set_console_color_rgb();
6016
6017 gotoxy(1, source.Top + 1);
6018 vtp_printf("\033[%dT", cLines);
6019 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006020
6021 /* Here we have to deal with a win32 console flake: If the scroll
6022 * region looks like abc and we scroll c to a and fill with d we get
6023 * cbd... if we scroll block c one line at a time to a, we get cdd...
6024 * vim expects cdd consistently... So we have to deal with that
6025 * here... (this also occurs scrolling the same way in the other
6026 * direction). */
6027
6028 if (source.Bottom < dest.Y)
6029 {
6030 COORD coord;
6031
6032 coord.X = 0;
6033 coord.Y = source.Bottom;
6034 clear_chars(coord, Columns * (dest.Y - source.Bottom));
6035 }
6036}
6037
6038
6039/*
6040 * Delete `cLines' lines at the current cursor position
6041 */
6042 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006043delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044{
6045 SMALL_RECT source;
6046 COORD dest;
6047 CHAR_INFO fill;
6048 int nb;
6049
6050 dest.X = 0;
6051 dest.Y = g_coord.Y;
6052
6053 source.Left = 0;
6054 source.Top = g_coord.Y + cLines;
6055 source.Right = g_srScrollRegion.Right;
6056 source.Bottom = g_srScrollRegion.Bottom;
6057
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006058 if (!USE_VTP)
6059 {
6060 fill.Char.AsciiChar = ' ';
6061 fill.Attributes = g_attrCurrent;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006062
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006063 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
6064 }
6065 else
6066 {
6067 set_console_color_rgb();
6068
6069 gotoxy(1, source.Top + 1);
6070 vtp_printf("\033[%dS", cLines);
6071 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006072
6073 /* Here we have to deal with a win32 console flake: If the scroll
6074 * region looks like abc and we scroll c to a and fill with d we get
6075 * cbd... if we scroll block c one line at a time to a, we get cdd...
6076 * vim expects cdd consistently... So we have to deal with that
6077 * here... (this also occurs scrolling the same way in the other
6078 * direction). */
6079
6080 nb = dest.Y + (source.Bottom - source.Top) + 1;
6081
6082 if (nb < source.Top)
6083 {
6084 COORD coord;
6085
6086 coord.X = 0;
6087 coord.Y = nb;
6088 clear_chars(coord, Columns * (source.Top - nb));
6089 }
6090}
6091
6092
6093/*
6094 * Set the cursor position
6095 */
6096 static void
6097gotoxy(
6098 unsigned x,
6099 unsigned y)
6100{
6101 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
6102 return;
6103
6104 /* external cursor coords are 1-based; internal are 0-based */
6105 g_coord.X = x - 1;
6106 g_coord.Y = y - 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006107
6108 if (!USE_VTP)
6109 SetConsoleCursorPosition(g_hConOut, g_coord);
6110 else
6111 vtp_printf("\033[%d;%dH", y, x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006112}
6113
6114
6115/*
6116 * Set the current text attribute = (foreground | background)
6117 * See ../doc/os_win32.txt for the numbers.
6118 */
6119 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006120textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006121{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006122 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123
6124 SetConsoleTextAttribute(g_hConOut, wAttr);
6125}
6126
6127
6128 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006129textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006131 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006132
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006133 if (!USE_VTP)
6134 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6135 else
6136 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137}
6138
6139
6140 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006141textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006142{
Bram Moolenaar6383b922015-03-24 17:12:19 +01006143 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006145 if (!USE_VTP)
6146 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
6147 else
6148 vtp_sgr_bulk(wAttr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006149}
6150
6151
6152/*
6153 * restore the default text attribute (whatever we started with)
6154 */
6155 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006156normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157{
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006158 if (!USE_VTP)
6159 textattr(g_attrDefault);
6160 else
6161 vtp_sgr_bulk(0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162}
6163
6164
6165static WORD g_attrPreStandout = 0;
6166
6167/*
6168 * Make the text standout, by brightening it
6169 */
6170 static void
6171standout(void)
6172{
6173 g_attrPreStandout = g_attrCurrent;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006174
Bram Moolenaar071d4272004-06-13 20:20:40 +00006175 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
6176}
6177
6178
6179/*
6180 * Turn off standout mode
6181 */
6182 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006183standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006184{
6185 if (g_attrPreStandout)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006186 textattr(g_attrPreStandout);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006187
6188 g_attrPreStandout = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189}
6190
6191
6192/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00006193 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006194 */
6195 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006196mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006197{
6198 char_u *p;
6199 int n;
6200
6201 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
6202 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006203 if (
6204#ifdef FEAT_TERMGUICOLORS
6205 !p_tgc &&
6206#endif
6207 T_ME[0] == ESC && T_ME[1] == '|')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006208 {
6209 p = T_ME + 2;
6210 n = getdigits(&p);
6211 if (*p == 'm' && n > 0)
6212 {
6213 cterm_normal_fg_color = (n & 0xf) + 1;
6214 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
6215 }
6216 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006217#ifdef FEAT_TERMGUICOLORS
6218 cterm_normal_fg_gui_color = INVALCOLOR;
6219 cterm_normal_bg_gui_color = INVALCOLOR;
6220#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221}
6222
6223
6224/*
6225 * visual bell: flash the screen
6226 */
6227 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006228visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006229{
6230 COORD coordOrigin = {0, 0};
6231 WORD attrFlash = ~g_attrCurrent & 0xff;
6232
6233 DWORD dwDummy;
6234 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
6235
6236 if (oldattrs == NULL)
6237 return;
6238 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
6239 coordOrigin, &dwDummy);
6240 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
6241 coordOrigin, &dwDummy);
6242
6243 Sleep(15); /* wait for 15 msec */
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006244 if (!USE_VTP)
6245 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 coordOrigin, &dwDummy);
6247 vim_free(oldattrs);
6248}
6249
6250
6251/*
6252 * Make the cursor visible or invisible
6253 */
6254 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006255cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256{
6257 s_cursor_visible = fVisible;
6258#ifdef MCH_CURSOR_SHAPE
6259 mch_update_cursor();
6260#endif
6261}
6262
6263
6264/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006265 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006266 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006268 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006270 char_u *pchBuf,
6271 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272{
6273 COORD coord = g_coord;
6274 DWORD written;
6275
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006276#ifdef FEAT_MBYTE
6277 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6278 {
6279 static WCHAR *unicodebuf = NULL;
6280 static int unibuflen = 0;
6281 int length;
6282 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006283
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006284 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
6285 if (unicodebuf == NULL || length > unibuflen)
6286 {
6287 vim_free(unicodebuf);
6288 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
6289 unibuflen = length;
6290 }
6291 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
6292 unicodebuf, unibuflen);
6293
6294 cells = mb_string2cells(pchBuf, cbToWrite);
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006295
6296 if (!USE_VTP)
6297 {
6298 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
6299 coord, &written);
6300 /* When writing fails or didn't write a single character, pretend one
6301 * character was written, otherwise we get stuck. */
6302 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
6303 coord, &cchwritten) == 0
6304 || cchwritten == 0)
6305 cchwritten = 1;
6306 }
6307 else
6308 {
6309 if (WriteConsoleW(g_hConOut, unicodebuf, length, &cchwritten,
6310 NULL) == 0 || cchwritten == 0)
6311 cchwritten = 1;
6312 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006313
6314 if (cchwritten == length)
6315 {
6316 written = cbToWrite;
6317 g_coord.X += (SHORT)cells;
6318 }
6319 else
6320 {
6321 char_u *p = pchBuf;
6322 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006323 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006324 written = p - pchBuf;
6325 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
6326 }
6327 }
6328 else
6329#endif
6330 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006331 if (!USE_VTP)
6332 {
6333 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
6334 coord, &written);
6335 /* When writing fails or didn't write a single character, pretend one
6336 * character was written, otherwise we get stuck. */
6337 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
6338 coord, &written) == 0
6339 || written == 0)
6340 written = 1;
6341 }
6342 else
6343 {
6344 if (WriteConsole(g_hConOut, (LPCSTR)pchBuf, cbToWrite, &written,
6345 NULL) == 0 || written == 0)
6346 written = 1;
6347 }
Bram Moolenaarac360bf2015-09-01 20:31:20 +02006348
6349 g_coord.X += (SHORT) written;
6350 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351
6352 while (g_coord.X > g_srScrollRegion.Right)
6353 {
6354 g_coord.X -= (SHORT) Columns;
6355 if (g_coord.Y < g_srScrollRegion.Bottom)
6356 g_coord.Y++;
6357 }
6358
6359 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6360
6361 return written;
6362}
6363
6364
6365/*
6366 * mch_write(): write the output buffer to the screen, translating ESC
6367 * sequences into calls to console output routines.
6368 */
6369 void
6370mch_write(
6371 char_u *s,
6372 int len)
6373{
6374 s[len] = NUL;
6375
6376 if (!term_console)
6377 {
6378 write(1, s, (unsigned)len);
6379 return;
6380 }
6381
6382 /* translate ESC | sequences into faked bios calls */
6383 while (len--)
6384 {
6385 /* optimization: use one single write_chars for runs of text,
6386 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006387 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006388
6389 if (p_wd)
6390 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006391 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006392 if (prefix != 0)
6393 prefix = 1;
6394 }
6395
6396 if (prefix != 0)
6397 {
6398 DWORD nWritten;
6399
6400 nWritten = write_chars(s, prefix);
6401#ifdef MCH_WRITE_DUMP
6402 if (fdDump)
6403 {
6404 fputc('>', fdDump);
6405 fwrite(s, sizeof(char_u), nWritten, fdDump);
6406 fputs("<\n", fdDump);
6407 }
6408#endif
6409 len -= (nWritten - 1);
6410 s += nWritten;
6411 }
6412 else if (s[0] == '\n')
6413 {
6414 /* \n, newline: go to the beginning of the next line or scroll */
6415 if (g_coord.Y == g_srScrollRegion.Bottom)
6416 {
6417 scroll(1);
6418 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6419 }
6420 else
6421 {
6422 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6423 }
6424#ifdef MCH_WRITE_DUMP
6425 if (fdDump)
6426 fputs("\\n\n", fdDump);
6427#endif
6428 s++;
6429 }
6430 else if (s[0] == '\r')
6431 {
6432 /* \r, carriage return: go to beginning of line */
6433 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6434#ifdef MCH_WRITE_DUMP
6435 if (fdDump)
6436 fputs("\\r\n", fdDump);
6437#endif
6438 s++;
6439 }
6440 else if (s[0] == '\b')
6441 {
6442 /* \b, backspace: move cursor one position left */
6443 if (g_coord.X > g_srScrollRegion.Left)
6444 g_coord.X--;
6445 else if (g_coord.Y > g_srScrollRegion.Top)
6446 {
6447 g_coord.X = g_srScrollRegion.Right;
6448 g_coord.Y--;
6449 }
6450 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6451#ifdef MCH_WRITE_DUMP
6452 if (fdDump)
6453 fputs("\\b\n", fdDump);
6454#endif
6455 s++;
6456 }
6457 else if (s[0] == '\a')
6458 {
6459 /* \a, bell */
6460 MessageBeep(0xFFFFFFFF);
6461#ifdef MCH_WRITE_DUMP
6462 if (fdDump)
6463 fputs("\\a\n", fdDump);
6464#endif
6465 s++;
6466 }
6467 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6468 {
6469#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006470 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006471#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006472 char_u *p;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006473 int arg1 = 0, arg2 = 0, argc = 0, args[16];
Bram Moolenaar071d4272004-06-13 20:20:40 +00006474
6475 switch (s[2])
6476 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006477 case '0': case '1': case '2': case '3': case '4':
6478 case '5': case '6': case '7': case '8': case '9':
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006479 p = s + 1;
6480 do
6481 {
6482 ++p;
6483 args[argc] = getdigits(&p);
6484 argc += (argc < 15) ? 1 : 0;
6485 if (p > s + len)
6486 break;
6487 } while (*p == ';');
6488
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489 if (p > s + len)
6490 break;
6491
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006492 arg1 = args[0];
6493 arg2 = args[1];
6494 if (*p == 'm')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006495 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006496 if (argc == 1 && args[0] == 0)
6497 normvideo();
6498 else if (argc == 1)
6499 {
6500 if (USE_VTP)
6501 textcolor((WORD) arg1);
6502 else
6503 textattr((WORD) arg1);
6504 }
6505 else if (USE_VTP)
6506 vtp_sgr_bulks(argc, args);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006507 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006508 else if (argc == 2 && *p == 'H')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509 {
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006510 gotoxy(arg2, arg1);
6511 }
6512 else if (argc == 2 && *p == 'r')
6513 {
6514 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6515 }
6516 else if (argc == 1 && *p == 'A')
6517 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006518 gotoxy(g_coord.X + 1,
6519 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6520 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006521 else if (argc == 1 && *p == 'b')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006522 {
6523 textbackground((WORD) arg1);
6524 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01006525 else if (argc == 1 && *p == 'C')
6526 {
6527 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6528 g_coord.Y + 1);
6529 }
6530 else if (argc == 1 && *p == 'f')
6531 {
6532 textcolor((WORD) arg1);
6533 }
6534 else if (argc == 1 && *p == 'H')
6535 {
6536 gotoxy(1, arg1);
6537 }
6538 else if (argc == 1 && *p == 'L')
6539 {
6540 insert_lines(arg1);
6541 }
6542 else if (argc == 1 && *p == 'M')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006543 {
6544 delete_lines(arg1);
6545 }
6546
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006547 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006548 s = p + 1;
6549 break;
6550
Bram Moolenaar071d4272004-06-13 20:20:40 +00006551 case 'A':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552 gotoxy(g_coord.X + 1,
6553 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6554 goto got3;
6555
6556 case 'B':
6557 visual_bell();
6558 goto got3;
6559
6560 case 'C':
Bram Moolenaar071d4272004-06-13 20:20:40 +00006561 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6562 g_coord.Y + 1);
6563 goto got3;
6564
6565 case 'E':
6566 termcap_mode_end();
6567 goto got3;
6568
6569 case 'F':
6570 standout();
6571 goto got3;
6572
6573 case 'f':
6574 standend();
6575 goto got3;
6576
6577 case 'H':
6578 gotoxy(1, 1);
6579 goto got3;
6580
6581 case 'j':
6582 clear_to_end_of_display();
6583 goto got3;
6584
6585 case 'J':
6586 clear_screen();
6587 goto got3;
6588
6589 case 'K':
6590 clear_to_end_of_line();
6591 goto got3;
6592
6593 case 'L':
6594 insert_lines(1);
6595 goto got3;
6596
6597 case 'M':
6598 delete_lines(1);
6599 goto got3;
6600
6601 case 'S':
6602 termcap_mode_start();
6603 goto got3;
6604
6605 case 'V':
6606 cursor_visible(TRUE);
6607 goto got3;
6608
6609 case 'v':
6610 cursor_visible(FALSE);
6611 goto got3;
6612
6613 got3:
6614 s += 3;
6615 len -= 2;
6616 }
6617
6618#ifdef MCH_WRITE_DUMP
6619 if (fdDump)
6620 {
6621 fputs("ESC | ", fdDump);
6622 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6623 fputc('\n', fdDump);
6624 }
6625#endif
6626 }
6627 else
6628 {
6629 /* Write a single character */
6630 DWORD nWritten;
6631
6632 nWritten = write_chars(s, 1);
6633#ifdef MCH_WRITE_DUMP
6634 if (fdDump)
6635 {
6636 fputc('>', fdDump);
6637 fwrite(s, sizeof(char_u), nWritten, fdDump);
6638 fputs("<\n", fdDump);
6639 }
6640#endif
6641
6642 len -= (nWritten - 1);
6643 s += nWritten;
6644 }
6645 }
6646
6647#ifdef MCH_WRITE_DUMP
6648 if (fdDump)
6649 fflush(fdDump);
6650#endif
6651}
6652
6653#endif /* FEAT_GUI_W32 */
6654
6655
6656/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006657 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658 */
6659 void
6660mch_delay(
6661 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006662 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663{
6664#ifdef FEAT_GUI_W32
6665 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006666#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006667 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006668# ifdef FEAT_MZSCHEME
6669 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6670 {
6671 int towait = p_mzq;
6672
6673 /* if msec is large enough, wait by portions in p_mzq */
6674 while (msec > 0)
6675 {
6676 mzvim_check_threads();
6677 if (msec < towait)
6678 towait = msec;
6679 Sleep(towait);
6680 msec -= towait;
6681 }
6682 }
6683 else
6684# endif
6685 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006687 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688#endif
6689}
6690
6691
6692/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006693 * This version of remove is not scared by a readonly (backup) file.
6694 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006695 * Return 0 for success, -1 for failure.
6696 */
6697 int
6698mch_remove(char_u *name)
6699{
6700#ifdef FEAT_MBYTE
6701 WCHAR *wn = NULL;
6702 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006703#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704
Bram Moolenaar203258c2016-01-17 22:15:16 +01006705 /*
6706 * On Windows, deleting a directory's symbolic link is done by
6707 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6708 */
6709 if (mch_isdir(name) && mch_is_symbolic_link(name))
6710 return mch_rmdir(name);
6711
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006712 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6713
6714#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006715 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6716 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006717 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718 if (wn != NULL)
6719 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006720 n = DeleteFileW(wn) ? 0 : -1;
6721 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006722 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006723 }
6724 }
6725#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006726 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006727}
6728
6729
6730/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006731 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732 */
6733 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006734mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006735{
6736#ifndef FEAT_GUI_W32 /* never used */
6737 if (g_fCtrlCPressed || g_fCBrkPressed)
6738 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006739 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006740 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6741 got_int = TRUE;
6742 }
6743#endif
6744}
6745
Bram Moolenaaree273972016-01-02 21:11:51 +01006746/* physical RAM to leave for the OS */
6747#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006748
6749/*
6750 * How much main memory in KiB that can be used by VIM.
6751 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006752 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006753mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006754{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006755 MEMORYSTATUSEX ms;
6756
Bram Moolenaaree273972016-01-02 21:11:51 +01006757 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006758 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6759 * what fits in 32 bits. But it's not always available. */
6760 ms.dwLength = sizeof(MEMORYSTATUSEX);
6761 GlobalMemoryStatusEx(&ms);
6762 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006763 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006764 /* Process address space fits in physical RAM, use all of it. */
6765 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006766 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006767 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006768 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006769 /* Catch old NT box or perverse hardware setup. */
6770 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006771 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006772 /* Use physical RAM less reserve for OS + data. */
6773 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006774}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775
Bram Moolenaar071d4272004-06-13 20:20:40 +00006776#ifdef FEAT_MBYTE
6777/*
6778 * Same code as below, but with wide functions and no comments.
6779 * Return 0 for success, non-zero for failure.
6780 */
6781 int
6782mch_wrename(WCHAR *wold, WCHAR *wnew)
6783{
6784 WCHAR *p;
6785 int i;
6786 WCHAR szTempFile[_MAX_PATH + 1];
6787 WCHAR szNewPath[_MAX_PATH + 1];
6788 HANDLE hf;
6789
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006790 p = wold;
6791 for (i = 0; wold[i] != NUL; ++i)
6792 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6793 && wold[i + 1] != 0)
6794 p = wold + i + 1;
6795 if ((int)(wold + i - p) < 8 || p[6] != '~')
6796 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797
6798 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6799 return -1;
6800 *p = NUL;
6801
6802 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6803 return -2;
6804
6805 if (!DeleteFileW(szTempFile))
6806 return -3;
6807
6808 if (!MoveFileW(wold, szTempFile))
6809 return -4;
6810
6811 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6812 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6813 return -5;
6814 if (!CloseHandle(hf))
6815 return -6;
6816
6817 if (!MoveFileW(szTempFile, wnew))
6818 {
6819 (void)MoveFileW(szTempFile, wold);
6820 return -7;
6821 }
6822
6823 DeleteFileW(szTempFile);
6824
6825 if (!DeleteFileW(wold))
6826 return -8;
6827
6828 return 0;
6829}
6830#endif
6831
6832
6833/*
6834 * mch_rename() works around a bug in rename (aka MoveFile) in
6835 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6836 * file whose short file name is "FOO.BAR" (its long file name will
6837 * be correct: "foo.bar~"). Because a file can be accessed by
6838 * either its SFN or its LFN, "foo.bar" has effectively been
6839 * renamed to "foo.bar", which is not at all what was wanted. This
6840 * seems to happen only when renaming files with three-character
6841 * extensions by appending a suffix that does not include ".".
6842 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6843 *
6844 * There is another problem, which isn't really a bug but isn't right either:
6845 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6846 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6847 * service pack 6. Doesn't seem to happen on Windows 98.
6848 *
6849 * Like rename(), returns 0 upon success, non-zero upon failure.
6850 * Should probably set errno appropriately when errors occur.
6851 */
6852 int
6853mch_rename(
6854 const char *pszOldFile,
6855 const char *pszNewFile)
6856{
6857 char szTempFile[_MAX_PATH+1];
6858 char szNewPath[_MAX_PATH+1];
6859 char *pszFilePart;
6860 HANDLE hf;
6861#ifdef FEAT_MBYTE
6862 WCHAR *wold = NULL;
6863 WCHAR *wnew = NULL;
6864 int retval = -1;
6865
6866 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6867 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006868 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6869 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870 if (wold != NULL && wnew != NULL)
6871 retval = mch_wrename(wold, wnew);
6872 vim_free(wold);
6873 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006874 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006875 }
6876#endif
6877
6878 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006879 * No need to play tricks unless the file name contains a "~" as the
6880 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006881 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006882 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6883 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6884 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006885
6886 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6887 * a directory, no error is returned and pszFilePart will be NULL. */
6888 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6889 || pszFilePart == NULL)
6890 return -1;
6891 *pszFilePart = NUL;
6892
6893 /* Get (and create) a unique temporary file name in directory of new file */
6894 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6895 return -2;
6896
6897 /* blow the temp file away */
6898 if (!DeleteFile(szTempFile))
6899 return -3;
6900
6901 /* rename old file to the temp file */
6902 if (!MoveFile(pszOldFile, szTempFile))
6903 return -4;
6904
6905 /* now create an empty file called pszOldFile; this prevents the operating
6906 * system using pszOldFile as an alias (SFN) if we're renaming within the
6907 * same directory. For example, we're editing a file called
6908 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6909 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6910 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006911 * cause all sorts of problems later in buf_write(). So, we create an
6912 * empty file called filena~1.txt and the system will have to find some
6913 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006914 */
6915 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6916 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6917 return -5;
6918 if (!CloseHandle(hf))
6919 return -6;
6920
6921 /* rename the temp file to the new file */
6922 if (!MoveFile(szTempFile, pszNewFile))
6923 {
6924 /* Renaming failed. Rename the file back to its old name, so that it
6925 * looks like nothing happened. */
6926 (void)MoveFile(szTempFile, pszOldFile);
6927
6928 return -7;
6929 }
6930
6931 /* Seems to be left around on Novell filesystems */
6932 DeleteFile(szTempFile);
6933
6934 /* finally, remove the empty old file */
6935 if (!DeleteFile(pszOldFile))
6936 return -8;
6937
6938 return 0; /* success */
6939}
6940
6941/*
6942 * Get the default shell for the current hardware platform
6943 */
6944 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006945default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006946{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006947 PlatformId();
6948
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006949 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950}
6951
6952/*
6953 * mch_access() extends access() to do more detailed check on network drives.
6954 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6955 */
6956 int
6957mch_access(char *n, int p)
6958{
6959 HANDLE hFile;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006960 int retval = -1; /* default: fail */
6961#ifdef FEAT_MBYTE
6962 WCHAR *wn = NULL;
6963
6964 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006965 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006966#endif
6967
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006968 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006969 {
6970 char TempName[_MAX_PATH + 16] = "";
6971#ifdef FEAT_MBYTE
6972 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6973#endif
6974
6975 if (p & R_OK)
6976 {
6977 /* Read check is performed by seeing if we can do a find file on
6978 * the directory for any file. */
6979#ifdef FEAT_MBYTE
6980 if (wn != NULL)
6981 {
6982 int i;
6983 WIN32_FIND_DATAW d;
6984
6985 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6986 TempNameW[i] = wn[i];
6987 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6988 TempNameW[i++] = '\\';
6989 TempNameW[i++] = '*';
6990 TempNameW[i++] = 0;
6991
6992 hFile = FindFirstFileW(TempNameW, &d);
6993 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006994 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006995 else
6996 (void)FindClose(hFile);
6997 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006998 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006999#endif
7000 {
7001 char *pch;
7002 WIN32_FIND_DATA d;
7003
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007004 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007005 pch = TempName + STRLEN(TempName) - 1;
7006 if (*pch != '\\' && *pch != '/')
7007 *++pch = '\\';
7008 *++pch = '*';
7009 *++pch = NUL;
7010
7011 hFile = FindFirstFile(TempName, &d);
7012 if (hFile == INVALID_HANDLE_VALUE)
7013 goto getout;
7014 (void)FindClose(hFile);
7015 }
7016 }
7017
7018 if (p & W_OK)
7019 {
7020 /* Trying to create a temporary file in the directory should catch
7021 * directories on read-only network shares. However, in
7022 * directories whose ACL allows writes but denies deletes will end
7023 * up keeping the temporary file :-(. */
7024#ifdef FEAT_MBYTE
7025 if (wn != NULL)
7026 {
7027 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007028 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029 else
7030 DeleteFileW(TempNameW);
7031 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007032 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007033#endif
7034 {
7035 if (!GetTempFileName(n, "VIM", 0, TempName))
7036 goto getout;
7037 mch_remove((char_u *)TempName);
7038 }
7039 }
7040 }
7041 else
7042 {
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007043 // Don't consider a file read-only if another process has opened it.
7044 DWORD share_mode = FILE_SHARE_READ | FILE_SHARE_WRITE;
7045
Bram Moolenaar071d4272004-06-13 20:20:40 +00007046 /* Trying to open the file for the required access does ACL, read-only
7047 * network share, and file attribute checks. */
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007048 DWORD access_mode = ((p & W_OK) ? GENERIC_WRITE : 0)
7049 | ((p & R_OK) ? GENERIC_READ : 0);
7050
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051#ifdef FEAT_MBYTE
7052 if (wn != NULL)
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007053 hFile = CreateFileW(wn, access_mode, share_mode,
7054 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007055 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007056#endif
Bram Moolenaar5aa98962018-05-06 17:09:38 +02007057 hFile = CreateFile(n, access_mode, share_mode,
7058 NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007059 if (hFile == INVALID_HANDLE_VALUE)
7060 goto getout;
7061 CloseHandle(hFile);
7062 }
7063
7064 retval = 0; /* success */
7065getout:
7066#ifdef FEAT_MBYTE
7067 vim_free(wn);
7068#endif
7069 return retval;
7070}
7071
7072#if defined(FEAT_MBYTE) || defined(PROTO)
7073/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007074 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007075 */
7076 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007077mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007079 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
7080# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00007081 WCHAR *wn;
7082 int f;
7083
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007084 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007085 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007086 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007087 if (wn != NULL)
7088 {
7089 f = _wopen(wn, flags, mode);
7090 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007091 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007092 }
7093 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00007094# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007095
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007096 /* open() can open a file which name is longer than _MAX_PATH bytes
7097 * and shorter than _MAX_PATH characters successfully, but sometimes it
7098 * causes unexpected error in another part. We make it an error explicitly
7099 * here. */
7100 if (strlen(name) >= _MAX_PATH)
7101 return -1;
7102
Bram Moolenaar071d4272004-06-13 20:20:40 +00007103 return open(name, flags, mode);
7104}
7105
7106/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007107 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007108 */
7109 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02007110mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007111{
7112 WCHAR *wn, *wm;
7113 FILE *f = NULL;
7114
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007115 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007116 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007117# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007118 /* Work around an annoying assertion in the Microsoft debug CRT
7119 * when mode's text/binary setting doesn't match _get_fmode(). */
7120 char newMode = mode[strlen(mode) - 1];
7121 int oldMode = 0;
7122
7123 _get_fmode(&oldMode);
7124 if (newMode == 't')
7125 _set_fmode(_O_TEXT);
7126 else if (newMode == 'b')
7127 _set_fmode(_O_BINARY);
7128# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01007129 wn = enc_to_utf16((char_u *)name, NULL);
7130 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007131 if (wn != NULL && wm != NULL)
7132 f = _wfopen(wn, wm);
7133 vim_free(wn);
7134 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007135
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00007136# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00007137 _set_fmode(oldMode);
7138# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007139 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007140 }
7141
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01007142 /* fopen() can open a file which name is longer than _MAX_PATH bytes
7143 * and shorter than _MAX_PATH characters successfully, but sometimes it
7144 * causes unexpected error in another part. We make it an error explicitly
7145 * here. */
7146 if (strlen(name) >= _MAX_PATH)
7147 return NULL;
7148
Bram Moolenaar071d4272004-06-13 20:20:40 +00007149 return fopen(name, mode);
7150}
7151#endif
7152
7153#ifdef FEAT_MBYTE
7154/*
7155 * SUB STREAM (aka info stream) handling:
7156 *
7157 * NTFS can have sub streams for each file. Normal contents of file is
7158 * stored in the main stream, and extra contents (author information and
7159 * title and so on) can be stored in sub stream. After Windows 2000, user
7160 * can access and store those informations in sub streams via explorer's
7161 * property menuitem in right click menu. Those informations in sub streams
7162 * were lost when copying only the main stream. So we have to copy sub
7163 * streams.
7164 *
7165 * Incomplete explanation:
7166 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
7167 * More useful info and an example:
7168 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
7169 */
7170
7171/*
7172 * Copy info stream data "substream". Read from the file with BackupRead(sh)
7173 * and write to stream "substream" of file "to".
7174 * Errors are ignored.
7175 */
7176 static void
7177copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
7178{
7179 HANDLE hTo;
7180 WCHAR *to_name;
7181
7182 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
7183 wcscpy(to_name, to);
7184 wcscat(to_name, substream);
7185
7186 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
7187 FILE_ATTRIBUTE_NORMAL, NULL);
7188 if (hTo != INVALID_HANDLE_VALUE)
7189 {
7190 long done;
7191 DWORD todo;
7192 DWORD readcnt, written;
7193 char buf[4096];
7194
7195 /* Copy block of bytes at a time. Abort when something goes wrong. */
7196 for (done = 0; done < len; done += written)
7197 {
7198 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007199 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
7200 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007201 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
7202 FALSE, FALSE, context)
7203 || readcnt != todo
7204 || !WriteFile(hTo, buf, todo, &written, NULL)
7205 || written != todo)
7206 break;
7207 }
7208 CloseHandle(hTo);
7209 }
7210
7211 free(to_name);
7212}
7213
7214/*
7215 * Copy info streams from file "from" to file "to".
7216 */
7217 static void
7218copy_infostreams(char_u *from, char_u *to)
7219{
7220 WCHAR *fromw;
7221 WCHAR *tow;
7222 HANDLE sh;
7223 WIN32_STREAM_ID sid;
7224 int headersize;
7225 WCHAR streamname[_MAX_PATH];
7226 DWORD readcount;
7227 void *context = NULL;
7228 DWORD lo, hi;
7229 int len;
7230
7231 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007232 fromw = enc_to_utf16(from, NULL);
7233 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007234 if (fromw != NULL && tow != NULL)
7235 {
7236 /* Open the file for reading. */
7237 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
7238 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
7239 if (sh != INVALID_HANDLE_VALUE)
7240 {
7241 /* Use BackupRead() to find the info streams. Repeat until we
7242 * have done them all.*/
7243 for (;;)
7244 {
7245 /* Get the header to find the length of the stream name. If
7246 * the "readcount" is zero we have done all info streams. */
7247 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007248 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007249 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
7250 &readcount, FALSE, FALSE, &context)
7251 || readcount == 0)
7252 break;
7253
7254 /* We only deal with streams that have a name. The normal
7255 * file data appears to be without a name, even though docs
7256 * suggest it is called "::$DATA". */
7257 if (sid.dwStreamNameSize > 0)
7258 {
7259 /* Read the stream name. */
7260 if (!BackupRead(sh, (LPBYTE)streamname,
7261 sid.dwStreamNameSize,
7262 &readcount, FALSE, FALSE, &context))
7263 break;
7264
7265 /* Copy an info stream with a name ":anything:$DATA".
7266 * Skip "::$DATA", it has no stream name (examples suggest
7267 * it might be used for the normal file contents).
7268 * Note that BackupRead() counts bytes, but the name is in
7269 * wide characters. */
7270 len = readcount / sizeof(WCHAR);
7271 streamname[len] = 0;
7272 if (len > 7 && wcsicmp(streamname + len - 6,
7273 L":$DATA") == 0)
7274 {
7275 streamname[len - 6] = 0;
7276 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00007277 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007278 }
7279 }
7280
7281 /* Advance to the next stream. We might try seeking too far,
7282 * but BackupSeek() doesn't skip over stream borders, thus
7283 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00007284 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007285 &lo, &hi, &context);
7286 }
7287
7288 /* Clear the context. */
7289 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
7290
7291 CloseHandle(sh);
7292 }
7293 }
7294 vim_free(fromw);
7295 vim_free(tow);
7296}
7297#endif
7298
7299/*
7300 * Copy file attributes from file "from" to file "to".
7301 * For Windows NT and later we copy info streams.
7302 * Always returns zero, errors are ignored.
7303 */
7304 int
7305mch_copy_file_attribute(char_u *from, char_u *to)
7306{
7307#ifdef FEAT_MBYTE
7308 /* File streams only work on Windows NT and later. */
7309 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007310 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007311#endif
7312 return 0;
7313}
7314
7315#if defined(MYRESETSTKOFLW) || defined(PROTO)
7316/*
7317 * Recreate a destroyed stack guard page in win32.
7318 * Written by Benjamin Peterson.
7319 */
7320
7321/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007322#define MIN_STACK_WINNT 2
7323
7324/*
7325 * This function does the same thing as _resetstkoflw(), which is only
7326 * available in DevStudio .net and later.
7327 * Returns 0 for failure, 1 for success.
7328 */
7329 int
7330myresetstkoflw(void)
7331{
7332 BYTE *pStackPtr;
7333 BYTE *pGuardPage;
7334 BYTE *pStackBase;
7335 BYTE *pLowestPossiblePage;
7336 MEMORY_BASIC_INFORMATION mbi;
7337 SYSTEM_INFO si;
7338 DWORD nPageSize;
7339 DWORD dummy;
7340
Bram Moolenaar071d4272004-06-13 20:20:40 +00007341 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00007342
7343 /* We need to know the system page size. */
7344 GetSystemInfo(&si);
7345 nPageSize = si.dwPageSize;
7346
7347 /* ...and the current stack pointer */
7348 pStackPtr = (BYTE*)_alloca(1);
7349
7350 /* ...and the base of the stack. */
7351 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
7352 return 0;
7353 pStackBase = (BYTE*)mbi.AllocationBase;
7354
7355 /* ...and the page thats min_stack_req pages away from stack base; this is
7356 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007357 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007358
Bram Moolenaar071d4272004-06-13 20:20:40 +00007359 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02007360 /* We want the first committed page in the stack Start at the stack
7361 * base and move forward through memory until we find a committed block.
7362 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007363 BYTE *pBlock = pStackBase;
7364
Bram Moolenaara466c992005-07-09 21:03:22 +00007365 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007366 {
7367 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
7368 return 0;
7369
7370 pBlock += mbi.RegionSize;
7371
7372 if (mbi.State & MEM_COMMIT)
7373 break;
7374 }
7375
7376 /* mbi now describes the first committed block in the stack. */
7377 if (mbi.Protect & PAGE_GUARD)
7378 return 1;
7379
7380 /* decide where the guard page should start */
7381 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
7382 pGuardPage = pLowestPossiblePage;
7383 else
7384 pGuardPage = (BYTE*)mbi.BaseAddress;
7385
7386 /* allocate the guard page */
7387 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
7388 return 0;
7389
7390 /* apply the guard attribute to the page */
7391 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
7392 &dummy))
7393 return 0;
7394 }
7395
7396 return 1;
7397}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007398#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007399
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007400
7401#if defined(FEAT_MBYTE) || defined(PROTO)
7402/*
7403 * The command line arguments in UCS2
7404 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007405static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007406static LPWSTR *ArglistW = NULL;
7407static int global_argc = 0;
7408static char **global_argv;
7409
7410static int used_file_argc = 0; /* last argument in global_argv[] used
7411 for the argument list. */
7412static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7413 command line arguments added to
7414 the argument list */
7415static int used_file_count = 0; /* nr of entries in used_file_indexes */
7416static int used_file_literal = FALSE; /* take file names literally */
7417static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007418static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007419static int used_alist_count = 0;
7420
7421
7422/*
7423 * Get the command line arguments. Unicode version.
7424 * Returns argc. Zero when something fails.
7425 */
7426 int
7427get_cmd_argsW(char ***argvp)
7428{
7429 char **argv = NULL;
7430 int argc = 0;
7431 int i;
7432
Bram Moolenaar14993322014-09-09 12:25:33 +02007433 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007434 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7435 if (ArglistW != NULL)
7436 {
7437 argv = malloc((nArgsW + 1) * sizeof(char *));
7438 if (argv != NULL)
7439 {
7440 argc = nArgsW;
7441 argv[argc] = NULL;
7442 for (i = 0; i < argc; ++i)
7443 {
7444 int len;
7445
7446 /* Convert each Unicode argument to the current codepage. */
7447 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007448 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007449 (LPSTR *)&argv[i], &len, 0, 0);
7450 if (argv[i] == NULL)
7451 {
7452 /* Out of memory, clear everything. */
7453 while (i > 0)
7454 free(argv[--i]);
7455 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007456 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007457 argc = 0;
7458 }
7459 }
7460 }
7461 }
7462
7463 global_argc = argc;
7464 global_argv = argv;
7465 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007466 {
7467 if (used_file_indexes != NULL)
7468 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007469 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007470 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007471
7472 if (argvp != NULL)
7473 *argvp = argv;
7474 return argc;
7475}
7476
7477 void
7478free_cmd_argsW(void)
7479{
7480 if (ArglistW != NULL)
7481 {
7482 GlobalFree(ArglistW);
7483 ArglistW = NULL;
7484 }
7485}
7486
7487/*
7488 * Remember "name" is an argument that was added to the argument list.
7489 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7490 * is called.
7491 */
7492 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007493used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007494{
7495 int i;
7496
7497 if (used_file_indexes == NULL)
7498 return;
7499 for (i = used_file_argc + 1; i < global_argc; ++i)
7500 if (STRCMP(global_argv[i], name) == 0)
7501 {
7502 used_file_argc = i;
7503 used_file_indexes[used_file_count++] = i;
7504 break;
7505 }
7506 used_file_literal = literal;
7507 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007508 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007509}
7510
7511/*
7512 * Remember the length of the argument list as it was. If it changes then we
7513 * leave it alone when 'encoding' is set.
7514 */
7515 void
7516set_alist_count(void)
7517{
7518 used_alist_count = GARGCOUNT;
7519}
7520
7521/*
7522 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7523 * has been changed while starting up. Use the UCS-2 command line arguments
7524 * and convert them to 'encoding'.
7525 */
7526 void
7527fix_arg_enc(void)
7528{
7529 int i;
7530 int idx;
7531 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007532 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007533
7534 /* Safety checks:
7535 * - if argument count differs between the wide and non-wide argument
7536 * list, something must be wrong.
7537 * - the file name arguments must have been located.
7538 * - the length of the argument list wasn't changed by the user.
7539 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007540 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007541 || ArglistW == NULL
7542 || used_file_indexes == NULL
7543 || used_file_count == 0
7544 || used_alist_count != GARGCOUNT)
7545 return;
7546
Bram Moolenaar86b68352004-12-27 21:59:20 +00007547 /* Remember the buffer numbers for the arguments. */
7548 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7549 if (fnum_list == NULL)
7550 return; /* out of memory */
7551 for (i = 0; i < GARGCOUNT; ++i)
7552 fnum_list[i] = GARGLIST[i].ae_fnum;
7553
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007554 /* Clear the argument list. Make room for the new arguments. */
7555 alist_clear(&global_alist);
7556 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007557 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007558
7559 for (i = 0; i < used_file_count; ++i)
7560 {
7561 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007562 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007563 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007564 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007565 int literal = used_file_literal;
7566
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007567#ifdef FEAT_DIFF
7568 /* When using diff mode may need to concatenate file name to
7569 * directory name. Just like it's done in main(). */
7570 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7571 && !mch_isdir(alist_name(&GARGLIST[0])))
7572 {
7573 char_u *r;
7574
7575 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7576 if (r != NULL)
7577 {
7578 vim_free(str);
7579 str = r;
7580 }
7581 }
7582#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007583 /* Re-use the old buffer by renaming it. When not using literal
7584 * names it's done by alist_expand() below. */
7585 if (used_file_literal)
7586 buf_set_name(fnum_list[i], str);
7587
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007588 /* Check backtick literal. backtick literal is already expanded in
7589 * main.c, so this part add str as literal. */
7590 if (literal == FALSE)
7591 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007592 size_t len = STRLEN(str);
7593
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007594 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7595 literal = TRUE;
7596 }
7597 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007598 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007599 }
7600
7601 if (!used_file_literal)
7602 {
7603 /* Now expand wildcards in the arguments. */
7604 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7605 * filename characters but are excluded from 'isfname' to make
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007606 * "gf" work on a file name in parenthesis (e.g.: see vim.h).
7607 * Also, unset wildignore to not be influenced by this option.
7608 * The arguments specified in command-line should be kept even if
7609 * encoding options were changed. */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007610 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007611 do_cmdline_cmd((char_u *)":let SaVe_WIG = &wig|set wig=");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007612 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007613 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
Bram Moolenaar20586cb2018-03-08 22:03:14 +01007614 do_cmdline_cmd((char_u *)":let &wig = SaVe_WIG|unlet SaVe_WIG");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007615 }
7616
7617 /* If wildcard expansion failed, we are editing the first file of the
7618 * arglist and there is no file name: Edit the first argument now. */
7619 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7620 {
7621 do_cmdline_cmd((char_u *)":rewind");
7622 if (GARGCOUNT == 1 && used_file_full_path)
Bram Moolenaarb7407d32018-02-03 17:36:27 +01007623 (void)vim_chdirfile(alist_name(&GARGLIST[0]), "drop");
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007624 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007625
7626 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007627}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007628#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007629
7630 int
7631mch_setenv(char *var, char *value, int x)
7632{
7633 char_u *envbuf;
7634
7635 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7636 if (envbuf == NULL)
7637 return -1;
7638
7639 sprintf((char *)envbuf, "%s=%s", var, value);
7640
7641#ifdef FEAT_MBYTE
7642 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7643 {
7644 WCHAR *p = enc_to_utf16(envbuf, NULL);
7645
7646 vim_free(envbuf);
7647 if (p == NULL)
7648 return -1;
7649 _wputenv(p);
7650# ifdef libintl_wputenv
7651 libintl_wputenv(p);
7652# endif
7653 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7654 vim_free(p);
7655 }
7656 else
7657#endif
7658 {
7659 _putenv((char *)envbuf);
7660# ifdef libintl_putenv
7661 libintl_putenv((char *)envbuf);
7662# endif
7663 /* Unlike Un*x systems, we can free the string for _putenv(). */
7664 vim_free(envbuf);
7665 }
7666
7667 return 0;
7668}
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007669
7670#ifndef FEAT_GUI_W32
7671
7672/*
7673 * Support for 256 colors and 24-bit colors was added in Windows 10
7674 * version 1703 (Creators update).
7675 */
7676# define VTP_FIRST_SUPPORT_BUILD MAKE_VER(10, 0, 15063)
7677
7678 static void
7679vtp_init(void)
7680{
7681 DWORD ver, mode;
7682 HMODULE hKerneldll;
7683 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007684# ifdef FEAT_TERMGUICOLORS
7685 COLORREF fg, bg;
7686# endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007687
7688 ver = get_build_number();
7689 vtp_working = (ver >= VTP_FIRST_SUPPORT_BUILD) ? 1 : 0;
7690 GetConsoleMode(g_hConOut, &mode);
7691 mode |= (ENABLE_PROCESSED_OUTPUT | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
7692 if (SetConsoleMode(g_hConOut, mode) == 0)
7693 vtp_working = 0;
7694
7695 /* Use functions supported from Vista */
7696 hKerneldll = GetModuleHandle("kernel32.dll");
7697 if (hKerneldll != NULL)
7698 {
7699 pGetConsoleScreenBufferInfoEx =
7700 (PfnGetConsoleScreenBufferInfoEx)GetProcAddress(
7701 hKerneldll, "GetConsoleScreenBufferInfoEx");
7702 pSetConsoleScreenBufferInfoEx =
7703 (PfnSetConsoleScreenBufferInfoEx)GetProcAddress(
7704 hKerneldll, "SetConsoleScreenBufferInfoEx");
7705 if (pGetConsoleScreenBufferInfoEx != NULL
7706 && pSetConsoleScreenBufferInfoEx != NULL)
7707 has_csbiex = TRUE;
7708 }
7709
7710 csbi.cbSize = sizeof(csbi);
7711 if (has_csbiex)
7712 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007713 save_console_bg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_bg];
7714 save_console_fg_rgb = (guicolor_T)csbi.ColorTable[g_color_index_fg];
7715
7716# ifdef FEAT_TERMGUICOLORS
7717 bg = (COLORREF)csbi.ColorTable[g_color_index_bg];
7718 fg = (COLORREF)csbi.ColorTable[g_color_index_fg];
7719 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
7720 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7721 default_console_color_bg = bg;
7722 default_console_color_fg = fg;
7723#endif
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007724
7725 set_console_color_rgb();
7726}
7727
7728 static void
7729vtp_exit(void)
7730{
7731 reset_console_color_rgb();
7732}
7733
7734 static int
7735vtp_printf(
7736 char *format,
7737 ...)
7738{
7739 char_u buf[100];
7740 va_list list;
7741 DWORD result;
7742
7743 va_start(list, format);
7744 vim_vsnprintf((char *)buf, 100, (char *)format, list);
7745 va_end(list);
7746 WriteConsoleA(g_hConOut, buf, (DWORD)STRLEN(buf), &result, NULL);
7747 return (int)result;
7748}
7749
7750 static void
7751vtp_sgr_bulk(
7752 int arg)
7753{
7754 int args[1];
7755
7756 args[0] = arg;
7757 vtp_sgr_bulks(1, args);
7758}
7759
7760 static void
7761vtp_sgr_bulks(
7762 int argc,
7763 int *args
7764)
7765{
7766 /* 2('\033[') + 4('255.') * 16 + NUL */
7767 char_u buf[2 + (4 * 16) + 1];
7768 char_u *p;
7769 int i;
7770
7771 p = buf;
7772 *p++ = '\033';
7773 *p++ = '[';
7774
7775 for (i = 0; i < argc; ++i)
7776 {
7777 p += vim_snprintf((char *)p, 4, "%d", args[i] & 0xff);
7778 *p++ = ';';
7779 }
7780 p--;
7781 *p++ = 'm';
7782 *p = NUL;
7783 vtp_printf((char *)buf);
7784}
7785
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007786# ifdef FEAT_TERMGUICOLORS
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007787 static int
7788ctermtoxterm(
7789 int cterm)
7790{
Bram Moolenaar9894e392018-05-05 14:29:06 +02007791 char_u r, g, b, idx;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007792
7793 cterm_color2rgb(cterm, &r, &g, &b, &idx);
7794 return (((int)r << 16) | ((int)g << 8) | (int)b);
7795}
Bram Moolenaar8a938af2018-05-01 17:30:41 +02007796# endif
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007797
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007798 static void
7799set_console_color_rgb(void)
7800{
7801# ifdef FEAT_TERMGUICOLORS
7802 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7803 int id;
7804 guicolor_T fg = INVALCOLOR;
7805 guicolor_T bg = INVALCOLOR;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007806 int ctermfg;
7807 int ctermbg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007808
7809 if (!USE_VTP)
7810 return;
7811
7812 id = syn_name2id((char_u *)"Normal");
7813 if (id > 0)
7814 syn_id2colors(id, &fg, &bg);
7815 if (fg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007816 {
7817 ctermfg = -1;
7818 if (id > 0)
7819 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007820 fg = ctermfg != -1 ? ctermtoxterm(ctermfg) : default_console_color_fg;
7821 cterm_normal_fg_gui_color = fg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007822 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007823 if (bg == INVALCOLOR)
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007824 {
7825 ctermbg = -1;
7826 if (id > 0)
7827 syn_id2cterm_bg(id, &ctermfg, &ctermbg);
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007828 bg = ctermbg != -1 ? ctermtoxterm(ctermbg) : default_console_color_bg;
7829 cterm_normal_bg_gui_color = bg;
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007830 }
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007831 fg = (GetRValue(fg) << 16) | (GetGValue(fg) << 8) | GetBValue(fg);
7832 bg = (GetRValue(bg) << 16) | (GetGValue(bg) << 8) | GetBValue(bg);
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)bg;
7842 csbi.ColorTable[g_color_index_fg] = (COLORREF)fg;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007843 if (has_csbiex)
7844 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7845# endif
7846}
7847
7848 static void
7849reset_console_color_rgb(void)
7850{
7851# ifdef FEAT_TERMGUICOLORS
7852 DYN_CONSOLE_SCREEN_BUFFER_INFOEX csbi;
7853
7854 csbi.cbSize = sizeof(csbi);
7855 if (has_csbiex)
7856 pGetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7857
7858 csbi.cbSize = sizeof(csbi);
7859 csbi.srWindow.Right += 1;
7860 csbi.srWindow.Bottom += 1;
Bram Moolenaarf6ceaf12018-08-30 17:47:05 +02007861 csbi.ColorTable[g_color_index_bg] = (COLORREF)save_console_bg_rgb;
7862 csbi.ColorTable[g_color_index_fg] = (COLORREF)save_console_fg_rgb;
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007863 if (has_csbiex)
7864 pSetConsoleScreenBufferInfoEx(g_hConOut, &csbi);
7865# endif
7866}
7867
7868 void
7869control_console_color_rgb(void)
7870{
7871 if (USE_VTP)
7872 set_console_color_rgb();
7873 else
7874 reset_console_color_rgb();
7875}
7876
7877 int
7878has_vtp_working(void)
7879{
7880 return vtp_working;
7881}
7882
7883 int
7884use_vtp(void)
7885{
7886 return USE_VTP;
7887}
7888
Bram Moolenaarc5cd8852018-05-01 15:47:38 +02007889 int
7890is_term_win32(void)
7891{
7892 return T_NAME != NULL && STRCMP(T_NAME, "win32") == 0;
7893}
7894
Bram Moolenaarcafafb32018-02-22 21:07:09 +01007895#endif