blob: 9fcb054d0e9a0c1b46f97599dbaf656f41361ab8 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
114typedef int KEY_EVENT_RECORD;
115typedef int LOGFONT;
116typedef int LPBOOL;
117typedef int LPCTSTR;
118typedef int LPDWORD;
119typedef int LPSTR;
120typedef int LPTSTR;
121typedef int LPVOID;
122typedef int MOUSE_EVENT_RECORD;
123typedef int PACL;
124typedef int PDWORD;
125typedef int PHANDLE;
126typedef int PRINTDLG;
127typedef int PSECURITY_DESCRIPTOR;
128typedef int PSID;
129typedef int SECURITY_INFORMATION;
130typedef int SHORT;
131typedef int SMALL_RECT;
132typedef int TEXTMETRIC;
133typedef int TOKEN_INFORMATION_CLASS;
134typedef int TRUSTEE;
135typedef int WORD;
136typedef int WCHAR;
137typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100138typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200139typedef int SE_OBJECT_TYPE;
140typedef int PSNSECINFO;
141typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100142typedef int STARTUPINFO;
143typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200144typedef int LPSECURITY_ATTRIBUTES;
145# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146#endif
147
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#if defined(__BORLANDC__)
149/* Strangely Borland uses a non-standard name. */
150# define wcsicmp(a, b) wcscmpi((a), (b))
151#endif
152
153#ifndef FEAT_GUI_W32
154/* Win32 Console handles for input and output */
155static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
156static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
157
158/* Win32 Screen buffer,coordinate,console I/O information */
159static SMALL_RECT g_srScrollRegion;
160static COORD g_coord; /* 0-based, but external coords are 1-based */
161
162/* The attribute of the screen when the editor was started */
163static WORD g_attrDefault = 7; /* lightgray text on black background */
164static WORD g_attrCurrent;
165
166static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
167static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
168static int g_fForceExit = FALSE; /* set when forcefully exiting */
169
170static void termcap_mode_start(void);
171static void termcap_mode_end(void);
172static void clear_chars(COORD coord, DWORD n);
173static void clear_screen(void);
174static void clear_to_end_of_display(void);
175static void clear_to_end_of_line(void);
176static void scroll(unsigned cLines);
177static void set_scroll_region(unsigned left, unsigned top,
178 unsigned right, unsigned bottom);
179static void insert_lines(unsigned cLines);
180static void delete_lines(unsigned cLines);
181static void gotoxy(unsigned x, unsigned y);
182static void normvideo(void);
183static void textattr(WORD wAttr);
184static void textcolor(WORD wAttr);
185static void textbackground(WORD wAttr);
186static void standout(void);
187static void standend(void);
188static void visual_bell(void);
189static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200190static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000191static void create_conin(void);
192static int s_cursor_visible = TRUE;
193static int did_create_conin = FALSE;
194#else
195static int s_dont_use_vimrun = TRUE;
196static int need_vimrun_warning = FALSE;
197static char *vimrun_path = "vimrun ";
198#endif
199
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200200static int win32_getattrs(char_u *name);
201static int win32_setattrs(char_u *name, int attrs);
202static int win32_set_archive(char_u *name);
203
Bram Moolenaar071d4272004-06-13 20:20:40 +0000204#ifndef FEAT_GUI_W32
205static int suppress_winsize = 1; /* don't fiddle with console */
206#endif
207
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200208static char_u *exe_path = NULL;
209
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100210static BOOL win8_or_later = FALSE;
211
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100212#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100213/*
214 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100215 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100216 */
217 static BOOL
218read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100219 HANDLE hInput,
220 INPUT_RECORD *lpBuffer,
221 DWORD nLength,
222 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100223{
224 enum
225 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100226 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100227 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100228 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100229 static DWORD s_dwIndex = 0;
230 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100231 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100232 int head;
233 int tail;
234 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100235
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200236 if (nLength == -2)
237 return (s_dwMax > 0) ? TRUE : FALSE;
238
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100239 if (!win8_or_later)
240 {
241 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200242 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
243 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100244 }
245
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100246 if (s_dwMax == 0)
247 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100248 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200249 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
250 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100251 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100252 s_dwIndex = 0;
253 s_dwMax = dwEvents;
254 if (dwEvents == 0)
255 {
256 *lpEvents = 0;
257 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100258 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100259
260 if (s_dwMax > 1)
261 {
262 head = 0;
263 tail = s_dwMax - 1;
264 while (head != tail)
265 {
266 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
267 && s_irCache[head + 1].EventType
268 == WINDOW_BUFFER_SIZE_EVENT)
269 {
270 /* Remove duplicate event to avoid flicker. */
271 for (i = head; i < tail; ++i)
272 s_irCache[i] = s_irCache[i + 1];
273 --tail;
274 continue;
275 }
276 head++;
277 }
278 s_dwMax = tail + 1;
279 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100280 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100281
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100282 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200283 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100284 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100285 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100286 return TRUE;
287}
288
289/*
290 * Version of PeekConsoleInput() that works with IME.
291 */
292 static BOOL
293peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100294 HANDLE hInput,
295 INPUT_RECORD *lpBuffer,
296 DWORD nLength,
297 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100298{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100299 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100300}
301
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100302# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200303 static DWORD
304msg_wait_for_multiple_objects(
305 DWORD nCount,
306 LPHANDLE pHandles,
307 BOOL fWaitAll,
308 DWORD dwMilliseconds,
309 DWORD dwWakeMask)
310{
311 if (read_console_input(NULL, NULL, -2, NULL))
312 return WAIT_OBJECT_0;
313 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
314 dwMilliseconds, dwWakeMask);
315}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100316# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200317
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100318# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200319 static DWORD
320wait_for_single_object(
321 HANDLE hHandle,
322 DWORD dwMilliseconds)
323{
324 if (read_console_input(NULL, NULL, -2, NULL))
325 return WAIT_OBJECT_0;
326 return WaitForSingleObject(hHandle, dwMilliseconds);
327}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100328# endif
329#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200330
Bram Moolenaar071d4272004-06-13 20:20:40 +0000331 static void
332get_exe_name(void)
333{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100334 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
335 * as the maximum length that works (plus a NUL byte). */
336#define MAX_ENV_PATH_LEN 8192
337 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200338 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000339
340 if (exe_name == NULL)
341 {
342 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100343 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 if (*temp != NUL)
345 exe_name = FullName_save((char_u *)temp, FALSE);
346 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000347
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200348 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000349 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200350 exe_path = vim_strnsave(exe_name,
351 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200352 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000353 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200354 /* Append our starting directory to $PATH, so that when doing
355 * "!xxd" it's found in our starting directory. Needed because
356 * SearchPath() also looks there. */
357 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100358 if (p == NULL
359 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200360 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100361 if (p == NULL || *p == NUL)
362 temp[0] = NUL;
363 else
364 {
365 STRCPY(temp, p);
366 STRCAT(temp, ";");
367 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200368 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100369 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200370 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000371 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373}
374
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200375/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100376 * Unescape characters in "p" that appear in "escaped".
377 */
378 static void
379unescape_shellxquote(char_u *p, char_u *escaped)
380{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100381 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100382 int n;
383
384 while (*p != NUL)
385 {
386 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
387 mch_memmove(p, p + 1, l--);
388#ifdef FEAT_MBYTE
389 n = (*mb_ptr2len)(p);
390#else
391 n = 1;
392#endif
393 p += n;
394 l -= n;
395 }
396}
397
398/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200399 * Load library "name".
400 */
401 HINSTANCE
402vimLoadLib(char *name)
403{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200404 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200405
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200406 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
407 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200408 if (exe_path == NULL)
409 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200410 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200411 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200412 WCHAR old_dirw[MAXPATHL];
413
414 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
415 {
416 /* Change directory to where the executable is, both to make
417 * sure we find a .dll there and to avoid looking for a .dll
418 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100419 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200420 dll = LoadLibrary(name);
421 SetCurrentDirectoryW(old_dirw);
422 return dll;
423 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200424 }
425 return dll;
426}
427
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
429# ifndef GETTEXT_DLL
430# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100431# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200433/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000434static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200435static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000436static char *null_libintl_textdomain(const char *);
437static char *null_libintl_bindtextdomain(const char *, const char *);
438static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200440static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000441char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200442char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
443 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000444char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
445char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000447char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
448 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449
450 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100451dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452{
453 int i;
454 static struct
455 {
456 char *name;
457 FARPROC *ptr;
458 } libintl_entry[] =
459 {
460 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200461 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000462 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
463 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
464 {NULL, NULL}
465 };
466
467 /* No need to initialize twice. */
468 if (hLibintlDLL)
469 return 1;
470 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100471 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100472#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100473 if (!hLibintlDLL)
474 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100475#endif
476 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200478 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200480 verbose_enter();
481 EMSG2(_(e_loadlib), GETTEXT_DLL);
482 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000483 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200484 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000485 }
486 for (i = 0; libintl_entry[i].name != NULL
487 && libintl_entry[i].ptr != NULL; ++i)
488 {
489 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
490 libintl_entry[i].name)) == NULL)
491 {
492 dyn_libintl_end();
493 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000494 {
495 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000497 verbose_leave();
498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000499 return 0;
500 }
501 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000502
503 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000504 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000505 "bind_textdomain_codeset");
506 if (dyn_libintl_bind_textdomain_codeset == NULL)
507 dyn_libintl_bind_textdomain_codeset =
508 null_libintl_bind_textdomain_codeset;
509
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510 return 1;
511}
512
513 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100514dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515{
516 if (hLibintlDLL)
517 FreeLibrary(hLibintlDLL);
518 hLibintlDLL = NULL;
519 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200520 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000521 dyn_libintl_textdomain = null_libintl_textdomain;
522 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000523 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524}
525
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000526/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000527 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000528null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000529{
530 return (char*)msgid;
531}
532
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000533/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000534 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200535null_libintl_ngettext(
536 const char *msgid,
537 const char *msgid_plural,
538 unsigned long n)
539{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200540 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200541}
542
543/*ARGSUSED*/
544 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000545null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000546{
547 return NULL;
548}
549
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000550/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000551 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000552null_libintl_bind_textdomain_codeset(const char *domainname,
553 const char *codeset)
554{
555 return NULL;
556}
557
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000558/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000559 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000560null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561{
562 return NULL;
563}
564
565#endif /* DYNAMIC_GETTEXT */
566
567/* This symbol is not defined in older versions of the SDK or Visual C++ */
568
569#ifndef VER_PLATFORM_WIN32_WINDOWS
570# define VER_PLATFORM_WIN32_WINDOWS 1
571#endif
572
573DWORD g_PlatformId;
574
575#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100576# ifndef PROTO
577# include <aclapi.h>
578# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200579# ifndef PROTECTED_DACL_SECURITY_INFORMATION
580# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
581# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582#endif
583
Bram Moolenaar27515922013-06-29 15:36:26 +0200584#ifdef HAVE_ACL
585/*
586 * Enables or disables the specified privilege.
587 */
588 static BOOL
589win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
590{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100591 BOOL bResult;
592 LUID luid;
593 HANDLE hToken;
594 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200595
596 if (!OpenProcessToken(GetCurrentProcess(),
597 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
598 return FALSE;
599
600 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
601 {
602 CloseHandle(hToken);
603 return FALSE;
604 }
605
Bram Moolenaar45500912014-07-09 20:51:07 +0200606 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200607 tokenPrivileges.Privileges[0].Luid = luid;
608 tokenPrivileges.Privileges[0].Attributes = bEnable ?
609 SE_PRIVILEGE_ENABLED : 0;
610
611 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
612 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
613
614 CloseHandle(hToken);
615
616 return bResult && GetLastError() == ERROR_SUCCESS;
617}
618#endif
619
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620/*
621 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
622 * VER_PLATFORM_WIN32_WINDOWS (Win95).
623 */
624 void
625PlatformId(void)
626{
627 static int done = FALSE;
628
629 if (!done)
630 {
631 OSVERSIONINFO ovi;
632
633 ovi.dwOSVersionInfoSize = sizeof(ovi);
634 GetVersionEx(&ovi);
635
636 g_PlatformId = ovi.dwPlatformId;
637
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100638 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
639 || ovi.dwMajorVersion > 6)
640 win8_or_later = TRUE;
641
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200643 /* Enable privilege for getting or setting SACLs. */
644 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000645#endif
646 done = TRUE;
647 }
648}
649
Bram Moolenaar071d4272004-06-13 20:20:40 +0000650#ifndef FEAT_GUI_W32
651
652#define SHIFT (SHIFT_PRESSED)
653#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
654#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
655#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
656
657
658/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
659 * We map function keys to their ANSI terminal equivalents, as produced
660 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
661 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
662 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
663 * combinations of function/arrow/etc keys.
664 */
665
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000666static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000667{
668 WORD wVirtKey;
669 BOOL fAnsiKey;
670 int chAlone;
671 int chShift;
672 int chCtrl;
673 int chAlt;
674} VirtKeyMap[] =
675{
676
677/* Key ANSI alone shift ctrl alt */
678 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
679
680 { VK_F1, TRUE, ';', 'T', '^', 'h', },
681 { VK_F2, TRUE, '<', 'U', '_', 'i', },
682 { VK_F3, TRUE, '=', 'V', '`', 'j', },
683 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
684 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
685 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
686 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
687 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
688 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
689 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
690 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
691 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
692
693 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
694 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
695 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
696 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
697 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
698 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
699 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
700 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
701 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
702 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
703
704 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
705
706#if 0
707 /* Most people don't have F13-F20, but what the hell... */
708 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
709 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
710 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
711 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
712 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
713 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
714 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
715 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
716#endif
717 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
718 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
719 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
720 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
721
722 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
723 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
724 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
725 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
726 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
727 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
728 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
729 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
730 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
731 /* Sorry, out of number space! <negri>*/
732 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
733
734};
735
736
737#ifdef _MSC_VER
738// The ToAscii bug destroys several registers. Need to turn off optimization
739// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000740# pragma warning(push)
741# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742# pragma optimize("", off)
743#endif
744
745#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200746# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200748# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000749#endif
750
751/* The return code indicates key code size. */
752 static int
753#ifdef __BORLANDC__
754 __stdcall
755#endif
756win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000757 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758{
759 UINT uMods = pker->dwControlKeyState;
760 static int s_iIsDead = 0;
761 static WORD awAnsiCode[2];
762 static BYTE abKeystate[256];
763
764
765 if (s_iIsDead == 2)
766 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200767 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768 s_iIsDead = 0;
769 return 1;
770 }
771
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200772 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773 return 1;
774
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200775 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000776
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200778 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000779
780 if (uMods & SHIFT_PRESSED)
781 abKeystate[VK_SHIFT] = 0x80;
782 if (uMods & CAPSLOCK_ON)
783 abKeystate[VK_CAPITAL] = 1;
784
785 if ((uMods & ALT_GR) == ALT_GR)
786 {
787 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
788 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
789 }
790
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200791 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
792 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000793
794 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200795 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000796
797 return s_iIsDead;
798}
799
800#ifdef _MSC_VER
801/* MUST switch optimization on again here, otherwise a call to
802 * decode_key_event() may crash (e.g. when hitting caps-lock) */
803# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000804# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805
806# if (_MSC_VER < 1100)
807/* MUST turn off global optimisation for this next function, or
808 * pressing ctrl-minus in insert mode crashes Vim when built with
809 * VC4.1. -- negri. */
810# pragma optimize("g", off)
811# endif
812#endif
813
814static BOOL g_fJustGotFocus = FALSE;
815
816/*
817 * Decode a KEY_EVENT into one or two keystrokes
818 */
819 static BOOL
820decode_key_event(
821 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200822 WCHAR *pch,
823 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000824 int *pmodifiers,
825 BOOL fDoPost)
826{
827 int i;
828 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
829
830 *pch = *pch2 = NUL;
831 g_fJustGotFocus = FALSE;
832
833 /* ignore key up events */
834 if (!pker->bKeyDown)
835 return FALSE;
836
837 /* ignore some keystrokes */
838 switch (pker->wVirtualKeyCode)
839 {
840 /* modifiers */
841 case VK_SHIFT:
842 case VK_CONTROL:
843 case VK_MENU: /* Alt key */
844 return FALSE;
845
846 default:
847 break;
848 }
849
850 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200851 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000852 {
853 /* Ctrl-6 is Ctrl-^ */
854 if (pker->wVirtualKeyCode == '6')
855 {
856 *pch = Ctrl_HAT;
857 return TRUE;
858 }
859 /* Ctrl-2 is Ctrl-@ */
860 else if (pker->wVirtualKeyCode == '2')
861 {
862 *pch = NUL;
863 return TRUE;
864 }
865 /* Ctrl-- is Ctrl-_ */
866 else if (pker->wVirtualKeyCode == 0xBD)
867 {
868 *pch = Ctrl__;
869 return TRUE;
870 }
871 }
872
873 /* Shift-TAB */
874 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
875 {
876 *pch = K_NUL;
877 *pch2 = '\017';
878 return TRUE;
879 }
880
881 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
882 {
883 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
884 {
885 if (nModifs == 0)
886 *pch = VirtKeyMap[i].chAlone;
887 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
888 *pch = VirtKeyMap[i].chShift;
889 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
890 *pch = VirtKeyMap[i].chCtrl;
891 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
892 *pch = VirtKeyMap[i].chAlt;
893
894 if (*pch != 0)
895 {
896 if (VirtKeyMap[i].fAnsiKey)
897 {
898 *pch2 = *pch;
899 *pch = K_NUL;
900 }
901
902 return TRUE;
903 }
904 }
905 }
906
907 i = win32_kbd_patch_key(pker);
908
909 if (i < 0)
910 *pch = NUL;
911 else
912 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200913 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914
915 if (pmodifiers != NULL)
916 {
917 /* Pass on the ALT key as a modifier, but only when not combined
918 * with CTRL (which is ALTGR). */
919 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
920 *pmodifiers |= MOD_MASK_ALT;
921
922 /* Pass on SHIFT only for special keys, because we don't know when
923 * it's already included with the character. */
924 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
925 *pmodifiers |= MOD_MASK_SHIFT;
926
927 /* Pass on CTRL only for non-special keys, because we don't know
928 * when it's already included with the character. And not when
929 * combined with ALT (which is ALTGR). */
930 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
931 && *pch >= 0x20 && *pch < 0x80)
932 *pmodifiers |= MOD_MASK_CTRL;
933 }
934 }
935
936 return (*pch != NUL);
937}
938
939#ifdef _MSC_VER
940# pragma optimize("", on)
941#endif
942
943#endif /* FEAT_GUI_W32 */
944
945
946#ifdef FEAT_MOUSE
947
948/*
949 * For the GUI the mouse handling is in gui_w32.c.
950 */
951# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000952/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000954mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000955{
956}
957# else
958static int g_fMouseAvail = FALSE; /* mouse present */
959static int g_fMouseActive = FALSE; /* mouse enabled */
960static int g_nMouseClick = -1; /* mouse status */
961static int g_xMouse; /* mouse x coordinate */
962static int g_yMouse; /* mouse y coordinate */
963
964/*
965 * Enable or disable mouse input
966 */
967 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000968mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969{
970 DWORD cmodein;
971
972 if (!g_fMouseAvail)
973 return;
974
975 g_fMouseActive = on;
976 GetConsoleMode(g_hConIn, &cmodein);
977
978 if (g_fMouseActive)
979 cmodein |= ENABLE_MOUSE_INPUT;
980 else
981 cmodein &= ~ENABLE_MOUSE_INPUT;
982
983 SetConsoleMode(g_hConIn, cmodein);
984}
985
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986/*
987 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
988 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
989 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
990 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
991 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
992 * and we return the mouse position in g_xMouse and g_yMouse.
993 *
994 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
995 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
996 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
997 *
998 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
999 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1000 *
1001 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1002 * moves, even if it stays within the same character cell. We ignore
1003 * all MOUSE_MOVED messages if the position hasn't really changed, and
1004 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1005 * we're only interested in MOUSE_DRAG).
1006 *
1007 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1008 * 2-button mouses by pressing the left & right buttons simultaneously.
1009 * In practice, it's almost impossible to click both at the same time,
1010 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1011 * in such cases, if the user is clicking quickly.
1012 */
1013 static BOOL
1014decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001015 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016{
1017 static int s_nOldButton = -1;
1018 static int s_nOldMouseClick = -1;
1019 static int s_xOldMouse = -1;
1020 static int s_yOldMouse = -1;
1021 static linenr_T s_old_topline = 0;
1022#ifdef FEAT_DIFF
1023 static int s_old_topfill = 0;
1024#endif
1025 static int s_cClicks = 1;
1026 static BOOL s_fReleased = TRUE;
1027 static DWORD s_dwLastClickTime = 0;
1028 static BOOL s_fNextIsMiddle = FALSE;
1029
1030 static DWORD cButtons = 0; /* number of buttons supported */
1031
1032 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1033 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1034 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1035 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1036
1037 int nButton;
1038
1039 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1040 cButtons = 2;
1041
1042 if (!g_fMouseAvail || !g_fMouseActive)
1043 {
1044 g_nMouseClick = -1;
1045 return FALSE;
1046 }
1047
1048 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1049 if (g_fJustGotFocus)
1050 {
1051 g_fJustGotFocus = FALSE;
1052 return FALSE;
1053 }
1054
1055 /* unprocessed mouse click? */
1056 if (g_nMouseClick != -1)
1057 return TRUE;
1058
1059 nButton = -1;
1060 g_xMouse = pmer->dwMousePosition.X;
1061 g_yMouse = pmer->dwMousePosition.Y;
1062
1063 if (pmer->dwEventFlags == MOUSE_MOVED)
1064 {
1065 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1066 * events even when the mouse moves only within a char cell.) */
1067 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1068 return FALSE;
1069 }
1070
1071 /* If no buttons are pressed... */
1072 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1073 {
1074 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1075 if (s_fReleased)
1076 return FALSE;
1077
1078 nButton = MOUSE_RELEASE;
1079 s_fReleased = TRUE;
1080 }
1081 else /* one or more buttons pressed */
1082 {
1083 /* on a 2-button mouse, hold down left and right buttons
1084 * simultaneously to get MIDDLE. */
1085
1086 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1087 {
1088 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1089
1090 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001091 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 if (dwLR == LEFT || dwLR == RIGHT)
1093 {
1094 for (;;)
1095 {
1096 /* wait a short time for next input event */
1097 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1098 != WAIT_OBJECT_0)
1099 break;
1100 else
1101 {
1102 DWORD cRecords = 0;
1103 INPUT_RECORD ir;
1104 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1105
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001106 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107
1108 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1109 || !(pmer2->dwButtonState & LEFT_RIGHT))
1110 break;
1111 else
1112 {
1113 if (pmer2->dwEventFlags != MOUSE_MOVED)
1114 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001115 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116
1117 return decode_mouse_event(pmer2);
1118 }
1119 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1120 s_yOldMouse == pmer2->dwMousePosition.Y)
1121 {
1122 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001123 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124
1125 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001126 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127
1128 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1129 break;
1130 }
1131 else
1132 break;
1133 }
1134 }
1135 }
1136 }
1137 }
1138
1139 if (s_fNextIsMiddle)
1140 {
1141 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1142 ? MOUSE_DRAG : MOUSE_MIDDLE;
1143 s_fNextIsMiddle = FALSE;
1144 }
1145 else if (cButtons == 2 &&
1146 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1147 {
1148 nButton = MOUSE_MIDDLE;
1149
1150 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1151 {
1152 s_fNextIsMiddle = TRUE;
1153 nButton = MOUSE_RELEASE;
1154 }
1155 }
1156 else if ((pmer->dwButtonState & LEFT) == LEFT)
1157 nButton = MOUSE_LEFT;
1158 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1159 nButton = MOUSE_MIDDLE;
1160 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1161 nButton = MOUSE_RIGHT;
1162
1163 if (! s_fReleased && ! s_fNextIsMiddle
1164 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1165 return FALSE;
1166
1167 s_fReleased = s_fNextIsMiddle;
1168 }
1169
1170 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1171 {
1172 /* button pressed or released, without mouse moving */
1173 if (nButton != -1 && nButton != MOUSE_RELEASE)
1174 {
1175 DWORD dwCurrentTime = GetTickCount();
1176
1177 if (s_xOldMouse != g_xMouse
1178 || s_yOldMouse != g_yMouse
1179 || s_nOldButton != nButton
1180 || s_old_topline != curwin->w_topline
1181#ifdef FEAT_DIFF
1182 || s_old_topfill != curwin->w_topfill
1183#endif
1184 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1185 {
1186 s_cClicks = 1;
1187 }
1188 else if (++s_cClicks > 4)
1189 {
1190 s_cClicks = 1;
1191 }
1192
1193 s_dwLastClickTime = dwCurrentTime;
1194 }
1195 }
1196 else if (pmer->dwEventFlags == MOUSE_MOVED)
1197 {
1198 if (nButton != -1 && nButton != MOUSE_RELEASE)
1199 nButton = MOUSE_DRAG;
1200
1201 s_cClicks = 1;
1202 }
1203
1204 if (nButton == -1)
1205 return FALSE;
1206
1207 if (nButton != MOUSE_RELEASE)
1208 s_nOldButton = nButton;
1209
1210 g_nMouseClick = nButton;
1211
1212 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1213 g_nMouseClick |= MOUSE_SHIFT;
1214 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1215 g_nMouseClick |= MOUSE_CTRL;
1216 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1217 g_nMouseClick |= MOUSE_ALT;
1218
1219 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1220 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1221
1222 /* only pass on interesting (i.e., different) mouse events */
1223 if (s_xOldMouse == g_xMouse
1224 && s_yOldMouse == g_yMouse
1225 && s_nOldMouseClick == g_nMouseClick)
1226 {
1227 g_nMouseClick = -1;
1228 return FALSE;
1229 }
1230
1231 s_xOldMouse = g_xMouse;
1232 s_yOldMouse = g_yMouse;
1233 s_old_topline = curwin->w_topline;
1234#ifdef FEAT_DIFF
1235 s_old_topfill = curwin->w_topfill;
1236#endif
1237 s_nOldMouseClick = g_nMouseClick;
1238
1239 return TRUE;
1240}
1241
1242# endif /* FEAT_GUI_W32 */
1243#endif /* FEAT_MOUSE */
1244
1245
1246#ifdef MCH_CURSOR_SHAPE
1247/*
1248 * Set the shape of the cursor.
1249 * 'thickness' can be from 1 (thin) to 99 (block)
1250 */
1251 static void
1252mch_set_cursor_shape(int thickness)
1253{
1254 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1255 ConsoleCursorInfo.dwSize = thickness;
1256 ConsoleCursorInfo.bVisible = s_cursor_visible;
1257
1258 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1259 if (s_cursor_visible)
1260 SetConsoleCursorPosition(g_hConOut, g_coord);
1261}
1262
1263 void
1264mch_update_cursor(void)
1265{
1266 int idx;
1267 int thickness;
1268
1269 /*
1270 * How the cursor is drawn depends on the current mode.
1271 */
1272 idx = get_shape_idx(FALSE);
1273
1274 if (shape_table[idx].shape == SHAPE_BLOCK)
1275 thickness = 99; /* 100 doesn't work on W95 */
1276 else
1277 thickness = shape_table[idx].percentage;
1278 mch_set_cursor_shape(thickness);
1279}
1280#endif
1281
1282#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1283/*
1284 * Handle FOCUS_EVENT.
1285 */
1286 static void
1287handle_focus_event(INPUT_RECORD ir)
1288{
1289 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1290 ui_focus_change((int)g_fJustGotFocus);
1291}
1292
1293/*
1294 * Wait until console input from keyboard or mouse is available,
1295 * or the time is up.
1296 * Return TRUE if something is available FALSE if not.
1297 */
1298 static int
1299WaitForChar(long msec)
1300{
1301 DWORD dwNow = 0, dwEndTime = 0;
1302 INPUT_RECORD ir;
1303 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001304 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001305#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001306 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001307#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001308
1309 if (msec > 0)
1310 /* Wait until the specified time has elapsed. */
1311 dwEndTime = GetTickCount() + msec;
1312 else if (msec < 0)
1313 /* Wait forever. */
1314 dwEndTime = INFINITE;
1315
1316 /* We need to loop until the end of the time period, because
1317 * we might get multiple unusable mouse events in that time.
1318 */
1319 for (;;)
1320 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001321#ifdef MESSAGE_QUEUE
1322 parse_queued_messages();
1323#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001324#ifdef FEAT_MZSCHEME
1325 mzvim_check_threads();
1326#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327#ifdef FEAT_CLIENTSERVER
1328 serverProcessPendingMessages();
1329#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001330
Bram Moolenaar071d4272004-06-13 20:20:40 +00001331 if (0
1332#ifdef FEAT_MOUSE
1333 || g_nMouseClick != -1
1334#endif
1335#ifdef FEAT_CLIENTSERVER
1336 || input_available()
1337#endif
1338 )
1339 return TRUE;
1340
1341 if (msec > 0)
1342 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001343 /* If the specified wait time has passed, return. Beware that
1344 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001346 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001347 break;
1348 }
1349 if (msec != 0)
1350 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001351 DWORD dwWaitTime = dwEndTime - dwNow;
1352
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001353#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar9186a272016-02-23 19:34:01 +01001354 /* Check channel while waiting input. */
1355 if (dwWaitTime > 100)
1356 dwWaitTime = 100;
1357#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001358#ifdef FEAT_MZSCHEME
1359 if (mzthreads_allowed() && p_mzq > 0
1360 && (msec < 0 || (long)dwWaitTime > p_mzq))
1361 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1362#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001363#ifdef FEAT_TIMERS
1364 {
1365 long due_time;
1366
1367 /* When waiting very briefly don't trigger timers. */
1368 if (dwWaitTime > 10)
1369 {
1370 /* Trigger timers and then get the time in msec until the
1371 * next one is due. Wait up to that time. */
1372 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001373 if (typebuf.tb_change_cnt != tb_change_cnt)
1374 {
1375 /* timer may have used feedkeys() */
1376 return FALSE;
1377 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001378 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1379 dwWaitTime = due_time;
1380 }
1381 }
1382#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001383#ifdef FEAT_CLIENTSERVER
1384 /* Wait for either an event on the console input or a message in
1385 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001386 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001387 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001389 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001390#endif
1391 continue;
1392 }
1393
1394 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001395 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001396
1397#ifdef FEAT_MBYTE_IME
1398 if (State & CMDLINE && msg_row == Rows - 1)
1399 {
1400 CONSOLE_SCREEN_BUFFER_INFO csbi;
1401
1402 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1403 {
1404 if (csbi.dwCursorPosition.Y != msg_row)
1405 {
1406 /* The screen is now messed up, must redraw the
1407 * command line and later all the windows. */
1408 redraw_all_later(CLEAR);
1409 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1410 redrawcmd();
1411 }
1412 }
1413 }
1414#endif
1415
1416 if (cRecords > 0)
1417 {
1418 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1419 {
1420#ifdef FEAT_MBYTE_IME
1421 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1422 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001423 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001424 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1425 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001426 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001427 continue;
1428 }
1429#endif
1430 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1431 NULL, FALSE))
1432 return TRUE;
1433 }
1434
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001435 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001436
1437 if (ir.EventType == FOCUS_EVENT)
1438 handle_focus_event(ir);
1439 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1440 shell_resized();
1441#ifdef FEAT_MOUSE
1442 else if (ir.EventType == MOUSE_EVENT
1443 && decode_mouse_event(&ir.Event.MouseEvent))
1444 return TRUE;
1445#endif
1446 }
1447 else if (msec == 0)
1448 break;
1449 }
1450
1451#ifdef FEAT_CLIENTSERVER
1452 /* Something might have been received while we were waiting. */
1453 if (input_available())
1454 return TRUE;
1455#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001456
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457 return FALSE;
1458}
1459
1460#ifndef FEAT_GUI_MSWIN
1461/*
1462 * return non-zero if a character is available
1463 */
1464 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001465mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466{
1467 return WaitForChar(0L);
1468}
1469#endif
1470
1471/*
1472 * Create the console input. Used when reading stdin doesn't work.
1473 */
1474 static void
1475create_conin(void)
1476{
1477 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1478 FILE_SHARE_READ|FILE_SHARE_WRITE,
1479 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001480 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001481 did_create_conin = TRUE;
1482}
1483
1484/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001485 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001487 static WCHAR
1488tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001489{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001490 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491
1492 for (;;)
1493 {
1494 INPUT_RECORD ir;
1495 DWORD cRecords = 0;
1496
1497#ifdef FEAT_CLIENTSERVER
1498 (void)WaitForChar(-1L);
1499 if (input_available())
1500 return 0;
1501# ifdef FEAT_MOUSE
1502 if (g_nMouseClick != -1)
1503 return 0;
1504# endif
1505#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001506 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507 {
1508 if (did_create_conin)
1509 read_error_exit();
1510 create_conin();
1511 continue;
1512 }
1513
1514 if (ir.EventType == KEY_EVENT)
1515 {
1516 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1517 pmodifiers, TRUE))
1518 return ch;
1519 }
1520 else if (ir.EventType == FOCUS_EVENT)
1521 handle_focus_event(ir);
1522 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1523 shell_resized();
1524#ifdef FEAT_MOUSE
1525 else if (ir.EventType == MOUSE_EVENT)
1526 {
1527 if (decode_mouse_event(&ir.Event.MouseEvent))
1528 return 0;
1529 }
1530#endif
1531 }
1532}
1533#endif /* !FEAT_GUI_W32 */
1534
1535
1536/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001537 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538 * Get one or more characters from the keyboard or the mouse.
1539 * If time == 0, do not wait for characters.
1540 * If time == n, wait a short time for characters.
1541 * If time == -1, wait forever for characters.
1542 * Returns the number of characters read into buf.
1543 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001544/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545 int
1546mch_inchar(
1547 char_u *buf,
1548 int maxlen,
1549 long time,
1550 int tb_change_cnt)
1551{
1552#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1553
1554 int len;
1555 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001556#define TYPEAHEADLEN 20
1557 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1558 static int typeaheadlen = 0;
1559
1560 /* First use any typeahead that was kept because "buf" was too small. */
1561 if (typeaheadlen > 0)
1562 goto theend;
1563
Bram Moolenaar071d4272004-06-13 20:20:40 +00001564 if (time >= 0)
1565 {
1566 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001567 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568 }
1569 else /* time == -1, wait forever */
1570 {
1571 mch_set_winsize_now(); /* Allow winsize changes from now on */
1572
Bram Moolenaar3918c952005-03-15 22:34:55 +00001573 /*
1574 * If there is no character available within 2 seconds (default)
1575 * write the autoscript file to disk. Or cause the CursorHold event
1576 * to be triggered.
1577 */
1578 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001579 {
1580#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001581 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001583 buf[0] = K_SPECIAL;
1584 buf[1] = KS_EXTRA;
1585 buf[2] = (int)KE_CURSORHOLD;
1586 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587 }
1588#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001589 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001590 }
1591 }
1592
1593 /*
1594 * Try to read as many characters as there are, until the buffer is full.
1595 */
1596
1597 /* we will get at least one key. Get more if they are available. */
1598 g_fCBrkPressed = FALSE;
1599
1600#ifdef MCH_WRITE_DUMP
1601 if (fdDump)
1602 fputc('[', fdDump);
1603#endif
1604
1605 /* Keep looping until there is something in the typeahead buffer and more
1606 * to get and still room in the buffer (up to two bytes for a char and
1607 * three bytes for a modifier). */
1608 while ((typeaheadlen == 0 || WaitForChar(0L))
1609 && typeaheadlen + 5 <= TYPEAHEADLEN)
1610 {
1611 if (typebuf_changed(tb_change_cnt))
1612 {
1613 /* "buf" may be invalid now if a client put something in the
1614 * typeahead buffer and "buf" is in the typeahead buffer. */
1615 typeaheadlen = 0;
1616 break;
1617 }
1618#ifdef FEAT_MOUSE
1619 if (g_nMouseClick != -1)
1620 {
1621# ifdef MCH_WRITE_DUMP
1622 if (fdDump)
1623 fprintf(fdDump, "{%02x @ %d, %d}",
1624 g_nMouseClick, g_xMouse, g_yMouse);
1625# endif
1626 typeahead[typeaheadlen++] = ESC + 128;
1627 typeahead[typeaheadlen++] = 'M';
1628 typeahead[typeaheadlen++] = g_nMouseClick;
1629 typeahead[typeaheadlen++] = g_xMouse + '!';
1630 typeahead[typeaheadlen++] = g_yMouse + '!';
1631 g_nMouseClick = -1;
1632 }
1633 else
1634#endif
1635 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001636 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637 int modifiers = 0;
1638
1639 c = tgetch(&modifiers, &ch2);
1640
1641 if (typebuf_changed(tb_change_cnt))
1642 {
1643 /* "buf" may be invalid now if a client put something in the
1644 * typeahead buffer and "buf" is in the typeahead buffer. */
1645 typeaheadlen = 0;
1646 break;
1647 }
1648
1649 if (c == Ctrl_C && ctrl_c_interrupts)
1650 {
1651#if defined(FEAT_CLIENTSERVER)
1652 trash_input_buf();
1653#endif
1654 got_int = TRUE;
1655 }
1656
1657#ifdef FEAT_MOUSE
1658 if (g_nMouseClick == -1)
1659#endif
1660 {
1661 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001662 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001664#ifdef FEAT_MBYTE
1665 if (ch2 == NUL)
1666 {
1667 int i;
1668 char_u *p;
1669 WCHAR ch[2];
1670
1671 ch[0] = c;
1672 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1673 {
1674 ch[1] = tgetch(&modifiers, &ch2);
1675 n++;
1676 }
1677 p = utf16_to_enc(ch, &n);
1678 if (p != NULL)
1679 {
1680 for (i = 0; i < n; i++)
1681 typeahead[typeaheadlen + i] = p[i];
1682 vim_free(p);
1683 }
1684 }
1685 else
1686#endif
1687 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 if (ch2 != NUL)
1689 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001690 typeahead[typeaheadlen + n] = 3;
1691 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001692 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694
Bram Moolenaar45500912014-07-09 20:51:07 +02001695 if (conv)
1696 {
1697 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001698
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001699 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001700 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001701 char_u *e = typeahead + TYPEAHEADLEN;
1702
1703 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001704 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001705 if (*p == K_NUL)
1706 {
1707 ++p;
1708 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1709 *p = 3;
1710 ++n;
1711 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001712 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001713 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001714 }
1715 }
1716
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 /* Use the ALT key to set the 8th bit of the character
1718 * when it's one byte, the 8th bit isn't set yet and not
1719 * using a double-byte encoding (would become a lead
1720 * byte). */
1721 if ((modifiers & MOD_MASK_ALT)
1722 && n == 1
1723 && (typeahead[typeaheadlen] & 0x80) == 0
1724#ifdef FEAT_MBYTE
1725 && !enc_dbcs
1726#endif
1727 )
1728 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001729#ifdef FEAT_MBYTE
1730 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1731 typeahead + typeaheadlen);
1732#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001733 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001734#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001735 modifiers &= ~MOD_MASK_ALT;
1736 }
1737
1738 if (modifiers != 0)
1739 {
1740 /* Prepend modifiers to the character. */
1741 mch_memmove(typeahead + typeaheadlen + 3,
1742 typeahead + typeaheadlen, n);
1743 typeahead[typeaheadlen++] = K_SPECIAL;
1744 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1745 typeahead[typeaheadlen++] = modifiers;
1746 }
1747
1748 typeaheadlen += n;
1749
1750#ifdef MCH_WRITE_DUMP
1751 if (fdDump)
1752 fputc(c, fdDump);
1753#endif
1754 }
1755 }
1756 }
1757
1758#ifdef MCH_WRITE_DUMP
1759 if (fdDump)
1760 {
1761 fputs("]\n", fdDump);
1762 fflush(fdDump);
1763 }
1764#endif
1765
Bram Moolenaar071d4272004-06-13 20:20:40 +00001766theend:
1767 /* Move typeahead to "buf", as much as fits. */
1768 len = 0;
1769 while (len < maxlen && typeaheadlen > 0)
1770 {
1771 buf[len++] = typeahead[0];
1772 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1773 }
1774 return len;
1775
1776#else /* FEAT_GUI_W32 */
1777 return 0;
1778#endif /* FEAT_GUI_W32 */
1779}
1780
Bram Moolenaar82881492012-11-20 16:53:39 +01001781#ifndef PROTO
1782# ifndef __MINGW32__
1783# include <shellapi.h> /* required for FindExecutable() */
1784# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001785#endif
1786
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001787/*
1788 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001789 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001790 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001792executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001794 char *dum;
1795 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001796 char *curpath, *newpath;
1797 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001799#ifdef FEAT_MBYTE
1800 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001802 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001803 WCHAR fnamew[_MAX_PATH];
1804 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001805 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001806
1807 if (p != NULL)
1808 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001809 wcurpath = _wgetenv(L"PATH");
1810 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1811 * sizeof(WCHAR));
1812 if (wnewpath == NULL)
1813 return FALSE;
1814 wcscpy(wnewpath, L".;");
1815 wcscat(wnewpath, wcurpath);
1816 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1817 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001818 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02001819 if (n == 0)
1820 return FALSE;
1821 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1822 return FALSE;
1823 if (path != NULL)
1824 *path = utf16_to_enc(fnamew, NULL);
1825 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001826 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001827 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001828#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001829
1830 curpath = getenv("PATH");
1831 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1832 if (newpath == NULL)
1833 return FALSE;
1834 STRCPY(newpath, ".;");
1835 STRCAT(newpath, curpath);
1836 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1837 vim_free(newpath);
1838 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001839 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001840 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001841 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001842 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001843 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001844 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001845}
1846
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001847#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001848 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001849/*
1850 * Bad parameter handler.
1851 *
1852 * Certain MS CRT functions will intentionally crash when passed invalid
1853 * parameters to highlight possible security holes. Setting this function as
1854 * the bad parameter handler will prevent the crash.
1855 *
1856 * In debug builds the parameters contain CRT information that might help track
1857 * down the source of a problem, but in non-debug builds the arguments are all
1858 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1859 * worth allowing these to make debugging of issues easier.
1860 */
1861 static void
1862bad_param_handler(const wchar_t *expression,
1863 const wchar_t *function,
1864 const wchar_t *file,
1865 unsigned int line,
1866 uintptr_t pReserved)
1867{
1868}
1869
1870# define SET_INVALID_PARAM_HANDLER \
1871 ((void)_set_invalid_parameter_handler(bad_param_handler))
1872#else
1873# define SET_INVALID_PARAM_HANDLER
1874#endif
1875
Bram Moolenaar071d4272004-06-13 20:20:40 +00001876#ifdef FEAT_GUI_W32
1877
1878/*
1879 * GUI version of mch_init().
1880 */
1881 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001882mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883{
1884#ifndef __MINGW32__
1885 extern int _fmode;
1886#endif
1887
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001888 /* Silently handle invalid parameters to CRT functions */
1889 SET_INVALID_PARAM_HANDLER;
1890
Bram Moolenaar071d4272004-06-13 20:20:40 +00001891 /* Let critical errors result in a failure, not in a dialog box. Required
1892 * for the timestamp test to work on removed floppies. */
1893 SetErrorMode(SEM_FAILCRITICALERRORS);
1894
1895 _fmode = O_BINARY; /* we do our own CR-LF translation */
1896
1897 /* Specify window size. Is there a place to get the default from? */
1898 Rows = 25;
1899 Columns = 80;
1900
1901 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001902 {
1903 char_u vimrun_location[_MAX_PATH + 4];
1904
1905 /* First try in same directory as gvim.exe */
1906 STRCPY(vimrun_location, exe_name);
1907 STRCPY(gettail(vimrun_location), "vimrun.exe");
1908 if (mch_getperm(vimrun_location) >= 0)
1909 {
1910 if (*skiptowhite(vimrun_location) != NUL)
1911 {
1912 /* Enclose path with white space in double quotes. */
1913 mch_memmove(vimrun_location + 1, vimrun_location,
1914 STRLEN(vimrun_location) + 1);
1915 *vimrun_location = '"';
1916 STRCPY(gettail(vimrun_location), "vimrun\" ");
1917 }
1918 else
1919 STRCPY(gettail(vimrun_location), "vimrun ");
1920
1921 vimrun_path = (char *)vim_strsave(vimrun_location);
1922 s_dont_use_vimrun = FALSE;
1923 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001924 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001925 s_dont_use_vimrun = FALSE;
1926
1927 /* Don't give the warning for a missing vimrun.exe right now, but only
1928 * when vimrun was supposed to be used. Don't bother people that do
1929 * not need vimrun.exe. */
1930 if (s_dont_use_vimrun)
1931 need_vimrun_warning = TRUE;
1932 }
1933
1934 /*
1935 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1936 * Otherwise the default "findstr /n" is used.
1937 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001938 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1940
1941#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001942 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001943#endif
1944}
1945
1946
1947#else /* FEAT_GUI_W32 */
1948
1949#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1950#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1951
1952/*
1953 * ClearConsoleBuffer()
1954 * Description:
1955 * Clears the entire contents of the console screen buffer, using the
1956 * specified attribute.
1957 * Returns:
1958 * TRUE on success
1959 */
1960 static BOOL
1961ClearConsoleBuffer(WORD wAttribute)
1962{
1963 CONSOLE_SCREEN_BUFFER_INFO csbi;
1964 COORD coord;
1965 DWORD NumCells, dummy;
1966
1967 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1968 return FALSE;
1969
1970 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1971 coord.X = 0;
1972 coord.Y = 0;
1973 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1974 coord, &dummy))
1975 {
1976 return FALSE;
1977 }
1978 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1979 coord, &dummy))
1980 {
1981 return FALSE;
1982 }
1983
1984 return TRUE;
1985}
1986
1987/*
1988 * FitConsoleWindow()
1989 * Description:
1990 * Checks if the console window will fit within given buffer dimensions.
1991 * Also, if requested, will shrink the window to fit.
1992 * Returns:
1993 * TRUE on success
1994 */
1995 static BOOL
1996FitConsoleWindow(
1997 COORD dwBufferSize,
1998 BOOL WantAdjust)
1999{
2000 CONSOLE_SCREEN_BUFFER_INFO csbi;
2001 COORD dwWindowSize;
2002 BOOL NeedAdjust = FALSE;
2003
2004 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2005 {
2006 /*
2007 * A buffer resize will fail if the current console window does
2008 * not lie completely within that buffer. To avoid this, we might
2009 * have to move and possibly shrink the window.
2010 */
2011 if (csbi.srWindow.Right >= dwBufferSize.X)
2012 {
2013 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2014 if (dwWindowSize.X > dwBufferSize.X)
2015 dwWindowSize.X = dwBufferSize.X;
2016 csbi.srWindow.Right = dwBufferSize.X - 1;
2017 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2018 NeedAdjust = TRUE;
2019 }
2020 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2021 {
2022 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2023 if (dwWindowSize.Y > dwBufferSize.Y)
2024 dwWindowSize.Y = dwBufferSize.Y;
2025 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2026 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2027 NeedAdjust = TRUE;
2028 }
2029 if (NeedAdjust && WantAdjust)
2030 {
2031 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2032 return FALSE;
2033 }
2034 return TRUE;
2035 }
2036
2037 return FALSE;
2038}
2039
2040typedef struct ConsoleBufferStruct
2041{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002042 BOOL IsValid;
2043 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002044 PCHAR_INFO Buffer;
2045 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002046} ConsoleBuffer;
2047
2048/*
2049 * SaveConsoleBuffer()
2050 * Description:
2051 * Saves important information about the console buffer, including the
2052 * actual buffer contents. The saved information is suitable for later
2053 * restoration by RestoreConsoleBuffer().
2054 * Returns:
2055 * TRUE if all information was saved; FALSE otherwise
2056 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2057 */
2058 static BOOL
2059SaveConsoleBuffer(
2060 ConsoleBuffer *cb)
2061{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002062 DWORD NumCells;
2063 COORD BufferCoord;
2064 SMALL_RECT ReadRegion;
2065 WORD Y, Y_incr;
2066
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 if (cb == NULL)
2068 return FALSE;
2069
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002070 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 {
2072 cb->IsValid = FALSE;
2073 return FALSE;
2074 }
2075 cb->IsValid = TRUE;
2076
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002077 /*
2078 * Allocate a buffer large enough to hold the entire console screen
2079 * buffer. If this ConsoleBuffer structure has already been initialized
2080 * with a buffer of the correct size, then just use that one.
2081 */
2082 if (!cb->IsValid || cb->Buffer == NULL ||
2083 cb->BufferSize.X != cb->Info.dwSize.X ||
2084 cb->BufferSize.Y != cb->Info.dwSize.Y)
2085 {
2086 cb->BufferSize.X = cb->Info.dwSize.X;
2087 cb->BufferSize.Y = cb->Info.dwSize.Y;
2088 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2089 vim_free(cb->Buffer);
2090 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2091 if (cb->Buffer == NULL)
2092 return FALSE;
2093 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094
2095 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002096 * We will now copy the console screen buffer into our buffer.
2097 * ReadConsoleOutput() seems to be limited as far as how much you
2098 * can read at a time. Empirically, this number seems to be about
2099 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2100 * in chunks until it is all copied. The chunks will all have the
2101 * same horizontal characteristics, so initialize them now. The
2102 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002103 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002104 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002105 ReadRegion.Left = 0;
2106 ReadRegion.Right = cb->Info.dwSize.X - 1;
2107 Y_incr = 12000 / cb->Info.dwSize.X;
2108 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002109 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002110 /*
2111 * Read into position (0, Y) in our buffer.
2112 */
2113 BufferCoord.Y = Y;
2114 /*
2115 * Read the region whose top left corner is (0, Y) and whose bottom
2116 * right corner is (width - 1, Y + Y_incr - 1). This should define
2117 * a region of size width by Y_incr. Don't worry if this region is
2118 * too large for the remaining buffer; it will be cropped.
2119 */
2120 ReadRegion.Top = Y;
2121 ReadRegion.Bottom = Y + Y_incr - 1;
2122 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2123 cb->Buffer, /* our buffer */
2124 cb->BufferSize, /* dimensions of our buffer */
2125 BufferCoord, /* offset in our buffer */
2126 &ReadRegion)) /* region to save */
2127 {
2128 vim_free(cb->Buffer);
2129 cb->Buffer = NULL;
2130 return FALSE;
2131 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132 }
2133
2134 return TRUE;
2135}
2136
2137/*
2138 * RestoreConsoleBuffer()
2139 * Description:
2140 * Restores important information about the console buffer, including the
2141 * actual buffer contents, if desired. The information to restore is in
2142 * the same format used by SaveConsoleBuffer().
2143 * Returns:
2144 * TRUE on success
2145 */
2146 static BOOL
2147RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002148 ConsoleBuffer *cb,
2149 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002150{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002151 COORD BufferCoord;
2152 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002153
2154 if (cb == NULL || !cb->IsValid)
2155 return FALSE;
2156
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002157 /*
2158 * Before restoring the buffer contents, clear the current buffer, and
2159 * restore the cursor position and window information. Doing this now
2160 * prevents old buffer contents from "flashing" onto the screen.
2161 */
2162 if (RestoreScreen)
2163 ClearConsoleBuffer(cb->Info.wAttributes);
2164
2165 FitConsoleWindow(cb->Info.dwSize, TRUE);
2166 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2167 return FALSE;
2168 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2169 return FALSE;
2170
2171 if (!RestoreScreen)
2172 {
2173 /*
2174 * No need to restore the screen buffer contents, so we're done.
2175 */
2176 return TRUE;
2177 }
2178
2179 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2180 return FALSE;
2181 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2182 return FALSE;
2183
2184 /*
2185 * Restore the screen buffer contents.
2186 */
2187 if (cb->Buffer != NULL)
2188 {
2189 BufferCoord.X = 0;
2190 BufferCoord.Y = 0;
2191 WriteRegion.Left = 0;
2192 WriteRegion.Top = 0;
2193 WriteRegion.Right = cb->Info.dwSize.X - 1;
2194 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2195 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2196 cb->Buffer, /* our buffer */
2197 cb->BufferSize, /* dimensions of our buffer */
2198 BufferCoord, /* offset in our buffer */
2199 &WriteRegion)) /* region to restore */
2200 {
2201 return FALSE;
2202 }
2203 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002204
2205 return TRUE;
2206}
2207
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002208#define FEAT_RESTORE_ORIG_SCREEN
2209#ifdef FEAT_RESTORE_ORIG_SCREEN
2210static ConsoleBuffer g_cbOrig = { 0 };
2211#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002212static ConsoleBuffer g_cbNonTermcap = { 0 };
2213static ConsoleBuffer g_cbTermcap = { 0 };
2214
2215#ifdef FEAT_TITLE
2216#ifdef __BORLANDC__
2217typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2218#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002219typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220#endif
2221char g_szOrigTitle[256] = { 0 };
2222HWND g_hWnd = NULL; /* also used in os_mswin.c */
2223static HICON g_hOrigIconSmall = NULL;
2224static HICON g_hOrigIcon = NULL;
2225static HICON g_hVimIcon = NULL;
2226static BOOL g_fCanChangeIcon = FALSE;
2227
2228/* ICON* are not defined in VC++ 4.0 */
2229#ifndef ICON_SMALL
2230#define ICON_SMALL 0
2231#endif
2232#ifndef ICON_BIG
2233#define ICON_BIG 1
2234#endif
2235/*
2236 * GetConsoleIcon()
2237 * Description:
2238 * Attempts to retrieve the small icon and/or the big icon currently in
2239 * use by a given window.
2240 * Returns:
2241 * TRUE on success
2242 */
2243 static BOOL
2244GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002245 HWND hWnd,
2246 HICON *phIconSmall,
2247 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002248{
2249 if (hWnd == NULL)
2250 return FALSE;
2251
2252 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002253 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2254 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002256 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2257 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002258 return TRUE;
2259}
2260
2261/*
2262 * SetConsoleIcon()
2263 * Description:
2264 * Attempts to change the small icon and/or the big icon currently in
2265 * use by a given window.
2266 * Returns:
2267 * TRUE on success
2268 */
2269 static BOOL
2270SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002271 HWND hWnd,
2272 HICON hIconSmall,
2273 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002275 if (hWnd == NULL)
2276 return FALSE;
2277
2278 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002279 SendMessage(hWnd, WM_SETICON,
2280 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002282 SendMessage(hWnd, WM_SETICON,
2283 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284 return TRUE;
2285}
2286
2287/*
2288 * SaveConsoleTitleAndIcon()
2289 * Description:
2290 * Saves the current console window title in g_szOrigTitle, for later
2291 * restoration. Also, attempts to obtain a handle to the console window,
2292 * and use it to save the small and big icons currently in use by the
2293 * console window. This is not always possible on some versions of Windows;
2294 * nor is it possible when running Vim remotely using Telnet (since the
2295 * console window the user sees is owned by a remote process).
2296 */
2297 static void
2298SaveConsoleTitleAndIcon(void)
2299{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300 /* Save the original title. */
2301 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2302 return;
2303
2304 /*
2305 * Obtain a handle to the console window using GetConsoleWindow() from
2306 * KERNEL32.DLL; we need to handle in order to change the window icon.
2307 * This function only exists on NT-based Windows, starting with Windows
2308 * 2000. On older operating systems, we can't change the window icon
2309 * anyway.
2310 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002311 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312 if (g_hWnd == NULL)
2313 return;
2314
2315 /* Save the original console window icon. */
2316 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2317 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2318 return;
2319
2320 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002321 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002322 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323 if (g_hVimIcon != NULL)
2324 g_fCanChangeIcon = TRUE;
2325}
2326#endif
2327
2328static int g_fWindInitCalled = FALSE;
2329static int g_fTermcapMode = FALSE;
2330static CONSOLE_CURSOR_INFO g_cci;
2331static DWORD g_cmodein = 0;
2332static DWORD g_cmodeout = 0;
2333
2334/*
2335 * non-GUI version of mch_init().
2336 */
2337 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002338mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002340#ifndef FEAT_RESTORE_ORIG_SCREEN
2341 CONSOLE_SCREEN_BUFFER_INFO csbi;
2342#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002343#ifndef __MINGW32__
2344 extern int _fmode;
2345#endif
2346
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002347 /* Silently handle invalid parameters to CRT functions */
2348 SET_INVALID_PARAM_HANDLER;
2349
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350 /* Let critical errors result in a failure, not in a dialog box. Required
2351 * for the timestamp test to work on removed floppies. */
2352 SetErrorMode(SEM_FAILCRITICALERRORS);
2353
2354 _fmode = O_BINARY; /* we do our own CR-LF translation */
2355 out_flush();
2356
2357 /* Obtain handles for the standard Console I/O devices */
2358 if (read_cmd_fd == 0)
2359 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2360 else
2361 create_conin();
2362 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2363
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002364#ifdef FEAT_RESTORE_ORIG_SCREEN
2365 /* Save the initial console buffer for later restoration */
2366 SaveConsoleBuffer(&g_cbOrig);
2367 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2368#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002369 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002370 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2371 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2372#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002373 if (cterm_normal_fg_color == 0)
2374 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2375 if (cterm_normal_bg_color == 0)
2376 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2377
2378 /* set termcap codes to current text attributes */
2379 update_tcap(g_attrCurrent);
2380
2381 GetConsoleCursorInfo(g_hConOut, &g_cci);
2382 GetConsoleMode(g_hConIn, &g_cmodein);
2383 GetConsoleMode(g_hConOut, &g_cmodeout);
2384
2385#ifdef FEAT_TITLE
2386 SaveConsoleTitleAndIcon();
2387 /*
2388 * Set both the small and big icons of the console window to Vim's icon.
2389 * Note that Vim presently only has one size of icon (32x32), but it
2390 * automatically gets scaled down to 16x16 when setting the small icon.
2391 */
2392 if (g_fCanChangeIcon)
2393 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2394#endif
2395
2396 ui_get_shellsize();
2397
2398#ifdef MCH_WRITE_DUMP
2399 fdDump = fopen("dump", "wt");
2400
2401 if (fdDump)
2402 {
2403 time_t t;
2404
2405 time(&t);
2406 fputs(ctime(&t), fdDump);
2407 fflush(fdDump);
2408 }
2409#endif
2410
2411 g_fWindInitCalled = TRUE;
2412
2413#ifdef FEAT_MOUSE
2414 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2415#endif
2416
2417#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002418 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420}
2421
2422/*
2423 * non-GUI version of mch_exit().
2424 * Shut down and exit with status `r'
2425 * Careful: mch_exit() may be called before mch_init()!
2426 */
2427 void
2428mch_exit(int r)
2429{
2430 stoptermcap();
2431
2432 if (g_fWindInitCalled)
2433 settmode(TMODE_COOK);
2434
2435 ml_close_all(TRUE); /* remove all memfiles */
2436
2437 if (g_fWindInitCalled)
2438 {
2439#ifdef FEAT_TITLE
2440 mch_restore_title(3);
2441 /*
2442 * Restore both the small and big icons of the console window to
2443 * what they were at startup. Don't do this when the window is
2444 * closed, Vim would hang here.
2445 */
2446 if (g_fCanChangeIcon && !g_fForceExit)
2447 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2448#endif
2449
2450#ifdef MCH_WRITE_DUMP
2451 if (fdDump)
2452 {
2453 time_t t;
2454
2455 time(&t);
2456 fputs(ctime(&t), fdDump);
2457 fclose(fdDump);
2458 }
2459 fdDump = NULL;
2460#endif
2461 }
2462
2463 SetConsoleCursorInfo(g_hConOut, &g_cci);
2464 SetConsoleMode(g_hConIn, g_cmodein);
2465 SetConsoleMode(g_hConOut, g_cmodeout);
2466
2467#ifdef DYNAMIC_GETTEXT
2468 dyn_libintl_end();
2469#endif
2470
2471 exit(r);
2472}
2473#endif /* !FEAT_GUI_W32 */
2474
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475/*
2476 * Do we have an interactive window?
2477 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002478/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002479 int
2480mch_check_win(
2481 int argc,
2482 char **argv)
2483{
2484 get_exe_name();
2485
2486#ifdef FEAT_GUI_W32
2487 return OK; /* GUI always has a tty */
2488#else
2489 if (isatty(1))
2490 return OK;
2491 return FAIL;
2492#endif
2493}
2494
2495
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002496#ifdef FEAT_MBYTE
2497/*
2498 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2499 * if it already exists. When "len" is > 0, also expand short to long
2500 * filenames.
2501 * Return FAIL if wide functions are not available, OK otherwise.
2502 * NOTE: much of this is identical to fname_case(), keep in sync!
2503 */
2504 static int
2505fname_casew(
2506 WCHAR *name,
2507 int len)
2508{
2509 WCHAR szTrueName[_MAX_PATH + 2];
2510 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2511 WCHAR *ptrue, *ptruePrev;
2512 WCHAR *porig, *porigPrev;
2513 int flen;
2514 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002515 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002516 int c;
2517 int slen;
2518
2519 flen = (int)wcslen(name);
2520 if (flen > _MAX_PATH)
2521 return OK;
2522
2523 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2524
2525 /* Build the new name in szTrueName[] one component at a time. */
2526 porig = name;
2527 ptrue = szTrueName;
2528
2529 if (iswalpha(porig[0]) && porig[1] == L':')
2530 {
2531 /* copy leading drive letter */
2532 *ptrue++ = *porig++;
2533 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002534 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002535 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002536
2537 while (*porig != NUL)
2538 {
2539 /* copy \ characters */
2540 while (*porig == psepc)
2541 *ptrue++ = *porig++;
2542
2543 ptruePrev = ptrue;
2544 porigPrev = porig;
2545 while (*porig != NUL && *porig != psepc)
2546 {
2547 *ptrue++ = *porig++;
2548 }
2549 *ptrue = NUL;
2550
2551 /* To avoid a slow failure append "\*" when searching a directory,
2552 * server or network share. */
2553 wcscpy(szTrueNameTemp, szTrueName);
2554 slen = (int)wcslen(szTrueNameTemp);
2555 if (*porig == psepc && slen + 2 < _MAX_PATH)
2556 wcscpy(szTrueNameTemp + slen, L"\\*");
2557
2558 /* Skip "", "." and "..". */
2559 if (ptrue > ptruePrev
2560 && (ptruePrev[0] != L'.'
2561 || (ptruePrev[1] != NUL
2562 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2563 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2564 != INVALID_HANDLE_VALUE)
2565 {
2566 c = *porig;
2567 *porig = NUL;
2568
2569 /* Only use the match when it's the same name (ignoring case) or
2570 * expansion is allowed and there is a match with the short name
2571 * and there is enough room. */
2572 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2573 || (len > 0
2574 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2575 && (int)(ptruePrev - szTrueName)
2576 + (int)wcslen(fb.cFileName) < len)))
2577 {
2578 wcscpy(ptruePrev, fb.cFileName);
2579
2580 /* Look for exact match and prefer it if found. Must be a
2581 * long name, otherwise there would be only one match. */
2582 while (FindNextFileW(hFind, &fb))
2583 {
2584 if (*fb.cAlternateFileName != NUL
2585 && (wcscoll(porigPrev, fb.cFileName) == 0
2586 || (len > 0
2587 && (_wcsicoll(porigPrev,
2588 fb.cAlternateFileName) == 0
2589 && (int)(ptruePrev - szTrueName)
2590 + (int)wcslen(fb.cFileName) < len))))
2591 {
2592 wcscpy(ptruePrev, fb.cFileName);
2593 break;
2594 }
2595 }
2596 }
2597 FindClose(hFind);
2598 *porig = c;
2599 ptrue = ptruePrev + wcslen(ptruePrev);
2600 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002601 }
2602
2603 wcscpy(name, szTrueName);
2604 return OK;
2605}
2606#endif
2607
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608/*
2609 * fname_case(): Set the case of the file name, if it already exists.
2610 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002611 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002612 */
2613 void
2614fname_case(
2615 char_u *name,
2616 int len)
2617{
2618 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002619 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002620 char *ptrue, *ptruePrev;
2621 char *porig, *porigPrev;
2622 int flen;
2623 WIN32_FIND_DATA fb;
2624 HANDLE hFind;
2625 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002626 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002627
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002628 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002629 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 return;
2631
2632 slash_adjust(name);
2633
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002634#ifdef FEAT_MBYTE
2635 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2636 {
2637 WCHAR *p = enc_to_utf16(name, NULL);
2638
2639 if (p != NULL)
2640 {
2641 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002642 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002643
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002644 wcsncpy(buf, p, _MAX_PATH);
2645 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002646 vim_free(p);
2647
2648 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2649 {
2650 q = utf16_to_enc(buf, NULL);
2651 if (q != NULL)
2652 {
2653 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2654 vim_free(q);
2655 return;
2656 }
2657 }
2658 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002659 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002660 }
2661#endif
2662
2663 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2664 * So we should check this after calling wide function. */
2665 if (flen > _MAX_PATH)
2666 return;
2667
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002669 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670 ptrue = szTrueName;
2671
2672 if (isalpha(porig[0]) && porig[1] == ':')
2673 {
2674 /* copy leading drive letter */
2675 *ptrue++ = *porig++;
2676 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002677 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002678 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002679
2680 while (*porig != NUL)
2681 {
2682 /* copy \ characters */
2683 while (*porig == psepc)
2684 *ptrue++ = *porig++;
2685
2686 ptruePrev = ptrue;
2687 porigPrev = porig;
2688 while (*porig != NUL && *porig != psepc)
2689 {
2690#ifdef FEAT_MBYTE
2691 int l;
2692
2693 if (enc_dbcs)
2694 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002695 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002696 while (--l >= 0)
2697 *ptrue++ = *porig++;
2698 }
2699 else
2700#endif
2701 *ptrue++ = *porig++;
2702 }
2703 *ptrue = NUL;
2704
Bram Moolenaar464c9252010-10-13 20:37:41 +02002705 /* To avoid a slow failure append "\*" when searching a directory,
2706 * server or network share. */
2707 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002708 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002709 if (*porig == psepc && slen + 2 < _MAX_PATH)
2710 STRCPY(szTrueNameTemp + slen, "\\*");
2711
Bram Moolenaar071d4272004-06-13 20:20:40 +00002712 /* Skip "", "." and "..". */
2713 if (ptrue > ptruePrev
2714 && (ptruePrev[0] != '.'
2715 || (ptruePrev[1] != NUL
2716 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002717 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002718 != INVALID_HANDLE_VALUE)
2719 {
2720 c = *porig;
2721 *porig = NUL;
2722
2723 /* Only use the match when it's the same name (ignoring case) or
2724 * expansion is allowed and there is a match with the short name
2725 * and there is enough room. */
2726 if (_stricoll(porigPrev, fb.cFileName) == 0
2727 || (len > 0
2728 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2729 && (int)(ptruePrev - szTrueName)
2730 + (int)strlen(fb.cFileName) < len)))
2731 {
2732 STRCPY(ptruePrev, fb.cFileName);
2733
2734 /* Look for exact match and prefer it if found. Must be a
2735 * long name, otherwise there would be only one match. */
2736 while (FindNextFile(hFind, &fb))
2737 {
2738 if (*fb.cAlternateFileName != NUL
2739 && (strcoll(porigPrev, fb.cFileName) == 0
2740 || (len > 0
2741 && (_stricoll(porigPrev,
2742 fb.cAlternateFileName) == 0
2743 && (int)(ptruePrev - szTrueName)
2744 + (int)strlen(fb.cFileName) < len))))
2745 {
2746 STRCPY(ptruePrev, fb.cFileName);
2747 break;
2748 }
2749 }
2750 }
2751 FindClose(hFind);
2752 *porig = c;
2753 ptrue = ptruePrev + strlen(ptruePrev);
2754 }
2755 }
2756
2757 STRCPY(name, szTrueName);
2758}
2759
2760
2761/*
2762 * Insert user name in s[len].
2763 */
2764 int
2765mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002766 char_u *s,
2767 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002769 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 DWORD cch = sizeof szUserName;
2771
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002772#ifdef FEAT_MBYTE
2773 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2774 {
2775 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2776 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2777
2778 if (GetUserNameW(wszUserName, &wcch))
2779 {
2780 char_u *p = utf16_to_enc(wszUserName, NULL);
2781
2782 if (p != NULL)
2783 {
2784 vim_strncpy(s, p, len - 1);
2785 vim_free(p);
2786 return OK;
2787 }
2788 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002789 }
2790#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791 if (GetUserName(szUserName, &cch))
2792 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002793 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794 return OK;
2795 }
2796 s[0] = NUL;
2797 return FAIL;
2798}
2799
2800
2801/*
2802 * Insert host name in s[len].
2803 */
2804 void
2805mch_get_host_name(
2806 char_u *s,
2807 int len)
2808{
2809 DWORD cch = len;
2810
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002811#ifdef FEAT_MBYTE
2812 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2813 {
2814 WCHAR wszHostName[256 + 1];
2815 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2816
2817 if (GetComputerNameW(wszHostName, &wcch))
2818 {
2819 char_u *p = utf16_to_enc(wszHostName, NULL);
2820
2821 if (p != NULL)
2822 {
2823 vim_strncpy(s, p, len - 1);
2824 vim_free(p);
2825 return;
2826 }
2827 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002828 }
2829#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002830 if (!GetComputerName((LPSTR)s, &cch))
2831 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832}
2833
2834
2835/*
2836 * return process ID
2837 */
2838 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002839mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002840{
2841 return (long)GetCurrentProcessId();
2842}
2843
2844
2845/*
2846 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2847 * Return OK for success, FAIL for failure.
2848 */
2849 int
2850mch_dirname(
2851 char_u *buf,
2852 int len)
2853{
2854 /*
2855 * Originally this was:
2856 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2857 * But the Win32s known bug list says that getcwd() doesn't work
2858 * so use the Win32 system call instead. <Negri>
2859 */
2860#ifdef FEAT_MBYTE
2861 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2862 {
2863 WCHAR wbuf[_MAX_PATH + 1];
2864
2865 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2866 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002867 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868
2869 if (p != NULL)
2870 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002871 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872 vim_free(p);
2873 return OK;
2874 }
2875 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002876 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 }
2878#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002879 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880}
2881
2882/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002883 * Get file permissions for "name".
2884 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 */
2886 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002887mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002888{
Bram Moolenaar8767f522016-07-01 17:17:39 +02002889 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002890 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002892 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01002893 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894}
2895
2896
2897/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002898 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002899 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002900 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901 */
2902 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002903mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002905 long n = -1;
2906
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907#ifdef FEAT_MBYTE
2908 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2909 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002910 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911
2912 if (p != NULL)
2913 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002914 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002916 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002917 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918 }
2919 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002920 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002922 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002923 if (n == -1)
2924 return FAIL;
2925
2926 win32_set_archive(name);
2927
2928 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929}
2930
2931/*
2932 * Set hidden flag for "name".
2933 */
2934 void
2935mch_hide(char_u *name)
2936{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002937 int attrs = win32_getattrs(name);
2938 if (attrs == -1)
2939 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002941 attrs |= FILE_ATTRIBUTE_HIDDEN;
2942 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002943}
2944
2945/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01002946 * Return TRUE if file "name" exists and is hidden.
2947 */
2948 int
2949mch_ishidden(char_u *name)
2950{
2951 int f = win32_getattrs(name);
2952
2953 if (f == -1)
2954 return FALSE; /* file does not exist at all */
2955
2956 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
2957}
2958
2959/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002960 * return TRUE if "name" is a directory
2961 * return FALSE if "name" is not a directory or upon error
2962 */
2963 int
2964mch_isdir(char_u *name)
2965{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002966 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967
2968 if (f == -1)
2969 return FALSE; /* file does not exist at all */
2970
2971 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2972}
2973
2974/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01002975 * return TRUE if "name" is a directory, NOT a symlink to a directory
2976 * return FALSE if "name" is not a directory
2977 * return FALSE for error
2978 */
2979 int
2980mch_isrealdir(char_u *name)
2981{
2982 return mch_isdir(name) && !mch_is_symbolic_link(name);
2983}
2984
2985/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002986 * Create directory "name".
2987 * Return 0 on success, -1 on error.
2988 */
2989 int
2990mch_mkdir(char_u *name)
2991{
2992#ifdef FEAT_MBYTE
2993 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2994 {
2995 WCHAR *p;
2996 int retval;
2997
2998 p = enc_to_utf16(name, NULL);
2999 if (p == NULL)
3000 return -1;
3001 retval = _wmkdir(p);
3002 vim_free(p);
3003 return retval;
3004 }
3005#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003006 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003007}
3008
3009/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003010 * Delete directory "name".
3011 * Return 0 on success, -1 on error.
3012 */
3013 int
3014mch_rmdir(char_u *name)
3015{
3016#ifdef FEAT_MBYTE
3017 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3018 {
3019 WCHAR *p;
3020 int retval;
3021
3022 p = enc_to_utf16(name, NULL);
3023 if (p == NULL)
3024 return -1;
3025 retval = _wrmdir(p);
3026 vim_free(p);
3027 return retval;
3028 }
3029#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003030 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003031}
3032
3033/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003034 * Return TRUE if file "fname" has more than one link.
3035 */
3036 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003037mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003038{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003039 BY_HANDLE_FILE_INFORMATION info;
3040
3041 return win32_fileinfo(fname, &info) == FILEINFO_OK
3042 && info.nNumberOfLinks > 1;
3043}
3044
3045/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003046 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003047 */
3048 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003049mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003050{
3051 HANDLE hFind;
3052 int res = FALSE;
3053 WIN32_FIND_DATAA findDataA;
3054 DWORD fileFlags = 0, reparseTag = 0;
3055#ifdef FEAT_MBYTE
3056 WCHAR *wn = NULL;
3057 WIN32_FIND_DATAW findDataW;
3058
3059 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003060 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003061 if (wn != NULL)
3062 {
3063 hFind = FindFirstFileW(wn, &findDataW);
3064 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003065 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003066 {
3067 fileFlags = findDataW.dwFileAttributes;
3068 reparseTag = findDataW.dwReserved0;
3069 }
3070 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003071 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003072#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003073 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003074 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003075 if (hFind != INVALID_HANDLE_VALUE)
3076 {
3077 fileFlags = findDataA.dwFileAttributes;
3078 reparseTag = findDataA.dwReserved0;
3079 }
3080 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003081
3082 if (hFind != INVALID_HANDLE_VALUE)
3083 FindClose(hFind);
3084
3085 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003086 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3087 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003088 res = TRUE;
3089
3090 return res;
3091}
3092
3093/*
3094 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3095 * link.
3096 */
3097 int
3098mch_is_linked(char_u *fname)
3099{
3100 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3101 return TRUE;
3102 return FALSE;
3103}
3104
3105/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003106 * Get the by-handle-file-information for "fname".
3107 * Returns FILEINFO_OK when OK.
3108 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3109 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3110 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3111 */
3112 int
3113win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3114{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003115 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003116 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003117#ifdef FEAT_MBYTE
3118 WCHAR *wn = NULL;
3119
3120 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003121 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003122 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003123 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003124 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003125 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003126 if (wn != NULL)
3127 {
3128 hFile = CreateFileW(wn, /* file name */
3129 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003130 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003131 NULL, /* security descriptor */
3132 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003133 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003134 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003135 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003136 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003137 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003138#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003139 hFile = CreateFile((LPCSTR)fname, /* file name */
3140 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003141 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003142 NULL, /* security descriptor */
3143 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003144 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003145 NULL); /* handle to template file */
3146
3147 if (hFile != INVALID_HANDLE_VALUE)
3148 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003149 if (GetFileInformationByHandle(hFile, info) != 0)
3150 res = FILEINFO_OK;
3151 else
3152 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003153 CloseHandle(hFile);
3154 }
3155
Bram Moolenaar03f48552006-02-28 23:52:23 +00003156 return res;
3157}
3158
3159/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003160 * get file attributes for `name'
3161 * -1 : error
3162 * else FILE_ATTRIBUTE_* defined in winnt.h
3163 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003164 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003165win32_getattrs(char_u *name)
3166{
3167 int attr;
3168#ifdef FEAT_MBYTE
3169 WCHAR *p = NULL;
3170
3171 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3172 p = enc_to_utf16(name, NULL);
3173
3174 if (p != NULL)
3175 {
3176 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003177 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003178 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003179 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003180#endif
3181 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003182
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003183 return attr;
3184}
3185
3186/*
3187 * set file attributes for `name' to `attrs'
3188 *
3189 * return -1 for failure, 0 otherwise
3190 */
3191 static
3192 int
3193win32_setattrs(char_u *name, int attrs)
3194{
3195 int res;
3196#ifdef FEAT_MBYTE
3197 WCHAR *p = NULL;
3198
3199 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3200 p = enc_to_utf16(name, NULL);
3201
3202 if (p != NULL)
3203 {
3204 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003205 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003206 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003207 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003208#endif
3209 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003210
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003211 return res ? 0 : -1;
3212}
3213
3214/*
3215 * Set archive flag for "name".
3216 */
3217 static
3218 int
3219win32_set_archive(char_u *name)
3220{
3221 int attrs = win32_getattrs(name);
3222 if (attrs == -1)
3223 return -1;
3224
3225 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3226 return win32_setattrs(name, attrs);
3227}
3228
3229/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003230 * Return TRUE if file or directory "name" is writable (not readonly).
3231 * Strange semantics of Win32: a readonly directory is writable, but you can't
3232 * delete a file. Let's say this means it is writable.
3233 */
3234 int
3235mch_writable(char_u *name)
3236{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003237 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003239 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3240 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003241}
3242
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243/*
3244 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003245 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246 * Return -1 if unknown.
3247 */
3248 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003249mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003250{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003251 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003252 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003253 char_u *p;
3254
3255 if (len >= _MAX_PATH) /* safety check */
3256 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003257 if (!use_path)
3258 {
3259 /* TODO: check if file is really executable. */
3260 return mch_getperm(name) != -1 && !mch_isdir(name);
3261 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003262
3263 /* If there already is an extension try using the name directly. Also do
3264 * this with a Unix-shell like 'shell'. */
3265 if (vim_strchr(gettail(name), '.') != NULL
3266 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003267 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003268 return TRUE;
3269
3270 /*
3271 * Loop over all extensions in $PATHEXT.
3272 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003273 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003274 p = mch_getenv("PATHEXT");
3275 if (p == NULL)
3276 p = (char_u *)".com;.exe;.bat;.cmd";
3277 while (*p)
3278 {
3279 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3280 {
3281 /* A single "." means no extension is added. */
3282 buf[len] = NUL;
3283 ++p;
3284 if (*p)
3285 ++p;
3286 }
3287 else
3288 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003289 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003290 return TRUE;
3291 }
3292 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003293}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294
3295/*
3296 * Check what "name" is:
3297 * NODE_NORMAL: file or directory (or doesn't exist)
3298 * NODE_WRITABLE: writable device, socket, fifo, etc.
3299 * NODE_OTHER: non-writable things
3300 */
3301 int
3302mch_nodetype(char_u *name)
3303{
3304 HANDLE hFile;
3305 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003306#ifdef FEAT_MBYTE
3307 WCHAR *wn = NULL;
3308#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003309
Bram Moolenaar043545e2006-10-10 16:44:07 +00003310 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3311 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3312 * here. */
3313 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3314 return NODE_WRITABLE;
3315
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003316#ifdef FEAT_MBYTE
3317 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003318 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003319
3320 if (wn != NULL)
3321 {
3322 hFile = CreateFileW(wn, /* file name */
3323 GENERIC_WRITE, /* access mode */
3324 0, /* share mode */
3325 NULL, /* security descriptor */
3326 OPEN_EXISTING, /* creation disposition */
3327 0, /* file attributes */
3328 NULL); /* handle to template file */
3329 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003330 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003331 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003332#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003333 hFile = CreateFile((LPCSTR)name, /* file name */
3334 GENERIC_WRITE, /* access mode */
3335 0, /* share mode */
3336 NULL, /* security descriptor */
3337 OPEN_EXISTING, /* creation disposition */
3338 0, /* file attributes */
3339 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340
3341 if (hFile == INVALID_HANDLE_VALUE)
3342 return NODE_NORMAL;
3343
3344 type = GetFileType(hFile);
3345 CloseHandle(hFile);
3346 if (type == FILE_TYPE_CHAR)
3347 return NODE_WRITABLE;
3348 if (type == FILE_TYPE_DISK)
3349 return NODE_NORMAL;
3350 return NODE_OTHER;
3351}
3352
3353#ifdef HAVE_ACL
3354struct my_acl
3355{
3356 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3357 PSID pSidOwner;
3358 PSID pSidGroup;
3359 PACL pDacl;
3360 PACL pSacl;
3361};
3362#endif
3363
3364/*
3365 * Return a pointer to the ACL of file "fname" in allocated memory.
3366 * Return NULL if the ACL is not available for whatever reason.
3367 */
3368 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003369mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003370{
3371#ifndef HAVE_ACL
3372 return (vim_acl_T)NULL;
3373#else
3374 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003375 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003377 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3378 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003380# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003381 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003382
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003383 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3384 wn = enc_to_utf16(fname, NULL);
3385 if (wn != NULL)
3386 {
3387 /* Try to retrieve the entire security descriptor. */
3388 err = GetNamedSecurityInfoW(
3389 wn, // Abstract filename
3390 SE_FILE_OBJECT, // File Object
3391 OWNER_SECURITY_INFORMATION |
3392 GROUP_SECURITY_INFORMATION |
3393 DACL_SECURITY_INFORMATION |
3394 SACL_SECURITY_INFORMATION,
3395 &p->pSidOwner, // Ownership information.
3396 &p->pSidGroup, // Group membership.
3397 &p->pDacl, // Discretionary information.
3398 &p->pSacl, // For auditing purposes.
3399 &p->pSecurityDescriptor);
3400 if (err == ERROR_ACCESS_DENIED ||
3401 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003402 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003403 /* Retrieve only DACL. */
3404 (void)GetNamedSecurityInfoW(
3405 wn,
3406 SE_FILE_OBJECT,
3407 DACL_SECURITY_INFORMATION,
3408 NULL,
3409 NULL,
3410 &p->pDacl,
3411 NULL,
3412 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003413 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003414 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003415 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003416 mch_free_acl((vim_acl_T)p);
3417 p = NULL;
3418 }
3419 vim_free(wn);
3420 }
3421 else
3422# endif
3423 {
3424 /* Try to retrieve the entire security descriptor. */
3425 err = GetNamedSecurityInfo(
3426 (LPSTR)fname, // Abstract filename
3427 SE_FILE_OBJECT, // File Object
3428 OWNER_SECURITY_INFORMATION |
3429 GROUP_SECURITY_INFORMATION |
3430 DACL_SECURITY_INFORMATION |
3431 SACL_SECURITY_INFORMATION,
3432 &p->pSidOwner, // Ownership information.
3433 &p->pSidGroup, // Group membership.
3434 &p->pDacl, // Discretionary information.
3435 &p->pSacl, // For auditing purposes.
3436 &p->pSecurityDescriptor);
3437 if (err == ERROR_ACCESS_DENIED ||
3438 err == ERROR_PRIVILEGE_NOT_HELD)
3439 {
3440 /* Retrieve only DACL. */
3441 (void)GetNamedSecurityInfo(
3442 (LPSTR)fname,
3443 SE_FILE_OBJECT,
3444 DACL_SECURITY_INFORMATION,
3445 NULL,
3446 NULL,
3447 &p->pDacl,
3448 NULL,
3449 &p->pSecurityDescriptor);
3450 }
3451 if (p->pSecurityDescriptor == NULL)
3452 {
3453 mch_free_acl((vim_acl_T)p);
3454 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003455 }
3456 }
3457 }
3458
3459 return (vim_acl_T)p;
3460#endif
3461}
3462
Bram Moolenaar27515922013-06-29 15:36:26 +02003463#ifdef HAVE_ACL
3464/*
3465 * Check if "acl" contains inherited ACE.
3466 */
3467 static BOOL
3468is_acl_inherited(PACL acl)
3469{
3470 DWORD i;
3471 ACL_SIZE_INFORMATION acl_info;
3472 PACCESS_ALLOWED_ACE ace;
3473
3474 acl_info.AceCount = 0;
3475 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3476 for (i = 0; i < acl_info.AceCount; i++)
3477 {
3478 GetAce(acl, i, (LPVOID *)&ace);
3479 if (ace->Header.AceFlags & INHERITED_ACE)
3480 return TRUE;
3481 }
3482 return FALSE;
3483}
3484#endif
3485
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486/*
3487 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3488 * Errors are ignored.
3489 * This must only be called with "acl" equal to what mch_get_acl() returned.
3490 */
3491 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003492mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493{
3494#ifdef HAVE_ACL
3495 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003496 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003498 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003499 {
3500# ifdef FEAT_MBYTE
3501 WCHAR *wn = NULL;
3502# endif
3503
3504 /* Set security flags */
3505 if (p->pSidOwner)
3506 sec_info |= OWNER_SECURITY_INFORMATION;
3507 if (p->pSidGroup)
3508 sec_info |= GROUP_SECURITY_INFORMATION;
3509 if (p->pDacl)
3510 {
3511 sec_info |= DACL_SECURITY_INFORMATION;
3512 /* Do not inherit its parent's DACL.
3513 * If the DACL is inherited, Cygwin permissions would be changed.
3514 */
3515 if (!is_acl_inherited(p->pDacl))
3516 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3517 }
3518 if (p->pSacl)
3519 sec_info |= SACL_SECURITY_INFORMATION;
3520
3521# ifdef FEAT_MBYTE
3522 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3523 wn = enc_to_utf16(fname, NULL);
3524 if (wn != NULL)
3525 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003526 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003527 wn, // Abstract filename
3528 SE_FILE_OBJECT, // File Object
3529 sec_info,
3530 p->pSidOwner, // Ownership information.
3531 p->pSidGroup, // Group membership.
3532 p->pDacl, // Discretionary information.
3533 p->pSacl // For auditing purposes.
3534 );
3535 vim_free(wn);
3536 }
3537 else
3538# endif
3539 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003540 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003541 (LPSTR)fname, // Abstract filename
3542 SE_FILE_OBJECT, // File Object
3543 sec_info,
3544 p->pSidOwner, // Ownership information.
3545 p->pSidGroup, // Group membership.
3546 p->pDacl, // Discretionary information.
3547 p->pSacl // For auditing purposes.
3548 );
3549 }
3550 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551#endif
3552}
3553
3554 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003555mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003556{
3557#ifdef HAVE_ACL
3558 struct my_acl *p = (struct my_acl *)acl;
3559
3560 if (p != NULL)
3561 {
3562 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3563 vim_free(p);
3564 }
3565#endif
3566}
3567
3568#ifndef FEAT_GUI_W32
3569
3570/*
3571 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3572 */
3573 static BOOL WINAPI
3574handler_routine(
3575 DWORD dwCtrlType)
3576{
3577 switch (dwCtrlType)
3578 {
3579 case CTRL_C_EVENT:
3580 if (ctrl_c_interrupts)
3581 g_fCtrlCPressed = TRUE;
3582 return TRUE;
3583
3584 case CTRL_BREAK_EVENT:
3585 g_fCBrkPressed = TRUE;
3586 return TRUE;
3587
3588 /* fatal events: shut down gracefully */
3589 case CTRL_CLOSE_EVENT:
3590 case CTRL_LOGOFF_EVENT:
3591 case CTRL_SHUTDOWN_EVENT:
3592 windgoto((int)Rows - 1, 0);
3593 g_fForceExit = TRUE;
3594
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003595 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596 (dwCtrlType == CTRL_CLOSE_EVENT
3597 ? _("close")
3598 : dwCtrlType == CTRL_LOGOFF_EVENT
3599 ? _("logoff")
3600 : _("shutdown")));
3601#ifdef DEBUG
3602 OutputDebugString(IObuff);
3603#endif
3604
3605 preserve_exit(); /* output IObuff, preserve files and exit */
3606
3607 return TRUE; /* not reached */
3608
3609 default:
3610 return FALSE;
3611 }
3612}
3613
3614
3615/*
3616 * set the tty in (raw) ? "raw" : "cooked" mode
3617 */
3618 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003619mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003620{
3621 DWORD cmodein;
3622 DWORD cmodeout;
3623 BOOL bEnableHandler;
3624
3625 GetConsoleMode(g_hConIn, &cmodein);
3626 GetConsoleMode(g_hConOut, &cmodeout);
3627 if (tmode == TMODE_RAW)
3628 {
3629 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3630 ENABLE_ECHO_INPUT);
3631#ifdef FEAT_MOUSE
3632 if (g_fMouseActive)
3633 cmodein |= ENABLE_MOUSE_INPUT;
3634#endif
3635 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3636 bEnableHandler = TRUE;
3637 }
3638 else /* cooked */
3639 {
3640 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3641 ENABLE_ECHO_INPUT);
3642 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3643 bEnableHandler = FALSE;
3644 }
3645 SetConsoleMode(g_hConIn, cmodein);
3646 SetConsoleMode(g_hConOut, cmodeout);
3647 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3648
3649#ifdef MCH_WRITE_DUMP
3650 if (fdDump)
3651 {
3652 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3653 tmode == TMODE_RAW ? "raw" :
3654 tmode == TMODE_COOK ? "cooked" : "normal",
3655 cmodein, cmodeout);
3656 fflush(fdDump);
3657 }
3658#endif
3659}
3660
3661
3662/*
3663 * Get the size of the current window in `Rows' and `Columns'
3664 * Return OK when size could be determined, FAIL otherwise.
3665 */
3666 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003667mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668{
3669 CONSOLE_SCREEN_BUFFER_INFO csbi;
3670
3671 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3672 {
3673 /*
3674 * For some reason, we are trying to get the screen dimensions
3675 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3676 * variables are really intended to mean the size of Vim screen
3677 * while in termcap mode.
3678 */
3679 Rows = g_cbTermcap.Info.dwSize.Y;
3680 Columns = g_cbTermcap.Info.dwSize.X;
3681 }
3682 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3683 {
3684 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3685 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3686 }
3687 else
3688 {
3689 Rows = 25;
3690 Columns = 80;
3691 }
3692 return OK;
3693}
3694
3695/*
3696 * Set a console window to `xSize' * `ySize'
3697 */
3698 static void
3699ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003700 HANDLE hConsole,
3701 int xSize,
3702 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703{
3704 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3705 SMALL_RECT srWindowRect; /* hold the new console size */
3706 COORD coordScreen;
3707
3708#ifdef MCH_WRITE_DUMP
3709 if (fdDump)
3710 {
3711 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3712 fflush(fdDump);
3713 }
3714#endif
3715
3716 /* get the largest size we can size the console window to */
3717 coordScreen = GetLargestConsoleWindowSize(hConsole);
3718
3719 /* define the new console window size and scroll position */
3720 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3721 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3722 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3723
3724 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3725 {
3726 int sx, sy;
3727
3728 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3729 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3730 if (sy < ySize || sx < xSize)
3731 {
3732 /*
3733 * Increasing number of lines/columns, do buffer first.
3734 * Use the maximal size in x and y direction.
3735 */
3736 if (sy < ySize)
3737 coordScreen.Y = ySize;
3738 else
3739 coordScreen.Y = sy;
3740 if (sx < xSize)
3741 coordScreen.X = xSize;
3742 else
3743 coordScreen.X = sx;
3744 SetConsoleScreenBufferSize(hConsole, coordScreen);
3745 }
3746 }
3747
3748 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3749 {
3750#ifdef MCH_WRITE_DUMP
3751 if (fdDump)
3752 {
3753 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3754 GetLastError());
3755 fflush(fdDump);
3756 }
3757#endif
3758 }
3759
3760 /* define the new console buffer size */
3761 coordScreen.X = xSize;
3762 coordScreen.Y = ySize;
3763
3764 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3765 {
3766#ifdef MCH_WRITE_DUMP
3767 if (fdDump)
3768 {
3769 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3770 GetLastError());
3771 fflush(fdDump);
3772 }
3773#endif
3774 }
3775}
3776
3777
3778/*
3779 * Set the console window to `Rows' * `Columns'
3780 */
3781 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003782mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783{
3784 COORD coordScreen;
3785
3786 /* Don't change window size while still starting up */
3787 if (suppress_winsize != 0)
3788 {
3789 suppress_winsize = 2;
3790 return;
3791 }
3792
3793 if (term_console)
3794 {
3795 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3796
3797 /* Clamp Rows and Columns to reasonable values */
3798 if (Rows > coordScreen.Y)
3799 Rows = coordScreen.Y;
3800 if (Columns > coordScreen.X)
3801 Columns = coordScreen.X;
3802
3803 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3804 }
3805}
3806
3807/*
3808 * Rows and/or Columns has changed.
3809 */
3810 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003811mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003812{
3813 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3814}
3815
3816
3817/*
3818 * Called when started up, to set the winsize that was delayed.
3819 */
3820 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003821mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822{
3823 if (suppress_winsize == 2)
3824 {
3825 suppress_winsize = 0;
3826 mch_set_shellsize();
3827 shell_resized();
3828 }
3829 suppress_winsize = 0;
3830}
3831#endif /* FEAT_GUI_W32 */
3832
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003833 static BOOL
3834vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003835 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003836 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003837 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003838 STARTUPINFO *si,
3839 PROCESS_INFORMATION *pi)
3840{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003841#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003842 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3843 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003844 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003845
3846 if (wcmd != NULL)
3847 {
3848 BOOL ret;
3849 ret = CreateProcessW(
3850 NULL, /* Executable name */
3851 wcmd, /* Command to execute */
3852 NULL, /* Process security attributes */
3853 NULL, /* Thread security attributes */
3854 inherit_handles, /* Inherit handles */
3855 flags, /* Creation flags */
3856 NULL, /* Environment */
3857 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003858 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003859 pi); /* Process information */
3860 vim_free(wcmd);
3861 return ret;
3862 }
3863 }
3864#endif
3865 return CreateProcess(
3866 NULL, /* Executable name */
3867 cmd, /* Command to execute */
3868 NULL, /* Process security attributes */
3869 NULL, /* Thread security attributes */
3870 inherit_handles, /* Inherit handles */
3871 flags, /* Creation flags */
3872 NULL, /* Environment */
3873 NULL, /* Current directory */
3874 si, /* Startup information */
3875 pi); /* Process information */
3876}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003877
3878
3879#if defined(FEAT_GUI_W32) || defined(PROTO)
3880
3881/*
3882 * Specialised version of system() for Win32 GUI mode.
3883 * This version proceeds as follows:
3884 * 1. Create a console window for use by the subprocess
3885 * 2. Run the subprocess (it gets the allocated console by default)
3886 * 3. Wait for the subprocess to terminate and get its exit code
3887 * 4. Prompt the user to press a key to close the console window
3888 */
3889 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003890mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003891{
3892 STARTUPINFO si;
3893 PROCESS_INFORMATION pi;
3894 DWORD ret = 0;
3895 HWND hwnd = GetFocus();
3896
3897 si.cb = sizeof(si);
3898 si.lpReserved = NULL;
3899 si.lpDesktop = NULL;
3900 si.lpTitle = NULL;
3901 si.dwFlags = STARTF_USESHOWWINDOW;
3902 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003903 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003904 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003906 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003907 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003908 else
3909 si.wShowWindow = SW_SHOWNORMAL;
3910 si.cbReserved2 = 0;
3911 si.lpReserved2 = NULL;
3912
Bram Moolenaar071d4272004-06-13 20:20:40 +00003913 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003914 vim_create_process(cmd, FALSE,
3915 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916
3917 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918 {
3919#ifdef FEAT_GUI
3920 int delay = 1;
3921
3922 /* Keep updating the window while waiting for the shell to finish. */
3923 for (;;)
3924 {
3925 MSG msg;
3926
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003927 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003928 {
3929 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003930 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003931 delay = 1;
3932 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933 }
3934 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3935 break;
3936
3937 /* We start waiting for a very short time and then increase it, so
3938 * that we respond quickly when the process is quick, and don't
3939 * consume too much overhead when it's slow. */
3940 if (delay < 50)
3941 delay += 10;
3942 }
3943#else
3944 WaitForSingleObject(pi.hProcess, INFINITE);
3945#endif
3946
3947 /* Get the command exit code */
3948 GetExitCodeProcess(pi.hProcess, &ret);
3949 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950
3951 /* Close the handles to the subprocess, so that it goes away */
3952 CloseHandle(pi.hThread);
3953 CloseHandle(pi.hProcess);
3954
3955 /* Try to get input focus back. Doesn't always work though. */
3956 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3957
3958 return ret;
3959}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003960
3961/*
3962 * Thread launched by the gui to send the current buffer data to the
3963 * process. This way avoid to hang up vim totally if the children
3964 * process take a long time to process the lines.
3965 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02003966 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003967sub_process_writer(LPVOID param)
3968{
3969 HANDLE g_hChildStd_IN_Wr = param;
3970 linenr_T lnum = curbuf->b_op_start.lnum;
3971 DWORD len = 0;
3972 DWORD l;
3973 char_u *lp = ml_get(lnum);
3974 char_u *s;
3975 int written = 0;
3976
3977 for (;;)
3978 {
3979 l = (DWORD)STRLEN(lp + written);
3980 if (l == 0)
3981 len = 0;
3982 else if (lp[written] == NL)
3983 {
3984 /* NL -> NUL translation */
3985 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3986 }
3987 else
3988 {
3989 s = vim_strchr(lp + written, NL);
3990 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3991 s == NULL ? l : (DWORD)(s - (lp + written)),
3992 &len, NULL);
3993 }
3994 if (len == (int)l)
3995 {
3996 /* Finished a line, add a NL, unless this line should not have
3997 * one. */
3998 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02003999 || (!curbuf->b_p_bin
4000 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004001 || (lnum != curbuf->b_no_eol_lnum
4002 && (lnum != curbuf->b_ml.ml_line_count
4003 || curbuf->b_p_eol)))
4004 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004005 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004006 }
4007
4008 ++lnum;
4009 if (lnum > curbuf->b_op_end.lnum)
4010 break;
4011
4012 lp = ml_get(lnum);
4013 written = 0;
4014 }
4015 else if (len > 0)
4016 written += len;
4017 }
4018
4019 /* finished all the lines, close pipe */
4020 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004021 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004022}
4023
4024
4025# define BUFLEN 100 /* length for buffer, stolen from unix version */
4026
4027/*
4028 * This function read from the children's stdout and write the
4029 * data on screen or in the buffer accordingly.
4030 */
4031 static void
4032dump_pipe(int options,
4033 HANDLE g_hChildStd_OUT_Rd,
4034 garray_T *ga,
4035 char_u buffer[],
4036 DWORD *buffer_off)
4037{
4038 DWORD availableBytes = 0;
4039 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004040 int ret;
4041 DWORD len;
4042 DWORD toRead;
4043 int repeatCount;
4044
4045 /* we query the pipe to see if there is any data to read
4046 * to avoid to perform a blocking read */
4047 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4048 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004049 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004050 NULL, /* number of read bytes */
4051 &availableBytes, /* available bytes total */
4052 NULL); /* byteLeft */
4053
4054 repeatCount = 0;
4055 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004056 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004057 {
4058 repeatCount++;
4059 toRead =
4060# ifdef FEAT_MBYTE
4061 (DWORD)(BUFLEN - *buffer_off);
4062# else
4063 (DWORD)BUFLEN;
4064# endif
4065 toRead = availableBytes < toRead ? availableBytes : toRead;
4066 ReadFile(g_hChildStd_OUT_Rd, buffer
4067# ifdef FEAT_MBYTE
4068 + *buffer_off, toRead
4069# else
4070 , toRead
4071# endif
4072 , &len, NULL);
4073
4074 /* If we haven't read anything, there is a problem */
4075 if (len == 0)
4076 break;
4077
4078 availableBytes -= len;
4079
4080 if (options & SHELL_READ)
4081 {
4082 /* Do NUL -> NL translation, append NL separated
4083 * lines to the current buffer. */
4084 for (i = 0; i < len; ++i)
4085 {
4086 if (buffer[i] == NL)
4087 append_ga_line(ga);
4088 else if (buffer[i] == NUL)
4089 ga_append(ga, NL);
4090 else
4091 ga_append(ga, buffer[i]);
4092 }
4093 }
4094# ifdef FEAT_MBYTE
4095 else if (has_mbyte)
4096 {
4097 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004098 int c;
4099 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004100
4101 len += *buffer_off;
4102 buffer[len] = NUL;
4103
4104 /* Check if the last character in buffer[] is
4105 * incomplete, keep these bytes for the next
4106 * round. */
4107 for (p = buffer; p < buffer + len; p += l)
4108 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004109 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004110 if (l == 0)
4111 l = 1; /* NUL byte? */
4112 else if (MB_BYTE2LEN(*p) != l)
4113 break;
4114 }
4115 if (p == buffer) /* no complete character */
4116 {
4117 /* avoid getting stuck at an illegal byte */
4118 if (len >= 12)
4119 ++p;
4120 else
4121 {
4122 *buffer_off = len;
4123 return;
4124 }
4125 }
4126 c = *p;
4127 *p = NUL;
4128 msg_puts(buffer);
4129 if (p < buffer + len)
4130 {
4131 *p = c;
4132 *buffer_off = (DWORD)((buffer + len) - p);
4133 mch_memmove(buffer, p, *buffer_off);
4134 return;
4135 }
4136 *buffer_off = 0;
4137 }
4138# endif /* FEAT_MBYTE */
4139 else
4140 {
4141 buffer[len] = NUL;
4142 msg_puts(buffer);
4143 }
4144
4145 windgoto(msg_row, msg_col);
4146 cursor_on();
4147 out_flush();
4148 }
4149}
4150
4151/*
4152 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4153 * for communication and doesn't open any new window.
4154 */
4155 static int
4156mch_system_piped(char *cmd, int options)
4157{
4158 STARTUPINFO si;
4159 PROCESS_INFORMATION pi;
4160 DWORD ret = 0;
4161
4162 HANDLE g_hChildStd_IN_Rd = NULL;
4163 HANDLE g_hChildStd_IN_Wr = NULL;
4164 HANDLE g_hChildStd_OUT_Rd = NULL;
4165 HANDLE g_hChildStd_OUT_Wr = NULL;
4166
4167 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4168 DWORD len;
4169
4170 /* buffer used to receive keys */
4171 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4172 int ta_len = 0; /* valid bytes in ta_buf[] */
4173
4174 DWORD i;
4175 int c;
4176 int noread_cnt = 0;
4177 garray_T ga;
4178 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004179 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004180 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004181
4182 SECURITY_ATTRIBUTES saAttr;
4183
4184 /* Set the bInheritHandle flag so pipe handles are inherited. */
4185 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4186 saAttr.bInheritHandle = TRUE;
4187 saAttr.lpSecurityDescriptor = NULL;
4188
4189 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4190 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004191 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004192 /* Create a pipe for the child process's STDIN. */
4193 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4194 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004195 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004196 {
4197 CloseHandle(g_hChildStd_IN_Rd);
4198 CloseHandle(g_hChildStd_IN_Wr);
4199 CloseHandle(g_hChildStd_OUT_Rd);
4200 CloseHandle(g_hChildStd_OUT_Wr);
4201 MSG_PUTS(_("\nCannot create pipes\n"));
4202 }
4203
4204 si.cb = sizeof(si);
4205 si.lpReserved = NULL;
4206 si.lpDesktop = NULL;
4207 si.lpTitle = NULL;
4208 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4209
4210 /* set-up our file redirection */
4211 si.hStdError = g_hChildStd_OUT_Wr;
4212 si.hStdOutput = g_hChildStd_OUT_Wr;
4213 si.hStdInput = g_hChildStd_IN_Rd;
4214 si.wShowWindow = SW_HIDE;
4215 si.cbReserved2 = 0;
4216 si.lpReserved2 = NULL;
4217
4218 if (options & SHELL_READ)
4219 ga_init2(&ga, 1, BUFLEN);
4220
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004221 if (cmd != NULL)
4222 {
4223 p = (char *)vim_strsave((char_u *)cmd);
4224 if (p != NULL)
4225 unescape_shellxquote((char_u *)p, p_sxe);
4226 else
4227 p = cmd;
4228 }
4229
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004230 /* Now, run the command.
4231 * About "Inherit handles" being TRUE: this command can be litigious,
4232 * handle inheritance was deactivated for pending temp file, but, if we
4233 * deactivate it, the pipes don't work for some reason. */
4234 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004235
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004236 if (p != cmd)
4237 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004238
4239 /* Close our unused side of the pipes */
4240 CloseHandle(g_hChildStd_IN_Rd);
4241 CloseHandle(g_hChildStd_OUT_Wr);
4242
4243 if (options & SHELL_WRITE)
4244 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004245 HANDLE thread = (HANDLE)
4246 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004247 0, /* default stack size */
4248 sub_process_writer, /* function to be executed */
4249 g_hChildStd_IN_Wr, /* parameter */
4250 0, /* creation flag, start immediately */
4251 NULL); /* we don't care about thread id */
4252 CloseHandle(thread);
4253 g_hChildStd_IN_Wr = NULL;
4254 }
4255
4256 /* Keep updating the window while waiting for the shell to finish. */
4257 for (;;)
4258 {
4259 MSG msg;
4260
Bram Moolenaar175d0702013-12-11 18:36:33 +01004261 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004262 {
4263 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004264 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004265 }
4266
4267 /* write pipe information in the window */
4268 if ((options & (SHELL_READ|SHELL_WRITE))
4269# ifdef FEAT_GUI
4270 || gui.in_use
4271# endif
4272 )
4273 {
4274 len = 0;
4275 if (!(options & SHELL_EXPAND)
4276 && ((options &
4277 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4278 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4279# ifdef FEAT_GUI
4280 || gui.in_use
4281# endif
4282 )
4283 && (ta_len > 0 || noread_cnt > 4))
4284 {
4285 if (ta_len == 0)
4286 {
4287 /* Get extra characters when we don't have any. Reset the
4288 * counter and timer. */
4289 noread_cnt = 0;
4290# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4291 gettimeofday(&start_tv, NULL);
4292# endif
4293 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4294 }
4295 if (ta_len > 0 || len > 0)
4296 {
4297 /*
4298 * For pipes: Check for CTRL-C: send interrupt signal to
4299 * child. Check for CTRL-D: EOF, close pipe to child.
4300 */
4301 if (len == 1 && cmd != NULL)
4302 {
4303 if (ta_buf[ta_len] == Ctrl_C)
4304 {
4305 /* Learn what exit code is expected, for
4306 * now put 9 as SIGKILL */
4307 TerminateProcess(pi.hProcess, 9);
4308 }
4309 if (ta_buf[ta_len] == Ctrl_D)
4310 {
4311 CloseHandle(g_hChildStd_IN_Wr);
4312 g_hChildStd_IN_Wr = NULL;
4313 }
4314 }
4315
4316 /* replace K_BS by <BS> and K_DEL by <DEL> */
4317 for (i = ta_len; i < ta_len + len; ++i)
4318 {
4319 if (ta_buf[i] == CSI && len - i > 2)
4320 {
4321 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4322 if (c == K_DEL || c == K_KDEL || c == K_BS)
4323 {
4324 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4325 (size_t)(len - i - 2));
4326 if (c == K_DEL || c == K_KDEL)
4327 ta_buf[i] = DEL;
4328 else
4329 ta_buf[i] = Ctrl_H;
4330 len -= 2;
4331 }
4332 }
4333 else if (ta_buf[i] == '\r')
4334 ta_buf[i] = '\n';
4335# ifdef FEAT_MBYTE
4336 if (has_mbyte)
4337 i += (*mb_ptr2len_len)(ta_buf + i,
4338 ta_len + len - i) - 1;
4339# endif
4340 }
4341
4342 /*
4343 * For pipes: echo the typed characters. For a pty this
4344 * does not seem to work.
4345 */
4346 for (i = ta_len; i < ta_len + len; ++i)
4347 {
4348 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4349 msg_putchar(ta_buf[i]);
4350# ifdef FEAT_MBYTE
4351 else if (has_mbyte)
4352 {
4353 int l = (*mb_ptr2len)(ta_buf + i);
4354
4355 msg_outtrans_len(ta_buf + i, l);
4356 i += l - 1;
4357 }
4358# endif
4359 else
4360 msg_outtrans_len(ta_buf + i, 1);
4361 }
4362 windgoto(msg_row, msg_col);
4363 out_flush();
4364
4365 ta_len += len;
4366
4367 /*
4368 * Write the characters to the child, unless EOF has been
4369 * typed for pipes. Write one character at a time, to
4370 * avoid losing too much typeahead. When writing buffer
4371 * lines, drop the typed characters (only check for
4372 * CTRL-C).
4373 */
4374 if (options & SHELL_WRITE)
4375 ta_len = 0;
4376 else if (g_hChildStd_IN_Wr != NULL)
4377 {
4378 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4379 1, &len, NULL);
4380 // if we are typing in, we want to keep things reactive
4381 delay = 1;
4382 if (len > 0)
4383 {
4384 ta_len -= len;
4385 mch_memmove(ta_buf, ta_buf + len, ta_len);
4386 }
4387 }
4388 }
4389 }
4390 }
4391
4392 if (ta_len)
4393 ui_inchar_undo(ta_buf, ta_len);
4394
4395 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4396 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004397 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004398 break;
4399 }
4400
4401 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004402 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004403
4404 /* We start waiting for a very short time and then increase it, so
4405 * that we respond quickly when the process is quick, and don't
4406 * consume too much overhead when it's slow. */
4407 if (delay < 50)
4408 delay += 10;
4409 }
4410
4411 /* Close the pipe */
4412 CloseHandle(g_hChildStd_OUT_Rd);
4413 if (g_hChildStd_IN_Wr != NULL)
4414 CloseHandle(g_hChildStd_IN_Wr);
4415
4416 WaitForSingleObject(pi.hProcess, INFINITE);
4417
4418 /* Get the command exit code */
4419 GetExitCodeProcess(pi.hProcess, &ret);
4420
4421 if (options & SHELL_READ)
4422 {
4423 if (ga.ga_len > 0)
4424 {
4425 append_ga_line(&ga);
4426 /* remember that the NL was missing */
4427 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4428 }
4429 else
4430 curbuf->b_no_eol_lnum = 0;
4431 ga_clear(&ga);
4432 }
4433
4434 /* Close the handles to the subprocess, so that it goes away */
4435 CloseHandle(pi.hThread);
4436 CloseHandle(pi.hProcess);
4437
4438 return ret;
4439}
4440
4441 static int
4442mch_system(char *cmd, int options)
4443{
4444 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004445 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004446 return mch_system_piped(cmd, options);
4447 else
4448 return mch_system_classic(cmd, options);
4449}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450#else
4451
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004452# ifdef FEAT_MBYTE
4453 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004454mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004455{
4456 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4457 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004458 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004459 if (wcmd != NULL)
4460 {
4461 int ret = _wsystem(wcmd);
4462 vim_free(wcmd);
4463 return ret;
4464 }
4465 }
4466 return system(cmd);
4467}
4468# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004469# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004470# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471
4472#endif
4473
4474/*
4475 * Either execute a command by calling the shell or start a new shell
4476 */
4477 int
4478mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004479 char_u *cmd,
4480 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004481{
4482 int x = 0;
4483 int tmode = cur_tmode;
4484#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004485 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004486# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004487 int did_set_title = FALSE;
4488
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004489 /* Change the title to reflect that we are in a subshell. */
4490 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4491 {
4492 WCHAR szShellTitle[512];
4493
4494 if (GetConsoleTitleW(szShellTitle,
4495 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4496 {
4497 if (cmd == NULL)
4498 wcscat(szShellTitle, L" :sh");
4499 else
4500 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004501 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004502
4503 if (wn != NULL)
4504 {
4505 wcscat(szShellTitle, L" - !");
4506 if ((wcslen(szShellTitle) + wcslen(wn) <
4507 sizeof(szShellTitle)/sizeof(WCHAR)))
4508 wcscat(szShellTitle, wn);
4509 SetConsoleTitleW(szShellTitle);
4510 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004511 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004512 }
4513 }
4514 }
4515 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004516 if (!did_set_title)
4517# endif
4518 /* Change the title to reflect that we are in a subshell. */
4519 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004521 if (cmd == NULL)
4522 strcat(szShellTitle, " :sh");
4523 else
4524 {
4525 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004526 if ((strlen(szShellTitle) + strlen((char *)cmd)
4527 < sizeof(szShellTitle)))
4528 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004529 }
4530 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004531 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004532#endif
4533
4534 out_flush();
4535
4536#ifdef MCH_WRITE_DUMP
4537 if (fdDump)
4538 {
4539 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4540 fflush(fdDump);
4541 }
4542#endif
4543
4544 /*
4545 * Catch all deadly signals while running the external command, because a
4546 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4547 */
4548 signal(SIGINT, SIG_IGN);
4549#if defined(__GNUC__) && !defined(__MINGW32__)
4550 signal(SIGKILL, SIG_IGN);
4551#else
4552 signal(SIGBREAK, SIG_IGN);
4553#endif
4554 signal(SIGILL, SIG_IGN);
4555 signal(SIGFPE, SIG_IGN);
4556 signal(SIGSEGV, SIG_IGN);
4557 signal(SIGTERM, SIG_IGN);
4558 signal(SIGABRT, SIG_IGN);
4559
4560 if (options & SHELL_COOKED)
4561 settmode(TMODE_COOK); /* set to normal mode */
4562
4563 if (cmd == NULL)
4564 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004565 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566 }
4567 else
4568 {
4569 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004570 char_u *newcmd = NULL;
4571 char_u *cmdbase = cmd;
4572 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004573
4574 /* Skip a leading ", ( and "(. */
4575 if (*cmdbase == '"' )
4576 ++cmdbase;
4577 if (*cmdbase == '(')
4578 ++cmdbase;
4579
4580 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4581 {
4582 STARTUPINFO si;
4583 PROCESS_INFORMATION pi;
4584 DWORD flags = CREATE_NEW_CONSOLE;
4585 char_u *p;
4586
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004587 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004588 si.cb = sizeof(si);
4589 si.lpReserved = NULL;
4590 si.lpDesktop = NULL;
4591 si.lpTitle = NULL;
4592 si.dwFlags = 0;
4593 si.cbReserved2 = 0;
4594 si.lpReserved2 = NULL;
4595
4596 cmdbase = skipwhite(cmdbase + 5);
4597 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4598 && vim_iswhite(cmdbase[4]))
4599 {
4600 cmdbase = skipwhite(cmdbase + 4);
4601 si.dwFlags = STARTF_USESHOWWINDOW;
4602 si.wShowWindow = SW_SHOWMINNOACTIVE;
4603 }
4604 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4605 && vim_iswhite(cmdbase[2]))
4606 {
4607 cmdbase = skipwhite(cmdbase + 2);
4608 flags = CREATE_NO_WINDOW;
4609 si.dwFlags = STARTF_USESTDHANDLES;
4610 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004611 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004612 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004613 NULL, // Security att.
4614 OPEN_EXISTING, // Open flags
4615 FILE_ATTRIBUTE_NORMAL, // File att.
4616 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004617 si.hStdOutput = si.hStdInput;
4618 si.hStdError = si.hStdInput;
4619 }
4620
4621 /* Remove a trailing ", ) and )" if they have a match
4622 * at the start of the command. */
4623 if (cmdbase > cmd)
4624 {
4625 p = cmdbase + STRLEN(cmdbase);
4626 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4627 *--p = NUL;
4628 if (p > cmdbase && p[-1] == ')'
4629 && (*cmd =='(' || cmd[1] == '('))
4630 *--p = NUL;
4631 }
4632
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004633 newcmd = cmdbase;
4634 unescape_shellxquote(cmdbase, p_sxe);
4635
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004636 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004637 * If creating new console, arguments are passed to the
4638 * 'cmd.exe' as-is. If it's not, arguments are not treated
4639 * correctly for current 'cmd.exe'. So unescape characters in
4640 * shellxescape except '|' for avoiding to be treated as
4641 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004642 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004643 if (flags != CREATE_NEW_CONSOLE)
4644 {
4645 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004646 char_u *cmd_shell = mch_getenv("COMSPEC");
4647
4648 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004649 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004650
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004651 subcmd = vim_strsave_escaped_ext(cmdbase,
4652 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004653 if (subcmd != NULL)
4654 {
4655 /* make "cmd.exe /c arguments" */
4656 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004657 newcmd = lalloc(cmdlen, TRUE);
4658 if (newcmd != NULL)
4659 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004660 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004661 else
4662 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004663 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004664 }
4665 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004666
4667 /*
4668 * Now, start the command as a process, so that it doesn't
4669 * inherit our handles which causes unpleasant dangling swap
4670 * files if we exit before the spawned process
4671 */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004672 if (vim_create_process((char *)newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004673 x = 0;
4674 else
4675 {
4676 x = -1;
4677#ifdef FEAT_GUI_W32
4678 EMSG(_("E371: Command not found"));
4679#endif
4680 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004681
4682 if (newcmd != cmdbase)
4683 vim_free(newcmd);
4684
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004685 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004686 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004687 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004688 CloseHandle(si.hStdInput);
4689 }
4690 /* Close the handles to the subprocess, so that it goes away */
4691 CloseHandle(pi.hThread);
4692 CloseHandle(pi.hProcess);
4693 }
4694 else
4695 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004696 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004698 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004699#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004700 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4701
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004702 newcmd = lalloc(cmdlen, TRUE);
4703 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004704 {
4705#if defined(FEAT_GUI_W32)
4706 if (need_vimrun_warning)
4707 {
4708 MessageBox(NULL,
4709 _("VIMRUN.EXE not found in your $PATH.\n"
4710 "External commands will not pause after completion.\n"
4711 "See :help win32-vimrun for more information."),
4712 _("Vim Warning"),
4713 MB_ICONWARNING);
4714 need_vimrun_warning = FALSE;
4715 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004716 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004717 /* Use vimrun to execute the command. It opens a console
4718 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004719 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004720 vimrun_path,
4721 (msg_silent != 0 || (options & SHELL_DOOUT))
4722 ? "-s " : "",
4723 p_sh, p_shcf, cmd);
4724 else
4725#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004726 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004727 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004728 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004729 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004730 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004731 }
4732 }
4733
4734 if (tmode == TMODE_RAW)
4735 settmode(TMODE_RAW); /* set to raw mode */
4736
4737 /* Print the return value, unless "vimrun" was used. */
4738 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4739#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004740 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741#endif
4742 )
4743 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004744 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 msg_putchar('\n');
4746 }
4747#ifdef FEAT_TITLE
4748 resettitle();
4749#endif
4750
4751 signal(SIGINT, SIG_DFL);
4752#if defined(__GNUC__) && !defined(__MINGW32__)
4753 signal(SIGKILL, SIG_DFL);
4754#else
4755 signal(SIGBREAK, SIG_DFL);
4756#endif
4757 signal(SIGILL, SIG_DFL);
4758 signal(SIGFPE, SIG_DFL);
4759 signal(SIGSEGV, SIG_DFL);
4760 signal(SIGTERM, SIG_DFL);
4761 signal(SIGABRT, SIG_DFL);
4762
4763 return x;
4764}
4765
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01004766#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004767 static HANDLE
4768job_io_file_open(
4769 char_u *fname,
4770 DWORD dwDesiredAccess,
4771 DWORD dwShareMode,
4772 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
4773 DWORD dwCreationDisposition,
4774 DWORD dwFlagsAndAttributes)
4775{
4776 HANDLE h;
4777# ifdef FEAT_MBYTE
4778 WCHAR *wn = NULL;
4779 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4780 {
4781 wn = enc_to_utf16(fname, NULL);
4782 if (wn != NULL)
4783 {
4784 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
4785 lpSecurityAttributes, dwCreationDisposition,
4786 dwFlagsAndAttributes, NULL);
4787 vim_free(wn);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004788 }
4789 }
4790 if (wn == NULL)
4791# endif
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004792 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
4793 lpSecurityAttributes, dwCreationDisposition,
4794 dwFlagsAndAttributes, NULL);
4795 return h;
4796}
4797
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004798 void
Bram Moolenaar9a6e33a2016-02-16 19:25:12 +01004799mch_start_job(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004800{
4801 STARTUPINFO si;
4802 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02004803 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004804 SECURITY_ATTRIBUTES saAttr;
4805 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01004806 HANDLE ifd[2];
4807 HANDLE ofd[2];
4808 HANDLE efd[2];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004809
4810 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
4811 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
4812 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
4813 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
4814 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
4815 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
4816 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
4817
4818 if (use_out_for_err && use_null_for_out)
4819 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01004820
4821 ifd[0] = INVALID_HANDLE_VALUE;
4822 ifd[1] = INVALID_HANDLE_VALUE;
4823 ofd[0] = INVALID_HANDLE_VALUE;
4824 ofd[1] = INVALID_HANDLE_VALUE;
4825 efd[0] = INVALID_HANDLE_VALUE;
4826 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004827
Bram Moolenaar14207f42016-10-27 21:13:10 +02004828 jo = CreateJobObject(NULL, NULL);
4829 if (jo == NULL)
4830 {
4831 job->jv_status = JOB_FAILED;
4832 goto failed;
4833 }
4834
Bram Moolenaar76467df2016-02-12 19:30:26 +01004835 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004836 ZeroMemory(&si, sizeof(si));
4837 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01004838 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004839 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004840
Bram Moolenaard8070362016-02-15 21:56:54 +01004841 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4842 saAttr.bInheritHandle = TRUE;
4843 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004844
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004845 if (use_file_for_in)
4846 {
4847 char_u *fname = options->jo_io_name[PART_IN];
4848
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004849 ifd[0] = job_io_file_open(fname, GENERIC_READ,
4850 FILE_SHARE_READ | FILE_SHARE_WRITE,
4851 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
4852 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01004853 {
4854 EMSG2(_(e_notopen), fname);
4855 goto failed;
4856 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004857 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004858 else if (!use_null_for_in &&
4859 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004860 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004861 goto failed;
4862
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004863 if (use_file_for_out)
4864 {
4865 char_u *fname = options->jo_io_name[PART_OUT];
4866
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004867 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
4868 FILE_SHARE_READ | FILE_SHARE_WRITE,
4869 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
4870 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004871 {
4872 EMSG2(_(e_notopen), fname);
4873 goto failed;
4874 }
4875 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004876 else if (!use_null_for_out &&
4877 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004878 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01004879 goto failed;
4880
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004881 if (use_file_for_err)
4882 {
4883 char_u *fname = options->jo_io_name[PART_ERR];
4884
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01004885 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
4886 FILE_SHARE_READ | FILE_SHARE_WRITE,
4887 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
4888 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004889 {
4890 EMSG2(_(e_notopen), fname);
4891 goto failed;
4892 }
4893 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004894 else if (!use_out_for_err && !use_null_for_err &&
4895 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004896 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01004897 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01004898
Bram Moolenaard8070362016-02-15 21:56:54 +01004899 si.dwFlags |= STARTF_USESTDHANDLES;
4900 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004901 si.hStdOutput = ofd[1];
4902 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
4903
4904 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
4905 {
Bram Moolenaarde279892016-03-11 22:19:44 +01004906 if (options->jo_set & JO_CHANNEL)
4907 {
4908 channel = options->jo_channel;
4909 if (channel != NULL)
4910 ++channel->ch_refcount;
4911 }
4912 else
4913 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004914 if (channel == NULL)
4915 goto failed;
4916 }
Bram Moolenaard8070362016-02-15 21:56:54 +01004917
4918 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02004919 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004920 CREATE_DEFAULT_ERROR_MODE |
4921 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01004922 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004923 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01004924 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02004925 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004926 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004927 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01004928 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004929
Bram Moolenaar14207f42016-10-27 21:13:10 +02004930 if (!AssignProcessToJobObject(jo, pi.hProcess))
4931 {
4932 /* if failing, switch the way to terminate
4933 * process with TerminateProcess. */
4934 CloseHandle(jo);
4935 jo = NULL;
4936 }
4937 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01004938 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004939 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02004940 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004941 job->jv_status = JOB_STARTED;
4942
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02004943 CloseHandle(ifd[0]);
4944 CloseHandle(ofd[1]);
4945 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01004946 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01004947
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004948 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004949 if (channel != NULL)
4950 {
4951 channel_set_pipes(channel,
4952 use_file_for_in || use_null_for_in
4953 ? INVALID_FD : (sock_T)ifd[1],
4954 use_file_for_out || use_null_for_out
4955 ? INVALID_FD : (sock_T)ofd[0],
4956 use_out_for_err || use_file_for_err || use_null_for_err
4957 ? INVALID_FD : (sock_T)efd[0]);
4958 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01004959 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01004960 return;
4961
4962failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01004963 CloseHandle(ifd[0]);
4964 CloseHandle(ofd[0]);
4965 CloseHandle(efd[0]);
4966 CloseHandle(ifd[1]);
4967 CloseHandle(ofd[1]);
4968 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01004969 channel_unref(channel);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004970}
4971
4972 char *
4973mch_job_status(job_T *job)
4974{
4975 DWORD dwExitCode = 0;
4976
Bram Moolenaar76467df2016-02-12 19:30:26 +01004977 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
4978 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004979 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01004980 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar97792de2016-10-15 18:36:49 +02004981 if (job->jv_status != JOB_ENDED)
4982 {
4983 ch_log(job->jv_channel, "Job ended");
4984 job->jv_status = JOB_ENDED;
4985 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004986 return "dead";
4987 }
4988 return "run";
4989}
4990
Bram Moolenaar97792de2016-10-15 18:36:49 +02004991 job_T *
4992mch_detect_ended_job(job_T *job_list)
4993{
4994 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
4995 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
4996 job_T *job = job_list;
4997
4998 while (job != NULL)
4999 {
5000 DWORD n;
5001 DWORD result;
5002
5003 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5004 && job != NULL; job = job->jv_next)
5005 {
5006 if (job->jv_status == JOB_STARTED)
5007 {
5008 jobHandles[n] = job->jv_proc_info.hProcess;
5009 jobArray[n] = job;
5010 ++n;
5011 }
5012 }
5013 if (n == 0)
5014 continue;
5015 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5016 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5017 {
5018 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5019
5020 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5021 return wait_job;
5022 }
5023 }
5024 return NULL;
5025}
5026
Bram Moolenaarfb630902016-10-29 14:55:00 +02005027 static BOOL
5028terminate_all(HANDLE process, int code)
5029{
5030 PROCESSENTRY32 pe;
5031 HANDLE h = INVALID_HANDLE_VALUE;
5032 DWORD pid = GetProcessId(process);
5033
5034 if (pid != 0)
5035 {
5036 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5037 if (h != INVALID_HANDLE_VALUE)
5038 {
5039 pe.dwSize = sizeof(PROCESSENTRY32);
5040 if (!Process32First(h, &pe))
5041 goto theend;
5042
5043 do
5044 {
5045 if (pe.th32ParentProcessID == pid)
5046 {
5047 HANDLE ph = OpenProcess(
5048 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5049 if (ph != NULL)
5050 {
5051 terminate_all(ph, code);
5052 CloseHandle(ph);
5053 }
5054 }
5055 } while (Process32Next(h, &pe));
5056
5057 CloseHandle(h);
5058 }
5059 }
5060
5061theend:
5062 return TerminateProcess(process, code);
5063}
5064
5065/*
5066 * Send a (deadly) signal to "job".
5067 * Return FAIL if it didn't work.
5068 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005069 int
5070mch_stop_job(job_T *job, char_u *how)
5071{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005072 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005073
Bram Moolenaar923d9262016-02-25 20:56:01 +01005074 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005075 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005076 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005077 if (job->jv_job_object != NULL)
5078 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005079 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005080 }
5081
5082 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5083 return FAIL;
5084 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005085 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5086 job->jv_proc_info.dwProcessId)
5087 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005088 FreeConsole();
5089 return ret;
5090}
5091
5092/*
5093 * Clear the data related to "job".
5094 */
5095 void
5096mch_clear_job(job_T *job)
5097{
5098 if (job->jv_status != JOB_FAILED)
5099 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005100 if (job->jv_job_object != NULL)
5101 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005102 CloseHandle(job->jv_proc_info.hProcess);
5103 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005104}
5105#endif
5106
Bram Moolenaar071d4272004-06-13 20:20:40 +00005107
5108#ifndef FEAT_GUI_W32
5109
5110/*
5111 * Start termcap mode
5112 */
5113 static void
5114termcap_mode_start(void)
5115{
5116 DWORD cmodein;
5117
5118 if (g_fTermcapMode)
5119 return;
5120
5121 SaveConsoleBuffer(&g_cbNonTermcap);
5122
5123 if (g_cbTermcap.IsValid)
5124 {
5125 /*
5126 * We've been in termcap mode before. Restore certain screen
5127 * characteristics, including the buffer size and the window
5128 * size. Since we will be redrawing the screen, we don't need
5129 * to restore the actual contents of the buffer.
5130 */
5131 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5132 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5133 Rows = g_cbTermcap.Info.dwSize.Y;
5134 Columns = g_cbTermcap.Info.dwSize.X;
5135 }
5136 else
5137 {
5138 /*
5139 * This is our first time entering termcap mode. Clear the console
5140 * screen buffer, and resize the buffer to match the current window
5141 * size. We will use this as the size of our editing environment.
5142 */
5143 ClearConsoleBuffer(g_attrCurrent);
5144 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5145 }
5146
5147#ifdef FEAT_TITLE
5148 resettitle();
5149#endif
5150
5151 GetConsoleMode(g_hConIn, &cmodein);
5152#ifdef FEAT_MOUSE
5153 if (g_fMouseActive)
5154 cmodein |= ENABLE_MOUSE_INPUT;
5155 else
5156 cmodein &= ~ENABLE_MOUSE_INPUT;
5157#endif
5158 cmodein |= ENABLE_WINDOW_INPUT;
5159 SetConsoleMode(g_hConIn, cmodein);
5160
5161 redraw_later_clear();
5162 g_fTermcapMode = TRUE;
5163}
5164
5165
5166/*
5167 * End termcap mode
5168 */
5169 static void
5170termcap_mode_end(void)
5171{
5172 DWORD cmodein;
5173 ConsoleBuffer *cb;
5174 COORD coord;
5175 DWORD dwDummy;
5176
5177 if (!g_fTermcapMode)
5178 return;
5179
5180 SaveConsoleBuffer(&g_cbTermcap);
5181
5182 GetConsoleMode(g_hConIn, &cmodein);
5183 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5184 SetConsoleMode(g_hConIn, cmodein);
5185
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005186#ifdef FEAT_RESTORE_ORIG_SCREEN
5187 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5188#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005189 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005190#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191 RestoreConsoleBuffer(cb, p_rs);
5192 SetConsoleCursorInfo(g_hConOut, &g_cci);
5193
5194 if (p_rs || exiting)
5195 {
5196 /*
5197 * Clear anything that happens to be on the current line.
5198 */
5199 coord.X = 0;
5200 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5201 FillConsoleOutputCharacter(g_hConOut, ' ',
5202 cb->Info.dwSize.X, coord, &dwDummy);
5203 /*
5204 * The following is just for aesthetics. If we are exiting without
5205 * restoring the screen, then we want to have a prompt string
5206 * appear at the bottom line. However, the command interpreter
5207 * seems to always advance the cursor one line before displaying
5208 * the prompt string, which causes the screen to scroll. To
5209 * counter this, move the cursor up one line before exiting.
5210 */
5211 if (exiting && !p_rs)
5212 coord.Y--;
5213 /*
5214 * Position the cursor at the leftmost column of the desired row.
5215 */
5216 SetConsoleCursorPosition(g_hConOut, coord);
5217 }
5218
5219 g_fTermcapMode = FALSE;
5220}
5221#endif /* FEAT_GUI_W32 */
5222
5223
5224#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005225/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005226 void
5227mch_write(
5228 char_u *s,
5229 int len)
5230{
5231 /* never used */
5232}
5233
5234#else
5235
5236/*
5237 * clear `n' chars, starting from `coord'
5238 */
5239 static void
5240clear_chars(
5241 COORD coord,
5242 DWORD n)
5243{
5244 DWORD dwDummy;
5245
5246 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5247 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5248}
5249
5250
5251/*
5252 * Clear the screen
5253 */
5254 static void
5255clear_screen(void)
5256{
5257 g_coord.X = g_coord.Y = 0;
5258 clear_chars(g_coord, Rows * Columns);
5259}
5260
5261
5262/*
5263 * Clear to end of display
5264 */
5265 static void
5266clear_to_end_of_display(void)
5267{
5268 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5269 * Columns + (Columns - g_coord.X));
5270}
5271
5272
5273/*
5274 * Clear to end of line
5275 */
5276 static void
5277clear_to_end_of_line(void)
5278{
5279 clear_chars(g_coord, Columns - g_coord.X);
5280}
5281
5282
5283/*
5284 * Scroll the scroll region up by `cLines' lines
5285 */
5286 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005287scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005288{
5289 COORD oldcoord = g_coord;
5290
5291 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5292 delete_lines(cLines);
5293
5294 g_coord = oldcoord;
5295}
5296
5297
5298/*
5299 * Set the scroll region
5300 */
5301 static void
5302set_scroll_region(
5303 unsigned left,
5304 unsigned top,
5305 unsigned right,
5306 unsigned bottom)
5307{
5308 if (left >= right
5309 || top >= bottom
5310 || right > (unsigned) Columns - 1
5311 || bottom > (unsigned) Rows - 1)
5312 return;
5313
5314 g_srScrollRegion.Left = left;
5315 g_srScrollRegion.Top = top;
5316 g_srScrollRegion.Right = right;
5317 g_srScrollRegion.Bottom = bottom;
5318}
5319
5320
5321/*
5322 * Insert `cLines' lines at the current cursor position
5323 */
5324 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005325insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005326{
5327 SMALL_RECT source;
5328 COORD dest;
5329 CHAR_INFO fill;
5330
5331 dest.X = 0;
5332 dest.Y = g_coord.Y + cLines;
5333
5334 source.Left = 0;
5335 source.Top = g_coord.Y;
5336 source.Right = g_srScrollRegion.Right;
5337 source.Bottom = g_srScrollRegion.Bottom - cLines;
5338
5339 fill.Char.AsciiChar = ' ';
5340 fill.Attributes = g_attrCurrent;
5341
5342 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5343
5344 /* Here we have to deal with a win32 console flake: If the scroll
5345 * region looks like abc and we scroll c to a and fill with d we get
5346 * cbd... if we scroll block c one line at a time to a, we get cdd...
5347 * vim expects cdd consistently... So we have to deal with that
5348 * here... (this also occurs scrolling the same way in the other
5349 * direction). */
5350
5351 if (source.Bottom < dest.Y)
5352 {
5353 COORD coord;
5354
5355 coord.X = 0;
5356 coord.Y = source.Bottom;
5357 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5358 }
5359}
5360
5361
5362/*
5363 * Delete `cLines' lines at the current cursor position
5364 */
5365 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005366delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005367{
5368 SMALL_RECT source;
5369 COORD dest;
5370 CHAR_INFO fill;
5371 int nb;
5372
5373 dest.X = 0;
5374 dest.Y = g_coord.Y;
5375
5376 source.Left = 0;
5377 source.Top = g_coord.Y + cLines;
5378 source.Right = g_srScrollRegion.Right;
5379 source.Bottom = g_srScrollRegion.Bottom;
5380
5381 fill.Char.AsciiChar = ' ';
5382 fill.Attributes = g_attrCurrent;
5383
5384 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5385
5386 /* Here we have to deal with a win32 console flake: If the scroll
5387 * region looks like abc and we scroll c to a and fill with d we get
5388 * cbd... if we scroll block c one line at a time to a, we get cdd...
5389 * vim expects cdd consistently... So we have to deal with that
5390 * here... (this also occurs scrolling the same way in the other
5391 * direction). */
5392
5393 nb = dest.Y + (source.Bottom - source.Top) + 1;
5394
5395 if (nb < source.Top)
5396 {
5397 COORD coord;
5398
5399 coord.X = 0;
5400 coord.Y = nb;
5401 clear_chars(coord, Columns * (source.Top - nb));
5402 }
5403}
5404
5405
5406/*
5407 * Set the cursor position
5408 */
5409 static void
5410gotoxy(
5411 unsigned x,
5412 unsigned y)
5413{
5414 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5415 return;
5416
5417 /* external cursor coords are 1-based; internal are 0-based */
5418 g_coord.X = x - 1;
5419 g_coord.Y = y - 1;
5420 SetConsoleCursorPosition(g_hConOut, g_coord);
5421}
5422
5423
5424/*
5425 * Set the current text attribute = (foreground | background)
5426 * See ../doc/os_win32.txt for the numbers.
5427 */
5428 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005429textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005430{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005431 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005432
5433 SetConsoleTextAttribute(g_hConOut, wAttr);
5434}
5435
5436
5437 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005438textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005439{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005440 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005441
5442 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5443}
5444
5445
5446 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005447textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005448{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005449 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005450
5451 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5452}
5453
5454
5455/*
5456 * restore the default text attribute (whatever we started with)
5457 */
5458 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005459normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005460{
5461 textattr(g_attrDefault);
5462}
5463
5464
5465static WORD g_attrPreStandout = 0;
5466
5467/*
5468 * Make the text standout, by brightening it
5469 */
5470 static void
5471standout(void)
5472{
5473 g_attrPreStandout = g_attrCurrent;
5474 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5475}
5476
5477
5478/*
5479 * Turn off standout mode
5480 */
5481 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005482standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005483{
5484 if (g_attrPreStandout)
5485 {
5486 textattr(g_attrPreStandout);
5487 g_attrPreStandout = 0;
5488 }
5489}
5490
5491
5492/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005493 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005494 */
5495 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005496mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005497{
5498 char_u *p;
5499 int n;
5500
5501 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5502 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5503 if (T_ME[0] == ESC && T_ME[1] == '|')
5504 {
5505 p = T_ME + 2;
5506 n = getdigits(&p);
5507 if (*p == 'm' && n > 0)
5508 {
5509 cterm_normal_fg_color = (n & 0xf) + 1;
5510 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5511 }
5512 }
5513}
5514
5515
5516/*
5517 * visual bell: flash the screen
5518 */
5519 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005520visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521{
5522 COORD coordOrigin = {0, 0};
5523 WORD attrFlash = ~g_attrCurrent & 0xff;
5524
5525 DWORD dwDummy;
5526 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5527
5528 if (oldattrs == NULL)
5529 return;
5530 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5531 coordOrigin, &dwDummy);
5532 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5533 coordOrigin, &dwDummy);
5534
5535 Sleep(15); /* wait for 15 msec */
5536 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5537 coordOrigin, &dwDummy);
5538 vim_free(oldattrs);
5539}
5540
5541
5542/*
5543 * Make the cursor visible or invisible
5544 */
5545 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005546cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547{
5548 s_cursor_visible = fVisible;
5549#ifdef MCH_CURSOR_SHAPE
5550 mch_update_cursor();
5551#endif
5552}
5553
5554
5555/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005556 * write `cbToWrite' bytes in `pchBuf' to the screen
5557 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005558 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005559 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005561 char_u *pchBuf,
5562 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563{
5564 COORD coord = g_coord;
5565 DWORD written;
5566
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005567#ifdef FEAT_MBYTE
5568 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5569 {
5570 static WCHAR *unicodebuf = NULL;
5571 static int unibuflen = 0;
5572 int length;
5573 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005574
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005575 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5576 if (unicodebuf == NULL || length > unibuflen)
5577 {
5578 vim_free(unicodebuf);
5579 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5580 unibuflen = length;
5581 }
5582 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5583 unicodebuf, unibuflen);
5584
5585 cells = mb_string2cells(pchBuf, cbToWrite);
5586 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5587 coord, &written);
5588 /* When writing fails or didn't write a single character, pretend one
5589 * character was written, otherwise we get stuck. */
5590 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5591 coord, &cchwritten) == 0
5592 || cchwritten == 0)
5593 cchwritten = 1;
5594
5595 if (cchwritten == length)
5596 {
5597 written = cbToWrite;
5598 g_coord.X += (SHORT)cells;
5599 }
5600 else
5601 {
5602 char_u *p = pchBuf;
5603 for (n = 0; n < cchwritten; n++)
5604 mb_cptr_adv(p);
5605 written = p - pchBuf;
5606 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5607 }
5608 }
5609 else
5610#endif
5611 {
5612 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5613 coord, &written);
5614 /* When writing fails or didn't write a single character, pretend one
5615 * character was written, otherwise we get stuck. */
5616 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5617 coord, &written) == 0
5618 || written == 0)
5619 written = 1;
5620
5621 g_coord.X += (SHORT) written;
5622 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623
5624 while (g_coord.X > g_srScrollRegion.Right)
5625 {
5626 g_coord.X -= (SHORT) Columns;
5627 if (g_coord.Y < g_srScrollRegion.Bottom)
5628 g_coord.Y++;
5629 }
5630
5631 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5632
5633 return written;
5634}
5635
5636
5637/*
5638 * mch_write(): write the output buffer to the screen, translating ESC
5639 * sequences into calls to console output routines.
5640 */
5641 void
5642mch_write(
5643 char_u *s,
5644 int len)
5645{
5646 s[len] = NUL;
5647
5648 if (!term_console)
5649 {
5650 write(1, s, (unsigned)len);
5651 return;
5652 }
5653
5654 /* translate ESC | sequences into faked bios calls */
5655 while (len--)
5656 {
5657 /* optimization: use one single write_chars for runs of text,
5658 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005659 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005660
5661 if (p_wd)
5662 {
5663 WaitForChar(p_wd);
5664 if (prefix != 0)
5665 prefix = 1;
5666 }
5667
5668 if (prefix != 0)
5669 {
5670 DWORD nWritten;
5671
5672 nWritten = write_chars(s, prefix);
5673#ifdef MCH_WRITE_DUMP
5674 if (fdDump)
5675 {
5676 fputc('>', fdDump);
5677 fwrite(s, sizeof(char_u), nWritten, fdDump);
5678 fputs("<\n", fdDump);
5679 }
5680#endif
5681 len -= (nWritten - 1);
5682 s += nWritten;
5683 }
5684 else if (s[0] == '\n')
5685 {
5686 /* \n, newline: go to the beginning of the next line or scroll */
5687 if (g_coord.Y == g_srScrollRegion.Bottom)
5688 {
5689 scroll(1);
5690 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5691 }
5692 else
5693 {
5694 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5695 }
5696#ifdef MCH_WRITE_DUMP
5697 if (fdDump)
5698 fputs("\\n\n", fdDump);
5699#endif
5700 s++;
5701 }
5702 else if (s[0] == '\r')
5703 {
5704 /* \r, carriage return: go to beginning of line */
5705 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5706#ifdef MCH_WRITE_DUMP
5707 if (fdDump)
5708 fputs("\\r\n", fdDump);
5709#endif
5710 s++;
5711 }
5712 else if (s[0] == '\b')
5713 {
5714 /* \b, backspace: move cursor one position left */
5715 if (g_coord.X > g_srScrollRegion.Left)
5716 g_coord.X--;
5717 else if (g_coord.Y > g_srScrollRegion.Top)
5718 {
5719 g_coord.X = g_srScrollRegion.Right;
5720 g_coord.Y--;
5721 }
5722 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5723#ifdef MCH_WRITE_DUMP
5724 if (fdDump)
5725 fputs("\\b\n", fdDump);
5726#endif
5727 s++;
5728 }
5729 else if (s[0] == '\a')
5730 {
5731 /* \a, bell */
5732 MessageBeep(0xFFFFFFFF);
5733#ifdef MCH_WRITE_DUMP
5734 if (fdDump)
5735 fputs("\\a\n", fdDump);
5736#endif
5737 s++;
5738 }
5739 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5740 {
5741#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005742 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005744 char_u *p;
5745 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746
5747 switch (s[2])
5748 {
5749 /* one or two numeric arguments, separated by ';' */
5750
5751 case '0': case '1': case '2': case '3': case '4':
5752 case '5': case '6': case '7': case '8': case '9':
5753 p = s + 2;
5754 arg1 = getdigits(&p); /* no check for length! */
5755 if (p > s + len)
5756 break;
5757
5758 if (*p == ';')
5759 {
5760 ++p;
5761 arg2 = getdigits(&p); /* no check for length! */
5762 if (p > s + len)
5763 break;
5764
5765 if (*p == 'H')
5766 gotoxy(arg2, arg1);
5767 else if (*p == 'r')
5768 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5769 }
5770 else if (*p == 'A')
5771 {
5772 /* move cursor up arg1 lines in same column */
5773 gotoxy(g_coord.X + 1,
5774 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5775 }
5776 else if (*p == 'C')
5777 {
5778 /* move cursor right arg1 columns in same line */
5779 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5780 g_coord.Y + 1);
5781 }
5782 else if (*p == 'H')
5783 {
5784 gotoxy(1, arg1);
5785 }
5786 else if (*p == 'L')
5787 {
5788 insert_lines(arg1);
5789 }
5790 else if (*p == 'm')
5791 {
5792 if (arg1 == 0)
5793 normvideo();
5794 else
5795 textattr((WORD) arg1);
5796 }
5797 else if (*p == 'f')
5798 {
5799 textcolor((WORD) arg1);
5800 }
5801 else if (*p == 'b')
5802 {
5803 textbackground((WORD) arg1);
5804 }
5805 else if (*p == 'M')
5806 {
5807 delete_lines(arg1);
5808 }
5809
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005810 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005811 s = p + 1;
5812 break;
5813
5814
5815 /* Three-character escape sequences */
5816
5817 case 'A':
5818 /* move cursor up one line in same column */
5819 gotoxy(g_coord.X + 1,
5820 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5821 goto got3;
5822
5823 case 'B':
5824 visual_bell();
5825 goto got3;
5826
5827 case 'C':
5828 /* move cursor right one column in same line */
5829 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5830 g_coord.Y + 1);
5831 goto got3;
5832
5833 case 'E':
5834 termcap_mode_end();
5835 goto got3;
5836
5837 case 'F':
5838 standout();
5839 goto got3;
5840
5841 case 'f':
5842 standend();
5843 goto got3;
5844
5845 case 'H':
5846 gotoxy(1, 1);
5847 goto got3;
5848
5849 case 'j':
5850 clear_to_end_of_display();
5851 goto got3;
5852
5853 case 'J':
5854 clear_screen();
5855 goto got3;
5856
5857 case 'K':
5858 clear_to_end_of_line();
5859 goto got3;
5860
5861 case 'L':
5862 insert_lines(1);
5863 goto got3;
5864
5865 case 'M':
5866 delete_lines(1);
5867 goto got3;
5868
5869 case 'S':
5870 termcap_mode_start();
5871 goto got3;
5872
5873 case 'V':
5874 cursor_visible(TRUE);
5875 goto got3;
5876
5877 case 'v':
5878 cursor_visible(FALSE);
5879 goto got3;
5880
5881 got3:
5882 s += 3;
5883 len -= 2;
5884 }
5885
5886#ifdef MCH_WRITE_DUMP
5887 if (fdDump)
5888 {
5889 fputs("ESC | ", fdDump);
5890 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5891 fputc('\n', fdDump);
5892 }
5893#endif
5894 }
5895 else
5896 {
5897 /* Write a single character */
5898 DWORD nWritten;
5899
5900 nWritten = write_chars(s, 1);
5901#ifdef MCH_WRITE_DUMP
5902 if (fdDump)
5903 {
5904 fputc('>', fdDump);
5905 fwrite(s, sizeof(char_u), nWritten, fdDump);
5906 fputs("<\n", fdDump);
5907 }
5908#endif
5909
5910 len -= (nWritten - 1);
5911 s += nWritten;
5912 }
5913 }
5914
5915#ifdef MCH_WRITE_DUMP
5916 if (fdDump)
5917 fflush(fdDump);
5918#endif
5919}
5920
5921#endif /* FEAT_GUI_W32 */
5922
5923
5924/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01005925 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005926 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005927/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928 void
5929mch_delay(
5930 long msec,
5931 int ignoreinput)
5932{
5933#ifdef FEAT_GUI_W32
5934 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005935#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005937# ifdef FEAT_MZSCHEME
5938 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5939 {
5940 int towait = p_mzq;
5941
5942 /* if msec is large enough, wait by portions in p_mzq */
5943 while (msec > 0)
5944 {
5945 mzvim_check_threads();
5946 if (msec < towait)
5947 towait = msec;
5948 Sleep(towait);
5949 msec -= towait;
5950 }
5951 }
5952 else
5953# endif
5954 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955 else
5956 WaitForChar(msec);
5957#endif
5958}
5959
5960
5961/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01005962 * This version of remove is not scared by a readonly (backup) file.
5963 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005964 * Return 0 for success, -1 for failure.
5965 */
5966 int
5967mch_remove(char_u *name)
5968{
5969#ifdef FEAT_MBYTE
5970 WCHAR *wn = NULL;
5971 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005972#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005973
Bram Moolenaar203258c2016-01-17 22:15:16 +01005974 /*
5975 * On Windows, deleting a directory's symbolic link is done by
5976 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
5977 */
5978 if (mch_isdir(name) && mch_is_symbolic_link(name))
5979 return mch_rmdir(name);
5980
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005981 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5982
5983#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005984 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5985 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005986 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005987 if (wn != NULL)
5988 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005989 n = DeleteFileW(wn) ? 0 : -1;
5990 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005991 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992 }
5993 }
5994#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005995 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005996}
5997
5998
5999/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006000 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001 */
6002 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006003mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006004{
6005#ifndef FEAT_GUI_W32 /* never used */
6006 if (g_fCtrlCPressed || g_fCBrkPressed)
6007 {
6008 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6009 got_int = TRUE;
6010 }
6011#endif
6012}
6013
Bram Moolenaaree273972016-01-02 21:11:51 +01006014/* physical RAM to leave for the OS */
6015#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006016
6017/*
6018 * How much main memory in KiB that can be used by VIM.
6019 */
6020/*ARGSUSED*/
6021 long_u
6022mch_total_mem(int special)
6023{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006024 MEMORYSTATUSEX ms;
6025
Bram Moolenaaree273972016-01-02 21:11:51 +01006026 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006027 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6028 * what fits in 32 bits. But it's not always available. */
6029 ms.dwLength = sizeof(MEMORYSTATUSEX);
6030 GlobalMemoryStatusEx(&ms);
6031 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006032 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006033 /* Process address space fits in physical RAM, use all of it. */
6034 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006035 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006036 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006037 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006038 /* Catch old NT box or perverse hardware setup. */
6039 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006040 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006041 /* Use physical RAM less reserve for OS + data. */
6042 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006043}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006044
Bram Moolenaar071d4272004-06-13 20:20:40 +00006045#ifdef FEAT_MBYTE
6046/*
6047 * Same code as below, but with wide functions and no comments.
6048 * Return 0 for success, non-zero for failure.
6049 */
6050 int
6051mch_wrename(WCHAR *wold, WCHAR *wnew)
6052{
6053 WCHAR *p;
6054 int i;
6055 WCHAR szTempFile[_MAX_PATH + 1];
6056 WCHAR szNewPath[_MAX_PATH + 1];
6057 HANDLE hf;
6058
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006059 p = wold;
6060 for (i = 0; wold[i] != NUL; ++i)
6061 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6062 && wold[i + 1] != 0)
6063 p = wold + i + 1;
6064 if ((int)(wold + i - p) < 8 || p[6] != '~')
6065 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006066
6067 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6068 return -1;
6069 *p = NUL;
6070
6071 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6072 return -2;
6073
6074 if (!DeleteFileW(szTempFile))
6075 return -3;
6076
6077 if (!MoveFileW(wold, szTempFile))
6078 return -4;
6079
6080 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6081 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6082 return -5;
6083 if (!CloseHandle(hf))
6084 return -6;
6085
6086 if (!MoveFileW(szTempFile, wnew))
6087 {
6088 (void)MoveFileW(szTempFile, wold);
6089 return -7;
6090 }
6091
6092 DeleteFileW(szTempFile);
6093
6094 if (!DeleteFileW(wold))
6095 return -8;
6096
6097 return 0;
6098}
6099#endif
6100
6101
6102/*
6103 * mch_rename() works around a bug in rename (aka MoveFile) in
6104 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6105 * file whose short file name is "FOO.BAR" (its long file name will
6106 * be correct: "foo.bar~"). Because a file can be accessed by
6107 * either its SFN or its LFN, "foo.bar" has effectively been
6108 * renamed to "foo.bar", which is not at all what was wanted. This
6109 * seems to happen only when renaming files with three-character
6110 * extensions by appending a suffix that does not include ".".
6111 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6112 *
6113 * There is another problem, which isn't really a bug but isn't right either:
6114 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6115 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6116 * service pack 6. Doesn't seem to happen on Windows 98.
6117 *
6118 * Like rename(), returns 0 upon success, non-zero upon failure.
6119 * Should probably set errno appropriately when errors occur.
6120 */
6121 int
6122mch_rename(
6123 const char *pszOldFile,
6124 const char *pszNewFile)
6125{
6126 char szTempFile[_MAX_PATH+1];
6127 char szNewPath[_MAX_PATH+1];
6128 char *pszFilePart;
6129 HANDLE hf;
6130#ifdef FEAT_MBYTE
6131 WCHAR *wold = NULL;
6132 WCHAR *wnew = NULL;
6133 int retval = -1;
6134
6135 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6136 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006137 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6138 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006139 if (wold != NULL && wnew != NULL)
6140 retval = mch_wrename(wold, wnew);
6141 vim_free(wold);
6142 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006143 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006144 }
6145#endif
6146
6147 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006148 * No need to play tricks unless the file name contains a "~" as the
6149 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006150 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006151 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6152 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6153 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006154
6155 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6156 * a directory, no error is returned and pszFilePart will be NULL. */
6157 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6158 || pszFilePart == NULL)
6159 return -1;
6160 *pszFilePart = NUL;
6161
6162 /* Get (and create) a unique temporary file name in directory of new file */
6163 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6164 return -2;
6165
6166 /* blow the temp file away */
6167 if (!DeleteFile(szTempFile))
6168 return -3;
6169
6170 /* rename old file to the temp file */
6171 if (!MoveFile(pszOldFile, szTempFile))
6172 return -4;
6173
6174 /* now create an empty file called pszOldFile; this prevents the operating
6175 * system using pszOldFile as an alias (SFN) if we're renaming within the
6176 * same directory. For example, we're editing a file called
6177 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6178 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6179 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006180 * cause all sorts of problems later in buf_write(). So, we create an
6181 * empty file called filena~1.txt and the system will have to find some
6182 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006183 */
6184 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6185 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6186 return -5;
6187 if (!CloseHandle(hf))
6188 return -6;
6189
6190 /* rename the temp file to the new file */
6191 if (!MoveFile(szTempFile, pszNewFile))
6192 {
6193 /* Renaming failed. Rename the file back to its old name, so that it
6194 * looks like nothing happened. */
6195 (void)MoveFile(szTempFile, pszOldFile);
6196
6197 return -7;
6198 }
6199
6200 /* Seems to be left around on Novell filesystems */
6201 DeleteFile(szTempFile);
6202
6203 /* finally, remove the empty old file */
6204 if (!DeleteFile(pszOldFile))
6205 return -8;
6206
6207 return 0; /* success */
6208}
6209
6210/*
6211 * Get the default shell for the current hardware platform
6212 */
6213 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006214default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006215{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 PlatformId();
6217
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006218 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219}
6220
6221/*
6222 * mch_access() extends access() to do more detailed check on network drives.
6223 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6224 */
6225 int
6226mch_access(char *n, int p)
6227{
6228 HANDLE hFile;
6229 DWORD am;
6230 int retval = -1; /* default: fail */
6231#ifdef FEAT_MBYTE
6232 WCHAR *wn = NULL;
6233
6234 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006235 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006236#endif
6237
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006238 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 {
6240 char TempName[_MAX_PATH + 16] = "";
6241#ifdef FEAT_MBYTE
6242 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6243#endif
6244
6245 if (p & R_OK)
6246 {
6247 /* Read check is performed by seeing if we can do a find file on
6248 * the directory for any file. */
6249#ifdef FEAT_MBYTE
6250 if (wn != NULL)
6251 {
6252 int i;
6253 WIN32_FIND_DATAW d;
6254
6255 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6256 TempNameW[i] = wn[i];
6257 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6258 TempNameW[i++] = '\\';
6259 TempNameW[i++] = '*';
6260 TempNameW[i++] = 0;
6261
6262 hFile = FindFirstFileW(TempNameW, &d);
6263 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006264 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 else
6266 (void)FindClose(hFile);
6267 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006268 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269#endif
6270 {
6271 char *pch;
6272 WIN32_FIND_DATA d;
6273
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006274 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 pch = TempName + STRLEN(TempName) - 1;
6276 if (*pch != '\\' && *pch != '/')
6277 *++pch = '\\';
6278 *++pch = '*';
6279 *++pch = NUL;
6280
6281 hFile = FindFirstFile(TempName, &d);
6282 if (hFile == INVALID_HANDLE_VALUE)
6283 goto getout;
6284 (void)FindClose(hFile);
6285 }
6286 }
6287
6288 if (p & W_OK)
6289 {
6290 /* Trying to create a temporary file in the directory should catch
6291 * directories on read-only network shares. However, in
6292 * directories whose ACL allows writes but denies deletes will end
6293 * up keeping the temporary file :-(. */
6294#ifdef FEAT_MBYTE
6295 if (wn != NULL)
6296 {
6297 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006298 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006299 else
6300 DeleteFileW(TempNameW);
6301 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006302 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006303#endif
6304 {
6305 if (!GetTempFileName(n, "VIM", 0, TempName))
6306 goto getout;
6307 mch_remove((char_u *)TempName);
6308 }
6309 }
6310 }
6311 else
6312 {
6313 /* Trying to open the file for the required access does ACL, read-only
6314 * network share, and file attribute checks. */
6315 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6316 | ((p & R_OK) ? GENERIC_READ : 0);
6317#ifdef FEAT_MBYTE
6318 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006320 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321#endif
6322 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6323 if (hFile == INVALID_HANDLE_VALUE)
6324 goto getout;
6325 CloseHandle(hFile);
6326 }
6327
6328 retval = 0; /* success */
6329getout:
6330#ifdef FEAT_MBYTE
6331 vim_free(wn);
6332#endif
6333 return retval;
6334}
6335
6336#if defined(FEAT_MBYTE) || defined(PROTO)
6337/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006338 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 */
6340 int
6341mch_open(char *name, int flags, int mode)
6342{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006343 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6344# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 WCHAR *wn;
6346 int f;
6347
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006348 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006350 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006351 if (wn != NULL)
6352 {
6353 f = _wopen(wn, flags, mode);
6354 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006355 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006356 }
6357 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006358# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006359
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006360 /* open() can open a file which name is longer than _MAX_PATH bytes
6361 * and shorter than _MAX_PATH characters successfully, but sometimes it
6362 * causes unexpected error in another part. We make it an error explicitly
6363 * here. */
6364 if (strlen(name) >= _MAX_PATH)
6365 return -1;
6366
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367 return open(name, flags, mode);
6368}
6369
6370/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006371 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006372 */
6373 FILE *
6374mch_fopen(char *name, char *mode)
6375{
6376 WCHAR *wn, *wm;
6377 FILE *f = NULL;
6378
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006379 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006380 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006381# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006382 /* Work around an annoying assertion in the Microsoft debug CRT
6383 * when mode's text/binary setting doesn't match _get_fmode(). */
6384 char newMode = mode[strlen(mode) - 1];
6385 int oldMode = 0;
6386
6387 _get_fmode(&oldMode);
6388 if (newMode == 't')
6389 _set_fmode(_O_TEXT);
6390 else if (newMode == 'b')
6391 _set_fmode(_O_BINARY);
6392# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006393 wn = enc_to_utf16((char_u *)name, NULL);
6394 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006395 if (wn != NULL && wm != NULL)
6396 f = _wfopen(wn, wm);
6397 vim_free(wn);
6398 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006399
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006400# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006401 _set_fmode(oldMode);
6402# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006403 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404 }
6405
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006406 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6407 * and shorter than _MAX_PATH characters successfully, but sometimes it
6408 * causes unexpected error in another part. We make it an error explicitly
6409 * here. */
6410 if (strlen(name) >= _MAX_PATH)
6411 return NULL;
6412
Bram Moolenaar071d4272004-06-13 20:20:40 +00006413 return fopen(name, mode);
6414}
6415#endif
6416
6417#ifdef FEAT_MBYTE
6418/*
6419 * SUB STREAM (aka info stream) handling:
6420 *
6421 * NTFS can have sub streams for each file. Normal contents of file is
6422 * stored in the main stream, and extra contents (author information and
6423 * title and so on) can be stored in sub stream. After Windows 2000, user
6424 * can access and store those informations in sub streams via explorer's
6425 * property menuitem in right click menu. Those informations in sub streams
6426 * were lost when copying only the main stream. So we have to copy sub
6427 * streams.
6428 *
6429 * Incomplete explanation:
6430 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6431 * More useful info and an example:
6432 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6433 */
6434
6435/*
6436 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6437 * and write to stream "substream" of file "to".
6438 * Errors are ignored.
6439 */
6440 static void
6441copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6442{
6443 HANDLE hTo;
6444 WCHAR *to_name;
6445
6446 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6447 wcscpy(to_name, to);
6448 wcscat(to_name, substream);
6449
6450 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6451 FILE_ATTRIBUTE_NORMAL, NULL);
6452 if (hTo != INVALID_HANDLE_VALUE)
6453 {
6454 long done;
6455 DWORD todo;
6456 DWORD readcnt, written;
6457 char buf[4096];
6458
6459 /* Copy block of bytes at a time. Abort when something goes wrong. */
6460 for (done = 0; done < len; done += written)
6461 {
6462 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006463 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6464 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006465 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6466 FALSE, FALSE, context)
6467 || readcnt != todo
6468 || !WriteFile(hTo, buf, todo, &written, NULL)
6469 || written != todo)
6470 break;
6471 }
6472 CloseHandle(hTo);
6473 }
6474
6475 free(to_name);
6476}
6477
6478/*
6479 * Copy info streams from file "from" to file "to".
6480 */
6481 static void
6482copy_infostreams(char_u *from, char_u *to)
6483{
6484 WCHAR *fromw;
6485 WCHAR *tow;
6486 HANDLE sh;
6487 WIN32_STREAM_ID sid;
6488 int headersize;
6489 WCHAR streamname[_MAX_PATH];
6490 DWORD readcount;
6491 void *context = NULL;
6492 DWORD lo, hi;
6493 int len;
6494
6495 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006496 fromw = enc_to_utf16(from, NULL);
6497 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006498 if (fromw != NULL && tow != NULL)
6499 {
6500 /* Open the file for reading. */
6501 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6502 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6503 if (sh != INVALID_HANDLE_VALUE)
6504 {
6505 /* Use BackupRead() to find the info streams. Repeat until we
6506 * have done them all.*/
6507 for (;;)
6508 {
6509 /* Get the header to find the length of the stream name. If
6510 * the "readcount" is zero we have done all info streams. */
6511 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006512 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6514 &readcount, FALSE, FALSE, &context)
6515 || readcount == 0)
6516 break;
6517
6518 /* We only deal with streams that have a name. The normal
6519 * file data appears to be without a name, even though docs
6520 * suggest it is called "::$DATA". */
6521 if (sid.dwStreamNameSize > 0)
6522 {
6523 /* Read the stream name. */
6524 if (!BackupRead(sh, (LPBYTE)streamname,
6525 sid.dwStreamNameSize,
6526 &readcount, FALSE, FALSE, &context))
6527 break;
6528
6529 /* Copy an info stream with a name ":anything:$DATA".
6530 * Skip "::$DATA", it has no stream name (examples suggest
6531 * it might be used for the normal file contents).
6532 * Note that BackupRead() counts bytes, but the name is in
6533 * wide characters. */
6534 len = readcount / sizeof(WCHAR);
6535 streamname[len] = 0;
6536 if (len > 7 && wcsicmp(streamname + len - 6,
6537 L":$DATA") == 0)
6538 {
6539 streamname[len - 6] = 0;
6540 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006541 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006542 }
6543 }
6544
6545 /* Advance to the next stream. We might try seeking too far,
6546 * but BackupSeek() doesn't skip over stream borders, thus
6547 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006548 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549 &lo, &hi, &context);
6550 }
6551
6552 /* Clear the context. */
6553 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6554
6555 CloseHandle(sh);
6556 }
6557 }
6558 vim_free(fromw);
6559 vim_free(tow);
6560}
6561#endif
6562
6563/*
6564 * Copy file attributes from file "from" to file "to".
6565 * For Windows NT and later we copy info streams.
6566 * Always returns zero, errors are ignored.
6567 */
6568 int
6569mch_copy_file_attribute(char_u *from, char_u *to)
6570{
6571#ifdef FEAT_MBYTE
6572 /* File streams only work on Windows NT and later. */
6573 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006574 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575#endif
6576 return 0;
6577}
6578
6579#if defined(MYRESETSTKOFLW) || defined(PROTO)
6580/*
6581 * Recreate a destroyed stack guard page in win32.
6582 * Written by Benjamin Peterson.
6583 */
6584
6585/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586#define MIN_STACK_WINNT 2
6587
6588/*
6589 * This function does the same thing as _resetstkoflw(), which is only
6590 * available in DevStudio .net and later.
6591 * Returns 0 for failure, 1 for success.
6592 */
6593 int
6594myresetstkoflw(void)
6595{
6596 BYTE *pStackPtr;
6597 BYTE *pGuardPage;
6598 BYTE *pStackBase;
6599 BYTE *pLowestPossiblePage;
6600 MEMORY_BASIC_INFORMATION mbi;
6601 SYSTEM_INFO si;
6602 DWORD nPageSize;
6603 DWORD dummy;
6604
Bram Moolenaar071d4272004-06-13 20:20:40 +00006605 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006606
6607 /* We need to know the system page size. */
6608 GetSystemInfo(&si);
6609 nPageSize = si.dwPageSize;
6610
6611 /* ...and the current stack pointer */
6612 pStackPtr = (BYTE*)_alloca(1);
6613
6614 /* ...and the base of the stack. */
6615 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6616 return 0;
6617 pStackBase = (BYTE*)mbi.AllocationBase;
6618
6619 /* ...and the page thats min_stack_req pages away from stack base; this is
6620 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006621 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006624 /* We want the first committed page in the stack Start at the stack
6625 * base and move forward through memory until we find a committed block.
6626 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006627 BYTE *pBlock = pStackBase;
6628
Bram Moolenaara466c992005-07-09 21:03:22 +00006629 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630 {
6631 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6632 return 0;
6633
6634 pBlock += mbi.RegionSize;
6635
6636 if (mbi.State & MEM_COMMIT)
6637 break;
6638 }
6639
6640 /* mbi now describes the first committed block in the stack. */
6641 if (mbi.Protect & PAGE_GUARD)
6642 return 1;
6643
6644 /* decide where the guard page should start */
6645 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6646 pGuardPage = pLowestPossiblePage;
6647 else
6648 pGuardPage = (BYTE*)mbi.BaseAddress;
6649
6650 /* allocate the guard page */
6651 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6652 return 0;
6653
6654 /* apply the guard attribute to the page */
6655 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6656 &dummy))
6657 return 0;
6658 }
6659
6660 return 1;
6661}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006662#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006663
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006664
6665#if defined(FEAT_MBYTE) || defined(PROTO)
6666/*
6667 * The command line arguments in UCS2
6668 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006669static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006670static LPWSTR *ArglistW = NULL;
6671static int global_argc = 0;
6672static char **global_argv;
6673
6674static int used_file_argc = 0; /* last argument in global_argv[] used
6675 for the argument list. */
6676static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6677 command line arguments added to
6678 the argument list */
6679static int used_file_count = 0; /* nr of entries in used_file_indexes */
6680static int used_file_literal = FALSE; /* take file names literally */
6681static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006682static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006683static int used_alist_count = 0;
6684
6685
6686/*
6687 * Get the command line arguments. Unicode version.
6688 * Returns argc. Zero when something fails.
6689 */
6690 int
6691get_cmd_argsW(char ***argvp)
6692{
6693 char **argv = NULL;
6694 int argc = 0;
6695 int i;
6696
Bram Moolenaar14993322014-09-09 12:25:33 +02006697 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006698 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6699 if (ArglistW != NULL)
6700 {
6701 argv = malloc((nArgsW + 1) * sizeof(char *));
6702 if (argv != NULL)
6703 {
6704 argc = nArgsW;
6705 argv[argc] = NULL;
6706 for (i = 0; i < argc; ++i)
6707 {
6708 int len;
6709
6710 /* Convert each Unicode argument to the current codepage. */
6711 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006712 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006713 (LPSTR *)&argv[i], &len, 0, 0);
6714 if (argv[i] == NULL)
6715 {
6716 /* Out of memory, clear everything. */
6717 while (i > 0)
6718 free(argv[--i]);
6719 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006720 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006721 argc = 0;
6722 }
6723 }
6724 }
6725 }
6726
6727 global_argc = argc;
6728 global_argv = argv;
6729 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006730 {
6731 if (used_file_indexes != NULL)
6732 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006733 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006734 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006735
6736 if (argvp != NULL)
6737 *argvp = argv;
6738 return argc;
6739}
6740
6741 void
6742free_cmd_argsW(void)
6743{
6744 if (ArglistW != NULL)
6745 {
6746 GlobalFree(ArglistW);
6747 ArglistW = NULL;
6748 }
6749}
6750
6751/*
6752 * Remember "name" is an argument that was added to the argument list.
6753 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6754 * is called.
6755 */
6756 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006757used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006758{
6759 int i;
6760
6761 if (used_file_indexes == NULL)
6762 return;
6763 for (i = used_file_argc + 1; i < global_argc; ++i)
6764 if (STRCMP(global_argv[i], name) == 0)
6765 {
6766 used_file_argc = i;
6767 used_file_indexes[used_file_count++] = i;
6768 break;
6769 }
6770 used_file_literal = literal;
6771 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006772 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006773}
6774
6775/*
6776 * Remember the length of the argument list as it was. If it changes then we
6777 * leave it alone when 'encoding' is set.
6778 */
6779 void
6780set_alist_count(void)
6781{
6782 used_alist_count = GARGCOUNT;
6783}
6784
6785/*
6786 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6787 * has been changed while starting up. Use the UCS-2 command line arguments
6788 * and convert them to 'encoding'.
6789 */
6790 void
6791fix_arg_enc(void)
6792{
6793 int i;
6794 int idx;
6795 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006796 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006797
6798 /* Safety checks:
6799 * - if argument count differs between the wide and non-wide argument
6800 * list, something must be wrong.
6801 * - the file name arguments must have been located.
6802 * - the length of the argument list wasn't changed by the user.
6803 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006804 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006805 || ArglistW == NULL
6806 || used_file_indexes == NULL
6807 || used_file_count == 0
6808 || used_alist_count != GARGCOUNT)
6809 return;
6810
Bram Moolenaar86b68352004-12-27 21:59:20 +00006811 /* Remember the buffer numbers for the arguments. */
6812 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6813 if (fnum_list == NULL)
6814 return; /* out of memory */
6815 for (i = 0; i < GARGCOUNT; ++i)
6816 fnum_list[i] = GARGLIST[i].ae_fnum;
6817
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006818 /* Clear the argument list. Make room for the new arguments. */
6819 alist_clear(&global_alist);
6820 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006821 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006822
6823 for (i = 0; i < used_file_count; ++i)
6824 {
6825 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006826 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006827 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006828 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006829#ifdef FEAT_DIFF
6830 /* When using diff mode may need to concatenate file name to
6831 * directory name. Just like it's done in main(). */
6832 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6833 && !mch_isdir(alist_name(&GARGLIST[0])))
6834 {
6835 char_u *r;
6836
6837 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6838 if (r != NULL)
6839 {
6840 vim_free(str);
6841 str = r;
6842 }
6843 }
6844#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006845 /* Re-use the old buffer by renaming it. When not using literal
6846 * names it's done by alist_expand() below. */
6847 if (used_file_literal)
6848 buf_set_name(fnum_list[i], str);
6849
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006850 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006851 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006852 }
6853
6854 if (!used_file_literal)
6855 {
6856 /* Now expand wildcards in the arguments. */
6857 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6858 * filename characters but are excluded from 'isfname' to make
6859 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6860 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006861 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006862 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6863 }
6864
6865 /* If wildcard expansion failed, we are editing the first file of the
6866 * arglist and there is no file name: Edit the first argument now. */
6867 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6868 {
6869 do_cmdline_cmd((char_u *)":rewind");
6870 if (GARGCOUNT == 1 && used_file_full_path)
6871 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6872 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006873
6874 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006875}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006876#endif