blob: e08adcbb19c8dc72bbb26556e57f5f5a63f9115c [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;
114typedef int KEY_EVENT_RECORD;
115typedef int LOGFONT;
116typedef int LPBOOL;
117typedef int LPCTSTR;
118typedef int LPDWORD;
119typedef int LPSTR;
120typedef int LPTSTR;
121typedef int LPVOID;
122typedef int MOUSE_EVENT_RECORD;
123typedef int PACL;
124typedef int PDWORD;
125typedef int PHANDLE;
126typedef int PRINTDLG;
127typedef int PSECURITY_DESCRIPTOR;
128typedef int PSID;
129typedef int SECURITY_INFORMATION;
130typedef int SHORT;
131typedef int SMALL_RECT;
132typedef int TEXTMETRIC;
133typedef int TOKEN_INFORMATION_CLASS;
134typedef int TRUSTEE;
135typedef int WORD;
136typedef int WCHAR;
137typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100138typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200139typedef int SE_OBJECT_TYPE;
140typedef int PSNSECINFO;
141typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100142typedef int STARTUPINFO;
143typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200144typedef int LPSECURITY_ATTRIBUTES;
145# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146#endif
147
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#if defined(__BORLANDC__)
149/* Strangely Borland uses a non-standard name. */
150# define wcsicmp(a, b) wcscmpi((a), (b))
151#endif
152
153#ifndef FEAT_GUI_W32
154/* Win32 Console handles for input and output */
155static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
156static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
157
158/* Win32 Screen buffer,coordinate,console I/O information */
159static SMALL_RECT g_srScrollRegion;
160static COORD g_coord; /* 0-based, but external coords are 1-based */
161
162/* The attribute of the screen when the editor was started */
163static WORD g_attrDefault = 7; /* lightgray text on black background */
164static WORD g_attrCurrent;
165
166static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
167static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
168static int g_fForceExit = FALSE; /* set when forcefully exiting */
169
170static void termcap_mode_start(void);
171static void termcap_mode_end(void);
172static void clear_chars(COORD coord, DWORD n);
173static void clear_screen(void);
174static void clear_to_end_of_display(void);
175static void clear_to_end_of_line(void);
176static void scroll(unsigned cLines);
177static void set_scroll_region(unsigned left, unsigned top,
178 unsigned right, unsigned bottom);
179static void insert_lines(unsigned cLines);
180static void delete_lines(unsigned cLines);
181static void gotoxy(unsigned x, unsigned y);
182static void normvideo(void);
183static void textattr(WORD wAttr);
184static void textcolor(WORD wAttr);
185static void textbackground(WORD wAttr);
186static void standout(void);
187static void standend(void);
188static void visual_bell(void);
189static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200190static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000191static void create_conin(void);
192static int s_cursor_visible = TRUE;
193static int did_create_conin = FALSE;
194#else
195static int s_dont_use_vimrun = TRUE;
196static int need_vimrun_warning = FALSE;
197static char *vimrun_path = "vimrun ";
198#endif
199
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200200static int win32_getattrs(char_u *name);
201static int win32_setattrs(char_u *name, int attrs);
202static int win32_set_archive(char_u *name);
203
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204#ifndef FEAT_GUI_W32
205static int suppress_winsize = 1; /* don't fiddle with console */
206#endif
207
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200208static char_u *exe_path = NULL;
209
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100210static BOOL win8_or_later = FALSE;
211
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100212#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100213/*
214 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100215 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100216 */
217 static BOOL
218read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100219 HANDLE hInput,
220 INPUT_RECORD *lpBuffer,
221 DWORD nLength,
222 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100223{
224 enum
225 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100226 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100227 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100228 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100229 static DWORD s_dwIndex = 0;
230 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100231 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100232 int head;
233 int tail;
234 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100235
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200236 if (nLength == -2)
237 return (s_dwMax > 0) ? TRUE : FALSE;
238
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100239 if (!win8_or_later)
240 {
241 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200242 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
243 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100244 }
245
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100246 if (s_dwMax == 0)
247 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100248 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200249 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
250 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100251 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100252 s_dwIndex = 0;
253 s_dwMax = dwEvents;
254 if (dwEvents == 0)
255 {
256 *lpEvents = 0;
257 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100258 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100259
260 if (s_dwMax > 1)
261 {
262 head = 0;
263 tail = s_dwMax - 1;
264 while (head != tail)
265 {
266 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
267 && s_irCache[head + 1].EventType
268 == WINDOW_BUFFER_SIZE_EVENT)
269 {
270 /* Remove duplicate event to avoid flicker. */
271 for (i = head; i < tail; ++i)
272 s_irCache[i] = s_irCache[i + 1];
273 --tail;
274 continue;
275 }
276 head++;
277 }
278 s_dwMax = tail + 1;
279 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100281
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100282 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200283 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100284 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100285 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100286 return TRUE;
287}
288
289/*
290 * Version of PeekConsoleInput() that works with IME.
291 */
292 static BOOL
293peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100299 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100300}
301
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100302# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200303 static DWORD
304msg_wait_for_multiple_objects(
305 DWORD nCount,
306 LPHANDLE pHandles,
307 BOOL fWaitAll,
308 DWORD dwMilliseconds,
309 DWORD dwWakeMask)
310{
311 if (read_console_input(NULL, NULL, -2, NULL))
312 return WAIT_OBJECT_0;
313 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
314 dwMilliseconds, dwWakeMask);
315}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100316# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200317
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100318# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200319 static DWORD
320wait_for_single_object(
321 HANDLE hHandle,
322 DWORD dwMilliseconds)
323{
324 if (read_console_input(NULL, NULL, -2, NULL))
325 return WAIT_OBJECT_0;
326 return WaitForSingleObject(hHandle, dwMilliseconds);
327}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100328# endif
329#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200330
Bram Moolenaar071d4272004-06-13 20:20:40 +0000331 static void
332get_exe_name(void)
333{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100334 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
335 * as the maximum length that works (plus a NUL byte). */
336#define MAX_ENV_PATH_LEN 8192
337 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200338 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000339
340 if (exe_name == NULL)
341 {
342 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100343 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 if (*temp != NUL)
345 exe_name = FullName_save((char_u *)temp, FALSE);
346 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000347
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200348 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000349 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200350 exe_path = vim_strnsave(exe_name,
351 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200352 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000353 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200354 /* Append our starting directory to $PATH, so that when doing
355 * "!xxd" it's found in our starting directory. Needed because
356 * SearchPath() also looks there. */
357 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100358 if (p == NULL
359 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200360 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100361 if (p == NULL || *p == NUL)
362 temp[0] = NUL;
363 else
364 {
365 STRCPY(temp, p);
366 STRCAT(temp, ";");
367 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200368 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100369 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200370 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000371 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373}
374
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200375/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100376 * Unescape characters in "p" that appear in "escaped".
377 */
378 static void
379unescape_shellxquote(char_u *p, char_u *escaped)
380{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100381 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100382 int n;
383
384 while (*p != NUL)
385 {
386 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
387 mch_memmove(p, p + 1, l--);
388#ifdef FEAT_MBYTE
389 n = (*mb_ptr2len)(p);
390#else
391 n = 1;
392#endif
393 p += n;
394 l -= n;
395 }
396}
397
398/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200399 * Load library "name".
400 */
401 HINSTANCE
402vimLoadLib(char *name)
403{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200404 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200405
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200406 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
407 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200408 if (exe_path == NULL)
409 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200410 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200411 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200412 WCHAR old_dirw[MAXPATHL];
413
414 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
415 {
416 /* Change directory to where the executable is, both to make
417 * sure we find a .dll there and to avoid looking for a .dll
418 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100419 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200420 dll = LoadLibrary(name);
421 SetCurrentDirectoryW(old_dirw);
422 return dll;
423 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200424 }
425 return dll;
426}
427
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
429# ifndef GETTEXT_DLL
430# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100431# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200433/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000434static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200435static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000436static char *null_libintl_textdomain(const char *);
437static char *null_libintl_bindtextdomain(const char *, const char *);
438static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200440static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000441char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200442char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
443 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000444char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
445char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000447char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
448 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449
450 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100451dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452{
453 int i;
454 static struct
455 {
456 char *name;
457 FARPROC *ptr;
458 } libintl_entry[] =
459 {
460 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200461 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000462 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
463 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
464 {NULL, NULL}
465 };
466
467 /* No need to initialize twice. */
468 if (hLibintlDLL)
469 return 1;
470 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100471 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100472#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100473 if (!hLibintlDLL)
474 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100475#endif
476 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480 verbose_enter();
481 EMSG2(_(e_loadlib), GETTEXT_DLL);
482 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000483 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200484 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000485 }
486 for (i = 0; libintl_entry[i].name != NULL
487 && libintl_entry[i].ptr != NULL; ++i)
488 {
489 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
490 libintl_entry[i].name)) == NULL)
491 {
492 dyn_libintl_end();
493 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000494 {
495 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000497 verbose_leave();
498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000499 return 0;
500 }
501 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000502
503 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000504 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000505 "bind_textdomain_codeset");
506 if (dyn_libintl_bind_textdomain_codeset == NULL)
507 dyn_libintl_bind_textdomain_codeset =
508 null_libintl_bind_textdomain_codeset;
509
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510 return 1;
511}
512
513 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100514dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515{
516 if (hLibintlDLL)
517 FreeLibrary(hLibintlDLL);
518 hLibintlDLL = NULL;
519 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200520 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521 dyn_libintl_textdomain = null_libintl_textdomain;
522 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000523 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524}
525
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000526/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000527 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000528null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529{
530 return (char*)msgid;
531}
532
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000533/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000534 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200535null_libintl_ngettext(
536 const char *msgid,
537 const char *msgid_plural,
538 unsigned long n)
539{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200540 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200541}
542
543/*ARGSUSED*/
544 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000545null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000546{
547 return NULL;
548}
549
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000550/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000551 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000552null_libintl_bind_textdomain_codeset(const char *domainname,
553 const char *codeset)
554{
555 return NULL;
556}
557
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000558/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000559 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000560null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561{
562 return NULL;
563}
564
565#endif /* DYNAMIC_GETTEXT */
566
567/* This symbol is not defined in older versions of the SDK or Visual C++ */
568
569#ifndef VER_PLATFORM_WIN32_WINDOWS
570# define VER_PLATFORM_WIN32_WINDOWS 1
571#endif
572
573DWORD g_PlatformId;
574
575#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100576# ifndef PROTO
577# include <aclapi.h>
578# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200579# ifndef PROTECTED_DACL_SECURITY_INFORMATION
580# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
581# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582#endif
583
Bram Moolenaar27515922013-06-29 15:36:26 +0200584#ifdef HAVE_ACL
585/*
586 * Enables or disables the specified privilege.
587 */
588 static BOOL
589win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
590{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100591 BOOL bResult;
592 LUID luid;
593 HANDLE hToken;
594 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200595
596 if (!OpenProcessToken(GetCurrentProcess(),
597 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
598 return FALSE;
599
600 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
601 {
602 CloseHandle(hToken);
603 return FALSE;
604 }
605
Bram Moolenaar45500912014-07-09 20:51:07 +0200606 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200607 tokenPrivileges.Privileges[0].Luid = luid;
608 tokenPrivileges.Privileges[0].Attributes = bEnable ?
609 SE_PRIVILEGE_ENABLED : 0;
610
611 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
612 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
613
614 CloseHandle(hToken);
615
616 return bResult && GetLastError() == ERROR_SUCCESS;
617}
618#endif
619
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620/*
621 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
622 * VER_PLATFORM_WIN32_WINDOWS (Win95).
623 */
624 void
625PlatformId(void)
626{
627 static int done = FALSE;
628
629 if (!done)
630 {
631 OSVERSIONINFO ovi;
632
633 ovi.dwOSVersionInfoSize = sizeof(ovi);
634 GetVersionEx(&ovi);
635
636 g_PlatformId = ovi.dwPlatformId;
637
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100638 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
639 || ovi.dwMajorVersion > 6)
640 win8_or_later = TRUE;
641
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200643 /* Enable privilege for getting or setting SACLs. */
644 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000645#endif
646 done = TRUE;
647 }
648}
649
Bram Moolenaar071d4272004-06-13 20:20:40 +0000650#ifndef FEAT_GUI_W32
651
652#define SHIFT (SHIFT_PRESSED)
653#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
654#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
655#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
656
657
658/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
659 * We map function keys to their ANSI terminal equivalents, as produced
660 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
661 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
662 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
663 * combinations of function/arrow/etc keys.
664 */
665
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000666static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000667{
668 WORD wVirtKey;
669 BOOL fAnsiKey;
670 int chAlone;
671 int chShift;
672 int chCtrl;
673 int chAlt;
674} VirtKeyMap[] =
675{
676
677/* Key ANSI alone shift ctrl alt */
678 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
679
680 { VK_F1, TRUE, ';', 'T', '^', 'h', },
681 { VK_F2, TRUE, '<', 'U', '_', 'i', },
682 { VK_F3, TRUE, '=', 'V', '`', 'j', },
683 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
684 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
685 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
686 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
687 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
688 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
689 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
690 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
691 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
692
693 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
694 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
695 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
696 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
697 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
698 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
699 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
700 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
701 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
702 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
703
704 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
705
706#if 0
707 /* Most people don't have F13-F20, but what the hell... */
708 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
709 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
710 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
711 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
712 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
713 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
714 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
715 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
716#endif
717 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
718 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
719 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
720 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
721
722 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
723 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
724 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
725 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
726 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
727 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
728 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
729 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
730 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
731 /* Sorry, out of number space! <negri>*/
732 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
733
734};
735
736
737#ifdef _MSC_VER
738// The ToAscii bug destroys several registers. Need to turn off optimization
739// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000740# pragma warning(push)
741# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742# pragma optimize("", off)
743#endif
744
745#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200746# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200748# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000749#endif
750
751/* The return code indicates key code size. */
752 static int
753#ifdef __BORLANDC__
754 __stdcall
755#endif
756win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000757 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758{
759 UINT uMods = pker->dwControlKeyState;
760 static int s_iIsDead = 0;
761 static WORD awAnsiCode[2];
762 static BYTE abKeystate[256];
763
764
765 if (s_iIsDead == 2)
766 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200767 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768 s_iIsDead = 0;
769 return 1;
770 }
771
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200772 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773 return 1;
774
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200775 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000776
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200778 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779
780 if (uMods & SHIFT_PRESSED)
781 abKeystate[VK_SHIFT] = 0x80;
782 if (uMods & CAPSLOCK_ON)
783 abKeystate[VK_CAPITAL] = 1;
784
785 if ((uMods & ALT_GR) == ALT_GR)
786 {
787 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
788 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
789 }
790
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200791 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
792 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000793
794 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200795 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796
797 return s_iIsDead;
798}
799
800#ifdef _MSC_VER
801/* MUST switch optimization on again here, otherwise a call to
802 * decode_key_event() may crash (e.g. when hitting caps-lock) */
803# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000804# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805
806# if (_MSC_VER < 1100)
807/* MUST turn off global optimisation for this next function, or
808 * pressing ctrl-minus in insert mode crashes Vim when built with
809 * VC4.1. -- negri. */
810# pragma optimize("g", off)
811# endif
812#endif
813
814static BOOL g_fJustGotFocus = FALSE;
815
816/*
817 * Decode a KEY_EVENT into one or two keystrokes
818 */
819 static BOOL
820decode_key_event(
821 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200822 WCHAR *pch,
823 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824 int *pmodifiers,
825 BOOL fDoPost)
826{
827 int i;
828 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
829
830 *pch = *pch2 = NUL;
831 g_fJustGotFocus = FALSE;
832
833 /* ignore key up events */
834 if (!pker->bKeyDown)
835 return FALSE;
836
837 /* ignore some keystrokes */
838 switch (pker->wVirtualKeyCode)
839 {
840 /* modifiers */
841 case VK_SHIFT:
842 case VK_CONTROL:
843 case VK_MENU: /* Alt key */
844 return FALSE;
845
846 default:
847 break;
848 }
849
850 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200851 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000852 {
853 /* Ctrl-6 is Ctrl-^ */
854 if (pker->wVirtualKeyCode == '6')
855 {
856 *pch = Ctrl_HAT;
857 return TRUE;
858 }
859 /* Ctrl-2 is Ctrl-@ */
860 else if (pker->wVirtualKeyCode == '2')
861 {
862 *pch = NUL;
863 return TRUE;
864 }
865 /* Ctrl-- is Ctrl-_ */
866 else if (pker->wVirtualKeyCode == 0xBD)
867 {
868 *pch = Ctrl__;
869 return TRUE;
870 }
871 }
872
873 /* Shift-TAB */
874 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
875 {
876 *pch = K_NUL;
877 *pch2 = '\017';
878 return TRUE;
879 }
880
881 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
882 {
883 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
884 {
885 if (nModifs == 0)
886 *pch = VirtKeyMap[i].chAlone;
887 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
888 *pch = VirtKeyMap[i].chShift;
889 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
890 *pch = VirtKeyMap[i].chCtrl;
891 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
892 *pch = VirtKeyMap[i].chAlt;
893
894 if (*pch != 0)
895 {
896 if (VirtKeyMap[i].fAnsiKey)
897 {
898 *pch2 = *pch;
899 *pch = K_NUL;
900 }
901
902 return TRUE;
903 }
904 }
905 }
906
907 i = win32_kbd_patch_key(pker);
908
909 if (i < 0)
910 *pch = NUL;
911 else
912 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200913 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914
915 if (pmodifiers != NULL)
916 {
917 /* Pass on the ALT key as a modifier, but only when not combined
918 * with CTRL (which is ALTGR). */
919 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
920 *pmodifiers |= MOD_MASK_ALT;
921
922 /* Pass on SHIFT only for special keys, because we don't know when
923 * it's already included with the character. */
924 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
925 *pmodifiers |= MOD_MASK_SHIFT;
926
927 /* Pass on CTRL only for non-special keys, because we don't know
928 * when it's already included with the character. And not when
929 * combined with ALT (which is ALTGR). */
930 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
931 && *pch >= 0x20 && *pch < 0x80)
932 *pmodifiers |= MOD_MASK_CTRL;
933 }
934 }
935
936 return (*pch != NUL);
937}
938
939#ifdef _MSC_VER
940# pragma optimize("", on)
941#endif
942
943#endif /* FEAT_GUI_W32 */
944
945
946#ifdef FEAT_MOUSE
947
948/*
949 * For the GUI the mouse handling is in gui_w32.c.
950 */
951# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000952/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000954mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955{
956}
957# else
958static int g_fMouseAvail = FALSE; /* mouse present */
959static int g_fMouseActive = FALSE; /* mouse enabled */
960static int g_nMouseClick = -1; /* mouse status */
961static int g_xMouse; /* mouse x coordinate */
962static int g_yMouse; /* mouse y coordinate */
963
964/*
965 * Enable or disable mouse input
966 */
967 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000968mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969{
970 DWORD cmodein;
971
972 if (!g_fMouseAvail)
973 return;
974
975 g_fMouseActive = on;
976 GetConsoleMode(g_hConIn, &cmodein);
977
978 if (g_fMouseActive)
979 cmodein |= ENABLE_MOUSE_INPUT;
980 else
981 cmodein &= ~ENABLE_MOUSE_INPUT;
982
983 SetConsoleMode(g_hConIn, cmodein);
984}
985
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986/*
987 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
988 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
989 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
990 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
991 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
992 * and we return the mouse position in g_xMouse and g_yMouse.
993 *
994 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
995 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
996 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
997 *
998 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
999 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1000 *
1001 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1002 * moves, even if it stays within the same character cell. We ignore
1003 * all MOUSE_MOVED messages if the position hasn't really changed, and
1004 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1005 * we're only interested in MOUSE_DRAG).
1006 *
1007 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1008 * 2-button mouses by pressing the left & right buttons simultaneously.
1009 * In practice, it's almost impossible to click both at the same time,
1010 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1011 * in such cases, if the user is clicking quickly.
1012 */
1013 static BOOL
1014decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001015 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016{
1017 static int s_nOldButton = -1;
1018 static int s_nOldMouseClick = -1;
1019 static int s_xOldMouse = -1;
1020 static int s_yOldMouse = -1;
1021 static linenr_T s_old_topline = 0;
1022#ifdef FEAT_DIFF
1023 static int s_old_topfill = 0;
1024#endif
1025 static int s_cClicks = 1;
1026 static BOOL s_fReleased = TRUE;
1027 static DWORD s_dwLastClickTime = 0;
1028 static BOOL s_fNextIsMiddle = FALSE;
1029
1030 static DWORD cButtons = 0; /* number of buttons supported */
1031
1032 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1033 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1034 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1035 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1036
1037 int nButton;
1038
1039 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1040 cButtons = 2;
1041
1042 if (!g_fMouseAvail || !g_fMouseActive)
1043 {
1044 g_nMouseClick = -1;
1045 return FALSE;
1046 }
1047
1048 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1049 if (g_fJustGotFocus)
1050 {
1051 g_fJustGotFocus = FALSE;
1052 return FALSE;
1053 }
1054
1055 /* unprocessed mouse click? */
1056 if (g_nMouseClick != -1)
1057 return TRUE;
1058
1059 nButton = -1;
1060 g_xMouse = pmer->dwMousePosition.X;
1061 g_yMouse = pmer->dwMousePosition.Y;
1062
1063 if (pmer->dwEventFlags == MOUSE_MOVED)
1064 {
1065 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1066 * events even when the mouse moves only within a char cell.) */
1067 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1068 return FALSE;
1069 }
1070
1071 /* If no buttons are pressed... */
1072 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1073 {
1074 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1075 if (s_fReleased)
1076 return FALSE;
1077
1078 nButton = MOUSE_RELEASE;
1079 s_fReleased = TRUE;
1080 }
1081 else /* one or more buttons pressed */
1082 {
1083 /* on a 2-button mouse, hold down left and right buttons
1084 * simultaneously to get MIDDLE. */
1085
1086 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1087 {
1088 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1089
1090 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001091 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 if (dwLR == LEFT || dwLR == RIGHT)
1093 {
1094 for (;;)
1095 {
1096 /* wait a short time for next input event */
1097 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1098 != WAIT_OBJECT_0)
1099 break;
1100 else
1101 {
1102 DWORD cRecords = 0;
1103 INPUT_RECORD ir;
1104 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1105
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001106 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107
1108 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1109 || !(pmer2->dwButtonState & LEFT_RIGHT))
1110 break;
1111 else
1112 {
1113 if (pmer2->dwEventFlags != MOUSE_MOVED)
1114 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001115 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116
1117 return decode_mouse_event(pmer2);
1118 }
1119 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1120 s_yOldMouse == pmer2->dwMousePosition.Y)
1121 {
1122 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001123 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124
1125 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001126 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127
1128 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1129 break;
1130 }
1131 else
1132 break;
1133 }
1134 }
1135 }
1136 }
1137 }
1138
1139 if (s_fNextIsMiddle)
1140 {
1141 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1142 ? MOUSE_DRAG : MOUSE_MIDDLE;
1143 s_fNextIsMiddle = FALSE;
1144 }
1145 else if (cButtons == 2 &&
1146 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1147 {
1148 nButton = MOUSE_MIDDLE;
1149
1150 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1151 {
1152 s_fNextIsMiddle = TRUE;
1153 nButton = MOUSE_RELEASE;
1154 }
1155 }
1156 else if ((pmer->dwButtonState & LEFT) == LEFT)
1157 nButton = MOUSE_LEFT;
1158 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1159 nButton = MOUSE_MIDDLE;
1160 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1161 nButton = MOUSE_RIGHT;
1162
1163 if (! s_fReleased && ! s_fNextIsMiddle
1164 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1165 return FALSE;
1166
1167 s_fReleased = s_fNextIsMiddle;
1168 }
1169
1170 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1171 {
1172 /* button pressed or released, without mouse moving */
1173 if (nButton != -1 && nButton != MOUSE_RELEASE)
1174 {
1175 DWORD dwCurrentTime = GetTickCount();
1176
1177 if (s_xOldMouse != g_xMouse
1178 || s_yOldMouse != g_yMouse
1179 || s_nOldButton != nButton
1180 || s_old_topline != curwin->w_topline
1181#ifdef FEAT_DIFF
1182 || s_old_topfill != curwin->w_topfill
1183#endif
1184 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1185 {
1186 s_cClicks = 1;
1187 }
1188 else if (++s_cClicks > 4)
1189 {
1190 s_cClicks = 1;
1191 }
1192
1193 s_dwLastClickTime = dwCurrentTime;
1194 }
1195 }
1196 else if (pmer->dwEventFlags == MOUSE_MOVED)
1197 {
1198 if (nButton != -1 && nButton != MOUSE_RELEASE)
1199 nButton = MOUSE_DRAG;
1200
1201 s_cClicks = 1;
1202 }
1203
1204 if (nButton == -1)
1205 return FALSE;
1206
1207 if (nButton != MOUSE_RELEASE)
1208 s_nOldButton = nButton;
1209
1210 g_nMouseClick = nButton;
1211
1212 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1213 g_nMouseClick |= MOUSE_SHIFT;
1214 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1215 g_nMouseClick |= MOUSE_CTRL;
1216 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1217 g_nMouseClick |= MOUSE_ALT;
1218
1219 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1220 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1221
1222 /* only pass on interesting (i.e., different) mouse events */
1223 if (s_xOldMouse == g_xMouse
1224 && s_yOldMouse == g_yMouse
1225 && s_nOldMouseClick == g_nMouseClick)
1226 {
1227 g_nMouseClick = -1;
1228 return FALSE;
1229 }
1230
1231 s_xOldMouse = g_xMouse;
1232 s_yOldMouse = g_yMouse;
1233 s_old_topline = curwin->w_topline;
1234#ifdef FEAT_DIFF
1235 s_old_topfill = curwin->w_topfill;
1236#endif
1237 s_nOldMouseClick = g_nMouseClick;
1238
1239 return TRUE;
1240}
1241
1242# endif /* FEAT_GUI_W32 */
1243#endif /* FEAT_MOUSE */
1244
1245
1246#ifdef MCH_CURSOR_SHAPE
1247/*
1248 * Set the shape of the cursor.
1249 * 'thickness' can be from 1 (thin) to 99 (block)
1250 */
1251 static void
1252mch_set_cursor_shape(int thickness)
1253{
1254 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1255 ConsoleCursorInfo.dwSize = thickness;
1256 ConsoleCursorInfo.bVisible = s_cursor_visible;
1257
1258 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1259 if (s_cursor_visible)
1260 SetConsoleCursorPosition(g_hConOut, g_coord);
1261}
1262
1263 void
1264mch_update_cursor(void)
1265{
1266 int idx;
1267 int thickness;
1268
1269 /*
1270 * How the cursor is drawn depends on the current mode.
1271 */
1272 idx = get_shape_idx(FALSE);
1273
1274 if (shape_table[idx].shape == SHAPE_BLOCK)
1275 thickness = 99; /* 100 doesn't work on W95 */
1276 else
1277 thickness = shape_table[idx].percentage;
1278 mch_set_cursor_shape(thickness);
1279}
1280#endif
1281
1282#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1283/*
1284 * Handle FOCUS_EVENT.
1285 */
1286 static void
1287handle_focus_event(INPUT_RECORD ir)
1288{
1289 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1290 ui_focus_change((int)g_fJustGotFocus);
1291}
1292
1293/*
1294 * Wait until console input from keyboard or mouse is available,
1295 * or the time is up.
1296 * Return TRUE if something is available FALSE if not.
1297 */
1298 static int
1299WaitForChar(long msec)
1300{
1301 DWORD dwNow = 0, dwEndTime = 0;
1302 INPUT_RECORD ir;
1303 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001304 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001305#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001306 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001307#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308
1309 if (msec > 0)
1310 /* Wait until the specified time has elapsed. */
1311 dwEndTime = GetTickCount() + msec;
1312 else if (msec < 0)
1313 /* Wait forever. */
1314 dwEndTime = INFINITE;
1315
1316 /* We need to loop until the end of the time period, because
1317 * we might get multiple unusable mouse events in that time.
1318 */
1319 for (;;)
1320 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001321#ifdef MESSAGE_QUEUE
1322 parse_queued_messages();
1323#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001324#ifdef FEAT_MZSCHEME
1325 mzvim_check_threads();
1326#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327#ifdef FEAT_CLIENTSERVER
1328 serverProcessPendingMessages();
1329#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001330
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331 if (0
1332#ifdef FEAT_MOUSE
1333 || g_nMouseClick != -1
1334#endif
1335#ifdef FEAT_CLIENTSERVER
1336 || input_available()
1337#endif
1338 )
1339 return TRUE;
1340
1341 if (msec > 0)
1342 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001343 /* If the specified wait time has passed, return. Beware that
1344 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001346 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001347 break;
1348 }
1349 if (msec != 0)
1350 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001351 DWORD dwWaitTime = dwEndTime - dwNow;
1352
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001353#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001354 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001355 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001356 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001357 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001358 /* If there is readahead then parse_queued_messages() timed out
1359 * and we should call it again soon. */
1360 if (channel_any_readahead())
1361 dwWaitTime = 10;
1362 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001363#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001364#ifdef FEAT_MZSCHEME
1365 if (mzthreads_allowed() && p_mzq > 0
1366 && (msec < 0 || (long)dwWaitTime > p_mzq))
1367 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1368#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001369#ifdef FEAT_TIMERS
1370 {
1371 long due_time;
1372
1373 /* When waiting very briefly don't trigger timers. */
1374 if (dwWaitTime > 10)
1375 {
1376 /* Trigger timers and then get the time in msec until the
1377 * next one is due. Wait up to that time. */
1378 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001379 if (typebuf.tb_change_cnt != tb_change_cnt)
1380 {
1381 /* timer may have used feedkeys() */
1382 return FALSE;
1383 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001384 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1385 dwWaitTime = due_time;
1386 }
1387 }
1388#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001389#ifdef FEAT_CLIENTSERVER
1390 /* Wait for either an event on the console input or a message in
1391 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001392 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001393 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001394#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001395 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001396#endif
1397 continue;
1398 }
1399
1400 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001401 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001402
1403#ifdef FEAT_MBYTE_IME
1404 if (State & CMDLINE && msg_row == Rows - 1)
1405 {
1406 CONSOLE_SCREEN_BUFFER_INFO csbi;
1407
1408 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1409 {
1410 if (csbi.dwCursorPosition.Y != msg_row)
1411 {
1412 /* The screen is now messed up, must redraw the
1413 * command line and later all the windows. */
1414 redraw_all_later(CLEAR);
1415 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1416 redrawcmd();
1417 }
1418 }
1419 }
1420#endif
1421
1422 if (cRecords > 0)
1423 {
1424 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1425 {
1426#ifdef FEAT_MBYTE_IME
1427 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1428 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001429 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001430 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1431 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001432 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001433 continue;
1434 }
1435#endif
1436 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1437 NULL, FALSE))
1438 return TRUE;
1439 }
1440
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001441 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001442
1443 if (ir.EventType == FOCUS_EVENT)
1444 handle_focus_event(ir);
1445 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1446 shell_resized();
1447#ifdef FEAT_MOUSE
1448 else if (ir.EventType == MOUSE_EVENT
1449 && decode_mouse_event(&ir.Event.MouseEvent))
1450 return TRUE;
1451#endif
1452 }
1453 else if (msec == 0)
1454 break;
1455 }
1456
1457#ifdef FEAT_CLIENTSERVER
1458 /* Something might have been received while we were waiting. */
1459 if (input_available())
1460 return TRUE;
1461#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001462
Bram Moolenaar071d4272004-06-13 20:20:40 +00001463 return FALSE;
1464}
1465
1466#ifndef FEAT_GUI_MSWIN
1467/*
1468 * return non-zero if a character is available
1469 */
1470 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001471mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472{
1473 return WaitForChar(0L);
1474}
1475#endif
1476
1477/*
1478 * Create the console input. Used when reading stdin doesn't work.
1479 */
1480 static void
1481create_conin(void)
1482{
1483 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1484 FILE_SHARE_READ|FILE_SHARE_WRITE,
1485 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001486 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001487 did_create_conin = TRUE;
1488}
1489
1490/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001491 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001493 static WCHAR
1494tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001496 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497
1498 for (;;)
1499 {
1500 INPUT_RECORD ir;
1501 DWORD cRecords = 0;
1502
1503#ifdef FEAT_CLIENTSERVER
1504 (void)WaitForChar(-1L);
1505 if (input_available())
1506 return 0;
1507# ifdef FEAT_MOUSE
1508 if (g_nMouseClick != -1)
1509 return 0;
1510# endif
1511#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001512 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513 {
1514 if (did_create_conin)
1515 read_error_exit();
1516 create_conin();
1517 continue;
1518 }
1519
1520 if (ir.EventType == KEY_EVENT)
1521 {
1522 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1523 pmodifiers, TRUE))
1524 return ch;
1525 }
1526 else if (ir.EventType == FOCUS_EVENT)
1527 handle_focus_event(ir);
1528 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1529 shell_resized();
1530#ifdef FEAT_MOUSE
1531 else if (ir.EventType == MOUSE_EVENT)
1532 {
1533 if (decode_mouse_event(&ir.Event.MouseEvent))
1534 return 0;
1535 }
1536#endif
1537 }
1538}
1539#endif /* !FEAT_GUI_W32 */
1540
1541
1542/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001543 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 * Get one or more characters from the keyboard or the mouse.
1545 * If time == 0, do not wait for characters.
1546 * If time == n, wait a short time for characters.
1547 * If time == -1, wait forever for characters.
1548 * Returns the number of characters read into buf.
1549 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001550/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551 int
1552mch_inchar(
1553 char_u *buf,
1554 int maxlen,
1555 long time,
1556 int tb_change_cnt)
1557{
1558#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1559
1560 int len;
1561 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001562#define TYPEAHEADLEN 20
1563 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1564 static int typeaheadlen = 0;
1565
1566 /* First use any typeahead that was kept because "buf" was too small. */
1567 if (typeaheadlen > 0)
1568 goto theend;
1569
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 if (time >= 0)
1571 {
1572 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001573 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574 }
1575 else /* time == -1, wait forever */
1576 {
1577 mch_set_winsize_now(); /* Allow winsize changes from now on */
1578
Bram Moolenaar3918c952005-03-15 22:34:55 +00001579 /*
1580 * If there is no character available within 2 seconds (default)
1581 * write the autoscript file to disk. Or cause the CursorHold event
1582 * to be triggered.
1583 */
1584 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585 {
1586#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001587 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001589 buf[0] = K_SPECIAL;
1590 buf[1] = KS_EXTRA;
1591 buf[2] = (int)KE_CURSORHOLD;
1592 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593 }
1594#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001595 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596 }
1597 }
1598
1599 /*
1600 * Try to read as many characters as there are, until the buffer is full.
1601 */
1602
1603 /* we will get at least one key. Get more if they are available. */
1604 g_fCBrkPressed = FALSE;
1605
1606#ifdef MCH_WRITE_DUMP
1607 if (fdDump)
1608 fputc('[', fdDump);
1609#endif
1610
1611 /* Keep looping until there is something in the typeahead buffer and more
1612 * to get and still room in the buffer (up to two bytes for a char and
1613 * three bytes for a modifier). */
1614 while ((typeaheadlen == 0 || WaitForChar(0L))
1615 && typeaheadlen + 5 <= TYPEAHEADLEN)
1616 {
1617 if (typebuf_changed(tb_change_cnt))
1618 {
1619 /* "buf" may be invalid now if a client put something in the
1620 * typeahead buffer and "buf" is in the typeahead buffer. */
1621 typeaheadlen = 0;
1622 break;
1623 }
1624#ifdef FEAT_MOUSE
1625 if (g_nMouseClick != -1)
1626 {
1627# ifdef MCH_WRITE_DUMP
1628 if (fdDump)
1629 fprintf(fdDump, "{%02x @ %d, %d}",
1630 g_nMouseClick, g_xMouse, g_yMouse);
1631# endif
1632 typeahead[typeaheadlen++] = ESC + 128;
1633 typeahead[typeaheadlen++] = 'M';
1634 typeahead[typeaheadlen++] = g_nMouseClick;
1635 typeahead[typeaheadlen++] = g_xMouse + '!';
1636 typeahead[typeaheadlen++] = g_yMouse + '!';
1637 g_nMouseClick = -1;
1638 }
1639 else
1640#endif
1641 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001642 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643 int modifiers = 0;
1644
1645 c = tgetch(&modifiers, &ch2);
1646
1647 if (typebuf_changed(tb_change_cnt))
1648 {
1649 /* "buf" may be invalid now if a client put something in the
1650 * typeahead buffer and "buf" is in the typeahead buffer. */
1651 typeaheadlen = 0;
1652 break;
1653 }
1654
1655 if (c == Ctrl_C && ctrl_c_interrupts)
1656 {
1657#if defined(FEAT_CLIENTSERVER)
1658 trash_input_buf();
1659#endif
1660 got_int = TRUE;
1661 }
1662
1663#ifdef FEAT_MOUSE
1664 if (g_nMouseClick == -1)
1665#endif
1666 {
1667 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001668 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001670#ifdef FEAT_MBYTE
1671 if (ch2 == NUL)
1672 {
1673 int i;
1674 char_u *p;
1675 WCHAR ch[2];
1676
1677 ch[0] = c;
1678 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1679 {
1680 ch[1] = tgetch(&modifiers, &ch2);
1681 n++;
1682 }
1683 p = utf16_to_enc(ch, &n);
1684 if (p != NULL)
1685 {
1686 for (i = 0; i < n; i++)
1687 typeahead[typeaheadlen + i] = p[i];
1688 vim_free(p);
1689 }
1690 }
1691 else
1692#endif
1693 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 if (ch2 != NUL)
1695 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001696 typeahead[typeaheadlen + n] = 3;
1697 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001698 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001699 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700
Bram Moolenaar45500912014-07-09 20:51:07 +02001701 if (conv)
1702 {
1703 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001704
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001705 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001706 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001707 char_u *e = typeahead + TYPEAHEADLEN;
1708
1709 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001710 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001711 if (*p == K_NUL)
1712 {
1713 ++p;
1714 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1715 *p = 3;
1716 ++n;
1717 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001718 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001719 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001720 }
1721 }
1722
Bram Moolenaar071d4272004-06-13 20:20:40 +00001723 /* Use the ALT key to set the 8th bit of the character
1724 * when it's one byte, the 8th bit isn't set yet and not
1725 * using a double-byte encoding (would become a lead
1726 * byte). */
1727 if ((modifiers & MOD_MASK_ALT)
1728 && n == 1
1729 && (typeahead[typeaheadlen] & 0x80) == 0
1730#ifdef FEAT_MBYTE
1731 && !enc_dbcs
1732#endif
1733 )
1734 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001735#ifdef FEAT_MBYTE
1736 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1737 typeahead + typeaheadlen);
1738#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001740#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001741 modifiers &= ~MOD_MASK_ALT;
1742 }
1743
1744 if (modifiers != 0)
1745 {
1746 /* Prepend modifiers to the character. */
1747 mch_memmove(typeahead + typeaheadlen + 3,
1748 typeahead + typeaheadlen, n);
1749 typeahead[typeaheadlen++] = K_SPECIAL;
1750 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1751 typeahead[typeaheadlen++] = modifiers;
1752 }
1753
1754 typeaheadlen += n;
1755
1756#ifdef MCH_WRITE_DUMP
1757 if (fdDump)
1758 fputc(c, fdDump);
1759#endif
1760 }
1761 }
1762 }
1763
1764#ifdef MCH_WRITE_DUMP
1765 if (fdDump)
1766 {
1767 fputs("]\n", fdDump);
1768 fflush(fdDump);
1769 }
1770#endif
1771
Bram Moolenaar071d4272004-06-13 20:20:40 +00001772theend:
1773 /* Move typeahead to "buf", as much as fits. */
1774 len = 0;
1775 while (len < maxlen && typeaheadlen > 0)
1776 {
1777 buf[len++] = typeahead[0];
1778 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1779 }
1780 return len;
1781
1782#else /* FEAT_GUI_W32 */
1783 return 0;
1784#endif /* FEAT_GUI_W32 */
1785}
1786
Bram Moolenaar82881492012-11-20 16:53:39 +01001787#ifndef PROTO
1788# ifndef __MINGW32__
1789# include <shellapi.h> /* required for FindExecutable() */
1790# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791#endif
1792
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001793/*
1794 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001795 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001796 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001798executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001800 char *dum;
1801 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001802 char *curpath, *newpath;
1803 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001804
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001805#ifdef FEAT_MBYTE
1806 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001808 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001809 WCHAR fnamew[_MAX_PATH];
1810 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001811 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001812
1813 if (p != NULL)
1814 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001815 wcurpath = _wgetenv(L"PATH");
1816 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1817 * sizeof(WCHAR));
1818 if (wnewpath == NULL)
1819 return FALSE;
1820 wcscpy(wnewpath, L".;");
1821 wcscat(wnewpath, wcurpath);
1822 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1823 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001824 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02001825 if (n == 0)
1826 return FALSE;
1827 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1828 return FALSE;
1829 if (path != NULL)
1830 *path = utf16_to_enc(fnamew, NULL);
1831 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001832 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001834#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001835
1836 curpath = getenv("PATH");
1837 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1838 if (newpath == NULL)
1839 return FALSE;
1840 STRCPY(newpath, ".;");
1841 STRCAT(newpath, curpath);
1842 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1843 vim_free(newpath);
1844 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001845 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001846 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001847 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001848 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001849 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001850 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851}
1852
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001853#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001854 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001855/*
1856 * Bad parameter handler.
1857 *
1858 * Certain MS CRT functions will intentionally crash when passed invalid
1859 * parameters to highlight possible security holes. Setting this function as
1860 * the bad parameter handler will prevent the crash.
1861 *
1862 * In debug builds the parameters contain CRT information that might help track
1863 * down the source of a problem, but in non-debug builds the arguments are all
1864 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1865 * worth allowing these to make debugging of issues easier.
1866 */
1867 static void
1868bad_param_handler(const wchar_t *expression,
1869 const wchar_t *function,
1870 const wchar_t *file,
1871 unsigned int line,
1872 uintptr_t pReserved)
1873{
1874}
1875
1876# define SET_INVALID_PARAM_HANDLER \
1877 ((void)_set_invalid_parameter_handler(bad_param_handler))
1878#else
1879# define SET_INVALID_PARAM_HANDLER
1880#endif
1881
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882#ifdef FEAT_GUI_W32
1883
1884/*
1885 * GUI version of mch_init().
1886 */
1887 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001888mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889{
1890#ifndef __MINGW32__
1891 extern int _fmode;
1892#endif
1893
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001894 /* Silently handle invalid parameters to CRT functions */
1895 SET_INVALID_PARAM_HANDLER;
1896
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 /* Let critical errors result in a failure, not in a dialog box. Required
1898 * for the timestamp test to work on removed floppies. */
1899 SetErrorMode(SEM_FAILCRITICALERRORS);
1900
1901 _fmode = O_BINARY; /* we do our own CR-LF translation */
1902
1903 /* Specify window size. Is there a place to get the default from? */
1904 Rows = 25;
1905 Columns = 80;
1906
1907 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 {
1909 char_u vimrun_location[_MAX_PATH + 4];
1910
1911 /* First try in same directory as gvim.exe */
1912 STRCPY(vimrun_location, exe_name);
1913 STRCPY(gettail(vimrun_location), "vimrun.exe");
1914 if (mch_getperm(vimrun_location) >= 0)
1915 {
1916 if (*skiptowhite(vimrun_location) != NUL)
1917 {
1918 /* Enclose path with white space in double quotes. */
1919 mch_memmove(vimrun_location + 1, vimrun_location,
1920 STRLEN(vimrun_location) + 1);
1921 *vimrun_location = '"';
1922 STRCPY(gettail(vimrun_location), "vimrun\" ");
1923 }
1924 else
1925 STRCPY(gettail(vimrun_location), "vimrun ");
1926
1927 vimrun_path = (char *)vim_strsave(vimrun_location);
1928 s_dont_use_vimrun = FALSE;
1929 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001930 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931 s_dont_use_vimrun = FALSE;
1932
1933 /* Don't give the warning for a missing vimrun.exe right now, but only
1934 * when vimrun was supposed to be used. Don't bother people that do
1935 * not need vimrun.exe. */
1936 if (s_dont_use_vimrun)
1937 need_vimrun_warning = TRUE;
1938 }
1939
1940 /*
1941 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1942 * Otherwise the default "findstr /n" is used.
1943 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001944 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001945 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1946
1947#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001948 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949#endif
1950}
1951
1952
1953#else /* FEAT_GUI_W32 */
1954
1955#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1956#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1957
1958/*
1959 * ClearConsoleBuffer()
1960 * Description:
1961 * Clears the entire contents of the console screen buffer, using the
1962 * specified attribute.
1963 * Returns:
1964 * TRUE on success
1965 */
1966 static BOOL
1967ClearConsoleBuffer(WORD wAttribute)
1968{
1969 CONSOLE_SCREEN_BUFFER_INFO csbi;
1970 COORD coord;
1971 DWORD NumCells, dummy;
1972
1973 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1974 return FALSE;
1975
1976 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1977 coord.X = 0;
1978 coord.Y = 0;
1979 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1980 coord, &dummy))
1981 {
1982 return FALSE;
1983 }
1984 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1985 coord, &dummy))
1986 {
1987 return FALSE;
1988 }
1989
1990 return TRUE;
1991}
1992
1993/*
1994 * FitConsoleWindow()
1995 * Description:
1996 * Checks if the console window will fit within given buffer dimensions.
1997 * Also, if requested, will shrink the window to fit.
1998 * Returns:
1999 * TRUE on success
2000 */
2001 static BOOL
2002FitConsoleWindow(
2003 COORD dwBufferSize,
2004 BOOL WantAdjust)
2005{
2006 CONSOLE_SCREEN_BUFFER_INFO csbi;
2007 COORD dwWindowSize;
2008 BOOL NeedAdjust = FALSE;
2009
2010 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2011 {
2012 /*
2013 * A buffer resize will fail if the current console window does
2014 * not lie completely within that buffer. To avoid this, we might
2015 * have to move and possibly shrink the window.
2016 */
2017 if (csbi.srWindow.Right >= dwBufferSize.X)
2018 {
2019 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2020 if (dwWindowSize.X > dwBufferSize.X)
2021 dwWindowSize.X = dwBufferSize.X;
2022 csbi.srWindow.Right = dwBufferSize.X - 1;
2023 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2024 NeedAdjust = TRUE;
2025 }
2026 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2027 {
2028 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2029 if (dwWindowSize.Y > dwBufferSize.Y)
2030 dwWindowSize.Y = dwBufferSize.Y;
2031 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2032 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2033 NeedAdjust = TRUE;
2034 }
2035 if (NeedAdjust && WantAdjust)
2036 {
2037 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2038 return FALSE;
2039 }
2040 return TRUE;
2041 }
2042
2043 return FALSE;
2044}
2045
2046typedef struct ConsoleBufferStruct
2047{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002048 BOOL IsValid;
2049 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002050 PCHAR_INFO Buffer;
2051 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002052} ConsoleBuffer;
2053
2054/*
2055 * SaveConsoleBuffer()
2056 * Description:
2057 * Saves important information about the console buffer, including the
2058 * actual buffer contents. The saved information is suitable for later
2059 * restoration by RestoreConsoleBuffer().
2060 * Returns:
2061 * TRUE if all information was saved; FALSE otherwise
2062 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2063 */
2064 static BOOL
2065SaveConsoleBuffer(
2066 ConsoleBuffer *cb)
2067{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002068 DWORD NumCells;
2069 COORD BufferCoord;
2070 SMALL_RECT ReadRegion;
2071 WORD Y, Y_incr;
2072
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 if (cb == NULL)
2074 return FALSE;
2075
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002076 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 {
2078 cb->IsValid = FALSE;
2079 return FALSE;
2080 }
2081 cb->IsValid = TRUE;
2082
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002083 /*
2084 * Allocate a buffer large enough to hold the entire console screen
2085 * buffer. If this ConsoleBuffer structure has already been initialized
2086 * with a buffer of the correct size, then just use that one.
2087 */
2088 if (!cb->IsValid || cb->Buffer == NULL ||
2089 cb->BufferSize.X != cb->Info.dwSize.X ||
2090 cb->BufferSize.Y != cb->Info.dwSize.Y)
2091 {
2092 cb->BufferSize.X = cb->Info.dwSize.X;
2093 cb->BufferSize.Y = cb->Info.dwSize.Y;
2094 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2095 vim_free(cb->Buffer);
2096 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2097 if (cb->Buffer == NULL)
2098 return FALSE;
2099 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002100
2101 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002102 * We will now copy the console screen buffer into our buffer.
2103 * ReadConsoleOutput() seems to be limited as far as how much you
2104 * can read at a time. Empirically, this number seems to be about
2105 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2106 * in chunks until it is all copied. The chunks will all have the
2107 * same horizontal characteristics, so initialize them now. The
2108 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002110 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002111 ReadRegion.Left = 0;
2112 ReadRegion.Right = cb->Info.dwSize.X - 1;
2113 Y_incr = 12000 / cb->Info.dwSize.X;
2114 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002116 /*
2117 * Read into position (0, Y) in our buffer.
2118 */
2119 BufferCoord.Y = Y;
2120 /*
2121 * Read the region whose top left corner is (0, Y) and whose bottom
2122 * right corner is (width - 1, Y + Y_incr - 1). This should define
2123 * a region of size width by Y_incr. Don't worry if this region is
2124 * too large for the remaining buffer; it will be cropped.
2125 */
2126 ReadRegion.Top = Y;
2127 ReadRegion.Bottom = Y + Y_incr - 1;
2128 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2129 cb->Buffer, /* our buffer */
2130 cb->BufferSize, /* dimensions of our buffer */
2131 BufferCoord, /* offset in our buffer */
2132 &ReadRegion)) /* region to save */
2133 {
2134 vim_free(cb->Buffer);
2135 cb->Buffer = NULL;
2136 return FALSE;
2137 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002138 }
2139
2140 return TRUE;
2141}
2142
2143/*
2144 * RestoreConsoleBuffer()
2145 * Description:
2146 * Restores important information about the console buffer, including the
2147 * actual buffer contents, if desired. The information to restore is in
2148 * the same format used by SaveConsoleBuffer().
2149 * Returns:
2150 * TRUE on success
2151 */
2152 static BOOL
2153RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002154 ConsoleBuffer *cb,
2155 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002156{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002157 COORD BufferCoord;
2158 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002159
2160 if (cb == NULL || !cb->IsValid)
2161 return FALSE;
2162
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002163 /*
2164 * Before restoring the buffer contents, clear the current buffer, and
2165 * restore the cursor position and window information. Doing this now
2166 * prevents old buffer contents from "flashing" onto the screen.
2167 */
2168 if (RestoreScreen)
2169 ClearConsoleBuffer(cb->Info.wAttributes);
2170
2171 FitConsoleWindow(cb->Info.dwSize, TRUE);
2172 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2173 return FALSE;
2174 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2175 return FALSE;
2176
2177 if (!RestoreScreen)
2178 {
2179 /*
2180 * No need to restore the screen buffer contents, so we're done.
2181 */
2182 return TRUE;
2183 }
2184
2185 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2186 return FALSE;
2187 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2188 return FALSE;
2189
2190 /*
2191 * Restore the screen buffer contents.
2192 */
2193 if (cb->Buffer != NULL)
2194 {
2195 BufferCoord.X = 0;
2196 BufferCoord.Y = 0;
2197 WriteRegion.Left = 0;
2198 WriteRegion.Top = 0;
2199 WriteRegion.Right = cb->Info.dwSize.X - 1;
2200 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2201 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2202 cb->Buffer, /* our buffer */
2203 cb->BufferSize, /* dimensions of our buffer */
2204 BufferCoord, /* offset in our buffer */
2205 &WriteRegion)) /* region to restore */
2206 {
2207 return FALSE;
2208 }
2209 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002210
2211 return TRUE;
2212}
2213
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002214#define FEAT_RESTORE_ORIG_SCREEN
2215#ifdef FEAT_RESTORE_ORIG_SCREEN
2216static ConsoleBuffer g_cbOrig = { 0 };
2217#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002218static ConsoleBuffer g_cbNonTermcap = { 0 };
2219static ConsoleBuffer g_cbTermcap = { 0 };
2220
2221#ifdef FEAT_TITLE
2222#ifdef __BORLANDC__
2223typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2224#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002225typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226#endif
2227char g_szOrigTitle[256] = { 0 };
2228HWND g_hWnd = NULL; /* also used in os_mswin.c */
2229static HICON g_hOrigIconSmall = NULL;
2230static HICON g_hOrigIcon = NULL;
2231static HICON g_hVimIcon = NULL;
2232static BOOL g_fCanChangeIcon = FALSE;
2233
2234/* ICON* are not defined in VC++ 4.0 */
2235#ifndef ICON_SMALL
2236#define ICON_SMALL 0
2237#endif
2238#ifndef ICON_BIG
2239#define ICON_BIG 1
2240#endif
2241/*
2242 * GetConsoleIcon()
2243 * Description:
2244 * Attempts to retrieve the small icon and/or the big icon currently in
2245 * use by a given window.
2246 * Returns:
2247 * TRUE on success
2248 */
2249 static BOOL
2250GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002251 HWND hWnd,
2252 HICON *phIconSmall,
2253 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002254{
2255 if (hWnd == NULL)
2256 return FALSE;
2257
2258 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002259 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2260 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002262 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2263 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264 return TRUE;
2265}
2266
2267/*
2268 * SetConsoleIcon()
2269 * Description:
2270 * Attempts to change the small icon and/or the big icon currently in
2271 * use by a given window.
2272 * Returns:
2273 * TRUE on success
2274 */
2275 static BOOL
2276SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002277 HWND hWnd,
2278 HICON hIconSmall,
2279 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 if (hWnd == NULL)
2282 return FALSE;
2283
2284 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002285 SendMessage(hWnd, WM_SETICON,
2286 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002288 SendMessage(hWnd, WM_SETICON,
2289 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290 return TRUE;
2291}
2292
2293/*
2294 * SaveConsoleTitleAndIcon()
2295 * Description:
2296 * Saves the current console window title in g_szOrigTitle, for later
2297 * restoration. Also, attempts to obtain a handle to the console window,
2298 * and use it to save the small and big icons currently in use by the
2299 * console window. This is not always possible on some versions of Windows;
2300 * nor is it possible when running Vim remotely using Telnet (since the
2301 * console window the user sees is owned by a remote process).
2302 */
2303 static void
2304SaveConsoleTitleAndIcon(void)
2305{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306 /* Save the original title. */
2307 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2308 return;
2309
2310 /*
2311 * Obtain a handle to the console window using GetConsoleWindow() from
2312 * KERNEL32.DLL; we need to handle in order to change the window icon.
2313 * This function only exists on NT-based Windows, starting with Windows
2314 * 2000. On older operating systems, we can't change the window icon
2315 * anyway.
2316 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002317 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002318 if (g_hWnd == NULL)
2319 return;
2320
2321 /* Save the original console window icon. */
2322 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2323 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2324 return;
2325
2326 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002327 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002328 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329 if (g_hVimIcon != NULL)
2330 g_fCanChangeIcon = TRUE;
2331}
2332#endif
2333
2334static int g_fWindInitCalled = FALSE;
2335static int g_fTermcapMode = FALSE;
2336static CONSOLE_CURSOR_INFO g_cci;
2337static DWORD g_cmodein = 0;
2338static DWORD g_cmodeout = 0;
2339
2340/*
2341 * non-GUI version of mch_init().
2342 */
2343 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002344mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002346#ifndef FEAT_RESTORE_ORIG_SCREEN
2347 CONSOLE_SCREEN_BUFFER_INFO csbi;
2348#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002349#ifndef __MINGW32__
2350 extern int _fmode;
2351#endif
2352
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002353 /* Silently handle invalid parameters to CRT functions */
2354 SET_INVALID_PARAM_HANDLER;
2355
Bram Moolenaar071d4272004-06-13 20:20:40 +00002356 /* Let critical errors result in a failure, not in a dialog box. Required
2357 * for the timestamp test to work on removed floppies. */
2358 SetErrorMode(SEM_FAILCRITICALERRORS);
2359
2360 _fmode = O_BINARY; /* we do our own CR-LF translation */
2361 out_flush();
2362
2363 /* Obtain handles for the standard Console I/O devices */
2364 if (read_cmd_fd == 0)
2365 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2366 else
2367 create_conin();
2368 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2369
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002370#ifdef FEAT_RESTORE_ORIG_SCREEN
2371 /* Save the initial console buffer for later restoration */
2372 SaveConsoleBuffer(&g_cbOrig);
2373 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2374#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002375 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002376 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2377 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2378#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 if (cterm_normal_fg_color == 0)
2380 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2381 if (cterm_normal_bg_color == 0)
2382 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2383
2384 /* set termcap codes to current text attributes */
2385 update_tcap(g_attrCurrent);
2386
2387 GetConsoleCursorInfo(g_hConOut, &g_cci);
2388 GetConsoleMode(g_hConIn, &g_cmodein);
2389 GetConsoleMode(g_hConOut, &g_cmodeout);
2390
2391#ifdef FEAT_TITLE
2392 SaveConsoleTitleAndIcon();
2393 /*
2394 * Set both the small and big icons of the console window to Vim's icon.
2395 * Note that Vim presently only has one size of icon (32x32), but it
2396 * automatically gets scaled down to 16x16 when setting the small icon.
2397 */
2398 if (g_fCanChangeIcon)
2399 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2400#endif
2401
2402 ui_get_shellsize();
2403
2404#ifdef MCH_WRITE_DUMP
2405 fdDump = fopen("dump", "wt");
2406
2407 if (fdDump)
2408 {
2409 time_t t;
2410
2411 time(&t);
2412 fputs(ctime(&t), fdDump);
2413 fflush(fdDump);
2414 }
2415#endif
2416
2417 g_fWindInitCalled = TRUE;
2418
2419#ifdef FEAT_MOUSE
2420 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2421#endif
2422
2423#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002424 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426}
2427
2428/*
2429 * non-GUI version of mch_exit().
2430 * Shut down and exit with status `r'
2431 * Careful: mch_exit() may be called before mch_init()!
2432 */
2433 void
2434mch_exit(int r)
2435{
2436 stoptermcap();
2437
2438 if (g_fWindInitCalled)
2439 settmode(TMODE_COOK);
2440
2441 ml_close_all(TRUE); /* remove all memfiles */
2442
2443 if (g_fWindInitCalled)
2444 {
2445#ifdef FEAT_TITLE
2446 mch_restore_title(3);
2447 /*
2448 * Restore both the small and big icons of the console window to
2449 * what they were at startup. Don't do this when the window is
2450 * closed, Vim would hang here.
2451 */
2452 if (g_fCanChangeIcon && !g_fForceExit)
2453 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2454#endif
2455
2456#ifdef MCH_WRITE_DUMP
2457 if (fdDump)
2458 {
2459 time_t t;
2460
2461 time(&t);
2462 fputs(ctime(&t), fdDump);
2463 fclose(fdDump);
2464 }
2465 fdDump = NULL;
2466#endif
2467 }
2468
2469 SetConsoleCursorInfo(g_hConOut, &g_cci);
2470 SetConsoleMode(g_hConIn, g_cmodein);
2471 SetConsoleMode(g_hConOut, g_cmodeout);
2472
2473#ifdef DYNAMIC_GETTEXT
2474 dyn_libintl_end();
2475#endif
2476
2477 exit(r);
2478}
2479#endif /* !FEAT_GUI_W32 */
2480
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481/*
2482 * Do we have an interactive window?
2483 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002484/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 int
2486mch_check_win(
2487 int argc,
2488 char **argv)
2489{
2490 get_exe_name();
2491
2492#ifdef FEAT_GUI_W32
2493 return OK; /* GUI always has a tty */
2494#else
2495 if (isatty(1))
2496 return OK;
2497 return FAIL;
2498#endif
2499}
2500
2501
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002502#ifdef FEAT_MBYTE
2503/*
2504 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2505 * if it already exists. When "len" is > 0, also expand short to long
2506 * filenames.
2507 * Return FAIL if wide functions are not available, OK otherwise.
2508 * NOTE: much of this is identical to fname_case(), keep in sync!
2509 */
2510 static int
2511fname_casew(
2512 WCHAR *name,
2513 int len)
2514{
2515 WCHAR szTrueName[_MAX_PATH + 2];
2516 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2517 WCHAR *ptrue, *ptruePrev;
2518 WCHAR *porig, *porigPrev;
2519 int flen;
2520 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002521 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002522 int c;
2523 int slen;
2524
2525 flen = (int)wcslen(name);
2526 if (flen > _MAX_PATH)
2527 return OK;
2528
2529 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2530
2531 /* Build the new name in szTrueName[] one component at a time. */
2532 porig = name;
2533 ptrue = szTrueName;
2534
2535 if (iswalpha(porig[0]) && porig[1] == L':')
2536 {
2537 /* copy leading drive letter */
2538 *ptrue++ = *porig++;
2539 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002540 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002541 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002542
2543 while (*porig != NUL)
2544 {
2545 /* copy \ characters */
2546 while (*porig == psepc)
2547 *ptrue++ = *porig++;
2548
2549 ptruePrev = ptrue;
2550 porigPrev = porig;
2551 while (*porig != NUL && *porig != psepc)
2552 {
2553 *ptrue++ = *porig++;
2554 }
2555 *ptrue = NUL;
2556
2557 /* To avoid a slow failure append "\*" when searching a directory,
2558 * server or network share. */
2559 wcscpy(szTrueNameTemp, szTrueName);
2560 slen = (int)wcslen(szTrueNameTemp);
2561 if (*porig == psepc && slen + 2 < _MAX_PATH)
2562 wcscpy(szTrueNameTemp + slen, L"\\*");
2563
2564 /* Skip "", "." and "..". */
2565 if (ptrue > ptruePrev
2566 && (ptruePrev[0] != L'.'
2567 || (ptruePrev[1] != NUL
2568 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2569 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2570 != INVALID_HANDLE_VALUE)
2571 {
2572 c = *porig;
2573 *porig = NUL;
2574
2575 /* Only use the match when it's the same name (ignoring case) or
2576 * expansion is allowed and there is a match with the short name
2577 * and there is enough room. */
2578 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2579 || (len > 0
2580 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2581 && (int)(ptruePrev - szTrueName)
2582 + (int)wcslen(fb.cFileName) < len)))
2583 {
2584 wcscpy(ptruePrev, fb.cFileName);
2585
2586 /* Look for exact match and prefer it if found. Must be a
2587 * long name, otherwise there would be only one match. */
2588 while (FindNextFileW(hFind, &fb))
2589 {
2590 if (*fb.cAlternateFileName != NUL
2591 && (wcscoll(porigPrev, fb.cFileName) == 0
2592 || (len > 0
2593 && (_wcsicoll(porigPrev,
2594 fb.cAlternateFileName) == 0
2595 && (int)(ptruePrev - szTrueName)
2596 + (int)wcslen(fb.cFileName) < len))))
2597 {
2598 wcscpy(ptruePrev, fb.cFileName);
2599 break;
2600 }
2601 }
2602 }
2603 FindClose(hFind);
2604 *porig = c;
2605 ptrue = ptruePrev + wcslen(ptruePrev);
2606 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002607 }
2608
2609 wcscpy(name, szTrueName);
2610 return OK;
2611}
2612#endif
2613
Bram Moolenaar071d4272004-06-13 20:20:40 +00002614/*
2615 * fname_case(): Set the case of the file name, if it already exists.
2616 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002617 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002618 */
2619 void
2620fname_case(
2621 char_u *name,
2622 int len)
2623{
2624 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002625 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 char *ptrue, *ptruePrev;
2627 char *porig, *porigPrev;
2628 int flen;
2629 WIN32_FIND_DATA fb;
2630 HANDLE hFind;
2631 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002632 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002633
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002634 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002635 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002636 return;
2637
2638 slash_adjust(name);
2639
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002640#ifdef FEAT_MBYTE
2641 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2642 {
2643 WCHAR *p = enc_to_utf16(name, NULL);
2644
2645 if (p != NULL)
2646 {
2647 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002648 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002649
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002650 wcsncpy(buf, p, _MAX_PATH);
2651 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002652 vim_free(p);
2653
2654 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2655 {
2656 q = utf16_to_enc(buf, NULL);
2657 if (q != NULL)
2658 {
2659 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2660 vim_free(q);
2661 return;
2662 }
2663 }
2664 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002665 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002666 }
2667#endif
2668
2669 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2670 * So we should check this after calling wide function. */
2671 if (flen > _MAX_PATH)
2672 return;
2673
Bram Moolenaar071d4272004-06-13 20:20:40 +00002674 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002675 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676 ptrue = szTrueName;
2677
2678 if (isalpha(porig[0]) && porig[1] == ':')
2679 {
2680 /* copy leading drive letter */
2681 *ptrue++ = *porig++;
2682 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002683 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002684 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002685
2686 while (*porig != NUL)
2687 {
2688 /* copy \ characters */
2689 while (*porig == psepc)
2690 *ptrue++ = *porig++;
2691
2692 ptruePrev = ptrue;
2693 porigPrev = porig;
2694 while (*porig != NUL && *porig != psepc)
2695 {
2696#ifdef FEAT_MBYTE
2697 int l;
2698
2699 if (enc_dbcs)
2700 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002701 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002702 while (--l >= 0)
2703 *ptrue++ = *porig++;
2704 }
2705 else
2706#endif
2707 *ptrue++ = *porig++;
2708 }
2709 *ptrue = NUL;
2710
Bram Moolenaar464c9252010-10-13 20:37:41 +02002711 /* To avoid a slow failure append "\*" when searching a directory,
2712 * server or network share. */
2713 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002714 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002715 if (*porig == psepc && slen + 2 < _MAX_PATH)
2716 STRCPY(szTrueNameTemp + slen, "\\*");
2717
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718 /* Skip "", "." and "..". */
2719 if (ptrue > ptruePrev
2720 && (ptruePrev[0] != '.'
2721 || (ptruePrev[1] != NUL
2722 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002723 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724 != INVALID_HANDLE_VALUE)
2725 {
2726 c = *porig;
2727 *porig = NUL;
2728
2729 /* Only use the match when it's the same name (ignoring case) or
2730 * expansion is allowed and there is a match with the short name
2731 * and there is enough room. */
2732 if (_stricoll(porigPrev, fb.cFileName) == 0
2733 || (len > 0
2734 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2735 && (int)(ptruePrev - szTrueName)
2736 + (int)strlen(fb.cFileName) < len)))
2737 {
2738 STRCPY(ptruePrev, fb.cFileName);
2739
2740 /* Look for exact match and prefer it if found. Must be a
2741 * long name, otherwise there would be only one match. */
2742 while (FindNextFile(hFind, &fb))
2743 {
2744 if (*fb.cAlternateFileName != NUL
2745 && (strcoll(porigPrev, fb.cFileName) == 0
2746 || (len > 0
2747 && (_stricoll(porigPrev,
2748 fb.cAlternateFileName) == 0
2749 && (int)(ptruePrev - szTrueName)
2750 + (int)strlen(fb.cFileName) < len))))
2751 {
2752 STRCPY(ptruePrev, fb.cFileName);
2753 break;
2754 }
2755 }
2756 }
2757 FindClose(hFind);
2758 *porig = c;
2759 ptrue = ptruePrev + strlen(ptruePrev);
2760 }
2761 }
2762
2763 STRCPY(name, szTrueName);
2764}
2765
2766
2767/*
2768 * Insert user name in s[len].
2769 */
2770 int
2771mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002772 char_u *s,
2773 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002775 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776 DWORD cch = sizeof szUserName;
2777
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002778#ifdef FEAT_MBYTE
2779 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2780 {
2781 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2782 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2783
2784 if (GetUserNameW(wszUserName, &wcch))
2785 {
2786 char_u *p = utf16_to_enc(wszUserName, NULL);
2787
2788 if (p != NULL)
2789 {
2790 vim_strncpy(s, p, len - 1);
2791 vim_free(p);
2792 return OK;
2793 }
2794 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002795 }
2796#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797 if (GetUserName(szUserName, &cch))
2798 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002799 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 return OK;
2801 }
2802 s[0] = NUL;
2803 return FAIL;
2804}
2805
2806
2807/*
2808 * Insert host name in s[len].
2809 */
2810 void
2811mch_get_host_name(
2812 char_u *s,
2813 int len)
2814{
2815 DWORD cch = len;
2816
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002817#ifdef FEAT_MBYTE
2818 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2819 {
2820 WCHAR wszHostName[256 + 1];
2821 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2822
2823 if (GetComputerNameW(wszHostName, &wcch))
2824 {
2825 char_u *p = utf16_to_enc(wszHostName, NULL);
2826
2827 if (p != NULL)
2828 {
2829 vim_strncpy(s, p, len - 1);
2830 vim_free(p);
2831 return;
2832 }
2833 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002834 }
2835#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002836 if (!GetComputerName((LPSTR)s, &cch))
2837 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002838}
2839
2840
2841/*
2842 * return process ID
2843 */
2844 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002845mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846{
2847 return (long)GetCurrentProcessId();
2848}
2849
2850
2851/*
2852 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2853 * Return OK for success, FAIL for failure.
2854 */
2855 int
2856mch_dirname(
2857 char_u *buf,
2858 int len)
2859{
2860 /*
2861 * Originally this was:
2862 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2863 * But the Win32s known bug list says that getcwd() doesn't work
2864 * so use the Win32 system call instead. <Negri>
2865 */
2866#ifdef FEAT_MBYTE
2867 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2868 {
2869 WCHAR wbuf[_MAX_PATH + 1];
2870
2871 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2872 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002873 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874
2875 if (p != NULL)
2876 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002877 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878 vim_free(p);
2879 return OK;
2880 }
2881 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002882 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002883 }
2884#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002885 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886}
2887
2888/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002889 * Get file permissions for "name".
2890 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891 */
2892 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002893mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002895 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002896 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002898 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002899 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900}
2901
2902
2903/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002904 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002905 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002906 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 */
2908 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002909mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002910{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002911 long n = -1;
2912
Bram Moolenaar071d4272004-06-13 20:20:40 +00002913#ifdef FEAT_MBYTE
2914 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2915 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002916 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917
2918 if (p != NULL)
2919 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002920 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002922 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002923 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 }
2925 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002926 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002928 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002929 if (n == -1)
2930 return FAIL;
2931
2932 win32_set_archive(name);
2933
2934 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935}
2936
2937/*
2938 * Set hidden flag for "name".
2939 */
2940 void
2941mch_hide(char_u *name)
2942{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002943 int attrs = win32_getattrs(name);
2944 if (attrs == -1)
2945 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002946
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002947 attrs |= FILE_ATTRIBUTE_HIDDEN;
2948 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002949}
2950
2951/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01002952 * Return TRUE if file "name" exists and is hidden.
2953 */
2954 int
2955mch_ishidden(char_u *name)
2956{
2957 int f = win32_getattrs(name);
2958
2959 if (f == -1)
2960 return FALSE; /* file does not exist at all */
2961
2962 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
2963}
2964
2965/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966 * return TRUE if "name" is a directory
2967 * return FALSE if "name" is not a directory or upon error
2968 */
2969 int
2970mch_isdir(char_u *name)
2971{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002972 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973
2974 if (f == -1)
2975 return FALSE; /* file does not exist at all */
2976
2977 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2978}
2979
2980/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01002981 * return TRUE if "name" is a directory, NOT a symlink to a directory
2982 * return FALSE if "name" is not a directory
2983 * return FALSE for error
2984 */
2985 int
2986mch_isrealdir(char_u *name)
2987{
2988 return mch_isdir(name) && !mch_is_symbolic_link(name);
2989}
2990
2991/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002992 * Create directory "name".
2993 * Return 0 on success, -1 on error.
2994 */
2995 int
2996mch_mkdir(char_u *name)
2997{
2998#ifdef FEAT_MBYTE
2999 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3000 {
3001 WCHAR *p;
3002 int retval;
3003
3004 p = enc_to_utf16(name, NULL);
3005 if (p == NULL)
3006 return -1;
3007 retval = _wmkdir(p);
3008 vim_free(p);
3009 return retval;
3010 }
3011#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003012 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003013}
3014
3015/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003016 * Delete directory "name".
3017 * Return 0 on success, -1 on error.
3018 */
3019 int
3020mch_rmdir(char_u *name)
3021{
3022#ifdef FEAT_MBYTE
3023 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3024 {
3025 WCHAR *p;
3026 int retval;
3027
3028 p = enc_to_utf16(name, NULL);
3029 if (p == NULL)
3030 return -1;
3031 retval = _wrmdir(p);
3032 vim_free(p);
3033 return retval;
3034 }
3035#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003036 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003037}
3038
3039/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003040 * Return TRUE if file "fname" has more than one link.
3041 */
3042 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003043mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003044{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003045 BY_HANDLE_FILE_INFORMATION info;
3046
3047 return win32_fileinfo(fname, &info) == FILEINFO_OK
3048 && info.nNumberOfLinks > 1;
3049}
3050
3051/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003052 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003053 */
3054 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003055mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003056{
3057 HANDLE hFind;
3058 int res = FALSE;
3059 WIN32_FIND_DATAA findDataA;
3060 DWORD fileFlags = 0, reparseTag = 0;
3061#ifdef FEAT_MBYTE
3062 WCHAR *wn = NULL;
3063 WIN32_FIND_DATAW findDataW;
3064
3065 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003066 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003067 if (wn != NULL)
3068 {
3069 hFind = FindFirstFileW(wn, &findDataW);
3070 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003071 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003072 {
3073 fileFlags = findDataW.dwFileAttributes;
3074 reparseTag = findDataW.dwReserved0;
3075 }
3076 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003077 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003078#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003079 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003080 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003081 if (hFind != INVALID_HANDLE_VALUE)
3082 {
3083 fileFlags = findDataA.dwFileAttributes;
3084 reparseTag = findDataA.dwReserved0;
3085 }
3086 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003087
3088 if (hFind != INVALID_HANDLE_VALUE)
3089 FindClose(hFind);
3090
3091 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003092 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3093 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003094 res = TRUE;
3095
3096 return res;
3097}
3098
3099/*
3100 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3101 * link.
3102 */
3103 int
3104mch_is_linked(char_u *fname)
3105{
3106 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3107 return TRUE;
3108 return FALSE;
3109}
3110
3111/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003112 * Get the by-handle-file-information for "fname".
3113 * Returns FILEINFO_OK when OK.
3114 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3115 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3116 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3117 */
3118 int
3119win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3120{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003121 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003122 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003123#ifdef FEAT_MBYTE
3124 WCHAR *wn = NULL;
3125
3126 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003127 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003128 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003129 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003130 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003131 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003132 if (wn != NULL)
3133 {
3134 hFile = CreateFileW(wn, /* file name */
3135 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003136 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003137 NULL, /* security descriptor */
3138 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003139 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003140 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003141 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003142 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003143 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003144#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003145 hFile = CreateFile((LPCSTR)fname, /* file name */
3146 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003147 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003148 NULL, /* security descriptor */
3149 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003150 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003151 NULL); /* handle to template file */
3152
3153 if (hFile != INVALID_HANDLE_VALUE)
3154 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003155 if (GetFileInformationByHandle(hFile, info) != 0)
3156 res = FILEINFO_OK;
3157 else
3158 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003159 CloseHandle(hFile);
3160 }
3161
Bram Moolenaar03f48552006-02-28 23:52:23 +00003162 return res;
3163}
3164
3165/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003166 * get file attributes for `name'
3167 * -1 : error
3168 * else FILE_ATTRIBUTE_* defined in winnt.h
3169 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003170 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003171win32_getattrs(char_u *name)
3172{
3173 int attr;
3174#ifdef FEAT_MBYTE
3175 WCHAR *p = NULL;
3176
3177 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3178 p = enc_to_utf16(name, NULL);
3179
3180 if (p != NULL)
3181 {
3182 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003183 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003184 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003185 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003186#endif
3187 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003188
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003189 return attr;
3190}
3191
3192/*
3193 * set file attributes for `name' to `attrs'
3194 *
3195 * return -1 for failure, 0 otherwise
3196 */
3197 static
3198 int
3199win32_setattrs(char_u *name, int attrs)
3200{
3201 int res;
3202#ifdef FEAT_MBYTE
3203 WCHAR *p = NULL;
3204
3205 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3206 p = enc_to_utf16(name, NULL);
3207
3208 if (p != NULL)
3209 {
3210 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003211 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003212 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003213 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003214#endif
3215 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003216
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003217 return res ? 0 : -1;
3218}
3219
3220/*
3221 * Set archive flag for "name".
3222 */
3223 static
3224 int
3225win32_set_archive(char_u *name)
3226{
3227 int attrs = win32_getattrs(name);
3228 if (attrs == -1)
3229 return -1;
3230
3231 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3232 return win32_setattrs(name, attrs);
3233}
3234
3235/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236 * Return TRUE if file or directory "name" is writable (not readonly).
3237 * Strange semantics of Win32: a readonly directory is writable, but you can't
3238 * delete a file. Let's say this means it is writable.
3239 */
3240 int
3241mch_writable(char_u *name)
3242{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003243 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003245 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3246 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247}
3248
Bram Moolenaar071d4272004-06-13 20:20:40 +00003249/*
3250 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003251 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252 * Return -1 if unknown.
3253 */
3254 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003255mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003257 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003258 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003259 char_u *p;
3260
3261 if (len >= _MAX_PATH) /* safety check */
3262 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003263 if (!use_path)
3264 {
3265 /* TODO: check if file is really executable. */
3266 return mch_getperm(name) != -1 && !mch_isdir(name);
3267 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003268
3269 /* If there already is an extension try using the name directly. Also do
3270 * this with a Unix-shell like 'shell'. */
3271 if (vim_strchr(gettail(name), '.') != NULL
3272 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003273 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003274 return TRUE;
3275
3276 /*
3277 * Loop over all extensions in $PATHEXT.
3278 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003279 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003280 p = mch_getenv("PATHEXT");
3281 if (p == NULL)
3282 p = (char_u *)".com;.exe;.bat;.cmd";
3283 while (*p)
3284 {
3285 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3286 {
3287 /* A single "." means no extension is added. */
3288 buf[len] = NUL;
3289 ++p;
3290 if (*p)
3291 ++p;
3292 }
3293 else
3294 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003295 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003296 return TRUE;
3297 }
3298 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003299}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003300
3301/*
3302 * Check what "name" is:
3303 * NODE_NORMAL: file or directory (or doesn't exist)
3304 * NODE_WRITABLE: writable device, socket, fifo, etc.
3305 * NODE_OTHER: non-writable things
3306 */
3307 int
3308mch_nodetype(char_u *name)
3309{
3310 HANDLE hFile;
3311 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003312#ifdef FEAT_MBYTE
3313 WCHAR *wn = NULL;
3314#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003315
Bram Moolenaar043545e2006-10-10 16:44:07 +00003316 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3317 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3318 * here. */
3319 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3320 return NODE_WRITABLE;
3321
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003322#ifdef FEAT_MBYTE
3323 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003324 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003325
3326 if (wn != NULL)
3327 {
3328 hFile = CreateFileW(wn, /* file name */
3329 GENERIC_WRITE, /* access mode */
3330 0, /* share mode */
3331 NULL, /* security descriptor */
3332 OPEN_EXISTING, /* creation disposition */
3333 0, /* file attributes */
3334 NULL); /* handle to template file */
3335 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003336 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003337 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003338#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003339 hFile = CreateFile((LPCSTR)name, /* file name */
3340 GENERIC_WRITE, /* access mode */
3341 0, /* share mode */
3342 NULL, /* security descriptor */
3343 OPEN_EXISTING, /* creation disposition */
3344 0, /* file attributes */
3345 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003346
3347 if (hFile == INVALID_HANDLE_VALUE)
3348 return NODE_NORMAL;
3349
3350 type = GetFileType(hFile);
3351 CloseHandle(hFile);
3352 if (type == FILE_TYPE_CHAR)
3353 return NODE_WRITABLE;
3354 if (type == FILE_TYPE_DISK)
3355 return NODE_NORMAL;
3356 return NODE_OTHER;
3357}
3358
3359#ifdef HAVE_ACL
3360struct my_acl
3361{
3362 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3363 PSID pSidOwner;
3364 PSID pSidGroup;
3365 PACL pDacl;
3366 PACL pSacl;
3367};
3368#endif
3369
3370/*
3371 * Return a pointer to the ACL of file "fname" in allocated memory.
3372 * Return NULL if the ACL is not available for whatever reason.
3373 */
3374 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003375mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376{
3377#ifndef HAVE_ACL
3378 return (vim_acl_T)NULL;
3379#else
3380 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003381 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003383 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3384 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003386# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003387 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003388
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003389 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3390 wn = enc_to_utf16(fname, NULL);
3391 if (wn != NULL)
3392 {
3393 /* Try to retrieve the entire security descriptor. */
3394 err = GetNamedSecurityInfoW(
3395 wn, // Abstract filename
3396 SE_FILE_OBJECT, // File Object
3397 OWNER_SECURITY_INFORMATION |
3398 GROUP_SECURITY_INFORMATION |
3399 DACL_SECURITY_INFORMATION |
3400 SACL_SECURITY_INFORMATION,
3401 &p->pSidOwner, // Ownership information.
3402 &p->pSidGroup, // Group membership.
3403 &p->pDacl, // Discretionary information.
3404 &p->pSacl, // For auditing purposes.
3405 &p->pSecurityDescriptor);
3406 if (err == ERROR_ACCESS_DENIED ||
3407 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003409 /* Retrieve only DACL. */
3410 (void)GetNamedSecurityInfoW(
3411 wn,
3412 SE_FILE_OBJECT,
3413 DACL_SECURITY_INFORMATION,
3414 NULL,
3415 NULL,
3416 &p->pDacl,
3417 NULL,
3418 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003419 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003420 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003421 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003422 mch_free_acl((vim_acl_T)p);
3423 p = NULL;
3424 }
3425 vim_free(wn);
3426 }
3427 else
3428# endif
3429 {
3430 /* Try to retrieve the entire security descriptor. */
3431 err = GetNamedSecurityInfo(
3432 (LPSTR)fname, // Abstract filename
3433 SE_FILE_OBJECT, // File Object
3434 OWNER_SECURITY_INFORMATION |
3435 GROUP_SECURITY_INFORMATION |
3436 DACL_SECURITY_INFORMATION |
3437 SACL_SECURITY_INFORMATION,
3438 &p->pSidOwner, // Ownership information.
3439 &p->pSidGroup, // Group membership.
3440 &p->pDacl, // Discretionary information.
3441 &p->pSacl, // For auditing purposes.
3442 &p->pSecurityDescriptor);
3443 if (err == ERROR_ACCESS_DENIED ||
3444 err == ERROR_PRIVILEGE_NOT_HELD)
3445 {
3446 /* Retrieve only DACL. */
3447 (void)GetNamedSecurityInfo(
3448 (LPSTR)fname,
3449 SE_FILE_OBJECT,
3450 DACL_SECURITY_INFORMATION,
3451 NULL,
3452 NULL,
3453 &p->pDacl,
3454 NULL,
3455 &p->pSecurityDescriptor);
3456 }
3457 if (p->pSecurityDescriptor == NULL)
3458 {
3459 mch_free_acl((vim_acl_T)p);
3460 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461 }
3462 }
3463 }
3464
3465 return (vim_acl_T)p;
3466#endif
3467}
3468
Bram Moolenaar27515922013-06-29 15:36:26 +02003469#ifdef HAVE_ACL
3470/*
3471 * Check if "acl" contains inherited ACE.
3472 */
3473 static BOOL
3474is_acl_inherited(PACL acl)
3475{
3476 DWORD i;
3477 ACL_SIZE_INFORMATION acl_info;
3478 PACCESS_ALLOWED_ACE ace;
3479
3480 acl_info.AceCount = 0;
3481 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3482 for (i = 0; i < acl_info.AceCount; i++)
3483 {
3484 GetAce(acl, i, (LPVOID *)&ace);
3485 if (ace->Header.AceFlags & INHERITED_ACE)
3486 return TRUE;
3487 }
3488 return FALSE;
3489}
3490#endif
3491
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492/*
3493 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3494 * Errors are ignored.
3495 * This must only be called with "acl" equal to what mch_get_acl() returned.
3496 */
3497 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003498mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003499{
3500#ifdef HAVE_ACL
3501 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003502 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003504 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003505 {
3506# ifdef FEAT_MBYTE
3507 WCHAR *wn = NULL;
3508# endif
3509
3510 /* Set security flags */
3511 if (p->pSidOwner)
3512 sec_info |= OWNER_SECURITY_INFORMATION;
3513 if (p->pSidGroup)
3514 sec_info |= GROUP_SECURITY_INFORMATION;
3515 if (p->pDacl)
3516 {
3517 sec_info |= DACL_SECURITY_INFORMATION;
3518 /* Do not inherit its parent's DACL.
3519 * If the DACL is inherited, Cygwin permissions would be changed.
3520 */
3521 if (!is_acl_inherited(p->pDacl))
3522 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3523 }
3524 if (p->pSacl)
3525 sec_info |= SACL_SECURITY_INFORMATION;
3526
3527# ifdef FEAT_MBYTE
3528 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3529 wn = enc_to_utf16(fname, NULL);
3530 if (wn != NULL)
3531 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003532 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003533 wn, // Abstract filename
3534 SE_FILE_OBJECT, // File Object
3535 sec_info,
3536 p->pSidOwner, // Ownership information.
3537 p->pSidGroup, // Group membership.
3538 p->pDacl, // Discretionary information.
3539 p->pSacl // For auditing purposes.
3540 );
3541 vim_free(wn);
3542 }
3543 else
3544# endif
3545 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003546 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003547 (LPSTR)fname, // Abstract filename
3548 SE_FILE_OBJECT, // File Object
3549 sec_info,
3550 p->pSidOwner, // Ownership information.
3551 p->pSidGroup, // Group membership.
3552 p->pDacl, // Discretionary information.
3553 p->pSacl // For auditing purposes.
3554 );
3555 }
3556 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557#endif
3558}
3559
3560 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003561mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003562{
3563#ifdef HAVE_ACL
3564 struct my_acl *p = (struct my_acl *)acl;
3565
3566 if (p != NULL)
3567 {
3568 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3569 vim_free(p);
3570 }
3571#endif
3572}
3573
3574#ifndef FEAT_GUI_W32
3575
3576/*
3577 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3578 */
3579 static BOOL WINAPI
3580handler_routine(
3581 DWORD dwCtrlType)
3582{
3583 switch (dwCtrlType)
3584 {
3585 case CTRL_C_EVENT:
3586 if (ctrl_c_interrupts)
3587 g_fCtrlCPressed = TRUE;
3588 return TRUE;
3589
3590 case CTRL_BREAK_EVENT:
3591 g_fCBrkPressed = TRUE;
3592 return TRUE;
3593
3594 /* fatal events: shut down gracefully */
3595 case CTRL_CLOSE_EVENT:
3596 case CTRL_LOGOFF_EVENT:
3597 case CTRL_SHUTDOWN_EVENT:
3598 windgoto((int)Rows - 1, 0);
3599 g_fForceExit = TRUE;
3600
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003601 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003602 (dwCtrlType == CTRL_CLOSE_EVENT
3603 ? _("close")
3604 : dwCtrlType == CTRL_LOGOFF_EVENT
3605 ? _("logoff")
3606 : _("shutdown")));
3607#ifdef DEBUG
3608 OutputDebugString(IObuff);
3609#endif
3610
3611 preserve_exit(); /* output IObuff, preserve files and exit */
3612
3613 return TRUE; /* not reached */
3614
3615 default:
3616 return FALSE;
3617 }
3618}
3619
3620
3621/*
3622 * set the tty in (raw) ? "raw" : "cooked" mode
3623 */
3624 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003625mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626{
3627 DWORD cmodein;
3628 DWORD cmodeout;
3629 BOOL bEnableHandler;
3630
3631 GetConsoleMode(g_hConIn, &cmodein);
3632 GetConsoleMode(g_hConOut, &cmodeout);
3633 if (tmode == TMODE_RAW)
3634 {
3635 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3636 ENABLE_ECHO_INPUT);
3637#ifdef FEAT_MOUSE
3638 if (g_fMouseActive)
3639 cmodein |= ENABLE_MOUSE_INPUT;
3640#endif
3641 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3642 bEnableHandler = TRUE;
3643 }
3644 else /* cooked */
3645 {
3646 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3647 ENABLE_ECHO_INPUT);
3648 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3649 bEnableHandler = FALSE;
3650 }
3651 SetConsoleMode(g_hConIn, cmodein);
3652 SetConsoleMode(g_hConOut, cmodeout);
3653 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3654
3655#ifdef MCH_WRITE_DUMP
3656 if (fdDump)
3657 {
3658 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3659 tmode == TMODE_RAW ? "raw" :
3660 tmode == TMODE_COOK ? "cooked" : "normal",
3661 cmodein, cmodeout);
3662 fflush(fdDump);
3663 }
3664#endif
3665}
3666
3667
3668/*
3669 * Get the size of the current window in `Rows' and `Columns'
3670 * Return OK when size could be determined, FAIL otherwise.
3671 */
3672 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003673mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674{
3675 CONSOLE_SCREEN_BUFFER_INFO csbi;
3676
3677 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3678 {
3679 /*
3680 * For some reason, we are trying to get the screen dimensions
3681 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3682 * variables are really intended to mean the size of Vim screen
3683 * while in termcap mode.
3684 */
3685 Rows = g_cbTermcap.Info.dwSize.Y;
3686 Columns = g_cbTermcap.Info.dwSize.X;
3687 }
3688 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3689 {
3690 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3691 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3692 }
3693 else
3694 {
3695 Rows = 25;
3696 Columns = 80;
3697 }
3698 return OK;
3699}
3700
3701/*
3702 * Set a console window to `xSize' * `ySize'
3703 */
3704 static void
3705ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003706 HANDLE hConsole,
3707 int xSize,
3708 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003709{
3710 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3711 SMALL_RECT srWindowRect; /* hold the new console size */
3712 COORD coordScreen;
3713
3714#ifdef MCH_WRITE_DUMP
3715 if (fdDump)
3716 {
3717 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3718 fflush(fdDump);
3719 }
3720#endif
3721
3722 /* get the largest size we can size the console window to */
3723 coordScreen = GetLargestConsoleWindowSize(hConsole);
3724
3725 /* define the new console window size and scroll position */
3726 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3727 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3728 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3729
3730 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3731 {
3732 int sx, sy;
3733
3734 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3735 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3736 if (sy < ySize || sx < xSize)
3737 {
3738 /*
3739 * Increasing number of lines/columns, do buffer first.
3740 * Use the maximal size in x and y direction.
3741 */
3742 if (sy < ySize)
3743 coordScreen.Y = ySize;
3744 else
3745 coordScreen.Y = sy;
3746 if (sx < xSize)
3747 coordScreen.X = xSize;
3748 else
3749 coordScreen.X = sx;
3750 SetConsoleScreenBufferSize(hConsole, coordScreen);
3751 }
3752 }
3753
3754 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3755 {
3756#ifdef MCH_WRITE_DUMP
3757 if (fdDump)
3758 {
3759 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3760 GetLastError());
3761 fflush(fdDump);
3762 }
3763#endif
3764 }
3765
3766 /* define the new console buffer size */
3767 coordScreen.X = xSize;
3768 coordScreen.Y = ySize;
3769
3770 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3771 {
3772#ifdef MCH_WRITE_DUMP
3773 if (fdDump)
3774 {
3775 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3776 GetLastError());
3777 fflush(fdDump);
3778 }
3779#endif
3780 }
3781}
3782
3783
3784/*
3785 * Set the console window to `Rows' * `Columns'
3786 */
3787 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003788mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003789{
3790 COORD coordScreen;
3791
3792 /* Don't change window size while still starting up */
3793 if (suppress_winsize != 0)
3794 {
3795 suppress_winsize = 2;
3796 return;
3797 }
3798
3799 if (term_console)
3800 {
3801 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3802
3803 /* Clamp Rows and Columns to reasonable values */
3804 if (Rows > coordScreen.Y)
3805 Rows = coordScreen.Y;
3806 if (Columns > coordScreen.X)
3807 Columns = coordScreen.X;
3808
3809 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3810 }
3811}
3812
3813/*
3814 * Rows and/or Columns has changed.
3815 */
3816 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003817mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818{
3819 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3820}
3821
3822
3823/*
3824 * Called when started up, to set the winsize that was delayed.
3825 */
3826 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003827mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003828{
3829 if (suppress_winsize == 2)
3830 {
3831 suppress_winsize = 0;
3832 mch_set_shellsize();
3833 shell_resized();
3834 }
3835 suppress_winsize = 0;
3836}
3837#endif /* FEAT_GUI_W32 */
3838
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003839 static BOOL
3840vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003841 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003842 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003843 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003844 STARTUPINFO *si,
3845 PROCESS_INFORMATION *pi)
3846{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003847#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003848 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3849 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003850 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003851
3852 if (wcmd != NULL)
3853 {
3854 BOOL ret;
3855 ret = CreateProcessW(
3856 NULL, /* Executable name */
3857 wcmd, /* Command to execute */
3858 NULL, /* Process security attributes */
3859 NULL, /* Thread security attributes */
3860 inherit_handles, /* Inherit handles */
3861 flags, /* Creation flags */
3862 NULL, /* Environment */
3863 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003864 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003865 pi); /* Process information */
3866 vim_free(wcmd);
3867 return ret;
3868 }
3869 }
3870#endif
3871 return CreateProcess(
3872 NULL, /* Executable name */
3873 cmd, /* Command to execute */
3874 NULL, /* Process security attributes */
3875 NULL, /* Thread security attributes */
3876 inherit_handles, /* Inherit handles */
3877 flags, /* Creation flags */
3878 NULL, /* Environment */
3879 NULL, /* Current directory */
3880 si, /* Startup information */
3881 pi); /* Process information */
3882}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883
3884
3885#if defined(FEAT_GUI_W32) || defined(PROTO)
3886
3887/*
3888 * Specialised version of system() for Win32 GUI mode.
3889 * This version proceeds as follows:
3890 * 1. Create a console window for use by the subprocess
3891 * 2. Run the subprocess (it gets the allocated console by default)
3892 * 3. Wait for the subprocess to terminate and get its exit code
3893 * 4. Prompt the user to press a key to close the console window
3894 */
3895 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003896mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003897{
3898 STARTUPINFO si;
3899 PROCESS_INFORMATION pi;
3900 DWORD ret = 0;
3901 HWND hwnd = GetFocus();
3902
3903 si.cb = sizeof(si);
3904 si.lpReserved = NULL;
3905 si.lpDesktop = NULL;
3906 si.lpTitle = NULL;
3907 si.dwFlags = STARTF_USESHOWWINDOW;
3908 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003909 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003910 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003912 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003913 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914 else
3915 si.wShowWindow = SW_SHOWNORMAL;
3916 si.cbReserved2 = 0;
3917 si.lpReserved2 = NULL;
3918
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003920 vim_create_process(cmd, FALSE,
3921 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003922
3923 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 {
3925#ifdef FEAT_GUI
3926 int delay = 1;
3927
3928 /* Keep updating the window while waiting for the shell to finish. */
3929 for (;;)
3930 {
3931 MSG msg;
3932
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003933 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 {
3935 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003936 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003937 delay = 1;
3938 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003939 }
3940 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3941 break;
3942
3943 /* We start waiting for a very short time and then increase it, so
3944 * that we respond quickly when the process is quick, and don't
3945 * consume too much overhead when it's slow. */
3946 if (delay < 50)
3947 delay += 10;
3948 }
3949#else
3950 WaitForSingleObject(pi.hProcess, INFINITE);
3951#endif
3952
3953 /* Get the command exit code */
3954 GetExitCodeProcess(pi.hProcess, &ret);
3955 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956
3957 /* Close the handles to the subprocess, so that it goes away */
3958 CloseHandle(pi.hThread);
3959 CloseHandle(pi.hProcess);
3960
3961 /* Try to get input focus back. Doesn't always work though. */
3962 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3963
3964 return ret;
3965}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003966
3967/*
3968 * Thread launched by the gui to send the current buffer data to the
3969 * process. This way avoid to hang up vim totally if the children
3970 * process take a long time to process the lines.
3971 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02003972 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003973sub_process_writer(LPVOID param)
3974{
3975 HANDLE g_hChildStd_IN_Wr = param;
3976 linenr_T lnum = curbuf->b_op_start.lnum;
3977 DWORD len = 0;
3978 DWORD l;
3979 char_u *lp = ml_get(lnum);
3980 char_u *s;
3981 int written = 0;
3982
3983 for (;;)
3984 {
3985 l = (DWORD)STRLEN(lp + written);
3986 if (l == 0)
3987 len = 0;
3988 else if (lp[written] == NL)
3989 {
3990 /* NL -> NUL translation */
3991 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3992 }
3993 else
3994 {
3995 s = vim_strchr(lp + written, NL);
3996 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3997 s == NULL ? l : (DWORD)(s - (lp + written)),
3998 &len, NULL);
3999 }
4000 if (len == (int)l)
4001 {
4002 /* Finished a line, add a NL, unless this line should not have
4003 * one. */
4004 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004005 || (!curbuf->b_p_bin
4006 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004007 || (lnum != curbuf->b_no_eol_lnum
4008 && (lnum != curbuf->b_ml.ml_line_count
4009 || curbuf->b_p_eol)))
4010 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004011 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004012 }
4013
4014 ++lnum;
4015 if (lnum > curbuf->b_op_end.lnum)
4016 break;
4017
4018 lp = ml_get(lnum);
4019 written = 0;
4020 }
4021 else if (len > 0)
4022 written += len;
4023 }
4024
4025 /* finished all the lines, close pipe */
4026 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004027 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004028}
4029
4030
4031# define BUFLEN 100 /* length for buffer, stolen from unix version */
4032
4033/*
4034 * This function read from the children's stdout and write the
4035 * data on screen or in the buffer accordingly.
4036 */
4037 static void
4038dump_pipe(int options,
4039 HANDLE g_hChildStd_OUT_Rd,
4040 garray_T *ga,
4041 char_u buffer[],
4042 DWORD *buffer_off)
4043{
4044 DWORD availableBytes = 0;
4045 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004046 int ret;
4047 DWORD len;
4048 DWORD toRead;
4049 int repeatCount;
4050
4051 /* we query the pipe to see if there is any data to read
4052 * to avoid to perform a blocking read */
4053 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4054 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004055 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004056 NULL, /* number of read bytes */
4057 &availableBytes, /* available bytes total */
4058 NULL); /* byteLeft */
4059
4060 repeatCount = 0;
4061 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004062 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004063 {
4064 repeatCount++;
4065 toRead =
4066# ifdef FEAT_MBYTE
4067 (DWORD)(BUFLEN - *buffer_off);
4068# else
4069 (DWORD)BUFLEN;
4070# endif
4071 toRead = availableBytes < toRead ? availableBytes : toRead;
4072 ReadFile(g_hChildStd_OUT_Rd, buffer
4073# ifdef FEAT_MBYTE
4074 + *buffer_off, toRead
4075# else
4076 , toRead
4077# endif
4078 , &len, NULL);
4079
4080 /* If we haven't read anything, there is a problem */
4081 if (len == 0)
4082 break;
4083
4084 availableBytes -= len;
4085
4086 if (options & SHELL_READ)
4087 {
4088 /* Do NUL -> NL translation, append NL separated
4089 * lines to the current buffer. */
4090 for (i = 0; i < len; ++i)
4091 {
4092 if (buffer[i] == NL)
4093 append_ga_line(ga);
4094 else if (buffer[i] == NUL)
4095 ga_append(ga, NL);
4096 else
4097 ga_append(ga, buffer[i]);
4098 }
4099 }
4100# ifdef FEAT_MBYTE
4101 else if (has_mbyte)
4102 {
4103 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004104 int c;
4105 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004106
4107 len += *buffer_off;
4108 buffer[len] = NUL;
4109
4110 /* Check if the last character in buffer[] is
4111 * incomplete, keep these bytes for the next
4112 * round. */
4113 for (p = buffer; p < buffer + len; p += l)
4114 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004115 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004116 if (l == 0)
4117 l = 1; /* NUL byte? */
4118 else if (MB_BYTE2LEN(*p) != l)
4119 break;
4120 }
4121 if (p == buffer) /* no complete character */
4122 {
4123 /* avoid getting stuck at an illegal byte */
4124 if (len >= 12)
4125 ++p;
4126 else
4127 {
4128 *buffer_off = len;
4129 return;
4130 }
4131 }
4132 c = *p;
4133 *p = NUL;
4134 msg_puts(buffer);
4135 if (p < buffer + len)
4136 {
4137 *p = c;
4138 *buffer_off = (DWORD)((buffer + len) - p);
4139 mch_memmove(buffer, p, *buffer_off);
4140 return;
4141 }
4142 *buffer_off = 0;
4143 }
4144# endif /* FEAT_MBYTE */
4145 else
4146 {
4147 buffer[len] = NUL;
4148 msg_puts(buffer);
4149 }
4150
4151 windgoto(msg_row, msg_col);
4152 cursor_on();
4153 out_flush();
4154 }
4155}
4156
4157/*
4158 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4159 * for communication and doesn't open any new window.
4160 */
4161 static int
4162mch_system_piped(char *cmd, int options)
4163{
4164 STARTUPINFO si;
4165 PROCESS_INFORMATION pi;
4166 DWORD ret = 0;
4167
4168 HANDLE g_hChildStd_IN_Rd = NULL;
4169 HANDLE g_hChildStd_IN_Wr = NULL;
4170 HANDLE g_hChildStd_OUT_Rd = NULL;
4171 HANDLE g_hChildStd_OUT_Wr = NULL;
4172
4173 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4174 DWORD len;
4175
4176 /* buffer used to receive keys */
4177 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4178 int ta_len = 0; /* valid bytes in ta_buf[] */
4179
4180 DWORD i;
4181 int c;
4182 int noread_cnt = 0;
4183 garray_T ga;
4184 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004185 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004186 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004187
4188 SECURITY_ATTRIBUTES saAttr;
4189
4190 /* Set the bInheritHandle flag so pipe handles are inherited. */
4191 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4192 saAttr.bInheritHandle = TRUE;
4193 saAttr.lpSecurityDescriptor = NULL;
4194
4195 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4196 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004197 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004198 /* Create a pipe for the child process's STDIN. */
4199 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4200 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004201 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004202 {
4203 CloseHandle(g_hChildStd_IN_Rd);
4204 CloseHandle(g_hChildStd_IN_Wr);
4205 CloseHandle(g_hChildStd_OUT_Rd);
4206 CloseHandle(g_hChildStd_OUT_Wr);
4207 MSG_PUTS(_("\nCannot create pipes\n"));
4208 }
4209
4210 si.cb = sizeof(si);
4211 si.lpReserved = NULL;
4212 si.lpDesktop = NULL;
4213 si.lpTitle = NULL;
4214 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4215
4216 /* set-up our file redirection */
4217 si.hStdError = g_hChildStd_OUT_Wr;
4218 si.hStdOutput = g_hChildStd_OUT_Wr;
4219 si.hStdInput = g_hChildStd_IN_Rd;
4220 si.wShowWindow = SW_HIDE;
4221 si.cbReserved2 = 0;
4222 si.lpReserved2 = NULL;
4223
4224 if (options & SHELL_READ)
4225 ga_init2(&ga, 1, BUFLEN);
4226
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004227 if (cmd != NULL)
4228 {
4229 p = (char *)vim_strsave((char_u *)cmd);
4230 if (p != NULL)
4231 unescape_shellxquote((char_u *)p, p_sxe);
4232 else
4233 p = cmd;
4234 }
4235
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004236 /* Now, run the command.
4237 * About "Inherit handles" being TRUE: this command can be litigious,
4238 * handle inheritance was deactivated for pending temp file, but, if we
4239 * deactivate it, the pipes don't work for some reason. */
4240 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004241
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004242 if (p != cmd)
4243 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004244
4245 /* Close our unused side of the pipes */
4246 CloseHandle(g_hChildStd_IN_Rd);
4247 CloseHandle(g_hChildStd_OUT_Wr);
4248
4249 if (options & SHELL_WRITE)
4250 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004251 HANDLE thread = (HANDLE)
4252 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004253 0, /* default stack size */
4254 sub_process_writer, /* function to be executed */
4255 g_hChildStd_IN_Wr, /* parameter */
4256 0, /* creation flag, start immediately */
4257 NULL); /* we don't care about thread id */
4258 CloseHandle(thread);
4259 g_hChildStd_IN_Wr = NULL;
4260 }
4261
4262 /* Keep updating the window while waiting for the shell to finish. */
4263 for (;;)
4264 {
4265 MSG msg;
4266
Bram Moolenaar175d0702013-12-11 18:36:33 +01004267 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004268 {
4269 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004270 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004271 }
4272
4273 /* write pipe information in the window */
4274 if ((options & (SHELL_READ|SHELL_WRITE))
4275# ifdef FEAT_GUI
4276 || gui.in_use
4277# endif
4278 )
4279 {
4280 len = 0;
4281 if (!(options & SHELL_EXPAND)
4282 && ((options &
4283 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4284 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4285# ifdef FEAT_GUI
4286 || gui.in_use
4287# endif
4288 )
4289 && (ta_len > 0 || noread_cnt > 4))
4290 {
4291 if (ta_len == 0)
4292 {
4293 /* Get extra characters when we don't have any. Reset the
4294 * counter and timer. */
4295 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004296 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4297 }
4298 if (ta_len > 0 || len > 0)
4299 {
4300 /*
4301 * For pipes: Check for CTRL-C: send interrupt signal to
4302 * child. Check for CTRL-D: EOF, close pipe to child.
4303 */
4304 if (len == 1 && cmd != NULL)
4305 {
4306 if (ta_buf[ta_len] == Ctrl_C)
4307 {
4308 /* Learn what exit code is expected, for
4309 * now put 9 as SIGKILL */
4310 TerminateProcess(pi.hProcess, 9);
4311 }
4312 if (ta_buf[ta_len] == Ctrl_D)
4313 {
4314 CloseHandle(g_hChildStd_IN_Wr);
4315 g_hChildStd_IN_Wr = NULL;
4316 }
4317 }
4318
4319 /* replace K_BS by <BS> and K_DEL by <DEL> */
4320 for (i = ta_len; i < ta_len + len; ++i)
4321 {
4322 if (ta_buf[i] == CSI && len - i > 2)
4323 {
4324 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4325 if (c == K_DEL || c == K_KDEL || c == K_BS)
4326 {
4327 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4328 (size_t)(len - i - 2));
4329 if (c == K_DEL || c == K_KDEL)
4330 ta_buf[i] = DEL;
4331 else
4332 ta_buf[i] = Ctrl_H;
4333 len -= 2;
4334 }
4335 }
4336 else if (ta_buf[i] == '\r')
4337 ta_buf[i] = '\n';
4338# ifdef FEAT_MBYTE
4339 if (has_mbyte)
4340 i += (*mb_ptr2len_len)(ta_buf + i,
4341 ta_len + len - i) - 1;
4342# endif
4343 }
4344
4345 /*
4346 * For pipes: echo the typed characters. For a pty this
4347 * does not seem to work.
4348 */
4349 for (i = ta_len; i < ta_len + len; ++i)
4350 {
4351 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4352 msg_putchar(ta_buf[i]);
4353# ifdef FEAT_MBYTE
4354 else if (has_mbyte)
4355 {
4356 int l = (*mb_ptr2len)(ta_buf + i);
4357
4358 msg_outtrans_len(ta_buf + i, l);
4359 i += l - 1;
4360 }
4361# endif
4362 else
4363 msg_outtrans_len(ta_buf + i, 1);
4364 }
4365 windgoto(msg_row, msg_col);
4366 out_flush();
4367
4368 ta_len += len;
4369
4370 /*
4371 * Write the characters to the child, unless EOF has been
4372 * typed for pipes. Write one character at a time, to
4373 * avoid losing too much typeahead. When writing buffer
4374 * lines, drop the typed characters (only check for
4375 * CTRL-C).
4376 */
4377 if (options & SHELL_WRITE)
4378 ta_len = 0;
4379 else if (g_hChildStd_IN_Wr != NULL)
4380 {
4381 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4382 1, &len, NULL);
4383 // if we are typing in, we want to keep things reactive
4384 delay = 1;
4385 if (len > 0)
4386 {
4387 ta_len -= len;
4388 mch_memmove(ta_buf, ta_buf + len, ta_len);
4389 }
4390 }
4391 }
4392 }
4393 }
4394
4395 if (ta_len)
4396 ui_inchar_undo(ta_buf, ta_len);
4397
4398 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4399 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004400 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004401 break;
4402 }
4403
4404 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004405 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004406
4407 /* We start waiting for a very short time and then increase it, so
4408 * that we respond quickly when the process is quick, and don't
4409 * consume too much overhead when it's slow. */
4410 if (delay < 50)
4411 delay += 10;
4412 }
4413
4414 /* Close the pipe */
4415 CloseHandle(g_hChildStd_OUT_Rd);
4416 if (g_hChildStd_IN_Wr != NULL)
4417 CloseHandle(g_hChildStd_IN_Wr);
4418
4419 WaitForSingleObject(pi.hProcess, INFINITE);
4420
4421 /* Get the command exit code */
4422 GetExitCodeProcess(pi.hProcess, &ret);
4423
4424 if (options & SHELL_READ)
4425 {
4426 if (ga.ga_len > 0)
4427 {
4428 append_ga_line(&ga);
4429 /* remember that the NL was missing */
4430 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4431 }
4432 else
4433 curbuf->b_no_eol_lnum = 0;
4434 ga_clear(&ga);
4435 }
4436
4437 /* Close the handles to the subprocess, so that it goes away */
4438 CloseHandle(pi.hThread);
4439 CloseHandle(pi.hProcess);
4440
4441 return ret;
4442}
4443
4444 static int
4445mch_system(char *cmd, int options)
4446{
4447 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004448 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004449 return mch_system_piped(cmd, options);
4450 else
4451 return mch_system_classic(cmd, options);
4452}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453#else
4454
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004455# ifdef FEAT_MBYTE
4456 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004457mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004458{
4459 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4460 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004461 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004462 if (wcmd != NULL)
4463 {
4464 int ret = _wsystem(wcmd);
4465 vim_free(wcmd);
4466 return ret;
4467 }
4468 }
4469 return system(cmd);
4470}
4471# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004472# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004473# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474
4475#endif
4476
4477/*
4478 * Either execute a command by calling the shell or start a new shell
4479 */
4480 int
4481mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004482 char_u *cmd,
4483 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484{
4485 int x = 0;
4486 int tmode = cur_tmode;
4487#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004488 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004489# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004490 int did_set_title = FALSE;
4491
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004492 /* Change the title to reflect that we are in a subshell. */
4493 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4494 {
4495 WCHAR szShellTitle[512];
4496
4497 if (GetConsoleTitleW(szShellTitle,
4498 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4499 {
4500 if (cmd == NULL)
4501 wcscat(szShellTitle, L" :sh");
4502 else
4503 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004504 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004505
4506 if (wn != NULL)
4507 {
4508 wcscat(szShellTitle, L" - !");
4509 if ((wcslen(szShellTitle) + wcslen(wn) <
4510 sizeof(szShellTitle)/sizeof(WCHAR)))
4511 wcscat(szShellTitle, wn);
4512 SetConsoleTitleW(szShellTitle);
4513 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004514 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004515 }
4516 }
4517 }
4518 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004519 if (!did_set_title)
4520# endif
4521 /* Change the title to reflect that we are in a subshell. */
4522 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004523 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004524 if (cmd == NULL)
4525 strcat(szShellTitle, " :sh");
4526 else
4527 {
4528 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004529 if ((strlen(szShellTitle) + strlen((char *)cmd)
4530 < sizeof(szShellTitle)))
4531 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004532 }
4533 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004534 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535#endif
4536
4537 out_flush();
4538
4539#ifdef MCH_WRITE_DUMP
4540 if (fdDump)
4541 {
4542 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4543 fflush(fdDump);
4544 }
4545#endif
4546
4547 /*
4548 * Catch all deadly signals while running the external command, because a
4549 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4550 */
4551 signal(SIGINT, SIG_IGN);
4552#if defined(__GNUC__) && !defined(__MINGW32__)
4553 signal(SIGKILL, SIG_IGN);
4554#else
4555 signal(SIGBREAK, SIG_IGN);
4556#endif
4557 signal(SIGILL, SIG_IGN);
4558 signal(SIGFPE, SIG_IGN);
4559 signal(SIGSEGV, SIG_IGN);
4560 signal(SIGTERM, SIG_IGN);
4561 signal(SIGABRT, SIG_IGN);
4562
4563 if (options & SHELL_COOKED)
4564 settmode(TMODE_COOK); /* set to normal mode */
4565
4566 if (cmd == NULL)
4567 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004568 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004569 }
4570 else
4571 {
4572 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004573 char_u *newcmd = NULL;
4574 char_u *cmdbase = cmd;
4575 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004576
4577 /* Skip a leading ", ( and "(. */
4578 if (*cmdbase == '"' )
4579 ++cmdbase;
4580 if (*cmdbase == '(')
4581 ++cmdbase;
4582
4583 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4584 {
4585 STARTUPINFO si;
4586 PROCESS_INFORMATION pi;
4587 DWORD flags = CREATE_NEW_CONSOLE;
4588 char_u *p;
4589
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004590 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004591 si.cb = sizeof(si);
4592 si.lpReserved = NULL;
4593 si.lpDesktop = NULL;
4594 si.lpTitle = NULL;
4595 si.dwFlags = 0;
4596 si.cbReserved2 = 0;
4597 si.lpReserved2 = NULL;
4598
4599 cmdbase = skipwhite(cmdbase + 5);
4600 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4601 && vim_iswhite(cmdbase[4]))
4602 {
4603 cmdbase = skipwhite(cmdbase + 4);
4604 si.dwFlags = STARTF_USESHOWWINDOW;
4605 si.wShowWindow = SW_SHOWMINNOACTIVE;
4606 }
4607 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4608 && vim_iswhite(cmdbase[2]))
4609 {
4610 cmdbase = skipwhite(cmdbase + 2);
4611 flags = CREATE_NO_WINDOW;
4612 si.dwFlags = STARTF_USESTDHANDLES;
4613 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004614 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004615 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004616 NULL, // Security att.
4617 OPEN_EXISTING, // Open flags
4618 FILE_ATTRIBUTE_NORMAL, // File att.
4619 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004620 si.hStdOutput = si.hStdInput;
4621 si.hStdError = si.hStdInput;
4622 }
4623
4624 /* Remove a trailing ", ) and )" if they have a match
4625 * at the start of the command. */
4626 if (cmdbase > cmd)
4627 {
4628 p = cmdbase + STRLEN(cmdbase);
4629 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4630 *--p = NUL;
4631 if (p > cmdbase && p[-1] == ')'
4632 && (*cmd =='(' || cmd[1] == '('))
4633 *--p = NUL;
4634 }
4635
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004636 newcmd = cmdbase;
4637 unescape_shellxquote(cmdbase, p_sxe);
4638
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004639 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004640 * If creating new console, arguments are passed to the
4641 * 'cmd.exe' as-is. If it's not, arguments are not treated
4642 * correctly for current 'cmd.exe'. So unescape characters in
4643 * shellxescape except '|' for avoiding to be treated as
4644 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004645 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004646 if (flags != CREATE_NEW_CONSOLE)
4647 {
4648 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004649 char_u *cmd_shell = mch_getenv("COMSPEC");
4650
4651 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004652 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004653
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004654 subcmd = vim_strsave_escaped_ext(cmdbase,
4655 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004656 if (subcmd != NULL)
4657 {
4658 /* make "cmd.exe /c arguments" */
4659 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004660 newcmd = lalloc(cmdlen, TRUE);
4661 if (newcmd != NULL)
4662 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004663 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004664 else
4665 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004666 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004667 }
4668 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004669
4670 /*
4671 * Now, start the command as a process, so that it doesn't
4672 * inherit our handles which causes unpleasant dangling swap
4673 * files if we exit before the spawned process
4674 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004675 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004676 x = 0;
4677 else
4678 {
4679 x = -1;
4680#ifdef FEAT_GUI_W32
4681 EMSG(_("E371: Command not found"));
4682#endif
4683 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004684
4685 if (newcmd != cmdbase)
4686 vim_free(newcmd);
4687
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004688 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004689 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004690 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004691 CloseHandle(si.hStdInput);
4692 }
4693 /* Close the handles to the subprocess, so that it goes away */
4694 CloseHandle(pi.hThread);
4695 CloseHandle(pi.hProcess);
4696 }
4697 else
4698 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004699 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004700#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004701 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004702#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004703 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4704
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004705 newcmd = lalloc(cmdlen, TRUE);
4706 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004707 {
4708#if defined(FEAT_GUI_W32)
4709 if (need_vimrun_warning)
4710 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004711 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4712 "External commands will not pause after completion.\n"
4713 "See :help win32-vimrun for more information.");
4714 char *title = _("Vim Warning");
4715# ifdef FEAT_MBYTE
4716 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4717 {
4718 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4719 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
4720
4721 if (wmsg != NULL && wtitle != NULL)
4722 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4723 vim_free(wmsg);
4724 vim_free(wtitle);
4725 }
4726 else
4727# endif
4728 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729 need_vimrun_warning = FALSE;
4730 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004731 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004732 /* Use vimrun to execute the command. It opens a console
4733 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004734 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735 vimrun_path,
4736 (msg_silent != 0 || (options & SHELL_DOOUT))
4737 ? "-s " : "",
4738 p_sh, p_shcf, cmd);
4739 else
4740#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004741 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004742 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004743 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004744 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004746 }
4747 }
4748
4749 if (tmode == TMODE_RAW)
4750 settmode(TMODE_RAW); /* set to raw mode */
4751
4752 /* Print the return value, unless "vimrun" was used. */
4753 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4754#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004755 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756#endif
4757 )
4758 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004759 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760 msg_putchar('\n');
4761 }
4762#ifdef FEAT_TITLE
4763 resettitle();
4764#endif
4765
4766 signal(SIGINT, SIG_DFL);
4767#if defined(__GNUC__) && !defined(__MINGW32__)
4768 signal(SIGKILL, SIG_DFL);
4769#else
4770 signal(SIGBREAK, SIG_DFL);
4771#endif
4772 signal(SIGILL, SIG_DFL);
4773 signal(SIGFPE, SIG_DFL);
4774 signal(SIGSEGV, SIG_DFL);
4775 signal(SIGTERM, SIG_DFL);
4776 signal(SIGABRT, SIG_DFL);
4777
4778 return x;
4779}
4780
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004781#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004782 static HANDLE
4783job_io_file_open(
4784 char_u *fname,
4785 DWORD dwDesiredAccess,
4786 DWORD dwShareMode,
4787 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4788 DWORD dwCreationDisposition,
4789 DWORD dwFlagsAndAttributes)
4790{
4791 HANDLE h;
4792# ifdef FEAT_MBYTE
4793 WCHAR *wn = NULL;
4794 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4795 {
4796 wn = enc_to_utf16(fname, NULL);
4797 if (wn != NULL)
4798 {
4799 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4800 lpSecurityAttributes, dwCreationDisposition,
4801 dwFlagsAndAttributes, NULL);
4802 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004803 }
4804 }
4805 if (wn == NULL)
4806# endif
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004807 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
4808 lpSecurityAttributes, dwCreationDisposition,
4809 dwFlagsAndAttributes, NULL);
4810 return h;
4811}
4812
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004813 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01004814mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004815{
4816 STARTUPINFO si;
4817 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02004818 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004819 SECURITY_ATTRIBUTES saAttr;
4820 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01004821 HANDLE ifd[2];
4822 HANDLE ofd[2];
4823 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004824
4825 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
4826 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
4827 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
4828 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
4829 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
4830 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
4831 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
4832
4833 if (use_out_for_err && use_null_for_out)
4834 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01004835
4836 ifd[0] = INVALID_HANDLE_VALUE;
4837 ifd[1] = INVALID_HANDLE_VALUE;
4838 ofd[0] = INVALID_HANDLE_VALUE;
4839 ofd[1] = INVALID_HANDLE_VALUE;
4840 efd[0] = INVALID_HANDLE_VALUE;
4841 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004842
Bram Moolenaar14207f42016-10-27 21:13:10 +02004843 jo = CreateJobObject(NULL, NULL);
4844 if (jo == NULL)
4845 {
4846 job->jv_status = JOB_FAILED;
4847 goto failed;
4848 }
4849
Bram Moolenaar76467df2016-02-12 19:30:26 +01004850 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004851 ZeroMemory(&si, sizeof(si));
4852 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01004853 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004854 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004855
Bram Moolenaard8070362016-02-15 21:56:54 +01004856 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4857 saAttr.bInheritHandle = TRUE;
4858 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004859
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004860 if (use_file_for_in)
4861 {
4862 char_u *fname = options->jo_io_name[PART_IN];
4863
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004864 ifd[0] = job_io_file_open(fname, GENERIC_READ,
4865 FILE_SHARE_READ | FILE_SHARE_WRITE,
4866 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
4867 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01004868 {
4869 EMSG2(_(e_notopen), fname);
4870 goto failed;
4871 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004872 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004873 else if (!use_null_for_in &&
4874 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004875 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004876 goto failed;
4877
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004878 if (use_file_for_out)
4879 {
4880 char_u *fname = options->jo_io_name[PART_OUT];
4881
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004882 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
4883 FILE_SHARE_READ | FILE_SHARE_WRITE,
4884 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
4885 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004886 {
4887 EMSG2(_(e_notopen), fname);
4888 goto failed;
4889 }
4890 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004891 else if (!use_null_for_out &&
4892 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004893 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004894 goto failed;
4895
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004896 if (use_file_for_err)
4897 {
4898 char_u *fname = options->jo_io_name[PART_ERR];
4899
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004900 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
4901 FILE_SHARE_READ | FILE_SHARE_WRITE,
4902 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
4903 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004904 {
4905 EMSG2(_(e_notopen), fname);
4906 goto failed;
4907 }
4908 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004909 else if (!use_out_for_err && !use_null_for_err &&
4910 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004911 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01004912 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004913
Bram Moolenaard8070362016-02-15 21:56:54 +01004914 si.dwFlags |= STARTF_USESTDHANDLES;
4915 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004916 si.hStdOutput = ofd[1];
4917 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
4918
4919 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
4920 {
Bram Moolenaarde279892016-03-11 22:19:44 +01004921 if (options->jo_set & JO_CHANNEL)
4922 {
4923 channel = options->jo_channel;
4924 if (channel != NULL)
4925 ++channel->ch_refcount;
4926 }
4927 else
4928 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004929 if (channel == NULL)
4930 goto failed;
4931 }
Bram Moolenaard8070362016-02-15 21:56:54 +01004932
4933 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02004934 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004935 CREATE_DEFAULT_ERROR_MODE |
4936 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01004937 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004938 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01004939 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02004940 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004941 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004942 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004943 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004944
Bram Moolenaar14207f42016-10-27 21:13:10 +02004945 if (!AssignProcessToJobObject(jo, pi.hProcess))
4946 {
4947 /* if failing, switch the way to terminate
4948 * process with TerminateProcess. */
4949 CloseHandle(jo);
4950 jo = NULL;
4951 }
4952 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01004953 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004954 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02004955 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004956 job->jv_status = JOB_STARTED;
4957
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02004958 CloseHandle(ifd[0]);
4959 CloseHandle(ofd[1]);
4960 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01004961 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01004962
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004963 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004964 if (channel != NULL)
4965 {
4966 channel_set_pipes(channel,
4967 use_file_for_in || use_null_for_in
4968 ? INVALID_FD : (sock_T)ifd[1],
4969 use_file_for_out || use_null_for_out
4970 ? INVALID_FD : (sock_T)ofd[0],
4971 use_out_for_err || use_file_for_err || use_null_for_err
4972 ? INVALID_FD : (sock_T)efd[0]);
4973 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004974 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004975 return;
4976
4977failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01004978 CloseHandle(ifd[0]);
4979 CloseHandle(ofd[0]);
4980 CloseHandle(efd[0]);
4981 CloseHandle(ifd[1]);
4982 CloseHandle(ofd[1]);
4983 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01004984 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004985}
4986
4987 char *
4988mch_job_status(job_T *job)
4989{
4990 DWORD dwExitCode = 0;
4991
Bram Moolenaar76467df2016-02-12 19:30:26 +01004992 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
4993 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004994 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01004995 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01004996 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02004997 {
4998 ch_log(job->jv_channel, "Job ended");
4999 job->jv_status = JOB_ENDED;
5000 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005001 return "dead";
5002 }
5003 return "run";
5004}
5005
Bram Moolenaar97792de2016-10-15 18:36:49 +02005006 job_T *
5007mch_detect_ended_job(job_T *job_list)
5008{
5009 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5010 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5011 job_T *job = job_list;
5012
5013 while (job != NULL)
5014 {
5015 DWORD n;
5016 DWORD result;
5017
5018 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5019 && job != NULL; job = job->jv_next)
5020 {
5021 if (job->jv_status == JOB_STARTED)
5022 {
5023 jobHandles[n] = job->jv_proc_info.hProcess;
5024 jobArray[n] = job;
5025 ++n;
5026 }
5027 }
5028 if (n == 0)
5029 continue;
5030 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5031 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5032 {
5033 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5034
5035 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5036 return wait_job;
5037 }
5038 }
5039 return NULL;
5040}
5041
Bram Moolenaarfb630902016-10-29 14:55:00 +02005042 static BOOL
5043terminate_all(HANDLE process, int code)
5044{
5045 PROCESSENTRY32 pe;
5046 HANDLE h = INVALID_HANDLE_VALUE;
5047 DWORD pid = GetProcessId(process);
5048
5049 if (pid != 0)
5050 {
5051 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5052 if (h != INVALID_HANDLE_VALUE)
5053 {
5054 pe.dwSize = sizeof(PROCESSENTRY32);
5055 if (!Process32First(h, &pe))
5056 goto theend;
5057
5058 do
5059 {
5060 if (pe.th32ParentProcessID == pid)
5061 {
5062 HANDLE ph = OpenProcess(
5063 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5064 if (ph != NULL)
5065 {
5066 terminate_all(ph, code);
5067 CloseHandle(ph);
5068 }
5069 }
5070 } while (Process32Next(h, &pe));
5071
5072 CloseHandle(h);
5073 }
5074 }
5075
5076theend:
5077 return TerminateProcess(process, code);
5078}
5079
5080/*
5081 * Send a (deadly) signal to "job".
5082 * Return FAIL if it didn't work.
5083 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005084 int
5085mch_stop_job(job_T *job, char_u *how)
5086{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005087 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005088
Bram Moolenaar923d9262016-02-25 20:56:01 +01005089 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005090 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005091 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005092 if (job->jv_job_object != NULL)
5093 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005094 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005095 }
5096
5097 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5098 return FAIL;
5099 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005100 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5101 job->jv_proc_info.dwProcessId)
5102 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005103 FreeConsole();
5104 return ret;
5105}
5106
5107/*
5108 * Clear the data related to "job".
5109 */
5110 void
5111mch_clear_job(job_T *job)
5112{
5113 if (job->jv_status != JOB_FAILED)
5114 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005115 if (job->jv_job_object != NULL)
5116 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005117 CloseHandle(job->jv_proc_info.hProcess);
5118 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005119}
5120#endif
5121
Bram Moolenaar071d4272004-06-13 20:20:40 +00005122
5123#ifndef FEAT_GUI_W32
5124
5125/*
5126 * Start termcap mode
5127 */
5128 static void
5129termcap_mode_start(void)
5130{
5131 DWORD cmodein;
5132
5133 if (g_fTermcapMode)
5134 return;
5135
5136 SaveConsoleBuffer(&g_cbNonTermcap);
5137
5138 if (g_cbTermcap.IsValid)
5139 {
5140 /*
5141 * We've been in termcap mode before. Restore certain screen
5142 * characteristics, including the buffer size and the window
5143 * size. Since we will be redrawing the screen, we don't need
5144 * to restore the actual contents of the buffer.
5145 */
5146 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5147 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5148 Rows = g_cbTermcap.Info.dwSize.Y;
5149 Columns = g_cbTermcap.Info.dwSize.X;
5150 }
5151 else
5152 {
5153 /*
5154 * This is our first time entering termcap mode. Clear the console
5155 * screen buffer, and resize the buffer to match the current window
5156 * size. We will use this as the size of our editing environment.
5157 */
5158 ClearConsoleBuffer(g_attrCurrent);
5159 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5160 }
5161
5162#ifdef FEAT_TITLE
5163 resettitle();
5164#endif
5165
5166 GetConsoleMode(g_hConIn, &cmodein);
5167#ifdef FEAT_MOUSE
5168 if (g_fMouseActive)
5169 cmodein |= ENABLE_MOUSE_INPUT;
5170 else
5171 cmodein &= ~ENABLE_MOUSE_INPUT;
5172#endif
5173 cmodein |= ENABLE_WINDOW_INPUT;
5174 SetConsoleMode(g_hConIn, cmodein);
5175
5176 redraw_later_clear();
5177 g_fTermcapMode = TRUE;
5178}
5179
5180
5181/*
5182 * End termcap mode
5183 */
5184 static void
5185termcap_mode_end(void)
5186{
5187 DWORD cmodein;
5188 ConsoleBuffer *cb;
5189 COORD coord;
5190 DWORD dwDummy;
5191
5192 if (!g_fTermcapMode)
5193 return;
5194
5195 SaveConsoleBuffer(&g_cbTermcap);
5196
5197 GetConsoleMode(g_hConIn, &cmodein);
5198 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5199 SetConsoleMode(g_hConIn, cmodein);
5200
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005201#ifdef FEAT_RESTORE_ORIG_SCREEN
5202 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5203#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005204 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005205#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005206 RestoreConsoleBuffer(cb, p_rs);
5207 SetConsoleCursorInfo(g_hConOut, &g_cci);
5208
5209 if (p_rs || exiting)
5210 {
5211 /*
5212 * Clear anything that happens to be on the current line.
5213 */
5214 coord.X = 0;
5215 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5216 FillConsoleOutputCharacter(g_hConOut, ' ',
5217 cb->Info.dwSize.X, coord, &dwDummy);
5218 /*
5219 * The following is just for aesthetics. If we are exiting without
5220 * restoring the screen, then we want to have a prompt string
5221 * appear at the bottom line. However, the command interpreter
5222 * seems to always advance the cursor one line before displaying
5223 * the prompt string, which causes the screen to scroll. To
5224 * counter this, move the cursor up one line before exiting.
5225 */
5226 if (exiting && !p_rs)
5227 coord.Y--;
5228 /*
5229 * Position the cursor at the leftmost column of the desired row.
5230 */
5231 SetConsoleCursorPosition(g_hConOut, coord);
5232 }
5233
5234 g_fTermcapMode = FALSE;
5235}
5236#endif /* FEAT_GUI_W32 */
5237
5238
5239#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005240/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241 void
5242mch_write(
5243 char_u *s,
5244 int len)
5245{
5246 /* never used */
5247}
5248
5249#else
5250
5251/*
5252 * clear `n' chars, starting from `coord'
5253 */
5254 static void
5255clear_chars(
5256 COORD coord,
5257 DWORD n)
5258{
5259 DWORD dwDummy;
5260
5261 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5262 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5263}
5264
5265
5266/*
5267 * Clear the screen
5268 */
5269 static void
5270clear_screen(void)
5271{
5272 g_coord.X = g_coord.Y = 0;
5273 clear_chars(g_coord, Rows * Columns);
5274}
5275
5276
5277/*
5278 * Clear to end of display
5279 */
5280 static void
5281clear_to_end_of_display(void)
5282{
5283 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5284 * Columns + (Columns - g_coord.X));
5285}
5286
5287
5288/*
5289 * Clear to end of line
5290 */
5291 static void
5292clear_to_end_of_line(void)
5293{
5294 clear_chars(g_coord, Columns - g_coord.X);
5295}
5296
5297
5298/*
5299 * Scroll the scroll region up by `cLines' lines
5300 */
5301 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005302scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005303{
5304 COORD oldcoord = g_coord;
5305
5306 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5307 delete_lines(cLines);
5308
5309 g_coord = oldcoord;
5310}
5311
5312
5313/*
5314 * Set the scroll region
5315 */
5316 static void
5317set_scroll_region(
5318 unsigned left,
5319 unsigned top,
5320 unsigned right,
5321 unsigned bottom)
5322{
5323 if (left >= right
5324 || top >= bottom
5325 || right > (unsigned) Columns - 1
5326 || bottom > (unsigned) Rows - 1)
5327 return;
5328
5329 g_srScrollRegion.Left = left;
5330 g_srScrollRegion.Top = top;
5331 g_srScrollRegion.Right = right;
5332 g_srScrollRegion.Bottom = bottom;
5333}
5334
5335
5336/*
5337 * Insert `cLines' lines at the current cursor position
5338 */
5339 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005340insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005341{
5342 SMALL_RECT source;
5343 COORD dest;
5344 CHAR_INFO fill;
5345
5346 dest.X = 0;
5347 dest.Y = g_coord.Y + cLines;
5348
5349 source.Left = 0;
5350 source.Top = g_coord.Y;
5351 source.Right = g_srScrollRegion.Right;
5352 source.Bottom = g_srScrollRegion.Bottom - cLines;
5353
5354 fill.Char.AsciiChar = ' ';
5355 fill.Attributes = g_attrCurrent;
5356
5357 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5358
5359 /* Here we have to deal with a win32 console flake: If the scroll
5360 * region looks like abc and we scroll c to a and fill with d we get
5361 * cbd... if we scroll block c one line at a time to a, we get cdd...
5362 * vim expects cdd consistently... So we have to deal with that
5363 * here... (this also occurs scrolling the same way in the other
5364 * direction). */
5365
5366 if (source.Bottom < dest.Y)
5367 {
5368 COORD coord;
5369
5370 coord.X = 0;
5371 coord.Y = source.Bottom;
5372 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5373 }
5374}
5375
5376
5377/*
5378 * Delete `cLines' lines at the current cursor position
5379 */
5380 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005381delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005382{
5383 SMALL_RECT source;
5384 COORD dest;
5385 CHAR_INFO fill;
5386 int nb;
5387
5388 dest.X = 0;
5389 dest.Y = g_coord.Y;
5390
5391 source.Left = 0;
5392 source.Top = g_coord.Y + cLines;
5393 source.Right = g_srScrollRegion.Right;
5394 source.Bottom = g_srScrollRegion.Bottom;
5395
5396 fill.Char.AsciiChar = ' ';
5397 fill.Attributes = g_attrCurrent;
5398
5399 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5400
5401 /* Here we have to deal with a win32 console flake: If the scroll
5402 * region looks like abc and we scroll c to a and fill with d we get
5403 * cbd... if we scroll block c one line at a time to a, we get cdd...
5404 * vim expects cdd consistently... So we have to deal with that
5405 * here... (this also occurs scrolling the same way in the other
5406 * direction). */
5407
5408 nb = dest.Y + (source.Bottom - source.Top) + 1;
5409
5410 if (nb < source.Top)
5411 {
5412 COORD coord;
5413
5414 coord.X = 0;
5415 coord.Y = nb;
5416 clear_chars(coord, Columns * (source.Top - nb));
5417 }
5418}
5419
5420
5421/*
5422 * Set the cursor position
5423 */
5424 static void
5425gotoxy(
5426 unsigned x,
5427 unsigned y)
5428{
5429 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5430 return;
5431
5432 /* external cursor coords are 1-based; internal are 0-based */
5433 g_coord.X = x - 1;
5434 g_coord.Y = y - 1;
5435 SetConsoleCursorPosition(g_hConOut, g_coord);
5436}
5437
5438
5439/*
5440 * Set the current text attribute = (foreground | background)
5441 * See ../doc/os_win32.txt for the numbers.
5442 */
5443 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005444textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005445{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005446 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005447
5448 SetConsoleTextAttribute(g_hConOut, wAttr);
5449}
5450
5451
5452 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005453textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005454{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005455 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005456
5457 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5458}
5459
5460
5461 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005462textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005463{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005464 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005465
5466 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5467}
5468
5469
5470/*
5471 * restore the default text attribute (whatever we started with)
5472 */
5473 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005474normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005475{
5476 textattr(g_attrDefault);
5477}
5478
5479
5480static WORD g_attrPreStandout = 0;
5481
5482/*
5483 * Make the text standout, by brightening it
5484 */
5485 static void
5486standout(void)
5487{
5488 g_attrPreStandout = g_attrCurrent;
5489 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5490}
5491
5492
5493/*
5494 * Turn off standout mode
5495 */
5496 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005497standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498{
5499 if (g_attrPreStandout)
5500 {
5501 textattr(g_attrPreStandout);
5502 g_attrPreStandout = 0;
5503 }
5504}
5505
5506
5507/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005508 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005509 */
5510 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005511mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512{
5513 char_u *p;
5514 int n;
5515
5516 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5517 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5518 if (T_ME[0] == ESC && T_ME[1] == '|')
5519 {
5520 p = T_ME + 2;
5521 n = getdigits(&p);
5522 if (*p == 'm' && n > 0)
5523 {
5524 cterm_normal_fg_color = (n & 0xf) + 1;
5525 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5526 }
5527 }
5528}
5529
5530
5531/*
5532 * visual bell: flash the screen
5533 */
5534 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005535visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005536{
5537 COORD coordOrigin = {0, 0};
5538 WORD attrFlash = ~g_attrCurrent & 0xff;
5539
5540 DWORD dwDummy;
5541 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5542
5543 if (oldattrs == NULL)
5544 return;
5545 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5546 coordOrigin, &dwDummy);
5547 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5548 coordOrigin, &dwDummy);
5549
5550 Sleep(15); /* wait for 15 msec */
5551 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5552 coordOrigin, &dwDummy);
5553 vim_free(oldattrs);
5554}
5555
5556
5557/*
5558 * Make the cursor visible or invisible
5559 */
5560 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005561cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562{
5563 s_cursor_visible = fVisible;
5564#ifdef MCH_CURSOR_SHAPE
5565 mch_update_cursor();
5566#endif
5567}
5568
5569
5570/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005571 * write `cbToWrite' bytes in `pchBuf' to the screen
5572 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005574 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005576 char_u *pchBuf,
5577 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005578{
5579 COORD coord = g_coord;
5580 DWORD written;
5581
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005582#ifdef FEAT_MBYTE
5583 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5584 {
5585 static WCHAR *unicodebuf = NULL;
5586 static int unibuflen = 0;
5587 int length;
5588 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005590 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5591 if (unicodebuf == NULL || length > unibuflen)
5592 {
5593 vim_free(unicodebuf);
5594 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5595 unibuflen = length;
5596 }
5597 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5598 unicodebuf, unibuflen);
5599
5600 cells = mb_string2cells(pchBuf, cbToWrite);
5601 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5602 coord, &written);
5603 /* When writing fails or didn't write a single character, pretend one
5604 * character was written, otherwise we get stuck. */
5605 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5606 coord, &cchwritten) == 0
5607 || cchwritten == 0)
5608 cchwritten = 1;
5609
5610 if (cchwritten == length)
5611 {
5612 written = cbToWrite;
5613 g_coord.X += (SHORT)cells;
5614 }
5615 else
5616 {
5617 char_u *p = pchBuf;
5618 for (n = 0; n < cchwritten; n++)
5619 mb_cptr_adv(p);
5620 written = p - pchBuf;
5621 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5622 }
5623 }
5624 else
5625#endif
5626 {
5627 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5628 coord, &written);
5629 /* When writing fails or didn't write a single character, pretend one
5630 * character was written, otherwise we get stuck. */
5631 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5632 coord, &written) == 0
5633 || written == 0)
5634 written = 1;
5635
5636 g_coord.X += (SHORT) written;
5637 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005638
5639 while (g_coord.X > g_srScrollRegion.Right)
5640 {
5641 g_coord.X -= (SHORT) Columns;
5642 if (g_coord.Y < g_srScrollRegion.Bottom)
5643 g_coord.Y++;
5644 }
5645
5646 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5647
5648 return written;
5649}
5650
5651
5652/*
5653 * mch_write(): write the output buffer to the screen, translating ESC
5654 * sequences into calls to console output routines.
5655 */
5656 void
5657mch_write(
5658 char_u *s,
5659 int len)
5660{
5661 s[len] = NUL;
5662
5663 if (!term_console)
5664 {
5665 write(1, s, (unsigned)len);
5666 return;
5667 }
5668
5669 /* translate ESC | sequences into faked bios calls */
5670 while (len--)
5671 {
5672 /* optimization: use one single write_chars for runs of text,
5673 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005674 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005675
5676 if (p_wd)
5677 {
5678 WaitForChar(p_wd);
5679 if (prefix != 0)
5680 prefix = 1;
5681 }
5682
5683 if (prefix != 0)
5684 {
5685 DWORD nWritten;
5686
5687 nWritten = write_chars(s, prefix);
5688#ifdef MCH_WRITE_DUMP
5689 if (fdDump)
5690 {
5691 fputc('>', fdDump);
5692 fwrite(s, sizeof(char_u), nWritten, fdDump);
5693 fputs("<\n", fdDump);
5694 }
5695#endif
5696 len -= (nWritten - 1);
5697 s += nWritten;
5698 }
5699 else if (s[0] == '\n')
5700 {
5701 /* \n, newline: go to the beginning of the next line or scroll */
5702 if (g_coord.Y == g_srScrollRegion.Bottom)
5703 {
5704 scroll(1);
5705 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5706 }
5707 else
5708 {
5709 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5710 }
5711#ifdef MCH_WRITE_DUMP
5712 if (fdDump)
5713 fputs("\\n\n", fdDump);
5714#endif
5715 s++;
5716 }
5717 else if (s[0] == '\r')
5718 {
5719 /* \r, carriage return: go to beginning of line */
5720 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5721#ifdef MCH_WRITE_DUMP
5722 if (fdDump)
5723 fputs("\\r\n", fdDump);
5724#endif
5725 s++;
5726 }
5727 else if (s[0] == '\b')
5728 {
5729 /* \b, backspace: move cursor one position left */
5730 if (g_coord.X > g_srScrollRegion.Left)
5731 g_coord.X--;
5732 else if (g_coord.Y > g_srScrollRegion.Top)
5733 {
5734 g_coord.X = g_srScrollRegion.Right;
5735 g_coord.Y--;
5736 }
5737 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5738#ifdef MCH_WRITE_DUMP
5739 if (fdDump)
5740 fputs("\\b\n", fdDump);
5741#endif
5742 s++;
5743 }
5744 else if (s[0] == '\a')
5745 {
5746 /* \a, bell */
5747 MessageBeep(0xFFFFFFFF);
5748#ifdef MCH_WRITE_DUMP
5749 if (fdDump)
5750 fputs("\\a\n", fdDump);
5751#endif
5752 s++;
5753 }
5754 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5755 {
5756#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005757 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005758#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005759 char_u *p;
5760 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761
5762 switch (s[2])
5763 {
5764 /* one or two numeric arguments, separated by ';' */
5765
5766 case '0': case '1': case '2': case '3': case '4':
5767 case '5': case '6': case '7': case '8': case '9':
5768 p = s + 2;
5769 arg1 = getdigits(&p); /* no check for length! */
5770 if (p > s + len)
5771 break;
5772
5773 if (*p == ';')
5774 {
5775 ++p;
5776 arg2 = getdigits(&p); /* no check for length! */
5777 if (p > s + len)
5778 break;
5779
5780 if (*p == 'H')
5781 gotoxy(arg2, arg1);
5782 else if (*p == 'r')
5783 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5784 }
5785 else if (*p == 'A')
5786 {
5787 /* move cursor up arg1 lines in same column */
5788 gotoxy(g_coord.X + 1,
5789 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5790 }
5791 else if (*p == 'C')
5792 {
5793 /* move cursor right arg1 columns in same line */
5794 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5795 g_coord.Y + 1);
5796 }
5797 else if (*p == 'H')
5798 {
5799 gotoxy(1, arg1);
5800 }
5801 else if (*p == 'L')
5802 {
5803 insert_lines(arg1);
5804 }
5805 else if (*p == 'm')
5806 {
5807 if (arg1 == 0)
5808 normvideo();
5809 else
5810 textattr((WORD) arg1);
5811 }
5812 else if (*p == 'f')
5813 {
5814 textcolor((WORD) arg1);
5815 }
5816 else if (*p == 'b')
5817 {
5818 textbackground((WORD) arg1);
5819 }
5820 else if (*p == 'M')
5821 {
5822 delete_lines(arg1);
5823 }
5824
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005825 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005826 s = p + 1;
5827 break;
5828
5829
5830 /* Three-character escape sequences */
5831
5832 case 'A':
5833 /* move cursor up one line in same column */
5834 gotoxy(g_coord.X + 1,
5835 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5836 goto got3;
5837
5838 case 'B':
5839 visual_bell();
5840 goto got3;
5841
5842 case 'C':
5843 /* move cursor right one column in same line */
5844 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5845 g_coord.Y + 1);
5846 goto got3;
5847
5848 case 'E':
5849 termcap_mode_end();
5850 goto got3;
5851
5852 case 'F':
5853 standout();
5854 goto got3;
5855
5856 case 'f':
5857 standend();
5858 goto got3;
5859
5860 case 'H':
5861 gotoxy(1, 1);
5862 goto got3;
5863
5864 case 'j':
5865 clear_to_end_of_display();
5866 goto got3;
5867
5868 case 'J':
5869 clear_screen();
5870 goto got3;
5871
5872 case 'K':
5873 clear_to_end_of_line();
5874 goto got3;
5875
5876 case 'L':
5877 insert_lines(1);
5878 goto got3;
5879
5880 case 'M':
5881 delete_lines(1);
5882 goto got3;
5883
5884 case 'S':
5885 termcap_mode_start();
5886 goto got3;
5887
5888 case 'V':
5889 cursor_visible(TRUE);
5890 goto got3;
5891
5892 case 'v':
5893 cursor_visible(FALSE);
5894 goto got3;
5895
5896 got3:
5897 s += 3;
5898 len -= 2;
5899 }
5900
5901#ifdef MCH_WRITE_DUMP
5902 if (fdDump)
5903 {
5904 fputs("ESC | ", fdDump);
5905 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5906 fputc('\n', fdDump);
5907 }
5908#endif
5909 }
5910 else
5911 {
5912 /* Write a single character */
5913 DWORD nWritten;
5914
5915 nWritten = write_chars(s, 1);
5916#ifdef MCH_WRITE_DUMP
5917 if (fdDump)
5918 {
5919 fputc('>', fdDump);
5920 fwrite(s, sizeof(char_u), nWritten, fdDump);
5921 fputs("<\n", fdDump);
5922 }
5923#endif
5924
5925 len -= (nWritten - 1);
5926 s += nWritten;
5927 }
5928 }
5929
5930#ifdef MCH_WRITE_DUMP
5931 if (fdDump)
5932 fflush(fdDump);
5933#endif
5934}
5935
5936#endif /* FEAT_GUI_W32 */
5937
5938
5939/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01005940 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005942/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943 void
5944mch_delay(
5945 long msec,
5946 int ignoreinput)
5947{
5948#ifdef FEAT_GUI_W32
5949 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005950#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005952# ifdef FEAT_MZSCHEME
5953 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5954 {
5955 int towait = p_mzq;
5956
5957 /* if msec is large enough, wait by portions in p_mzq */
5958 while (msec > 0)
5959 {
5960 mzvim_check_threads();
5961 if (msec < towait)
5962 towait = msec;
5963 Sleep(towait);
5964 msec -= towait;
5965 }
5966 }
5967 else
5968# endif
5969 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005970 else
5971 WaitForChar(msec);
5972#endif
5973}
5974
5975
5976/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01005977 * This version of remove is not scared by a readonly (backup) file.
5978 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005979 * Return 0 for success, -1 for failure.
5980 */
5981 int
5982mch_remove(char_u *name)
5983{
5984#ifdef FEAT_MBYTE
5985 WCHAR *wn = NULL;
5986 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005987#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005988
Bram Moolenaar203258c2016-01-17 22:15:16 +01005989 /*
5990 * On Windows, deleting a directory's symbolic link is done by
5991 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
5992 */
5993 if (mch_isdir(name) && mch_is_symbolic_link(name))
5994 return mch_rmdir(name);
5995
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005996 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5997
5998#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005999 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6000 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006001 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002 if (wn != NULL)
6003 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004 n = DeleteFileW(wn) ? 0 : -1;
6005 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006006 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006007 }
6008 }
6009#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006010 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006011}
6012
6013
6014/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006015 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006016 */
6017 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006018mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006019{
6020#ifndef FEAT_GUI_W32 /* never used */
6021 if (g_fCtrlCPressed || g_fCBrkPressed)
6022 {
6023 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6024 got_int = TRUE;
6025 }
6026#endif
6027}
6028
Bram Moolenaaree273972016-01-02 21:11:51 +01006029/* physical RAM to leave for the OS */
6030#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006031
6032/*
6033 * How much main memory in KiB that can be used by VIM.
6034 */
6035/*ARGSUSED*/
6036 long_u
6037mch_total_mem(int special)
6038{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006039 MEMORYSTATUSEX ms;
6040
Bram Moolenaaree273972016-01-02 21:11:51 +01006041 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006042 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6043 * what fits in 32 bits. But it's not always available. */
6044 ms.dwLength = sizeof(MEMORYSTATUSEX);
6045 GlobalMemoryStatusEx(&ms);
6046 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006047 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006048 /* Process address space fits in physical RAM, use all of it. */
6049 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006050 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006051 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006052 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006053 /* Catch old NT box or perverse hardware setup. */
6054 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006055 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006056 /* Use physical RAM less reserve for OS + data. */
6057 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006058}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006059
Bram Moolenaar071d4272004-06-13 20:20:40 +00006060#ifdef FEAT_MBYTE
6061/*
6062 * Same code as below, but with wide functions and no comments.
6063 * Return 0 for success, non-zero for failure.
6064 */
6065 int
6066mch_wrename(WCHAR *wold, WCHAR *wnew)
6067{
6068 WCHAR *p;
6069 int i;
6070 WCHAR szTempFile[_MAX_PATH + 1];
6071 WCHAR szNewPath[_MAX_PATH + 1];
6072 HANDLE hf;
6073
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006074 p = wold;
6075 for (i = 0; wold[i] != NUL; ++i)
6076 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6077 && wold[i + 1] != 0)
6078 p = wold + i + 1;
6079 if ((int)(wold + i - p) < 8 || p[6] != '~')
6080 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081
6082 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6083 return -1;
6084 *p = NUL;
6085
6086 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6087 return -2;
6088
6089 if (!DeleteFileW(szTempFile))
6090 return -3;
6091
6092 if (!MoveFileW(wold, szTempFile))
6093 return -4;
6094
6095 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6096 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6097 return -5;
6098 if (!CloseHandle(hf))
6099 return -6;
6100
6101 if (!MoveFileW(szTempFile, wnew))
6102 {
6103 (void)MoveFileW(szTempFile, wold);
6104 return -7;
6105 }
6106
6107 DeleteFileW(szTempFile);
6108
6109 if (!DeleteFileW(wold))
6110 return -8;
6111
6112 return 0;
6113}
6114#endif
6115
6116
6117/*
6118 * mch_rename() works around a bug in rename (aka MoveFile) in
6119 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6120 * file whose short file name is "FOO.BAR" (its long file name will
6121 * be correct: "foo.bar~"). Because a file can be accessed by
6122 * either its SFN or its LFN, "foo.bar" has effectively been
6123 * renamed to "foo.bar", which is not at all what was wanted. This
6124 * seems to happen only when renaming files with three-character
6125 * extensions by appending a suffix that does not include ".".
6126 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6127 *
6128 * There is another problem, which isn't really a bug but isn't right either:
6129 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6130 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6131 * service pack 6. Doesn't seem to happen on Windows 98.
6132 *
6133 * Like rename(), returns 0 upon success, non-zero upon failure.
6134 * Should probably set errno appropriately when errors occur.
6135 */
6136 int
6137mch_rename(
6138 const char *pszOldFile,
6139 const char *pszNewFile)
6140{
6141 char szTempFile[_MAX_PATH+1];
6142 char szNewPath[_MAX_PATH+1];
6143 char *pszFilePart;
6144 HANDLE hf;
6145#ifdef FEAT_MBYTE
6146 WCHAR *wold = NULL;
6147 WCHAR *wnew = NULL;
6148 int retval = -1;
6149
6150 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6151 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006152 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6153 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154 if (wold != NULL && wnew != NULL)
6155 retval = mch_wrename(wold, wnew);
6156 vim_free(wold);
6157 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006158 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006159 }
6160#endif
6161
6162 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006163 * No need to play tricks unless the file name contains a "~" as the
6164 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006166 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6167 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6168 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169
6170 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6171 * a directory, no error is returned and pszFilePart will be NULL. */
6172 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6173 || pszFilePart == NULL)
6174 return -1;
6175 *pszFilePart = NUL;
6176
6177 /* Get (and create) a unique temporary file name in directory of new file */
6178 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6179 return -2;
6180
6181 /* blow the temp file away */
6182 if (!DeleteFile(szTempFile))
6183 return -3;
6184
6185 /* rename old file to the temp file */
6186 if (!MoveFile(pszOldFile, szTempFile))
6187 return -4;
6188
6189 /* now create an empty file called pszOldFile; this prevents the operating
6190 * system using pszOldFile as an alias (SFN) if we're renaming within the
6191 * same directory. For example, we're editing a file called
6192 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6193 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6194 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006195 * cause all sorts of problems later in buf_write(). So, we create an
6196 * empty file called filena~1.txt and the system will have to find some
6197 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006198 */
6199 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6200 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6201 return -5;
6202 if (!CloseHandle(hf))
6203 return -6;
6204
6205 /* rename the temp file to the new file */
6206 if (!MoveFile(szTempFile, pszNewFile))
6207 {
6208 /* Renaming failed. Rename the file back to its old name, so that it
6209 * looks like nothing happened. */
6210 (void)MoveFile(szTempFile, pszOldFile);
6211
6212 return -7;
6213 }
6214
6215 /* Seems to be left around on Novell filesystems */
6216 DeleteFile(szTempFile);
6217
6218 /* finally, remove the empty old file */
6219 if (!DeleteFile(pszOldFile))
6220 return -8;
6221
6222 return 0; /* success */
6223}
6224
6225/*
6226 * Get the default shell for the current hardware platform
6227 */
6228 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006229default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006230{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006231 PlatformId();
6232
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006233 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006234}
6235
6236/*
6237 * mch_access() extends access() to do more detailed check on network drives.
6238 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6239 */
6240 int
6241mch_access(char *n, int p)
6242{
6243 HANDLE hFile;
6244 DWORD am;
6245 int retval = -1; /* default: fail */
6246#ifdef FEAT_MBYTE
6247 WCHAR *wn = NULL;
6248
6249 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006250 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251#endif
6252
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006253 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 {
6255 char TempName[_MAX_PATH + 16] = "";
6256#ifdef FEAT_MBYTE
6257 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6258#endif
6259
6260 if (p & R_OK)
6261 {
6262 /* Read check is performed by seeing if we can do a find file on
6263 * the directory for any file. */
6264#ifdef FEAT_MBYTE
6265 if (wn != NULL)
6266 {
6267 int i;
6268 WIN32_FIND_DATAW d;
6269
6270 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6271 TempNameW[i] = wn[i];
6272 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6273 TempNameW[i++] = '\\';
6274 TempNameW[i++] = '*';
6275 TempNameW[i++] = 0;
6276
6277 hFile = FindFirstFileW(TempNameW, &d);
6278 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006279 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006280 else
6281 (void)FindClose(hFile);
6282 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006283 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284#endif
6285 {
6286 char *pch;
6287 WIN32_FIND_DATA d;
6288
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006289 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006290 pch = TempName + STRLEN(TempName) - 1;
6291 if (*pch != '\\' && *pch != '/')
6292 *++pch = '\\';
6293 *++pch = '*';
6294 *++pch = NUL;
6295
6296 hFile = FindFirstFile(TempName, &d);
6297 if (hFile == INVALID_HANDLE_VALUE)
6298 goto getout;
6299 (void)FindClose(hFile);
6300 }
6301 }
6302
6303 if (p & W_OK)
6304 {
6305 /* Trying to create a temporary file in the directory should catch
6306 * directories on read-only network shares. However, in
6307 * directories whose ACL allows writes but denies deletes will end
6308 * up keeping the temporary file :-(. */
6309#ifdef FEAT_MBYTE
6310 if (wn != NULL)
6311 {
6312 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006313 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006314 else
6315 DeleteFileW(TempNameW);
6316 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006317 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318#endif
6319 {
6320 if (!GetTempFileName(n, "VIM", 0, TempName))
6321 goto getout;
6322 mch_remove((char_u *)TempName);
6323 }
6324 }
6325 }
6326 else
6327 {
6328 /* Trying to open the file for the required access does ACL, read-only
6329 * network share, and file attribute checks. */
6330 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6331 | ((p & R_OK) ? GENERIC_READ : 0);
6332#ifdef FEAT_MBYTE
6333 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006335 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006336#endif
6337 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6338 if (hFile == INVALID_HANDLE_VALUE)
6339 goto getout;
6340 CloseHandle(hFile);
6341 }
6342
6343 retval = 0; /* success */
6344getout:
6345#ifdef FEAT_MBYTE
6346 vim_free(wn);
6347#endif
6348 return retval;
6349}
6350
6351#if defined(FEAT_MBYTE) || defined(PROTO)
6352/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006353 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 */
6355 int
6356mch_open(char *name, int flags, int mode)
6357{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006358 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6359# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006360 WCHAR *wn;
6361 int f;
6362
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006363 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006365 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006366 if (wn != NULL)
6367 {
6368 f = _wopen(wn, flags, mode);
6369 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006370 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006371 }
6372 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006373# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006374
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006375 /* open() can open a file which name is longer than _MAX_PATH bytes
6376 * and shorter than _MAX_PATH characters successfully, but sometimes it
6377 * causes unexpected error in another part. We make it an error explicitly
6378 * here. */
6379 if (strlen(name) >= _MAX_PATH)
6380 return -1;
6381
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382 return open(name, flags, mode);
6383}
6384
6385/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006386 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006387 */
6388 FILE *
6389mch_fopen(char *name, char *mode)
6390{
6391 WCHAR *wn, *wm;
6392 FILE *f = NULL;
6393
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006394 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006396# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006397 /* Work around an annoying assertion in the Microsoft debug CRT
6398 * when mode's text/binary setting doesn't match _get_fmode(). */
6399 char newMode = mode[strlen(mode) - 1];
6400 int oldMode = 0;
6401
6402 _get_fmode(&oldMode);
6403 if (newMode == 't')
6404 _set_fmode(_O_TEXT);
6405 else if (newMode == 'b')
6406 _set_fmode(_O_BINARY);
6407# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006408 wn = enc_to_utf16((char_u *)name, NULL);
6409 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006410 if (wn != NULL && wm != NULL)
6411 f = _wfopen(wn, wm);
6412 vim_free(wn);
6413 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006414
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006415# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006416 _set_fmode(oldMode);
6417# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006418 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006419 }
6420
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006421 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6422 * and shorter than _MAX_PATH characters successfully, but sometimes it
6423 * causes unexpected error in another part. We make it an error explicitly
6424 * here. */
6425 if (strlen(name) >= _MAX_PATH)
6426 return NULL;
6427
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428 return fopen(name, mode);
6429}
6430#endif
6431
6432#ifdef FEAT_MBYTE
6433/*
6434 * SUB STREAM (aka info stream) handling:
6435 *
6436 * NTFS can have sub streams for each file. Normal contents of file is
6437 * stored in the main stream, and extra contents (author information and
6438 * title and so on) can be stored in sub stream. After Windows 2000, user
6439 * can access and store those informations in sub streams via explorer's
6440 * property menuitem in right click menu. Those informations in sub streams
6441 * were lost when copying only the main stream. So we have to copy sub
6442 * streams.
6443 *
6444 * Incomplete explanation:
6445 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6446 * More useful info and an example:
6447 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6448 */
6449
6450/*
6451 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6452 * and write to stream "substream" of file "to".
6453 * Errors are ignored.
6454 */
6455 static void
6456copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6457{
6458 HANDLE hTo;
6459 WCHAR *to_name;
6460
6461 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6462 wcscpy(to_name, to);
6463 wcscat(to_name, substream);
6464
6465 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6466 FILE_ATTRIBUTE_NORMAL, NULL);
6467 if (hTo != INVALID_HANDLE_VALUE)
6468 {
6469 long done;
6470 DWORD todo;
6471 DWORD readcnt, written;
6472 char buf[4096];
6473
6474 /* Copy block of bytes at a time. Abort when something goes wrong. */
6475 for (done = 0; done < len; done += written)
6476 {
6477 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006478 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6479 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6481 FALSE, FALSE, context)
6482 || readcnt != todo
6483 || !WriteFile(hTo, buf, todo, &written, NULL)
6484 || written != todo)
6485 break;
6486 }
6487 CloseHandle(hTo);
6488 }
6489
6490 free(to_name);
6491}
6492
6493/*
6494 * Copy info streams from file "from" to file "to".
6495 */
6496 static void
6497copy_infostreams(char_u *from, char_u *to)
6498{
6499 WCHAR *fromw;
6500 WCHAR *tow;
6501 HANDLE sh;
6502 WIN32_STREAM_ID sid;
6503 int headersize;
6504 WCHAR streamname[_MAX_PATH];
6505 DWORD readcount;
6506 void *context = NULL;
6507 DWORD lo, hi;
6508 int len;
6509
6510 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006511 fromw = enc_to_utf16(from, NULL);
6512 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 if (fromw != NULL && tow != NULL)
6514 {
6515 /* Open the file for reading. */
6516 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6517 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6518 if (sh != INVALID_HANDLE_VALUE)
6519 {
6520 /* Use BackupRead() to find the info streams. Repeat until we
6521 * have done them all.*/
6522 for (;;)
6523 {
6524 /* Get the header to find the length of the stream name. If
6525 * the "readcount" is zero we have done all info streams. */
6526 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006527 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006528 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6529 &readcount, FALSE, FALSE, &context)
6530 || readcount == 0)
6531 break;
6532
6533 /* We only deal with streams that have a name. The normal
6534 * file data appears to be without a name, even though docs
6535 * suggest it is called "::$DATA". */
6536 if (sid.dwStreamNameSize > 0)
6537 {
6538 /* Read the stream name. */
6539 if (!BackupRead(sh, (LPBYTE)streamname,
6540 sid.dwStreamNameSize,
6541 &readcount, FALSE, FALSE, &context))
6542 break;
6543
6544 /* Copy an info stream with a name ":anything:$DATA".
6545 * Skip "::$DATA", it has no stream name (examples suggest
6546 * it might be used for the normal file contents).
6547 * Note that BackupRead() counts bytes, but the name is in
6548 * wide characters. */
6549 len = readcount / sizeof(WCHAR);
6550 streamname[len] = 0;
6551 if (len > 7 && wcsicmp(streamname + len - 6,
6552 L":$DATA") == 0)
6553 {
6554 streamname[len - 6] = 0;
6555 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006556 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006557 }
6558 }
6559
6560 /* Advance to the next stream. We might try seeking too far,
6561 * but BackupSeek() doesn't skip over stream borders, thus
6562 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006563 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006564 &lo, &hi, &context);
6565 }
6566
6567 /* Clear the context. */
6568 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6569
6570 CloseHandle(sh);
6571 }
6572 }
6573 vim_free(fromw);
6574 vim_free(tow);
6575}
6576#endif
6577
6578/*
6579 * Copy file attributes from file "from" to file "to".
6580 * For Windows NT and later we copy info streams.
6581 * Always returns zero, errors are ignored.
6582 */
6583 int
6584mch_copy_file_attribute(char_u *from, char_u *to)
6585{
6586#ifdef FEAT_MBYTE
6587 /* File streams only work on Windows NT and later. */
6588 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006589 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006590#endif
6591 return 0;
6592}
6593
6594#if defined(MYRESETSTKOFLW) || defined(PROTO)
6595/*
6596 * Recreate a destroyed stack guard page in win32.
6597 * Written by Benjamin Peterson.
6598 */
6599
6600/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006601#define MIN_STACK_WINNT 2
6602
6603/*
6604 * This function does the same thing as _resetstkoflw(), which is only
6605 * available in DevStudio .net and later.
6606 * Returns 0 for failure, 1 for success.
6607 */
6608 int
6609myresetstkoflw(void)
6610{
6611 BYTE *pStackPtr;
6612 BYTE *pGuardPage;
6613 BYTE *pStackBase;
6614 BYTE *pLowestPossiblePage;
6615 MEMORY_BASIC_INFORMATION mbi;
6616 SYSTEM_INFO si;
6617 DWORD nPageSize;
6618 DWORD dummy;
6619
Bram Moolenaar071d4272004-06-13 20:20:40 +00006620 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006621
6622 /* We need to know the system page size. */
6623 GetSystemInfo(&si);
6624 nPageSize = si.dwPageSize;
6625
6626 /* ...and the current stack pointer */
6627 pStackPtr = (BYTE*)_alloca(1);
6628
6629 /* ...and the base of the stack. */
6630 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6631 return 0;
6632 pStackBase = (BYTE*)mbi.AllocationBase;
6633
6634 /* ...and the page thats min_stack_req pages away from stack base; this is
6635 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006636 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006637
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006639 /* We want the first committed page in the stack Start at the stack
6640 * base and move forward through memory until we find a committed block.
6641 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006642 BYTE *pBlock = pStackBase;
6643
Bram Moolenaara466c992005-07-09 21:03:22 +00006644 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006645 {
6646 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6647 return 0;
6648
6649 pBlock += mbi.RegionSize;
6650
6651 if (mbi.State & MEM_COMMIT)
6652 break;
6653 }
6654
6655 /* mbi now describes the first committed block in the stack. */
6656 if (mbi.Protect & PAGE_GUARD)
6657 return 1;
6658
6659 /* decide where the guard page should start */
6660 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6661 pGuardPage = pLowestPossiblePage;
6662 else
6663 pGuardPage = (BYTE*)mbi.BaseAddress;
6664
6665 /* allocate the guard page */
6666 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6667 return 0;
6668
6669 /* apply the guard attribute to the page */
6670 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6671 &dummy))
6672 return 0;
6673 }
6674
6675 return 1;
6676}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006677#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006678
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006679
6680#if defined(FEAT_MBYTE) || defined(PROTO)
6681/*
6682 * The command line arguments in UCS2
6683 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006684static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006685static LPWSTR *ArglistW = NULL;
6686static int global_argc = 0;
6687static char **global_argv;
6688
6689static int used_file_argc = 0; /* last argument in global_argv[] used
6690 for the argument list. */
6691static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6692 command line arguments added to
6693 the argument list */
6694static int used_file_count = 0; /* nr of entries in used_file_indexes */
6695static int used_file_literal = FALSE; /* take file names literally */
6696static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006697static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006698static int used_alist_count = 0;
6699
6700
6701/*
6702 * Get the command line arguments. Unicode version.
6703 * Returns argc. Zero when something fails.
6704 */
6705 int
6706get_cmd_argsW(char ***argvp)
6707{
6708 char **argv = NULL;
6709 int argc = 0;
6710 int i;
6711
Bram Moolenaar14993322014-09-09 12:25:33 +02006712 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006713 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6714 if (ArglistW != NULL)
6715 {
6716 argv = malloc((nArgsW + 1) * sizeof(char *));
6717 if (argv != NULL)
6718 {
6719 argc = nArgsW;
6720 argv[argc] = NULL;
6721 for (i = 0; i < argc; ++i)
6722 {
6723 int len;
6724
6725 /* Convert each Unicode argument to the current codepage. */
6726 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006727 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006728 (LPSTR *)&argv[i], &len, 0, 0);
6729 if (argv[i] == NULL)
6730 {
6731 /* Out of memory, clear everything. */
6732 while (i > 0)
6733 free(argv[--i]);
6734 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006735 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006736 argc = 0;
6737 }
6738 }
6739 }
6740 }
6741
6742 global_argc = argc;
6743 global_argv = argv;
6744 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006745 {
6746 if (used_file_indexes != NULL)
6747 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006748 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006749 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006750
6751 if (argvp != NULL)
6752 *argvp = argv;
6753 return argc;
6754}
6755
6756 void
6757free_cmd_argsW(void)
6758{
6759 if (ArglistW != NULL)
6760 {
6761 GlobalFree(ArglistW);
6762 ArglistW = NULL;
6763 }
6764}
6765
6766/*
6767 * Remember "name" is an argument that was added to the argument list.
6768 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6769 * is called.
6770 */
6771 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006772used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006773{
6774 int i;
6775
6776 if (used_file_indexes == NULL)
6777 return;
6778 for (i = used_file_argc + 1; i < global_argc; ++i)
6779 if (STRCMP(global_argv[i], name) == 0)
6780 {
6781 used_file_argc = i;
6782 used_file_indexes[used_file_count++] = i;
6783 break;
6784 }
6785 used_file_literal = literal;
6786 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006787 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006788}
6789
6790/*
6791 * Remember the length of the argument list as it was. If it changes then we
6792 * leave it alone when 'encoding' is set.
6793 */
6794 void
6795set_alist_count(void)
6796{
6797 used_alist_count = GARGCOUNT;
6798}
6799
6800/*
6801 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6802 * has been changed while starting up. Use the UCS-2 command line arguments
6803 * and convert them to 'encoding'.
6804 */
6805 void
6806fix_arg_enc(void)
6807{
6808 int i;
6809 int idx;
6810 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006811 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006812
6813 /* Safety checks:
6814 * - if argument count differs between the wide and non-wide argument
6815 * list, something must be wrong.
6816 * - the file name arguments must have been located.
6817 * - the length of the argument list wasn't changed by the user.
6818 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006819 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006820 || ArglistW == NULL
6821 || used_file_indexes == NULL
6822 || used_file_count == 0
6823 || used_alist_count != GARGCOUNT)
6824 return;
6825
Bram Moolenaar86b68352004-12-27 21:59:20 +00006826 /* Remember the buffer numbers for the arguments. */
6827 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6828 if (fnum_list == NULL)
6829 return; /* out of memory */
6830 for (i = 0; i < GARGCOUNT; ++i)
6831 fnum_list[i] = GARGLIST[i].ae_fnum;
6832
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006833 /* Clear the argument list. Make room for the new arguments. */
6834 alist_clear(&global_alist);
6835 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006836 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006837
6838 for (i = 0; i < used_file_count; ++i)
6839 {
6840 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006841 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006842 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006843 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006844#ifdef FEAT_DIFF
6845 /* When using diff mode may need to concatenate file name to
6846 * directory name. Just like it's done in main(). */
6847 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6848 && !mch_isdir(alist_name(&GARGLIST[0])))
6849 {
6850 char_u *r;
6851
6852 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6853 if (r != NULL)
6854 {
6855 vim_free(str);
6856 str = r;
6857 }
6858 }
6859#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006860 /* Re-use the old buffer by renaming it. When not using literal
6861 * names it's done by alist_expand() below. */
6862 if (used_file_literal)
6863 buf_set_name(fnum_list[i], str);
6864
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006865 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006866 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006867 }
6868
6869 if (!used_file_literal)
6870 {
6871 /* Now expand wildcards in the arguments. */
6872 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6873 * filename characters but are excluded from 'isfname' to make
6874 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6875 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006876 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006877 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6878 }
6879
6880 /* If wildcard expansion failed, we are editing the first file of the
6881 * arglist and there is no file name: Edit the first argument now. */
6882 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6883 {
6884 do_cmdline_cmd((char_u *)":rewind");
6885 if (GARGCOUNT == 1 && used_file_full_path)
6886 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6887 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006888
6889 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006890}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006891#endif