blob: 9ff2f7ee40a61ab16dcf5dc464e293276b03f9d8 [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
53#ifdef __MINGW32__
54# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
55# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
56# endif
57# ifndef RIGHTMOST_BUTTON_PRESSED
58# define RIGHTMOST_BUTTON_PRESSED 0x0002
59# endif
60# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
61# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
62# endif
63# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
64# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
65# endif
66# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
67# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
68# endif
69
70/*
71 * EventFlags
72 */
73# ifndef MOUSE_MOVED
74# define MOUSE_MOVED 0x0001
75# endif
76# ifndef DOUBLE_CLICK
77# define DOUBLE_CLICK 0x0002
78# endif
79#endif
80
81/* Record all output and all keyboard & mouse input */
82/* #define MCH_WRITE_DUMP */
83
84#ifdef MCH_WRITE_DUMP
85FILE* fdDump = NULL;
86#endif
87
88/*
89 * When generating prototypes for Win32 on Unix, these lines make the syntax
90 * errors disappear. They do not need to be correct.
91 */
92#ifdef PROTO
93#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000094typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000095typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000096typedef int ACCESS_MASK;
97typedef int BOOL;
98typedef int COLORREF;
99typedef int CONSOLE_CURSOR_INFO;
100typedef int COORD;
101typedef int DWORD;
102typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100103typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000104typedef int HDC;
105typedef int HFONT;
106typedef int HICON;
107typedef int HINSTANCE;
108typedef int HWND;
109typedef int INPUT_RECORD;
110typedef int KEY_EVENT_RECORD;
111typedef int LOGFONT;
112typedef int LPBOOL;
113typedef int LPCTSTR;
114typedef int LPDWORD;
115typedef int LPSTR;
116typedef int LPTSTR;
117typedef int LPVOID;
118typedef int MOUSE_EVENT_RECORD;
119typedef int PACL;
120typedef int PDWORD;
121typedef int PHANDLE;
122typedef int PRINTDLG;
123typedef int PSECURITY_DESCRIPTOR;
124typedef int PSID;
125typedef int SECURITY_INFORMATION;
126typedef int SHORT;
127typedef int SMALL_RECT;
128typedef int TEXTMETRIC;
129typedef int TOKEN_INFORMATION_CLASS;
130typedef int TRUSTEE;
131typedef int WORD;
132typedef int WCHAR;
133typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100134typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200135typedef int SE_OBJECT_TYPE;
136typedef int PSNSECINFO;
137typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100138typedef int STARTUPINFO;
139typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200140typedef int LPSECURITY_ATTRIBUTES;
141# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000142#endif
143
Bram Moolenaar071d4272004-06-13 20:20:40 +0000144#if defined(__BORLANDC__)
145/* Strangely Borland uses a non-standard name. */
146# define wcsicmp(a, b) wcscmpi((a), (b))
147#endif
148
149#ifndef FEAT_GUI_W32
150/* Win32 Console handles for input and output */
151static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
152static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
153
154/* Win32 Screen buffer,coordinate,console I/O information */
155static SMALL_RECT g_srScrollRegion;
156static COORD g_coord; /* 0-based, but external coords are 1-based */
157
158/* The attribute of the screen when the editor was started */
159static WORD g_attrDefault = 7; /* lightgray text on black background */
160static WORD g_attrCurrent;
161
162static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
163static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
164static int g_fForceExit = FALSE; /* set when forcefully exiting */
165
166static void termcap_mode_start(void);
167static void termcap_mode_end(void);
168static void clear_chars(COORD coord, DWORD n);
169static void clear_screen(void);
170static void clear_to_end_of_display(void);
171static void clear_to_end_of_line(void);
172static void scroll(unsigned cLines);
173static void set_scroll_region(unsigned left, unsigned top,
174 unsigned right, unsigned bottom);
175static void insert_lines(unsigned cLines);
176static void delete_lines(unsigned cLines);
177static void gotoxy(unsigned x, unsigned y);
178static void normvideo(void);
179static void textattr(WORD wAttr);
180static void textcolor(WORD wAttr);
181static void textbackground(WORD wAttr);
182static void standout(void);
183static void standend(void);
184static void visual_bell(void);
185static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200186static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000187static void create_conin(void);
188static int s_cursor_visible = TRUE;
189static int did_create_conin = FALSE;
190#else
191static int s_dont_use_vimrun = TRUE;
192static int need_vimrun_warning = FALSE;
193static char *vimrun_path = "vimrun ";
194#endif
195
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200196static int win32_getattrs(char_u *name);
197static int win32_setattrs(char_u *name, int attrs);
198static int win32_set_archive(char_u *name);
199
Bram Moolenaar071d4272004-06-13 20:20:40 +0000200#ifndef FEAT_GUI_W32
201static int suppress_winsize = 1; /* don't fiddle with console */
202#endif
203
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200204static char_u *exe_path = NULL;
205
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100206static BOOL win8_or_later = FALSE;
207
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100208#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100209/*
210 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100211 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100212 */
213 static BOOL
214read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100215 HANDLE hInput,
216 INPUT_RECORD *lpBuffer,
217 DWORD nLength,
218 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100219{
220 enum
221 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100222 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100223 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100224 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100225 static DWORD s_dwIndex = 0;
226 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100227 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100228 int head;
229 int tail;
230 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100231
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200232 if (nLength == -2)
233 return (s_dwMax > 0) ? TRUE : FALSE;
234
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100235 if (!win8_or_later)
236 {
237 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200238 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
239 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100240 }
241
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100242 if (s_dwMax == 0)
243 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100244 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200245 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
246 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100247 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100248 s_dwIndex = 0;
249 s_dwMax = dwEvents;
250 if (dwEvents == 0)
251 {
252 *lpEvents = 0;
253 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100254 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100255
256 if (s_dwMax > 1)
257 {
258 head = 0;
259 tail = s_dwMax - 1;
260 while (head != tail)
261 {
262 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
263 && s_irCache[head + 1].EventType
264 == WINDOW_BUFFER_SIZE_EVENT)
265 {
266 /* Remove duplicate event to avoid flicker. */
267 for (i = head; i < tail; ++i)
268 s_irCache[i] = s_irCache[i + 1];
269 --tail;
270 continue;
271 }
272 head++;
273 }
274 s_dwMax = tail + 1;
275 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100276 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100277
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100278 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200279 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100281 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100282 return TRUE;
283}
284
285/*
286 * Version of PeekConsoleInput() that works with IME.
287 */
288 static BOOL
289peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100290 HANDLE hInput,
291 INPUT_RECORD *lpBuffer,
292 DWORD nLength,
293 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100294{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100296}
297
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100298# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200299 static DWORD
300msg_wait_for_multiple_objects(
301 DWORD nCount,
302 LPHANDLE pHandles,
303 BOOL fWaitAll,
304 DWORD dwMilliseconds,
305 DWORD dwWakeMask)
306{
307 if (read_console_input(NULL, NULL, -2, NULL))
308 return WAIT_OBJECT_0;
309 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
310 dwMilliseconds, dwWakeMask);
311}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100312# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200313
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100314# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200315 static DWORD
316wait_for_single_object(
317 HANDLE hHandle,
318 DWORD dwMilliseconds)
319{
320 if (read_console_input(NULL, NULL, -2, NULL))
321 return WAIT_OBJECT_0;
322 return WaitForSingleObject(hHandle, dwMilliseconds);
323}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100324# endif
325#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200326
Bram Moolenaar071d4272004-06-13 20:20:40 +0000327 static void
328get_exe_name(void)
329{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100330 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
331 * as the maximum length that works (plus a NUL byte). */
332#define MAX_ENV_PATH_LEN 8192
333 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200334 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000335
336 if (exe_name == NULL)
337 {
338 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100339 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340 if (*temp != NUL)
341 exe_name = FullName_save((char_u *)temp, FALSE);
342 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000343
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200344 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000345 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200346 exe_path = vim_strnsave(exe_name,
347 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200348 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000349 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200350 /* Append our starting directory to $PATH, so that when doing
351 * "!xxd" it's found in our starting directory. Needed because
352 * SearchPath() also looks there. */
353 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100354 if (p == NULL
355 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200356 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100357 if (p == NULL || *p == NUL)
358 temp[0] = NUL;
359 else
360 {
361 STRCPY(temp, p);
362 STRCAT(temp, ";");
363 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200364 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100365 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200366 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000367 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000368 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000369}
370
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200371/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100372 * Unescape characters in "p" that appear in "escaped".
373 */
374 static void
375unescape_shellxquote(char_u *p, char_u *escaped)
376{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100377 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100378 int n;
379
380 while (*p != NUL)
381 {
382 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
383 mch_memmove(p, p + 1, l--);
384#ifdef FEAT_MBYTE
385 n = (*mb_ptr2len)(p);
386#else
387 n = 1;
388#endif
389 p += n;
390 l -= n;
391 }
392}
393
394/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200395 * Load library "name".
396 */
397 HINSTANCE
398vimLoadLib(char *name)
399{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200400 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200401
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200402 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
403 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200404 if (exe_path == NULL)
405 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200406 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200407 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200408 WCHAR old_dirw[MAXPATHL];
409
410 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
411 {
412 /* Change directory to where the executable is, both to make
413 * sure we find a .dll there and to avoid looking for a .dll
414 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100415 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200416 dll = LoadLibrary(name);
417 SetCurrentDirectoryW(old_dirw);
418 return dll;
419 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200420 }
421 return dll;
422}
423
Bram Moolenaar071d4272004-06-13 20:20:40 +0000424#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
425# ifndef GETTEXT_DLL
426# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100427# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200429/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000430static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200431static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000432static char *null_libintl_textdomain(const char *);
433static char *null_libintl_bindtextdomain(const char *, const char *);
434static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200436static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000437char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200438char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
439 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000440char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
441char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000443char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
444 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445
446 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100447dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000448{
449 int i;
450 static struct
451 {
452 char *name;
453 FARPROC *ptr;
454 } libintl_entry[] =
455 {
456 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200457 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
459 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
460 {NULL, NULL}
461 };
462
463 /* No need to initialize twice. */
464 if (hLibintlDLL)
465 return 1;
466 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100467 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100468#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100469 if (!hLibintlDLL)
470 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100471#endif
472 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000473 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200474 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200476 verbose_enter();
477 EMSG2(_(e_loadlib), GETTEXT_DLL);
478 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481 }
482 for (i = 0; libintl_entry[i].name != NULL
483 && libintl_entry[i].ptr != NULL; ++i)
484 {
485 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
486 libintl_entry[i].name)) == NULL)
487 {
488 dyn_libintl_end();
489 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000490 {
491 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000492 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000493 verbose_leave();
494 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495 return 0;
496 }
497 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000498
499 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000500 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000501 "bind_textdomain_codeset");
502 if (dyn_libintl_bind_textdomain_codeset == NULL)
503 dyn_libintl_bind_textdomain_codeset =
504 null_libintl_bind_textdomain_codeset;
505
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506 return 1;
507}
508
509 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100510dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511{
512 if (hLibintlDLL)
513 FreeLibrary(hLibintlDLL);
514 hLibintlDLL = NULL;
515 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200516 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000517 dyn_libintl_textdomain = null_libintl_textdomain;
518 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000519 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520}
521
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000522/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000524null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525{
526 return (char*)msgid;
527}
528
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000529/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000530 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200531null_libintl_ngettext(
532 const char *msgid,
533 const char *msgid_plural,
534 unsigned long n)
535{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200536 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200537}
538
539/*ARGSUSED*/
540 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000541null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542{
543 return NULL;
544}
545
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000546/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000547 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000548null_libintl_bind_textdomain_codeset(const char *domainname,
549 const char *codeset)
550{
551 return NULL;
552}
553
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000554/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000555 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000556null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000557{
558 return NULL;
559}
560
561#endif /* DYNAMIC_GETTEXT */
562
563/* This symbol is not defined in older versions of the SDK or Visual C++ */
564
565#ifndef VER_PLATFORM_WIN32_WINDOWS
566# define VER_PLATFORM_WIN32_WINDOWS 1
567#endif
568
569DWORD g_PlatformId;
570
571#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100572# ifndef PROTO
573# include <aclapi.h>
574# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200575# ifndef PROTECTED_DACL_SECURITY_INFORMATION
576# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
577# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000578#endif
579
Bram Moolenaar27515922013-06-29 15:36:26 +0200580#ifdef HAVE_ACL
581/*
582 * Enables or disables the specified privilege.
583 */
584 static BOOL
585win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
586{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100587 BOOL bResult;
588 LUID luid;
589 HANDLE hToken;
590 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200591
592 if (!OpenProcessToken(GetCurrentProcess(),
593 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
594 return FALSE;
595
596 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
597 {
598 CloseHandle(hToken);
599 return FALSE;
600 }
601
Bram Moolenaar45500912014-07-09 20:51:07 +0200602 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200603 tokenPrivileges.Privileges[0].Luid = luid;
604 tokenPrivileges.Privileges[0].Attributes = bEnable ?
605 SE_PRIVILEGE_ENABLED : 0;
606
607 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
608 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
609
610 CloseHandle(hToken);
611
612 return bResult && GetLastError() == ERROR_SUCCESS;
613}
614#endif
615
Bram Moolenaar071d4272004-06-13 20:20:40 +0000616/*
617 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
618 * VER_PLATFORM_WIN32_WINDOWS (Win95).
619 */
620 void
621PlatformId(void)
622{
623 static int done = FALSE;
624
625 if (!done)
626 {
627 OSVERSIONINFO ovi;
628
629 ovi.dwOSVersionInfoSize = sizeof(ovi);
630 GetVersionEx(&ovi);
631
632 g_PlatformId = ovi.dwPlatformId;
633
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100634 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
635 || ovi.dwMajorVersion > 6)
636 win8_or_later = TRUE;
637
Bram Moolenaar071d4272004-06-13 20:20:40 +0000638#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200639 /* Enable privilege for getting or setting SACLs. */
640 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641#endif
642 done = TRUE;
643 }
644}
645
Bram Moolenaar071d4272004-06-13 20:20:40 +0000646#ifndef FEAT_GUI_W32
647
648#define SHIFT (SHIFT_PRESSED)
649#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
650#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
651#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
652
653
654/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
655 * We map function keys to their ANSI terminal equivalents, as produced
656 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
657 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
658 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
659 * combinations of function/arrow/etc keys.
660 */
661
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000662static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000663{
664 WORD wVirtKey;
665 BOOL fAnsiKey;
666 int chAlone;
667 int chShift;
668 int chCtrl;
669 int chAlt;
670} VirtKeyMap[] =
671{
672
673/* Key ANSI alone shift ctrl alt */
674 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
675
676 { VK_F1, TRUE, ';', 'T', '^', 'h', },
677 { VK_F2, TRUE, '<', 'U', '_', 'i', },
678 { VK_F3, TRUE, '=', 'V', '`', 'j', },
679 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
680 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
681 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
682 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
683 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
684 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
685 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
686 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
687 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
688
689 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
690 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
691 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
692 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
693 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
694 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
695 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
696 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
697 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
698 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
699
700 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
701
702#if 0
703 /* Most people don't have F13-F20, but what the hell... */
704 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
705 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
706 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
707 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
708 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
709 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
710 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
711 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
712#endif
713 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
714 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
715 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
716 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
717
718 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
719 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
720 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
721 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
722 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
723 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
724 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
725 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
726 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
727 /* Sorry, out of number space! <negri>*/
728 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
729
730};
731
732
733#ifdef _MSC_VER
734// The ToAscii bug destroys several registers. Need to turn off optimization
735// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000736# pragma warning(push)
737# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738# pragma optimize("", off)
739#endif
740
741#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200742# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000743#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200744# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000745#endif
746
747/* The return code indicates key code size. */
748 static int
749#ifdef __BORLANDC__
750 __stdcall
751#endif
752win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000753 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754{
755 UINT uMods = pker->dwControlKeyState;
756 static int s_iIsDead = 0;
757 static WORD awAnsiCode[2];
758 static BYTE abKeystate[256];
759
760
761 if (s_iIsDead == 2)
762 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200763 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764 s_iIsDead = 0;
765 return 1;
766 }
767
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200768 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769 return 1;
770
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200771 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200774 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775
776 if (uMods & SHIFT_PRESSED)
777 abKeystate[VK_SHIFT] = 0x80;
778 if (uMods & CAPSLOCK_ON)
779 abKeystate[VK_CAPITAL] = 1;
780
781 if ((uMods & ALT_GR) == ALT_GR)
782 {
783 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
784 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
785 }
786
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200787 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
788 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789
790 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200791 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792
793 return s_iIsDead;
794}
795
796#ifdef _MSC_VER
797/* MUST switch optimization on again here, otherwise a call to
798 * decode_key_event() may crash (e.g. when hitting caps-lock) */
799# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000800# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000801
802# if (_MSC_VER < 1100)
803/* MUST turn off global optimisation for this next function, or
804 * pressing ctrl-minus in insert mode crashes Vim when built with
805 * VC4.1. -- negri. */
806# pragma optimize("g", off)
807# endif
808#endif
809
810static BOOL g_fJustGotFocus = FALSE;
811
812/*
813 * Decode a KEY_EVENT into one or two keystrokes
814 */
815 static BOOL
816decode_key_event(
817 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200818 WCHAR *pch,
819 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820 int *pmodifiers,
821 BOOL fDoPost)
822{
823 int i;
824 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
825
826 *pch = *pch2 = NUL;
827 g_fJustGotFocus = FALSE;
828
829 /* ignore key up events */
830 if (!pker->bKeyDown)
831 return FALSE;
832
833 /* ignore some keystrokes */
834 switch (pker->wVirtualKeyCode)
835 {
836 /* modifiers */
837 case VK_SHIFT:
838 case VK_CONTROL:
839 case VK_MENU: /* Alt key */
840 return FALSE;
841
842 default:
843 break;
844 }
845
846 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200847 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000848 {
849 /* Ctrl-6 is Ctrl-^ */
850 if (pker->wVirtualKeyCode == '6')
851 {
852 *pch = Ctrl_HAT;
853 return TRUE;
854 }
855 /* Ctrl-2 is Ctrl-@ */
856 else if (pker->wVirtualKeyCode == '2')
857 {
858 *pch = NUL;
859 return TRUE;
860 }
861 /* Ctrl-- is Ctrl-_ */
862 else if (pker->wVirtualKeyCode == 0xBD)
863 {
864 *pch = Ctrl__;
865 return TRUE;
866 }
867 }
868
869 /* Shift-TAB */
870 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
871 {
872 *pch = K_NUL;
873 *pch2 = '\017';
874 return TRUE;
875 }
876
877 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
878 {
879 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
880 {
881 if (nModifs == 0)
882 *pch = VirtKeyMap[i].chAlone;
883 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
884 *pch = VirtKeyMap[i].chShift;
885 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
886 *pch = VirtKeyMap[i].chCtrl;
887 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
888 *pch = VirtKeyMap[i].chAlt;
889
890 if (*pch != 0)
891 {
892 if (VirtKeyMap[i].fAnsiKey)
893 {
894 *pch2 = *pch;
895 *pch = K_NUL;
896 }
897
898 return TRUE;
899 }
900 }
901 }
902
903 i = win32_kbd_patch_key(pker);
904
905 if (i < 0)
906 *pch = NUL;
907 else
908 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200909 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910
911 if (pmodifiers != NULL)
912 {
913 /* Pass on the ALT key as a modifier, but only when not combined
914 * with CTRL (which is ALTGR). */
915 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
916 *pmodifiers |= MOD_MASK_ALT;
917
918 /* Pass on SHIFT only for special keys, because we don't know when
919 * it's already included with the character. */
920 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
921 *pmodifiers |= MOD_MASK_SHIFT;
922
923 /* Pass on CTRL only for non-special keys, because we don't know
924 * when it's already included with the character. And not when
925 * combined with ALT (which is ALTGR). */
926 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
927 && *pch >= 0x20 && *pch < 0x80)
928 *pmodifiers |= MOD_MASK_CTRL;
929 }
930 }
931
932 return (*pch != NUL);
933}
934
935#ifdef _MSC_VER
936# pragma optimize("", on)
937#endif
938
939#endif /* FEAT_GUI_W32 */
940
941
942#ifdef FEAT_MOUSE
943
944/*
945 * For the GUI the mouse handling is in gui_w32.c.
946 */
947# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000948/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000950mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000951{
952}
953# else
954static int g_fMouseAvail = FALSE; /* mouse present */
955static int g_fMouseActive = FALSE; /* mouse enabled */
956static int g_nMouseClick = -1; /* mouse status */
957static int g_xMouse; /* mouse x coordinate */
958static int g_yMouse; /* mouse y coordinate */
959
960/*
961 * Enable or disable mouse input
962 */
963 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000964mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000965{
966 DWORD cmodein;
967
968 if (!g_fMouseAvail)
969 return;
970
971 g_fMouseActive = on;
972 GetConsoleMode(g_hConIn, &cmodein);
973
974 if (g_fMouseActive)
975 cmodein |= ENABLE_MOUSE_INPUT;
976 else
977 cmodein &= ~ENABLE_MOUSE_INPUT;
978
979 SetConsoleMode(g_hConIn, cmodein);
980}
981
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982/*
983 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
984 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
985 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
986 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
987 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
988 * and we return the mouse position in g_xMouse and g_yMouse.
989 *
990 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
991 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
992 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
993 *
994 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
995 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
996 *
997 * Windows will send us MOUSE_MOVED notifications whenever the mouse
998 * moves, even if it stays within the same character cell. We ignore
999 * all MOUSE_MOVED messages if the position hasn't really changed, and
1000 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1001 * we're only interested in MOUSE_DRAG).
1002 *
1003 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1004 * 2-button mouses by pressing the left & right buttons simultaneously.
1005 * In practice, it's almost impossible to click both at the same time,
1006 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1007 * in such cases, if the user is clicking quickly.
1008 */
1009 static BOOL
1010decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001011 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001012{
1013 static int s_nOldButton = -1;
1014 static int s_nOldMouseClick = -1;
1015 static int s_xOldMouse = -1;
1016 static int s_yOldMouse = -1;
1017 static linenr_T s_old_topline = 0;
1018#ifdef FEAT_DIFF
1019 static int s_old_topfill = 0;
1020#endif
1021 static int s_cClicks = 1;
1022 static BOOL s_fReleased = TRUE;
1023 static DWORD s_dwLastClickTime = 0;
1024 static BOOL s_fNextIsMiddle = FALSE;
1025
1026 static DWORD cButtons = 0; /* number of buttons supported */
1027
1028 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1029 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1030 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1031 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1032
1033 int nButton;
1034
1035 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1036 cButtons = 2;
1037
1038 if (!g_fMouseAvail || !g_fMouseActive)
1039 {
1040 g_nMouseClick = -1;
1041 return FALSE;
1042 }
1043
1044 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1045 if (g_fJustGotFocus)
1046 {
1047 g_fJustGotFocus = FALSE;
1048 return FALSE;
1049 }
1050
1051 /* unprocessed mouse click? */
1052 if (g_nMouseClick != -1)
1053 return TRUE;
1054
1055 nButton = -1;
1056 g_xMouse = pmer->dwMousePosition.X;
1057 g_yMouse = pmer->dwMousePosition.Y;
1058
1059 if (pmer->dwEventFlags == MOUSE_MOVED)
1060 {
1061 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1062 * events even when the mouse moves only within a char cell.) */
1063 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1064 return FALSE;
1065 }
1066
1067 /* If no buttons are pressed... */
1068 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1069 {
1070 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1071 if (s_fReleased)
1072 return FALSE;
1073
1074 nButton = MOUSE_RELEASE;
1075 s_fReleased = TRUE;
1076 }
1077 else /* one or more buttons pressed */
1078 {
1079 /* on a 2-button mouse, hold down left and right buttons
1080 * simultaneously to get MIDDLE. */
1081
1082 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1083 {
1084 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1085
1086 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001087 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 if (dwLR == LEFT || dwLR == RIGHT)
1089 {
1090 for (;;)
1091 {
1092 /* wait a short time for next input event */
1093 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1094 != WAIT_OBJECT_0)
1095 break;
1096 else
1097 {
1098 DWORD cRecords = 0;
1099 INPUT_RECORD ir;
1100 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1101
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001102 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103
1104 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1105 || !(pmer2->dwButtonState & LEFT_RIGHT))
1106 break;
1107 else
1108 {
1109 if (pmer2->dwEventFlags != MOUSE_MOVED)
1110 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001111 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112
1113 return decode_mouse_event(pmer2);
1114 }
1115 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1116 s_yOldMouse == pmer2->dwMousePosition.Y)
1117 {
1118 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001119 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001120
1121 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001122 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123
1124 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1125 break;
1126 }
1127 else
1128 break;
1129 }
1130 }
1131 }
1132 }
1133 }
1134
1135 if (s_fNextIsMiddle)
1136 {
1137 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1138 ? MOUSE_DRAG : MOUSE_MIDDLE;
1139 s_fNextIsMiddle = FALSE;
1140 }
1141 else if (cButtons == 2 &&
1142 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1143 {
1144 nButton = MOUSE_MIDDLE;
1145
1146 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1147 {
1148 s_fNextIsMiddle = TRUE;
1149 nButton = MOUSE_RELEASE;
1150 }
1151 }
1152 else if ((pmer->dwButtonState & LEFT) == LEFT)
1153 nButton = MOUSE_LEFT;
1154 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1155 nButton = MOUSE_MIDDLE;
1156 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1157 nButton = MOUSE_RIGHT;
1158
1159 if (! s_fReleased && ! s_fNextIsMiddle
1160 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1161 return FALSE;
1162
1163 s_fReleased = s_fNextIsMiddle;
1164 }
1165
1166 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1167 {
1168 /* button pressed or released, without mouse moving */
1169 if (nButton != -1 && nButton != MOUSE_RELEASE)
1170 {
1171 DWORD dwCurrentTime = GetTickCount();
1172
1173 if (s_xOldMouse != g_xMouse
1174 || s_yOldMouse != g_yMouse
1175 || s_nOldButton != nButton
1176 || s_old_topline != curwin->w_topline
1177#ifdef FEAT_DIFF
1178 || s_old_topfill != curwin->w_topfill
1179#endif
1180 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1181 {
1182 s_cClicks = 1;
1183 }
1184 else if (++s_cClicks > 4)
1185 {
1186 s_cClicks = 1;
1187 }
1188
1189 s_dwLastClickTime = dwCurrentTime;
1190 }
1191 }
1192 else if (pmer->dwEventFlags == MOUSE_MOVED)
1193 {
1194 if (nButton != -1 && nButton != MOUSE_RELEASE)
1195 nButton = MOUSE_DRAG;
1196
1197 s_cClicks = 1;
1198 }
1199
1200 if (nButton == -1)
1201 return FALSE;
1202
1203 if (nButton != MOUSE_RELEASE)
1204 s_nOldButton = nButton;
1205
1206 g_nMouseClick = nButton;
1207
1208 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1209 g_nMouseClick |= MOUSE_SHIFT;
1210 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1211 g_nMouseClick |= MOUSE_CTRL;
1212 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1213 g_nMouseClick |= MOUSE_ALT;
1214
1215 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1216 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1217
1218 /* only pass on interesting (i.e., different) mouse events */
1219 if (s_xOldMouse == g_xMouse
1220 && s_yOldMouse == g_yMouse
1221 && s_nOldMouseClick == g_nMouseClick)
1222 {
1223 g_nMouseClick = -1;
1224 return FALSE;
1225 }
1226
1227 s_xOldMouse = g_xMouse;
1228 s_yOldMouse = g_yMouse;
1229 s_old_topline = curwin->w_topline;
1230#ifdef FEAT_DIFF
1231 s_old_topfill = curwin->w_topfill;
1232#endif
1233 s_nOldMouseClick = g_nMouseClick;
1234
1235 return TRUE;
1236}
1237
1238# endif /* FEAT_GUI_W32 */
1239#endif /* FEAT_MOUSE */
1240
1241
1242#ifdef MCH_CURSOR_SHAPE
1243/*
1244 * Set the shape of the cursor.
1245 * 'thickness' can be from 1 (thin) to 99 (block)
1246 */
1247 static void
1248mch_set_cursor_shape(int thickness)
1249{
1250 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1251 ConsoleCursorInfo.dwSize = thickness;
1252 ConsoleCursorInfo.bVisible = s_cursor_visible;
1253
1254 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1255 if (s_cursor_visible)
1256 SetConsoleCursorPosition(g_hConOut, g_coord);
1257}
1258
1259 void
1260mch_update_cursor(void)
1261{
1262 int idx;
1263 int thickness;
1264
1265 /*
1266 * How the cursor is drawn depends on the current mode.
1267 */
1268 idx = get_shape_idx(FALSE);
1269
1270 if (shape_table[idx].shape == SHAPE_BLOCK)
1271 thickness = 99; /* 100 doesn't work on W95 */
1272 else
1273 thickness = shape_table[idx].percentage;
1274 mch_set_cursor_shape(thickness);
1275}
1276#endif
1277
1278#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1279/*
1280 * Handle FOCUS_EVENT.
1281 */
1282 static void
1283handle_focus_event(INPUT_RECORD ir)
1284{
1285 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1286 ui_focus_change((int)g_fJustGotFocus);
1287}
1288
1289/*
1290 * Wait until console input from keyboard or mouse is available,
1291 * or the time is up.
1292 * Return TRUE if something is available FALSE if not.
1293 */
1294 static int
1295WaitForChar(long msec)
1296{
1297 DWORD dwNow = 0, dwEndTime = 0;
1298 INPUT_RECORD ir;
1299 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001300 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001301#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001302 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001303#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001304
1305 if (msec > 0)
1306 /* Wait until the specified time has elapsed. */
1307 dwEndTime = GetTickCount() + msec;
1308 else if (msec < 0)
1309 /* Wait forever. */
1310 dwEndTime = INFINITE;
1311
1312 /* We need to loop until the end of the time period, because
1313 * we might get multiple unusable mouse events in that time.
1314 */
1315 for (;;)
1316 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001317#ifdef MESSAGE_QUEUE
1318 parse_queued_messages();
1319#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001320#ifdef FEAT_MZSCHEME
1321 mzvim_check_threads();
1322#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001323#ifdef FEAT_CLIENTSERVER
1324 serverProcessPendingMessages();
1325#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001326
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327 if (0
1328#ifdef FEAT_MOUSE
1329 || g_nMouseClick != -1
1330#endif
1331#ifdef FEAT_CLIENTSERVER
1332 || input_available()
1333#endif
1334 )
1335 return TRUE;
1336
1337 if (msec > 0)
1338 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001339 /* If the specified wait time has passed, return. Beware that
1340 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001341 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001342 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001343 break;
1344 }
1345 if (msec != 0)
1346 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001347 DWORD dwWaitTime = dwEndTime - dwNow;
1348
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001349#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar9186a272016-02-23 19:34:01 +01001350 /* Check channel while waiting input. */
1351 if (dwWaitTime > 100)
1352 dwWaitTime = 100;
1353#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001354#ifdef FEAT_MZSCHEME
1355 if (mzthreads_allowed() && p_mzq > 0
1356 && (msec < 0 || (long)dwWaitTime > p_mzq))
1357 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1358#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001359#ifdef FEAT_TIMERS
1360 {
1361 long due_time;
1362
1363 /* When waiting very briefly don't trigger timers. */
1364 if (dwWaitTime > 10)
1365 {
1366 /* Trigger timers and then get the time in msec until the
1367 * next one is due. Wait up to that time. */
1368 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001369 if (typebuf.tb_change_cnt != tb_change_cnt)
1370 {
1371 /* timer may have used feedkeys() */
1372 return FALSE;
1373 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001374 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1375 dwWaitTime = due_time;
1376 }
1377 }
1378#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001379#ifdef FEAT_CLIENTSERVER
1380 /* Wait for either an event on the console input or a message in
1381 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001382 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001383 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001385 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001386#endif
1387 continue;
1388 }
1389
1390 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001391 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001392
1393#ifdef FEAT_MBYTE_IME
1394 if (State & CMDLINE && msg_row == Rows - 1)
1395 {
1396 CONSOLE_SCREEN_BUFFER_INFO csbi;
1397
1398 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1399 {
1400 if (csbi.dwCursorPosition.Y != msg_row)
1401 {
1402 /* The screen is now messed up, must redraw the
1403 * command line and later all the windows. */
1404 redraw_all_later(CLEAR);
1405 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1406 redrawcmd();
1407 }
1408 }
1409 }
1410#endif
1411
1412 if (cRecords > 0)
1413 {
1414 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1415 {
1416#ifdef FEAT_MBYTE_IME
1417 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1418 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001419 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001420 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1421 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001422 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001423 continue;
1424 }
1425#endif
1426 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1427 NULL, FALSE))
1428 return TRUE;
1429 }
1430
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001431 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001432
1433 if (ir.EventType == FOCUS_EVENT)
1434 handle_focus_event(ir);
1435 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1436 shell_resized();
1437#ifdef FEAT_MOUSE
1438 else if (ir.EventType == MOUSE_EVENT
1439 && decode_mouse_event(&ir.Event.MouseEvent))
1440 return TRUE;
1441#endif
1442 }
1443 else if (msec == 0)
1444 break;
1445 }
1446
1447#ifdef FEAT_CLIENTSERVER
1448 /* Something might have been received while we were waiting. */
1449 if (input_available())
1450 return TRUE;
1451#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001452
Bram Moolenaar071d4272004-06-13 20:20:40 +00001453 return FALSE;
1454}
1455
1456#ifndef FEAT_GUI_MSWIN
1457/*
1458 * return non-zero if a character is available
1459 */
1460 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001461mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462{
1463 return WaitForChar(0L);
1464}
1465#endif
1466
1467/*
1468 * Create the console input. Used when reading stdin doesn't work.
1469 */
1470 static void
1471create_conin(void)
1472{
1473 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1474 FILE_SHARE_READ|FILE_SHARE_WRITE,
1475 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001476 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001477 did_create_conin = TRUE;
1478}
1479
1480/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001481 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001482 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001483 static WCHAR
1484tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001485{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001486 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001487
1488 for (;;)
1489 {
1490 INPUT_RECORD ir;
1491 DWORD cRecords = 0;
1492
1493#ifdef FEAT_CLIENTSERVER
1494 (void)WaitForChar(-1L);
1495 if (input_available())
1496 return 0;
1497# ifdef FEAT_MOUSE
1498 if (g_nMouseClick != -1)
1499 return 0;
1500# endif
1501#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001502 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503 {
1504 if (did_create_conin)
1505 read_error_exit();
1506 create_conin();
1507 continue;
1508 }
1509
1510 if (ir.EventType == KEY_EVENT)
1511 {
1512 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1513 pmodifiers, TRUE))
1514 return ch;
1515 }
1516 else if (ir.EventType == FOCUS_EVENT)
1517 handle_focus_event(ir);
1518 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1519 shell_resized();
1520#ifdef FEAT_MOUSE
1521 else if (ir.EventType == MOUSE_EVENT)
1522 {
1523 if (decode_mouse_event(&ir.Event.MouseEvent))
1524 return 0;
1525 }
1526#endif
1527 }
1528}
1529#endif /* !FEAT_GUI_W32 */
1530
1531
1532/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001533 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534 * Get one or more characters from the keyboard or the mouse.
1535 * If time == 0, do not wait for characters.
1536 * If time == n, wait a short time for characters.
1537 * If time == -1, wait forever for characters.
1538 * Returns the number of characters read into buf.
1539 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001540/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541 int
1542mch_inchar(
1543 char_u *buf,
1544 int maxlen,
1545 long time,
1546 int tb_change_cnt)
1547{
1548#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1549
1550 int len;
1551 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552#define TYPEAHEADLEN 20
1553 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1554 static int typeaheadlen = 0;
1555
1556 /* First use any typeahead that was kept because "buf" was too small. */
1557 if (typeaheadlen > 0)
1558 goto theend;
1559
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 if (time >= 0)
1561 {
1562 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001563 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564 }
1565 else /* time == -1, wait forever */
1566 {
1567 mch_set_winsize_now(); /* Allow winsize changes from now on */
1568
Bram Moolenaar3918c952005-03-15 22:34:55 +00001569 /*
1570 * If there is no character available within 2 seconds (default)
1571 * write the autoscript file to disk. Or cause the CursorHold event
1572 * to be triggered.
1573 */
1574 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001575 {
1576#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001577 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001579 buf[0] = K_SPECIAL;
1580 buf[1] = KS_EXTRA;
1581 buf[2] = (int)KE_CURSORHOLD;
1582 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583 }
1584#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001585 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586 }
1587 }
1588
1589 /*
1590 * Try to read as many characters as there are, until the buffer is full.
1591 */
1592
1593 /* we will get at least one key. Get more if they are available. */
1594 g_fCBrkPressed = FALSE;
1595
1596#ifdef MCH_WRITE_DUMP
1597 if (fdDump)
1598 fputc('[', fdDump);
1599#endif
1600
1601 /* Keep looping until there is something in the typeahead buffer and more
1602 * to get and still room in the buffer (up to two bytes for a char and
1603 * three bytes for a modifier). */
1604 while ((typeaheadlen == 0 || WaitForChar(0L))
1605 && typeaheadlen + 5 <= TYPEAHEADLEN)
1606 {
1607 if (typebuf_changed(tb_change_cnt))
1608 {
1609 /* "buf" may be invalid now if a client put something in the
1610 * typeahead buffer and "buf" is in the typeahead buffer. */
1611 typeaheadlen = 0;
1612 break;
1613 }
1614#ifdef FEAT_MOUSE
1615 if (g_nMouseClick != -1)
1616 {
1617# ifdef MCH_WRITE_DUMP
1618 if (fdDump)
1619 fprintf(fdDump, "{%02x @ %d, %d}",
1620 g_nMouseClick, g_xMouse, g_yMouse);
1621# endif
1622 typeahead[typeaheadlen++] = ESC + 128;
1623 typeahead[typeaheadlen++] = 'M';
1624 typeahead[typeaheadlen++] = g_nMouseClick;
1625 typeahead[typeaheadlen++] = g_xMouse + '!';
1626 typeahead[typeaheadlen++] = g_yMouse + '!';
1627 g_nMouseClick = -1;
1628 }
1629 else
1630#endif
1631 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001632 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633 int modifiers = 0;
1634
1635 c = tgetch(&modifiers, &ch2);
1636
1637 if (typebuf_changed(tb_change_cnt))
1638 {
1639 /* "buf" may be invalid now if a client put something in the
1640 * typeahead buffer and "buf" is in the typeahead buffer. */
1641 typeaheadlen = 0;
1642 break;
1643 }
1644
1645 if (c == Ctrl_C && ctrl_c_interrupts)
1646 {
1647#if defined(FEAT_CLIENTSERVER)
1648 trash_input_buf();
1649#endif
1650 got_int = TRUE;
1651 }
1652
1653#ifdef FEAT_MOUSE
1654 if (g_nMouseClick == -1)
1655#endif
1656 {
1657 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001658 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001659
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001660#ifdef FEAT_MBYTE
1661 if (ch2 == NUL)
1662 {
1663 int i;
1664 char_u *p;
1665 WCHAR ch[2];
1666
1667 ch[0] = c;
1668 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1669 {
1670 ch[1] = tgetch(&modifiers, &ch2);
1671 n++;
1672 }
1673 p = utf16_to_enc(ch, &n);
1674 if (p != NULL)
1675 {
1676 for (i = 0; i < n; i++)
1677 typeahead[typeaheadlen + i] = p[i];
1678 vim_free(p);
1679 }
1680 }
1681 else
1682#endif
1683 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 if (ch2 != NUL)
1685 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001686 typeahead[typeaheadlen + n] = 3;
1687 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001688 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690
Bram Moolenaar45500912014-07-09 20:51:07 +02001691 if (conv)
1692 {
1693 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001694
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001695 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001696 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001697 char_u *e = typeahead + TYPEAHEADLEN;
1698
1699 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001700 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001701 if (*p == K_NUL)
1702 {
1703 ++p;
1704 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1705 *p = 3;
1706 ++n;
1707 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001708 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001709 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001710 }
1711 }
1712
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 /* Use the ALT key to set the 8th bit of the character
1714 * when it's one byte, the 8th bit isn't set yet and not
1715 * using a double-byte encoding (would become a lead
1716 * byte). */
1717 if ((modifiers & MOD_MASK_ALT)
1718 && n == 1
1719 && (typeahead[typeaheadlen] & 0x80) == 0
1720#ifdef FEAT_MBYTE
1721 && !enc_dbcs
1722#endif
1723 )
1724 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001725#ifdef FEAT_MBYTE
1726 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1727 typeahead + typeaheadlen);
1728#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001730#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001731 modifiers &= ~MOD_MASK_ALT;
1732 }
1733
1734 if (modifiers != 0)
1735 {
1736 /* Prepend modifiers to the character. */
1737 mch_memmove(typeahead + typeaheadlen + 3,
1738 typeahead + typeaheadlen, n);
1739 typeahead[typeaheadlen++] = K_SPECIAL;
1740 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1741 typeahead[typeaheadlen++] = modifiers;
1742 }
1743
1744 typeaheadlen += n;
1745
1746#ifdef MCH_WRITE_DUMP
1747 if (fdDump)
1748 fputc(c, fdDump);
1749#endif
1750 }
1751 }
1752 }
1753
1754#ifdef MCH_WRITE_DUMP
1755 if (fdDump)
1756 {
1757 fputs("]\n", fdDump);
1758 fflush(fdDump);
1759 }
1760#endif
1761
Bram Moolenaar071d4272004-06-13 20:20:40 +00001762theend:
1763 /* Move typeahead to "buf", as much as fits. */
1764 len = 0;
1765 while (len < maxlen && typeaheadlen > 0)
1766 {
1767 buf[len++] = typeahead[0];
1768 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1769 }
1770 return len;
1771
1772#else /* FEAT_GUI_W32 */
1773 return 0;
1774#endif /* FEAT_GUI_W32 */
1775}
1776
Bram Moolenaar82881492012-11-20 16:53:39 +01001777#ifndef PROTO
1778# ifndef __MINGW32__
1779# include <shellapi.h> /* required for FindExecutable() */
1780# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781#endif
1782
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001783/*
1784 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001785 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001786 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001788executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001789{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001790 char *dum;
1791 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001792 char *curpath, *newpath;
1793 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001795#ifdef FEAT_MBYTE
1796 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001798 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001799 WCHAR fnamew[_MAX_PATH];
1800 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001801 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001802
1803 if (p != NULL)
1804 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001805 wcurpath = _wgetenv(L"PATH");
1806 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1807 * sizeof(WCHAR));
1808 if (wnewpath == NULL)
1809 return FALSE;
1810 wcscpy(wnewpath, L".;");
1811 wcscat(wnewpath, wcurpath);
1812 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1813 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001814 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02001815 if (n == 0)
1816 return FALSE;
1817 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1818 return FALSE;
1819 if (path != NULL)
1820 *path = utf16_to_enc(fnamew, NULL);
1821 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001822 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001823 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001824#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001825
1826 curpath = getenv("PATH");
1827 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1828 if (newpath == NULL)
1829 return FALSE;
1830 STRCPY(newpath, ".;");
1831 STRCAT(newpath, curpath);
1832 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1833 vim_free(newpath);
1834 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001835 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001836 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001837 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001838 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001839 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001840 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001841}
1842
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001843#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001844 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001845/*
1846 * Bad parameter handler.
1847 *
1848 * Certain MS CRT functions will intentionally crash when passed invalid
1849 * parameters to highlight possible security holes. Setting this function as
1850 * the bad parameter handler will prevent the crash.
1851 *
1852 * In debug builds the parameters contain CRT information that might help track
1853 * down the source of a problem, but in non-debug builds the arguments are all
1854 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1855 * worth allowing these to make debugging of issues easier.
1856 */
1857 static void
1858bad_param_handler(const wchar_t *expression,
1859 const wchar_t *function,
1860 const wchar_t *file,
1861 unsigned int line,
1862 uintptr_t pReserved)
1863{
1864}
1865
1866# define SET_INVALID_PARAM_HANDLER \
1867 ((void)_set_invalid_parameter_handler(bad_param_handler))
1868#else
1869# define SET_INVALID_PARAM_HANDLER
1870#endif
1871
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872#ifdef FEAT_GUI_W32
1873
1874/*
1875 * GUI version of mch_init().
1876 */
1877 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001878mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879{
1880#ifndef __MINGW32__
1881 extern int _fmode;
1882#endif
1883
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001884 /* Silently handle invalid parameters to CRT functions */
1885 SET_INVALID_PARAM_HANDLER;
1886
Bram Moolenaar071d4272004-06-13 20:20:40 +00001887 /* Let critical errors result in a failure, not in a dialog box. Required
1888 * for the timestamp test to work on removed floppies. */
1889 SetErrorMode(SEM_FAILCRITICALERRORS);
1890
1891 _fmode = O_BINARY; /* we do our own CR-LF translation */
1892
1893 /* Specify window size. Is there a place to get the default from? */
1894 Rows = 25;
1895 Columns = 80;
1896
1897 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001898 {
1899 char_u vimrun_location[_MAX_PATH + 4];
1900
1901 /* First try in same directory as gvim.exe */
1902 STRCPY(vimrun_location, exe_name);
1903 STRCPY(gettail(vimrun_location), "vimrun.exe");
1904 if (mch_getperm(vimrun_location) >= 0)
1905 {
1906 if (*skiptowhite(vimrun_location) != NUL)
1907 {
1908 /* Enclose path with white space in double quotes. */
1909 mch_memmove(vimrun_location + 1, vimrun_location,
1910 STRLEN(vimrun_location) + 1);
1911 *vimrun_location = '"';
1912 STRCPY(gettail(vimrun_location), "vimrun\" ");
1913 }
1914 else
1915 STRCPY(gettail(vimrun_location), "vimrun ");
1916
1917 vimrun_path = (char *)vim_strsave(vimrun_location);
1918 s_dont_use_vimrun = FALSE;
1919 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001920 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 s_dont_use_vimrun = FALSE;
1922
1923 /* Don't give the warning for a missing vimrun.exe right now, but only
1924 * when vimrun was supposed to be used. Don't bother people that do
1925 * not need vimrun.exe. */
1926 if (s_dont_use_vimrun)
1927 need_vimrun_warning = TRUE;
1928 }
1929
1930 /*
1931 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1932 * Otherwise the default "findstr /n" is used.
1933 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001934 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1936
1937#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001938 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939#endif
1940}
1941
1942
1943#else /* FEAT_GUI_W32 */
1944
1945#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1946#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1947
1948/*
1949 * ClearConsoleBuffer()
1950 * Description:
1951 * Clears the entire contents of the console screen buffer, using the
1952 * specified attribute.
1953 * Returns:
1954 * TRUE on success
1955 */
1956 static BOOL
1957ClearConsoleBuffer(WORD wAttribute)
1958{
1959 CONSOLE_SCREEN_BUFFER_INFO csbi;
1960 COORD coord;
1961 DWORD NumCells, dummy;
1962
1963 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1964 return FALSE;
1965
1966 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1967 coord.X = 0;
1968 coord.Y = 0;
1969 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1970 coord, &dummy))
1971 {
1972 return FALSE;
1973 }
1974 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1975 coord, &dummy))
1976 {
1977 return FALSE;
1978 }
1979
1980 return TRUE;
1981}
1982
1983/*
1984 * FitConsoleWindow()
1985 * Description:
1986 * Checks if the console window will fit within given buffer dimensions.
1987 * Also, if requested, will shrink the window to fit.
1988 * Returns:
1989 * TRUE on success
1990 */
1991 static BOOL
1992FitConsoleWindow(
1993 COORD dwBufferSize,
1994 BOOL WantAdjust)
1995{
1996 CONSOLE_SCREEN_BUFFER_INFO csbi;
1997 COORD dwWindowSize;
1998 BOOL NeedAdjust = FALSE;
1999
2000 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2001 {
2002 /*
2003 * A buffer resize will fail if the current console window does
2004 * not lie completely within that buffer. To avoid this, we might
2005 * have to move and possibly shrink the window.
2006 */
2007 if (csbi.srWindow.Right >= dwBufferSize.X)
2008 {
2009 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2010 if (dwWindowSize.X > dwBufferSize.X)
2011 dwWindowSize.X = dwBufferSize.X;
2012 csbi.srWindow.Right = dwBufferSize.X - 1;
2013 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2014 NeedAdjust = TRUE;
2015 }
2016 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2017 {
2018 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2019 if (dwWindowSize.Y > dwBufferSize.Y)
2020 dwWindowSize.Y = dwBufferSize.Y;
2021 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2022 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2023 NeedAdjust = TRUE;
2024 }
2025 if (NeedAdjust && WantAdjust)
2026 {
2027 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2028 return FALSE;
2029 }
2030 return TRUE;
2031 }
2032
2033 return FALSE;
2034}
2035
2036typedef struct ConsoleBufferStruct
2037{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002038 BOOL IsValid;
2039 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002040 PCHAR_INFO Buffer;
2041 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042} ConsoleBuffer;
2043
2044/*
2045 * SaveConsoleBuffer()
2046 * Description:
2047 * Saves important information about the console buffer, including the
2048 * actual buffer contents. The saved information is suitable for later
2049 * restoration by RestoreConsoleBuffer().
2050 * Returns:
2051 * TRUE if all information was saved; FALSE otherwise
2052 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2053 */
2054 static BOOL
2055SaveConsoleBuffer(
2056 ConsoleBuffer *cb)
2057{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002058 DWORD NumCells;
2059 COORD BufferCoord;
2060 SMALL_RECT ReadRegion;
2061 WORD Y, Y_incr;
2062
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063 if (cb == NULL)
2064 return FALSE;
2065
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002066 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 {
2068 cb->IsValid = FALSE;
2069 return FALSE;
2070 }
2071 cb->IsValid = TRUE;
2072
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002073 /*
2074 * Allocate a buffer large enough to hold the entire console screen
2075 * buffer. If this ConsoleBuffer structure has already been initialized
2076 * with a buffer of the correct size, then just use that one.
2077 */
2078 if (!cb->IsValid || cb->Buffer == NULL ||
2079 cb->BufferSize.X != cb->Info.dwSize.X ||
2080 cb->BufferSize.Y != cb->Info.dwSize.Y)
2081 {
2082 cb->BufferSize.X = cb->Info.dwSize.X;
2083 cb->BufferSize.Y = cb->Info.dwSize.Y;
2084 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2085 vim_free(cb->Buffer);
2086 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2087 if (cb->Buffer == NULL)
2088 return FALSE;
2089 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090
2091 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002092 * We will now copy the console screen buffer into our buffer.
2093 * ReadConsoleOutput() seems to be limited as far as how much you
2094 * can read at a time. Empirically, this number seems to be about
2095 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2096 * in chunks until it is all copied. The chunks will all have the
2097 * same horizontal characteristics, so initialize them now. The
2098 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002100 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002101 ReadRegion.Left = 0;
2102 ReadRegion.Right = cb->Info.dwSize.X - 1;
2103 Y_incr = 12000 / cb->Info.dwSize.X;
2104 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002105 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002106 /*
2107 * Read into position (0, Y) in our buffer.
2108 */
2109 BufferCoord.Y = Y;
2110 /*
2111 * Read the region whose top left corner is (0, Y) and whose bottom
2112 * right corner is (width - 1, Y + Y_incr - 1). This should define
2113 * a region of size width by Y_incr. Don't worry if this region is
2114 * too large for the remaining buffer; it will be cropped.
2115 */
2116 ReadRegion.Top = Y;
2117 ReadRegion.Bottom = Y + Y_incr - 1;
2118 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2119 cb->Buffer, /* our buffer */
2120 cb->BufferSize, /* dimensions of our buffer */
2121 BufferCoord, /* offset in our buffer */
2122 &ReadRegion)) /* region to save */
2123 {
2124 vim_free(cb->Buffer);
2125 cb->Buffer = NULL;
2126 return FALSE;
2127 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002128 }
2129
2130 return TRUE;
2131}
2132
2133/*
2134 * RestoreConsoleBuffer()
2135 * Description:
2136 * Restores important information about the console buffer, including the
2137 * actual buffer contents, if desired. The information to restore is in
2138 * the same format used by SaveConsoleBuffer().
2139 * Returns:
2140 * TRUE on success
2141 */
2142 static BOOL
2143RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002144 ConsoleBuffer *cb,
2145 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002146{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002147 COORD BufferCoord;
2148 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149
2150 if (cb == NULL || !cb->IsValid)
2151 return FALSE;
2152
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002153 /*
2154 * Before restoring the buffer contents, clear the current buffer, and
2155 * restore the cursor position and window information. Doing this now
2156 * prevents old buffer contents from "flashing" onto the screen.
2157 */
2158 if (RestoreScreen)
2159 ClearConsoleBuffer(cb->Info.wAttributes);
2160
2161 FitConsoleWindow(cb->Info.dwSize, TRUE);
2162 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2163 return FALSE;
2164 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2165 return FALSE;
2166
2167 if (!RestoreScreen)
2168 {
2169 /*
2170 * No need to restore the screen buffer contents, so we're done.
2171 */
2172 return TRUE;
2173 }
2174
2175 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2176 return FALSE;
2177 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2178 return FALSE;
2179
2180 /*
2181 * Restore the screen buffer contents.
2182 */
2183 if (cb->Buffer != NULL)
2184 {
2185 BufferCoord.X = 0;
2186 BufferCoord.Y = 0;
2187 WriteRegion.Left = 0;
2188 WriteRegion.Top = 0;
2189 WriteRegion.Right = cb->Info.dwSize.X - 1;
2190 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2191 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2192 cb->Buffer, /* our buffer */
2193 cb->BufferSize, /* dimensions of our buffer */
2194 BufferCoord, /* offset in our buffer */
2195 &WriteRegion)) /* region to restore */
2196 {
2197 return FALSE;
2198 }
2199 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200
2201 return TRUE;
2202}
2203
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002204#define FEAT_RESTORE_ORIG_SCREEN
2205#ifdef FEAT_RESTORE_ORIG_SCREEN
2206static ConsoleBuffer g_cbOrig = { 0 };
2207#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002208static ConsoleBuffer g_cbNonTermcap = { 0 };
2209static ConsoleBuffer g_cbTermcap = { 0 };
2210
2211#ifdef FEAT_TITLE
2212#ifdef __BORLANDC__
2213typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2214#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002215typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216#endif
2217char g_szOrigTitle[256] = { 0 };
2218HWND g_hWnd = NULL; /* also used in os_mswin.c */
2219static HICON g_hOrigIconSmall = NULL;
2220static HICON g_hOrigIcon = NULL;
2221static HICON g_hVimIcon = NULL;
2222static BOOL g_fCanChangeIcon = FALSE;
2223
2224/* ICON* are not defined in VC++ 4.0 */
2225#ifndef ICON_SMALL
2226#define ICON_SMALL 0
2227#endif
2228#ifndef ICON_BIG
2229#define ICON_BIG 1
2230#endif
2231/*
2232 * GetConsoleIcon()
2233 * Description:
2234 * Attempts to retrieve the small icon and/or the big icon currently in
2235 * use by a given window.
2236 * Returns:
2237 * TRUE on success
2238 */
2239 static BOOL
2240GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002241 HWND hWnd,
2242 HICON *phIconSmall,
2243 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244{
2245 if (hWnd == NULL)
2246 return FALSE;
2247
2248 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002249 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2250 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002252 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2253 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002254 return TRUE;
2255}
2256
2257/*
2258 * SetConsoleIcon()
2259 * Description:
2260 * Attempts to change the small icon and/or the big icon currently in
2261 * use by a given window.
2262 * Returns:
2263 * TRUE on success
2264 */
2265 static BOOL
2266SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002267 HWND hWnd,
2268 HICON hIconSmall,
2269 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002271 if (hWnd == NULL)
2272 return FALSE;
2273
2274 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002275 SendMessage(hWnd, WM_SETICON,
2276 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002278 SendMessage(hWnd, WM_SETICON,
2279 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280 return TRUE;
2281}
2282
2283/*
2284 * SaveConsoleTitleAndIcon()
2285 * Description:
2286 * Saves the current console window title in g_szOrigTitle, for later
2287 * restoration. Also, attempts to obtain a handle to the console window,
2288 * and use it to save the small and big icons currently in use by the
2289 * console window. This is not always possible on some versions of Windows;
2290 * nor is it possible when running Vim remotely using Telnet (since the
2291 * console window the user sees is owned by a remote process).
2292 */
2293 static void
2294SaveConsoleTitleAndIcon(void)
2295{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296 /* Save the original title. */
2297 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2298 return;
2299
2300 /*
2301 * Obtain a handle to the console window using GetConsoleWindow() from
2302 * KERNEL32.DLL; we need to handle in order to change the window icon.
2303 * This function only exists on NT-based Windows, starting with Windows
2304 * 2000. On older operating systems, we can't change the window icon
2305 * anyway.
2306 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002307 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 if (g_hWnd == NULL)
2309 return;
2310
2311 /* Save the original console window icon. */
2312 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2313 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2314 return;
2315
2316 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002317 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002318 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002319 if (g_hVimIcon != NULL)
2320 g_fCanChangeIcon = TRUE;
2321}
2322#endif
2323
2324static int g_fWindInitCalled = FALSE;
2325static int g_fTermcapMode = FALSE;
2326static CONSOLE_CURSOR_INFO g_cci;
2327static DWORD g_cmodein = 0;
2328static DWORD g_cmodeout = 0;
2329
2330/*
2331 * non-GUI version of mch_init().
2332 */
2333 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002334mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002336#ifndef FEAT_RESTORE_ORIG_SCREEN
2337 CONSOLE_SCREEN_BUFFER_INFO csbi;
2338#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339#ifndef __MINGW32__
2340 extern int _fmode;
2341#endif
2342
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002343 /* Silently handle invalid parameters to CRT functions */
2344 SET_INVALID_PARAM_HANDLER;
2345
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346 /* Let critical errors result in a failure, not in a dialog box. Required
2347 * for the timestamp test to work on removed floppies. */
2348 SetErrorMode(SEM_FAILCRITICALERRORS);
2349
2350 _fmode = O_BINARY; /* we do our own CR-LF translation */
2351 out_flush();
2352
2353 /* Obtain handles for the standard Console I/O devices */
2354 if (read_cmd_fd == 0)
2355 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2356 else
2357 create_conin();
2358 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2359
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002360#ifdef FEAT_RESTORE_ORIG_SCREEN
2361 /* Save the initial console buffer for later restoration */
2362 SaveConsoleBuffer(&g_cbOrig);
2363 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2364#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002366 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2367 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2368#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369 if (cterm_normal_fg_color == 0)
2370 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2371 if (cterm_normal_bg_color == 0)
2372 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2373
2374 /* set termcap codes to current text attributes */
2375 update_tcap(g_attrCurrent);
2376
2377 GetConsoleCursorInfo(g_hConOut, &g_cci);
2378 GetConsoleMode(g_hConIn, &g_cmodein);
2379 GetConsoleMode(g_hConOut, &g_cmodeout);
2380
2381#ifdef FEAT_TITLE
2382 SaveConsoleTitleAndIcon();
2383 /*
2384 * Set both the small and big icons of the console window to Vim's icon.
2385 * Note that Vim presently only has one size of icon (32x32), but it
2386 * automatically gets scaled down to 16x16 when setting the small icon.
2387 */
2388 if (g_fCanChangeIcon)
2389 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2390#endif
2391
2392 ui_get_shellsize();
2393
2394#ifdef MCH_WRITE_DUMP
2395 fdDump = fopen("dump", "wt");
2396
2397 if (fdDump)
2398 {
2399 time_t t;
2400
2401 time(&t);
2402 fputs(ctime(&t), fdDump);
2403 fflush(fdDump);
2404 }
2405#endif
2406
2407 g_fWindInitCalled = TRUE;
2408
2409#ifdef FEAT_MOUSE
2410 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2411#endif
2412
2413#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002414 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002416}
2417
2418/*
2419 * non-GUI version of mch_exit().
2420 * Shut down and exit with status `r'
2421 * Careful: mch_exit() may be called before mch_init()!
2422 */
2423 void
2424mch_exit(int r)
2425{
2426 stoptermcap();
2427
2428 if (g_fWindInitCalled)
2429 settmode(TMODE_COOK);
2430
2431 ml_close_all(TRUE); /* remove all memfiles */
2432
2433 if (g_fWindInitCalled)
2434 {
2435#ifdef FEAT_TITLE
2436 mch_restore_title(3);
2437 /*
2438 * Restore both the small and big icons of the console window to
2439 * what they were at startup. Don't do this when the window is
2440 * closed, Vim would hang here.
2441 */
2442 if (g_fCanChangeIcon && !g_fForceExit)
2443 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2444#endif
2445
2446#ifdef MCH_WRITE_DUMP
2447 if (fdDump)
2448 {
2449 time_t t;
2450
2451 time(&t);
2452 fputs(ctime(&t), fdDump);
2453 fclose(fdDump);
2454 }
2455 fdDump = NULL;
2456#endif
2457 }
2458
2459 SetConsoleCursorInfo(g_hConOut, &g_cci);
2460 SetConsoleMode(g_hConIn, g_cmodein);
2461 SetConsoleMode(g_hConOut, g_cmodeout);
2462
2463#ifdef DYNAMIC_GETTEXT
2464 dyn_libintl_end();
2465#endif
2466
2467 exit(r);
2468}
2469#endif /* !FEAT_GUI_W32 */
2470
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471/*
2472 * Do we have an interactive window?
2473 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002474/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475 int
2476mch_check_win(
2477 int argc,
2478 char **argv)
2479{
2480 get_exe_name();
2481
2482#ifdef FEAT_GUI_W32
2483 return OK; /* GUI always has a tty */
2484#else
2485 if (isatty(1))
2486 return OK;
2487 return FAIL;
2488#endif
2489}
2490
2491
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002492#ifdef FEAT_MBYTE
2493/*
2494 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2495 * if it already exists. When "len" is > 0, also expand short to long
2496 * filenames.
2497 * Return FAIL if wide functions are not available, OK otherwise.
2498 * NOTE: much of this is identical to fname_case(), keep in sync!
2499 */
2500 static int
2501fname_casew(
2502 WCHAR *name,
2503 int len)
2504{
2505 WCHAR szTrueName[_MAX_PATH + 2];
2506 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2507 WCHAR *ptrue, *ptruePrev;
2508 WCHAR *porig, *porigPrev;
2509 int flen;
2510 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002511 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002512 int c;
2513 int slen;
2514
2515 flen = (int)wcslen(name);
2516 if (flen > _MAX_PATH)
2517 return OK;
2518
2519 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2520
2521 /* Build the new name in szTrueName[] one component at a time. */
2522 porig = name;
2523 ptrue = szTrueName;
2524
2525 if (iswalpha(porig[0]) && porig[1] == L':')
2526 {
2527 /* copy leading drive letter */
2528 *ptrue++ = *porig++;
2529 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002530 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002531 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002532
2533 while (*porig != NUL)
2534 {
2535 /* copy \ characters */
2536 while (*porig == psepc)
2537 *ptrue++ = *porig++;
2538
2539 ptruePrev = ptrue;
2540 porigPrev = porig;
2541 while (*porig != NUL && *porig != psepc)
2542 {
2543 *ptrue++ = *porig++;
2544 }
2545 *ptrue = NUL;
2546
2547 /* To avoid a slow failure append "\*" when searching a directory,
2548 * server or network share. */
2549 wcscpy(szTrueNameTemp, szTrueName);
2550 slen = (int)wcslen(szTrueNameTemp);
2551 if (*porig == psepc && slen + 2 < _MAX_PATH)
2552 wcscpy(szTrueNameTemp + slen, L"\\*");
2553
2554 /* Skip "", "." and "..". */
2555 if (ptrue > ptruePrev
2556 && (ptruePrev[0] != L'.'
2557 || (ptruePrev[1] != NUL
2558 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2559 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2560 != INVALID_HANDLE_VALUE)
2561 {
2562 c = *porig;
2563 *porig = NUL;
2564
2565 /* Only use the match when it's the same name (ignoring case) or
2566 * expansion is allowed and there is a match with the short name
2567 * and there is enough room. */
2568 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2569 || (len > 0
2570 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2571 && (int)(ptruePrev - szTrueName)
2572 + (int)wcslen(fb.cFileName) < len)))
2573 {
2574 wcscpy(ptruePrev, fb.cFileName);
2575
2576 /* Look for exact match and prefer it if found. Must be a
2577 * long name, otherwise there would be only one match. */
2578 while (FindNextFileW(hFind, &fb))
2579 {
2580 if (*fb.cAlternateFileName != NUL
2581 && (wcscoll(porigPrev, fb.cFileName) == 0
2582 || (len > 0
2583 && (_wcsicoll(porigPrev,
2584 fb.cAlternateFileName) == 0
2585 && (int)(ptruePrev - szTrueName)
2586 + (int)wcslen(fb.cFileName) < len))))
2587 {
2588 wcscpy(ptruePrev, fb.cFileName);
2589 break;
2590 }
2591 }
2592 }
2593 FindClose(hFind);
2594 *porig = c;
2595 ptrue = ptruePrev + wcslen(ptruePrev);
2596 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002597 }
2598
2599 wcscpy(name, szTrueName);
2600 return OK;
2601}
2602#endif
2603
Bram Moolenaar071d4272004-06-13 20:20:40 +00002604/*
2605 * fname_case(): Set the case of the file name, if it already exists.
2606 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002607 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608 */
2609 void
2610fname_case(
2611 char_u *name,
2612 int len)
2613{
2614 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002615 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002616 char *ptrue, *ptruePrev;
2617 char *porig, *porigPrev;
2618 int flen;
2619 WIN32_FIND_DATA fb;
2620 HANDLE hFind;
2621 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002622 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002623
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002624 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002625 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 return;
2627
2628 slash_adjust(name);
2629
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002630#ifdef FEAT_MBYTE
2631 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2632 {
2633 WCHAR *p = enc_to_utf16(name, NULL);
2634
2635 if (p != NULL)
2636 {
2637 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002638 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002639
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002640 wcsncpy(buf, p, _MAX_PATH);
2641 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002642 vim_free(p);
2643
2644 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2645 {
2646 q = utf16_to_enc(buf, NULL);
2647 if (q != NULL)
2648 {
2649 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2650 vim_free(q);
2651 return;
2652 }
2653 }
2654 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002655 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002656 }
2657#endif
2658
2659 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2660 * So we should check this after calling wide function. */
2661 if (flen > _MAX_PATH)
2662 return;
2663
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002665 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002666 ptrue = szTrueName;
2667
2668 if (isalpha(porig[0]) && porig[1] == ':')
2669 {
2670 /* copy leading drive letter */
2671 *ptrue++ = *porig++;
2672 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002673 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002674 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002675
2676 while (*porig != NUL)
2677 {
2678 /* copy \ characters */
2679 while (*porig == psepc)
2680 *ptrue++ = *porig++;
2681
2682 ptruePrev = ptrue;
2683 porigPrev = porig;
2684 while (*porig != NUL && *porig != psepc)
2685 {
2686#ifdef FEAT_MBYTE
2687 int l;
2688
2689 if (enc_dbcs)
2690 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002691 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002692 while (--l >= 0)
2693 *ptrue++ = *porig++;
2694 }
2695 else
2696#endif
2697 *ptrue++ = *porig++;
2698 }
2699 *ptrue = NUL;
2700
Bram Moolenaar464c9252010-10-13 20:37:41 +02002701 /* To avoid a slow failure append "\*" when searching a directory,
2702 * server or network share. */
2703 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002704 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002705 if (*porig == psepc && slen + 2 < _MAX_PATH)
2706 STRCPY(szTrueNameTemp + slen, "\\*");
2707
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708 /* Skip "", "." and "..". */
2709 if (ptrue > ptruePrev
2710 && (ptruePrev[0] != '.'
2711 || (ptruePrev[1] != NUL
2712 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002713 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 != INVALID_HANDLE_VALUE)
2715 {
2716 c = *porig;
2717 *porig = NUL;
2718
2719 /* Only use the match when it's the same name (ignoring case) or
2720 * expansion is allowed and there is a match with the short name
2721 * and there is enough room. */
2722 if (_stricoll(porigPrev, fb.cFileName) == 0
2723 || (len > 0
2724 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2725 && (int)(ptruePrev - szTrueName)
2726 + (int)strlen(fb.cFileName) < len)))
2727 {
2728 STRCPY(ptruePrev, fb.cFileName);
2729
2730 /* Look for exact match and prefer it if found. Must be a
2731 * long name, otherwise there would be only one match. */
2732 while (FindNextFile(hFind, &fb))
2733 {
2734 if (*fb.cAlternateFileName != NUL
2735 && (strcoll(porigPrev, fb.cFileName) == 0
2736 || (len > 0
2737 && (_stricoll(porigPrev,
2738 fb.cAlternateFileName) == 0
2739 && (int)(ptruePrev - szTrueName)
2740 + (int)strlen(fb.cFileName) < len))))
2741 {
2742 STRCPY(ptruePrev, fb.cFileName);
2743 break;
2744 }
2745 }
2746 }
2747 FindClose(hFind);
2748 *porig = c;
2749 ptrue = ptruePrev + strlen(ptruePrev);
2750 }
2751 }
2752
2753 STRCPY(name, szTrueName);
2754}
2755
2756
2757/*
2758 * Insert user name in s[len].
2759 */
2760 int
2761mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002762 char_u *s,
2763 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002765 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766 DWORD cch = sizeof szUserName;
2767
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002768#ifdef FEAT_MBYTE
2769 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2770 {
2771 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2772 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2773
2774 if (GetUserNameW(wszUserName, &wcch))
2775 {
2776 char_u *p = utf16_to_enc(wszUserName, NULL);
2777
2778 if (p != NULL)
2779 {
2780 vim_strncpy(s, p, len - 1);
2781 vim_free(p);
2782 return OK;
2783 }
2784 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002785 }
2786#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002787 if (GetUserName(szUserName, &cch))
2788 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002789 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002790 return OK;
2791 }
2792 s[0] = NUL;
2793 return FAIL;
2794}
2795
2796
2797/*
2798 * Insert host name in s[len].
2799 */
2800 void
2801mch_get_host_name(
2802 char_u *s,
2803 int len)
2804{
2805 DWORD cch = len;
2806
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002807#ifdef FEAT_MBYTE
2808 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2809 {
2810 WCHAR wszHostName[256 + 1];
2811 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2812
2813 if (GetComputerNameW(wszHostName, &wcch))
2814 {
2815 char_u *p = utf16_to_enc(wszHostName, NULL);
2816
2817 if (p != NULL)
2818 {
2819 vim_strncpy(s, p, len - 1);
2820 vim_free(p);
2821 return;
2822 }
2823 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002824 }
2825#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002826 if (!GetComputerName((LPSTR)s, &cch))
2827 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002828}
2829
2830
2831/*
2832 * return process ID
2833 */
2834 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002835mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002836{
2837 return (long)GetCurrentProcessId();
2838}
2839
2840
2841/*
2842 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2843 * Return OK for success, FAIL for failure.
2844 */
2845 int
2846mch_dirname(
2847 char_u *buf,
2848 int len)
2849{
2850 /*
2851 * Originally this was:
2852 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2853 * But the Win32s known bug list says that getcwd() doesn't work
2854 * so use the Win32 system call instead. <Negri>
2855 */
2856#ifdef FEAT_MBYTE
2857 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2858 {
2859 WCHAR wbuf[_MAX_PATH + 1];
2860
2861 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2862 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002863 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864
2865 if (p != NULL)
2866 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002867 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868 vim_free(p);
2869 return OK;
2870 }
2871 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002872 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 }
2874#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002875 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876}
2877
2878/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002879 * Get file permissions for "name".
2880 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 */
2882 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002883mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002885 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002886 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002888 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002889 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890}
2891
2892
2893/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002894 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002895 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002896 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 */
2898 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002899mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002901 long n = -1;
2902
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903#ifdef FEAT_MBYTE
2904 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2905 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002906 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907
2908 if (p != NULL)
2909 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002910 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002912 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002913 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914 }
2915 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002916 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002918 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002919 if (n == -1)
2920 return FAIL;
2921
2922 win32_set_archive(name);
2923
2924 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925}
2926
2927/*
2928 * Set hidden flag for "name".
2929 */
2930 void
2931mch_hide(char_u *name)
2932{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002933 int attrs = win32_getattrs(name);
2934 if (attrs == -1)
2935 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002937 attrs |= FILE_ATTRIBUTE_HIDDEN;
2938 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939}
2940
2941/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01002942 * Return TRUE if file "name" exists and is hidden.
2943 */
2944 int
2945mch_ishidden(char_u *name)
2946{
2947 int f = win32_getattrs(name);
2948
2949 if (f == -1)
2950 return FALSE; /* file does not exist at all */
2951
2952 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
2953}
2954
2955/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 * return TRUE if "name" is a directory
2957 * return FALSE if "name" is not a directory or upon error
2958 */
2959 int
2960mch_isdir(char_u *name)
2961{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002962 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963
2964 if (f == -1)
2965 return FALSE; /* file does not exist at all */
2966
2967 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2968}
2969
2970/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01002971 * return TRUE if "name" is a directory, NOT a symlink to a directory
2972 * return FALSE if "name" is not a directory
2973 * return FALSE for error
2974 */
2975 int
2976mch_isrealdir(char_u *name)
2977{
2978 return mch_isdir(name) && !mch_is_symbolic_link(name);
2979}
2980
2981/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002982 * Create directory "name".
2983 * Return 0 on success, -1 on error.
2984 */
2985 int
2986mch_mkdir(char_u *name)
2987{
2988#ifdef FEAT_MBYTE
2989 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2990 {
2991 WCHAR *p;
2992 int retval;
2993
2994 p = enc_to_utf16(name, NULL);
2995 if (p == NULL)
2996 return -1;
2997 retval = _wmkdir(p);
2998 vim_free(p);
2999 return retval;
3000 }
3001#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003002 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003003}
3004
3005/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003006 * Delete directory "name".
3007 * Return 0 on success, -1 on error.
3008 */
3009 int
3010mch_rmdir(char_u *name)
3011{
3012#ifdef FEAT_MBYTE
3013 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3014 {
3015 WCHAR *p;
3016 int retval;
3017
3018 p = enc_to_utf16(name, NULL);
3019 if (p == NULL)
3020 return -1;
3021 retval = _wrmdir(p);
3022 vim_free(p);
3023 return retval;
3024 }
3025#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003026 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003027}
3028
3029/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003030 * Return TRUE if file "fname" has more than one link.
3031 */
3032 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003033mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003034{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003035 BY_HANDLE_FILE_INFORMATION info;
3036
3037 return win32_fileinfo(fname, &info) == FILEINFO_OK
3038 && info.nNumberOfLinks > 1;
3039}
3040
3041/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003042 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003043 */
3044 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003045mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003046{
3047 HANDLE hFind;
3048 int res = FALSE;
3049 WIN32_FIND_DATAA findDataA;
3050 DWORD fileFlags = 0, reparseTag = 0;
3051#ifdef FEAT_MBYTE
3052 WCHAR *wn = NULL;
3053 WIN32_FIND_DATAW findDataW;
3054
3055 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003056 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003057 if (wn != NULL)
3058 {
3059 hFind = FindFirstFileW(wn, &findDataW);
3060 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003061 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003062 {
3063 fileFlags = findDataW.dwFileAttributes;
3064 reparseTag = findDataW.dwReserved0;
3065 }
3066 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003067 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003068#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003069 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003070 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003071 if (hFind != INVALID_HANDLE_VALUE)
3072 {
3073 fileFlags = findDataA.dwFileAttributes;
3074 reparseTag = findDataA.dwReserved0;
3075 }
3076 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003077
3078 if (hFind != INVALID_HANDLE_VALUE)
3079 FindClose(hFind);
3080
3081 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003082 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3083 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003084 res = TRUE;
3085
3086 return res;
3087}
3088
3089/*
3090 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3091 * link.
3092 */
3093 int
3094mch_is_linked(char_u *fname)
3095{
3096 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3097 return TRUE;
3098 return FALSE;
3099}
3100
3101/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003102 * Get the by-handle-file-information for "fname".
3103 * Returns FILEINFO_OK when OK.
3104 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3105 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3106 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3107 */
3108 int
3109win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3110{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003111 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003112 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003113#ifdef FEAT_MBYTE
3114 WCHAR *wn = NULL;
3115
3116 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003117 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003118 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003119 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003120 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003121 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003122 if (wn != NULL)
3123 {
3124 hFile = CreateFileW(wn, /* file name */
3125 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003126 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003127 NULL, /* security descriptor */
3128 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003129 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003130 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003131 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003132 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003133 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003134#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003135 hFile = CreateFile((LPCSTR)fname, /* file name */
3136 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003137 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003138 NULL, /* security descriptor */
3139 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003140 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003141 NULL); /* handle to template file */
3142
3143 if (hFile != INVALID_HANDLE_VALUE)
3144 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003145 if (GetFileInformationByHandle(hFile, info) != 0)
3146 res = FILEINFO_OK;
3147 else
3148 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003149 CloseHandle(hFile);
3150 }
3151
Bram Moolenaar03f48552006-02-28 23:52:23 +00003152 return res;
3153}
3154
3155/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003156 * get file attributes for `name'
3157 * -1 : error
3158 * else FILE_ATTRIBUTE_* defined in winnt.h
3159 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003160 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003161win32_getattrs(char_u *name)
3162{
3163 int attr;
3164#ifdef FEAT_MBYTE
3165 WCHAR *p = NULL;
3166
3167 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3168 p = enc_to_utf16(name, NULL);
3169
3170 if (p != NULL)
3171 {
3172 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003173 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003174 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003175 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003176#endif
3177 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003178
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003179 return attr;
3180}
3181
3182/*
3183 * set file attributes for `name' to `attrs'
3184 *
3185 * return -1 for failure, 0 otherwise
3186 */
3187 static
3188 int
3189win32_setattrs(char_u *name, int attrs)
3190{
3191 int res;
3192#ifdef FEAT_MBYTE
3193 WCHAR *p = NULL;
3194
3195 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3196 p = enc_to_utf16(name, NULL);
3197
3198 if (p != NULL)
3199 {
3200 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003201 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003202 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003203 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003204#endif
3205 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003206
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003207 return res ? 0 : -1;
3208}
3209
3210/*
3211 * Set archive flag for "name".
3212 */
3213 static
3214 int
3215win32_set_archive(char_u *name)
3216{
3217 int attrs = win32_getattrs(name);
3218 if (attrs == -1)
3219 return -1;
3220
3221 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3222 return win32_setattrs(name, attrs);
3223}
3224
3225/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003226 * Return TRUE if file or directory "name" is writable (not readonly).
3227 * Strange semantics of Win32: a readonly directory is writable, but you can't
3228 * delete a file. Let's say this means it is writable.
3229 */
3230 int
3231mch_writable(char_u *name)
3232{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003233 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003234
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003235 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3236 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237}
3238
Bram Moolenaar071d4272004-06-13 20:20:40 +00003239/*
3240 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003241 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003242 * Return -1 if unknown.
3243 */
3244 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003245mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003247 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003248 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003249 char_u *p;
3250
3251 if (len >= _MAX_PATH) /* safety check */
3252 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003253 if (!use_path)
3254 {
3255 /* TODO: check if file is really executable. */
3256 return mch_getperm(name) != -1 && !mch_isdir(name);
3257 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003258
3259 /* If there already is an extension try using the name directly. Also do
3260 * this with a Unix-shell like 'shell'. */
3261 if (vim_strchr(gettail(name), '.') != NULL
3262 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003263 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003264 return TRUE;
3265
3266 /*
3267 * Loop over all extensions in $PATHEXT.
3268 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003269 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003270 p = mch_getenv("PATHEXT");
3271 if (p == NULL)
3272 p = (char_u *)".com;.exe;.bat;.cmd";
3273 while (*p)
3274 {
3275 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3276 {
3277 /* A single "." means no extension is added. */
3278 buf[len] = NUL;
3279 ++p;
3280 if (*p)
3281 ++p;
3282 }
3283 else
3284 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003285 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003286 return TRUE;
3287 }
3288 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003289}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290
3291/*
3292 * Check what "name" is:
3293 * NODE_NORMAL: file or directory (or doesn't exist)
3294 * NODE_WRITABLE: writable device, socket, fifo, etc.
3295 * NODE_OTHER: non-writable things
3296 */
3297 int
3298mch_nodetype(char_u *name)
3299{
3300 HANDLE hFile;
3301 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003302#ifdef FEAT_MBYTE
3303 WCHAR *wn = NULL;
3304#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003305
Bram Moolenaar043545e2006-10-10 16:44:07 +00003306 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3307 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3308 * here. */
3309 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3310 return NODE_WRITABLE;
3311
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003312#ifdef FEAT_MBYTE
3313 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003314 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003315
3316 if (wn != NULL)
3317 {
3318 hFile = CreateFileW(wn, /* file name */
3319 GENERIC_WRITE, /* access mode */
3320 0, /* share mode */
3321 NULL, /* security descriptor */
3322 OPEN_EXISTING, /* creation disposition */
3323 0, /* file attributes */
3324 NULL); /* handle to template file */
3325 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003326 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003327 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003328#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003329 hFile = CreateFile((LPCSTR)name, /* file name */
3330 GENERIC_WRITE, /* access mode */
3331 0, /* share mode */
3332 NULL, /* security descriptor */
3333 OPEN_EXISTING, /* creation disposition */
3334 0, /* file attributes */
3335 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336
3337 if (hFile == INVALID_HANDLE_VALUE)
3338 return NODE_NORMAL;
3339
3340 type = GetFileType(hFile);
3341 CloseHandle(hFile);
3342 if (type == FILE_TYPE_CHAR)
3343 return NODE_WRITABLE;
3344 if (type == FILE_TYPE_DISK)
3345 return NODE_NORMAL;
3346 return NODE_OTHER;
3347}
3348
3349#ifdef HAVE_ACL
3350struct my_acl
3351{
3352 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3353 PSID pSidOwner;
3354 PSID pSidGroup;
3355 PACL pDacl;
3356 PACL pSacl;
3357};
3358#endif
3359
3360/*
3361 * Return a pointer to the ACL of file "fname" in allocated memory.
3362 * Return NULL if the ACL is not available for whatever reason.
3363 */
3364 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003365mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003366{
3367#ifndef HAVE_ACL
3368 return (vim_acl_T)NULL;
3369#else
3370 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003371 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003372
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003373 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3374 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003375 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003376# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003377 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003378
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003379 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3380 wn = enc_to_utf16(fname, NULL);
3381 if (wn != NULL)
3382 {
3383 /* Try to retrieve the entire security descriptor. */
3384 err = GetNamedSecurityInfoW(
3385 wn, // Abstract filename
3386 SE_FILE_OBJECT, // File Object
3387 OWNER_SECURITY_INFORMATION |
3388 GROUP_SECURITY_INFORMATION |
3389 DACL_SECURITY_INFORMATION |
3390 SACL_SECURITY_INFORMATION,
3391 &p->pSidOwner, // Ownership information.
3392 &p->pSidGroup, // Group membership.
3393 &p->pDacl, // Discretionary information.
3394 &p->pSacl, // For auditing purposes.
3395 &p->pSecurityDescriptor);
3396 if (err == ERROR_ACCESS_DENIED ||
3397 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003398 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003399 /* Retrieve only DACL. */
3400 (void)GetNamedSecurityInfoW(
3401 wn,
3402 SE_FILE_OBJECT,
3403 DACL_SECURITY_INFORMATION,
3404 NULL,
3405 NULL,
3406 &p->pDacl,
3407 NULL,
3408 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003409 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003410 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003411 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003412 mch_free_acl((vim_acl_T)p);
3413 p = NULL;
3414 }
3415 vim_free(wn);
3416 }
3417 else
3418# endif
3419 {
3420 /* Try to retrieve the entire security descriptor. */
3421 err = GetNamedSecurityInfo(
3422 (LPSTR)fname, // Abstract filename
3423 SE_FILE_OBJECT, // File Object
3424 OWNER_SECURITY_INFORMATION |
3425 GROUP_SECURITY_INFORMATION |
3426 DACL_SECURITY_INFORMATION |
3427 SACL_SECURITY_INFORMATION,
3428 &p->pSidOwner, // Ownership information.
3429 &p->pSidGroup, // Group membership.
3430 &p->pDacl, // Discretionary information.
3431 &p->pSacl, // For auditing purposes.
3432 &p->pSecurityDescriptor);
3433 if (err == ERROR_ACCESS_DENIED ||
3434 err == ERROR_PRIVILEGE_NOT_HELD)
3435 {
3436 /* Retrieve only DACL. */
3437 (void)GetNamedSecurityInfo(
3438 (LPSTR)fname,
3439 SE_FILE_OBJECT,
3440 DACL_SECURITY_INFORMATION,
3441 NULL,
3442 NULL,
3443 &p->pDacl,
3444 NULL,
3445 &p->pSecurityDescriptor);
3446 }
3447 if (p->pSecurityDescriptor == NULL)
3448 {
3449 mch_free_acl((vim_acl_T)p);
3450 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451 }
3452 }
3453 }
3454
3455 return (vim_acl_T)p;
3456#endif
3457}
3458
Bram Moolenaar27515922013-06-29 15:36:26 +02003459#ifdef HAVE_ACL
3460/*
3461 * Check if "acl" contains inherited ACE.
3462 */
3463 static BOOL
3464is_acl_inherited(PACL acl)
3465{
3466 DWORD i;
3467 ACL_SIZE_INFORMATION acl_info;
3468 PACCESS_ALLOWED_ACE ace;
3469
3470 acl_info.AceCount = 0;
3471 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3472 for (i = 0; i < acl_info.AceCount; i++)
3473 {
3474 GetAce(acl, i, (LPVOID *)&ace);
3475 if (ace->Header.AceFlags & INHERITED_ACE)
3476 return TRUE;
3477 }
3478 return FALSE;
3479}
3480#endif
3481
Bram Moolenaar071d4272004-06-13 20:20:40 +00003482/*
3483 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3484 * Errors are ignored.
3485 * This must only be called with "acl" equal to what mch_get_acl() returned.
3486 */
3487 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003488mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489{
3490#ifdef HAVE_ACL
3491 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003492 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003494 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003495 {
3496# ifdef FEAT_MBYTE
3497 WCHAR *wn = NULL;
3498# endif
3499
3500 /* Set security flags */
3501 if (p->pSidOwner)
3502 sec_info |= OWNER_SECURITY_INFORMATION;
3503 if (p->pSidGroup)
3504 sec_info |= GROUP_SECURITY_INFORMATION;
3505 if (p->pDacl)
3506 {
3507 sec_info |= DACL_SECURITY_INFORMATION;
3508 /* Do not inherit its parent's DACL.
3509 * If the DACL is inherited, Cygwin permissions would be changed.
3510 */
3511 if (!is_acl_inherited(p->pDacl))
3512 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3513 }
3514 if (p->pSacl)
3515 sec_info |= SACL_SECURITY_INFORMATION;
3516
3517# ifdef FEAT_MBYTE
3518 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3519 wn = enc_to_utf16(fname, NULL);
3520 if (wn != NULL)
3521 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003522 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003523 wn, // Abstract filename
3524 SE_FILE_OBJECT, // File Object
3525 sec_info,
3526 p->pSidOwner, // Ownership information.
3527 p->pSidGroup, // Group membership.
3528 p->pDacl, // Discretionary information.
3529 p->pSacl // For auditing purposes.
3530 );
3531 vim_free(wn);
3532 }
3533 else
3534# endif
3535 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003536 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003537 (LPSTR)fname, // Abstract filename
3538 SE_FILE_OBJECT, // File Object
3539 sec_info,
3540 p->pSidOwner, // Ownership information.
3541 p->pSidGroup, // Group membership.
3542 p->pDacl, // Discretionary information.
3543 p->pSacl // For auditing purposes.
3544 );
3545 }
3546 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547#endif
3548}
3549
3550 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003551mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003552{
3553#ifdef HAVE_ACL
3554 struct my_acl *p = (struct my_acl *)acl;
3555
3556 if (p != NULL)
3557 {
3558 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3559 vim_free(p);
3560 }
3561#endif
3562}
3563
3564#ifndef FEAT_GUI_W32
3565
3566/*
3567 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3568 */
3569 static BOOL WINAPI
3570handler_routine(
3571 DWORD dwCtrlType)
3572{
3573 switch (dwCtrlType)
3574 {
3575 case CTRL_C_EVENT:
3576 if (ctrl_c_interrupts)
3577 g_fCtrlCPressed = TRUE;
3578 return TRUE;
3579
3580 case CTRL_BREAK_EVENT:
3581 g_fCBrkPressed = TRUE;
3582 return TRUE;
3583
3584 /* fatal events: shut down gracefully */
3585 case CTRL_CLOSE_EVENT:
3586 case CTRL_LOGOFF_EVENT:
3587 case CTRL_SHUTDOWN_EVENT:
3588 windgoto((int)Rows - 1, 0);
3589 g_fForceExit = TRUE;
3590
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003591 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003592 (dwCtrlType == CTRL_CLOSE_EVENT
3593 ? _("close")
3594 : dwCtrlType == CTRL_LOGOFF_EVENT
3595 ? _("logoff")
3596 : _("shutdown")));
3597#ifdef DEBUG
3598 OutputDebugString(IObuff);
3599#endif
3600
3601 preserve_exit(); /* output IObuff, preserve files and exit */
3602
3603 return TRUE; /* not reached */
3604
3605 default:
3606 return FALSE;
3607 }
3608}
3609
3610
3611/*
3612 * set the tty in (raw) ? "raw" : "cooked" mode
3613 */
3614 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003615mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003616{
3617 DWORD cmodein;
3618 DWORD cmodeout;
3619 BOOL bEnableHandler;
3620
3621 GetConsoleMode(g_hConIn, &cmodein);
3622 GetConsoleMode(g_hConOut, &cmodeout);
3623 if (tmode == TMODE_RAW)
3624 {
3625 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3626 ENABLE_ECHO_INPUT);
3627#ifdef FEAT_MOUSE
3628 if (g_fMouseActive)
3629 cmodein |= ENABLE_MOUSE_INPUT;
3630#endif
3631 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3632 bEnableHandler = TRUE;
3633 }
3634 else /* cooked */
3635 {
3636 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3637 ENABLE_ECHO_INPUT);
3638 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3639 bEnableHandler = FALSE;
3640 }
3641 SetConsoleMode(g_hConIn, cmodein);
3642 SetConsoleMode(g_hConOut, cmodeout);
3643 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3644
3645#ifdef MCH_WRITE_DUMP
3646 if (fdDump)
3647 {
3648 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3649 tmode == TMODE_RAW ? "raw" :
3650 tmode == TMODE_COOK ? "cooked" : "normal",
3651 cmodein, cmodeout);
3652 fflush(fdDump);
3653 }
3654#endif
3655}
3656
3657
3658/*
3659 * Get the size of the current window in `Rows' and `Columns'
3660 * Return OK when size could be determined, FAIL otherwise.
3661 */
3662 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003663mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664{
3665 CONSOLE_SCREEN_BUFFER_INFO csbi;
3666
3667 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3668 {
3669 /*
3670 * For some reason, we are trying to get the screen dimensions
3671 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3672 * variables are really intended to mean the size of Vim screen
3673 * while in termcap mode.
3674 */
3675 Rows = g_cbTermcap.Info.dwSize.Y;
3676 Columns = g_cbTermcap.Info.dwSize.X;
3677 }
3678 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3679 {
3680 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3681 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3682 }
3683 else
3684 {
3685 Rows = 25;
3686 Columns = 80;
3687 }
3688 return OK;
3689}
3690
3691/*
3692 * Set a console window to `xSize' * `ySize'
3693 */
3694 static void
3695ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003696 HANDLE hConsole,
3697 int xSize,
3698 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003699{
3700 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3701 SMALL_RECT srWindowRect; /* hold the new console size */
3702 COORD coordScreen;
3703
3704#ifdef MCH_WRITE_DUMP
3705 if (fdDump)
3706 {
3707 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3708 fflush(fdDump);
3709 }
3710#endif
3711
3712 /* get the largest size we can size the console window to */
3713 coordScreen = GetLargestConsoleWindowSize(hConsole);
3714
3715 /* define the new console window size and scroll position */
3716 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3717 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3718 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3719
3720 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3721 {
3722 int sx, sy;
3723
3724 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3725 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3726 if (sy < ySize || sx < xSize)
3727 {
3728 /*
3729 * Increasing number of lines/columns, do buffer first.
3730 * Use the maximal size in x and y direction.
3731 */
3732 if (sy < ySize)
3733 coordScreen.Y = ySize;
3734 else
3735 coordScreen.Y = sy;
3736 if (sx < xSize)
3737 coordScreen.X = xSize;
3738 else
3739 coordScreen.X = sx;
3740 SetConsoleScreenBufferSize(hConsole, coordScreen);
3741 }
3742 }
3743
3744 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3745 {
3746#ifdef MCH_WRITE_DUMP
3747 if (fdDump)
3748 {
3749 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3750 GetLastError());
3751 fflush(fdDump);
3752 }
3753#endif
3754 }
3755
3756 /* define the new console buffer size */
3757 coordScreen.X = xSize;
3758 coordScreen.Y = ySize;
3759
3760 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3761 {
3762#ifdef MCH_WRITE_DUMP
3763 if (fdDump)
3764 {
3765 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3766 GetLastError());
3767 fflush(fdDump);
3768 }
3769#endif
3770 }
3771}
3772
3773
3774/*
3775 * Set the console window to `Rows' * `Columns'
3776 */
3777 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003778mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779{
3780 COORD coordScreen;
3781
3782 /* Don't change window size while still starting up */
3783 if (suppress_winsize != 0)
3784 {
3785 suppress_winsize = 2;
3786 return;
3787 }
3788
3789 if (term_console)
3790 {
3791 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3792
3793 /* Clamp Rows and Columns to reasonable values */
3794 if (Rows > coordScreen.Y)
3795 Rows = coordScreen.Y;
3796 if (Columns > coordScreen.X)
3797 Columns = coordScreen.X;
3798
3799 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3800 }
3801}
3802
3803/*
3804 * Rows and/or Columns has changed.
3805 */
3806 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003807mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003808{
3809 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3810}
3811
3812
3813/*
3814 * Called when started up, to set the winsize that was delayed.
3815 */
3816 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003817mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003818{
3819 if (suppress_winsize == 2)
3820 {
3821 suppress_winsize = 0;
3822 mch_set_shellsize();
3823 shell_resized();
3824 }
3825 suppress_winsize = 0;
3826}
3827#endif /* FEAT_GUI_W32 */
3828
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003829 static BOOL
3830vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003831 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003832 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003833 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003834 STARTUPINFO *si,
3835 PROCESS_INFORMATION *pi)
3836{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003837#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003838 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3839 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003840 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003841
3842 if (wcmd != NULL)
3843 {
3844 BOOL ret;
3845 ret = CreateProcessW(
3846 NULL, /* Executable name */
3847 wcmd, /* Command to execute */
3848 NULL, /* Process security attributes */
3849 NULL, /* Thread security attributes */
3850 inherit_handles, /* Inherit handles */
3851 flags, /* Creation flags */
3852 NULL, /* Environment */
3853 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003854 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003855 pi); /* Process information */
3856 vim_free(wcmd);
3857 return ret;
3858 }
3859 }
3860#endif
3861 return CreateProcess(
3862 NULL, /* Executable name */
3863 cmd, /* Command to execute */
3864 NULL, /* Process security attributes */
3865 NULL, /* Thread security attributes */
3866 inherit_handles, /* Inherit handles */
3867 flags, /* Creation flags */
3868 NULL, /* Environment */
3869 NULL, /* Current directory */
3870 si, /* Startup information */
3871 pi); /* Process information */
3872}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003873
3874
3875#if defined(FEAT_GUI_W32) || defined(PROTO)
3876
3877/*
3878 * Specialised version of system() for Win32 GUI mode.
3879 * This version proceeds as follows:
3880 * 1. Create a console window for use by the subprocess
3881 * 2. Run the subprocess (it gets the allocated console by default)
3882 * 3. Wait for the subprocess to terminate and get its exit code
3883 * 4. Prompt the user to press a key to close the console window
3884 */
3885 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003886mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003887{
3888 STARTUPINFO si;
3889 PROCESS_INFORMATION pi;
3890 DWORD ret = 0;
3891 HWND hwnd = GetFocus();
3892
3893 si.cb = sizeof(si);
3894 si.lpReserved = NULL;
3895 si.lpDesktop = NULL;
3896 si.lpTitle = NULL;
3897 si.dwFlags = STARTF_USESHOWWINDOW;
3898 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003899 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003900 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003902 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003903 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003904 else
3905 si.wShowWindow = SW_SHOWNORMAL;
3906 si.cbReserved2 = 0;
3907 si.lpReserved2 = NULL;
3908
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003910 vim_create_process(cmd, FALSE,
3911 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912
3913 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003914 {
3915#ifdef FEAT_GUI
3916 int delay = 1;
3917
3918 /* Keep updating the window while waiting for the shell to finish. */
3919 for (;;)
3920 {
3921 MSG msg;
3922
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003923 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003924 {
3925 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003926 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003927 delay = 1;
3928 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929 }
3930 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3931 break;
3932
3933 /* We start waiting for a very short time and then increase it, so
3934 * that we respond quickly when the process is quick, and don't
3935 * consume too much overhead when it's slow. */
3936 if (delay < 50)
3937 delay += 10;
3938 }
3939#else
3940 WaitForSingleObject(pi.hProcess, INFINITE);
3941#endif
3942
3943 /* Get the command exit code */
3944 GetExitCodeProcess(pi.hProcess, &ret);
3945 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946
3947 /* Close the handles to the subprocess, so that it goes away */
3948 CloseHandle(pi.hThread);
3949 CloseHandle(pi.hProcess);
3950
3951 /* Try to get input focus back. Doesn't always work though. */
3952 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3953
3954 return ret;
3955}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003956
3957/*
3958 * Thread launched by the gui to send the current buffer data to the
3959 * process. This way avoid to hang up vim totally if the children
3960 * process take a long time to process the lines.
3961 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02003962 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003963sub_process_writer(LPVOID param)
3964{
3965 HANDLE g_hChildStd_IN_Wr = param;
3966 linenr_T lnum = curbuf->b_op_start.lnum;
3967 DWORD len = 0;
3968 DWORD l;
3969 char_u *lp = ml_get(lnum);
3970 char_u *s;
3971 int written = 0;
3972
3973 for (;;)
3974 {
3975 l = (DWORD)STRLEN(lp + written);
3976 if (l == 0)
3977 len = 0;
3978 else if (lp[written] == NL)
3979 {
3980 /* NL -> NUL translation */
3981 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3982 }
3983 else
3984 {
3985 s = vim_strchr(lp + written, NL);
3986 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3987 s == NULL ? l : (DWORD)(s - (lp + written)),
3988 &len, NULL);
3989 }
3990 if (len == (int)l)
3991 {
3992 /* Finished a line, add a NL, unless this line should not have
3993 * one. */
3994 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02003995 || (!curbuf->b_p_bin
3996 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003997 || (lnum != curbuf->b_no_eol_lnum
3998 && (lnum != curbuf->b_ml.ml_line_count
3999 || curbuf->b_p_eol)))
4000 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004001 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004002 }
4003
4004 ++lnum;
4005 if (lnum > curbuf->b_op_end.lnum)
4006 break;
4007
4008 lp = ml_get(lnum);
4009 written = 0;
4010 }
4011 else if (len > 0)
4012 written += len;
4013 }
4014
4015 /* finished all the lines, close pipe */
4016 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004017 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004018}
4019
4020
4021# define BUFLEN 100 /* length for buffer, stolen from unix version */
4022
4023/*
4024 * This function read from the children's stdout and write the
4025 * data on screen or in the buffer accordingly.
4026 */
4027 static void
4028dump_pipe(int options,
4029 HANDLE g_hChildStd_OUT_Rd,
4030 garray_T *ga,
4031 char_u buffer[],
4032 DWORD *buffer_off)
4033{
4034 DWORD availableBytes = 0;
4035 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004036 int ret;
4037 DWORD len;
4038 DWORD toRead;
4039 int repeatCount;
4040
4041 /* we query the pipe to see if there is any data to read
4042 * to avoid to perform a blocking read */
4043 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4044 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004045 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004046 NULL, /* number of read bytes */
4047 &availableBytes, /* available bytes total */
4048 NULL); /* byteLeft */
4049
4050 repeatCount = 0;
4051 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004052 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004053 {
4054 repeatCount++;
4055 toRead =
4056# ifdef FEAT_MBYTE
4057 (DWORD)(BUFLEN - *buffer_off);
4058# else
4059 (DWORD)BUFLEN;
4060# endif
4061 toRead = availableBytes < toRead ? availableBytes : toRead;
4062 ReadFile(g_hChildStd_OUT_Rd, buffer
4063# ifdef FEAT_MBYTE
4064 + *buffer_off, toRead
4065# else
4066 , toRead
4067# endif
4068 , &len, NULL);
4069
4070 /* If we haven't read anything, there is a problem */
4071 if (len == 0)
4072 break;
4073
4074 availableBytes -= len;
4075
4076 if (options & SHELL_READ)
4077 {
4078 /* Do NUL -> NL translation, append NL separated
4079 * lines to the current buffer. */
4080 for (i = 0; i < len; ++i)
4081 {
4082 if (buffer[i] == NL)
4083 append_ga_line(ga);
4084 else if (buffer[i] == NUL)
4085 ga_append(ga, NL);
4086 else
4087 ga_append(ga, buffer[i]);
4088 }
4089 }
4090# ifdef FEAT_MBYTE
4091 else if (has_mbyte)
4092 {
4093 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004094 int c;
4095 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004096
4097 len += *buffer_off;
4098 buffer[len] = NUL;
4099
4100 /* Check if the last character in buffer[] is
4101 * incomplete, keep these bytes for the next
4102 * round. */
4103 for (p = buffer; p < buffer + len; p += l)
4104 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004105 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004106 if (l == 0)
4107 l = 1; /* NUL byte? */
4108 else if (MB_BYTE2LEN(*p) != l)
4109 break;
4110 }
4111 if (p == buffer) /* no complete character */
4112 {
4113 /* avoid getting stuck at an illegal byte */
4114 if (len >= 12)
4115 ++p;
4116 else
4117 {
4118 *buffer_off = len;
4119 return;
4120 }
4121 }
4122 c = *p;
4123 *p = NUL;
4124 msg_puts(buffer);
4125 if (p < buffer + len)
4126 {
4127 *p = c;
4128 *buffer_off = (DWORD)((buffer + len) - p);
4129 mch_memmove(buffer, p, *buffer_off);
4130 return;
4131 }
4132 *buffer_off = 0;
4133 }
4134# endif /* FEAT_MBYTE */
4135 else
4136 {
4137 buffer[len] = NUL;
4138 msg_puts(buffer);
4139 }
4140
4141 windgoto(msg_row, msg_col);
4142 cursor_on();
4143 out_flush();
4144 }
4145}
4146
4147/*
4148 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4149 * for communication and doesn't open any new window.
4150 */
4151 static int
4152mch_system_piped(char *cmd, int options)
4153{
4154 STARTUPINFO si;
4155 PROCESS_INFORMATION pi;
4156 DWORD ret = 0;
4157
4158 HANDLE g_hChildStd_IN_Rd = NULL;
4159 HANDLE g_hChildStd_IN_Wr = NULL;
4160 HANDLE g_hChildStd_OUT_Rd = NULL;
4161 HANDLE g_hChildStd_OUT_Wr = NULL;
4162
4163 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4164 DWORD len;
4165
4166 /* buffer used to receive keys */
4167 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4168 int ta_len = 0; /* valid bytes in ta_buf[] */
4169
4170 DWORD i;
4171 int c;
4172 int noread_cnt = 0;
4173 garray_T ga;
4174 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004175 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004176 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004177
4178 SECURITY_ATTRIBUTES saAttr;
4179
4180 /* Set the bInheritHandle flag so pipe handles are inherited. */
4181 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4182 saAttr.bInheritHandle = TRUE;
4183 saAttr.lpSecurityDescriptor = NULL;
4184
4185 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4186 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004187 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004188 /* Create a pipe for the child process's STDIN. */
4189 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4190 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004191 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004192 {
4193 CloseHandle(g_hChildStd_IN_Rd);
4194 CloseHandle(g_hChildStd_IN_Wr);
4195 CloseHandle(g_hChildStd_OUT_Rd);
4196 CloseHandle(g_hChildStd_OUT_Wr);
4197 MSG_PUTS(_("\nCannot create pipes\n"));
4198 }
4199
4200 si.cb = sizeof(si);
4201 si.lpReserved = NULL;
4202 si.lpDesktop = NULL;
4203 si.lpTitle = NULL;
4204 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4205
4206 /* set-up our file redirection */
4207 si.hStdError = g_hChildStd_OUT_Wr;
4208 si.hStdOutput = g_hChildStd_OUT_Wr;
4209 si.hStdInput = g_hChildStd_IN_Rd;
4210 si.wShowWindow = SW_HIDE;
4211 si.cbReserved2 = 0;
4212 si.lpReserved2 = NULL;
4213
4214 if (options & SHELL_READ)
4215 ga_init2(&ga, 1, BUFLEN);
4216
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004217 if (cmd != NULL)
4218 {
4219 p = (char *)vim_strsave((char_u *)cmd);
4220 if (p != NULL)
4221 unescape_shellxquote((char_u *)p, p_sxe);
4222 else
4223 p = cmd;
4224 }
4225
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004226 /* Now, run the command.
4227 * About "Inherit handles" being TRUE: this command can be litigious,
4228 * handle inheritance was deactivated for pending temp file, but, if we
4229 * deactivate it, the pipes don't work for some reason. */
4230 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004231
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004232 if (p != cmd)
4233 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004234
4235 /* Close our unused side of the pipes */
4236 CloseHandle(g_hChildStd_IN_Rd);
4237 CloseHandle(g_hChildStd_OUT_Wr);
4238
4239 if (options & SHELL_WRITE)
4240 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004241 HANDLE thread = (HANDLE)
4242 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004243 0, /* default stack size */
4244 sub_process_writer, /* function to be executed */
4245 g_hChildStd_IN_Wr, /* parameter */
4246 0, /* creation flag, start immediately */
4247 NULL); /* we don't care about thread id */
4248 CloseHandle(thread);
4249 g_hChildStd_IN_Wr = NULL;
4250 }
4251
4252 /* Keep updating the window while waiting for the shell to finish. */
4253 for (;;)
4254 {
4255 MSG msg;
4256
Bram Moolenaar175d0702013-12-11 18:36:33 +01004257 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004258 {
4259 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004260 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004261 }
4262
4263 /* write pipe information in the window */
4264 if ((options & (SHELL_READ|SHELL_WRITE))
4265# ifdef FEAT_GUI
4266 || gui.in_use
4267# endif
4268 )
4269 {
4270 len = 0;
4271 if (!(options & SHELL_EXPAND)
4272 && ((options &
4273 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4274 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4275# ifdef FEAT_GUI
4276 || gui.in_use
4277# endif
4278 )
4279 && (ta_len > 0 || noread_cnt > 4))
4280 {
4281 if (ta_len == 0)
4282 {
4283 /* Get extra characters when we don't have any. Reset the
4284 * counter and timer. */
4285 noread_cnt = 0;
4286# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4287 gettimeofday(&start_tv, NULL);
4288# endif
4289 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4290 }
4291 if (ta_len > 0 || len > 0)
4292 {
4293 /*
4294 * For pipes: Check for CTRL-C: send interrupt signal to
4295 * child. Check for CTRL-D: EOF, close pipe to child.
4296 */
4297 if (len == 1 && cmd != NULL)
4298 {
4299 if (ta_buf[ta_len] == Ctrl_C)
4300 {
4301 /* Learn what exit code is expected, for
4302 * now put 9 as SIGKILL */
4303 TerminateProcess(pi.hProcess, 9);
4304 }
4305 if (ta_buf[ta_len] == Ctrl_D)
4306 {
4307 CloseHandle(g_hChildStd_IN_Wr);
4308 g_hChildStd_IN_Wr = NULL;
4309 }
4310 }
4311
4312 /* replace K_BS by <BS> and K_DEL by <DEL> */
4313 for (i = ta_len; i < ta_len + len; ++i)
4314 {
4315 if (ta_buf[i] == CSI && len - i > 2)
4316 {
4317 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4318 if (c == K_DEL || c == K_KDEL || c == K_BS)
4319 {
4320 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4321 (size_t)(len - i - 2));
4322 if (c == K_DEL || c == K_KDEL)
4323 ta_buf[i] = DEL;
4324 else
4325 ta_buf[i] = Ctrl_H;
4326 len -= 2;
4327 }
4328 }
4329 else if (ta_buf[i] == '\r')
4330 ta_buf[i] = '\n';
4331# ifdef FEAT_MBYTE
4332 if (has_mbyte)
4333 i += (*mb_ptr2len_len)(ta_buf + i,
4334 ta_len + len - i) - 1;
4335# endif
4336 }
4337
4338 /*
4339 * For pipes: echo the typed characters. For a pty this
4340 * does not seem to work.
4341 */
4342 for (i = ta_len; i < ta_len + len; ++i)
4343 {
4344 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4345 msg_putchar(ta_buf[i]);
4346# ifdef FEAT_MBYTE
4347 else if (has_mbyte)
4348 {
4349 int l = (*mb_ptr2len)(ta_buf + i);
4350
4351 msg_outtrans_len(ta_buf + i, l);
4352 i += l - 1;
4353 }
4354# endif
4355 else
4356 msg_outtrans_len(ta_buf + i, 1);
4357 }
4358 windgoto(msg_row, msg_col);
4359 out_flush();
4360
4361 ta_len += len;
4362
4363 /*
4364 * Write the characters to the child, unless EOF has been
4365 * typed for pipes. Write one character at a time, to
4366 * avoid losing too much typeahead. When writing buffer
4367 * lines, drop the typed characters (only check for
4368 * CTRL-C).
4369 */
4370 if (options & SHELL_WRITE)
4371 ta_len = 0;
4372 else if (g_hChildStd_IN_Wr != NULL)
4373 {
4374 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4375 1, &len, NULL);
4376 // if we are typing in, we want to keep things reactive
4377 delay = 1;
4378 if (len > 0)
4379 {
4380 ta_len -= len;
4381 mch_memmove(ta_buf, ta_buf + len, ta_len);
4382 }
4383 }
4384 }
4385 }
4386 }
4387
4388 if (ta_len)
4389 ui_inchar_undo(ta_buf, ta_len);
4390
4391 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4392 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004393 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004394 break;
4395 }
4396
4397 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004398 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004399
4400 /* We start waiting for a very short time and then increase it, so
4401 * that we respond quickly when the process is quick, and don't
4402 * consume too much overhead when it's slow. */
4403 if (delay < 50)
4404 delay += 10;
4405 }
4406
4407 /* Close the pipe */
4408 CloseHandle(g_hChildStd_OUT_Rd);
4409 if (g_hChildStd_IN_Wr != NULL)
4410 CloseHandle(g_hChildStd_IN_Wr);
4411
4412 WaitForSingleObject(pi.hProcess, INFINITE);
4413
4414 /* Get the command exit code */
4415 GetExitCodeProcess(pi.hProcess, &ret);
4416
4417 if (options & SHELL_READ)
4418 {
4419 if (ga.ga_len > 0)
4420 {
4421 append_ga_line(&ga);
4422 /* remember that the NL was missing */
4423 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4424 }
4425 else
4426 curbuf->b_no_eol_lnum = 0;
4427 ga_clear(&ga);
4428 }
4429
4430 /* Close the handles to the subprocess, so that it goes away */
4431 CloseHandle(pi.hThread);
4432 CloseHandle(pi.hProcess);
4433
4434 return ret;
4435}
4436
4437 static int
4438mch_system(char *cmd, int options)
4439{
4440 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004441 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004442 return mch_system_piped(cmd, options);
4443 else
4444 return mch_system_classic(cmd, options);
4445}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446#else
4447
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004448# ifdef FEAT_MBYTE
4449 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004450mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004451{
4452 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4453 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004454 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004455 if (wcmd != NULL)
4456 {
4457 int ret = _wsystem(wcmd);
4458 vim_free(wcmd);
4459 return ret;
4460 }
4461 }
4462 return system(cmd);
4463}
4464# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004465# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004466# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467
4468#endif
4469
4470/*
4471 * Either execute a command by calling the shell or start a new shell
4472 */
4473 int
4474mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004475 char_u *cmd,
4476 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477{
4478 int x = 0;
4479 int tmode = cur_tmode;
4480#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004481 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004482# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004483 int did_set_title = FALSE;
4484
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004485 /* Change the title to reflect that we are in a subshell. */
4486 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4487 {
4488 WCHAR szShellTitle[512];
4489
4490 if (GetConsoleTitleW(szShellTitle,
4491 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4492 {
4493 if (cmd == NULL)
4494 wcscat(szShellTitle, L" :sh");
4495 else
4496 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004497 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004498
4499 if (wn != NULL)
4500 {
4501 wcscat(szShellTitle, L" - !");
4502 if ((wcslen(szShellTitle) + wcslen(wn) <
4503 sizeof(szShellTitle)/sizeof(WCHAR)))
4504 wcscat(szShellTitle, wn);
4505 SetConsoleTitleW(szShellTitle);
4506 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004507 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004508 }
4509 }
4510 }
4511 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004512 if (!did_set_title)
4513# endif
4514 /* Change the title to reflect that we are in a subshell. */
4515 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004517 if (cmd == NULL)
4518 strcat(szShellTitle, " :sh");
4519 else
4520 {
4521 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004522 if ((strlen(szShellTitle) + strlen((char *)cmd)
4523 < sizeof(szShellTitle)))
4524 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004525 }
4526 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004527 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004528#endif
4529
4530 out_flush();
4531
4532#ifdef MCH_WRITE_DUMP
4533 if (fdDump)
4534 {
4535 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4536 fflush(fdDump);
4537 }
4538#endif
4539
4540 /*
4541 * Catch all deadly signals while running the external command, because a
4542 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4543 */
4544 signal(SIGINT, SIG_IGN);
4545#if defined(__GNUC__) && !defined(__MINGW32__)
4546 signal(SIGKILL, SIG_IGN);
4547#else
4548 signal(SIGBREAK, SIG_IGN);
4549#endif
4550 signal(SIGILL, SIG_IGN);
4551 signal(SIGFPE, SIG_IGN);
4552 signal(SIGSEGV, SIG_IGN);
4553 signal(SIGTERM, SIG_IGN);
4554 signal(SIGABRT, SIG_IGN);
4555
4556 if (options & SHELL_COOKED)
4557 settmode(TMODE_COOK); /* set to normal mode */
4558
4559 if (cmd == NULL)
4560 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004561 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004562 }
4563 else
4564 {
4565 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004566 char_u *newcmd = NULL;
4567 char_u *cmdbase = cmd;
4568 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004569
4570 /* Skip a leading ", ( and "(. */
4571 if (*cmdbase == '"' )
4572 ++cmdbase;
4573 if (*cmdbase == '(')
4574 ++cmdbase;
4575
4576 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4577 {
4578 STARTUPINFO si;
4579 PROCESS_INFORMATION pi;
4580 DWORD flags = CREATE_NEW_CONSOLE;
4581 char_u *p;
4582
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004583 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004584 si.cb = sizeof(si);
4585 si.lpReserved = NULL;
4586 si.lpDesktop = NULL;
4587 si.lpTitle = NULL;
4588 si.dwFlags = 0;
4589 si.cbReserved2 = 0;
4590 si.lpReserved2 = NULL;
4591
4592 cmdbase = skipwhite(cmdbase + 5);
4593 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4594 && vim_iswhite(cmdbase[4]))
4595 {
4596 cmdbase = skipwhite(cmdbase + 4);
4597 si.dwFlags = STARTF_USESHOWWINDOW;
4598 si.wShowWindow = SW_SHOWMINNOACTIVE;
4599 }
4600 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4601 && vim_iswhite(cmdbase[2]))
4602 {
4603 cmdbase = skipwhite(cmdbase + 2);
4604 flags = CREATE_NO_WINDOW;
4605 si.dwFlags = STARTF_USESTDHANDLES;
4606 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004607 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004608 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004609 NULL, // Security att.
4610 OPEN_EXISTING, // Open flags
4611 FILE_ATTRIBUTE_NORMAL, // File att.
4612 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004613 si.hStdOutput = si.hStdInput;
4614 si.hStdError = si.hStdInput;
4615 }
4616
4617 /* Remove a trailing ", ) and )" if they have a match
4618 * at the start of the command. */
4619 if (cmdbase > cmd)
4620 {
4621 p = cmdbase + STRLEN(cmdbase);
4622 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4623 *--p = NUL;
4624 if (p > cmdbase && p[-1] == ')'
4625 && (*cmd =='(' || cmd[1] == '('))
4626 *--p = NUL;
4627 }
4628
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004629 newcmd = cmdbase;
4630 unescape_shellxquote(cmdbase, p_sxe);
4631
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004632 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004633 * If creating new console, arguments are passed to the
4634 * 'cmd.exe' as-is. If it's not, arguments are not treated
4635 * correctly for current 'cmd.exe'. So unescape characters in
4636 * shellxescape except '|' for avoiding to be treated as
4637 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004638 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004639 if (flags != CREATE_NEW_CONSOLE)
4640 {
4641 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004642 char_u *cmd_shell = mch_getenv("COMSPEC");
4643
4644 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004645 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004646
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004647 subcmd = vim_strsave_escaped_ext(cmdbase,
4648 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004649 if (subcmd != NULL)
4650 {
4651 /* make "cmd.exe /c arguments" */
4652 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004653 newcmd = lalloc(cmdlen, TRUE);
4654 if (newcmd != NULL)
4655 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004656 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004657 else
4658 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004659 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004660 }
4661 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004662
4663 /*
4664 * Now, start the command as a process, so that it doesn't
4665 * inherit our handles which causes unpleasant dangling swap
4666 * files if we exit before the spawned process
4667 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004668 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004669 x = 0;
4670 else
4671 {
4672 x = -1;
4673#ifdef FEAT_GUI_W32
4674 EMSG(_("E371: Command not found"));
4675#endif
4676 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004677
4678 if (newcmd != cmdbase)
4679 vim_free(newcmd);
4680
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004681 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004682 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004683 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004684 CloseHandle(si.hStdInput);
4685 }
4686 /* Close the handles to the subprocess, so that it goes away */
4687 CloseHandle(pi.hThread);
4688 CloseHandle(pi.hProcess);
4689 }
4690 else
4691 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004692 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004693#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004694 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004695#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004696 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4697
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004698 newcmd = lalloc(cmdlen, TRUE);
4699 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004700 {
4701#if defined(FEAT_GUI_W32)
4702 if (need_vimrun_warning)
4703 {
4704 MessageBox(NULL,
4705 _("VIMRUN.EXE not found in your $PATH.\n"
4706 "External commands will not pause after completion.\n"
4707 "See :help win32-vimrun for more information."),
4708 _("Vim Warning"),
4709 MB_ICONWARNING);
4710 need_vimrun_warning = FALSE;
4711 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004712 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004713 /* Use vimrun to execute the command. It opens a console
4714 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004715 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004716 vimrun_path,
4717 (msg_silent != 0 || (options & SHELL_DOOUT))
4718 ? "-s " : "",
4719 p_sh, p_shcf, cmd);
4720 else
4721#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004722 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004723 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004725 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004726 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004727 }
4728 }
4729
4730 if (tmode == TMODE_RAW)
4731 settmode(TMODE_RAW); /* set to raw mode */
4732
4733 /* Print the return value, unless "vimrun" was used. */
4734 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4735#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004736 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737#endif
4738 )
4739 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004740 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741 msg_putchar('\n');
4742 }
4743#ifdef FEAT_TITLE
4744 resettitle();
4745#endif
4746
4747 signal(SIGINT, SIG_DFL);
4748#if defined(__GNUC__) && !defined(__MINGW32__)
4749 signal(SIGKILL, SIG_DFL);
4750#else
4751 signal(SIGBREAK, SIG_DFL);
4752#endif
4753 signal(SIGILL, SIG_DFL);
4754 signal(SIGFPE, SIG_DFL);
4755 signal(SIGSEGV, SIG_DFL);
4756 signal(SIGTERM, SIG_DFL);
4757 signal(SIGABRT, SIG_DFL);
4758
4759 return x;
4760}
4761
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004762#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004763 static HANDLE
4764job_io_file_open(
4765 char_u *fname,
4766 DWORD dwDesiredAccess,
4767 DWORD dwShareMode,
4768 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4769 DWORD dwCreationDisposition,
4770 DWORD dwFlagsAndAttributes)
4771{
4772 HANDLE h;
4773# ifdef FEAT_MBYTE
4774 WCHAR *wn = NULL;
4775 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4776 {
4777 wn = enc_to_utf16(fname, NULL);
4778 if (wn != NULL)
4779 {
4780 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4781 lpSecurityAttributes, dwCreationDisposition,
4782 dwFlagsAndAttributes, NULL);
4783 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004784 }
4785 }
4786 if (wn == NULL)
4787# endif
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004788 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
4789 lpSecurityAttributes, dwCreationDisposition,
4790 dwFlagsAndAttributes, NULL);
4791 return h;
4792}
4793
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004794 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01004795mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004796{
4797 STARTUPINFO si;
4798 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004799 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004800 SECURITY_ATTRIBUTES saAttr;
4801 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01004802 HANDLE ifd[2];
4803 HANDLE ofd[2];
4804 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004805
4806 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
4807 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
4808 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
4809 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
4810 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
4811 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
4812 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
4813
4814 if (use_out_for_err && use_null_for_out)
4815 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01004816
4817 ifd[0] = INVALID_HANDLE_VALUE;
4818 ifd[1] = INVALID_HANDLE_VALUE;
4819 ofd[0] = INVALID_HANDLE_VALUE;
4820 ofd[1] = INVALID_HANDLE_VALUE;
4821 efd[0] = INVALID_HANDLE_VALUE;
4822 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004823
Bram Moolenaar76467df2016-02-12 19:30:26 +01004824 jo = CreateJobObject(NULL, NULL);
4825 if (jo == NULL)
4826 {
4827 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004828 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004829 }
4830
4831 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004832 ZeroMemory(&si, sizeof(si));
4833 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01004834 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004835 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004836
Bram Moolenaard8070362016-02-15 21:56:54 +01004837 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4838 saAttr.bInheritHandle = TRUE;
4839 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004840
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004841 if (use_file_for_in)
4842 {
4843 char_u *fname = options->jo_io_name[PART_IN];
4844
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004845 ifd[0] = job_io_file_open(fname, GENERIC_READ,
4846 FILE_SHARE_READ | FILE_SHARE_WRITE,
4847 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
4848 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01004849 {
4850 EMSG2(_(e_notopen), fname);
4851 goto failed;
4852 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004853 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004854 else if (!use_null_for_in &&
4855 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004856 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004857 goto failed;
4858
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004859 if (use_file_for_out)
4860 {
4861 char_u *fname = options->jo_io_name[PART_OUT];
4862
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004863 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
4864 FILE_SHARE_READ | FILE_SHARE_WRITE,
4865 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
4866 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004867 {
4868 EMSG2(_(e_notopen), fname);
4869 goto failed;
4870 }
4871 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004872 else if (!use_null_for_out &&
4873 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004874 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004875 goto failed;
4876
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004877 if (use_file_for_err)
4878 {
4879 char_u *fname = options->jo_io_name[PART_ERR];
4880
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004881 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
4882 FILE_SHARE_READ | FILE_SHARE_WRITE,
4883 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
4884 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004885 {
4886 EMSG2(_(e_notopen), fname);
4887 goto failed;
4888 }
4889 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004890 else if (!use_out_for_err && !use_null_for_err &&
4891 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004892 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01004893 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004894
Bram Moolenaard8070362016-02-15 21:56:54 +01004895 si.dwFlags |= STARTF_USESTDHANDLES;
4896 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004897 si.hStdOutput = ofd[1];
4898 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
4899
4900 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
4901 {
Bram Moolenaarde279892016-03-11 22:19:44 +01004902 if (options->jo_set & JO_CHANNEL)
4903 {
4904 channel = options->jo_channel;
4905 if (channel != NULL)
4906 ++channel->ch_refcount;
4907 }
4908 else
4909 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004910 if (channel == NULL)
4911 goto failed;
4912 }
Bram Moolenaard8070362016-02-15 21:56:54 +01004913
4914 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01004915 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004916 CREATE_DEFAULT_ERROR_MODE |
4917 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01004918 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004919 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01004920 {
4921 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004922 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004923 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004924 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004925
4926 if (!AssignProcessToJobObject(jo, pi.hProcess))
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004927 {
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004928 /* if failing, switch the way to terminate
4929 * process with TerminateProcess. */
4930 CloseHandle(jo);
4931 jo = NULL;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004932 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004933 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01004934 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004935 job->jv_proc_info = pi;
4936 job->jv_job_object = jo;
4937 job->jv_status = JOB_STARTED;
4938
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02004939 CloseHandle(ifd[0]);
4940 CloseHandle(ofd[1]);
4941 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01004942 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01004943
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004944 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004945 if (channel != NULL)
4946 {
4947 channel_set_pipes(channel,
4948 use_file_for_in || use_null_for_in
4949 ? INVALID_FD : (sock_T)ifd[1],
4950 use_file_for_out || use_null_for_out
4951 ? INVALID_FD : (sock_T)ofd[0],
4952 use_out_for_err || use_file_for_err || use_null_for_err
4953 ? INVALID_FD : (sock_T)efd[0]);
4954 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004955 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004956 return;
4957
4958failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01004959 CloseHandle(ifd[0]);
4960 CloseHandle(ofd[0]);
4961 CloseHandle(efd[0]);
4962 CloseHandle(ifd[1]);
4963 CloseHandle(ofd[1]);
4964 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01004965 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004966}
4967
4968 char *
4969mch_job_status(job_T *job)
4970{
4971 DWORD dwExitCode = 0;
4972
Bram Moolenaar76467df2016-02-12 19:30:26 +01004973 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
4974 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004975 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01004976 job->jv_status = JOB_ENDED;
Bram Moolenaareab089d2016-02-21 19:32:02 +01004977 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004978 return "dead";
4979 }
4980 return "run";
4981}
4982
4983 int
4984mch_stop_job(job_T *job, char_u *how)
4985{
Bram Moolenaar923d9262016-02-25 20:56:01 +01004986 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004987
Bram Moolenaar923d9262016-02-25 20:56:01 +01004988 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01004989 {
4990 if (job->jv_job_object != NULL)
4991 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
4992 else
4993 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
4994 }
4995
4996 if (!AttachConsole(job->jv_proc_info.dwProcessId))
4997 return FAIL;
4998 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01004999 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5000 job->jv_proc_info.dwProcessId)
5001 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005002 FreeConsole();
5003 return ret;
5004}
5005
5006/*
5007 * Clear the data related to "job".
5008 */
5009 void
5010mch_clear_job(job_T *job)
5011{
5012 if (job->jv_status != JOB_FAILED)
5013 {
5014 if (job->jv_job_object != NULL)
5015 CloseHandle(job->jv_job_object);
5016 CloseHandle(job->jv_proc_info.hProcess);
5017 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005018}
5019#endif
5020
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021
5022#ifndef FEAT_GUI_W32
5023
5024/*
5025 * Start termcap mode
5026 */
5027 static void
5028termcap_mode_start(void)
5029{
5030 DWORD cmodein;
5031
5032 if (g_fTermcapMode)
5033 return;
5034
5035 SaveConsoleBuffer(&g_cbNonTermcap);
5036
5037 if (g_cbTermcap.IsValid)
5038 {
5039 /*
5040 * We've been in termcap mode before. Restore certain screen
5041 * characteristics, including the buffer size and the window
5042 * size. Since we will be redrawing the screen, we don't need
5043 * to restore the actual contents of the buffer.
5044 */
5045 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5046 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5047 Rows = g_cbTermcap.Info.dwSize.Y;
5048 Columns = g_cbTermcap.Info.dwSize.X;
5049 }
5050 else
5051 {
5052 /*
5053 * This is our first time entering termcap mode. Clear the console
5054 * screen buffer, and resize the buffer to match the current window
5055 * size. We will use this as the size of our editing environment.
5056 */
5057 ClearConsoleBuffer(g_attrCurrent);
5058 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5059 }
5060
5061#ifdef FEAT_TITLE
5062 resettitle();
5063#endif
5064
5065 GetConsoleMode(g_hConIn, &cmodein);
5066#ifdef FEAT_MOUSE
5067 if (g_fMouseActive)
5068 cmodein |= ENABLE_MOUSE_INPUT;
5069 else
5070 cmodein &= ~ENABLE_MOUSE_INPUT;
5071#endif
5072 cmodein |= ENABLE_WINDOW_INPUT;
5073 SetConsoleMode(g_hConIn, cmodein);
5074
5075 redraw_later_clear();
5076 g_fTermcapMode = TRUE;
5077}
5078
5079
5080/*
5081 * End termcap mode
5082 */
5083 static void
5084termcap_mode_end(void)
5085{
5086 DWORD cmodein;
5087 ConsoleBuffer *cb;
5088 COORD coord;
5089 DWORD dwDummy;
5090
5091 if (!g_fTermcapMode)
5092 return;
5093
5094 SaveConsoleBuffer(&g_cbTermcap);
5095
5096 GetConsoleMode(g_hConIn, &cmodein);
5097 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5098 SetConsoleMode(g_hConIn, cmodein);
5099
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005100#ifdef FEAT_RESTORE_ORIG_SCREEN
5101 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5102#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005103 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005104#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005105 RestoreConsoleBuffer(cb, p_rs);
5106 SetConsoleCursorInfo(g_hConOut, &g_cci);
5107
5108 if (p_rs || exiting)
5109 {
5110 /*
5111 * Clear anything that happens to be on the current line.
5112 */
5113 coord.X = 0;
5114 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5115 FillConsoleOutputCharacter(g_hConOut, ' ',
5116 cb->Info.dwSize.X, coord, &dwDummy);
5117 /*
5118 * The following is just for aesthetics. If we are exiting without
5119 * restoring the screen, then we want to have a prompt string
5120 * appear at the bottom line. However, the command interpreter
5121 * seems to always advance the cursor one line before displaying
5122 * the prompt string, which causes the screen to scroll. To
5123 * counter this, move the cursor up one line before exiting.
5124 */
5125 if (exiting && !p_rs)
5126 coord.Y--;
5127 /*
5128 * Position the cursor at the leftmost column of the desired row.
5129 */
5130 SetConsoleCursorPosition(g_hConOut, coord);
5131 }
5132
5133 g_fTermcapMode = FALSE;
5134}
5135#endif /* FEAT_GUI_W32 */
5136
5137
5138#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005139/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005140 void
5141mch_write(
5142 char_u *s,
5143 int len)
5144{
5145 /* never used */
5146}
5147
5148#else
5149
5150/*
5151 * clear `n' chars, starting from `coord'
5152 */
5153 static void
5154clear_chars(
5155 COORD coord,
5156 DWORD n)
5157{
5158 DWORD dwDummy;
5159
5160 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5161 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5162}
5163
5164
5165/*
5166 * Clear the screen
5167 */
5168 static void
5169clear_screen(void)
5170{
5171 g_coord.X = g_coord.Y = 0;
5172 clear_chars(g_coord, Rows * Columns);
5173}
5174
5175
5176/*
5177 * Clear to end of display
5178 */
5179 static void
5180clear_to_end_of_display(void)
5181{
5182 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5183 * Columns + (Columns - g_coord.X));
5184}
5185
5186
5187/*
5188 * Clear to end of line
5189 */
5190 static void
5191clear_to_end_of_line(void)
5192{
5193 clear_chars(g_coord, Columns - g_coord.X);
5194}
5195
5196
5197/*
5198 * Scroll the scroll region up by `cLines' lines
5199 */
5200 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005201scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005202{
5203 COORD oldcoord = g_coord;
5204
5205 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5206 delete_lines(cLines);
5207
5208 g_coord = oldcoord;
5209}
5210
5211
5212/*
5213 * Set the scroll region
5214 */
5215 static void
5216set_scroll_region(
5217 unsigned left,
5218 unsigned top,
5219 unsigned right,
5220 unsigned bottom)
5221{
5222 if (left >= right
5223 || top >= bottom
5224 || right > (unsigned) Columns - 1
5225 || bottom > (unsigned) Rows - 1)
5226 return;
5227
5228 g_srScrollRegion.Left = left;
5229 g_srScrollRegion.Top = top;
5230 g_srScrollRegion.Right = right;
5231 g_srScrollRegion.Bottom = bottom;
5232}
5233
5234
5235/*
5236 * Insert `cLines' lines at the current cursor position
5237 */
5238 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005239insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005240{
5241 SMALL_RECT source;
5242 COORD dest;
5243 CHAR_INFO fill;
5244
5245 dest.X = 0;
5246 dest.Y = g_coord.Y + cLines;
5247
5248 source.Left = 0;
5249 source.Top = g_coord.Y;
5250 source.Right = g_srScrollRegion.Right;
5251 source.Bottom = g_srScrollRegion.Bottom - cLines;
5252
5253 fill.Char.AsciiChar = ' ';
5254 fill.Attributes = g_attrCurrent;
5255
5256 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5257
5258 /* Here we have to deal with a win32 console flake: If the scroll
5259 * region looks like abc and we scroll c to a and fill with d we get
5260 * cbd... if we scroll block c one line at a time to a, we get cdd...
5261 * vim expects cdd consistently... So we have to deal with that
5262 * here... (this also occurs scrolling the same way in the other
5263 * direction). */
5264
5265 if (source.Bottom < dest.Y)
5266 {
5267 COORD coord;
5268
5269 coord.X = 0;
5270 coord.Y = source.Bottom;
5271 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5272 }
5273}
5274
5275
5276/*
5277 * Delete `cLines' lines at the current cursor position
5278 */
5279 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005280delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005281{
5282 SMALL_RECT source;
5283 COORD dest;
5284 CHAR_INFO fill;
5285 int nb;
5286
5287 dest.X = 0;
5288 dest.Y = g_coord.Y;
5289
5290 source.Left = 0;
5291 source.Top = g_coord.Y + cLines;
5292 source.Right = g_srScrollRegion.Right;
5293 source.Bottom = g_srScrollRegion.Bottom;
5294
5295 fill.Char.AsciiChar = ' ';
5296 fill.Attributes = g_attrCurrent;
5297
5298 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5299
5300 /* Here we have to deal with a win32 console flake: If the scroll
5301 * region looks like abc and we scroll c to a and fill with d we get
5302 * cbd... if we scroll block c one line at a time to a, we get cdd...
5303 * vim expects cdd consistently... So we have to deal with that
5304 * here... (this also occurs scrolling the same way in the other
5305 * direction). */
5306
5307 nb = dest.Y + (source.Bottom - source.Top) + 1;
5308
5309 if (nb < source.Top)
5310 {
5311 COORD coord;
5312
5313 coord.X = 0;
5314 coord.Y = nb;
5315 clear_chars(coord, Columns * (source.Top - nb));
5316 }
5317}
5318
5319
5320/*
5321 * Set the cursor position
5322 */
5323 static void
5324gotoxy(
5325 unsigned x,
5326 unsigned y)
5327{
5328 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5329 return;
5330
5331 /* external cursor coords are 1-based; internal are 0-based */
5332 g_coord.X = x - 1;
5333 g_coord.Y = y - 1;
5334 SetConsoleCursorPosition(g_hConOut, g_coord);
5335}
5336
5337
5338/*
5339 * Set the current text attribute = (foreground | background)
5340 * See ../doc/os_win32.txt for the numbers.
5341 */
5342 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005343textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005344{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005345 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005346
5347 SetConsoleTextAttribute(g_hConOut, wAttr);
5348}
5349
5350
5351 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005352textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005354 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005355
5356 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5357}
5358
5359
5360 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005361textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005362{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005363 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364
5365 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5366}
5367
5368
5369/*
5370 * restore the default text attribute (whatever we started with)
5371 */
5372 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005373normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005374{
5375 textattr(g_attrDefault);
5376}
5377
5378
5379static WORD g_attrPreStandout = 0;
5380
5381/*
5382 * Make the text standout, by brightening it
5383 */
5384 static void
5385standout(void)
5386{
5387 g_attrPreStandout = g_attrCurrent;
5388 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5389}
5390
5391
5392/*
5393 * Turn off standout mode
5394 */
5395 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005396standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005397{
5398 if (g_attrPreStandout)
5399 {
5400 textattr(g_attrPreStandout);
5401 g_attrPreStandout = 0;
5402 }
5403}
5404
5405
5406/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005407 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005408 */
5409 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005410mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005411{
5412 char_u *p;
5413 int n;
5414
5415 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5416 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5417 if (T_ME[0] == ESC && T_ME[1] == '|')
5418 {
5419 p = T_ME + 2;
5420 n = getdigits(&p);
5421 if (*p == 'm' && n > 0)
5422 {
5423 cterm_normal_fg_color = (n & 0xf) + 1;
5424 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5425 }
5426 }
5427}
5428
5429
5430/*
5431 * visual bell: flash the screen
5432 */
5433 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005434visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435{
5436 COORD coordOrigin = {0, 0};
5437 WORD attrFlash = ~g_attrCurrent & 0xff;
5438
5439 DWORD dwDummy;
5440 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5441
5442 if (oldattrs == NULL)
5443 return;
5444 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5445 coordOrigin, &dwDummy);
5446 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5447 coordOrigin, &dwDummy);
5448
5449 Sleep(15); /* wait for 15 msec */
5450 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5451 coordOrigin, &dwDummy);
5452 vim_free(oldattrs);
5453}
5454
5455
5456/*
5457 * Make the cursor visible or invisible
5458 */
5459 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005460cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005461{
5462 s_cursor_visible = fVisible;
5463#ifdef MCH_CURSOR_SHAPE
5464 mch_update_cursor();
5465#endif
5466}
5467
5468
5469/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005470 * write `cbToWrite' bytes in `pchBuf' to the screen
5471 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005472 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005473 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005475 char_u *pchBuf,
5476 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005477{
5478 COORD coord = g_coord;
5479 DWORD written;
5480
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005481#ifdef FEAT_MBYTE
5482 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5483 {
5484 static WCHAR *unicodebuf = NULL;
5485 static int unibuflen = 0;
5486 int length;
5487 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005489 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5490 if (unicodebuf == NULL || length > unibuflen)
5491 {
5492 vim_free(unicodebuf);
5493 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5494 unibuflen = length;
5495 }
5496 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5497 unicodebuf, unibuflen);
5498
5499 cells = mb_string2cells(pchBuf, cbToWrite);
5500 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5501 coord, &written);
5502 /* When writing fails or didn't write a single character, pretend one
5503 * character was written, otherwise we get stuck. */
5504 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5505 coord, &cchwritten) == 0
5506 || cchwritten == 0)
5507 cchwritten = 1;
5508
5509 if (cchwritten == length)
5510 {
5511 written = cbToWrite;
5512 g_coord.X += (SHORT)cells;
5513 }
5514 else
5515 {
5516 char_u *p = pchBuf;
5517 for (n = 0; n < cchwritten; n++)
5518 mb_cptr_adv(p);
5519 written = p - pchBuf;
5520 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5521 }
5522 }
5523 else
5524#endif
5525 {
5526 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5527 coord, &written);
5528 /* When writing fails or didn't write a single character, pretend one
5529 * character was written, otherwise we get stuck. */
5530 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5531 coord, &written) == 0
5532 || written == 0)
5533 written = 1;
5534
5535 g_coord.X += (SHORT) written;
5536 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537
5538 while (g_coord.X > g_srScrollRegion.Right)
5539 {
5540 g_coord.X -= (SHORT) Columns;
5541 if (g_coord.Y < g_srScrollRegion.Bottom)
5542 g_coord.Y++;
5543 }
5544
5545 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5546
5547 return written;
5548}
5549
5550
5551/*
5552 * mch_write(): write the output buffer to the screen, translating ESC
5553 * sequences into calls to console output routines.
5554 */
5555 void
5556mch_write(
5557 char_u *s,
5558 int len)
5559{
5560 s[len] = NUL;
5561
5562 if (!term_console)
5563 {
5564 write(1, s, (unsigned)len);
5565 return;
5566 }
5567
5568 /* translate ESC | sequences into faked bios calls */
5569 while (len--)
5570 {
5571 /* optimization: use one single write_chars for runs of text,
5572 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005573 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574
5575 if (p_wd)
5576 {
5577 WaitForChar(p_wd);
5578 if (prefix != 0)
5579 prefix = 1;
5580 }
5581
5582 if (prefix != 0)
5583 {
5584 DWORD nWritten;
5585
5586 nWritten = write_chars(s, prefix);
5587#ifdef MCH_WRITE_DUMP
5588 if (fdDump)
5589 {
5590 fputc('>', fdDump);
5591 fwrite(s, sizeof(char_u), nWritten, fdDump);
5592 fputs("<\n", fdDump);
5593 }
5594#endif
5595 len -= (nWritten - 1);
5596 s += nWritten;
5597 }
5598 else if (s[0] == '\n')
5599 {
5600 /* \n, newline: go to the beginning of the next line or scroll */
5601 if (g_coord.Y == g_srScrollRegion.Bottom)
5602 {
5603 scroll(1);
5604 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5605 }
5606 else
5607 {
5608 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5609 }
5610#ifdef MCH_WRITE_DUMP
5611 if (fdDump)
5612 fputs("\\n\n", fdDump);
5613#endif
5614 s++;
5615 }
5616 else if (s[0] == '\r')
5617 {
5618 /* \r, carriage return: go to beginning of line */
5619 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5620#ifdef MCH_WRITE_DUMP
5621 if (fdDump)
5622 fputs("\\r\n", fdDump);
5623#endif
5624 s++;
5625 }
5626 else if (s[0] == '\b')
5627 {
5628 /* \b, backspace: move cursor one position left */
5629 if (g_coord.X > g_srScrollRegion.Left)
5630 g_coord.X--;
5631 else if (g_coord.Y > g_srScrollRegion.Top)
5632 {
5633 g_coord.X = g_srScrollRegion.Right;
5634 g_coord.Y--;
5635 }
5636 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5637#ifdef MCH_WRITE_DUMP
5638 if (fdDump)
5639 fputs("\\b\n", fdDump);
5640#endif
5641 s++;
5642 }
5643 else if (s[0] == '\a')
5644 {
5645 /* \a, bell */
5646 MessageBeep(0xFFFFFFFF);
5647#ifdef MCH_WRITE_DUMP
5648 if (fdDump)
5649 fputs("\\a\n", fdDump);
5650#endif
5651 s++;
5652 }
5653 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5654 {
5655#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005656 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005657#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005658 char_u *p;
5659 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660
5661 switch (s[2])
5662 {
5663 /* one or two numeric arguments, separated by ';' */
5664
5665 case '0': case '1': case '2': case '3': case '4':
5666 case '5': case '6': case '7': case '8': case '9':
5667 p = s + 2;
5668 arg1 = getdigits(&p); /* no check for length! */
5669 if (p > s + len)
5670 break;
5671
5672 if (*p == ';')
5673 {
5674 ++p;
5675 arg2 = getdigits(&p); /* no check for length! */
5676 if (p > s + len)
5677 break;
5678
5679 if (*p == 'H')
5680 gotoxy(arg2, arg1);
5681 else if (*p == 'r')
5682 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5683 }
5684 else if (*p == 'A')
5685 {
5686 /* move cursor up arg1 lines in same column */
5687 gotoxy(g_coord.X + 1,
5688 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5689 }
5690 else if (*p == 'C')
5691 {
5692 /* move cursor right arg1 columns in same line */
5693 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5694 g_coord.Y + 1);
5695 }
5696 else if (*p == 'H')
5697 {
5698 gotoxy(1, arg1);
5699 }
5700 else if (*p == 'L')
5701 {
5702 insert_lines(arg1);
5703 }
5704 else if (*p == 'm')
5705 {
5706 if (arg1 == 0)
5707 normvideo();
5708 else
5709 textattr((WORD) arg1);
5710 }
5711 else if (*p == 'f')
5712 {
5713 textcolor((WORD) arg1);
5714 }
5715 else if (*p == 'b')
5716 {
5717 textbackground((WORD) arg1);
5718 }
5719 else if (*p == 'M')
5720 {
5721 delete_lines(arg1);
5722 }
5723
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005724 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725 s = p + 1;
5726 break;
5727
5728
5729 /* Three-character escape sequences */
5730
5731 case 'A':
5732 /* move cursor up one line in same column */
5733 gotoxy(g_coord.X + 1,
5734 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5735 goto got3;
5736
5737 case 'B':
5738 visual_bell();
5739 goto got3;
5740
5741 case 'C':
5742 /* move cursor right one column in same line */
5743 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5744 g_coord.Y + 1);
5745 goto got3;
5746
5747 case 'E':
5748 termcap_mode_end();
5749 goto got3;
5750
5751 case 'F':
5752 standout();
5753 goto got3;
5754
5755 case 'f':
5756 standend();
5757 goto got3;
5758
5759 case 'H':
5760 gotoxy(1, 1);
5761 goto got3;
5762
5763 case 'j':
5764 clear_to_end_of_display();
5765 goto got3;
5766
5767 case 'J':
5768 clear_screen();
5769 goto got3;
5770
5771 case 'K':
5772 clear_to_end_of_line();
5773 goto got3;
5774
5775 case 'L':
5776 insert_lines(1);
5777 goto got3;
5778
5779 case 'M':
5780 delete_lines(1);
5781 goto got3;
5782
5783 case 'S':
5784 termcap_mode_start();
5785 goto got3;
5786
5787 case 'V':
5788 cursor_visible(TRUE);
5789 goto got3;
5790
5791 case 'v':
5792 cursor_visible(FALSE);
5793 goto got3;
5794
5795 got3:
5796 s += 3;
5797 len -= 2;
5798 }
5799
5800#ifdef MCH_WRITE_DUMP
5801 if (fdDump)
5802 {
5803 fputs("ESC | ", fdDump);
5804 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5805 fputc('\n', fdDump);
5806 }
5807#endif
5808 }
5809 else
5810 {
5811 /* Write a single character */
5812 DWORD nWritten;
5813
5814 nWritten = write_chars(s, 1);
5815#ifdef MCH_WRITE_DUMP
5816 if (fdDump)
5817 {
5818 fputc('>', fdDump);
5819 fwrite(s, sizeof(char_u), nWritten, fdDump);
5820 fputs("<\n", fdDump);
5821 }
5822#endif
5823
5824 len -= (nWritten - 1);
5825 s += nWritten;
5826 }
5827 }
5828
5829#ifdef MCH_WRITE_DUMP
5830 if (fdDump)
5831 fflush(fdDump);
5832#endif
5833}
5834
5835#endif /* FEAT_GUI_W32 */
5836
5837
5838/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01005839 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005841/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005842 void
5843mch_delay(
5844 long msec,
5845 int ignoreinput)
5846{
5847#ifdef FEAT_GUI_W32
5848 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005849#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005850 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005851# ifdef FEAT_MZSCHEME
5852 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5853 {
5854 int towait = p_mzq;
5855
5856 /* if msec is large enough, wait by portions in p_mzq */
5857 while (msec > 0)
5858 {
5859 mzvim_check_threads();
5860 if (msec < towait)
5861 towait = msec;
5862 Sleep(towait);
5863 msec -= towait;
5864 }
5865 }
5866 else
5867# endif
5868 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005869 else
5870 WaitForChar(msec);
5871#endif
5872}
5873
5874
5875/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01005876 * This version of remove is not scared by a readonly (backup) file.
5877 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878 * Return 0 for success, -1 for failure.
5879 */
5880 int
5881mch_remove(char_u *name)
5882{
5883#ifdef FEAT_MBYTE
5884 WCHAR *wn = NULL;
5885 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005886#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005887
Bram Moolenaar203258c2016-01-17 22:15:16 +01005888 /*
5889 * On Windows, deleting a directory's symbolic link is done by
5890 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
5891 */
5892 if (mch_isdir(name) && mch_is_symbolic_link(name))
5893 return mch_rmdir(name);
5894
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005895 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5896
5897#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5899 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005900 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005901 if (wn != NULL)
5902 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005903 n = DeleteFileW(wn) ? 0 : -1;
5904 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005905 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906 }
5907 }
5908#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005909 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005910}
5911
5912
5913/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02005914 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915 */
5916 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02005917mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005918{
5919#ifndef FEAT_GUI_W32 /* never used */
5920 if (g_fCtrlCPressed || g_fCBrkPressed)
5921 {
5922 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5923 got_int = TRUE;
5924 }
5925#endif
5926}
5927
Bram Moolenaaree273972016-01-02 21:11:51 +01005928/* physical RAM to leave for the OS */
5929#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01005930
5931/*
5932 * How much main memory in KiB that can be used by VIM.
5933 */
5934/*ARGSUSED*/
5935 long_u
5936mch_total_mem(int special)
5937{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005938 MEMORYSTATUSEX ms;
5939
Bram Moolenaaree273972016-01-02 21:11:51 +01005940 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005941 /* Need to use GlobalMemoryStatusEx() when there is more memory than
5942 * what fits in 32 bits. But it's not always available. */
5943 ms.dwLength = sizeof(MEMORYSTATUSEX);
5944 GlobalMemoryStatusEx(&ms);
5945 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01005946 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005947 /* Process address space fits in physical RAM, use all of it. */
5948 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01005949 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005950 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01005951 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005952 /* Catch old NT box or perverse hardware setup. */
5953 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01005954 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005955 /* Use physical RAM less reserve for OS + data. */
5956 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01005957}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005958
Bram Moolenaar071d4272004-06-13 20:20:40 +00005959#ifdef FEAT_MBYTE
5960/*
5961 * Same code as below, but with wide functions and no comments.
5962 * Return 0 for success, non-zero for failure.
5963 */
5964 int
5965mch_wrename(WCHAR *wold, WCHAR *wnew)
5966{
5967 WCHAR *p;
5968 int i;
5969 WCHAR szTempFile[_MAX_PATH + 1];
5970 WCHAR szNewPath[_MAX_PATH + 1];
5971 HANDLE hf;
5972
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005973 p = wold;
5974 for (i = 0; wold[i] != NUL; ++i)
5975 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5976 && wold[i + 1] != 0)
5977 p = wold + i + 1;
5978 if ((int)(wold + i - p) < 8 || p[6] != '~')
5979 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005980
5981 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5982 return -1;
5983 *p = NUL;
5984
5985 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5986 return -2;
5987
5988 if (!DeleteFileW(szTempFile))
5989 return -3;
5990
5991 if (!MoveFileW(wold, szTempFile))
5992 return -4;
5993
5994 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5995 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5996 return -5;
5997 if (!CloseHandle(hf))
5998 return -6;
5999
6000 if (!MoveFileW(szTempFile, wnew))
6001 {
6002 (void)MoveFileW(szTempFile, wold);
6003 return -7;
6004 }
6005
6006 DeleteFileW(szTempFile);
6007
6008 if (!DeleteFileW(wold))
6009 return -8;
6010
6011 return 0;
6012}
6013#endif
6014
6015
6016/*
6017 * mch_rename() works around a bug in rename (aka MoveFile) in
6018 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6019 * file whose short file name is "FOO.BAR" (its long file name will
6020 * be correct: "foo.bar~"). Because a file can be accessed by
6021 * either its SFN or its LFN, "foo.bar" has effectively been
6022 * renamed to "foo.bar", which is not at all what was wanted. This
6023 * seems to happen only when renaming files with three-character
6024 * extensions by appending a suffix that does not include ".".
6025 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6026 *
6027 * There is another problem, which isn't really a bug but isn't right either:
6028 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6029 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6030 * service pack 6. Doesn't seem to happen on Windows 98.
6031 *
6032 * Like rename(), returns 0 upon success, non-zero upon failure.
6033 * Should probably set errno appropriately when errors occur.
6034 */
6035 int
6036mch_rename(
6037 const char *pszOldFile,
6038 const char *pszNewFile)
6039{
6040 char szTempFile[_MAX_PATH+1];
6041 char szNewPath[_MAX_PATH+1];
6042 char *pszFilePart;
6043 HANDLE hf;
6044#ifdef FEAT_MBYTE
6045 WCHAR *wold = NULL;
6046 WCHAR *wnew = NULL;
6047 int retval = -1;
6048
6049 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6050 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006051 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6052 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006053 if (wold != NULL && wnew != NULL)
6054 retval = mch_wrename(wold, wnew);
6055 vim_free(wold);
6056 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006057 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006058 }
6059#endif
6060
6061 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006062 * No need to play tricks unless the file name contains a "~" as the
6063 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006064 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006065 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6066 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6067 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068
6069 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6070 * a directory, no error is returned and pszFilePart will be NULL. */
6071 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6072 || pszFilePart == NULL)
6073 return -1;
6074 *pszFilePart = NUL;
6075
6076 /* Get (and create) a unique temporary file name in directory of new file */
6077 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6078 return -2;
6079
6080 /* blow the temp file away */
6081 if (!DeleteFile(szTempFile))
6082 return -3;
6083
6084 /* rename old file to the temp file */
6085 if (!MoveFile(pszOldFile, szTempFile))
6086 return -4;
6087
6088 /* now create an empty file called pszOldFile; this prevents the operating
6089 * system using pszOldFile as an alias (SFN) if we're renaming within the
6090 * same directory. For example, we're editing a file called
6091 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6092 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6093 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006094 * cause all sorts of problems later in buf_write(). So, we create an
6095 * empty file called filena~1.txt and the system will have to find some
6096 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006097 */
6098 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6099 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6100 return -5;
6101 if (!CloseHandle(hf))
6102 return -6;
6103
6104 /* rename the temp file to the new file */
6105 if (!MoveFile(szTempFile, pszNewFile))
6106 {
6107 /* Renaming failed. Rename the file back to its old name, so that it
6108 * looks like nothing happened. */
6109 (void)MoveFile(szTempFile, pszOldFile);
6110
6111 return -7;
6112 }
6113
6114 /* Seems to be left around on Novell filesystems */
6115 DeleteFile(szTempFile);
6116
6117 /* finally, remove the empty old file */
6118 if (!DeleteFile(pszOldFile))
6119 return -8;
6120
6121 return 0; /* success */
6122}
6123
6124/*
6125 * Get the default shell for the current hardware platform
6126 */
6127 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006128default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130 PlatformId();
6131
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006132 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006133}
6134
6135/*
6136 * mch_access() extends access() to do more detailed check on network drives.
6137 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6138 */
6139 int
6140mch_access(char *n, int p)
6141{
6142 HANDLE hFile;
6143 DWORD am;
6144 int retval = -1; /* default: fail */
6145#ifdef FEAT_MBYTE
6146 WCHAR *wn = NULL;
6147
6148 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006149 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150#endif
6151
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006152 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006153 {
6154 char TempName[_MAX_PATH + 16] = "";
6155#ifdef FEAT_MBYTE
6156 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6157#endif
6158
6159 if (p & R_OK)
6160 {
6161 /* Read check is performed by seeing if we can do a find file on
6162 * the directory for any file. */
6163#ifdef FEAT_MBYTE
6164 if (wn != NULL)
6165 {
6166 int i;
6167 WIN32_FIND_DATAW d;
6168
6169 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6170 TempNameW[i] = wn[i];
6171 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6172 TempNameW[i++] = '\\';
6173 TempNameW[i++] = '*';
6174 TempNameW[i++] = 0;
6175
6176 hFile = FindFirstFileW(TempNameW, &d);
6177 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006178 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006179 else
6180 (void)FindClose(hFile);
6181 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006182 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183#endif
6184 {
6185 char *pch;
6186 WIN32_FIND_DATA d;
6187
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006188 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 pch = TempName + STRLEN(TempName) - 1;
6190 if (*pch != '\\' && *pch != '/')
6191 *++pch = '\\';
6192 *++pch = '*';
6193 *++pch = NUL;
6194
6195 hFile = FindFirstFile(TempName, &d);
6196 if (hFile == INVALID_HANDLE_VALUE)
6197 goto getout;
6198 (void)FindClose(hFile);
6199 }
6200 }
6201
6202 if (p & W_OK)
6203 {
6204 /* Trying to create a temporary file in the directory should catch
6205 * directories on read-only network shares. However, in
6206 * directories whose ACL allows writes but denies deletes will end
6207 * up keeping the temporary file :-(. */
6208#ifdef FEAT_MBYTE
6209 if (wn != NULL)
6210 {
6211 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006212 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006213 else
6214 DeleteFileW(TempNameW);
6215 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006216 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217#endif
6218 {
6219 if (!GetTempFileName(n, "VIM", 0, TempName))
6220 goto getout;
6221 mch_remove((char_u *)TempName);
6222 }
6223 }
6224 }
6225 else
6226 {
6227 /* Trying to open the file for the required access does ACL, read-only
6228 * network share, and file attribute checks. */
6229 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6230 | ((p & R_OK) ? GENERIC_READ : 0);
6231#ifdef FEAT_MBYTE
6232 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006233 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006234 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006235#endif
6236 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6237 if (hFile == INVALID_HANDLE_VALUE)
6238 goto getout;
6239 CloseHandle(hFile);
6240 }
6241
6242 retval = 0; /* success */
6243getout:
6244#ifdef FEAT_MBYTE
6245 vim_free(wn);
6246#endif
6247 return retval;
6248}
6249
6250#if defined(FEAT_MBYTE) || defined(PROTO)
6251/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006252 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253 */
6254 int
6255mch_open(char *name, int flags, int mode)
6256{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006257 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6258# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259 WCHAR *wn;
6260 int f;
6261
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006262 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006264 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 if (wn != NULL)
6266 {
6267 f = _wopen(wn, flags, mode);
6268 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006269 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 }
6271 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006272# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006274 /* open() can open a file which name is longer than _MAX_PATH bytes
6275 * and shorter than _MAX_PATH characters successfully, but sometimes it
6276 * causes unexpected error in another part. We make it an error explicitly
6277 * here. */
6278 if (strlen(name) >= _MAX_PATH)
6279 return -1;
6280
Bram Moolenaar071d4272004-06-13 20:20:40 +00006281 return open(name, flags, mode);
6282}
6283
6284/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006285 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 */
6287 FILE *
6288mch_fopen(char *name, char *mode)
6289{
6290 WCHAR *wn, *wm;
6291 FILE *f = NULL;
6292
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006293 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006295# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006296 /* Work around an annoying assertion in the Microsoft debug CRT
6297 * when mode's text/binary setting doesn't match _get_fmode(). */
6298 char newMode = mode[strlen(mode) - 1];
6299 int oldMode = 0;
6300
6301 _get_fmode(&oldMode);
6302 if (newMode == 't')
6303 _set_fmode(_O_TEXT);
6304 else if (newMode == 'b')
6305 _set_fmode(_O_BINARY);
6306# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006307 wn = enc_to_utf16((char_u *)name, NULL);
6308 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006309 if (wn != NULL && wm != NULL)
6310 f = _wfopen(wn, wm);
6311 vim_free(wn);
6312 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006313
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006314# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006315 _set_fmode(oldMode);
6316# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006317 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318 }
6319
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006320 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6321 * and shorter than _MAX_PATH characters successfully, but sometimes it
6322 * causes unexpected error in another part. We make it an error explicitly
6323 * here. */
6324 if (strlen(name) >= _MAX_PATH)
6325 return NULL;
6326
Bram Moolenaar071d4272004-06-13 20:20:40 +00006327 return fopen(name, mode);
6328}
6329#endif
6330
6331#ifdef FEAT_MBYTE
6332/*
6333 * SUB STREAM (aka info stream) handling:
6334 *
6335 * NTFS can have sub streams for each file. Normal contents of file is
6336 * stored in the main stream, and extra contents (author information and
6337 * title and so on) can be stored in sub stream. After Windows 2000, user
6338 * can access and store those informations in sub streams via explorer's
6339 * property menuitem in right click menu. Those informations in sub streams
6340 * were lost when copying only the main stream. So we have to copy sub
6341 * streams.
6342 *
6343 * Incomplete explanation:
6344 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6345 * More useful info and an example:
6346 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6347 */
6348
6349/*
6350 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6351 * and write to stream "substream" of file "to".
6352 * Errors are ignored.
6353 */
6354 static void
6355copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6356{
6357 HANDLE hTo;
6358 WCHAR *to_name;
6359
6360 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6361 wcscpy(to_name, to);
6362 wcscat(to_name, substream);
6363
6364 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6365 FILE_ATTRIBUTE_NORMAL, NULL);
6366 if (hTo != INVALID_HANDLE_VALUE)
6367 {
6368 long done;
6369 DWORD todo;
6370 DWORD readcnt, written;
6371 char buf[4096];
6372
6373 /* Copy block of bytes at a time. Abort when something goes wrong. */
6374 for (done = 0; done < len; done += written)
6375 {
6376 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006377 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6378 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006379 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6380 FALSE, FALSE, context)
6381 || readcnt != todo
6382 || !WriteFile(hTo, buf, todo, &written, NULL)
6383 || written != todo)
6384 break;
6385 }
6386 CloseHandle(hTo);
6387 }
6388
6389 free(to_name);
6390}
6391
6392/*
6393 * Copy info streams from file "from" to file "to".
6394 */
6395 static void
6396copy_infostreams(char_u *from, char_u *to)
6397{
6398 WCHAR *fromw;
6399 WCHAR *tow;
6400 HANDLE sh;
6401 WIN32_STREAM_ID sid;
6402 int headersize;
6403 WCHAR streamname[_MAX_PATH];
6404 DWORD readcount;
6405 void *context = NULL;
6406 DWORD lo, hi;
6407 int len;
6408
6409 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006410 fromw = enc_to_utf16(from, NULL);
6411 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006412 if (fromw != NULL && tow != NULL)
6413 {
6414 /* Open the file for reading. */
6415 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6416 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6417 if (sh != INVALID_HANDLE_VALUE)
6418 {
6419 /* Use BackupRead() to find the info streams. Repeat until we
6420 * have done them all.*/
6421 for (;;)
6422 {
6423 /* Get the header to find the length of the stream name. If
6424 * the "readcount" is zero we have done all info streams. */
6425 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006426 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006427 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6428 &readcount, FALSE, FALSE, &context)
6429 || readcount == 0)
6430 break;
6431
6432 /* We only deal with streams that have a name. The normal
6433 * file data appears to be without a name, even though docs
6434 * suggest it is called "::$DATA". */
6435 if (sid.dwStreamNameSize > 0)
6436 {
6437 /* Read the stream name. */
6438 if (!BackupRead(sh, (LPBYTE)streamname,
6439 sid.dwStreamNameSize,
6440 &readcount, FALSE, FALSE, &context))
6441 break;
6442
6443 /* Copy an info stream with a name ":anything:$DATA".
6444 * Skip "::$DATA", it has no stream name (examples suggest
6445 * it might be used for the normal file contents).
6446 * Note that BackupRead() counts bytes, but the name is in
6447 * wide characters. */
6448 len = readcount / sizeof(WCHAR);
6449 streamname[len] = 0;
6450 if (len > 7 && wcsicmp(streamname + len - 6,
6451 L":$DATA") == 0)
6452 {
6453 streamname[len - 6] = 0;
6454 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006455 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006456 }
6457 }
6458
6459 /* Advance to the next stream. We might try seeking too far,
6460 * but BackupSeek() doesn't skip over stream borders, thus
6461 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006462 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006463 &lo, &hi, &context);
6464 }
6465
6466 /* Clear the context. */
6467 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6468
6469 CloseHandle(sh);
6470 }
6471 }
6472 vim_free(fromw);
6473 vim_free(tow);
6474}
6475#endif
6476
6477/*
6478 * Copy file attributes from file "from" to file "to".
6479 * For Windows NT and later we copy info streams.
6480 * Always returns zero, errors are ignored.
6481 */
6482 int
6483mch_copy_file_attribute(char_u *from, char_u *to)
6484{
6485#ifdef FEAT_MBYTE
6486 /* File streams only work on Windows NT and later. */
6487 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006488 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006489#endif
6490 return 0;
6491}
6492
6493#if defined(MYRESETSTKOFLW) || defined(PROTO)
6494/*
6495 * Recreate a destroyed stack guard page in win32.
6496 * Written by Benjamin Peterson.
6497 */
6498
6499/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006500#define MIN_STACK_WINNT 2
6501
6502/*
6503 * This function does the same thing as _resetstkoflw(), which is only
6504 * available in DevStudio .net and later.
6505 * Returns 0 for failure, 1 for success.
6506 */
6507 int
6508myresetstkoflw(void)
6509{
6510 BYTE *pStackPtr;
6511 BYTE *pGuardPage;
6512 BYTE *pStackBase;
6513 BYTE *pLowestPossiblePage;
6514 MEMORY_BASIC_INFORMATION mbi;
6515 SYSTEM_INFO si;
6516 DWORD nPageSize;
6517 DWORD dummy;
6518
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006520
6521 /* We need to know the system page size. */
6522 GetSystemInfo(&si);
6523 nPageSize = si.dwPageSize;
6524
6525 /* ...and the current stack pointer */
6526 pStackPtr = (BYTE*)_alloca(1);
6527
6528 /* ...and the base of the stack. */
6529 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6530 return 0;
6531 pStackBase = (BYTE*)mbi.AllocationBase;
6532
6533 /* ...and the page thats min_stack_req pages away from stack base; this is
6534 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006535 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006536
Bram Moolenaar071d4272004-06-13 20:20:40 +00006537 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006538 /* We want the first committed page in the stack Start at the stack
6539 * base and move forward through memory until we find a committed block.
6540 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006541 BYTE *pBlock = pStackBase;
6542
Bram Moolenaara466c992005-07-09 21:03:22 +00006543 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 {
6545 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6546 return 0;
6547
6548 pBlock += mbi.RegionSize;
6549
6550 if (mbi.State & MEM_COMMIT)
6551 break;
6552 }
6553
6554 /* mbi now describes the first committed block in the stack. */
6555 if (mbi.Protect & PAGE_GUARD)
6556 return 1;
6557
6558 /* decide where the guard page should start */
6559 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6560 pGuardPage = pLowestPossiblePage;
6561 else
6562 pGuardPage = (BYTE*)mbi.BaseAddress;
6563
6564 /* allocate the guard page */
6565 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6566 return 0;
6567
6568 /* apply the guard attribute to the page */
6569 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6570 &dummy))
6571 return 0;
6572 }
6573
6574 return 1;
6575}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006576#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006577
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006578
6579#if defined(FEAT_MBYTE) || defined(PROTO)
6580/*
6581 * The command line arguments in UCS2
6582 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006583static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006584static LPWSTR *ArglistW = NULL;
6585static int global_argc = 0;
6586static char **global_argv;
6587
6588static int used_file_argc = 0; /* last argument in global_argv[] used
6589 for the argument list. */
6590static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6591 command line arguments added to
6592 the argument list */
6593static int used_file_count = 0; /* nr of entries in used_file_indexes */
6594static int used_file_literal = FALSE; /* take file names literally */
6595static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006596static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006597static int used_alist_count = 0;
6598
6599
6600/*
6601 * Get the command line arguments. Unicode version.
6602 * Returns argc. Zero when something fails.
6603 */
6604 int
6605get_cmd_argsW(char ***argvp)
6606{
6607 char **argv = NULL;
6608 int argc = 0;
6609 int i;
6610
Bram Moolenaar14993322014-09-09 12:25:33 +02006611 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006612 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6613 if (ArglistW != NULL)
6614 {
6615 argv = malloc((nArgsW + 1) * sizeof(char *));
6616 if (argv != NULL)
6617 {
6618 argc = nArgsW;
6619 argv[argc] = NULL;
6620 for (i = 0; i < argc; ++i)
6621 {
6622 int len;
6623
6624 /* Convert each Unicode argument to the current codepage. */
6625 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006626 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006627 (LPSTR *)&argv[i], &len, 0, 0);
6628 if (argv[i] == NULL)
6629 {
6630 /* Out of memory, clear everything. */
6631 while (i > 0)
6632 free(argv[--i]);
6633 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006634 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006635 argc = 0;
6636 }
6637 }
6638 }
6639 }
6640
6641 global_argc = argc;
6642 global_argv = argv;
6643 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006644 {
6645 if (used_file_indexes != NULL)
6646 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006647 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006648 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006649
6650 if (argvp != NULL)
6651 *argvp = argv;
6652 return argc;
6653}
6654
6655 void
6656free_cmd_argsW(void)
6657{
6658 if (ArglistW != NULL)
6659 {
6660 GlobalFree(ArglistW);
6661 ArglistW = NULL;
6662 }
6663}
6664
6665/*
6666 * Remember "name" is an argument that was added to the argument list.
6667 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6668 * is called.
6669 */
6670 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006671used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006672{
6673 int i;
6674
6675 if (used_file_indexes == NULL)
6676 return;
6677 for (i = used_file_argc + 1; i < global_argc; ++i)
6678 if (STRCMP(global_argv[i], name) == 0)
6679 {
6680 used_file_argc = i;
6681 used_file_indexes[used_file_count++] = i;
6682 break;
6683 }
6684 used_file_literal = literal;
6685 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006686 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006687}
6688
6689/*
6690 * Remember the length of the argument list as it was. If it changes then we
6691 * leave it alone when 'encoding' is set.
6692 */
6693 void
6694set_alist_count(void)
6695{
6696 used_alist_count = GARGCOUNT;
6697}
6698
6699/*
6700 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6701 * has been changed while starting up. Use the UCS-2 command line arguments
6702 * and convert them to 'encoding'.
6703 */
6704 void
6705fix_arg_enc(void)
6706{
6707 int i;
6708 int idx;
6709 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006710 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006711
6712 /* Safety checks:
6713 * - if argument count differs between the wide and non-wide argument
6714 * list, something must be wrong.
6715 * - the file name arguments must have been located.
6716 * - the length of the argument list wasn't changed by the user.
6717 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006718 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006719 || ArglistW == NULL
6720 || used_file_indexes == NULL
6721 || used_file_count == 0
6722 || used_alist_count != GARGCOUNT)
6723 return;
6724
Bram Moolenaar86b68352004-12-27 21:59:20 +00006725 /* Remember the buffer numbers for the arguments. */
6726 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6727 if (fnum_list == NULL)
6728 return; /* out of memory */
6729 for (i = 0; i < GARGCOUNT; ++i)
6730 fnum_list[i] = GARGLIST[i].ae_fnum;
6731
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006732 /* Clear the argument list. Make room for the new arguments. */
6733 alist_clear(&global_alist);
6734 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006735 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006736
6737 for (i = 0; i < used_file_count; ++i)
6738 {
6739 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006740 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006741 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006742 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006743#ifdef FEAT_DIFF
6744 /* When using diff mode may need to concatenate file name to
6745 * directory name. Just like it's done in main(). */
6746 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6747 && !mch_isdir(alist_name(&GARGLIST[0])))
6748 {
6749 char_u *r;
6750
6751 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6752 if (r != NULL)
6753 {
6754 vim_free(str);
6755 str = r;
6756 }
6757 }
6758#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006759 /* Re-use the old buffer by renaming it. When not using literal
6760 * names it's done by alist_expand() below. */
6761 if (used_file_literal)
6762 buf_set_name(fnum_list[i], str);
6763
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006764 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006765 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006766 }
6767
6768 if (!used_file_literal)
6769 {
6770 /* Now expand wildcards in the arguments. */
6771 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6772 * filename characters but are excluded from 'isfname' to make
6773 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6774 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006775 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006776 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6777 }
6778
6779 /* If wildcard expansion failed, we are editing the first file of the
6780 * arglist and there is no file name: Edit the first argument now. */
6781 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6782 {
6783 do_cmdline_cmd((char_u *)":rewind");
6784 if (GARGCOUNT == 1 && used_file_full_path)
6785 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6786 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006787
6788 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006789}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006790#endif