blob: 7695e938c3a393f064af0ac0b26310ed931ddea5 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
53#ifdef __MINGW32__
54# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
55# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
56# endif
57# ifndef RIGHTMOST_BUTTON_PRESSED
58# define RIGHTMOST_BUTTON_PRESSED 0x0002
59# endif
60# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
61# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
62# endif
63# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
64# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
65# endif
66# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
67# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
68# endif
69
70/*
71 * EventFlags
72 */
73# ifndef MOUSE_MOVED
74# define MOUSE_MOVED 0x0001
75# endif
76# ifndef DOUBLE_CLICK
77# define DOUBLE_CLICK 0x0002
78# endif
79#endif
80
81/* Record all output and all keyboard & mouse input */
82/* #define MCH_WRITE_DUMP */
83
84#ifdef MCH_WRITE_DUMP
85FILE* fdDump = NULL;
86#endif
87
88/*
89 * When generating prototypes for Win32 on Unix, these lines make the syntax
90 * errors disappear. They do not need to be correct.
91 */
92#ifdef PROTO
93#define WINAPI
94#define WINBASEAPI
95typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000096typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000097typedef int ACCESS_MASK;
98typedef int BOOL;
99typedef int COLORREF;
100typedef int CONSOLE_CURSOR_INFO;
101typedef int COORD;
102typedef int DWORD;
103typedef int HANDLE;
104typedef int HDC;
105typedef int HFONT;
106typedef int HICON;
107typedef int HINSTANCE;
108typedef int HWND;
109typedef int INPUT_RECORD;
110typedef int KEY_EVENT_RECORD;
111typedef int LOGFONT;
112typedef int LPBOOL;
113typedef int LPCTSTR;
114typedef int LPDWORD;
115typedef int LPSTR;
116typedef int LPTSTR;
117typedef int LPVOID;
118typedef int MOUSE_EVENT_RECORD;
119typedef int PACL;
120typedef int PDWORD;
121typedef int PHANDLE;
122typedef int PRINTDLG;
123typedef int PSECURITY_DESCRIPTOR;
124typedef int PSID;
125typedef int SECURITY_INFORMATION;
126typedef int SHORT;
127typedef int SMALL_RECT;
128typedef int TEXTMETRIC;
129typedef int TOKEN_INFORMATION_CLASS;
130typedef int TRUSTEE;
131typedef int WORD;
132typedef int WCHAR;
133typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100134typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200135typedef int SE_OBJECT_TYPE;
136typedef int PSNSECINFO;
137typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100138typedef int STARTUPINFO;
139typedef int PROCESS_INFORMATION;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140#endif
141
142#ifndef FEAT_GUI_W32
143/* Undocumented API in kernel32.dll needed to work around dead key bug in
144 * console-mode applications in NT 4.0. If you switch keyboard layouts
145 * in a console app to a layout that includes dead keys and then hit a
146 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
147 * and Michael Dietrich for helping me figure out this workaround.
148 */
149
150/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
151#ifndef WINBASEAPI
152# define WINBASEAPI __stdcall
153#endif
154#if defined(__BORLANDC__)
155typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
156#else
157typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
158#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000159static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160#endif
161
162#if defined(__BORLANDC__)
163/* Strangely Borland uses a non-standard name. */
164# define wcsicmp(a, b) wcscmpi((a), (b))
165#endif
166
Bram Moolenaar82881492012-11-20 16:53:39 +0100167#ifndef PROTO
168
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200169/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200170#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100171LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200172BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
173BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
174BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
175#endif
176
Bram Moolenaar82881492012-11-20 16:53:39 +0100177#endif /* PROTO */
178
Bram Moolenaar071d4272004-06-13 20:20:40 +0000179#ifndef FEAT_GUI_W32
180/* Win32 Console handles for input and output */
181static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
182static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
183
184/* Win32 Screen buffer,coordinate,console I/O information */
185static SMALL_RECT g_srScrollRegion;
186static COORD g_coord; /* 0-based, but external coords are 1-based */
187
188/* The attribute of the screen when the editor was started */
189static WORD g_attrDefault = 7; /* lightgray text on black background */
190static WORD g_attrCurrent;
191
192static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
193static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
194static int g_fForceExit = FALSE; /* set when forcefully exiting */
195
196static void termcap_mode_start(void);
197static void termcap_mode_end(void);
198static void clear_chars(COORD coord, DWORD n);
199static void clear_screen(void);
200static void clear_to_end_of_display(void);
201static void clear_to_end_of_line(void);
202static void scroll(unsigned cLines);
203static void set_scroll_region(unsigned left, unsigned top,
204 unsigned right, unsigned bottom);
205static void insert_lines(unsigned cLines);
206static void delete_lines(unsigned cLines);
207static void gotoxy(unsigned x, unsigned y);
208static void normvideo(void);
209static void textattr(WORD wAttr);
210static void textcolor(WORD wAttr);
211static void textbackground(WORD wAttr);
212static void standout(void);
213static void standend(void);
214static void visual_bell(void);
215static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200216static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
217static WCHAR tgetch(int *pmodifiers, WCHAR *pch2);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000218static void create_conin(void);
219static int s_cursor_visible = TRUE;
220static int did_create_conin = FALSE;
221#else
222static int s_dont_use_vimrun = TRUE;
223static int need_vimrun_warning = FALSE;
224static char *vimrun_path = "vimrun ";
225#endif
226
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200227static int win32_getattrs(char_u *name);
228static int win32_setattrs(char_u *name, int attrs);
229static int win32_set_archive(char_u *name);
230
Bram Moolenaar071d4272004-06-13 20:20:40 +0000231#ifndef FEAT_GUI_W32
232static int suppress_winsize = 1; /* don't fiddle with console */
233#endif
234
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235static char_u *exe_path = NULL;
236
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100237static BOOL win8_or_later = FALSE;
238
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100239/*
240 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100241 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100242 */
243 static BOOL
244read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100245 HANDLE hInput,
246 INPUT_RECORD *lpBuffer,
247 DWORD nLength,
248 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100249{
250 enum
251 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100252 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100253 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100254 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100255 static DWORD s_dwIndex = 0;
256 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100257 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100258 int head;
259 int tail;
260 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100261
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200262 if (nLength == -2)
263 return (s_dwMax > 0) ? TRUE : FALSE;
264
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100265 if (!win8_or_later)
266 {
267 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200268 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
269 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100270 }
271
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100272 if (s_dwMax == 0)
273 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100274 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200275 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
276 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100277 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100278 s_dwIndex = 0;
279 s_dwMax = dwEvents;
280 if (dwEvents == 0)
281 {
282 *lpEvents = 0;
283 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100284 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100285
286 if (s_dwMax > 1)
287 {
288 head = 0;
289 tail = s_dwMax - 1;
290 while (head != tail)
291 {
292 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
293 && s_irCache[head + 1].EventType
294 == WINDOW_BUFFER_SIZE_EVENT)
295 {
296 /* Remove duplicate event to avoid flicker. */
297 for (i = head; i < tail; ++i)
298 s_irCache[i] = s_irCache[i + 1];
299 --tail;
300 continue;
301 }
302 head++;
303 }
304 s_dwMax = tail + 1;
305 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100306 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100307
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100308 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200309 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100310 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100311 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100312 return TRUE;
313}
314
315/*
316 * Version of PeekConsoleInput() that works with IME.
317 */
318 static BOOL
319peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100320 HANDLE hInput,
321 INPUT_RECORD *lpBuffer,
322 DWORD nLength,
323 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100324{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100325 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100326}
327
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200328 static DWORD
329msg_wait_for_multiple_objects(
330 DWORD nCount,
331 LPHANDLE pHandles,
332 BOOL fWaitAll,
333 DWORD dwMilliseconds,
334 DWORD dwWakeMask)
335{
336 if (read_console_input(NULL, NULL, -2, NULL))
337 return WAIT_OBJECT_0;
338 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
339 dwMilliseconds, dwWakeMask);
340}
341
342 static DWORD
343wait_for_single_object(
344 HANDLE hHandle,
345 DWORD dwMilliseconds)
346{
347 if (read_console_input(NULL, NULL, -2, NULL))
348 return WAIT_OBJECT_0;
349 return WaitForSingleObject(hHandle, dwMilliseconds);
350}
351
Bram Moolenaar071d4272004-06-13 20:20:40 +0000352 static void
353get_exe_name(void)
354{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100355 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
356 * as the maximum length that works (plus a NUL byte). */
357#define MAX_ENV_PATH_LEN 8192
358 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200359 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360
361 if (exe_name == NULL)
362 {
363 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100364 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365 if (*temp != NUL)
366 exe_name = FullName_save((char_u *)temp, FALSE);
367 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000368
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200369 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000370 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200371 exe_path = vim_strnsave(exe_name,
372 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200373 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000374 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200375 /* Append our starting directory to $PATH, so that when doing
376 * "!xxd" it's found in our starting directory. Needed because
377 * SearchPath() also looks there. */
378 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100379 if (p == NULL
380 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200381 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100382 if (p == NULL || *p == NUL)
383 temp[0] = NUL;
384 else
385 {
386 STRCPY(temp, p);
387 STRCAT(temp, ";");
388 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200389 STRCAT(temp, exe_path);
390 vim_setenv((char_u *)"PATH", temp);
391 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000392 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000393 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394}
395
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200396/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100397 * Unescape characters in "p" that appear in "escaped".
398 */
399 static void
400unescape_shellxquote(char_u *p, char_u *escaped)
401{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100402 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100403 int n;
404
405 while (*p != NUL)
406 {
407 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
408 mch_memmove(p, p + 1, l--);
409#ifdef FEAT_MBYTE
410 n = (*mb_ptr2len)(p);
411#else
412 n = 1;
413#endif
414 p += n;
415 l -= n;
416 }
417}
418
419/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200420 * Load library "name".
421 */
422 HINSTANCE
423vimLoadLib(char *name)
424{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200425 HINSTANCE dll = NULL;
426 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200427
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200428 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
429 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200430 if (exe_path == NULL)
431 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200432 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200433 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200434#ifdef FEAT_MBYTE
435 WCHAR old_dirw[MAXPATHL];
436
437 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
438 {
439 /* Change directory to where the executable is, both to make
440 * sure we find a .dll there and to avoid looking for a .dll
441 * in the current directory. */
442 SetCurrentDirectory(exe_path);
443 dll = LoadLibrary(name);
444 SetCurrentDirectoryW(old_dirw);
445 return dll;
446 }
447 /* Retry with non-wide function (for Windows 98). */
448 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
449#endif
450 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
451 {
452 /* Change directory to where the executable is, both to make
453 * sure we find a .dll there and to avoid looking for a .dll
454 * in the current directory. */
455 SetCurrentDirectory(exe_path);
456 dll = LoadLibrary(name);
457 SetCurrentDirectory(old_dir);
458 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200459 }
460 return dll;
461}
462
Bram Moolenaar071d4272004-06-13 20:20:40 +0000463#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
464# ifndef GETTEXT_DLL
465# define GETTEXT_DLL "libintl.dll"
466# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200467/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000468static char *null_libintl_gettext(const char *);
469static char *null_libintl_textdomain(const char *);
470static char *null_libintl_bindtextdomain(const char *, const char *);
471static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000472
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200473static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000474char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
475char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
476char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000477 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000478char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
479 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000480
481 int
482dyn_libintl_init(char *libname)
483{
484 int i;
485 static struct
486 {
487 char *name;
488 FARPROC *ptr;
489 } libintl_entry[] =
490 {
491 {"gettext", (FARPROC*)&dyn_libintl_gettext},
492 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
493 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
494 {NULL, NULL}
495 };
496
497 /* No need to initialize twice. */
498 if (hLibintlDLL)
499 return 1;
500 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200501 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502 if (!hLibintlDLL)
503 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200504 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200506 verbose_enter();
507 EMSG2(_(e_loadlib), GETTEXT_DLL);
508 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200510 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511 }
512 for (i = 0; libintl_entry[i].name != NULL
513 && libintl_entry[i].ptr != NULL; ++i)
514 {
515 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
516 libintl_entry[i].name)) == NULL)
517 {
518 dyn_libintl_end();
519 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000520 {
521 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000523 verbose_leave();
524 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000525 return 0;
526 }
527 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000528
529 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000530 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000531 "bind_textdomain_codeset");
532 if (dyn_libintl_bind_textdomain_codeset == NULL)
533 dyn_libintl_bind_textdomain_codeset =
534 null_libintl_bind_textdomain_codeset;
535
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 return 1;
537}
538
539 void
540dyn_libintl_end()
541{
542 if (hLibintlDLL)
543 FreeLibrary(hLibintlDLL);
544 hLibintlDLL = NULL;
545 dyn_libintl_gettext = null_libintl_gettext;
546 dyn_libintl_textdomain = null_libintl_textdomain;
547 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000548 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549}
550
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000551/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000553null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000554{
555 return (char*)msgid;
556}
557
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000558/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000560null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561{
562 return NULL;
563}
564
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000565/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000566 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000567null_libintl_bind_textdomain_codeset(const char *domainname,
568 const char *codeset)
569{
570 return NULL;
571}
572
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000573/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000574 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000575null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576{
577 return NULL;
578}
579
580#endif /* DYNAMIC_GETTEXT */
581
582/* This symbol is not defined in older versions of the SDK or Visual C++ */
583
584#ifndef VER_PLATFORM_WIN32_WINDOWS
585# define VER_PLATFORM_WIN32_WINDOWS 1
586#endif
587
588DWORD g_PlatformId;
589
590#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100591# ifndef PROTO
592# include <aclapi.h>
593# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200594# ifndef PROTECTED_DACL_SECURITY_INFORMATION
595# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
596# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100597
Bram Moolenaar071d4272004-06-13 20:20:40 +0000598/*
599 * These are needed to dynamically load the ADVAPI DLL, which is not
600 * implemented under Windows 95 (and causes VIM to crash)
601 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200602typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200604typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000605 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
606 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200607# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200608typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200609 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200610typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200611 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
612 PSECURITY_DESCRIPTOR *);
613# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614
615static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
616static PSNSECINFO pSetNamedSecurityInfo;
617static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200618# ifdef FEAT_MBYTE
619static PSNSECINFOW pSetNamedSecurityInfoW;
620static PGNSECINFOW pGetNamedSecurityInfoW;
621# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622#endif
623
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200624typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
625
626static BOOL allowPiping = FALSE;
627static PSETHANDLEINFORMATION pSetHandleInformation;
628
Bram Moolenaar27515922013-06-29 15:36:26 +0200629#ifdef HAVE_ACL
630/*
631 * Enables or disables the specified privilege.
632 */
633 static BOOL
634win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
635{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100636 BOOL bResult;
637 LUID luid;
638 HANDLE hToken;
639 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200640
641 if (!OpenProcessToken(GetCurrentProcess(),
642 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
643 return FALSE;
644
645 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
646 {
647 CloseHandle(hToken);
648 return FALSE;
649 }
650
Bram Moolenaar45500912014-07-09 20:51:07 +0200651 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200652 tokenPrivileges.Privileges[0].Luid = luid;
653 tokenPrivileges.Privileges[0].Attributes = bEnable ?
654 SE_PRIVILEGE_ENABLED : 0;
655
656 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
657 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
658
659 CloseHandle(hToken);
660
661 return bResult && GetLastError() == ERROR_SUCCESS;
662}
663#endif
664
Bram Moolenaar071d4272004-06-13 20:20:40 +0000665/*
666 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
667 * VER_PLATFORM_WIN32_WINDOWS (Win95).
668 */
669 void
670PlatformId(void)
671{
672 static int done = FALSE;
673
674 if (!done)
675 {
676 OSVERSIONINFO ovi;
677
678 ovi.dwOSVersionInfoSize = sizeof(ovi);
679 GetVersionEx(&ovi);
680
681 g_PlatformId = ovi.dwPlatformId;
682
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100683 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
684 || ovi.dwMajorVersion > 6)
685 win8_or_later = TRUE;
686
Bram Moolenaar071d4272004-06-13 20:20:40 +0000687#ifdef HAVE_ACL
688 /*
689 * Load the ADVAPI runtime if we are on anything
690 * other than Windows 95
691 */
692 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
693 {
694 /*
695 * do this load. Problems: Doesn't unload at end of run (this is
696 * theoretically okay, since Windows should unload it when VIM
697 * terminates). Should we be using the 'mch_libcall' routines?
698 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
699 * time we verify security...
700 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200701 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000702 if (advapi_lib != NULL)
703 {
704 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
705 "SetNamedSecurityInfoA");
706 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
707 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200708# ifdef FEAT_MBYTE
709 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
710 "SetNamedSecurityInfoW");
711 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
712 "GetNamedSecurityInfoW");
713# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000714 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200715 || pGetNamedSecurityInfo == NULL
716# ifdef FEAT_MBYTE
717 || pSetNamedSecurityInfoW == NULL
718 || pGetNamedSecurityInfoW == NULL
719# endif
720 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721 {
722 /* If we can't get the function addresses, set advapi_lib
723 * to NULL so that we don't use them. */
724 FreeLibrary(advapi_lib);
725 advapi_lib = NULL;
726 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200727 /* Enable privilege for getting or setting SACLs. */
728 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000729 }
730 }
731#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200732 /*
733 * If we are on windows NT, try to load the pipe functions, only
734 * available from Win2K.
735 */
736 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
737 {
738 HANDLE kernel32 = GetModuleHandle("kernel32");
739 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
740 kernel32, "SetHandleInformation");
741
742 allowPiping = pSetHandleInformation != NULL;
743 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000744 done = TRUE;
745 }
746}
747
748/*
749 * Return TRUE when running on Windows 95 (or 98 or ME).
750 * Only to be used after mch_init().
751 */
752 int
753mch_windows95(void)
754{
755 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
756}
757
758#ifdef FEAT_GUI_W32
759/*
760 * Used to work around the "can't do synchronous spawn"
761 * problem on Win32s, without resorting to Universal Thunk.
762 */
763static int old_num_windows;
764static int num_windows;
765
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000766/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000767 static BOOL CALLBACK
768win32ssynch_cb(HWND hwnd, LPARAM lparam)
769{
770 num_windows++;
771 return TRUE;
772}
773#endif
774
775#ifndef FEAT_GUI_W32
776
777#define SHIFT (SHIFT_PRESSED)
778#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
779#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
780#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
781
782
783/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
784 * We map function keys to their ANSI terminal equivalents, as produced
785 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
786 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
787 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
788 * combinations of function/arrow/etc keys.
789 */
790
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000791static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792{
793 WORD wVirtKey;
794 BOOL fAnsiKey;
795 int chAlone;
796 int chShift;
797 int chCtrl;
798 int chAlt;
799} VirtKeyMap[] =
800{
801
802/* Key ANSI alone shift ctrl alt */
803 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
804
805 { VK_F1, TRUE, ';', 'T', '^', 'h', },
806 { VK_F2, TRUE, '<', 'U', '_', 'i', },
807 { VK_F3, TRUE, '=', 'V', '`', 'j', },
808 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
809 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
810 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
811 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
812 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
813 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
814 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
815 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
816 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
817
818 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
819 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
820 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
821 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
822 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
823 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
824 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
825 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
826 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
827 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
828
829 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
830
831#if 0
832 /* Most people don't have F13-F20, but what the hell... */
833 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
834 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
835 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
836 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
837 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
838 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
839 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
840 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
841#endif
842 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
843 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
844 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
845 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
846
847 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
848 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
849 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
850 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
851 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
852 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
853 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
854 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
855 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
856 /* Sorry, out of number space! <negri>*/
857 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
858
859};
860
861
862#ifdef _MSC_VER
863// The ToAscii bug destroys several registers. Need to turn off optimization
864// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000865# pragma warning(push)
866# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000867# pragma optimize("", off)
868#endif
869
870#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200871# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000872#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200873# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000874#endif
875
876/* The return code indicates key code size. */
877 static int
878#ifdef __BORLANDC__
879 __stdcall
880#endif
881win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000882 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000883{
884 UINT uMods = pker->dwControlKeyState;
885 static int s_iIsDead = 0;
886 static WORD awAnsiCode[2];
887 static BYTE abKeystate[256];
888
889
890 if (s_iIsDead == 2)
891 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200892 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000893 s_iIsDead = 0;
894 return 1;
895 }
896
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200897 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898 return 1;
899
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200900 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901
902 // Should only be non-NULL on NT 4.0
903 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
904 {
905 CHAR szKLID[KL_NAMELENGTH];
906
907 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
908 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
909 }
910
911 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200912 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
914 if (uMods & SHIFT_PRESSED)
915 abKeystate[VK_SHIFT] = 0x80;
916 if (uMods & CAPSLOCK_ON)
917 abKeystate[VK_CAPITAL] = 1;
918
919 if ((uMods & ALT_GR) == ALT_GR)
920 {
921 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
922 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
923 }
924
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200925 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
926 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000927
928 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200929 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930
931 return s_iIsDead;
932}
933
934#ifdef _MSC_VER
935/* MUST switch optimization on again here, otherwise a call to
936 * decode_key_event() may crash (e.g. when hitting caps-lock) */
937# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000938# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939
940# if (_MSC_VER < 1100)
941/* MUST turn off global optimisation for this next function, or
942 * pressing ctrl-minus in insert mode crashes Vim when built with
943 * VC4.1. -- negri. */
944# pragma optimize("g", off)
945# endif
946#endif
947
948static BOOL g_fJustGotFocus = FALSE;
949
950/*
951 * Decode a KEY_EVENT into one or two keystrokes
952 */
953 static BOOL
954decode_key_event(
955 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200956 WCHAR *pch,
957 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000958 int *pmodifiers,
959 BOOL fDoPost)
960{
961 int i;
962 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
963
964 *pch = *pch2 = NUL;
965 g_fJustGotFocus = FALSE;
966
967 /* ignore key up events */
968 if (!pker->bKeyDown)
969 return FALSE;
970
971 /* ignore some keystrokes */
972 switch (pker->wVirtualKeyCode)
973 {
974 /* modifiers */
975 case VK_SHIFT:
976 case VK_CONTROL:
977 case VK_MENU: /* Alt key */
978 return FALSE;
979
980 default:
981 break;
982 }
983
984 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200985 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000986 {
987 /* Ctrl-6 is Ctrl-^ */
988 if (pker->wVirtualKeyCode == '6')
989 {
990 *pch = Ctrl_HAT;
991 return TRUE;
992 }
993 /* Ctrl-2 is Ctrl-@ */
994 else if (pker->wVirtualKeyCode == '2')
995 {
996 *pch = NUL;
997 return TRUE;
998 }
999 /* Ctrl-- is Ctrl-_ */
1000 else if (pker->wVirtualKeyCode == 0xBD)
1001 {
1002 *pch = Ctrl__;
1003 return TRUE;
1004 }
1005 }
1006
1007 /* Shift-TAB */
1008 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1009 {
1010 *pch = K_NUL;
1011 *pch2 = '\017';
1012 return TRUE;
1013 }
1014
1015 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1016 {
1017 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1018 {
1019 if (nModifs == 0)
1020 *pch = VirtKeyMap[i].chAlone;
1021 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1022 *pch = VirtKeyMap[i].chShift;
1023 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1024 *pch = VirtKeyMap[i].chCtrl;
1025 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1026 *pch = VirtKeyMap[i].chAlt;
1027
1028 if (*pch != 0)
1029 {
1030 if (VirtKeyMap[i].fAnsiKey)
1031 {
1032 *pch2 = *pch;
1033 *pch = K_NUL;
1034 }
1035
1036 return TRUE;
1037 }
1038 }
1039 }
1040
1041 i = win32_kbd_patch_key(pker);
1042
1043 if (i < 0)
1044 *pch = NUL;
1045 else
1046 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001047 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001048
1049 if (pmodifiers != NULL)
1050 {
1051 /* Pass on the ALT key as a modifier, but only when not combined
1052 * with CTRL (which is ALTGR). */
1053 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1054 *pmodifiers |= MOD_MASK_ALT;
1055
1056 /* Pass on SHIFT only for special keys, because we don't know when
1057 * it's already included with the character. */
1058 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1059 *pmodifiers |= MOD_MASK_SHIFT;
1060
1061 /* Pass on CTRL only for non-special keys, because we don't know
1062 * when it's already included with the character. And not when
1063 * combined with ALT (which is ALTGR). */
1064 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1065 && *pch >= 0x20 && *pch < 0x80)
1066 *pmodifiers |= MOD_MASK_CTRL;
1067 }
1068 }
1069
1070 return (*pch != NUL);
1071}
1072
1073#ifdef _MSC_VER
1074# pragma optimize("", on)
1075#endif
1076
1077#endif /* FEAT_GUI_W32 */
1078
1079
1080#ifdef FEAT_MOUSE
1081
1082/*
1083 * For the GUI the mouse handling is in gui_w32.c.
1084 */
1085# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001086/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001087 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001088mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001089{
1090}
1091# else
1092static int g_fMouseAvail = FALSE; /* mouse present */
1093static int g_fMouseActive = FALSE; /* mouse enabled */
1094static int g_nMouseClick = -1; /* mouse status */
1095static int g_xMouse; /* mouse x coordinate */
1096static int g_yMouse; /* mouse y coordinate */
1097
1098/*
1099 * Enable or disable mouse input
1100 */
1101 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001102mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001103{
1104 DWORD cmodein;
1105
1106 if (!g_fMouseAvail)
1107 return;
1108
1109 g_fMouseActive = on;
1110 GetConsoleMode(g_hConIn, &cmodein);
1111
1112 if (g_fMouseActive)
1113 cmodein |= ENABLE_MOUSE_INPUT;
1114 else
1115 cmodein &= ~ENABLE_MOUSE_INPUT;
1116
1117 SetConsoleMode(g_hConIn, cmodein);
1118}
1119
1120
1121/*
1122 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1123 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1124 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1125 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1126 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1127 * and we return the mouse position in g_xMouse and g_yMouse.
1128 *
1129 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1130 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1131 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1132 *
1133 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1134 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1135 *
1136 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1137 * moves, even if it stays within the same character cell. We ignore
1138 * all MOUSE_MOVED messages if the position hasn't really changed, and
1139 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1140 * we're only interested in MOUSE_DRAG).
1141 *
1142 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1143 * 2-button mouses by pressing the left & right buttons simultaneously.
1144 * In practice, it's almost impossible to click both at the same time,
1145 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1146 * in such cases, if the user is clicking quickly.
1147 */
1148 static BOOL
1149decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001150 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151{
1152 static int s_nOldButton = -1;
1153 static int s_nOldMouseClick = -1;
1154 static int s_xOldMouse = -1;
1155 static int s_yOldMouse = -1;
1156 static linenr_T s_old_topline = 0;
1157#ifdef FEAT_DIFF
1158 static int s_old_topfill = 0;
1159#endif
1160 static int s_cClicks = 1;
1161 static BOOL s_fReleased = TRUE;
1162 static DWORD s_dwLastClickTime = 0;
1163 static BOOL s_fNextIsMiddle = FALSE;
1164
1165 static DWORD cButtons = 0; /* number of buttons supported */
1166
1167 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1168 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1169 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1170 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1171
1172 int nButton;
1173
1174 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1175 cButtons = 2;
1176
1177 if (!g_fMouseAvail || !g_fMouseActive)
1178 {
1179 g_nMouseClick = -1;
1180 return FALSE;
1181 }
1182
1183 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1184 if (g_fJustGotFocus)
1185 {
1186 g_fJustGotFocus = FALSE;
1187 return FALSE;
1188 }
1189
1190 /* unprocessed mouse click? */
1191 if (g_nMouseClick != -1)
1192 return TRUE;
1193
1194 nButton = -1;
1195 g_xMouse = pmer->dwMousePosition.X;
1196 g_yMouse = pmer->dwMousePosition.Y;
1197
1198 if (pmer->dwEventFlags == MOUSE_MOVED)
1199 {
1200 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1201 * events even when the mouse moves only within a char cell.) */
1202 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1203 return FALSE;
1204 }
1205
1206 /* If no buttons are pressed... */
1207 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1208 {
1209 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1210 if (s_fReleased)
1211 return FALSE;
1212
1213 nButton = MOUSE_RELEASE;
1214 s_fReleased = TRUE;
1215 }
1216 else /* one or more buttons pressed */
1217 {
1218 /* on a 2-button mouse, hold down left and right buttons
1219 * simultaneously to get MIDDLE. */
1220
1221 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1222 {
1223 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1224
1225 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001226 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001227 if (dwLR == LEFT || dwLR == RIGHT)
1228 {
1229 for (;;)
1230 {
1231 /* wait a short time for next input event */
1232 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1233 != WAIT_OBJECT_0)
1234 break;
1235 else
1236 {
1237 DWORD cRecords = 0;
1238 INPUT_RECORD ir;
1239 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1240
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001241 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001242
1243 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1244 || !(pmer2->dwButtonState & LEFT_RIGHT))
1245 break;
1246 else
1247 {
1248 if (pmer2->dwEventFlags != MOUSE_MOVED)
1249 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001250 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001251
1252 return decode_mouse_event(pmer2);
1253 }
1254 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1255 s_yOldMouse == pmer2->dwMousePosition.Y)
1256 {
1257 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001258 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001259
1260 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001261 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001262
1263 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1264 break;
1265 }
1266 else
1267 break;
1268 }
1269 }
1270 }
1271 }
1272 }
1273
1274 if (s_fNextIsMiddle)
1275 {
1276 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1277 ? MOUSE_DRAG : MOUSE_MIDDLE;
1278 s_fNextIsMiddle = FALSE;
1279 }
1280 else if (cButtons == 2 &&
1281 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1282 {
1283 nButton = MOUSE_MIDDLE;
1284
1285 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1286 {
1287 s_fNextIsMiddle = TRUE;
1288 nButton = MOUSE_RELEASE;
1289 }
1290 }
1291 else if ((pmer->dwButtonState & LEFT) == LEFT)
1292 nButton = MOUSE_LEFT;
1293 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1294 nButton = MOUSE_MIDDLE;
1295 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1296 nButton = MOUSE_RIGHT;
1297
1298 if (! s_fReleased && ! s_fNextIsMiddle
1299 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1300 return FALSE;
1301
1302 s_fReleased = s_fNextIsMiddle;
1303 }
1304
1305 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1306 {
1307 /* button pressed or released, without mouse moving */
1308 if (nButton != -1 && nButton != MOUSE_RELEASE)
1309 {
1310 DWORD dwCurrentTime = GetTickCount();
1311
1312 if (s_xOldMouse != g_xMouse
1313 || s_yOldMouse != g_yMouse
1314 || s_nOldButton != nButton
1315 || s_old_topline != curwin->w_topline
1316#ifdef FEAT_DIFF
1317 || s_old_topfill != curwin->w_topfill
1318#endif
1319 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1320 {
1321 s_cClicks = 1;
1322 }
1323 else if (++s_cClicks > 4)
1324 {
1325 s_cClicks = 1;
1326 }
1327
1328 s_dwLastClickTime = dwCurrentTime;
1329 }
1330 }
1331 else if (pmer->dwEventFlags == MOUSE_MOVED)
1332 {
1333 if (nButton != -1 && nButton != MOUSE_RELEASE)
1334 nButton = MOUSE_DRAG;
1335
1336 s_cClicks = 1;
1337 }
1338
1339 if (nButton == -1)
1340 return FALSE;
1341
1342 if (nButton != MOUSE_RELEASE)
1343 s_nOldButton = nButton;
1344
1345 g_nMouseClick = nButton;
1346
1347 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1348 g_nMouseClick |= MOUSE_SHIFT;
1349 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1350 g_nMouseClick |= MOUSE_CTRL;
1351 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1352 g_nMouseClick |= MOUSE_ALT;
1353
1354 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1355 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1356
1357 /* only pass on interesting (i.e., different) mouse events */
1358 if (s_xOldMouse == g_xMouse
1359 && s_yOldMouse == g_yMouse
1360 && s_nOldMouseClick == g_nMouseClick)
1361 {
1362 g_nMouseClick = -1;
1363 return FALSE;
1364 }
1365
1366 s_xOldMouse = g_xMouse;
1367 s_yOldMouse = g_yMouse;
1368 s_old_topline = curwin->w_topline;
1369#ifdef FEAT_DIFF
1370 s_old_topfill = curwin->w_topfill;
1371#endif
1372 s_nOldMouseClick = g_nMouseClick;
1373
1374 return TRUE;
1375}
1376
1377# endif /* FEAT_GUI_W32 */
1378#endif /* FEAT_MOUSE */
1379
1380
1381#ifdef MCH_CURSOR_SHAPE
1382/*
1383 * Set the shape of the cursor.
1384 * 'thickness' can be from 1 (thin) to 99 (block)
1385 */
1386 static void
1387mch_set_cursor_shape(int thickness)
1388{
1389 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1390 ConsoleCursorInfo.dwSize = thickness;
1391 ConsoleCursorInfo.bVisible = s_cursor_visible;
1392
1393 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1394 if (s_cursor_visible)
1395 SetConsoleCursorPosition(g_hConOut, g_coord);
1396}
1397
1398 void
1399mch_update_cursor(void)
1400{
1401 int idx;
1402 int thickness;
1403
1404 /*
1405 * How the cursor is drawn depends on the current mode.
1406 */
1407 idx = get_shape_idx(FALSE);
1408
1409 if (shape_table[idx].shape == SHAPE_BLOCK)
1410 thickness = 99; /* 100 doesn't work on W95 */
1411 else
1412 thickness = shape_table[idx].percentage;
1413 mch_set_cursor_shape(thickness);
1414}
1415#endif
1416
1417#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1418/*
1419 * Handle FOCUS_EVENT.
1420 */
1421 static void
1422handle_focus_event(INPUT_RECORD ir)
1423{
1424 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1425 ui_focus_change((int)g_fJustGotFocus);
1426}
1427
1428/*
1429 * Wait until console input from keyboard or mouse is available,
1430 * or the time is up.
1431 * Return TRUE if something is available FALSE if not.
1432 */
1433 static int
1434WaitForChar(long msec)
1435{
1436 DWORD dwNow = 0, dwEndTime = 0;
1437 INPUT_RECORD ir;
1438 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001439 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001440
1441 if (msec > 0)
1442 /* Wait until the specified time has elapsed. */
1443 dwEndTime = GetTickCount() + msec;
1444 else if (msec < 0)
1445 /* Wait forever. */
1446 dwEndTime = INFINITE;
1447
1448 /* We need to loop until the end of the time period, because
1449 * we might get multiple unusable mouse events in that time.
1450 */
1451 for (;;)
1452 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001453#ifdef FEAT_MZSCHEME
1454 mzvim_check_threads();
1455#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456#ifdef FEAT_CLIENTSERVER
1457 serverProcessPendingMessages();
1458#endif
1459 if (0
1460#ifdef FEAT_MOUSE
1461 || g_nMouseClick != -1
1462#endif
1463#ifdef FEAT_CLIENTSERVER
1464 || input_available()
1465#endif
1466 )
1467 return TRUE;
1468
1469 if (msec > 0)
1470 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001471 /* If the specified wait time has passed, return. Beware that
1472 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001474 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475 break;
1476 }
1477 if (msec != 0)
1478 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001479 DWORD dwWaitTime = dwEndTime - dwNow;
1480
1481#ifdef FEAT_MZSCHEME
1482 if (mzthreads_allowed() && p_mzq > 0
1483 && (msec < 0 || (long)dwWaitTime > p_mzq))
1484 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1485#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001486#ifdef FEAT_CLIENTSERVER
1487 /* Wait for either an event on the console input or a message in
1488 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001489 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001490 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001492 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493#endif
1494 continue;
1495 }
1496
1497 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001498 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499
1500#ifdef FEAT_MBYTE_IME
1501 if (State & CMDLINE && msg_row == Rows - 1)
1502 {
1503 CONSOLE_SCREEN_BUFFER_INFO csbi;
1504
1505 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1506 {
1507 if (csbi.dwCursorPosition.Y != msg_row)
1508 {
1509 /* The screen is now messed up, must redraw the
1510 * command line and later all the windows. */
1511 redraw_all_later(CLEAR);
1512 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1513 redrawcmd();
1514 }
1515 }
1516 }
1517#endif
1518
1519 if (cRecords > 0)
1520 {
1521 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1522 {
1523#ifdef FEAT_MBYTE_IME
1524 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1525 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001526 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001527 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1528 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001529 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001530 continue;
1531 }
1532#endif
1533 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1534 NULL, FALSE))
1535 return TRUE;
1536 }
1537
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001538 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539
1540 if (ir.EventType == FOCUS_EVENT)
1541 handle_focus_event(ir);
1542 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1543 shell_resized();
1544#ifdef FEAT_MOUSE
1545 else if (ir.EventType == MOUSE_EVENT
1546 && decode_mouse_event(&ir.Event.MouseEvent))
1547 return TRUE;
1548#endif
1549 }
1550 else if (msec == 0)
1551 break;
1552 }
1553
1554#ifdef FEAT_CLIENTSERVER
1555 /* Something might have been received while we were waiting. */
1556 if (input_available())
1557 return TRUE;
1558#endif
1559 return FALSE;
1560}
1561
1562#ifndef FEAT_GUI_MSWIN
1563/*
1564 * return non-zero if a character is available
1565 */
1566 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001567mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568{
1569 return WaitForChar(0L);
1570}
1571#endif
1572
1573/*
1574 * Create the console input. Used when reading stdin doesn't work.
1575 */
1576 static void
1577create_conin(void)
1578{
1579 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1580 FILE_SHARE_READ|FILE_SHARE_WRITE,
1581 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001582 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583 did_create_conin = TRUE;
1584}
1585
1586/*
1587 * Get a keystroke or a mouse event
1588 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001589 static WCHAR
1590tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001592 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593
1594 for (;;)
1595 {
1596 INPUT_RECORD ir;
1597 DWORD cRecords = 0;
1598
1599#ifdef FEAT_CLIENTSERVER
1600 (void)WaitForChar(-1L);
1601 if (input_available())
1602 return 0;
1603# ifdef FEAT_MOUSE
1604 if (g_nMouseClick != -1)
1605 return 0;
1606# endif
1607#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001608 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001609 {
1610 if (did_create_conin)
1611 read_error_exit();
1612 create_conin();
1613 continue;
1614 }
1615
1616 if (ir.EventType == KEY_EVENT)
1617 {
1618 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1619 pmodifiers, TRUE))
1620 return ch;
1621 }
1622 else if (ir.EventType == FOCUS_EVENT)
1623 handle_focus_event(ir);
1624 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1625 shell_resized();
1626#ifdef FEAT_MOUSE
1627 else if (ir.EventType == MOUSE_EVENT)
1628 {
1629 if (decode_mouse_event(&ir.Event.MouseEvent))
1630 return 0;
1631 }
1632#endif
1633 }
1634}
1635#endif /* !FEAT_GUI_W32 */
1636
1637
1638/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001639 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 * Get one or more characters from the keyboard or the mouse.
1641 * If time == 0, do not wait for characters.
1642 * If time == n, wait a short time for characters.
1643 * If time == -1, wait forever for characters.
1644 * Returns the number of characters read into buf.
1645 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001646/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001647 int
1648mch_inchar(
1649 char_u *buf,
1650 int maxlen,
1651 long time,
1652 int tb_change_cnt)
1653{
1654#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1655
1656 int len;
1657 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001658#define TYPEAHEADLEN 20
1659 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1660 static int typeaheadlen = 0;
1661
1662 /* First use any typeahead that was kept because "buf" was too small. */
1663 if (typeaheadlen > 0)
1664 goto theend;
1665
1666#ifdef FEAT_SNIFF
1667 if (want_sniff_request)
1668 {
1669 if (sniff_request_waiting)
1670 {
1671 /* return K_SNIFF */
1672 typeahead[typeaheadlen++] = CSI;
1673 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1674 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1675 sniff_request_waiting = 0;
1676 want_sniff_request = 0;
1677 goto theend;
1678 }
1679 else if (time < 0 || time > 250)
1680 {
1681 /* don't wait too long, a request might be pending */
1682 time = 250;
1683 }
1684 }
1685#endif
1686
1687 if (time >= 0)
1688 {
1689 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001690 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 }
1692 else /* time == -1, wait forever */
1693 {
1694 mch_set_winsize_now(); /* Allow winsize changes from now on */
1695
Bram Moolenaar3918c952005-03-15 22:34:55 +00001696 /*
1697 * If there is no character available within 2 seconds (default)
1698 * write the autoscript file to disk. Or cause the CursorHold event
1699 * to be triggered.
1700 */
1701 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001702 {
1703#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001704 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001705 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001706 buf[0] = K_SPECIAL;
1707 buf[1] = KS_EXTRA;
1708 buf[2] = (int)KE_CURSORHOLD;
1709 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 }
1711#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001712 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 }
1714 }
1715
1716 /*
1717 * Try to read as many characters as there are, until the buffer is full.
1718 */
1719
1720 /* we will get at least one key. Get more if they are available. */
1721 g_fCBrkPressed = FALSE;
1722
1723#ifdef MCH_WRITE_DUMP
1724 if (fdDump)
1725 fputc('[', fdDump);
1726#endif
1727
1728 /* Keep looping until there is something in the typeahead buffer and more
1729 * to get and still room in the buffer (up to two bytes for a char and
1730 * three bytes for a modifier). */
1731 while ((typeaheadlen == 0 || WaitForChar(0L))
1732 && typeaheadlen + 5 <= TYPEAHEADLEN)
1733 {
1734 if (typebuf_changed(tb_change_cnt))
1735 {
1736 /* "buf" may be invalid now if a client put something in the
1737 * typeahead buffer and "buf" is in the typeahead buffer. */
1738 typeaheadlen = 0;
1739 break;
1740 }
1741#ifdef FEAT_MOUSE
1742 if (g_nMouseClick != -1)
1743 {
1744# ifdef MCH_WRITE_DUMP
1745 if (fdDump)
1746 fprintf(fdDump, "{%02x @ %d, %d}",
1747 g_nMouseClick, g_xMouse, g_yMouse);
1748# endif
1749 typeahead[typeaheadlen++] = ESC + 128;
1750 typeahead[typeaheadlen++] = 'M';
1751 typeahead[typeaheadlen++] = g_nMouseClick;
1752 typeahead[typeaheadlen++] = g_xMouse + '!';
1753 typeahead[typeaheadlen++] = g_yMouse + '!';
1754 g_nMouseClick = -1;
1755 }
1756 else
1757#endif
1758 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001759 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 int modifiers = 0;
1761
1762 c = tgetch(&modifiers, &ch2);
1763
1764 if (typebuf_changed(tb_change_cnt))
1765 {
1766 /* "buf" may be invalid now if a client put something in the
1767 * typeahead buffer and "buf" is in the typeahead buffer. */
1768 typeaheadlen = 0;
1769 break;
1770 }
1771
1772 if (c == Ctrl_C && ctrl_c_interrupts)
1773 {
1774#if defined(FEAT_CLIENTSERVER)
1775 trash_input_buf();
1776#endif
1777 got_int = TRUE;
1778 }
1779
1780#ifdef FEAT_MOUSE
1781 if (g_nMouseClick == -1)
1782#endif
1783 {
1784 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001785 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001787#ifdef FEAT_MBYTE
1788 if (ch2 == NUL)
1789 {
1790 int i;
1791 char_u *p;
1792 WCHAR ch[2];
1793
1794 ch[0] = c;
1795 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1796 {
1797 ch[1] = tgetch(&modifiers, &ch2);
1798 n++;
1799 }
1800 p = utf16_to_enc(ch, &n);
1801 if (p != NULL)
1802 {
1803 for (i = 0; i < n; i++)
1804 typeahead[typeaheadlen + i] = p[i];
1805 vim_free(p);
1806 }
1807 }
1808 else
1809#endif
1810 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001811 if (ch2 != NUL)
1812 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001813 typeahead[typeaheadlen + n] = 3;
1814 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001815 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001817
Bram Moolenaar45500912014-07-09 20:51:07 +02001818 if (conv)
1819 {
1820 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001821
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001822 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001823 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001824 char_u *e = typeahead + TYPEAHEADLEN;
1825
1826 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001827 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001828 if (*p == K_NUL)
1829 {
1830 ++p;
1831 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1832 *p = 3;
1833 ++n;
1834 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001835 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001836 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001837 }
1838 }
1839
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 /* Use the ALT key to set the 8th bit of the character
1841 * when it's one byte, the 8th bit isn't set yet and not
1842 * using a double-byte encoding (would become a lead
1843 * byte). */
1844 if ((modifiers & MOD_MASK_ALT)
1845 && n == 1
1846 && (typeahead[typeaheadlen] & 0x80) == 0
1847#ifdef FEAT_MBYTE
1848 && !enc_dbcs
1849#endif
1850 )
1851 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001852#ifdef FEAT_MBYTE
1853 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1854 typeahead + typeaheadlen);
1855#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001856 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001857#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858 modifiers &= ~MOD_MASK_ALT;
1859 }
1860
1861 if (modifiers != 0)
1862 {
1863 /* Prepend modifiers to the character. */
1864 mch_memmove(typeahead + typeaheadlen + 3,
1865 typeahead + typeaheadlen, n);
1866 typeahead[typeaheadlen++] = K_SPECIAL;
1867 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1868 typeahead[typeaheadlen++] = modifiers;
1869 }
1870
1871 typeaheadlen += n;
1872
1873#ifdef MCH_WRITE_DUMP
1874 if (fdDump)
1875 fputc(c, fdDump);
1876#endif
1877 }
1878 }
1879 }
1880
1881#ifdef MCH_WRITE_DUMP
1882 if (fdDump)
1883 {
1884 fputs("]\n", fdDump);
1885 fflush(fdDump);
1886 }
1887#endif
1888
Bram Moolenaar071d4272004-06-13 20:20:40 +00001889theend:
1890 /* Move typeahead to "buf", as much as fits. */
1891 len = 0;
1892 while (len < maxlen && typeaheadlen > 0)
1893 {
1894 buf[len++] = typeahead[0];
1895 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1896 }
1897 return len;
1898
1899#else /* FEAT_GUI_W32 */
1900 return 0;
1901#endif /* FEAT_GUI_W32 */
1902}
1903
Bram Moolenaar82881492012-11-20 16:53:39 +01001904#ifndef PROTO
1905# ifndef __MINGW32__
1906# include <shellapi.h> /* required for FindExecutable() */
1907# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908#endif
1909
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001910/*
1911 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001912 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001913 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001915executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001917 char *dum;
1918 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001919 char *curpath, *newpath;
1920 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001922#ifdef FEAT_MBYTE
1923 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001925 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001926 WCHAR fnamew[_MAX_PATH];
1927 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001928 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001929
1930 if (p != NULL)
1931 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001932 wcurpath = _wgetenv(L"PATH");
1933 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1934 * sizeof(WCHAR));
1935 if (wnewpath == NULL)
1936 return FALSE;
1937 wcscpy(wnewpath, L".;");
1938 wcscat(wnewpath, wcurpath);
1939 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1940 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001941 vim_free(p);
1942 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1943 {
1944 if (n == 0)
1945 return FALSE;
1946 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1947 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001948 if (path != NULL)
1949 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001950 return TRUE;
1951 }
1952 /* Retry with non-wide function (for Windows 98). */
1953 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001955#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001956
1957 curpath = getenv("PATH");
1958 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1959 if (newpath == NULL)
1960 return FALSE;
1961 STRCPY(newpath, ".;");
1962 STRCAT(newpath, curpath);
1963 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1964 vim_free(newpath);
1965 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001966 return FALSE;
1967 if (mch_isdir(fname))
1968 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001969 if (path != NULL)
1970 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001971 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001972}
1973
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001974#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001975 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001976/*
1977 * Bad parameter handler.
1978 *
1979 * Certain MS CRT functions will intentionally crash when passed invalid
1980 * parameters to highlight possible security holes. Setting this function as
1981 * the bad parameter handler will prevent the crash.
1982 *
1983 * In debug builds the parameters contain CRT information that might help track
1984 * down the source of a problem, but in non-debug builds the arguments are all
1985 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1986 * worth allowing these to make debugging of issues easier.
1987 */
1988 static void
1989bad_param_handler(const wchar_t *expression,
1990 const wchar_t *function,
1991 const wchar_t *file,
1992 unsigned int line,
1993 uintptr_t pReserved)
1994{
1995}
1996
1997# define SET_INVALID_PARAM_HANDLER \
1998 ((void)_set_invalid_parameter_handler(bad_param_handler))
1999#else
2000# define SET_INVALID_PARAM_HANDLER
2001#endif
2002
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003#ifdef FEAT_GUI_W32
2004
2005/*
2006 * GUI version of mch_init().
2007 */
2008 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002009mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010{
2011#ifndef __MINGW32__
2012 extern int _fmode;
2013#endif
2014
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002015 /* Silently handle invalid parameters to CRT functions */
2016 SET_INVALID_PARAM_HANDLER;
2017
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018 /* Let critical errors result in a failure, not in a dialog box. Required
2019 * for the timestamp test to work on removed floppies. */
2020 SetErrorMode(SEM_FAILCRITICALERRORS);
2021
2022 _fmode = O_BINARY; /* we do our own CR-LF translation */
2023
2024 /* Specify window size. Is there a place to get the default from? */
2025 Rows = 25;
2026 Columns = 80;
2027
2028 /* Look for 'vimrun' */
2029 if (!gui_is_win32s())
2030 {
2031 char_u vimrun_location[_MAX_PATH + 4];
2032
2033 /* First try in same directory as gvim.exe */
2034 STRCPY(vimrun_location, exe_name);
2035 STRCPY(gettail(vimrun_location), "vimrun.exe");
2036 if (mch_getperm(vimrun_location) >= 0)
2037 {
2038 if (*skiptowhite(vimrun_location) != NUL)
2039 {
2040 /* Enclose path with white space in double quotes. */
2041 mch_memmove(vimrun_location + 1, vimrun_location,
2042 STRLEN(vimrun_location) + 1);
2043 *vimrun_location = '"';
2044 STRCPY(gettail(vimrun_location), "vimrun\" ");
2045 }
2046 else
2047 STRCPY(gettail(vimrun_location), "vimrun ");
2048
2049 vimrun_path = (char *)vim_strsave(vimrun_location);
2050 s_dont_use_vimrun = FALSE;
2051 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002052 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002053 s_dont_use_vimrun = FALSE;
2054
2055 /* Don't give the warning for a missing vimrun.exe right now, but only
2056 * when vimrun was supposed to be used. Don't bother people that do
2057 * not need vimrun.exe. */
2058 if (s_dont_use_vimrun)
2059 need_vimrun_warning = TRUE;
2060 }
2061
2062 /*
2063 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2064 * Otherwise the default "findstr /n" is used.
2065 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002066 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2068
2069#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002070 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071#endif
2072}
2073
2074
2075#else /* FEAT_GUI_W32 */
2076
2077#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2078#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2079
2080/*
2081 * ClearConsoleBuffer()
2082 * Description:
2083 * Clears the entire contents of the console screen buffer, using the
2084 * specified attribute.
2085 * Returns:
2086 * TRUE on success
2087 */
2088 static BOOL
2089ClearConsoleBuffer(WORD wAttribute)
2090{
2091 CONSOLE_SCREEN_BUFFER_INFO csbi;
2092 COORD coord;
2093 DWORD NumCells, dummy;
2094
2095 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2096 return FALSE;
2097
2098 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2099 coord.X = 0;
2100 coord.Y = 0;
2101 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2102 coord, &dummy))
2103 {
2104 return FALSE;
2105 }
2106 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2107 coord, &dummy))
2108 {
2109 return FALSE;
2110 }
2111
2112 return TRUE;
2113}
2114
2115/*
2116 * FitConsoleWindow()
2117 * Description:
2118 * Checks if the console window will fit within given buffer dimensions.
2119 * Also, if requested, will shrink the window to fit.
2120 * Returns:
2121 * TRUE on success
2122 */
2123 static BOOL
2124FitConsoleWindow(
2125 COORD dwBufferSize,
2126 BOOL WantAdjust)
2127{
2128 CONSOLE_SCREEN_BUFFER_INFO csbi;
2129 COORD dwWindowSize;
2130 BOOL NeedAdjust = FALSE;
2131
2132 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2133 {
2134 /*
2135 * A buffer resize will fail if the current console window does
2136 * not lie completely within that buffer. To avoid this, we might
2137 * have to move and possibly shrink the window.
2138 */
2139 if (csbi.srWindow.Right >= dwBufferSize.X)
2140 {
2141 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2142 if (dwWindowSize.X > dwBufferSize.X)
2143 dwWindowSize.X = dwBufferSize.X;
2144 csbi.srWindow.Right = dwBufferSize.X - 1;
2145 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2146 NeedAdjust = TRUE;
2147 }
2148 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2149 {
2150 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2151 if (dwWindowSize.Y > dwBufferSize.Y)
2152 dwWindowSize.Y = dwBufferSize.Y;
2153 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2154 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2155 NeedAdjust = TRUE;
2156 }
2157 if (NeedAdjust && WantAdjust)
2158 {
2159 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2160 return FALSE;
2161 }
2162 return TRUE;
2163 }
2164
2165 return FALSE;
2166}
2167
2168typedef struct ConsoleBufferStruct
2169{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002170 BOOL IsValid;
2171 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar61594242015-09-01 20:23:37 +02002172 HANDLE handle;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002173} ConsoleBuffer;
2174
2175/*
2176 * SaveConsoleBuffer()
2177 * Description:
2178 * Saves important information about the console buffer, including the
2179 * actual buffer contents. The saved information is suitable for later
2180 * restoration by RestoreConsoleBuffer().
2181 * Returns:
2182 * TRUE if all information was saved; FALSE otherwise
2183 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2184 */
2185 static BOOL
2186SaveConsoleBuffer(
2187 ConsoleBuffer *cb)
2188{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 if (cb == NULL)
2190 return FALSE;
2191
Bram Moolenaar61594242015-09-01 20:23:37 +02002192 if (!GetConsoleScreenBufferInfo(cb->handle, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002193 {
2194 cb->IsValid = FALSE;
2195 return FALSE;
2196 }
2197 cb->IsValid = TRUE;
2198
Bram Moolenaar61594242015-09-01 20:23:37 +02002199 return TRUE;
2200}
2201
2202/*
2203 * CopyOldConsoleBuffer()
2204 * Description:
2205 * Copies the old console buffer contents to the current console buffer.
2206 * This is used when 'restorescreen' is off.
2207 * Returns:
2208 * TRUE on success
2209 */
2210 static BOOL
2211CopyOldConsoleBuffer(
2212 ConsoleBuffer *cb,
2213 HANDLE hConOld)
2214{
2215 COORD BufferCoord;
2216 COORD BufferSize;
2217 PCHAR_INFO Buffer;
2218 DWORD NumCells;
2219 SMALL_RECT ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220
2221 /*
Bram Moolenaar61594242015-09-01 20:23:37 +02002222 * Before copying the buffer contents, clear the current buffer, and
2223 * restore the window information. Doing this now prevents old buffer
2224 * contents from "flashing" onto the screen.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002225 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002226 ClearConsoleBuffer(cb->Info.wAttributes);
2227
2228 /* We only need to copy the window area, not whole buffer. */
2229 BufferSize.X = cb->Info.srWindow.Right - cb->Info.srWindow.Left + 1;
2230 BufferSize.Y = cb->Info.srWindow.Bottom - cb->Info.srWindow.Top + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231 ReadRegion.Left = 0;
Bram Moolenaar61594242015-09-01 20:23:37 +02002232 ReadRegion.Right = BufferSize.X - 1;
2233 ReadRegion.Top = 0;
2234 ReadRegion.Bottom = BufferSize.Y - 1;
2235
2236 NumCells = BufferSize.X * BufferSize.Y;
2237 Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2238 if (Buffer == NULL)
2239 return FALSE;
2240
2241 BufferCoord.X = 0;
2242 BufferCoord.Y = 0;
2243
2244 if (!ReadConsoleOutputW(hConOld, /* output handle */
2245 Buffer, /* our buffer */
2246 BufferSize, /* dimensions of our buffer */
2247 BufferCoord, /* offset in our buffer */
2248 &ReadRegion)) /* region to save */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002249 {
Bram Moolenaar61594242015-09-01 20:23:37 +02002250 vim_free(Buffer);
2251 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002252 }
Bram Moolenaar61594242015-09-01 20:23:37 +02002253 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2254 Buffer, /* our buffer */
2255 BufferSize, /* dimensions of our buffer */
2256 BufferCoord, /* offset in our buffer */
2257 &ReadRegion)) /* region to restore */
2258 {
2259 vim_free(Buffer);
2260 return FALSE;
2261 }
2262 vim_free(Buffer);
2263 SetConsoleWindowInfo(g_hConOut, TRUE, &ReadRegion);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264
2265 return TRUE;
2266}
2267
2268/*
2269 * RestoreConsoleBuffer()
2270 * Description:
2271 * Restores important information about the console buffer, including the
2272 * actual buffer contents, if desired. The information to restore is in
2273 * the same format used by SaveConsoleBuffer().
2274 * Returns:
2275 * TRUE on success
2276 */
2277 static BOOL
2278RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002279 ConsoleBuffer *cb,
2280 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281{
Bram Moolenaar61594242015-09-01 20:23:37 +02002282 HANDLE hConOld;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002283
2284 if (cb == NULL || !cb->IsValid)
2285 return FALSE;
2286
Bram Moolenaar61594242015-09-01 20:23:37 +02002287 hConOld = g_hConOut;
2288 g_hConOut = cb->handle;
2289 if (!RestoreScreen && exiting)
2290 CopyOldConsoleBuffer(cb, hConOld);
2291 SetConsoleActiveScreenBuffer(g_hConOut);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292
2293 return TRUE;
2294}
2295
Bram Moolenaar071d4272004-06-13 20:20:40 +00002296static ConsoleBuffer g_cbNonTermcap = { 0 };
2297static ConsoleBuffer g_cbTermcap = { 0 };
2298
2299#ifdef FEAT_TITLE
2300#ifdef __BORLANDC__
2301typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2302#else
2303typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2304#endif
2305char g_szOrigTitle[256] = { 0 };
2306HWND g_hWnd = NULL; /* also used in os_mswin.c */
2307static HICON g_hOrigIconSmall = NULL;
2308static HICON g_hOrigIcon = NULL;
2309static HICON g_hVimIcon = NULL;
2310static BOOL g_fCanChangeIcon = FALSE;
2311
2312/* ICON* are not defined in VC++ 4.0 */
2313#ifndef ICON_SMALL
2314#define ICON_SMALL 0
2315#endif
2316#ifndef ICON_BIG
2317#define ICON_BIG 1
2318#endif
2319/*
2320 * GetConsoleIcon()
2321 * Description:
2322 * Attempts to retrieve the small icon and/or the big icon currently in
2323 * use by a given window.
2324 * Returns:
2325 * TRUE on success
2326 */
2327 static BOOL
2328GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002329 HWND hWnd,
2330 HICON *phIconSmall,
2331 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002332{
2333 if (hWnd == NULL)
2334 return FALSE;
2335
2336 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002337 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2338 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002340 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2341 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002342 return TRUE;
2343}
2344
2345/*
2346 * SetConsoleIcon()
2347 * Description:
2348 * Attempts to change the small icon and/or the big icon currently in
2349 * use by a given window.
2350 * Returns:
2351 * TRUE on success
2352 */
2353 static BOOL
2354SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002355 HWND hWnd,
2356 HICON hIconSmall,
2357 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002359 HICON hPrevIconSmall;
2360 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002361
2362 if (hWnd == NULL)
2363 return FALSE;
2364
2365 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002366 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2367 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002369 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2370 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371 return TRUE;
2372}
2373
2374/*
2375 * SaveConsoleTitleAndIcon()
2376 * Description:
2377 * Saves the current console window title in g_szOrigTitle, for later
2378 * restoration. Also, attempts to obtain a handle to the console window,
2379 * and use it to save the small and big icons currently in use by the
2380 * console window. This is not always possible on some versions of Windows;
2381 * nor is it possible when running Vim remotely using Telnet (since the
2382 * console window the user sees is owned by a remote process).
2383 */
2384 static void
2385SaveConsoleTitleAndIcon(void)
2386{
2387 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2388
2389 /* Save the original title. */
2390 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2391 return;
2392
2393 /*
2394 * Obtain a handle to the console window using GetConsoleWindow() from
2395 * KERNEL32.DLL; we need to handle in order to change the window icon.
2396 * This function only exists on NT-based Windows, starting with Windows
2397 * 2000. On older operating systems, we can't change the window icon
2398 * anyway.
2399 */
2400 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2401 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2402 "GetConsoleWindow")) != NULL)
2403 {
2404 g_hWnd = (*GetConsoleWindowProc)();
2405 }
2406 if (g_hWnd == NULL)
2407 return;
2408
2409 /* Save the original console window icon. */
2410 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2411 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2412 return;
2413
2414 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002415 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2416 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417 if (g_hVimIcon != NULL)
2418 g_fCanChangeIcon = TRUE;
2419}
2420#endif
2421
2422static int g_fWindInitCalled = FALSE;
2423static int g_fTermcapMode = FALSE;
2424static CONSOLE_CURSOR_INFO g_cci;
2425static DWORD g_cmodein = 0;
2426static DWORD g_cmodeout = 0;
2427
2428/*
2429 * non-GUI version of mch_init().
2430 */
2431 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002432mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434#ifndef __MINGW32__
2435 extern int _fmode;
2436#endif
2437
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002438 /* Silently handle invalid parameters to CRT functions */
2439 SET_INVALID_PARAM_HANDLER;
2440
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441 /* Let critical errors result in a failure, not in a dialog box. Required
2442 * for the timestamp test to work on removed floppies. */
2443 SetErrorMode(SEM_FAILCRITICALERRORS);
2444
2445 _fmode = O_BINARY; /* we do our own CR-LF translation */
2446 out_flush();
2447
2448 /* Obtain handles for the standard Console I/O devices */
2449 if (read_cmd_fd == 0)
2450 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2451 else
2452 create_conin();
2453 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
Bram Moolenaar61594242015-09-01 20:23:37 +02002454 g_cbNonTermcap.handle = g_hConOut;
2455 g_cbTermcap.handle = CreateConsoleScreenBuffer(
2456 GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
2457 NULL, CONSOLE_TEXTMODE_BUFFER, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458
Bram Moolenaar071d4272004-06-13 20:20:40 +00002459 /* Get current text attributes */
Bram Moolenaar61594242015-09-01 20:23:37 +02002460 SaveConsoleBuffer(&g_cbNonTermcap);
2461 g_attrCurrent = g_attrDefault = g_cbNonTermcap.Info.wAttributes;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462 if (cterm_normal_fg_color == 0)
2463 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2464 if (cterm_normal_bg_color == 0)
2465 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2466
2467 /* set termcap codes to current text attributes */
2468 update_tcap(g_attrCurrent);
2469
2470 GetConsoleCursorInfo(g_hConOut, &g_cci);
2471 GetConsoleMode(g_hConIn, &g_cmodein);
2472 GetConsoleMode(g_hConOut, &g_cmodeout);
2473
2474#ifdef FEAT_TITLE
2475 SaveConsoleTitleAndIcon();
2476 /*
2477 * Set both the small and big icons of the console window to Vim's icon.
2478 * Note that Vim presently only has one size of icon (32x32), but it
2479 * automatically gets scaled down to 16x16 when setting the small icon.
2480 */
2481 if (g_fCanChangeIcon)
2482 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2483#endif
2484
2485 ui_get_shellsize();
2486
2487#ifdef MCH_WRITE_DUMP
2488 fdDump = fopen("dump", "wt");
2489
2490 if (fdDump)
2491 {
2492 time_t t;
2493
2494 time(&t);
2495 fputs(ctime(&t), fdDump);
2496 fflush(fdDump);
2497 }
2498#endif
2499
2500 g_fWindInitCalled = TRUE;
2501
2502#ifdef FEAT_MOUSE
2503 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2504#endif
2505
2506#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002507 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002508#endif
2509
2510 /* This will be NULL on anything but NT 4.0 */
2511 s_pfnGetConsoleKeyboardLayoutName =
2512 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2513 "GetConsoleKeyboardLayoutNameA");
2514}
2515
2516/*
2517 * non-GUI version of mch_exit().
2518 * Shut down and exit with status `r'
2519 * Careful: mch_exit() may be called before mch_init()!
2520 */
2521 void
2522mch_exit(int r)
2523{
2524 stoptermcap();
2525
2526 if (g_fWindInitCalled)
2527 settmode(TMODE_COOK);
2528
2529 ml_close_all(TRUE); /* remove all memfiles */
2530
2531 if (g_fWindInitCalled)
2532 {
2533#ifdef FEAT_TITLE
2534 mch_restore_title(3);
2535 /*
2536 * Restore both the small and big icons of the console window to
2537 * what they were at startup. Don't do this when the window is
2538 * closed, Vim would hang here.
2539 */
2540 if (g_fCanChangeIcon && !g_fForceExit)
2541 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2542#endif
2543
2544#ifdef MCH_WRITE_DUMP
2545 if (fdDump)
2546 {
2547 time_t t;
2548
2549 time(&t);
2550 fputs(ctime(&t), fdDump);
2551 fclose(fdDump);
2552 }
2553 fdDump = NULL;
2554#endif
2555 }
2556
2557 SetConsoleCursorInfo(g_hConOut, &g_cci);
2558 SetConsoleMode(g_hConIn, g_cmodein);
2559 SetConsoleMode(g_hConOut, g_cmodeout);
2560
Bram Moolenaar61594242015-09-01 20:23:37 +02002561 CloseHandle(g_cbTermcap.handle);
2562
Bram Moolenaar071d4272004-06-13 20:20:40 +00002563#ifdef DYNAMIC_GETTEXT
2564 dyn_libintl_end();
2565#endif
2566
2567 exit(r);
2568}
2569#endif /* !FEAT_GUI_W32 */
2570
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571/*
2572 * Do we have an interactive window?
2573 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002574/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 int
2576mch_check_win(
2577 int argc,
2578 char **argv)
2579{
2580 get_exe_name();
2581
2582#ifdef FEAT_GUI_W32
2583 return OK; /* GUI always has a tty */
2584#else
2585 if (isatty(1))
2586 return OK;
2587 return FAIL;
2588#endif
2589}
2590
2591
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002592#ifdef FEAT_MBYTE
2593/*
2594 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2595 * if it already exists. When "len" is > 0, also expand short to long
2596 * filenames.
2597 * Return FAIL if wide functions are not available, OK otherwise.
2598 * NOTE: much of this is identical to fname_case(), keep in sync!
2599 */
2600 static int
2601fname_casew(
2602 WCHAR *name,
2603 int len)
2604{
2605 WCHAR szTrueName[_MAX_PATH + 2];
2606 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2607 WCHAR *ptrue, *ptruePrev;
2608 WCHAR *porig, *porigPrev;
2609 int flen;
2610 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002611 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002612 int c;
2613 int slen;
2614
2615 flen = (int)wcslen(name);
2616 if (flen > _MAX_PATH)
2617 return OK;
2618
2619 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2620
2621 /* Build the new name in szTrueName[] one component at a time. */
2622 porig = name;
2623 ptrue = szTrueName;
2624
2625 if (iswalpha(porig[0]) && porig[1] == L':')
2626 {
2627 /* copy leading drive letter */
2628 *ptrue++ = *porig++;
2629 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002630 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002631 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002632
2633 while (*porig != NUL)
2634 {
2635 /* copy \ characters */
2636 while (*porig == psepc)
2637 *ptrue++ = *porig++;
2638
2639 ptruePrev = ptrue;
2640 porigPrev = porig;
2641 while (*porig != NUL && *porig != psepc)
2642 {
2643 *ptrue++ = *porig++;
2644 }
2645 *ptrue = NUL;
2646
2647 /* To avoid a slow failure append "\*" when searching a directory,
2648 * server or network share. */
2649 wcscpy(szTrueNameTemp, szTrueName);
2650 slen = (int)wcslen(szTrueNameTemp);
2651 if (*porig == psepc && slen + 2 < _MAX_PATH)
2652 wcscpy(szTrueNameTemp + slen, L"\\*");
2653
2654 /* Skip "", "." and "..". */
2655 if (ptrue > ptruePrev
2656 && (ptruePrev[0] != L'.'
2657 || (ptruePrev[1] != NUL
2658 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2659 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2660 != INVALID_HANDLE_VALUE)
2661 {
2662 c = *porig;
2663 *porig = NUL;
2664
2665 /* Only use the match when it's the same name (ignoring case) or
2666 * expansion is allowed and there is a match with the short name
2667 * and there is enough room. */
2668 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2669 || (len > 0
2670 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2671 && (int)(ptruePrev - szTrueName)
2672 + (int)wcslen(fb.cFileName) < len)))
2673 {
2674 wcscpy(ptruePrev, fb.cFileName);
2675
2676 /* Look for exact match and prefer it if found. Must be a
2677 * long name, otherwise there would be only one match. */
2678 while (FindNextFileW(hFind, &fb))
2679 {
2680 if (*fb.cAlternateFileName != NUL
2681 && (wcscoll(porigPrev, fb.cFileName) == 0
2682 || (len > 0
2683 && (_wcsicoll(porigPrev,
2684 fb.cAlternateFileName) == 0
2685 && (int)(ptruePrev - szTrueName)
2686 + (int)wcslen(fb.cFileName) < len))))
2687 {
2688 wcscpy(ptruePrev, fb.cFileName);
2689 break;
2690 }
2691 }
2692 }
2693 FindClose(hFind);
2694 *porig = c;
2695 ptrue = ptruePrev + wcslen(ptruePrev);
2696 }
2697 else if (hFind == INVALID_HANDLE_VALUE
2698 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2699 return FAIL;
2700 }
2701
2702 wcscpy(name, szTrueName);
2703 return OK;
2704}
2705#endif
2706
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707/*
2708 * fname_case(): Set the case of the file name, if it already exists.
2709 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002710 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 */
2712 void
2713fname_case(
2714 char_u *name,
2715 int len)
2716{
2717 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002718 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 char *ptrue, *ptruePrev;
2720 char *porig, *porigPrev;
2721 int flen;
2722 WIN32_FIND_DATA fb;
2723 HANDLE hFind;
2724 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002725 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002726
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002727 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002728 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 return;
2730
2731 slash_adjust(name);
2732
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002733#ifdef FEAT_MBYTE
2734 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2735 {
2736 WCHAR *p = enc_to_utf16(name, NULL);
2737
2738 if (p != NULL)
2739 {
2740 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002741 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002742
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002743 wcsncpy(buf, p, _MAX_PATH);
2744 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002745 vim_free(p);
2746
2747 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2748 {
2749 q = utf16_to_enc(buf, NULL);
2750 if (q != NULL)
2751 {
2752 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2753 vim_free(q);
2754 return;
2755 }
2756 }
2757 }
2758 /* Retry with non-wide function (for Windows 98). */
2759 }
2760#endif
2761
2762 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2763 * So we should check this after calling wide function. */
2764 if (flen > _MAX_PATH)
2765 return;
2766
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767 /* Build the new name in szTrueName[] one component at a time. */
2768 porig = name;
2769 ptrue = szTrueName;
2770
2771 if (isalpha(porig[0]) && porig[1] == ':')
2772 {
2773 /* copy leading drive letter */
2774 *ptrue++ = *porig++;
2775 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002776 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002777 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778
2779 while (*porig != NUL)
2780 {
2781 /* copy \ characters */
2782 while (*porig == psepc)
2783 *ptrue++ = *porig++;
2784
2785 ptruePrev = ptrue;
2786 porigPrev = porig;
2787 while (*porig != NUL && *porig != psepc)
2788 {
2789#ifdef FEAT_MBYTE
2790 int l;
2791
2792 if (enc_dbcs)
2793 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002794 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795 while (--l >= 0)
2796 *ptrue++ = *porig++;
2797 }
2798 else
2799#endif
2800 *ptrue++ = *porig++;
2801 }
2802 *ptrue = NUL;
2803
Bram Moolenaar464c9252010-10-13 20:37:41 +02002804 /* To avoid a slow failure append "\*" when searching a directory,
2805 * server or network share. */
2806 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002807 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002808 if (*porig == psepc && slen + 2 < _MAX_PATH)
2809 STRCPY(szTrueNameTemp + slen, "\\*");
2810
Bram Moolenaar071d4272004-06-13 20:20:40 +00002811 /* Skip "", "." and "..". */
2812 if (ptrue > ptruePrev
2813 && (ptruePrev[0] != '.'
2814 || (ptruePrev[1] != NUL
2815 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002816 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817 != INVALID_HANDLE_VALUE)
2818 {
2819 c = *porig;
2820 *porig = NUL;
2821
2822 /* Only use the match when it's the same name (ignoring case) or
2823 * expansion is allowed and there is a match with the short name
2824 * and there is enough room. */
2825 if (_stricoll(porigPrev, fb.cFileName) == 0
2826 || (len > 0
2827 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2828 && (int)(ptruePrev - szTrueName)
2829 + (int)strlen(fb.cFileName) < len)))
2830 {
2831 STRCPY(ptruePrev, fb.cFileName);
2832
2833 /* Look for exact match and prefer it if found. Must be a
2834 * long name, otherwise there would be only one match. */
2835 while (FindNextFile(hFind, &fb))
2836 {
2837 if (*fb.cAlternateFileName != NUL
2838 && (strcoll(porigPrev, fb.cFileName) == 0
2839 || (len > 0
2840 && (_stricoll(porigPrev,
2841 fb.cAlternateFileName) == 0
2842 && (int)(ptruePrev - szTrueName)
2843 + (int)strlen(fb.cFileName) < len))))
2844 {
2845 STRCPY(ptruePrev, fb.cFileName);
2846 break;
2847 }
2848 }
2849 }
2850 FindClose(hFind);
2851 *porig = c;
2852 ptrue = ptruePrev + strlen(ptruePrev);
2853 }
2854 }
2855
2856 STRCPY(name, szTrueName);
2857}
2858
2859
2860/*
2861 * Insert user name in s[len].
2862 */
2863 int
2864mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002865 char_u *s,
2866 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002868 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869 DWORD cch = sizeof szUserName;
2870
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002871#ifdef FEAT_MBYTE
2872 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2873 {
2874 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2875 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2876
2877 if (GetUserNameW(wszUserName, &wcch))
2878 {
2879 char_u *p = utf16_to_enc(wszUserName, NULL);
2880
2881 if (p != NULL)
2882 {
2883 vim_strncpy(s, p, len - 1);
2884 vim_free(p);
2885 return OK;
2886 }
2887 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002888 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2889 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002890 /* Retry with non-wide function (for Windows 98). */
2891 }
2892#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893 if (GetUserName(szUserName, &cch))
2894 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002895 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 return OK;
2897 }
2898 s[0] = NUL;
2899 return FAIL;
2900}
2901
2902
2903/*
2904 * Insert host name in s[len].
2905 */
2906 void
2907mch_get_host_name(
2908 char_u *s,
2909 int len)
2910{
2911 DWORD cch = len;
2912
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002913#ifdef FEAT_MBYTE
2914 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2915 {
2916 WCHAR wszHostName[256 + 1];
2917 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2918
2919 if (GetComputerNameW(wszHostName, &wcch))
2920 {
2921 char_u *p = utf16_to_enc(wszHostName, NULL);
2922
2923 if (p != NULL)
2924 {
2925 vim_strncpy(s, p, len - 1);
2926 vim_free(p);
2927 return;
2928 }
2929 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002930 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2931 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002932 /* Retry with non-wide function (for Windows 98). */
2933 }
2934#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002935 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002936 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937}
2938
2939
2940/*
2941 * return process ID
2942 */
2943 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002944mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945{
2946 return (long)GetCurrentProcessId();
2947}
2948
2949
2950/*
2951 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2952 * Return OK for success, FAIL for failure.
2953 */
2954 int
2955mch_dirname(
2956 char_u *buf,
2957 int len)
2958{
2959 /*
2960 * Originally this was:
2961 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2962 * But the Win32s known bug list says that getcwd() doesn't work
2963 * so use the Win32 system call instead. <Negri>
2964 */
2965#ifdef FEAT_MBYTE
2966 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2967 {
2968 WCHAR wbuf[_MAX_PATH + 1];
2969
2970 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2971 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002972 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973
2974 if (p != NULL)
2975 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002976 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002977 vim_free(p);
2978 return OK;
2979 }
2980 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002981 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2982 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002983 /* Retry with non-wide function (for Windows 98). */
2984 }
2985#endif
2986 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2987}
2988
2989/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002990 * Get file permissions for "name".
2991 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992 */
2993 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002994mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002996 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002997 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002999 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003000 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003001}
3002
3003
3004/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003005 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003006 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003007 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003008 */
3009 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003010mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003012 long n = -1;
3013
Bram Moolenaar071d4272004-06-13 20:20:40 +00003014#ifdef FEAT_MBYTE
3015 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3016 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003017 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003018
3019 if (p != NULL)
3020 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003021 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003022 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003023 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003024 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 /* Retry with non-wide function (for Windows 98). */
3026 }
3027 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003028 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003029#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003030 n = _chmod(name, perm);
3031 if (n == -1)
3032 return FAIL;
3033
3034 win32_set_archive(name);
3035
3036 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037}
3038
3039/*
3040 * Set hidden flag for "name".
3041 */
3042 void
3043mch_hide(char_u *name)
3044{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003045 int attrs = win32_getattrs(name);
3046 if (attrs == -1)
3047 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003049 attrs |= FILE_ATTRIBUTE_HIDDEN;
3050 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051}
3052
3053/*
3054 * return TRUE if "name" is a directory
3055 * return FALSE if "name" is not a directory or upon error
3056 */
3057 int
3058mch_isdir(char_u *name)
3059{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003060 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003061
3062 if (f == -1)
3063 return FALSE; /* file does not exist at all */
3064
3065 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3066}
3067
3068/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003069 * Create directory "name".
3070 * Return 0 on success, -1 on error.
3071 */
3072 int
3073mch_mkdir(char_u *name)
3074{
3075#ifdef FEAT_MBYTE
3076 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3077 {
3078 WCHAR *p;
3079 int retval;
3080
3081 p = enc_to_utf16(name, NULL);
3082 if (p == NULL)
3083 return -1;
3084 retval = _wmkdir(p);
3085 vim_free(p);
3086 return retval;
3087 }
3088#endif
3089 return _mkdir(name);
3090}
3091
3092/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003093 * Return TRUE if file "fname" has more than one link.
3094 */
3095 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003096mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003097{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003098 BY_HANDLE_FILE_INFORMATION info;
3099
3100 return win32_fileinfo(fname, &info) == FILEINFO_OK
3101 && info.nNumberOfLinks > 1;
3102}
3103
3104/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003105 * Return TRUE if file "fname" is a symbolic link.
3106 */
3107 int
3108mch_is_symbolic_link(char_u *fname)
3109{
3110 HANDLE hFind;
3111 int res = FALSE;
3112 WIN32_FIND_DATAA findDataA;
3113 DWORD fileFlags = 0, reparseTag = 0;
3114#ifdef FEAT_MBYTE
3115 WCHAR *wn = NULL;
3116 WIN32_FIND_DATAW findDataW;
3117
3118 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3119 wn = enc_to_utf16(fname, NULL);
3120 if (wn != NULL)
3121 {
3122 hFind = FindFirstFileW(wn, &findDataW);
3123 vim_free(wn);
3124 if (hFind == INVALID_HANDLE_VALUE
3125 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3126 {
3127 /* Retry with non-wide function (for Windows 98). */
3128 hFind = FindFirstFile(fname, &findDataA);
3129 if (hFind != INVALID_HANDLE_VALUE)
3130 {
3131 fileFlags = findDataA.dwFileAttributes;
3132 reparseTag = findDataA.dwReserved0;
3133 }
3134 }
3135 else
3136 {
3137 fileFlags = findDataW.dwFileAttributes;
3138 reparseTag = findDataW.dwReserved0;
3139 }
3140 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003141 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003142#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003143 {
3144 hFind = FindFirstFile(fname, &findDataA);
3145 if (hFind != INVALID_HANDLE_VALUE)
3146 {
3147 fileFlags = findDataA.dwFileAttributes;
3148 reparseTag = findDataA.dwReserved0;
3149 }
3150 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003151
3152 if (hFind != INVALID_HANDLE_VALUE)
3153 FindClose(hFind);
3154
3155 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3156 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3157 res = TRUE;
3158
3159 return res;
3160}
3161
3162/*
3163 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3164 * link.
3165 */
3166 int
3167mch_is_linked(char_u *fname)
3168{
3169 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3170 return TRUE;
3171 return FALSE;
3172}
3173
3174/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003175 * Get the by-handle-file-information for "fname".
3176 * Returns FILEINFO_OK when OK.
3177 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3178 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3179 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3180 */
3181 int
3182win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3183{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003184 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003185 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003186#ifdef FEAT_MBYTE
3187 WCHAR *wn = NULL;
3188
3189 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003190 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003191 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003192 if (wn == NULL)
3193 res = FILEINFO_ENC_FAIL;
3194 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003195 if (wn != NULL)
3196 {
3197 hFile = CreateFileW(wn, /* file name */
3198 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003199 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003200 NULL, /* security descriptor */
3201 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003202 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003203 NULL); /* handle to template file */
3204 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003205 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003206 {
3207 /* Retry with non-wide function (for Windows 98). */
3208 vim_free(wn);
3209 wn = NULL;
3210 }
3211 }
3212 if (wn == NULL)
3213#endif
3214 hFile = CreateFile(fname, /* file name */
3215 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003216 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003217 NULL, /* security descriptor */
3218 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003219 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003220 NULL); /* handle to template file */
3221
3222 if (hFile != INVALID_HANDLE_VALUE)
3223 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003224 if (GetFileInformationByHandle(hFile, info) != 0)
3225 res = FILEINFO_OK;
3226 else
3227 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003228 CloseHandle(hFile);
3229 }
3230
3231#ifdef FEAT_MBYTE
3232 vim_free(wn);
3233#endif
3234 return res;
3235}
3236
3237/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003238 * get file attributes for `name'
3239 * -1 : error
3240 * else FILE_ATTRIBUTE_* defined in winnt.h
3241 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003242 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003243win32_getattrs(char_u *name)
3244{
3245 int attr;
3246#ifdef FEAT_MBYTE
3247 WCHAR *p = NULL;
3248
3249 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3250 p = enc_to_utf16(name, NULL);
3251
3252 if (p != NULL)
3253 {
3254 attr = GetFileAttributesW(p);
3255 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3256 {
3257 /* Retry with non-wide function (for Windows 98). */
3258 vim_free(p);
3259 p = NULL;
3260 }
3261 }
3262 if (p == NULL)
3263#endif
3264 attr = GetFileAttributes((char *)name);
3265#ifdef FEAT_MBYTE
3266 vim_free(p);
3267#endif
3268 return attr;
3269}
3270
3271/*
3272 * set file attributes for `name' to `attrs'
3273 *
3274 * return -1 for failure, 0 otherwise
3275 */
3276 static
3277 int
3278win32_setattrs(char_u *name, int attrs)
3279{
3280 int res;
3281#ifdef FEAT_MBYTE
3282 WCHAR *p = NULL;
3283
3284 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3285 p = enc_to_utf16(name, NULL);
3286
3287 if (p != NULL)
3288 {
3289 res = SetFileAttributesW(p, attrs);
3290 if (res == FALSE
3291 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3292 {
3293 /* Retry with non-wide function (for Windows 98). */
3294 vim_free(p);
3295 p = NULL;
3296 }
3297 }
3298 if (p == NULL)
3299#endif
3300 res = SetFileAttributes((char *)name, attrs);
3301#ifdef FEAT_MBYTE
3302 vim_free(p);
3303#endif
3304 return res ? 0 : -1;
3305}
3306
3307/*
3308 * Set archive flag for "name".
3309 */
3310 static
3311 int
3312win32_set_archive(char_u *name)
3313{
3314 int attrs = win32_getattrs(name);
3315 if (attrs == -1)
3316 return -1;
3317
3318 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3319 return win32_setattrs(name, attrs);
3320}
3321
3322/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003323 * Return TRUE if file or directory "name" is writable (not readonly).
3324 * Strange semantics of Win32: a readonly directory is writable, but you can't
3325 * delete a file. Let's say this means it is writable.
3326 */
3327 int
3328mch_writable(char_u *name)
3329{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003330 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003331
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003332 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3333 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003334}
3335
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336/*
3337 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003338 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339 * Return -1 if unknown.
3340 */
3341 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003342mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003344 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003345 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003346 char_u *p;
3347
3348 if (len >= _MAX_PATH) /* safety check */
3349 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003350 if (!use_path)
3351 {
3352 /* TODO: check if file is really executable. */
3353 return mch_getperm(name) != -1 && !mch_isdir(name);
3354 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003355
3356 /* If there already is an extension try using the name directly. Also do
3357 * this with a Unix-shell like 'shell'. */
3358 if (vim_strchr(gettail(name), '.') != NULL
3359 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003360 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003361 return TRUE;
3362
3363 /*
3364 * Loop over all extensions in $PATHEXT.
3365 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003366 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003367 p = mch_getenv("PATHEXT");
3368 if (p == NULL)
3369 p = (char_u *)".com;.exe;.bat;.cmd";
3370 while (*p)
3371 {
3372 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3373 {
3374 /* A single "." means no extension is added. */
3375 buf[len] = NUL;
3376 ++p;
3377 if (*p)
3378 ++p;
3379 }
3380 else
3381 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003382 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003383 return TRUE;
3384 }
3385 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003387
3388/*
3389 * Check what "name" is:
3390 * NODE_NORMAL: file or directory (or doesn't exist)
3391 * NODE_WRITABLE: writable device, socket, fifo, etc.
3392 * NODE_OTHER: non-writable things
3393 */
3394 int
3395mch_nodetype(char_u *name)
3396{
3397 HANDLE hFile;
3398 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003399#ifdef FEAT_MBYTE
3400 WCHAR *wn = NULL;
3401#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003402
Bram Moolenaar043545e2006-10-10 16:44:07 +00003403 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3404 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3405 * here. */
3406 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3407 return NODE_WRITABLE;
3408
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003409#ifdef FEAT_MBYTE
3410 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3411 {
3412 wn = enc_to_utf16(name, NULL);
3413 if (wn != NULL)
3414 {
3415 hFile = CreateFileW(wn, /* file name */
3416 GENERIC_WRITE, /* access mode */
3417 0, /* share mode */
3418 NULL, /* security descriptor */
3419 OPEN_EXISTING, /* creation disposition */
3420 0, /* file attributes */
3421 NULL); /* handle to template file */
3422 if (hFile == INVALID_HANDLE_VALUE
3423 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3424 {
3425 /* Retry with non-wide function (for Windows 98). */
3426 vim_free(wn);
3427 wn = NULL;
3428 }
3429 }
3430 }
3431 if (wn == NULL)
3432#endif
3433 hFile = CreateFile(name, /* file name */
3434 GENERIC_WRITE, /* access mode */
3435 0, /* share mode */
3436 NULL, /* security descriptor */
3437 OPEN_EXISTING, /* creation disposition */
3438 0, /* file attributes */
3439 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003440
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003441#ifdef FEAT_MBYTE
3442 vim_free(wn);
3443#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444 if (hFile == INVALID_HANDLE_VALUE)
3445 return NODE_NORMAL;
3446
3447 type = GetFileType(hFile);
3448 CloseHandle(hFile);
3449 if (type == FILE_TYPE_CHAR)
3450 return NODE_WRITABLE;
3451 if (type == FILE_TYPE_DISK)
3452 return NODE_NORMAL;
3453 return NODE_OTHER;
3454}
3455
3456#ifdef HAVE_ACL
3457struct my_acl
3458{
3459 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3460 PSID pSidOwner;
3461 PSID pSidGroup;
3462 PACL pDacl;
3463 PACL pSacl;
3464};
3465#endif
3466
3467/*
3468 * Return a pointer to the ACL of file "fname" in allocated memory.
3469 * Return NULL if the ACL is not available for whatever reason.
3470 */
3471 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003472mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003473{
3474#ifndef HAVE_ACL
3475 return (vim_acl_T)NULL;
3476#else
3477 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003478 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003479
3480 /* This only works on Windows NT and 2000. */
3481 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3482 {
3483 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3484 if (p != NULL)
3485 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003486# ifdef FEAT_MBYTE
3487 WCHAR *wn = NULL;
3488
3489 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3490 wn = enc_to_utf16(fname, NULL);
3491 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003493 /* Try to retrieve the entire security descriptor. */
3494 err = pGetNamedSecurityInfoW(
3495 wn, // Abstract filename
3496 SE_FILE_OBJECT, // File Object
3497 OWNER_SECURITY_INFORMATION |
3498 GROUP_SECURITY_INFORMATION |
3499 DACL_SECURITY_INFORMATION |
3500 SACL_SECURITY_INFORMATION,
3501 &p->pSidOwner, // Ownership information.
3502 &p->pSidGroup, // Group membership.
3503 &p->pDacl, // Discretionary information.
3504 &p->pSacl, // For auditing purposes.
3505 &p->pSecurityDescriptor);
3506 if (err == ERROR_ACCESS_DENIED ||
3507 err == ERROR_PRIVILEGE_NOT_HELD)
3508 {
3509 /* Retrieve only DACL. */
3510 (void)pGetNamedSecurityInfoW(
3511 wn,
3512 SE_FILE_OBJECT,
3513 DACL_SECURITY_INFORMATION,
3514 NULL,
3515 NULL,
3516 &p->pDacl,
3517 NULL,
3518 &p->pSecurityDescriptor);
3519 }
3520 if (p->pSecurityDescriptor == NULL)
3521 {
3522 mch_free_acl((vim_acl_T)p);
3523 p = NULL;
3524 }
3525 vim_free(wn);
3526 }
3527 else
3528# endif
3529 {
3530 /* Try to retrieve the entire security descriptor. */
3531 err = pGetNamedSecurityInfo(
3532 (LPSTR)fname, // Abstract filename
3533 SE_FILE_OBJECT, // File Object
3534 OWNER_SECURITY_INFORMATION |
3535 GROUP_SECURITY_INFORMATION |
3536 DACL_SECURITY_INFORMATION |
3537 SACL_SECURITY_INFORMATION,
3538 &p->pSidOwner, // Ownership information.
3539 &p->pSidGroup, // Group membership.
3540 &p->pDacl, // Discretionary information.
3541 &p->pSacl, // For auditing purposes.
3542 &p->pSecurityDescriptor);
3543 if (err == ERROR_ACCESS_DENIED ||
3544 err == ERROR_PRIVILEGE_NOT_HELD)
3545 {
3546 /* Retrieve only DACL. */
3547 (void)pGetNamedSecurityInfo(
3548 (LPSTR)fname,
3549 SE_FILE_OBJECT,
3550 DACL_SECURITY_INFORMATION,
3551 NULL,
3552 NULL,
3553 &p->pDacl,
3554 NULL,
3555 &p->pSecurityDescriptor);
3556 }
3557 if (p->pSecurityDescriptor == NULL)
3558 {
3559 mch_free_acl((vim_acl_T)p);
3560 p = NULL;
3561 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003562 }
3563 }
3564 }
3565
3566 return (vim_acl_T)p;
3567#endif
3568}
3569
Bram Moolenaar27515922013-06-29 15:36:26 +02003570#ifdef HAVE_ACL
3571/*
3572 * Check if "acl" contains inherited ACE.
3573 */
3574 static BOOL
3575is_acl_inherited(PACL acl)
3576{
3577 DWORD i;
3578 ACL_SIZE_INFORMATION acl_info;
3579 PACCESS_ALLOWED_ACE ace;
3580
3581 acl_info.AceCount = 0;
3582 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3583 for (i = 0; i < acl_info.AceCount; i++)
3584 {
3585 GetAce(acl, i, (LPVOID *)&ace);
3586 if (ace->Header.AceFlags & INHERITED_ACE)
3587 return TRUE;
3588 }
3589 return FALSE;
3590}
3591#endif
3592
Bram Moolenaar071d4272004-06-13 20:20:40 +00003593/*
3594 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3595 * Errors are ignored.
3596 * This must only be called with "acl" equal to what mch_get_acl() returned.
3597 */
3598 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003599mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600{
3601#ifdef HAVE_ACL
3602 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003603 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604
3605 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003606 {
3607# ifdef FEAT_MBYTE
3608 WCHAR *wn = NULL;
3609# endif
3610
3611 /* Set security flags */
3612 if (p->pSidOwner)
3613 sec_info |= OWNER_SECURITY_INFORMATION;
3614 if (p->pSidGroup)
3615 sec_info |= GROUP_SECURITY_INFORMATION;
3616 if (p->pDacl)
3617 {
3618 sec_info |= DACL_SECURITY_INFORMATION;
3619 /* Do not inherit its parent's DACL.
3620 * If the DACL is inherited, Cygwin permissions would be changed.
3621 */
3622 if (!is_acl_inherited(p->pDacl))
3623 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3624 }
3625 if (p->pSacl)
3626 sec_info |= SACL_SECURITY_INFORMATION;
3627
3628# ifdef FEAT_MBYTE
3629 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3630 wn = enc_to_utf16(fname, NULL);
3631 if (wn != NULL)
3632 {
3633 (void)pSetNamedSecurityInfoW(
3634 wn, // Abstract filename
3635 SE_FILE_OBJECT, // File Object
3636 sec_info,
3637 p->pSidOwner, // Ownership information.
3638 p->pSidGroup, // Group membership.
3639 p->pDacl, // Discretionary information.
3640 p->pSacl // For auditing purposes.
3641 );
3642 vim_free(wn);
3643 }
3644 else
3645# endif
3646 {
3647 (void)pSetNamedSecurityInfo(
3648 (LPSTR)fname, // Abstract filename
3649 SE_FILE_OBJECT, // File Object
3650 sec_info,
3651 p->pSidOwner, // Ownership information.
3652 p->pSidGroup, // Group membership.
3653 p->pDacl, // Discretionary information.
3654 p->pSacl // For auditing purposes.
3655 );
3656 }
3657 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658#endif
3659}
3660
3661 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003662mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663{
3664#ifdef HAVE_ACL
3665 struct my_acl *p = (struct my_acl *)acl;
3666
3667 if (p != NULL)
3668 {
3669 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3670 vim_free(p);
3671 }
3672#endif
3673}
3674
3675#ifndef FEAT_GUI_W32
3676
3677/*
3678 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3679 */
3680 static BOOL WINAPI
3681handler_routine(
3682 DWORD dwCtrlType)
3683{
3684 switch (dwCtrlType)
3685 {
3686 case CTRL_C_EVENT:
3687 if (ctrl_c_interrupts)
3688 g_fCtrlCPressed = TRUE;
3689 return TRUE;
3690
3691 case CTRL_BREAK_EVENT:
3692 g_fCBrkPressed = TRUE;
3693 return TRUE;
3694
3695 /* fatal events: shut down gracefully */
3696 case CTRL_CLOSE_EVENT:
3697 case CTRL_LOGOFF_EVENT:
3698 case CTRL_SHUTDOWN_EVENT:
3699 windgoto((int)Rows - 1, 0);
3700 g_fForceExit = TRUE;
3701
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003702 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003703 (dwCtrlType == CTRL_CLOSE_EVENT
3704 ? _("close")
3705 : dwCtrlType == CTRL_LOGOFF_EVENT
3706 ? _("logoff")
3707 : _("shutdown")));
3708#ifdef DEBUG
3709 OutputDebugString(IObuff);
3710#endif
3711
3712 preserve_exit(); /* output IObuff, preserve files and exit */
3713
3714 return TRUE; /* not reached */
3715
3716 default:
3717 return FALSE;
3718 }
3719}
3720
3721
3722/*
3723 * set the tty in (raw) ? "raw" : "cooked" mode
3724 */
3725 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003726mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727{
3728 DWORD cmodein;
3729 DWORD cmodeout;
3730 BOOL bEnableHandler;
3731
3732 GetConsoleMode(g_hConIn, &cmodein);
3733 GetConsoleMode(g_hConOut, &cmodeout);
3734 if (tmode == TMODE_RAW)
3735 {
3736 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3737 ENABLE_ECHO_INPUT);
3738#ifdef FEAT_MOUSE
3739 if (g_fMouseActive)
3740 cmodein |= ENABLE_MOUSE_INPUT;
3741#endif
3742 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3743 bEnableHandler = TRUE;
3744 }
3745 else /* cooked */
3746 {
3747 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3748 ENABLE_ECHO_INPUT);
3749 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3750 bEnableHandler = FALSE;
3751 }
3752 SetConsoleMode(g_hConIn, cmodein);
3753 SetConsoleMode(g_hConOut, cmodeout);
3754 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3755
3756#ifdef MCH_WRITE_DUMP
3757 if (fdDump)
3758 {
3759 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3760 tmode == TMODE_RAW ? "raw" :
3761 tmode == TMODE_COOK ? "cooked" : "normal",
3762 cmodein, cmodeout);
3763 fflush(fdDump);
3764 }
3765#endif
3766}
3767
3768
3769/*
3770 * Get the size of the current window in `Rows' and `Columns'
3771 * Return OK when size could be determined, FAIL otherwise.
3772 */
3773 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003774mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775{
3776 CONSOLE_SCREEN_BUFFER_INFO csbi;
3777
3778 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3779 {
3780 /*
3781 * For some reason, we are trying to get the screen dimensions
3782 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3783 * variables are really intended to mean the size of Vim screen
3784 * while in termcap mode.
3785 */
3786 Rows = g_cbTermcap.Info.dwSize.Y;
3787 Columns = g_cbTermcap.Info.dwSize.X;
3788 }
3789 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3790 {
3791 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3792 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3793 }
3794 else
3795 {
3796 Rows = 25;
3797 Columns = 80;
3798 }
3799 return OK;
3800}
3801
3802/*
3803 * Set a console window to `xSize' * `ySize'
3804 */
3805 static void
3806ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003807 HANDLE hConsole,
3808 int xSize,
3809 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003810{
3811 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3812 SMALL_RECT srWindowRect; /* hold the new console size */
3813 COORD coordScreen;
3814
3815#ifdef MCH_WRITE_DUMP
3816 if (fdDump)
3817 {
3818 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3819 fflush(fdDump);
3820 }
3821#endif
3822
3823 /* get the largest size we can size the console window to */
3824 coordScreen = GetLargestConsoleWindowSize(hConsole);
3825
3826 /* define the new console window size and scroll position */
3827 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3828 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3829 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3830
3831 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3832 {
3833 int sx, sy;
3834
3835 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3836 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3837 if (sy < ySize || sx < xSize)
3838 {
3839 /*
3840 * Increasing number of lines/columns, do buffer first.
3841 * Use the maximal size in x and y direction.
3842 */
3843 if (sy < ySize)
3844 coordScreen.Y = ySize;
3845 else
3846 coordScreen.Y = sy;
3847 if (sx < xSize)
3848 coordScreen.X = xSize;
3849 else
3850 coordScreen.X = sx;
3851 SetConsoleScreenBufferSize(hConsole, coordScreen);
3852 }
3853 }
3854
3855 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3856 {
3857#ifdef MCH_WRITE_DUMP
3858 if (fdDump)
3859 {
3860 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3861 GetLastError());
3862 fflush(fdDump);
3863 }
3864#endif
3865 }
3866
3867 /* define the new console buffer size */
3868 coordScreen.X = xSize;
3869 coordScreen.Y = ySize;
3870
3871 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3872 {
3873#ifdef MCH_WRITE_DUMP
3874 if (fdDump)
3875 {
3876 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3877 GetLastError());
3878 fflush(fdDump);
3879 }
3880#endif
3881 }
3882}
3883
3884
3885/*
3886 * Set the console window to `Rows' * `Columns'
3887 */
3888 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003889mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003890{
3891 COORD coordScreen;
3892
3893 /* Don't change window size while still starting up */
3894 if (suppress_winsize != 0)
3895 {
3896 suppress_winsize = 2;
3897 return;
3898 }
3899
3900 if (term_console)
3901 {
3902 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3903
3904 /* Clamp Rows and Columns to reasonable values */
3905 if (Rows > coordScreen.Y)
3906 Rows = coordScreen.Y;
3907 if (Columns > coordScreen.X)
3908 Columns = coordScreen.X;
3909
3910 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3911 }
3912}
3913
3914/*
3915 * Rows and/or Columns has changed.
3916 */
3917 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003918mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003919{
3920 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3921}
3922
3923
3924/*
3925 * Called when started up, to set the winsize that was delayed.
3926 */
3927 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003928mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003929{
3930 if (suppress_winsize == 2)
3931 {
3932 suppress_winsize = 0;
3933 mch_set_shellsize();
3934 shell_resized();
3935 }
3936 suppress_winsize = 0;
3937}
3938#endif /* FEAT_GUI_W32 */
3939
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003940 static BOOL
3941vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003942 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003943 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003944 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003945 STARTUPINFO *si,
3946 PROCESS_INFORMATION *pi)
3947{
3948# ifdef FEAT_MBYTE
3949 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3950 {
3951 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
3952
3953 if (wcmd != NULL)
3954 {
3955 BOOL ret;
3956 ret = CreateProcessW(
3957 NULL, /* Executable name */
3958 wcmd, /* Command to execute */
3959 NULL, /* Process security attributes */
3960 NULL, /* Thread security attributes */
3961 inherit_handles, /* Inherit handles */
3962 flags, /* Creation flags */
3963 NULL, /* Environment */
3964 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003965 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003966 pi); /* Process information */
3967 vim_free(wcmd);
3968 return ret;
3969 }
3970 }
3971#endif
3972 return CreateProcess(
3973 NULL, /* Executable name */
3974 cmd, /* Command to execute */
3975 NULL, /* Process security attributes */
3976 NULL, /* Thread security attributes */
3977 inherit_handles, /* Inherit handles */
3978 flags, /* Creation flags */
3979 NULL, /* Environment */
3980 NULL, /* Current directory */
3981 si, /* Startup information */
3982 pi); /* Process information */
3983}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984
3985
3986#if defined(FEAT_GUI_W32) || defined(PROTO)
3987
3988/*
3989 * Specialised version of system() for Win32 GUI mode.
3990 * This version proceeds as follows:
3991 * 1. Create a console window for use by the subprocess
3992 * 2. Run the subprocess (it gets the allocated console by default)
3993 * 3. Wait for the subprocess to terminate and get its exit code
3994 * 4. Prompt the user to press a key to close the console window
3995 */
3996 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003997mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003998{
3999 STARTUPINFO si;
4000 PROCESS_INFORMATION pi;
4001 DWORD ret = 0;
4002 HWND hwnd = GetFocus();
4003
4004 si.cb = sizeof(si);
4005 si.lpReserved = NULL;
4006 si.lpDesktop = NULL;
4007 si.lpTitle = NULL;
4008 si.dwFlags = STARTF_USESHOWWINDOW;
4009 /*
4010 * It's nicer to run a filter command in a minimized window, but in
4011 * Windows 95 this makes the command MUCH slower. We can't do it under
4012 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004013 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004014 */
4015 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004016 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017 else
4018 si.wShowWindow = SW_SHOWNORMAL;
4019 si.cbReserved2 = 0;
4020 si.lpReserved2 = NULL;
4021
4022 /* There is a strange error on Windows 95 when using "c:\\command.com".
4023 * When the "c:\\" is left out it works OK...? */
4024 if (mch_windows95()
4025 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4026 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4027 cmd += 3;
4028
4029 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004030 vim_create_process(cmd, FALSE,
4031 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032
4033 /* Wait for the command to terminate before continuing */
4034 if (g_PlatformId != VER_PLATFORM_WIN32s)
4035 {
4036#ifdef FEAT_GUI
4037 int delay = 1;
4038
4039 /* Keep updating the window while waiting for the shell to finish. */
4040 for (;;)
4041 {
4042 MSG msg;
4043
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004044 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004045 {
4046 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004047 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004048 delay = 1;
4049 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004050 }
4051 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4052 break;
4053
4054 /* We start waiting for a very short time and then increase it, so
4055 * that we respond quickly when the process is quick, and don't
4056 * consume too much overhead when it's slow. */
4057 if (delay < 50)
4058 delay += 10;
4059 }
4060#else
4061 WaitForSingleObject(pi.hProcess, INFINITE);
4062#endif
4063
4064 /* Get the command exit code */
4065 GetExitCodeProcess(pi.hProcess, &ret);
4066 }
4067 else
4068 {
4069 /*
4070 * This ugly code is the only quick way of performing
4071 * a synchronous spawn under Win32s. Yuk.
4072 */
4073 num_windows = 0;
4074 EnumWindows(win32ssynch_cb, 0);
4075 old_num_windows = num_windows;
4076 do
4077 {
4078 Sleep(1000);
4079 num_windows = 0;
4080 EnumWindows(win32ssynch_cb, 0);
4081 } while (num_windows == old_num_windows);
4082 ret = 0;
4083 }
4084
4085 /* Close the handles to the subprocess, so that it goes away */
4086 CloseHandle(pi.hThread);
4087 CloseHandle(pi.hProcess);
4088
4089 /* Try to get input focus back. Doesn't always work though. */
4090 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4091
4092 return ret;
4093}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004094
4095/*
4096 * Thread launched by the gui to send the current buffer data to the
4097 * process. This way avoid to hang up vim totally if the children
4098 * process take a long time to process the lines.
4099 */
4100 static DWORD WINAPI
4101sub_process_writer(LPVOID param)
4102{
4103 HANDLE g_hChildStd_IN_Wr = param;
4104 linenr_T lnum = curbuf->b_op_start.lnum;
4105 DWORD len = 0;
4106 DWORD l;
4107 char_u *lp = ml_get(lnum);
4108 char_u *s;
4109 int written = 0;
4110
4111 for (;;)
4112 {
4113 l = (DWORD)STRLEN(lp + written);
4114 if (l == 0)
4115 len = 0;
4116 else if (lp[written] == NL)
4117 {
4118 /* NL -> NUL translation */
4119 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4120 }
4121 else
4122 {
4123 s = vim_strchr(lp + written, NL);
4124 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4125 s == NULL ? l : (DWORD)(s - (lp + written)),
4126 &len, NULL);
4127 }
4128 if (len == (int)l)
4129 {
4130 /* Finished a line, add a NL, unless this line should not have
4131 * one. */
4132 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004133 || (!curbuf->b_p_bin
4134 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004135 || (lnum != curbuf->b_no_eol_lnum
4136 && (lnum != curbuf->b_ml.ml_line_count
4137 || curbuf->b_p_eol)))
4138 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004139 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004140 }
4141
4142 ++lnum;
4143 if (lnum > curbuf->b_op_end.lnum)
4144 break;
4145
4146 lp = ml_get(lnum);
4147 written = 0;
4148 }
4149 else if (len > 0)
4150 written += len;
4151 }
4152
4153 /* finished all the lines, close pipe */
4154 CloseHandle(g_hChildStd_IN_Wr);
4155 ExitThread(0);
4156}
4157
4158
4159# define BUFLEN 100 /* length for buffer, stolen from unix version */
4160
4161/*
4162 * This function read from the children's stdout and write the
4163 * data on screen or in the buffer accordingly.
4164 */
4165 static void
4166dump_pipe(int options,
4167 HANDLE g_hChildStd_OUT_Rd,
4168 garray_T *ga,
4169 char_u buffer[],
4170 DWORD *buffer_off)
4171{
4172 DWORD availableBytes = 0;
4173 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004174 int ret;
4175 DWORD len;
4176 DWORD toRead;
4177 int repeatCount;
4178
4179 /* we query the pipe to see if there is any data to read
4180 * to avoid to perform a blocking read */
4181 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4182 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004183 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004184 NULL, /* number of read bytes */
4185 &availableBytes, /* available bytes total */
4186 NULL); /* byteLeft */
4187
4188 repeatCount = 0;
4189 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004190 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004191 {
4192 repeatCount++;
4193 toRead =
4194# ifdef FEAT_MBYTE
4195 (DWORD)(BUFLEN - *buffer_off);
4196# else
4197 (DWORD)BUFLEN;
4198# endif
4199 toRead = availableBytes < toRead ? availableBytes : toRead;
4200 ReadFile(g_hChildStd_OUT_Rd, buffer
4201# ifdef FEAT_MBYTE
4202 + *buffer_off, toRead
4203# else
4204 , toRead
4205# endif
4206 , &len, NULL);
4207
4208 /* If we haven't read anything, there is a problem */
4209 if (len == 0)
4210 break;
4211
4212 availableBytes -= len;
4213
4214 if (options & SHELL_READ)
4215 {
4216 /* Do NUL -> NL translation, append NL separated
4217 * lines to the current buffer. */
4218 for (i = 0; i < len; ++i)
4219 {
4220 if (buffer[i] == NL)
4221 append_ga_line(ga);
4222 else if (buffer[i] == NUL)
4223 ga_append(ga, NL);
4224 else
4225 ga_append(ga, buffer[i]);
4226 }
4227 }
4228# ifdef FEAT_MBYTE
4229 else if (has_mbyte)
4230 {
4231 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004232 int c;
4233 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004234
4235 len += *buffer_off;
4236 buffer[len] = NUL;
4237
4238 /* Check if the last character in buffer[] is
4239 * incomplete, keep these bytes for the next
4240 * round. */
4241 for (p = buffer; p < buffer + len; p += l)
4242 {
4243 l = mb_cptr2len(p);
4244 if (l == 0)
4245 l = 1; /* NUL byte? */
4246 else if (MB_BYTE2LEN(*p) != l)
4247 break;
4248 }
4249 if (p == buffer) /* no complete character */
4250 {
4251 /* avoid getting stuck at an illegal byte */
4252 if (len >= 12)
4253 ++p;
4254 else
4255 {
4256 *buffer_off = len;
4257 return;
4258 }
4259 }
4260 c = *p;
4261 *p = NUL;
4262 msg_puts(buffer);
4263 if (p < buffer + len)
4264 {
4265 *p = c;
4266 *buffer_off = (DWORD)((buffer + len) - p);
4267 mch_memmove(buffer, p, *buffer_off);
4268 return;
4269 }
4270 *buffer_off = 0;
4271 }
4272# endif /* FEAT_MBYTE */
4273 else
4274 {
4275 buffer[len] = NUL;
4276 msg_puts(buffer);
4277 }
4278
4279 windgoto(msg_row, msg_col);
4280 cursor_on();
4281 out_flush();
4282 }
4283}
4284
4285/*
4286 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4287 * for communication and doesn't open any new window.
4288 */
4289 static int
4290mch_system_piped(char *cmd, int options)
4291{
4292 STARTUPINFO si;
4293 PROCESS_INFORMATION pi;
4294 DWORD ret = 0;
4295
4296 HANDLE g_hChildStd_IN_Rd = NULL;
4297 HANDLE g_hChildStd_IN_Wr = NULL;
4298 HANDLE g_hChildStd_OUT_Rd = NULL;
4299 HANDLE g_hChildStd_OUT_Wr = NULL;
4300
4301 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4302 DWORD len;
4303
4304 /* buffer used to receive keys */
4305 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4306 int ta_len = 0; /* valid bytes in ta_buf[] */
4307
4308 DWORD i;
4309 int c;
4310 int noread_cnt = 0;
4311 garray_T ga;
4312 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004313 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004314 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004315
4316 SECURITY_ATTRIBUTES saAttr;
4317
4318 /* Set the bInheritHandle flag so pipe handles are inherited. */
4319 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4320 saAttr.bInheritHandle = TRUE;
4321 saAttr.lpSecurityDescriptor = NULL;
4322
4323 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4324 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4325 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4326 /* Create a pipe for the child process's STDIN. */
4327 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4328 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4329 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4330 {
4331 CloseHandle(g_hChildStd_IN_Rd);
4332 CloseHandle(g_hChildStd_IN_Wr);
4333 CloseHandle(g_hChildStd_OUT_Rd);
4334 CloseHandle(g_hChildStd_OUT_Wr);
4335 MSG_PUTS(_("\nCannot create pipes\n"));
4336 }
4337
4338 si.cb = sizeof(si);
4339 si.lpReserved = NULL;
4340 si.lpDesktop = NULL;
4341 si.lpTitle = NULL;
4342 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4343
4344 /* set-up our file redirection */
4345 si.hStdError = g_hChildStd_OUT_Wr;
4346 si.hStdOutput = g_hChildStd_OUT_Wr;
4347 si.hStdInput = g_hChildStd_IN_Rd;
4348 si.wShowWindow = SW_HIDE;
4349 si.cbReserved2 = 0;
4350 si.lpReserved2 = NULL;
4351
4352 if (options & SHELL_READ)
4353 ga_init2(&ga, 1, BUFLEN);
4354
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004355 if (cmd != NULL)
4356 {
4357 p = (char *)vim_strsave((char_u *)cmd);
4358 if (p != NULL)
4359 unescape_shellxquote((char_u *)p, p_sxe);
4360 else
4361 p = cmd;
4362 }
4363
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004364 /* Now, run the command.
4365 * About "Inherit handles" being TRUE: this command can be litigious,
4366 * handle inheritance was deactivated for pending temp file, but, if we
4367 * deactivate it, the pipes don't work for some reason. */
4368 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004369
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004370 if (p != cmd)
4371 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004372
4373 /* Close our unused side of the pipes */
4374 CloseHandle(g_hChildStd_IN_Rd);
4375 CloseHandle(g_hChildStd_OUT_Wr);
4376
4377 if (options & SHELL_WRITE)
4378 {
4379 HANDLE thread =
4380 CreateThread(NULL, /* security attributes */
4381 0, /* default stack size */
4382 sub_process_writer, /* function to be executed */
4383 g_hChildStd_IN_Wr, /* parameter */
4384 0, /* creation flag, start immediately */
4385 NULL); /* we don't care about thread id */
4386 CloseHandle(thread);
4387 g_hChildStd_IN_Wr = NULL;
4388 }
4389
4390 /* Keep updating the window while waiting for the shell to finish. */
4391 for (;;)
4392 {
4393 MSG msg;
4394
Bram Moolenaar175d0702013-12-11 18:36:33 +01004395 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004396 {
4397 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004398 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004399 }
4400
4401 /* write pipe information in the window */
4402 if ((options & (SHELL_READ|SHELL_WRITE))
4403# ifdef FEAT_GUI
4404 || gui.in_use
4405# endif
4406 )
4407 {
4408 len = 0;
4409 if (!(options & SHELL_EXPAND)
4410 && ((options &
4411 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4412 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4413# ifdef FEAT_GUI
4414 || gui.in_use
4415# endif
4416 )
4417 && (ta_len > 0 || noread_cnt > 4))
4418 {
4419 if (ta_len == 0)
4420 {
4421 /* Get extra characters when we don't have any. Reset the
4422 * counter and timer. */
4423 noread_cnt = 0;
4424# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4425 gettimeofday(&start_tv, NULL);
4426# endif
4427 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4428 }
4429 if (ta_len > 0 || len > 0)
4430 {
4431 /*
4432 * For pipes: Check for CTRL-C: send interrupt signal to
4433 * child. Check for CTRL-D: EOF, close pipe to child.
4434 */
4435 if (len == 1 && cmd != NULL)
4436 {
4437 if (ta_buf[ta_len] == Ctrl_C)
4438 {
4439 /* Learn what exit code is expected, for
4440 * now put 9 as SIGKILL */
4441 TerminateProcess(pi.hProcess, 9);
4442 }
4443 if (ta_buf[ta_len] == Ctrl_D)
4444 {
4445 CloseHandle(g_hChildStd_IN_Wr);
4446 g_hChildStd_IN_Wr = NULL;
4447 }
4448 }
4449
4450 /* replace K_BS by <BS> and K_DEL by <DEL> */
4451 for (i = ta_len; i < ta_len + len; ++i)
4452 {
4453 if (ta_buf[i] == CSI && len - i > 2)
4454 {
4455 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4456 if (c == K_DEL || c == K_KDEL || c == K_BS)
4457 {
4458 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4459 (size_t)(len - i - 2));
4460 if (c == K_DEL || c == K_KDEL)
4461 ta_buf[i] = DEL;
4462 else
4463 ta_buf[i] = Ctrl_H;
4464 len -= 2;
4465 }
4466 }
4467 else if (ta_buf[i] == '\r')
4468 ta_buf[i] = '\n';
4469# ifdef FEAT_MBYTE
4470 if (has_mbyte)
4471 i += (*mb_ptr2len_len)(ta_buf + i,
4472 ta_len + len - i) - 1;
4473# endif
4474 }
4475
4476 /*
4477 * For pipes: echo the typed characters. For a pty this
4478 * does not seem to work.
4479 */
4480 for (i = ta_len; i < ta_len + len; ++i)
4481 {
4482 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4483 msg_putchar(ta_buf[i]);
4484# ifdef FEAT_MBYTE
4485 else if (has_mbyte)
4486 {
4487 int l = (*mb_ptr2len)(ta_buf + i);
4488
4489 msg_outtrans_len(ta_buf + i, l);
4490 i += l - 1;
4491 }
4492# endif
4493 else
4494 msg_outtrans_len(ta_buf + i, 1);
4495 }
4496 windgoto(msg_row, msg_col);
4497 out_flush();
4498
4499 ta_len += len;
4500
4501 /*
4502 * Write the characters to the child, unless EOF has been
4503 * typed for pipes. Write one character at a time, to
4504 * avoid losing too much typeahead. When writing buffer
4505 * lines, drop the typed characters (only check for
4506 * CTRL-C).
4507 */
4508 if (options & SHELL_WRITE)
4509 ta_len = 0;
4510 else if (g_hChildStd_IN_Wr != NULL)
4511 {
4512 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4513 1, &len, NULL);
4514 // if we are typing in, we want to keep things reactive
4515 delay = 1;
4516 if (len > 0)
4517 {
4518 ta_len -= len;
4519 mch_memmove(ta_buf, ta_buf + len, ta_len);
4520 }
4521 }
4522 }
4523 }
4524 }
4525
4526 if (ta_len)
4527 ui_inchar_undo(ta_buf, ta_len);
4528
4529 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4530 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004531 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004532 break;
4533 }
4534
4535 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004536 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004537
4538 /* We start waiting for a very short time and then increase it, so
4539 * that we respond quickly when the process is quick, and don't
4540 * consume too much overhead when it's slow. */
4541 if (delay < 50)
4542 delay += 10;
4543 }
4544
4545 /* Close the pipe */
4546 CloseHandle(g_hChildStd_OUT_Rd);
4547 if (g_hChildStd_IN_Wr != NULL)
4548 CloseHandle(g_hChildStd_IN_Wr);
4549
4550 WaitForSingleObject(pi.hProcess, INFINITE);
4551
4552 /* Get the command exit code */
4553 GetExitCodeProcess(pi.hProcess, &ret);
4554
4555 if (options & SHELL_READ)
4556 {
4557 if (ga.ga_len > 0)
4558 {
4559 append_ga_line(&ga);
4560 /* remember that the NL was missing */
4561 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4562 }
4563 else
4564 curbuf->b_no_eol_lnum = 0;
4565 ga_clear(&ga);
4566 }
4567
4568 /* Close the handles to the subprocess, so that it goes away */
4569 CloseHandle(pi.hThread);
4570 CloseHandle(pi.hProcess);
4571
4572 return ret;
4573}
4574
4575 static int
4576mch_system(char *cmd, int options)
4577{
4578 /* if we can pipe and the shelltemp option is off */
4579 if (allowPiping && !p_stmp)
4580 return mch_system_piped(cmd, options);
4581 else
4582 return mch_system_classic(cmd, options);
4583}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004584#else
4585
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004586# ifdef FEAT_MBYTE
4587 static int
4588mch_system(char *cmd, int options)
4589{
4590 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4591 {
4592 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4593 if (wcmd != NULL)
4594 {
4595 int ret = _wsystem(wcmd);
4596 vim_free(wcmd);
4597 return ret;
4598 }
4599 }
4600 return system(cmd);
4601}
4602# else
4603# define mch_system(c, o) system(c)
4604# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004605
4606#endif
4607
4608/*
4609 * Either execute a command by calling the shell or start a new shell
4610 */
4611 int
4612mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004613 char_u *cmd,
4614 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615{
4616 int x = 0;
4617 int tmode = cur_tmode;
4618#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004619 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004620# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004621 int did_set_title = FALSE;
4622
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004623 /* Change the title to reflect that we are in a subshell. */
4624 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4625 {
4626 WCHAR szShellTitle[512];
4627
4628 if (GetConsoleTitleW(szShellTitle,
4629 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4630 {
4631 if (cmd == NULL)
4632 wcscat(szShellTitle, L" :sh");
4633 else
4634 {
4635 WCHAR *wn = enc_to_utf16(cmd, NULL);
4636
4637 if (wn != NULL)
4638 {
4639 wcscat(szShellTitle, L" - !");
4640 if ((wcslen(szShellTitle) + wcslen(wn) <
4641 sizeof(szShellTitle)/sizeof(WCHAR)))
4642 wcscat(szShellTitle, wn);
4643 SetConsoleTitleW(szShellTitle);
4644 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004645 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004646 }
4647 }
4648 }
4649 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004650 if (!did_set_title)
4651# endif
4652 /* Change the title to reflect that we are in a subshell. */
4653 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004655 if (cmd == NULL)
4656 strcat(szShellTitle, " :sh");
4657 else
4658 {
4659 strcat(szShellTitle, " - !");
4660 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4661 strcat(szShellTitle, cmd);
4662 }
4663 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004665#endif
4666
4667 out_flush();
4668
4669#ifdef MCH_WRITE_DUMP
4670 if (fdDump)
4671 {
4672 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4673 fflush(fdDump);
4674 }
4675#endif
4676
4677 /*
4678 * Catch all deadly signals while running the external command, because a
4679 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4680 */
4681 signal(SIGINT, SIG_IGN);
4682#if defined(__GNUC__) && !defined(__MINGW32__)
4683 signal(SIGKILL, SIG_IGN);
4684#else
4685 signal(SIGBREAK, SIG_IGN);
4686#endif
4687 signal(SIGILL, SIG_IGN);
4688 signal(SIGFPE, SIG_IGN);
4689 signal(SIGSEGV, SIG_IGN);
4690 signal(SIGTERM, SIG_IGN);
4691 signal(SIGABRT, SIG_IGN);
4692
4693 if (options & SHELL_COOKED)
4694 settmode(TMODE_COOK); /* set to normal mode */
4695
4696 if (cmd == NULL)
4697 {
4698 x = mch_system(p_sh, options);
4699 }
4700 else
4701 {
4702 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004703 char_u *newcmd = NULL;
4704 char_u *cmdbase = cmd;
4705 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004706
4707 /* Skip a leading ", ( and "(. */
4708 if (*cmdbase == '"' )
4709 ++cmdbase;
4710 if (*cmdbase == '(')
4711 ++cmdbase;
4712
4713 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4714 {
4715 STARTUPINFO si;
4716 PROCESS_INFORMATION pi;
4717 DWORD flags = CREATE_NEW_CONSOLE;
4718 char_u *p;
4719
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004720 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004721 si.cb = sizeof(si);
4722 si.lpReserved = NULL;
4723 si.lpDesktop = NULL;
4724 si.lpTitle = NULL;
4725 si.dwFlags = 0;
4726 si.cbReserved2 = 0;
4727 si.lpReserved2 = NULL;
4728
4729 cmdbase = skipwhite(cmdbase + 5);
4730 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4731 && vim_iswhite(cmdbase[4]))
4732 {
4733 cmdbase = skipwhite(cmdbase + 4);
4734 si.dwFlags = STARTF_USESHOWWINDOW;
4735 si.wShowWindow = SW_SHOWMINNOACTIVE;
4736 }
4737 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4738 && vim_iswhite(cmdbase[2]))
4739 {
4740 cmdbase = skipwhite(cmdbase + 2);
4741 flags = CREATE_NO_WINDOW;
4742 si.dwFlags = STARTF_USESTDHANDLES;
4743 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004744 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004745 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004746 NULL, // Security att.
4747 OPEN_EXISTING, // Open flags
4748 FILE_ATTRIBUTE_NORMAL, // File att.
4749 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004750 si.hStdOutput = si.hStdInput;
4751 si.hStdError = si.hStdInput;
4752 }
4753
4754 /* Remove a trailing ", ) and )" if they have a match
4755 * at the start of the command. */
4756 if (cmdbase > cmd)
4757 {
4758 p = cmdbase + STRLEN(cmdbase);
4759 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4760 *--p = NUL;
4761 if (p > cmdbase && p[-1] == ')'
4762 && (*cmd =='(' || cmd[1] == '('))
4763 *--p = NUL;
4764 }
4765
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004766 newcmd = cmdbase;
4767 unescape_shellxquote(cmdbase, p_sxe);
4768
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004769 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004770 * If creating new console, arguments are passed to the
4771 * 'cmd.exe' as-is. If it's not, arguments are not treated
4772 * correctly for current 'cmd.exe'. So unescape characters in
4773 * shellxescape except '|' for avoiding to be treated as
4774 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004775 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004776 if (flags != CREATE_NEW_CONSOLE)
4777 {
4778 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004779 char_u *cmd_shell = mch_getenv("COMSPEC");
4780
4781 if (cmd_shell == NULL || *cmd_shell == NUL)
4782 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004783
4784 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4785 if (subcmd != NULL)
4786 {
4787 /* make "cmd.exe /c arguments" */
4788 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004789 newcmd = lalloc(cmdlen, TRUE);
4790 if (newcmd != NULL)
4791 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004792 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004793 else
4794 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004795 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004796 }
4797 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004798
4799 /*
4800 * Now, start the command as a process, so that it doesn't
4801 * inherit our handles which causes unpleasant dangling swap
4802 * files if we exit before the spawned process
4803 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004804 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004805 x = 0;
4806 else
4807 {
4808 x = -1;
4809#ifdef FEAT_GUI_W32
4810 EMSG(_("E371: Command not found"));
4811#endif
4812 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004813
4814 if (newcmd != cmdbase)
4815 vim_free(newcmd);
4816
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004817 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004818 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004819 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004820 CloseHandle(si.hStdInput);
4821 }
4822 /* Close the handles to the subprocess, so that it goes away */
4823 CloseHandle(pi.hThread);
4824 CloseHandle(pi.hProcess);
4825 }
4826 else
4827 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004828 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004829#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004830 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004831#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004832 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4833
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004834 newcmd = lalloc(cmdlen, TRUE);
4835 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836 {
4837#if defined(FEAT_GUI_W32)
4838 if (need_vimrun_warning)
4839 {
4840 MessageBox(NULL,
4841 _("VIMRUN.EXE not found in your $PATH.\n"
4842 "External commands will not pause after completion.\n"
4843 "See :help win32-vimrun for more information."),
4844 _("Vim Warning"),
4845 MB_ICONWARNING);
4846 need_vimrun_warning = FALSE;
4847 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004848 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004849 /* Use vimrun to execute the command. It opens a console
4850 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004851 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004852 vimrun_path,
4853 (msg_silent != 0 || (options & SHELL_DOOUT))
4854 ? "-s " : "",
4855 p_sh, p_shcf, cmd);
4856 else
4857#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004858 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004859 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004860 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004861 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004862 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004863 }
4864 }
4865
4866 if (tmode == TMODE_RAW)
4867 settmode(TMODE_RAW); /* set to raw mode */
4868
4869 /* Print the return value, unless "vimrun" was used. */
4870 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4871#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004872 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4873 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004874#endif
4875 )
4876 {
4877 smsg(_("shell returned %d"), x);
4878 msg_putchar('\n');
4879 }
4880#ifdef FEAT_TITLE
4881 resettitle();
4882#endif
4883
4884 signal(SIGINT, SIG_DFL);
4885#if defined(__GNUC__) && !defined(__MINGW32__)
4886 signal(SIGKILL, SIG_DFL);
4887#else
4888 signal(SIGBREAK, SIG_DFL);
4889#endif
4890 signal(SIGILL, SIG_DFL);
4891 signal(SIGFPE, SIG_DFL);
4892 signal(SIGSEGV, SIG_DFL);
4893 signal(SIGTERM, SIG_DFL);
4894 signal(SIGABRT, SIG_DFL);
4895
4896 return x;
4897}
4898
4899
4900#ifndef FEAT_GUI_W32
4901
4902/*
4903 * Start termcap mode
4904 */
4905 static void
4906termcap_mode_start(void)
4907{
4908 DWORD cmodein;
4909
4910 if (g_fTermcapMode)
4911 return;
4912
4913 SaveConsoleBuffer(&g_cbNonTermcap);
4914
4915 if (g_cbTermcap.IsValid)
4916 {
4917 /*
4918 * We've been in termcap mode before. Restore certain screen
4919 * characteristics, including the buffer size and the window
4920 * size. Since we will be redrawing the screen, we don't need
4921 * to restore the actual contents of the buffer.
4922 */
4923 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4924 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4925 Rows = g_cbTermcap.Info.dwSize.Y;
4926 Columns = g_cbTermcap.Info.dwSize.X;
4927 }
4928 else
4929 {
4930 /*
4931 * This is our first time entering termcap mode. Clear the console
4932 * screen buffer, and resize the buffer to match the current window
4933 * size. We will use this as the size of our editing environment.
4934 */
Bram Moolenaar61594242015-09-01 20:23:37 +02004935 g_hConOut = g_cbTermcap.handle;
4936 SetConsoleActiveScreenBuffer(g_hConOut);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004937 ClearConsoleBuffer(g_attrCurrent);
4938 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4939 }
4940
4941#ifdef FEAT_TITLE
4942 resettitle();
4943#endif
4944
4945 GetConsoleMode(g_hConIn, &cmodein);
4946#ifdef FEAT_MOUSE
4947 if (g_fMouseActive)
4948 cmodein |= ENABLE_MOUSE_INPUT;
4949 else
4950 cmodein &= ~ENABLE_MOUSE_INPUT;
4951#endif
4952 cmodein |= ENABLE_WINDOW_INPUT;
4953 SetConsoleMode(g_hConIn, cmodein);
4954
4955 redraw_later_clear();
4956 g_fTermcapMode = TRUE;
4957}
4958
4959
4960/*
4961 * End termcap mode
4962 */
4963 static void
4964termcap_mode_end(void)
4965{
4966 DWORD cmodein;
4967 ConsoleBuffer *cb;
4968 COORD coord;
4969 DWORD dwDummy;
4970
4971 if (!g_fTermcapMode)
4972 return;
4973
4974 SaveConsoleBuffer(&g_cbTermcap);
4975
4976 GetConsoleMode(g_hConIn, &cmodein);
4977 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4978 SetConsoleMode(g_hConIn, cmodein);
4979
Bram Moolenaar071d4272004-06-13 20:20:40 +00004980 cb = &g_cbNonTermcap;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004981 RestoreConsoleBuffer(cb, p_rs);
4982 SetConsoleCursorInfo(g_hConOut, &g_cci);
4983
4984 if (p_rs || exiting)
4985 {
4986 /*
4987 * Clear anything that happens to be on the current line.
4988 */
4989 coord.X = 0;
4990 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4991 FillConsoleOutputCharacter(g_hConOut, ' ',
4992 cb->Info.dwSize.X, coord, &dwDummy);
4993 /*
4994 * The following is just for aesthetics. If we are exiting without
4995 * restoring the screen, then we want to have a prompt string
4996 * appear at the bottom line. However, the command interpreter
4997 * seems to always advance the cursor one line before displaying
4998 * the prompt string, which causes the screen to scroll. To
4999 * counter this, move the cursor up one line before exiting.
5000 */
5001 if (exiting && !p_rs)
5002 coord.Y--;
5003 /*
5004 * Position the cursor at the leftmost column of the desired row.
5005 */
5006 SetConsoleCursorPosition(g_hConOut, coord);
5007 }
5008
5009 g_fTermcapMode = FALSE;
5010}
5011#endif /* FEAT_GUI_W32 */
5012
5013
5014#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005015/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005016 void
5017mch_write(
5018 char_u *s,
5019 int len)
5020{
5021 /* never used */
5022}
5023
5024#else
5025
5026/*
5027 * clear `n' chars, starting from `coord'
5028 */
5029 static void
5030clear_chars(
5031 COORD coord,
5032 DWORD n)
5033{
5034 DWORD dwDummy;
5035
5036 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5037 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5038}
5039
5040
5041/*
5042 * Clear the screen
5043 */
5044 static void
5045clear_screen(void)
5046{
5047 g_coord.X = g_coord.Y = 0;
5048 clear_chars(g_coord, Rows * Columns);
5049}
5050
5051
5052/*
5053 * Clear to end of display
5054 */
5055 static void
5056clear_to_end_of_display(void)
5057{
5058 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5059 * Columns + (Columns - g_coord.X));
5060}
5061
5062
5063/*
5064 * Clear to end of line
5065 */
5066 static void
5067clear_to_end_of_line(void)
5068{
5069 clear_chars(g_coord, Columns - g_coord.X);
5070}
5071
5072
5073/*
5074 * Scroll the scroll region up by `cLines' lines
5075 */
5076 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005077scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005078{
5079 COORD oldcoord = g_coord;
5080
5081 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5082 delete_lines(cLines);
5083
5084 g_coord = oldcoord;
5085}
5086
5087
5088/*
5089 * Set the scroll region
5090 */
5091 static void
5092set_scroll_region(
5093 unsigned left,
5094 unsigned top,
5095 unsigned right,
5096 unsigned bottom)
5097{
5098 if (left >= right
5099 || top >= bottom
5100 || right > (unsigned) Columns - 1
5101 || bottom > (unsigned) Rows - 1)
5102 return;
5103
5104 g_srScrollRegion.Left = left;
5105 g_srScrollRegion.Top = top;
5106 g_srScrollRegion.Right = right;
5107 g_srScrollRegion.Bottom = bottom;
5108}
5109
5110
5111/*
5112 * Insert `cLines' lines at the current cursor position
5113 */
5114 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005115insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005116{
5117 SMALL_RECT source;
5118 COORD dest;
5119 CHAR_INFO fill;
5120
5121 dest.X = 0;
5122 dest.Y = g_coord.Y + cLines;
5123
5124 source.Left = 0;
5125 source.Top = g_coord.Y;
5126 source.Right = g_srScrollRegion.Right;
5127 source.Bottom = g_srScrollRegion.Bottom - cLines;
5128
5129 fill.Char.AsciiChar = ' ';
5130 fill.Attributes = g_attrCurrent;
5131
5132 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5133
5134 /* Here we have to deal with a win32 console flake: If the scroll
5135 * region looks like abc and we scroll c to a and fill with d we get
5136 * cbd... if we scroll block c one line at a time to a, we get cdd...
5137 * vim expects cdd consistently... So we have to deal with that
5138 * here... (this also occurs scrolling the same way in the other
5139 * direction). */
5140
5141 if (source.Bottom < dest.Y)
5142 {
5143 COORD coord;
5144
5145 coord.X = 0;
5146 coord.Y = source.Bottom;
5147 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5148 }
5149}
5150
5151
5152/*
5153 * Delete `cLines' lines at the current cursor position
5154 */
5155 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005156delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157{
5158 SMALL_RECT source;
5159 COORD dest;
5160 CHAR_INFO fill;
5161 int nb;
5162
5163 dest.X = 0;
5164 dest.Y = g_coord.Y;
5165
5166 source.Left = 0;
5167 source.Top = g_coord.Y + cLines;
5168 source.Right = g_srScrollRegion.Right;
5169 source.Bottom = g_srScrollRegion.Bottom;
5170
5171 fill.Char.AsciiChar = ' ';
5172 fill.Attributes = g_attrCurrent;
5173
5174 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5175
5176 /* Here we have to deal with a win32 console flake: If the scroll
5177 * region looks like abc and we scroll c to a and fill with d we get
5178 * cbd... if we scroll block c one line at a time to a, we get cdd...
5179 * vim expects cdd consistently... So we have to deal with that
5180 * here... (this also occurs scrolling the same way in the other
5181 * direction). */
5182
5183 nb = dest.Y + (source.Bottom - source.Top) + 1;
5184
5185 if (nb < source.Top)
5186 {
5187 COORD coord;
5188
5189 coord.X = 0;
5190 coord.Y = nb;
5191 clear_chars(coord, Columns * (source.Top - nb));
5192 }
5193}
5194
5195
5196/*
5197 * Set the cursor position
5198 */
5199 static void
5200gotoxy(
5201 unsigned x,
5202 unsigned y)
5203{
5204 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5205 return;
5206
5207 /* external cursor coords are 1-based; internal are 0-based */
5208 g_coord.X = x - 1;
5209 g_coord.Y = y - 1;
5210 SetConsoleCursorPosition(g_hConOut, g_coord);
5211}
5212
5213
5214/*
5215 * Set the current text attribute = (foreground | background)
5216 * See ../doc/os_win32.txt for the numbers.
5217 */
5218 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005219textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005220{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005221 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005222
5223 SetConsoleTextAttribute(g_hConOut, wAttr);
5224}
5225
5226
5227 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005228textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005229{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005230 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005231
5232 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5233}
5234
5235
5236 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005237textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005238{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005239 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005240
5241 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5242}
5243
5244
5245/*
5246 * restore the default text attribute (whatever we started with)
5247 */
5248 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005249normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005250{
5251 textattr(g_attrDefault);
5252}
5253
5254
5255static WORD g_attrPreStandout = 0;
5256
5257/*
5258 * Make the text standout, by brightening it
5259 */
5260 static void
5261standout(void)
5262{
5263 g_attrPreStandout = g_attrCurrent;
5264 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5265}
5266
5267
5268/*
5269 * Turn off standout mode
5270 */
5271 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005272standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005273{
5274 if (g_attrPreStandout)
5275 {
5276 textattr(g_attrPreStandout);
5277 g_attrPreStandout = 0;
5278 }
5279}
5280
5281
5282/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005283 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005284 */
5285 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005286mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005287{
5288 char_u *p;
5289 int n;
5290
5291 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5292 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5293 if (T_ME[0] == ESC && T_ME[1] == '|')
5294 {
5295 p = T_ME + 2;
5296 n = getdigits(&p);
5297 if (*p == 'm' && n > 0)
5298 {
5299 cterm_normal_fg_color = (n & 0xf) + 1;
5300 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5301 }
5302 }
5303}
5304
5305
5306/*
5307 * visual bell: flash the screen
5308 */
5309 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005310visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005311{
5312 COORD coordOrigin = {0, 0};
5313 WORD attrFlash = ~g_attrCurrent & 0xff;
5314
5315 DWORD dwDummy;
5316 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5317
5318 if (oldattrs == NULL)
5319 return;
5320 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5321 coordOrigin, &dwDummy);
5322 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5323 coordOrigin, &dwDummy);
5324
5325 Sleep(15); /* wait for 15 msec */
5326 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5327 coordOrigin, &dwDummy);
5328 vim_free(oldattrs);
5329}
5330
5331
5332/*
5333 * Make the cursor visible or invisible
5334 */
5335 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005336cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005337{
5338 s_cursor_visible = fVisible;
5339#ifdef MCH_CURSOR_SHAPE
5340 mch_update_cursor();
5341#endif
5342}
5343
5344
5345/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005346 * write `cbToWrite' bytes in `pchBuf' to the screen
5347 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005348 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005349 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005350write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005351 char_u *pchBuf,
5352 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353{
5354 COORD coord = g_coord;
5355 DWORD written;
5356
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005357#ifdef FEAT_MBYTE
5358 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5359 {
5360 static WCHAR *unicodebuf = NULL;
5361 static int unibuflen = 0;
5362 int length;
5363 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005365 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5366 if (unicodebuf == NULL || length > unibuflen)
5367 {
5368 vim_free(unicodebuf);
5369 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5370 unibuflen = length;
5371 }
5372 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5373 unicodebuf, unibuflen);
5374
5375 cells = mb_string2cells(pchBuf, cbToWrite);
5376 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5377 coord, &written);
5378 /* When writing fails or didn't write a single character, pretend one
5379 * character was written, otherwise we get stuck. */
5380 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5381 coord, &cchwritten) == 0
5382 || cchwritten == 0)
5383 cchwritten = 1;
5384
5385 if (cchwritten == length)
5386 {
5387 written = cbToWrite;
5388 g_coord.X += (SHORT)cells;
5389 }
5390 else
5391 {
5392 char_u *p = pchBuf;
5393 for (n = 0; n < cchwritten; n++)
5394 mb_cptr_adv(p);
5395 written = p - pchBuf;
5396 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5397 }
5398 }
5399 else
5400#endif
5401 {
5402 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5403 coord, &written);
5404 /* When writing fails or didn't write a single character, pretend one
5405 * character was written, otherwise we get stuck. */
5406 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5407 coord, &written) == 0
5408 || written == 0)
5409 written = 1;
5410
5411 g_coord.X += (SHORT) written;
5412 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413
5414 while (g_coord.X > g_srScrollRegion.Right)
5415 {
5416 g_coord.X -= (SHORT) Columns;
5417 if (g_coord.Y < g_srScrollRegion.Bottom)
5418 g_coord.Y++;
5419 }
5420
5421 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5422
5423 return written;
5424}
5425
5426
5427/*
5428 * mch_write(): write the output buffer to the screen, translating ESC
5429 * sequences into calls to console output routines.
5430 */
5431 void
5432mch_write(
5433 char_u *s,
5434 int len)
5435{
5436 s[len] = NUL;
5437
5438 if (!term_console)
5439 {
5440 write(1, s, (unsigned)len);
5441 return;
5442 }
5443
5444 /* translate ESC | sequences into faked bios calls */
5445 while (len--)
5446 {
5447 /* optimization: use one single write_chars for runs of text,
5448 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005449 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005450
5451 if (p_wd)
5452 {
5453 WaitForChar(p_wd);
5454 if (prefix != 0)
5455 prefix = 1;
5456 }
5457
5458 if (prefix != 0)
5459 {
5460 DWORD nWritten;
5461
5462 nWritten = write_chars(s, prefix);
5463#ifdef MCH_WRITE_DUMP
5464 if (fdDump)
5465 {
5466 fputc('>', fdDump);
5467 fwrite(s, sizeof(char_u), nWritten, fdDump);
5468 fputs("<\n", fdDump);
5469 }
5470#endif
5471 len -= (nWritten - 1);
5472 s += nWritten;
5473 }
5474 else if (s[0] == '\n')
5475 {
5476 /* \n, newline: go to the beginning of the next line or scroll */
5477 if (g_coord.Y == g_srScrollRegion.Bottom)
5478 {
5479 scroll(1);
5480 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5481 }
5482 else
5483 {
5484 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5485 }
5486#ifdef MCH_WRITE_DUMP
5487 if (fdDump)
5488 fputs("\\n\n", fdDump);
5489#endif
5490 s++;
5491 }
5492 else if (s[0] == '\r')
5493 {
5494 /* \r, carriage return: go to beginning of line */
5495 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5496#ifdef MCH_WRITE_DUMP
5497 if (fdDump)
5498 fputs("\\r\n", fdDump);
5499#endif
5500 s++;
5501 }
5502 else if (s[0] == '\b')
5503 {
5504 /* \b, backspace: move cursor one position left */
5505 if (g_coord.X > g_srScrollRegion.Left)
5506 g_coord.X--;
5507 else if (g_coord.Y > g_srScrollRegion.Top)
5508 {
5509 g_coord.X = g_srScrollRegion.Right;
5510 g_coord.Y--;
5511 }
5512 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5513#ifdef MCH_WRITE_DUMP
5514 if (fdDump)
5515 fputs("\\b\n", fdDump);
5516#endif
5517 s++;
5518 }
5519 else if (s[0] == '\a')
5520 {
5521 /* \a, bell */
5522 MessageBeep(0xFFFFFFFF);
5523#ifdef MCH_WRITE_DUMP
5524 if (fdDump)
5525 fputs("\\a\n", fdDump);
5526#endif
5527 s++;
5528 }
5529 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5530 {
5531#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005532 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005533#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005534 char_u *p;
5535 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005536
5537 switch (s[2])
5538 {
5539 /* one or two numeric arguments, separated by ';' */
5540
5541 case '0': case '1': case '2': case '3': case '4':
5542 case '5': case '6': case '7': case '8': case '9':
5543 p = s + 2;
5544 arg1 = getdigits(&p); /* no check for length! */
5545 if (p > s + len)
5546 break;
5547
5548 if (*p == ';')
5549 {
5550 ++p;
5551 arg2 = getdigits(&p); /* no check for length! */
5552 if (p > s + len)
5553 break;
5554
5555 if (*p == 'H')
5556 gotoxy(arg2, arg1);
5557 else if (*p == 'r')
5558 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5559 }
5560 else if (*p == 'A')
5561 {
5562 /* move cursor up arg1 lines in same column */
5563 gotoxy(g_coord.X + 1,
5564 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5565 }
5566 else if (*p == 'C')
5567 {
5568 /* move cursor right arg1 columns in same line */
5569 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5570 g_coord.Y + 1);
5571 }
5572 else if (*p == 'H')
5573 {
5574 gotoxy(1, arg1);
5575 }
5576 else if (*p == 'L')
5577 {
5578 insert_lines(arg1);
5579 }
5580 else if (*p == 'm')
5581 {
5582 if (arg1 == 0)
5583 normvideo();
5584 else
5585 textattr((WORD) arg1);
5586 }
5587 else if (*p == 'f')
5588 {
5589 textcolor((WORD) arg1);
5590 }
5591 else if (*p == 'b')
5592 {
5593 textbackground((WORD) arg1);
5594 }
5595 else if (*p == 'M')
5596 {
5597 delete_lines(arg1);
5598 }
5599
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005600 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005601 s = p + 1;
5602 break;
5603
5604
5605 /* Three-character escape sequences */
5606
5607 case 'A':
5608 /* move cursor up one line in same column */
5609 gotoxy(g_coord.X + 1,
5610 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5611 goto got3;
5612
5613 case 'B':
5614 visual_bell();
5615 goto got3;
5616
5617 case 'C':
5618 /* move cursor right one column in same line */
5619 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5620 g_coord.Y + 1);
5621 goto got3;
5622
5623 case 'E':
5624 termcap_mode_end();
5625 goto got3;
5626
5627 case 'F':
5628 standout();
5629 goto got3;
5630
5631 case 'f':
5632 standend();
5633 goto got3;
5634
5635 case 'H':
5636 gotoxy(1, 1);
5637 goto got3;
5638
5639 case 'j':
5640 clear_to_end_of_display();
5641 goto got3;
5642
5643 case 'J':
5644 clear_screen();
5645 goto got3;
5646
5647 case 'K':
5648 clear_to_end_of_line();
5649 goto got3;
5650
5651 case 'L':
5652 insert_lines(1);
5653 goto got3;
5654
5655 case 'M':
5656 delete_lines(1);
5657 goto got3;
5658
5659 case 'S':
5660 termcap_mode_start();
5661 goto got3;
5662
5663 case 'V':
5664 cursor_visible(TRUE);
5665 goto got3;
5666
5667 case 'v':
5668 cursor_visible(FALSE);
5669 goto got3;
5670
5671 got3:
5672 s += 3;
5673 len -= 2;
5674 }
5675
5676#ifdef MCH_WRITE_DUMP
5677 if (fdDump)
5678 {
5679 fputs("ESC | ", fdDump);
5680 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5681 fputc('\n', fdDump);
5682 }
5683#endif
5684 }
5685 else
5686 {
5687 /* Write a single character */
5688 DWORD nWritten;
5689
5690 nWritten = write_chars(s, 1);
5691#ifdef MCH_WRITE_DUMP
5692 if (fdDump)
5693 {
5694 fputc('>', fdDump);
5695 fwrite(s, sizeof(char_u), nWritten, fdDump);
5696 fputs("<\n", fdDump);
5697 }
5698#endif
5699
5700 len -= (nWritten - 1);
5701 s += nWritten;
5702 }
5703 }
5704
5705#ifdef MCH_WRITE_DUMP
5706 if (fdDump)
5707 fflush(fdDump);
5708#endif
5709}
5710
5711#endif /* FEAT_GUI_W32 */
5712
5713
5714/*
5715 * Delay for half a second.
5716 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005717/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718 void
5719mch_delay(
5720 long msec,
5721 int ignoreinput)
5722{
5723#ifdef FEAT_GUI_W32
5724 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005725#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005726 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005727# ifdef FEAT_MZSCHEME
5728 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5729 {
5730 int towait = p_mzq;
5731
5732 /* if msec is large enough, wait by portions in p_mzq */
5733 while (msec > 0)
5734 {
5735 mzvim_check_threads();
5736 if (msec < towait)
5737 towait = msec;
5738 Sleep(towait);
5739 msec -= towait;
5740 }
5741 }
5742 else
5743# endif
5744 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745 else
5746 WaitForChar(msec);
5747#endif
5748}
5749
5750
5751/*
5752 * this version of remove is not scared by a readonly (backup) file
5753 * Return 0 for success, -1 for failure.
5754 */
5755 int
5756mch_remove(char_u *name)
5757{
5758#ifdef FEAT_MBYTE
5759 WCHAR *wn = NULL;
5760 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005761#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005762
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005763 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5764
5765#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005766 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5767 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005768 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005769 if (wn != NULL)
5770 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771 n = DeleteFileW(wn) ? 0 : -1;
5772 vim_free(wn);
5773 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5774 return n;
5775 /* Retry with non-wide function (for Windows 98). */
5776 }
5777 }
5778#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779 return DeleteFile(name) ? 0 : -1;
5780}
5781
5782
5783/*
5784 * check for an "interrupt signal": CTRL-break or CTRL-C
5785 */
5786 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005787mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005788{
5789#ifndef FEAT_GUI_W32 /* never used */
5790 if (g_fCtrlCPressed || g_fCBrkPressed)
5791 {
5792 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5793 got_int = TRUE;
5794 }
5795#endif
5796}
5797
5798
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799#ifdef FEAT_MBYTE
5800/*
5801 * Same code as below, but with wide functions and no comments.
5802 * Return 0 for success, non-zero for failure.
5803 */
5804 int
5805mch_wrename(WCHAR *wold, WCHAR *wnew)
5806{
5807 WCHAR *p;
5808 int i;
5809 WCHAR szTempFile[_MAX_PATH + 1];
5810 WCHAR szNewPath[_MAX_PATH + 1];
5811 HANDLE hf;
5812
5813 if (!mch_windows95())
5814 {
5815 p = wold;
5816 for (i = 0; wold[i] != NUL; ++i)
5817 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5818 && wold[i + 1] != 0)
5819 p = wold + i + 1;
5820 if ((int)(wold + i - p) < 8 || p[6] != '~')
5821 return (MoveFileW(wold, wnew) == 0);
5822 }
5823
5824 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5825 return -1;
5826 *p = NUL;
5827
5828 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5829 return -2;
5830
5831 if (!DeleteFileW(szTempFile))
5832 return -3;
5833
5834 if (!MoveFileW(wold, szTempFile))
5835 return -4;
5836
5837 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5838 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5839 return -5;
5840 if (!CloseHandle(hf))
5841 return -6;
5842
5843 if (!MoveFileW(szTempFile, wnew))
5844 {
5845 (void)MoveFileW(szTempFile, wold);
5846 return -7;
5847 }
5848
5849 DeleteFileW(szTempFile);
5850
5851 if (!DeleteFileW(wold))
5852 return -8;
5853
5854 return 0;
5855}
5856#endif
5857
5858
5859/*
5860 * mch_rename() works around a bug in rename (aka MoveFile) in
5861 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5862 * file whose short file name is "FOO.BAR" (its long file name will
5863 * be correct: "foo.bar~"). Because a file can be accessed by
5864 * either its SFN or its LFN, "foo.bar" has effectively been
5865 * renamed to "foo.bar", which is not at all what was wanted. This
5866 * seems to happen only when renaming files with three-character
5867 * extensions by appending a suffix that does not include ".".
5868 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5869 *
5870 * There is another problem, which isn't really a bug but isn't right either:
5871 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5872 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5873 * service pack 6. Doesn't seem to happen on Windows 98.
5874 *
5875 * Like rename(), returns 0 upon success, non-zero upon failure.
5876 * Should probably set errno appropriately when errors occur.
5877 */
5878 int
5879mch_rename(
5880 const char *pszOldFile,
5881 const char *pszNewFile)
5882{
5883 char szTempFile[_MAX_PATH+1];
5884 char szNewPath[_MAX_PATH+1];
5885 char *pszFilePart;
5886 HANDLE hf;
5887#ifdef FEAT_MBYTE
5888 WCHAR *wold = NULL;
5889 WCHAR *wnew = NULL;
5890 int retval = -1;
5891
5892 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5893 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005894 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5895 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005896 if (wold != NULL && wnew != NULL)
5897 retval = mch_wrename(wold, wnew);
5898 vim_free(wold);
5899 vim_free(wnew);
5900 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5901 return retval;
5902 /* Retry with non-wide function (for Windows 98). */
5903 }
5904#endif
5905
5906 /*
5907 * No need to play tricks if not running Windows 95, unless the file name
5908 * contains a "~" as the seventh character.
5909 */
5910 if (!mch_windows95())
5911 {
5912 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5913 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5914 return rename(pszOldFile, pszNewFile);
5915 }
5916
5917 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5918 * a directory, no error is returned and pszFilePart will be NULL. */
5919 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5920 || pszFilePart == NULL)
5921 return -1;
5922 *pszFilePart = NUL;
5923
5924 /* Get (and create) a unique temporary file name in directory of new file */
5925 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5926 return -2;
5927
5928 /* blow the temp file away */
5929 if (!DeleteFile(szTempFile))
5930 return -3;
5931
5932 /* rename old file to the temp file */
5933 if (!MoveFile(pszOldFile, szTempFile))
5934 return -4;
5935
5936 /* now create an empty file called pszOldFile; this prevents the operating
5937 * system using pszOldFile as an alias (SFN) if we're renaming within the
5938 * same directory. For example, we're editing a file called
5939 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5940 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5941 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005942 * cause all sorts of problems later in buf_write(). So, we create an
5943 * empty file called filena~1.txt and the system will have to find some
5944 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005945 */
5946 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5947 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5948 return -5;
5949 if (!CloseHandle(hf))
5950 return -6;
5951
5952 /* rename the temp file to the new file */
5953 if (!MoveFile(szTempFile, pszNewFile))
5954 {
5955 /* Renaming failed. Rename the file back to its old name, so that it
5956 * looks like nothing happened. */
5957 (void)MoveFile(szTempFile, pszOldFile);
5958
5959 return -7;
5960 }
5961
5962 /* Seems to be left around on Novell filesystems */
5963 DeleteFile(szTempFile);
5964
5965 /* finally, remove the empty old file */
5966 if (!DeleteFile(pszOldFile))
5967 return -8;
5968
5969 return 0; /* success */
5970}
5971
5972/*
5973 * Get the default shell for the current hardware platform
5974 */
5975 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005976default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005977{
5978 char* psz = NULL;
5979
5980 PlatformId();
5981
5982 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5983 psz = "cmd.exe";
5984 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5985 psz = "command.com";
5986
5987 return psz;
5988}
5989
5990/*
5991 * mch_access() extends access() to do more detailed check on network drives.
5992 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5993 */
5994 int
5995mch_access(char *n, int p)
5996{
5997 HANDLE hFile;
5998 DWORD am;
5999 int retval = -1; /* default: fail */
6000#ifdef FEAT_MBYTE
6001 WCHAR *wn = NULL;
6002
6003 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006004 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006005#endif
6006
6007 if (mch_isdir(n))
6008 {
6009 char TempName[_MAX_PATH + 16] = "";
6010#ifdef FEAT_MBYTE
6011 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6012#endif
6013
6014 if (p & R_OK)
6015 {
6016 /* Read check is performed by seeing if we can do a find file on
6017 * the directory for any file. */
6018#ifdef FEAT_MBYTE
6019 if (wn != NULL)
6020 {
6021 int i;
6022 WIN32_FIND_DATAW d;
6023
6024 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6025 TempNameW[i] = wn[i];
6026 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6027 TempNameW[i++] = '\\';
6028 TempNameW[i++] = '*';
6029 TempNameW[i++] = 0;
6030
6031 hFile = FindFirstFileW(TempNameW, &d);
6032 if (hFile == INVALID_HANDLE_VALUE)
6033 {
6034 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6035 goto getout;
6036
6037 /* Retry with non-wide function (for Windows 98). */
6038 vim_free(wn);
6039 wn = NULL;
6040 }
6041 else
6042 (void)FindClose(hFile);
6043 }
6044 if (wn == NULL)
6045#endif
6046 {
6047 char *pch;
6048 WIN32_FIND_DATA d;
6049
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006050 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051 pch = TempName + STRLEN(TempName) - 1;
6052 if (*pch != '\\' && *pch != '/')
6053 *++pch = '\\';
6054 *++pch = '*';
6055 *++pch = NUL;
6056
6057 hFile = FindFirstFile(TempName, &d);
6058 if (hFile == INVALID_HANDLE_VALUE)
6059 goto getout;
6060 (void)FindClose(hFile);
6061 }
6062 }
6063
6064 if (p & W_OK)
6065 {
6066 /* Trying to create a temporary file in the directory should catch
6067 * directories on read-only network shares. However, in
6068 * directories whose ACL allows writes but denies deletes will end
6069 * up keeping the temporary file :-(. */
6070#ifdef FEAT_MBYTE
6071 if (wn != NULL)
6072 {
6073 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6074 {
6075 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6076 goto getout;
6077
6078 /* Retry with non-wide function (for Windows 98). */
6079 vim_free(wn);
6080 wn = NULL;
6081 }
6082 else
6083 DeleteFileW(TempNameW);
6084 }
6085 if (wn == NULL)
6086#endif
6087 {
6088 if (!GetTempFileName(n, "VIM", 0, TempName))
6089 goto getout;
6090 mch_remove((char_u *)TempName);
6091 }
6092 }
6093 }
6094 else
6095 {
6096 /* Trying to open the file for the required access does ACL, read-only
6097 * network share, and file attribute checks. */
6098 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6099 | ((p & R_OK) ? GENERIC_READ : 0);
6100#ifdef FEAT_MBYTE
6101 if (wn != NULL)
6102 {
6103 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6104 if (hFile == INVALID_HANDLE_VALUE
6105 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6106 {
6107 /* Retry with non-wide function (for Windows 98). */
6108 vim_free(wn);
6109 wn = NULL;
6110 }
6111 }
6112 if (wn == NULL)
6113#endif
6114 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6115 if (hFile == INVALID_HANDLE_VALUE)
6116 goto getout;
6117 CloseHandle(hFile);
6118 }
6119
6120 retval = 0; /* success */
6121getout:
6122#ifdef FEAT_MBYTE
6123 vim_free(wn);
6124#endif
6125 return retval;
6126}
6127
6128#if defined(FEAT_MBYTE) || defined(PROTO)
6129/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006130 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006131 */
6132 int
6133mch_open(char *name, int flags, int mode)
6134{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006135 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6136# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137 WCHAR *wn;
6138 int f;
6139
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006140 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006141 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006142 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006143 if (wn != NULL)
6144 {
6145 f = _wopen(wn, flags, mode);
6146 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006147 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006148 return f;
6149 /* Retry with non-wide function (for Windows 98). Can't use
6150 * GetLastError() here and it's unclear what errno gets set to if
6151 * the _wopen() fails for missing wide functions. */
6152 }
6153 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006154# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006155
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006156 /* open() can open a file which name is longer than _MAX_PATH bytes
6157 * and shorter than _MAX_PATH characters successfully, but sometimes it
6158 * causes unexpected error in another part. We make it an error explicitly
6159 * here. */
6160 if (strlen(name) >= _MAX_PATH)
6161 return -1;
6162
Bram Moolenaar071d4272004-06-13 20:20:40 +00006163 return open(name, flags, mode);
6164}
6165
6166/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006167 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 */
6169 FILE *
6170mch_fopen(char *name, char *mode)
6171{
6172 WCHAR *wn, *wm;
6173 FILE *f = NULL;
6174
6175 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6176# ifdef __BORLANDC__
6177 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6178 && g_PlatformId == VER_PLATFORM_WIN32_NT
6179# endif
6180 )
6181 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006182# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006183 /* Work around an annoying assertion in the Microsoft debug CRT
6184 * when mode's text/binary setting doesn't match _get_fmode(). */
6185 char newMode = mode[strlen(mode) - 1];
6186 int oldMode = 0;
6187
6188 _get_fmode(&oldMode);
6189 if (newMode == 't')
6190 _set_fmode(_O_TEXT);
6191 else if (newMode == 'b')
6192 _set_fmode(_O_BINARY);
6193# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006194 wn = enc_to_utf16(name, NULL);
6195 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006196 if (wn != NULL && wm != NULL)
6197 f = _wfopen(wn, wm);
6198 vim_free(wn);
6199 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006200
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006201# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006202 _set_fmode(oldMode);
6203# endif
6204
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006205 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006206 return f;
6207 /* Retry with non-wide function (for Windows 98). Can't use
6208 * GetLastError() here and it's unclear what errno gets set to if
6209 * the _wfopen() fails for missing wide functions. */
6210 }
6211
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006212 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6213 * and shorter than _MAX_PATH characters successfully, but sometimes it
6214 * causes unexpected error in another part. We make it an error explicitly
6215 * here. */
6216 if (strlen(name) >= _MAX_PATH)
6217 return NULL;
6218
Bram Moolenaar071d4272004-06-13 20:20:40 +00006219 return fopen(name, mode);
6220}
6221#endif
6222
6223#ifdef FEAT_MBYTE
6224/*
6225 * SUB STREAM (aka info stream) handling:
6226 *
6227 * NTFS can have sub streams for each file. Normal contents of file is
6228 * stored in the main stream, and extra contents (author information and
6229 * title and so on) can be stored in sub stream. After Windows 2000, user
6230 * can access and store those informations in sub streams via explorer's
6231 * property menuitem in right click menu. Those informations in sub streams
6232 * were lost when copying only the main stream. So we have to copy sub
6233 * streams.
6234 *
6235 * Incomplete explanation:
6236 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6237 * More useful info and an example:
6238 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6239 */
6240
6241/*
6242 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6243 * and write to stream "substream" of file "to".
6244 * Errors are ignored.
6245 */
6246 static void
6247copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6248{
6249 HANDLE hTo;
6250 WCHAR *to_name;
6251
6252 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6253 wcscpy(to_name, to);
6254 wcscat(to_name, substream);
6255
6256 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6257 FILE_ATTRIBUTE_NORMAL, NULL);
6258 if (hTo != INVALID_HANDLE_VALUE)
6259 {
6260 long done;
6261 DWORD todo;
6262 DWORD readcnt, written;
6263 char buf[4096];
6264
6265 /* Copy block of bytes at a time. Abort when something goes wrong. */
6266 for (done = 0; done < len; done += written)
6267 {
6268 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006269 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6270 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6272 FALSE, FALSE, context)
6273 || readcnt != todo
6274 || !WriteFile(hTo, buf, todo, &written, NULL)
6275 || written != todo)
6276 break;
6277 }
6278 CloseHandle(hTo);
6279 }
6280
6281 free(to_name);
6282}
6283
6284/*
6285 * Copy info streams from file "from" to file "to".
6286 */
6287 static void
6288copy_infostreams(char_u *from, char_u *to)
6289{
6290 WCHAR *fromw;
6291 WCHAR *tow;
6292 HANDLE sh;
6293 WIN32_STREAM_ID sid;
6294 int headersize;
6295 WCHAR streamname[_MAX_PATH];
6296 DWORD readcount;
6297 void *context = NULL;
6298 DWORD lo, hi;
6299 int len;
6300
6301 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006302 fromw = enc_to_utf16(from, NULL);
6303 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304 if (fromw != NULL && tow != NULL)
6305 {
6306 /* Open the file for reading. */
6307 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6308 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6309 if (sh != INVALID_HANDLE_VALUE)
6310 {
6311 /* Use BackupRead() to find the info streams. Repeat until we
6312 * have done them all.*/
6313 for (;;)
6314 {
6315 /* Get the header to find the length of the stream name. If
6316 * the "readcount" is zero we have done all info streams. */
6317 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006318 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6320 &readcount, FALSE, FALSE, &context)
6321 || readcount == 0)
6322 break;
6323
6324 /* We only deal with streams that have a name. The normal
6325 * file data appears to be without a name, even though docs
6326 * suggest it is called "::$DATA". */
6327 if (sid.dwStreamNameSize > 0)
6328 {
6329 /* Read the stream name. */
6330 if (!BackupRead(sh, (LPBYTE)streamname,
6331 sid.dwStreamNameSize,
6332 &readcount, FALSE, FALSE, &context))
6333 break;
6334
6335 /* Copy an info stream with a name ":anything:$DATA".
6336 * Skip "::$DATA", it has no stream name (examples suggest
6337 * it might be used for the normal file contents).
6338 * Note that BackupRead() counts bytes, but the name is in
6339 * wide characters. */
6340 len = readcount / sizeof(WCHAR);
6341 streamname[len] = 0;
6342 if (len > 7 && wcsicmp(streamname + len - 6,
6343 L":$DATA") == 0)
6344 {
6345 streamname[len - 6] = 0;
6346 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006347 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348 }
6349 }
6350
6351 /* Advance to the next stream. We might try seeking too far,
6352 * but BackupSeek() doesn't skip over stream borders, thus
6353 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006354 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 &lo, &hi, &context);
6356 }
6357
6358 /* Clear the context. */
6359 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6360
6361 CloseHandle(sh);
6362 }
6363 }
6364 vim_free(fromw);
6365 vim_free(tow);
6366}
6367#endif
6368
6369/*
6370 * Copy file attributes from file "from" to file "to".
6371 * For Windows NT and later we copy info streams.
6372 * Always returns zero, errors are ignored.
6373 */
6374 int
6375mch_copy_file_attribute(char_u *from, char_u *to)
6376{
6377#ifdef FEAT_MBYTE
6378 /* File streams only work on Windows NT and later. */
6379 PlatformId();
6380 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6381 copy_infostreams(from, to);
6382#endif
6383 return 0;
6384}
6385
6386#if defined(MYRESETSTKOFLW) || defined(PROTO)
6387/*
6388 * Recreate a destroyed stack guard page in win32.
6389 * Written by Benjamin Peterson.
6390 */
6391
6392/* These magic numbers are from the MS header files */
6393#define MIN_STACK_WIN9X 17
6394#define MIN_STACK_WINNT 2
6395
6396/*
6397 * This function does the same thing as _resetstkoflw(), which is only
6398 * available in DevStudio .net and later.
6399 * Returns 0 for failure, 1 for success.
6400 */
6401 int
6402myresetstkoflw(void)
6403{
6404 BYTE *pStackPtr;
6405 BYTE *pGuardPage;
6406 BYTE *pStackBase;
6407 BYTE *pLowestPossiblePage;
6408 MEMORY_BASIC_INFORMATION mbi;
6409 SYSTEM_INFO si;
6410 DWORD nPageSize;
6411 DWORD dummy;
6412
6413 /* This code will not work on win32s. */
6414 PlatformId();
6415 if (g_PlatformId == VER_PLATFORM_WIN32s)
6416 return 0;
6417
6418 /* We need to know the system page size. */
6419 GetSystemInfo(&si);
6420 nPageSize = si.dwPageSize;
6421
6422 /* ...and the current stack pointer */
6423 pStackPtr = (BYTE*)_alloca(1);
6424
6425 /* ...and the base of the stack. */
6426 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6427 return 0;
6428 pStackBase = (BYTE*)mbi.AllocationBase;
6429
6430 /* ...and the page thats min_stack_req pages away from stack base; this is
6431 * the lowest page we could use. */
6432 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6433 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6434
6435 /* On Win95, we want the next page down from the end of the stack. */
6436 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6437 {
6438 /* Find the page that's only 1 page down from the page that the stack
6439 * ptr is in. */
6440 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6441 / (DWORD)nPageSize) - 1));
6442 if (pGuardPage < pLowestPossiblePage)
6443 return 0;
6444
6445 /* Apply the noaccess attribute to the page -- there's no guard
6446 * attribute in win95-type OSes. */
6447 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6448 return 0;
6449 }
6450 else
6451 {
6452 /* On NT, however, we want the first committed page in the stack Start
6453 * at the stack base and move forward through memory until we find a
6454 * committed block. */
6455 BYTE *pBlock = pStackBase;
6456
Bram Moolenaara466c992005-07-09 21:03:22 +00006457 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006458 {
6459 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6460 return 0;
6461
6462 pBlock += mbi.RegionSize;
6463
6464 if (mbi.State & MEM_COMMIT)
6465 break;
6466 }
6467
6468 /* mbi now describes the first committed block in the stack. */
6469 if (mbi.Protect & PAGE_GUARD)
6470 return 1;
6471
6472 /* decide where the guard page should start */
6473 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6474 pGuardPage = pLowestPossiblePage;
6475 else
6476 pGuardPage = (BYTE*)mbi.BaseAddress;
6477
6478 /* allocate the guard page */
6479 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6480 return 0;
6481
6482 /* apply the guard attribute to the page */
6483 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6484 &dummy))
6485 return 0;
6486 }
6487
6488 return 1;
6489}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006490#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006492
6493#if defined(FEAT_MBYTE) || defined(PROTO)
6494/*
6495 * The command line arguments in UCS2
6496 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006497static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006498static LPWSTR *ArglistW = NULL;
6499static int global_argc = 0;
6500static char **global_argv;
6501
6502static int used_file_argc = 0; /* last argument in global_argv[] used
6503 for the argument list. */
6504static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6505 command line arguments added to
6506 the argument list */
6507static int used_file_count = 0; /* nr of entries in used_file_indexes */
6508static int used_file_literal = FALSE; /* take file names literally */
6509static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006510static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006511static int used_alist_count = 0;
6512
6513
6514/*
6515 * Get the command line arguments. Unicode version.
6516 * Returns argc. Zero when something fails.
6517 */
6518 int
6519get_cmd_argsW(char ***argvp)
6520{
6521 char **argv = NULL;
6522 int argc = 0;
6523 int i;
6524
Bram Moolenaar14993322014-09-09 12:25:33 +02006525 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006526 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6527 if (ArglistW != NULL)
6528 {
6529 argv = malloc((nArgsW + 1) * sizeof(char *));
6530 if (argv != NULL)
6531 {
6532 argc = nArgsW;
6533 argv[argc] = NULL;
6534 for (i = 0; i < argc; ++i)
6535 {
6536 int len;
6537
6538 /* Convert each Unicode argument to the current codepage. */
6539 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006540 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006541 (LPSTR *)&argv[i], &len, 0, 0);
6542 if (argv[i] == NULL)
6543 {
6544 /* Out of memory, clear everything. */
6545 while (i > 0)
6546 free(argv[--i]);
6547 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006548 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006549 argc = 0;
6550 }
6551 }
6552 }
6553 }
6554
6555 global_argc = argc;
6556 global_argv = argv;
6557 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006558 {
6559 if (used_file_indexes != NULL)
6560 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006561 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006562 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006563
6564 if (argvp != NULL)
6565 *argvp = argv;
6566 return argc;
6567}
6568
6569 void
6570free_cmd_argsW(void)
6571{
6572 if (ArglistW != NULL)
6573 {
6574 GlobalFree(ArglistW);
6575 ArglistW = NULL;
6576 }
6577}
6578
6579/*
6580 * Remember "name" is an argument that was added to the argument list.
6581 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6582 * is called.
6583 */
6584 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006585used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006586{
6587 int i;
6588
6589 if (used_file_indexes == NULL)
6590 return;
6591 for (i = used_file_argc + 1; i < global_argc; ++i)
6592 if (STRCMP(global_argv[i], name) == 0)
6593 {
6594 used_file_argc = i;
6595 used_file_indexes[used_file_count++] = i;
6596 break;
6597 }
6598 used_file_literal = literal;
6599 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006600 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006601}
6602
6603/*
6604 * Remember the length of the argument list as it was. If it changes then we
6605 * leave it alone when 'encoding' is set.
6606 */
6607 void
6608set_alist_count(void)
6609{
6610 used_alist_count = GARGCOUNT;
6611}
6612
6613/*
6614 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6615 * has been changed while starting up. Use the UCS-2 command line arguments
6616 * and convert them to 'encoding'.
6617 */
6618 void
6619fix_arg_enc(void)
6620{
6621 int i;
6622 int idx;
6623 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006624 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006625
6626 /* Safety checks:
6627 * - if argument count differs between the wide and non-wide argument
6628 * list, something must be wrong.
6629 * - the file name arguments must have been located.
6630 * - the length of the argument list wasn't changed by the user.
6631 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006632 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006633 || ArglistW == NULL
6634 || used_file_indexes == NULL
6635 || used_file_count == 0
6636 || used_alist_count != GARGCOUNT)
6637 return;
6638
Bram Moolenaar86b68352004-12-27 21:59:20 +00006639 /* Remember the buffer numbers for the arguments. */
6640 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6641 if (fnum_list == NULL)
6642 return; /* out of memory */
6643 for (i = 0; i < GARGCOUNT; ++i)
6644 fnum_list[i] = GARGLIST[i].ae_fnum;
6645
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006646 /* Clear the argument list. Make room for the new arguments. */
6647 alist_clear(&global_alist);
6648 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006649 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006650
6651 for (i = 0; i < used_file_count; ++i)
6652 {
6653 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006654 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006655 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006656 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006657#ifdef FEAT_DIFF
6658 /* When using diff mode may need to concatenate file name to
6659 * directory name. Just like it's done in main(). */
6660 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6661 && !mch_isdir(alist_name(&GARGLIST[0])))
6662 {
6663 char_u *r;
6664
6665 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6666 if (r != NULL)
6667 {
6668 vim_free(str);
6669 str = r;
6670 }
6671 }
6672#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006673 /* Re-use the old buffer by renaming it. When not using literal
6674 * names it's done by alist_expand() below. */
6675 if (used_file_literal)
6676 buf_set_name(fnum_list[i], str);
6677
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006678 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006679 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006680 }
6681
6682 if (!used_file_literal)
6683 {
6684 /* Now expand wildcards in the arguments. */
6685 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6686 * filename characters but are excluded from 'isfname' to make
6687 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6688 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006689 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006690 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6691 }
6692
6693 /* If wildcard expansion failed, we are editing the first file of the
6694 * arglist and there is no file name: Edit the first argument now. */
6695 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6696 {
6697 do_cmdline_cmd((char_u *)":rewind");
6698 if (GARGCOUNT == 1 && used_file_full_path)
6699 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6700 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006701
6702 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006703}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704#endif