blob: d782a9d613b218c533f8c3e31ef7891998160bd5 [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);
216static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
217static char_u tgetch(int *pmodifiers, char_u *pch2);
218static 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)
268 return PeekConsoleInput(hInput, lpBuffer, 1, lpEvents);
269 return ReadConsoleInput(hInput, lpBuffer, 1, &dwEvents);
270 }
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)
275 return PeekConsoleInput(hInput, lpBuffer, 1, lpEvents);
276 if (!ReadConsoleInput(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__)
871# define AChar AsciiChar
872#else
873# define AChar uChar.AsciiChar
874#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 {
892 pker->AChar = (CHAR) awAnsiCode[1];
893 s_iIsDead = 0;
894 return 1;
895 }
896
897 if (pker->AChar != 0)
898 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 */
912 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
913
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
925 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
926 abKeystate, awAnsiCode, 0);
927
928 if (s_iIsDead > 0)
929 pker->AChar = (CHAR) awAnsiCode[0];
930
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,
956 char_u *pch,
957 char_u *pch2,
958 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 */
985 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
986 {
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 {
1047 *pch = (i > 0) ? pker->AChar : NUL;
1048
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;
1439 char_u ch, ch2;
1440
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 */
1526 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1527 && 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 */
1589 static char_u
1590tgetch(int *pmodifiers, char_u *pch2)
1591{
1592 char_u ch;
1593
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;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001661#ifdef FEAT_MBYTE
1662 static char_u *rest = NULL; /* unconverted rest of previous read */
1663 static int restlen = 0;
1664 int unconverted;
1665#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001666
1667 /* First use any typeahead that was kept because "buf" was too small. */
1668 if (typeaheadlen > 0)
1669 goto theend;
1670
1671#ifdef FEAT_SNIFF
1672 if (want_sniff_request)
1673 {
1674 if (sniff_request_waiting)
1675 {
1676 /* return K_SNIFF */
1677 typeahead[typeaheadlen++] = CSI;
1678 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1679 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1680 sniff_request_waiting = 0;
1681 want_sniff_request = 0;
1682 goto theend;
1683 }
1684 else if (time < 0 || time > 250)
1685 {
1686 /* don't wait too long, a request might be pending */
1687 time = 250;
1688 }
1689 }
1690#endif
1691
1692 if (time >= 0)
1693 {
1694 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001695 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696 }
1697 else /* time == -1, wait forever */
1698 {
1699 mch_set_winsize_now(); /* Allow winsize changes from now on */
1700
Bram Moolenaar3918c952005-03-15 22:34:55 +00001701 /*
1702 * If there is no character available within 2 seconds (default)
1703 * write the autoscript file to disk. Or cause the CursorHold event
1704 * to be triggered.
1705 */
1706 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001707 {
1708#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001709 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001710 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001711 buf[0] = K_SPECIAL;
1712 buf[1] = KS_EXTRA;
1713 buf[2] = (int)KE_CURSORHOLD;
1714 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715 }
1716#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001717 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001718 }
1719 }
1720
1721 /*
1722 * Try to read as many characters as there are, until the buffer is full.
1723 */
1724
1725 /* we will get at least one key. Get more if they are available. */
1726 g_fCBrkPressed = FALSE;
1727
1728#ifdef MCH_WRITE_DUMP
1729 if (fdDump)
1730 fputc('[', fdDump);
1731#endif
1732
1733 /* Keep looping until there is something in the typeahead buffer and more
1734 * to get and still room in the buffer (up to two bytes for a char and
1735 * three bytes for a modifier). */
1736 while ((typeaheadlen == 0 || WaitForChar(0L))
1737 && typeaheadlen + 5 <= TYPEAHEADLEN)
1738 {
1739 if (typebuf_changed(tb_change_cnt))
1740 {
1741 /* "buf" may be invalid now if a client put something in the
1742 * typeahead buffer and "buf" is in the typeahead buffer. */
1743 typeaheadlen = 0;
1744 break;
1745 }
1746#ifdef FEAT_MOUSE
1747 if (g_nMouseClick != -1)
1748 {
1749# ifdef MCH_WRITE_DUMP
1750 if (fdDump)
1751 fprintf(fdDump, "{%02x @ %d, %d}",
1752 g_nMouseClick, g_xMouse, g_yMouse);
1753# endif
1754 typeahead[typeaheadlen++] = ESC + 128;
1755 typeahead[typeaheadlen++] = 'M';
1756 typeahead[typeaheadlen++] = g_nMouseClick;
1757 typeahead[typeaheadlen++] = g_xMouse + '!';
1758 typeahead[typeaheadlen++] = g_yMouse + '!';
1759 g_nMouseClick = -1;
1760 }
1761 else
1762#endif
1763 {
1764 char_u ch2 = NUL;
1765 int modifiers = 0;
1766
1767 c = tgetch(&modifiers, &ch2);
1768
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001769#ifdef FEAT_MBYTE
1770 /* stolen from fill_input_buf() in ui.c */
1771 if (rest != NULL)
1772 {
1773 /* Use remainder of previous call, starts with an invalid
1774 * character that may become valid when reading more. */
1775 if (restlen > TYPEAHEADLEN - typeaheadlen)
1776 unconverted = TYPEAHEADLEN - typeaheadlen;
1777 else
1778 unconverted = restlen;
1779 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1780 if (unconverted == restlen)
1781 {
1782 vim_free(rest);
1783 rest = NULL;
1784 }
1785 else
1786 {
1787 restlen -= unconverted;
1788 mch_memmove(rest, rest + unconverted, restlen);
1789 }
1790 typeaheadlen += unconverted;
1791 }
1792 else
1793 unconverted = 0;
1794#endif
1795
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796 if (typebuf_changed(tb_change_cnt))
1797 {
1798 /* "buf" may be invalid now if a client put something in the
1799 * typeahead buffer and "buf" is in the typeahead buffer. */
1800 typeaheadlen = 0;
1801 break;
1802 }
1803
1804 if (c == Ctrl_C && ctrl_c_interrupts)
1805 {
1806#if defined(FEAT_CLIENTSERVER)
1807 trash_input_buf();
1808#endif
1809 got_int = TRUE;
1810 }
1811
1812#ifdef FEAT_MOUSE
1813 if (g_nMouseClick == -1)
1814#endif
1815 {
1816 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001817 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818
Bram Moolenaar071d4272004-06-13 20:20:40 +00001819 typeahead[typeaheadlen] = c;
1820 if (ch2 != NUL)
1821 {
Bram Moolenaar45500912014-07-09 20:51:07 +02001822 typeahead[typeaheadlen + 1] = 3;
1823 typeahead[typeaheadlen + 2] = ch2;
1824 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 }
1826#ifdef FEAT_MBYTE
1827 /* Only convert normal characters, not special keys. Need to
1828 * convert before applying ALT, otherwise mapping <M-x> breaks
1829 * when 'tenc' is set. */
1830 if (input_conv.vc_type != CONV_NONE
1831 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001832 {
Bram Moolenaar45500912014-07-09 20:51:07 +02001833 conv = TRUE;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001834 typeaheadlen -= unconverted;
1835 n = convert_input_safe(typeahead + typeaheadlen,
1836 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1837 rest == NULL ? &rest : NULL, &restlen);
1838 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001839#endif
1840
Bram Moolenaar45500912014-07-09 20:51:07 +02001841 if (conv)
1842 {
1843 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001844
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001845 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001846 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001847 char_u *e = typeahead + TYPEAHEADLEN;
1848
1849 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001850 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001851 if (*p == K_NUL)
1852 {
1853 ++p;
1854 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1855 *p = 3;
1856 ++n;
1857 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001858 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001859 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001860 }
1861 }
1862
Bram Moolenaar071d4272004-06-13 20:20:40 +00001863 /* Use the ALT key to set the 8th bit of the character
1864 * when it's one byte, the 8th bit isn't set yet and not
1865 * using a double-byte encoding (would become a lead
1866 * byte). */
1867 if ((modifiers & MOD_MASK_ALT)
1868 && n == 1
1869 && (typeahead[typeaheadlen] & 0x80) == 0
1870#ifdef FEAT_MBYTE
1871 && !enc_dbcs
1872#endif
1873 )
1874 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001875#ifdef FEAT_MBYTE
1876 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1877 typeahead + typeaheadlen);
1878#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001880#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881 modifiers &= ~MOD_MASK_ALT;
1882 }
1883
1884 if (modifiers != 0)
1885 {
1886 /* Prepend modifiers to the character. */
1887 mch_memmove(typeahead + typeaheadlen + 3,
1888 typeahead + typeaheadlen, n);
1889 typeahead[typeaheadlen++] = K_SPECIAL;
1890 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1891 typeahead[typeaheadlen++] = modifiers;
1892 }
1893
1894 typeaheadlen += n;
1895
1896#ifdef MCH_WRITE_DUMP
1897 if (fdDump)
1898 fputc(c, fdDump);
1899#endif
1900 }
1901 }
1902 }
1903
1904#ifdef MCH_WRITE_DUMP
1905 if (fdDump)
1906 {
1907 fputs("]\n", fdDump);
1908 fflush(fdDump);
1909 }
1910#endif
1911
Bram Moolenaar071d4272004-06-13 20:20:40 +00001912theend:
1913 /* Move typeahead to "buf", as much as fits. */
1914 len = 0;
1915 while (len < maxlen && typeaheadlen > 0)
1916 {
1917 buf[len++] = typeahead[0];
1918 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1919 }
1920 return len;
1921
1922#else /* FEAT_GUI_W32 */
1923 return 0;
1924#endif /* FEAT_GUI_W32 */
1925}
1926
Bram Moolenaar82881492012-11-20 16:53:39 +01001927#ifndef PROTO
1928# ifndef __MINGW32__
1929# include <shellapi.h> /* required for FindExecutable() */
1930# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001931#endif
1932
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001933/*
1934 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001935 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001936 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001938executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001940 char *dum;
1941 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001942 char *curpath, *newpath;
1943 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001945#ifdef FEAT_MBYTE
1946 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001948 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001949 WCHAR fnamew[_MAX_PATH];
1950 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001951 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001952
1953 if (p != NULL)
1954 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001955 wcurpath = _wgetenv(L"PATH");
1956 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1957 * sizeof(WCHAR));
1958 if (wnewpath == NULL)
1959 return FALSE;
1960 wcscpy(wnewpath, L".;");
1961 wcscat(wnewpath, wcurpath);
1962 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1963 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001964 vim_free(p);
1965 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1966 {
1967 if (n == 0)
1968 return FALSE;
1969 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1970 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001971 if (path != NULL)
1972 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001973 return TRUE;
1974 }
1975 /* Retry with non-wide function (for Windows 98). */
1976 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001978#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001979
1980 curpath = getenv("PATH");
1981 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1982 if (newpath == NULL)
1983 return FALSE;
1984 STRCPY(newpath, ".;");
1985 STRCAT(newpath, curpath);
1986 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1987 vim_free(newpath);
1988 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001989 return FALSE;
1990 if (mch_isdir(fname))
1991 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001992 if (path != NULL)
1993 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001994 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995}
1996
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001997#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001998 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001999/*
2000 * Bad parameter handler.
2001 *
2002 * Certain MS CRT functions will intentionally crash when passed invalid
2003 * parameters to highlight possible security holes. Setting this function as
2004 * the bad parameter handler will prevent the crash.
2005 *
2006 * In debug builds the parameters contain CRT information that might help track
2007 * down the source of a problem, but in non-debug builds the arguments are all
2008 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2009 * worth allowing these to make debugging of issues easier.
2010 */
2011 static void
2012bad_param_handler(const wchar_t *expression,
2013 const wchar_t *function,
2014 const wchar_t *file,
2015 unsigned int line,
2016 uintptr_t pReserved)
2017{
2018}
2019
2020# define SET_INVALID_PARAM_HANDLER \
2021 ((void)_set_invalid_parameter_handler(bad_param_handler))
2022#else
2023# define SET_INVALID_PARAM_HANDLER
2024#endif
2025
Bram Moolenaar071d4272004-06-13 20:20:40 +00002026#ifdef FEAT_GUI_W32
2027
2028/*
2029 * GUI version of mch_init().
2030 */
2031 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002032mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033{
2034#ifndef __MINGW32__
2035 extern int _fmode;
2036#endif
2037
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002038 /* Silently handle invalid parameters to CRT functions */
2039 SET_INVALID_PARAM_HANDLER;
2040
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041 /* Let critical errors result in a failure, not in a dialog box. Required
2042 * for the timestamp test to work on removed floppies. */
2043 SetErrorMode(SEM_FAILCRITICALERRORS);
2044
2045 _fmode = O_BINARY; /* we do our own CR-LF translation */
2046
2047 /* Specify window size. Is there a place to get the default from? */
2048 Rows = 25;
2049 Columns = 80;
2050
2051 /* Look for 'vimrun' */
2052 if (!gui_is_win32s())
2053 {
2054 char_u vimrun_location[_MAX_PATH + 4];
2055
2056 /* First try in same directory as gvim.exe */
2057 STRCPY(vimrun_location, exe_name);
2058 STRCPY(gettail(vimrun_location), "vimrun.exe");
2059 if (mch_getperm(vimrun_location) >= 0)
2060 {
2061 if (*skiptowhite(vimrun_location) != NUL)
2062 {
2063 /* Enclose path with white space in double quotes. */
2064 mch_memmove(vimrun_location + 1, vimrun_location,
2065 STRLEN(vimrun_location) + 1);
2066 *vimrun_location = '"';
2067 STRCPY(gettail(vimrun_location), "vimrun\" ");
2068 }
2069 else
2070 STRCPY(gettail(vimrun_location), "vimrun ");
2071
2072 vimrun_path = (char *)vim_strsave(vimrun_location);
2073 s_dont_use_vimrun = FALSE;
2074 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002075 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002076 s_dont_use_vimrun = FALSE;
2077
2078 /* Don't give the warning for a missing vimrun.exe right now, but only
2079 * when vimrun was supposed to be used. Don't bother people that do
2080 * not need vimrun.exe. */
2081 if (s_dont_use_vimrun)
2082 need_vimrun_warning = TRUE;
2083 }
2084
2085 /*
2086 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2087 * Otherwise the default "findstr /n" is used.
2088 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002089 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002090 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2091
2092#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002093 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002094#endif
2095}
2096
2097
2098#else /* FEAT_GUI_W32 */
2099
2100#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2101#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2102
2103/*
2104 * ClearConsoleBuffer()
2105 * Description:
2106 * Clears the entire contents of the console screen buffer, using the
2107 * specified attribute.
2108 * Returns:
2109 * TRUE on success
2110 */
2111 static BOOL
2112ClearConsoleBuffer(WORD wAttribute)
2113{
2114 CONSOLE_SCREEN_BUFFER_INFO csbi;
2115 COORD coord;
2116 DWORD NumCells, dummy;
2117
2118 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2119 return FALSE;
2120
2121 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2122 coord.X = 0;
2123 coord.Y = 0;
2124 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2125 coord, &dummy))
2126 {
2127 return FALSE;
2128 }
2129 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2130 coord, &dummy))
2131 {
2132 return FALSE;
2133 }
2134
2135 return TRUE;
2136}
2137
2138/*
2139 * FitConsoleWindow()
2140 * Description:
2141 * Checks if the console window will fit within given buffer dimensions.
2142 * Also, if requested, will shrink the window to fit.
2143 * Returns:
2144 * TRUE on success
2145 */
2146 static BOOL
2147FitConsoleWindow(
2148 COORD dwBufferSize,
2149 BOOL WantAdjust)
2150{
2151 CONSOLE_SCREEN_BUFFER_INFO csbi;
2152 COORD dwWindowSize;
2153 BOOL NeedAdjust = FALSE;
2154
2155 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2156 {
2157 /*
2158 * A buffer resize will fail if the current console window does
2159 * not lie completely within that buffer. To avoid this, we might
2160 * have to move and possibly shrink the window.
2161 */
2162 if (csbi.srWindow.Right >= dwBufferSize.X)
2163 {
2164 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2165 if (dwWindowSize.X > dwBufferSize.X)
2166 dwWindowSize.X = dwBufferSize.X;
2167 csbi.srWindow.Right = dwBufferSize.X - 1;
2168 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2169 NeedAdjust = TRUE;
2170 }
2171 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2172 {
2173 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2174 if (dwWindowSize.Y > dwBufferSize.Y)
2175 dwWindowSize.Y = dwBufferSize.Y;
2176 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2177 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2178 NeedAdjust = TRUE;
2179 }
2180 if (NeedAdjust && WantAdjust)
2181 {
2182 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2183 return FALSE;
2184 }
2185 return TRUE;
2186 }
2187
2188 return FALSE;
2189}
2190
2191typedef struct ConsoleBufferStruct
2192{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002193 BOOL IsValid;
2194 CONSOLE_SCREEN_BUFFER_INFO Info;
2195 PCHAR_INFO Buffer;
2196 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197} ConsoleBuffer;
2198
2199/*
2200 * SaveConsoleBuffer()
2201 * Description:
2202 * Saves important information about the console buffer, including the
2203 * actual buffer contents. The saved information is suitable for later
2204 * restoration by RestoreConsoleBuffer().
2205 * Returns:
2206 * TRUE if all information was saved; FALSE otherwise
2207 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2208 */
2209 static BOOL
2210SaveConsoleBuffer(
2211 ConsoleBuffer *cb)
2212{
2213 DWORD NumCells;
2214 COORD BufferCoord;
2215 SMALL_RECT ReadRegion;
2216 WORD Y, Y_incr;
2217
2218 if (cb == NULL)
2219 return FALSE;
2220
2221 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2222 {
2223 cb->IsValid = FALSE;
2224 return FALSE;
2225 }
2226 cb->IsValid = TRUE;
2227
2228 /*
2229 * Allocate a buffer large enough to hold the entire console screen
2230 * buffer. If this ConsoleBuffer structure has already been initialized
2231 * with a buffer of the correct size, then just use that one.
2232 */
2233 if (!cb->IsValid || cb->Buffer == NULL ||
2234 cb->BufferSize.X != cb->Info.dwSize.X ||
2235 cb->BufferSize.Y != cb->Info.dwSize.Y)
2236 {
2237 cb->BufferSize.X = cb->Info.dwSize.X;
2238 cb->BufferSize.Y = cb->Info.dwSize.Y;
2239 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002240 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002241 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2242 if (cb->Buffer == NULL)
2243 return FALSE;
2244 }
2245
2246 /*
2247 * We will now copy the console screen buffer into our buffer.
2248 * ReadConsoleOutput() seems to be limited as far as how much you
2249 * can read at a time. Empirically, this number seems to be about
2250 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2251 * in chunks until it is all copied. The chunks will all have the
2252 * same horizontal characteristics, so initialize them now. The
2253 * height of each chunk will be (12000 / width).
2254 */
2255 BufferCoord.X = 0;
2256 ReadRegion.Left = 0;
2257 ReadRegion.Right = cb->Info.dwSize.X - 1;
2258 Y_incr = 12000 / cb->Info.dwSize.X;
2259 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2260 {
2261 /*
2262 * Read into position (0, Y) in our buffer.
2263 */
2264 BufferCoord.Y = Y;
2265 /*
2266 * Read the region whose top left corner is (0, Y) and whose bottom
2267 * right corner is (width - 1, Y + Y_incr - 1). This should define
2268 * a region of size width by Y_incr. Don't worry if this region is
2269 * too large for the remaining buffer; it will be cropped.
2270 */
2271 ReadRegion.Top = Y;
2272 ReadRegion.Bottom = Y + Y_incr - 1;
2273 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2274 cb->Buffer, /* our buffer */
2275 cb->BufferSize, /* dimensions of our buffer */
2276 BufferCoord, /* offset in our buffer */
2277 &ReadRegion)) /* region to save */
2278 {
2279 vim_free(cb->Buffer);
2280 cb->Buffer = NULL;
2281 return FALSE;
2282 }
2283 }
2284
2285 return TRUE;
2286}
2287
2288/*
2289 * RestoreConsoleBuffer()
2290 * Description:
2291 * Restores important information about the console buffer, including the
2292 * actual buffer contents, if desired. The information to restore is in
2293 * the same format used by SaveConsoleBuffer().
2294 * Returns:
2295 * TRUE on success
2296 */
2297 static BOOL
2298RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002299 ConsoleBuffer *cb,
2300 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002301{
2302 COORD BufferCoord;
2303 SMALL_RECT WriteRegion;
2304
2305 if (cb == NULL || !cb->IsValid)
2306 return FALSE;
2307
2308 /*
2309 * Before restoring the buffer contents, clear the current buffer, and
2310 * restore the cursor position and window information. Doing this now
2311 * prevents old buffer contents from "flashing" onto the screen.
2312 */
2313 if (RestoreScreen)
2314 ClearConsoleBuffer(cb->Info.wAttributes);
2315
2316 FitConsoleWindow(cb->Info.dwSize, TRUE);
2317 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2318 return FALSE;
2319 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2320 return FALSE;
2321
2322 if (!RestoreScreen)
2323 {
2324 /*
2325 * No need to restore the screen buffer contents, so we're done.
2326 */
2327 return TRUE;
2328 }
2329
2330 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2331 return FALSE;
2332 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2333 return FALSE;
2334
2335 /*
2336 * Restore the screen buffer contents.
2337 */
2338 if (cb->Buffer != NULL)
2339 {
2340 BufferCoord.X = 0;
2341 BufferCoord.Y = 0;
2342 WriteRegion.Left = 0;
2343 WriteRegion.Top = 0;
2344 WriteRegion.Right = cb->Info.dwSize.X - 1;
2345 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2346 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2347 cb->Buffer, /* our buffer */
2348 cb->BufferSize, /* dimensions of our buffer */
2349 BufferCoord, /* offset in our buffer */
2350 &WriteRegion)) /* region to restore */
2351 {
2352 return FALSE;
2353 }
2354 }
2355
2356 return TRUE;
2357}
2358
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002359#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360#ifdef FEAT_RESTORE_ORIG_SCREEN
2361static ConsoleBuffer g_cbOrig = { 0 };
2362#endif
2363static ConsoleBuffer g_cbNonTermcap = { 0 };
2364static ConsoleBuffer g_cbTermcap = { 0 };
2365
2366#ifdef FEAT_TITLE
2367#ifdef __BORLANDC__
2368typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2369#else
2370typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2371#endif
2372char g_szOrigTitle[256] = { 0 };
2373HWND g_hWnd = NULL; /* also used in os_mswin.c */
2374static HICON g_hOrigIconSmall = NULL;
2375static HICON g_hOrigIcon = NULL;
2376static HICON g_hVimIcon = NULL;
2377static BOOL g_fCanChangeIcon = FALSE;
2378
2379/* ICON* are not defined in VC++ 4.0 */
2380#ifndef ICON_SMALL
2381#define ICON_SMALL 0
2382#endif
2383#ifndef ICON_BIG
2384#define ICON_BIG 1
2385#endif
2386/*
2387 * GetConsoleIcon()
2388 * Description:
2389 * Attempts to retrieve the small icon and/or the big icon currently in
2390 * use by a given window.
2391 * Returns:
2392 * TRUE on success
2393 */
2394 static BOOL
2395GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002396 HWND hWnd,
2397 HICON *phIconSmall,
2398 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399{
2400 if (hWnd == NULL)
2401 return FALSE;
2402
2403 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002404 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2405 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002407 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2408 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 return TRUE;
2410}
2411
2412/*
2413 * SetConsoleIcon()
2414 * Description:
2415 * Attempts to change the small icon and/or the big icon currently in
2416 * use by a given window.
2417 * Returns:
2418 * TRUE on success
2419 */
2420 static BOOL
2421SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002422 HWND hWnd,
2423 HICON hIconSmall,
2424 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002426 HICON hPrevIconSmall;
2427 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428
2429 if (hWnd == NULL)
2430 return FALSE;
2431
2432 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002433 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2434 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002436 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2437 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438 return TRUE;
2439}
2440
2441/*
2442 * SaveConsoleTitleAndIcon()
2443 * Description:
2444 * Saves the current console window title in g_szOrigTitle, for later
2445 * restoration. Also, attempts to obtain a handle to the console window,
2446 * and use it to save the small and big icons currently in use by the
2447 * console window. This is not always possible on some versions of Windows;
2448 * nor is it possible when running Vim remotely using Telnet (since the
2449 * console window the user sees is owned by a remote process).
2450 */
2451 static void
2452SaveConsoleTitleAndIcon(void)
2453{
2454 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2455
2456 /* Save the original title. */
2457 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2458 return;
2459
2460 /*
2461 * Obtain a handle to the console window using GetConsoleWindow() from
2462 * KERNEL32.DLL; we need to handle in order to change the window icon.
2463 * This function only exists on NT-based Windows, starting with Windows
2464 * 2000. On older operating systems, we can't change the window icon
2465 * anyway.
2466 */
2467 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2468 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2469 "GetConsoleWindow")) != NULL)
2470 {
2471 g_hWnd = (*GetConsoleWindowProc)();
2472 }
2473 if (g_hWnd == NULL)
2474 return;
2475
2476 /* Save the original console window icon. */
2477 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2478 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2479 return;
2480
2481 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002482 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2483 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002484 if (g_hVimIcon != NULL)
2485 g_fCanChangeIcon = TRUE;
2486}
2487#endif
2488
2489static int g_fWindInitCalled = FALSE;
2490static int g_fTermcapMode = FALSE;
2491static CONSOLE_CURSOR_INFO g_cci;
2492static DWORD g_cmodein = 0;
2493static DWORD g_cmodeout = 0;
2494
2495/*
2496 * non-GUI version of mch_init().
2497 */
2498 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002499mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500{
2501#ifndef FEAT_RESTORE_ORIG_SCREEN
2502 CONSOLE_SCREEN_BUFFER_INFO csbi;
2503#endif
2504#ifndef __MINGW32__
2505 extern int _fmode;
2506#endif
2507
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002508 /* Silently handle invalid parameters to CRT functions */
2509 SET_INVALID_PARAM_HANDLER;
2510
Bram Moolenaar071d4272004-06-13 20:20:40 +00002511 /* Let critical errors result in a failure, not in a dialog box. Required
2512 * for the timestamp test to work on removed floppies. */
2513 SetErrorMode(SEM_FAILCRITICALERRORS);
2514
2515 _fmode = O_BINARY; /* we do our own CR-LF translation */
2516 out_flush();
2517
2518 /* Obtain handles for the standard Console I/O devices */
2519 if (read_cmd_fd == 0)
2520 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2521 else
2522 create_conin();
2523 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2524
2525#ifdef FEAT_RESTORE_ORIG_SCREEN
2526 /* Save the initial console buffer for later restoration */
2527 SaveConsoleBuffer(&g_cbOrig);
2528 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2529#else
2530 /* Get current text attributes */
2531 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2532 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2533#endif
2534 if (cterm_normal_fg_color == 0)
2535 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2536 if (cterm_normal_bg_color == 0)
2537 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2538
2539 /* set termcap codes to current text attributes */
2540 update_tcap(g_attrCurrent);
2541
2542 GetConsoleCursorInfo(g_hConOut, &g_cci);
2543 GetConsoleMode(g_hConIn, &g_cmodein);
2544 GetConsoleMode(g_hConOut, &g_cmodeout);
2545
2546#ifdef FEAT_TITLE
2547 SaveConsoleTitleAndIcon();
2548 /*
2549 * Set both the small and big icons of the console window to Vim's icon.
2550 * Note that Vim presently only has one size of icon (32x32), but it
2551 * automatically gets scaled down to 16x16 when setting the small icon.
2552 */
2553 if (g_fCanChangeIcon)
2554 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2555#endif
2556
2557 ui_get_shellsize();
2558
2559#ifdef MCH_WRITE_DUMP
2560 fdDump = fopen("dump", "wt");
2561
2562 if (fdDump)
2563 {
2564 time_t t;
2565
2566 time(&t);
2567 fputs(ctime(&t), fdDump);
2568 fflush(fdDump);
2569 }
2570#endif
2571
2572 g_fWindInitCalled = TRUE;
2573
2574#ifdef FEAT_MOUSE
2575 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2576#endif
2577
2578#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002579 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002580#endif
2581
2582 /* This will be NULL on anything but NT 4.0 */
2583 s_pfnGetConsoleKeyboardLayoutName =
2584 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2585 "GetConsoleKeyboardLayoutNameA");
2586}
2587
2588/*
2589 * non-GUI version of mch_exit().
2590 * Shut down and exit with status `r'
2591 * Careful: mch_exit() may be called before mch_init()!
2592 */
2593 void
2594mch_exit(int r)
2595{
2596 stoptermcap();
2597
2598 if (g_fWindInitCalled)
2599 settmode(TMODE_COOK);
2600
2601 ml_close_all(TRUE); /* remove all memfiles */
2602
2603 if (g_fWindInitCalled)
2604 {
2605#ifdef FEAT_TITLE
2606 mch_restore_title(3);
2607 /*
2608 * Restore both the small and big icons of the console window to
2609 * what they were at startup. Don't do this when the window is
2610 * closed, Vim would hang here.
2611 */
2612 if (g_fCanChangeIcon && !g_fForceExit)
2613 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2614#endif
2615
2616#ifdef MCH_WRITE_DUMP
2617 if (fdDump)
2618 {
2619 time_t t;
2620
2621 time(&t);
2622 fputs(ctime(&t), fdDump);
2623 fclose(fdDump);
2624 }
2625 fdDump = NULL;
2626#endif
2627 }
2628
2629 SetConsoleCursorInfo(g_hConOut, &g_cci);
2630 SetConsoleMode(g_hConIn, g_cmodein);
2631 SetConsoleMode(g_hConOut, g_cmodeout);
2632
2633#ifdef DYNAMIC_GETTEXT
2634 dyn_libintl_end();
2635#endif
2636
2637 exit(r);
2638}
2639#endif /* !FEAT_GUI_W32 */
2640
Bram Moolenaar071d4272004-06-13 20:20:40 +00002641/*
2642 * Do we have an interactive window?
2643 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002644/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002645 int
2646mch_check_win(
2647 int argc,
2648 char **argv)
2649{
2650 get_exe_name();
2651
2652#ifdef FEAT_GUI_W32
2653 return OK; /* GUI always has a tty */
2654#else
2655 if (isatty(1))
2656 return OK;
2657 return FAIL;
2658#endif
2659}
2660
2661
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002662#ifdef FEAT_MBYTE
2663/*
2664 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2665 * if it already exists. When "len" is > 0, also expand short to long
2666 * filenames.
2667 * Return FAIL if wide functions are not available, OK otherwise.
2668 * NOTE: much of this is identical to fname_case(), keep in sync!
2669 */
2670 static int
2671fname_casew(
2672 WCHAR *name,
2673 int len)
2674{
2675 WCHAR szTrueName[_MAX_PATH + 2];
2676 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2677 WCHAR *ptrue, *ptruePrev;
2678 WCHAR *porig, *porigPrev;
2679 int flen;
2680 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002681 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002682 int c;
2683 int slen;
2684
2685 flen = (int)wcslen(name);
2686 if (flen > _MAX_PATH)
2687 return OK;
2688
2689 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2690
2691 /* Build the new name in szTrueName[] one component at a time. */
2692 porig = name;
2693 ptrue = szTrueName;
2694
2695 if (iswalpha(porig[0]) && porig[1] == L':')
2696 {
2697 /* copy leading drive letter */
2698 *ptrue++ = *porig++;
2699 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002700 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002701 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002702
2703 while (*porig != NUL)
2704 {
2705 /* copy \ characters */
2706 while (*porig == psepc)
2707 *ptrue++ = *porig++;
2708
2709 ptruePrev = ptrue;
2710 porigPrev = porig;
2711 while (*porig != NUL && *porig != psepc)
2712 {
2713 *ptrue++ = *porig++;
2714 }
2715 *ptrue = NUL;
2716
2717 /* To avoid a slow failure append "\*" when searching a directory,
2718 * server or network share. */
2719 wcscpy(szTrueNameTemp, szTrueName);
2720 slen = (int)wcslen(szTrueNameTemp);
2721 if (*porig == psepc && slen + 2 < _MAX_PATH)
2722 wcscpy(szTrueNameTemp + slen, L"\\*");
2723
2724 /* Skip "", "." and "..". */
2725 if (ptrue > ptruePrev
2726 && (ptruePrev[0] != L'.'
2727 || (ptruePrev[1] != NUL
2728 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2729 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2730 != INVALID_HANDLE_VALUE)
2731 {
2732 c = *porig;
2733 *porig = NUL;
2734
2735 /* Only use the match when it's the same name (ignoring case) or
2736 * expansion is allowed and there is a match with the short name
2737 * and there is enough room. */
2738 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2739 || (len > 0
2740 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2741 && (int)(ptruePrev - szTrueName)
2742 + (int)wcslen(fb.cFileName) < len)))
2743 {
2744 wcscpy(ptruePrev, fb.cFileName);
2745
2746 /* Look for exact match and prefer it if found. Must be a
2747 * long name, otherwise there would be only one match. */
2748 while (FindNextFileW(hFind, &fb))
2749 {
2750 if (*fb.cAlternateFileName != NUL
2751 && (wcscoll(porigPrev, fb.cFileName) == 0
2752 || (len > 0
2753 && (_wcsicoll(porigPrev,
2754 fb.cAlternateFileName) == 0
2755 && (int)(ptruePrev - szTrueName)
2756 + (int)wcslen(fb.cFileName) < len))))
2757 {
2758 wcscpy(ptruePrev, fb.cFileName);
2759 break;
2760 }
2761 }
2762 }
2763 FindClose(hFind);
2764 *porig = c;
2765 ptrue = ptruePrev + wcslen(ptruePrev);
2766 }
2767 else if (hFind == INVALID_HANDLE_VALUE
2768 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2769 return FAIL;
2770 }
2771
2772 wcscpy(name, szTrueName);
2773 return OK;
2774}
2775#endif
2776
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777/*
2778 * fname_case(): Set the case of the file name, if it already exists.
2779 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002780 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002781 */
2782 void
2783fname_case(
2784 char_u *name,
2785 int len)
2786{
2787 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002788 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002789 char *ptrue, *ptruePrev;
2790 char *porig, *porigPrev;
2791 int flen;
2792 WIN32_FIND_DATA fb;
2793 HANDLE hFind;
2794 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002795 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002796
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002797 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002798 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002799 return;
2800
2801 slash_adjust(name);
2802
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002803#ifdef FEAT_MBYTE
2804 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2805 {
2806 WCHAR *p = enc_to_utf16(name, NULL);
2807
2808 if (p != NULL)
2809 {
2810 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002811 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002812
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002813 wcsncpy(buf, p, _MAX_PATH);
2814 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002815 vim_free(p);
2816
2817 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2818 {
2819 q = utf16_to_enc(buf, NULL);
2820 if (q != NULL)
2821 {
2822 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2823 vim_free(q);
2824 return;
2825 }
2826 }
2827 }
2828 /* Retry with non-wide function (for Windows 98). */
2829 }
2830#endif
2831
2832 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2833 * So we should check this after calling wide function. */
2834 if (flen > _MAX_PATH)
2835 return;
2836
Bram Moolenaar071d4272004-06-13 20:20:40 +00002837 /* Build the new name in szTrueName[] one component at a time. */
2838 porig = name;
2839 ptrue = szTrueName;
2840
2841 if (isalpha(porig[0]) && porig[1] == ':')
2842 {
2843 /* copy leading drive letter */
2844 *ptrue++ = *porig++;
2845 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002847 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848
2849 while (*porig != NUL)
2850 {
2851 /* copy \ characters */
2852 while (*porig == psepc)
2853 *ptrue++ = *porig++;
2854
2855 ptruePrev = ptrue;
2856 porigPrev = porig;
2857 while (*porig != NUL && *porig != psepc)
2858 {
2859#ifdef FEAT_MBYTE
2860 int l;
2861
2862 if (enc_dbcs)
2863 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002864 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865 while (--l >= 0)
2866 *ptrue++ = *porig++;
2867 }
2868 else
2869#endif
2870 *ptrue++ = *porig++;
2871 }
2872 *ptrue = NUL;
2873
Bram Moolenaar464c9252010-10-13 20:37:41 +02002874 /* To avoid a slow failure append "\*" when searching a directory,
2875 * server or network share. */
2876 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002877 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002878 if (*porig == psepc && slen + 2 < _MAX_PATH)
2879 STRCPY(szTrueNameTemp + slen, "\\*");
2880
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 /* Skip "", "." and "..". */
2882 if (ptrue > ptruePrev
2883 && (ptruePrev[0] != '.'
2884 || (ptruePrev[1] != NUL
2885 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002886 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002887 != INVALID_HANDLE_VALUE)
2888 {
2889 c = *porig;
2890 *porig = NUL;
2891
2892 /* Only use the match when it's the same name (ignoring case) or
2893 * expansion is allowed and there is a match with the short name
2894 * and there is enough room. */
2895 if (_stricoll(porigPrev, fb.cFileName) == 0
2896 || (len > 0
2897 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2898 && (int)(ptruePrev - szTrueName)
2899 + (int)strlen(fb.cFileName) < len)))
2900 {
2901 STRCPY(ptruePrev, fb.cFileName);
2902
2903 /* Look for exact match and prefer it if found. Must be a
2904 * long name, otherwise there would be only one match. */
2905 while (FindNextFile(hFind, &fb))
2906 {
2907 if (*fb.cAlternateFileName != NUL
2908 && (strcoll(porigPrev, fb.cFileName) == 0
2909 || (len > 0
2910 && (_stricoll(porigPrev,
2911 fb.cAlternateFileName) == 0
2912 && (int)(ptruePrev - szTrueName)
2913 + (int)strlen(fb.cFileName) < len))))
2914 {
2915 STRCPY(ptruePrev, fb.cFileName);
2916 break;
2917 }
2918 }
2919 }
2920 FindClose(hFind);
2921 *porig = c;
2922 ptrue = ptruePrev + strlen(ptruePrev);
2923 }
2924 }
2925
2926 STRCPY(name, szTrueName);
2927}
2928
2929
2930/*
2931 * Insert user name in s[len].
2932 */
2933 int
2934mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002935 char_u *s,
2936 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002938 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002939 DWORD cch = sizeof szUserName;
2940
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002941#ifdef FEAT_MBYTE
2942 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2943 {
2944 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2945 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2946
2947 if (GetUserNameW(wszUserName, &wcch))
2948 {
2949 char_u *p = utf16_to_enc(wszUserName, NULL);
2950
2951 if (p != NULL)
2952 {
2953 vim_strncpy(s, p, len - 1);
2954 vim_free(p);
2955 return OK;
2956 }
2957 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002958 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2959 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002960 /* Retry with non-wide function (for Windows 98). */
2961 }
2962#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963 if (GetUserName(szUserName, &cch))
2964 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002965 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966 return OK;
2967 }
2968 s[0] = NUL;
2969 return FAIL;
2970}
2971
2972
2973/*
2974 * Insert host name in s[len].
2975 */
2976 void
2977mch_get_host_name(
2978 char_u *s,
2979 int len)
2980{
2981 DWORD cch = len;
2982
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002983#ifdef FEAT_MBYTE
2984 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2985 {
2986 WCHAR wszHostName[256 + 1];
2987 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2988
2989 if (GetComputerNameW(wszHostName, &wcch))
2990 {
2991 char_u *p = utf16_to_enc(wszHostName, NULL);
2992
2993 if (p != NULL)
2994 {
2995 vim_strncpy(s, p, len - 1);
2996 vim_free(p);
2997 return;
2998 }
2999 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003000 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3001 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003002 /* Retry with non-wide function (for Windows 98). */
3003 }
3004#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003005 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003006 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003007}
3008
3009
3010/*
3011 * return process ID
3012 */
3013 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003014mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015{
3016 return (long)GetCurrentProcessId();
3017}
3018
3019
3020/*
3021 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3022 * Return OK for success, FAIL for failure.
3023 */
3024 int
3025mch_dirname(
3026 char_u *buf,
3027 int len)
3028{
3029 /*
3030 * Originally this was:
3031 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3032 * But the Win32s known bug list says that getcwd() doesn't work
3033 * so use the Win32 system call instead. <Negri>
3034 */
3035#ifdef FEAT_MBYTE
3036 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3037 {
3038 WCHAR wbuf[_MAX_PATH + 1];
3039
3040 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3041 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003042 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043
3044 if (p != NULL)
3045 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003046 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047 vim_free(p);
3048 return OK;
3049 }
3050 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003051 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3052 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053 /* Retry with non-wide function (for Windows 98). */
3054 }
3055#endif
3056 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3057}
3058
3059/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003060 * Get file permissions for "name".
3061 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003062 */
3063 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003064mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003066 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003067 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003069 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003070 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071}
3072
3073
3074/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003075 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003076 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003077 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078 */
3079 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003080mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003082 long n = -1;
3083
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084#ifdef FEAT_MBYTE
3085 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3086 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003087 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003088
3089 if (p != NULL)
3090 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003091 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003092 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003093 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003094 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095 /* Retry with non-wide function (for Windows 98). */
3096 }
3097 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003098 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003100 n = _chmod(name, perm);
3101 if (n == -1)
3102 return FAIL;
3103
3104 win32_set_archive(name);
3105
3106 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107}
3108
3109/*
3110 * Set hidden flag for "name".
3111 */
3112 void
3113mch_hide(char_u *name)
3114{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003115 int attrs = win32_getattrs(name);
3116 if (attrs == -1)
3117 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003119 attrs |= FILE_ATTRIBUTE_HIDDEN;
3120 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003121}
3122
3123/*
3124 * return TRUE if "name" is a directory
3125 * return FALSE if "name" is not a directory or upon error
3126 */
3127 int
3128mch_isdir(char_u *name)
3129{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003130 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003131
3132 if (f == -1)
3133 return FALSE; /* file does not exist at all */
3134
3135 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3136}
3137
3138/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003139 * Create directory "name".
3140 * Return 0 on success, -1 on error.
3141 */
3142 int
3143mch_mkdir(char_u *name)
3144{
3145#ifdef FEAT_MBYTE
3146 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3147 {
3148 WCHAR *p;
3149 int retval;
3150
3151 p = enc_to_utf16(name, NULL);
3152 if (p == NULL)
3153 return -1;
3154 retval = _wmkdir(p);
3155 vim_free(p);
3156 return retval;
3157 }
3158#endif
3159 return _mkdir(name);
3160}
3161
3162/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003163 * Return TRUE if file "fname" has more than one link.
3164 */
3165 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003166mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003167{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003168 BY_HANDLE_FILE_INFORMATION info;
3169
3170 return win32_fileinfo(fname, &info) == FILEINFO_OK
3171 && info.nNumberOfLinks > 1;
3172}
3173
3174/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003175 * Return TRUE if file "fname" is a symbolic link.
3176 */
3177 int
3178mch_is_symbolic_link(char_u *fname)
3179{
3180 HANDLE hFind;
3181 int res = FALSE;
3182 WIN32_FIND_DATAA findDataA;
3183 DWORD fileFlags = 0, reparseTag = 0;
3184#ifdef FEAT_MBYTE
3185 WCHAR *wn = NULL;
3186 WIN32_FIND_DATAW findDataW;
3187
3188 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3189 wn = enc_to_utf16(fname, NULL);
3190 if (wn != NULL)
3191 {
3192 hFind = FindFirstFileW(wn, &findDataW);
3193 vim_free(wn);
3194 if (hFind == INVALID_HANDLE_VALUE
3195 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3196 {
3197 /* Retry with non-wide function (for Windows 98). */
3198 hFind = FindFirstFile(fname, &findDataA);
3199 if (hFind != INVALID_HANDLE_VALUE)
3200 {
3201 fileFlags = findDataA.dwFileAttributes;
3202 reparseTag = findDataA.dwReserved0;
3203 }
3204 }
3205 else
3206 {
3207 fileFlags = findDataW.dwFileAttributes;
3208 reparseTag = findDataW.dwReserved0;
3209 }
3210 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003211 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003212#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003213 {
3214 hFind = FindFirstFile(fname, &findDataA);
3215 if (hFind != INVALID_HANDLE_VALUE)
3216 {
3217 fileFlags = findDataA.dwFileAttributes;
3218 reparseTag = findDataA.dwReserved0;
3219 }
3220 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003221
3222 if (hFind != INVALID_HANDLE_VALUE)
3223 FindClose(hFind);
3224
3225 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3226 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3227 res = TRUE;
3228
3229 return res;
3230}
3231
3232/*
3233 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3234 * link.
3235 */
3236 int
3237mch_is_linked(char_u *fname)
3238{
3239 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3240 return TRUE;
3241 return FALSE;
3242}
3243
3244/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003245 * Get the by-handle-file-information for "fname".
3246 * Returns FILEINFO_OK when OK.
3247 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3248 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3249 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3250 */
3251 int
3252win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3253{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003254 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003255 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003256#ifdef FEAT_MBYTE
3257 WCHAR *wn = NULL;
3258
3259 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003260 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003261 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003262 if (wn == NULL)
3263 res = FILEINFO_ENC_FAIL;
3264 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003265 if (wn != NULL)
3266 {
3267 hFile = CreateFileW(wn, /* file name */
3268 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003269 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003270 NULL, /* security descriptor */
3271 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003272 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003273 NULL); /* handle to template file */
3274 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003275 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003276 {
3277 /* Retry with non-wide function (for Windows 98). */
3278 vim_free(wn);
3279 wn = NULL;
3280 }
3281 }
3282 if (wn == NULL)
3283#endif
3284 hFile = CreateFile(fname, /* file name */
3285 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003286 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003287 NULL, /* security descriptor */
3288 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003289 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003290 NULL); /* handle to template file */
3291
3292 if (hFile != INVALID_HANDLE_VALUE)
3293 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003294 if (GetFileInformationByHandle(hFile, info) != 0)
3295 res = FILEINFO_OK;
3296 else
3297 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003298 CloseHandle(hFile);
3299 }
3300
3301#ifdef FEAT_MBYTE
3302 vim_free(wn);
3303#endif
3304 return res;
3305}
3306
3307/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003308 * get file attributes for `name'
3309 * -1 : error
3310 * else FILE_ATTRIBUTE_* defined in winnt.h
3311 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003312 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003313win32_getattrs(char_u *name)
3314{
3315 int attr;
3316#ifdef FEAT_MBYTE
3317 WCHAR *p = NULL;
3318
3319 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3320 p = enc_to_utf16(name, NULL);
3321
3322 if (p != NULL)
3323 {
3324 attr = GetFileAttributesW(p);
3325 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3326 {
3327 /* Retry with non-wide function (for Windows 98). */
3328 vim_free(p);
3329 p = NULL;
3330 }
3331 }
3332 if (p == NULL)
3333#endif
3334 attr = GetFileAttributes((char *)name);
3335#ifdef FEAT_MBYTE
3336 vim_free(p);
3337#endif
3338 return attr;
3339}
3340
3341/*
3342 * set file attributes for `name' to `attrs'
3343 *
3344 * return -1 for failure, 0 otherwise
3345 */
3346 static
3347 int
3348win32_setattrs(char_u *name, int attrs)
3349{
3350 int res;
3351#ifdef FEAT_MBYTE
3352 WCHAR *p = NULL;
3353
3354 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3355 p = enc_to_utf16(name, NULL);
3356
3357 if (p != NULL)
3358 {
3359 res = SetFileAttributesW(p, attrs);
3360 if (res == FALSE
3361 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3362 {
3363 /* Retry with non-wide function (for Windows 98). */
3364 vim_free(p);
3365 p = NULL;
3366 }
3367 }
3368 if (p == NULL)
3369#endif
3370 res = SetFileAttributes((char *)name, attrs);
3371#ifdef FEAT_MBYTE
3372 vim_free(p);
3373#endif
3374 return res ? 0 : -1;
3375}
3376
3377/*
3378 * Set archive flag for "name".
3379 */
3380 static
3381 int
3382win32_set_archive(char_u *name)
3383{
3384 int attrs = win32_getattrs(name);
3385 if (attrs == -1)
3386 return -1;
3387
3388 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3389 return win32_setattrs(name, attrs);
3390}
3391
3392/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003393 * Return TRUE if file or directory "name" is writable (not readonly).
3394 * Strange semantics of Win32: a readonly directory is writable, but you can't
3395 * delete a file. Let's say this means it is writable.
3396 */
3397 int
3398mch_writable(char_u *name)
3399{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003400 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003401
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003402 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3403 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003404}
3405
Bram Moolenaar071d4272004-06-13 20:20:40 +00003406/*
3407 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003408 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003409 * Return -1 if unknown.
3410 */
3411 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003412mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003414 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003415 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003416 char_u *p;
3417
3418 if (len >= _MAX_PATH) /* safety check */
3419 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003420 if (!use_path)
3421 {
3422 /* TODO: check if file is really executable. */
3423 return mch_getperm(name) != -1 && !mch_isdir(name);
3424 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003425
3426 /* If there already is an extension try using the name directly. Also do
3427 * this with a Unix-shell like 'shell'. */
3428 if (vim_strchr(gettail(name), '.') != NULL
3429 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003430 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003431 return TRUE;
3432
3433 /*
3434 * Loop over all extensions in $PATHEXT.
3435 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003436 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003437 p = mch_getenv("PATHEXT");
3438 if (p == NULL)
3439 p = (char_u *)".com;.exe;.bat;.cmd";
3440 while (*p)
3441 {
3442 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3443 {
3444 /* A single "." means no extension is added. */
3445 buf[len] = NUL;
3446 ++p;
3447 if (*p)
3448 ++p;
3449 }
3450 else
3451 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003452 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003453 return TRUE;
3454 }
3455 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003456}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457
3458/*
3459 * Check what "name" is:
3460 * NODE_NORMAL: file or directory (or doesn't exist)
3461 * NODE_WRITABLE: writable device, socket, fifo, etc.
3462 * NODE_OTHER: non-writable things
3463 */
3464 int
3465mch_nodetype(char_u *name)
3466{
3467 HANDLE hFile;
3468 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003469#ifdef FEAT_MBYTE
3470 WCHAR *wn = NULL;
3471#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472
Bram Moolenaar043545e2006-10-10 16:44:07 +00003473 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3474 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3475 * here. */
3476 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3477 return NODE_WRITABLE;
3478
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003479#ifdef FEAT_MBYTE
3480 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3481 {
3482 wn = enc_to_utf16(name, NULL);
3483 if (wn != NULL)
3484 {
3485 hFile = CreateFileW(wn, /* file name */
3486 GENERIC_WRITE, /* access mode */
3487 0, /* share mode */
3488 NULL, /* security descriptor */
3489 OPEN_EXISTING, /* creation disposition */
3490 0, /* file attributes */
3491 NULL); /* handle to template file */
3492 if (hFile == INVALID_HANDLE_VALUE
3493 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3494 {
3495 /* Retry with non-wide function (for Windows 98). */
3496 vim_free(wn);
3497 wn = NULL;
3498 }
3499 }
3500 }
3501 if (wn == NULL)
3502#endif
3503 hFile = CreateFile(name, /* file name */
3504 GENERIC_WRITE, /* access mode */
3505 0, /* share mode */
3506 NULL, /* security descriptor */
3507 OPEN_EXISTING, /* creation disposition */
3508 0, /* file attributes */
3509 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003511#ifdef FEAT_MBYTE
3512 vim_free(wn);
3513#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514 if (hFile == INVALID_HANDLE_VALUE)
3515 return NODE_NORMAL;
3516
3517 type = GetFileType(hFile);
3518 CloseHandle(hFile);
3519 if (type == FILE_TYPE_CHAR)
3520 return NODE_WRITABLE;
3521 if (type == FILE_TYPE_DISK)
3522 return NODE_NORMAL;
3523 return NODE_OTHER;
3524}
3525
3526#ifdef HAVE_ACL
3527struct my_acl
3528{
3529 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3530 PSID pSidOwner;
3531 PSID pSidGroup;
3532 PACL pDacl;
3533 PACL pSacl;
3534};
3535#endif
3536
3537/*
3538 * Return a pointer to the ACL of file "fname" in allocated memory.
3539 * Return NULL if the ACL is not available for whatever reason.
3540 */
3541 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003542mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003543{
3544#ifndef HAVE_ACL
3545 return (vim_acl_T)NULL;
3546#else
3547 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003548 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003549
3550 /* This only works on Windows NT and 2000. */
3551 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3552 {
3553 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3554 if (p != NULL)
3555 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003556# ifdef FEAT_MBYTE
3557 WCHAR *wn = NULL;
3558
3559 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3560 wn = enc_to_utf16(fname, NULL);
3561 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003562 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003563 /* Try to retrieve the entire security descriptor. */
3564 err = pGetNamedSecurityInfoW(
3565 wn, // Abstract filename
3566 SE_FILE_OBJECT, // File Object
3567 OWNER_SECURITY_INFORMATION |
3568 GROUP_SECURITY_INFORMATION |
3569 DACL_SECURITY_INFORMATION |
3570 SACL_SECURITY_INFORMATION,
3571 &p->pSidOwner, // Ownership information.
3572 &p->pSidGroup, // Group membership.
3573 &p->pDacl, // Discretionary information.
3574 &p->pSacl, // For auditing purposes.
3575 &p->pSecurityDescriptor);
3576 if (err == ERROR_ACCESS_DENIED ||
3577 err == ERROR_PRIVILEGE_NOT_HELD)
3578 {
3579 /* Retrieve only DACL. */
3580 (void)pGetNamedSecurityInfoW(
3581 wn,
3582 SE_FILE_OBJECT,
3583 DACL_SECURITY_INFORMATION,
3584 NULL,
3585 NULL,
3586 &p->pDacl,
3587 NULL,
3588 &p->pSecurityDescriptor);
3589 }
3590 if (p->pSecurityDescriptor == NULL)
3591 {
3592 mch_free_acl((vim_acl_T)p);
3593 p = NULL;
3594 }
3595 vim_free(wn);
3596 }
3597 else
3598# endif
3599 {
3600 /* Try to retrieve the entire security descriptor. */
3601 err = pGetNamedSecurityInfo(
3602 (LPSTR)fname, // Abstract filename
3603 SE_FILE_OBJECT, // File Object
3604 OWNER_SECURITY_INFORMATION |
3605 GROUP_SECURITY_INFORMATION |
3606 DACL_SECURITY_INFORMATION |
3607 SACL_SECURITY_INFORMATION,
3608 &p->pSidOwner, // Ownership information.
3609 &p->pSidGroup, // Group membership.
3610 &p->pDacl, // Discretionary information.
3611 &p->pSacl, // For auditing purposes.
3612 &p->pSecurityDescriptor);
3613 if (err == ERROR_ACCESS_DENIED ||
3614 err == ERROR_PRIVILEGE_NOT_HELD)
3615 {
3616 /* Retrieve only DACL. */
3617 (void)pGetNamedSecurityInfo(
3618 (LPSTR)fname,
3619 SE_FILE_OBJECT,
3620 DACL_SECURITY_INFORMATION,
3621 NULL,
3622 NULL,
3623 &p->pDacl,
3624 NULL,
3625 &p->pSecurityDescriptor);
3626 }
3627 if (p->pSecurityDescriptor == NULL)
3628 {
3629 mch_free_acl((vim_acl_T)p);
3630 p = NULL;
3631 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003632 }
3633 }
3634 }
3635
3636 return (vim_acl_T)p;
3637#endif
3638}
3639
Bram Moolenaar27515922013-06-29 15:36:26 +02003640#ifdef HAVE_ACL
3641/*
3642 * Check if "acl" contains inherited ACE.
3643 */
3644 static BOOL
3645is_acl_inherited(PACL acl)
3646{
3647 DWORD i;
3648 ACL_SIZE_INFORMATION acl_info;
3649 PACCESS_ALLOWED_ACE ace;
3650
3651 acl_info.AceCount = 0;
3652 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3653 for (i = 0; i < acl_info.AceCount; i++)
3654 {
3655 GetAce(acl, i, (LPVOID *)&ace);
3656 if (ace->Header.AceFlags & INHERITED_ACE)
3657 return TRUE;
3658 }
3659 return FALSE;
3660}
3661#endif
3662
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663/*
3664 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3665 * Errors are ignored.
3666 * This must only be called with "acl" equal to what mch_get_acl() returned.
3667 */
3668 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003669mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670{
3671#ifdef HAVE_ACL
3672 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003673 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674
3675 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003676 {
3677# ifdef FEAT_MBYTE
3678 WCHAR *wn = NULL;
3679# endif
3680
3681 /* Set security flags */
3682 if (p->pSidOwner)
3683 sec_info |= OWNER_SECURITY_INFORMATION;
3684 if (p->pSidGroup)
3685 sec_info |= GROUP_SECURITY_INFORMATION;
3686 if (p->pDacl)
3687 {
3688 sec_info |= DACL_SECURITY_INFORMATION;
3689 /* Do not inherit its parent's DACL.
3690 * If the DACL is inherited, Cygwin permissions would be changed.
3691 */
3692 if (!is_acl_inherited(p->pDacl))
3693 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3694 }
3695 if (p->pSacl)
3696 sec_info |= SACL_SECURITY_INFORMATION;
3697
3698# ifdef FEAT_MBYTE
3699 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3700 wn = enc_to_utf16(fname, NULL);
3701 if (wn != NULL)
3702 {
3703 (void)pSetNamedSecurityInfoW(
3704 wn, // Abstract filename
3705 SE_FILE_OBJECT, // File Object
3706 sec_info,
3707 p->pSidOwner, // Ownership information.
3708 p->pSidGroup, // Group membership.
3709 p->pDacl, // Discretionary information.
3710 p->pSacl // For auditing purposes.
3711 );
3712 vim_free(wn);
3713 }
3714 else
3715# endif
3716 {
3717 (void)pSetNamedSecurityInfo(
3718 (LPSTR)fname, // Abstract filename
3719 SE_FILE_OBJECT, // File Object
3720 sec_info,
3721 p->pSidOwner, // Ownership information.
3722 p->pSidGroup, // Group membership.
3723 p->pDacl, // Discretionary information.
3724 p->pSacl // For auditing purposes.
3725 );
3726 }
3727 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728#endif
3729}
3730
3731 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003732mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003733{
3734#ifdef HAVE_ACL
3735 struct my_acl *p = (struct my_acl *)acl;
3736
3737 if (p != NULL)
3738 {
3739 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3740 vim_free(p);
3741 }
3742#endif
3743}
3744
3745#ifndef FEAT_GUI_W32
3746
3747/*
3748 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3749 */
3750 static BOOL WINAPI
3751handler_routine(
3752 DWORD dwCtrlType)
3753{
3754 switch (dwCtrlType)
3755 {
3756 case CTRL_C_EVENT:
3757 if (ctrl_c_interrupts)
3758 g_fCtrlCPressed = TRUE;
3759 return TRUE;
3760
3761 case CTRL_BREAK_EVENT:
3762 g_fCBrkPressed = TRUE;
3763 return TRUE;
3764
3765 /* fatal events: shut down gracefully */
3766 case CTRL_CLOSE_EVENT:
3767 case CTRL_LOGOFF_EVENT:
3768 case CTRL_SHUTDOWN_EVENT:
3769 windgoto((int)Rows - 1, 0);
3770 g_fForceExit = TRUE;
3771
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003772 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003773 (dwCtrlType == CTRL_CLOSE_EVENT
3774 ? _("close")
3775 : dwCtrlType == CTRL_LOGOFF_EVENT
3776 ? _("logoff")
3777 : _("shutdown")));
3778#ifdef DEBUG
3779 OutputDebugString(IObuff);
3780#endif
3781
3782 preserve_exit(); /* output IObuff, preserve files and exit */
3783
3784 return TRUE; /* not reached */
3785
3786 default:
3787 return FALSE;
3788 }
3789}
3790
3791
3792/*
3793 * set the tty in (raw) ? "raw" : "cooked" mode
3794 */
3795 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003796mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003797{
3798 DWORD cmodein;
3799 DWORD cmodeout;
3800 BOOL bEnableHandler;
3801
3802 GetConsoleMode(g_hConIn, &cmodein);
3803 GetConsoleMode(g_hConOut, &cmodeout);
3804 if (tmode == TMODE_RAW)
3805 {
3806 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3807 ENABLE_ECHO_INPUT);
3808#ifdef FEAT_MOUSE
3809 if (g_fMouseActive)
3810 cmodein |= ENABLE_MOUSE_INPUT;
3811#endif
3812 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3813 bEnableHandler = TRUE;
3814 }
3815 else /* cooked */
3816 {
3817 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3818 ENABLE_ECHO_INPUT);
3819 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3820 bEnableHandler = FALSE;
3821 }
3822 SetConsoleMode(g_hConIn, cmodein);
3823 SetConsoleMode(g_hConOut, cmodeout);
3824 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3825
3826#ifdef MCH_WRITE_DUMP
3827 if (fdDump)
3828 {
3829 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3830 tmode == TMODE_RAW ? "raw" :
3831 tmode == TMODE_COOK ? "cooked" : "normal",
3832 cmodein, cmodeout);
3833 fflush(fdDump);
3834 }
3835#endif
3836}
3837
3838
3839/*
3840 * Get the size of the current window in `Rows' and `Columns'
3841 * Return OK when size could be determined, FAIL otherwise.
3842 */
3843 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003844mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003845{
3846 CONSOLE_SCREEN_BUFFER_INFO csbi;
3847
3848 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3849 {
3850 /*
3851 * For some reason, we are trying to get the screen dimensions
3852 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3853 * variables are really intended to mean the size of Vim screen
3854 * while in termcap mode.
3855 */
3856 Rows = g_cbTermcap.Info.dwSize.Y;
3857 Columns = g_cbTermcap.Info.dwSize.X;
3858 }
3859 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3860 {
3861 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3862 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3863 }
3864 else
3865 {
3866 Rows = 25;
3867 Columns = 80;
3868 }
3869 return OK;
3870}
3871
3872/*
3873 * Set a console window to `xSize' * `ySize'
3874 */
3875 static void
3876ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003877 HANDLE hConsole,
3878 int xSize,
3879 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003880{
3881 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3882 SMALL_RECT srWindowRect; /* hold the new console size */
3883 COORD coordScreen;
3884
3885#ifdef MCH_WRITE_DUMP
3886 if (fdDump)
3887 {
3888 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3889 fflush(fdDump);
3890 }
3891#endif
3892
3893 /* get the largest size we can size the console window to */
3894 coordScreen = GetLargestConsoleWindowSize(hConsole);
3895
3896 /* define the new console window size and scroll position */
3897 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3898 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3899 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3900
3901 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3902 {
3903 int sx, sy;
3904
3905 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3906 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3907 if (sy < ySize || sx < xSize)
3908 {
3909 /*
3910 * Increasing number of lines/columns, do buffer first.
3911 * Use the maximal size in x and y direction.
3912 */
3913 if (sy < ySize)
3914 coordScreen.Y = ySize;
3915 else
3916 coordScreen.Y = sy;
3917 if (sx < xSize)
3918 coordScreen.X = xSize;
3919 else
3920 coordScreen.X = sx;
3921 SetConsoleScreenBufferSize(hConsole, coordScreen);
3922 }
3923 }
3924
3925 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3926 {
3927#ifdef MCH_WRITE_DUMP
3928 if (fdDump)
3929 {
3930 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3931 GetLastError());
3932 fflush(fdDump);
3933 }
3934#endif
3935 }
3936
3937 /* define the new console buffer size */
3938 coordScreen.X = xSize;
3939 coordScreen.Y = ySize;
3940
3941 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3942 {
3943#ifdef MCH_WRITE_DUMP
3944 if (fdDump)
3945 {
3946 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3947 GetLastError());
3948 fflush(fdDump);
3949 }
3950#endif
3951 }
3952}
3953
3954
3955/*
3956 * Set the console window to `Rows' * `Columns'
3957 */
3958 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003959mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960{
3961 COORD coordScreen;
3962
3963 /* Don't change window size while still starting up */
3964 if (suppress_winsize != 0)
3965 {
3966 suppress_winsize = 2;
3967 return;
3968 }
3969
3970 if (term_console)
3971 {
3972 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3973
3974 /* Clamp Rows and Columns to reasonable values */
3975 if (Rows > coordScreen.Y)
3976 Rows = coordScreen.Y;
3977 if (Columns > coordScreen.X)
3978 Columns = coordScreen.X;
3979
3980 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3981 }
3982}
3983
3984/*
3985 * Rows and/or Columns has changed.
3986 */
3987 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003988mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003989{
3990 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3991}
3992
3993
3994/*
3995 * Called when started up, to set the winsize that was delayed.
3996 */
3997 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003998mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003999{
4000 if (suppress_winsize == 2)
4001 {
4002 suppress_winsize = 0;
4003 mch_set_shellsize();
4004 shell_resized();
4005 }
4006 suppress_winsize = 0;
4007}
4008#endif /* FEAT_GUI_W32 */
4009
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004010 static BOOL
4011vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004012 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004013 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004014 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004015 STARTUPINFO *si,
4016 PROCESS_INFORMATION *pi)
4017{
4018# ifdef FEAT_MBYTE
4019 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4020 {
4021 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4022
4023 if (wcmd != NULL)
4024 {
4025 BOOL ret;
4026 ret = CreateProcessW(
4027 NULL, /* Executable name */
4028 wcmd, /* Command to execute */
4029 NULL, /* Process security attributes */
4030 NULL, /* Thread security attributes */
4031 inherit_handles, /* Inherit handles */
4032 flags, /* Creation flags */
4033 NULL, /* Environment */
4034 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004035 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004036 pi); /* Process information */
4037 vim_free(wcmd);
4038 return ret;
4039 }
4040 }
4041#endif
4042 return CreateProcess(
4043 NULL, /* Executable name */
4044 cmd, /* Command to execute */
4045 NULL, /* Process security attributes */
4046 NULL, /* Thread security attributes */
4047 inherit_handles, /* Inherit handles */
4048 flags, /* Creation flags */
4049 NULL, /* Environment */
4050 NULL, /* Current directory */
4051 si, /* Startup information */
4052 pi); /* Process information */
4053}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054
4055
4056#if defined(FEAT_GUI_W32) || defined(PROTO)
4057
4058/*
4059 * Specialised version of system() for Win32 GUI mode.
4060 * This version proceeds as follows:
4061 * 1. Create a console window for use by the subprocess
4062 * 2. Run the subprocess (it gets the allocated console by default)
4063 * 3. Wait for the subprocess to terminate and get its exit code
4064 * 4. Prompt the user to press a key to close the console window
4065 */
4066 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004067mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004068{
4069 STARTUPINFO si;
4070 PROCESS_INFORMATION pi;
4071 DWORD ret = 0;
4072 HWND hwnd = GetFocus();
4073
4074 si.cb = sizeof(si);
4075 si.lpReserved = NULL;
4076 si.lpDesktop = NULL;
4077 si.lpTitle = NULL;
4078 si.dwFlags = STARTF_USESHOWWINDOW;
4079 /*
4080 * It's nicer to run a filter command in a minimized window, but in
4081 * Windows 95 this makes the command MUCH slower. We can't do it under
4082 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004083 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004084 */
4085 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004086 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004087 else
4088 si.wShowWindow = SW_SHOWNORMAL;
4089 si.cbReserved2 = 0;
4090 si.lpReserved2 = NULL;
4091
4092 /* There is a strange error on Windows 95 when using "c:\\command.com".
4093 * When the "c:\\" is left out it works OK...? */
4094 if (mch_windows95()
4095 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4096 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4097 cmd += 3;
4098
4099 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004100 vim_create_process(cmd, FALSE,
4101 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004102
4103 /* Wait for the command to terminate before continuing */
4104 if (g_PlatformId != VER_PLATFORM_WIN32s)
4105 {
4106#ifdef FEAT_GUI
4107 int delay = 1;
4108
4109 /* Keep updating the window while waiting for the shell to finish. */
4110 for (;;)
4111 {
4112 MSG msg;
4113
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004114 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004115 {
4116 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004117 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004118 delay = 1;
4119 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 }
4121 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4122 break;
4123
4124 /* We start waiting for a very short time and then increase it, so
4125 * that we respond quickly when the process is quick, and don't
4126 * consume too much overhead when it's slow. */
4127 if (delay < 50)
4128 delay += 10;
4129 }
4130#else
4131 WaitForSingleObject(pi.hProcess, INFINITE);
4132#endif
4133
4134 /* Get the command exit code */
4135 GetExitCodeProcess(pi.hProcess, &ret);
4136 }
4137 else
4138 {
4139 /*
4140 * This ugly code is the only quick way of performing
4141 * a synchronous spawn under Win32s. Yuk.
4142 */
4143 num_windows = 0;
4144 EnumWindows(win32ssynch_cb, 0);
4145 old_num_windows = num_windows;
4146 do
4147 {
4148 Sleep(1000);
4149 num_windows = 0;
4150 EnumWindows(win32ssynch_cb, 0);
4151 } while (num_windows == old_num_windows);
4152 ret = 0;
4153 }
4154
4155 /* Close the handles to the subprocess, so that it goes away */
4156 CloseHandle(pi.hThread);
4157 CloseHandle(pi.hProcess);
4158
4159 /* Try to get input focus back. Doesn't always work though. */
4160 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4161
4162 return ret;
4163}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004164
4165/*
4166 * Thread launched by the gui to send the current buffer data to the
4167 * process. This way avoid to hang up vim totally if the children
4168 * process take a long time to process the lines.
4169 */
4170 static DWORD WINAPI
4171sub_process_writer(LPVOID param)
4172{
4173 HANDLE g_hChildStd_IN_Wr = param;
4174 linenr_T lnum = curbuf->b_op_start.lnum;
4175 DWORD len = 0;
4176 DWORD l;
4177 char_u *lp = ml_get(lnum);
4178 char_u *s;
4179 int written = 0;
4180
4181 for (;;)
4182 {
4183 l = (DWORD)STRLEN(lp + written);
4184 if (l == 0)
4185 len = 0;
4186 else if (lp[written] == NL)
4187 {
4188 /* NL -> NUL translation */
4189 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4190 }
4191 else
4192 {
4193 s = vim_strchr(lp + written, NL);
4194 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4195 s == NULL ? l : (DWORD)(s - (lp + written)),
4196 &len, NULL);
4197 }
4198 if (len == (int)l)
4199 {
4200 /* Finished a line, add a NL, unless this line should not have
4201 * one. */
4202 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004203 || (!curbuf->b_p_bin
4204 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004205 || (lnum != curbuf->b_no_eol_lnum
4206 && (lnum != curbuf->b_ml.ml_line_count
4207 || curbuf->b_p_eol)))
4208 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004209 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004210 }
4211
4212 ++lnum;
4213 if (lnum > curbuf->b_op_end.lnum)
4214 break;
4215
4216 lp = ml_get(lnum);
4217 written = 0;
4218 }
4219 else if (len > 0)
4220 written += len;
4221 }
4222
4223 /* finished all the lines, close pipe */
4224 CloseHandle(g_hChildStd_IN_Wr);
4225 ExitThread(0);
4226}
4227
4228
4229# define BUFLEN 100 /* length for buffer, stolen from unix version */
4230
4231/*
4232 * This function read from the children's stdout and write the
4233 * data on screen or in the buffer accordingly.
4234 */
4235 static void
4236dump_pipe(int options,
4237 HANDLE g_hChildStd_OUT_Rd,
4238 garray_T *ga,
4239 char_u buffer[],
4240 DWORD *buffer_off)
4241{
4242 DWORD availableBytes = 0;
4243 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004244 int ret;
4245 DWORD len;
4246 DWORD toRead;
4247 int repeatCount;
4248
4249 /* we query the pipe to see if there is any data to read
4250 * to avoid to perform a blocking read */
4251 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4252 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004253 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004254 NULL, /* number of read bytes */
4255 &availableBytes, /* available bytes total */
4256 NULL); /* byteLeft */
4257
4258 repeatCount = 0;
4259 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004260 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004261 {
4262 repeatCount++;
4263 toRead =
4264# ifdef FEAT_MBYTE
4265 (DWORD)(BUFLEN - *buffer_off);
4266# else
4267 (DWORD)BUFLEN;
4268# endif
4269 toRead = availableBytes < toRead ? availableBytes : toRead;
4270 ReadFile(g_hChildStd_OUT_Rd, buffer
4271# ifdef FEAT_MBYTE
4272 + *buffer_off, toRead
4273# else
4274 , toRead
4275# endif
4276 , &len, NULL);
4277
4278 /* If we haven't read anything, there is a problem */
4279 if (len == 0)
4280 break;
4281
4282 availableBytes -= len;
4283
4284 if (options & SHELL_READ)
4285 {
4286 /* Do NUL -> NL translation, append NL separated
4287 * lines to the current buffer. */
4288 for (i = 0; i < len; ++i)
4289 {
4290 if (buffer[i] == NL)
4291 append_ga_line(ga);
4292 else if (buffer[i] == NUL)
4293 ga_append(ga, NL);
4294 else
4295 ga_append(ga, buffer[i]);
4296 }
4297 }
4298# ifdef FEAT_MBYTE
4299 else if (has_mbyte)
4300 {
4301 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004302 int c;
4303 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004304
4305 len += *buffer_off;
4306 buffer[len] = NUL;
4307
4308 /* Check if the last character in buffer[] is
4309 * incomplete, keep these bytes for the next
4310 * round. */
4311 for (p = buffer; p < buffer + len; p += l)
4312 {
4313 l = mb_cptr2len(p);
4314 if (l == 0)
4315 l = 1; /* NUL byte? */
4316 else if (MB_BYTE2LEN(*p) != l)
4317 break;
4318 }
4319 if (p == buffer) /* no complete character */
4320 {
4321 /* avoid getting stuck at an illegal byte */
4322 if (len >= 12)
4323 ++p;
4324 else
4325 {
4326 *buffer_off = len;
4327 return;
4328 }
4329 }
4330 c = *p;
4331 *p = NUL;
4332 msg_puts(buffer);
4333 if (p < buffer + len)
4334 {
4335 *p = c;
4336 *buffer_off = (DWORD)((buffer + len) - p);
4337 mch_memmove(buffer, p, *buffer_off);
4338 return;
4339 }
4340 *buffer_off = 0;
4341 }
4342# endif /* FEAT_MBYTE */
4343 else
4344 {
4345 buffer[len] = NUL;
4346 msg_puts(buffer);
4347 }
4348
4349 windgoto(msg_row, msg_col);
4350 cursor_on();
4351 out_flush();
4352 }
4353}
4354
4355/*
4356 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4357 * for communication and doesn't open any new window.
4358 */
4359 static int
4360mch_system_piped(char *cmd, int options)
4361{
4362 STARTUPINFO si;
4363 PROCESS_INFORMATION pi;
4364 DWORD ret = 0;
4365
4366 HANDLE g_hChildStd_IN_Rd = NULL;
4367 HANDLE g_hChildStd_IN_Wr = NULL;
4368 HANDLE g_hChildStd_OUT_Rd = NULL;
4369 HANDLE g_hChildStd_OUT_Wr = NULL;
4370
4371 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4372 DWORD len;
4373
4374 /* buffer used to receive keys */
4375 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4376 int ta_len = 0; /* valid bytes in ta_buf[] */
4377
4378 DWORD i;
4379 int c;
4380 int noread_cnt = 0;
4381 garray_T ga;
4382 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004383 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004384 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004385
4386 SECURITY_ATTRIBUTES saAttr;
4387
4388 /* Set the bInheritHandle flag so pipe handles are inherited. */
4389 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4390 saAttr.bInheritHandle = TRUE;
4391 saAttr.lpSecurityDescriptor = NULL;
4392
4393 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4394 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4395 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4396 /* Create a pipe for the child process's STDIN. */
4397 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4398 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4399 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4400 {
4401 CloseHandle(g_hChildStd_IN_Rd);
4402 CloseHandle(g_hChildStd_IN_Wr);
4403 CloseHandle(g_hChildStd_OUT_Rd);
4404 CloseHandle(g_hChildStd_OUT_Wr);
4405 MSG_PUTS(_("\nCannot create pipes\n"));
4406 }
4407
4408 si.cb = sizeof(si);
4409 si.lpReserved = NULL;
4410 si.lpDesktop = NULL;
4411 si.lpTitle = NULL;
4412 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4413
4414 /* set-up our file redirection */
4415 si.hStdError = g_hChildStd_OUT_Wr;
4416 si.hStdOutput = g_hChildStd_OUT_Wr;
4417 si.hStdInput = g_hChildStd_IN_Rd;
4418 si.wShowWindow = SW_HIDE;
4419 si.cbReserved2 = 0;
4420 si.lpReserved2 = NULL;
4421
4422 if (options & SHELL_READ)
4423 ga_init2(&ga, 1, BUFLEN);
4424
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004425 if (cmd != NULL)
4426 {
4427 p = (char *)vim_strsave((char_u *)cmd);
4428 if (p != NULL)
4429 unescape_shellxquote((char_u *)p, p_sxe);
4430 else
4431 p = cmd;
4432 }
4433
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004434 /* Now, run the command.
4435 * About "Inherit handles" being TRUE: this command can be litigious,
4436 * handle inheritance was deactivated for pending temp file, but, if we
4437 * deactivate it, the pipes don't work for some reason. */
4438 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004439
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004440 if (p != cmd)
4441 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004442
4443 /* Close our unused side of the pipes */
4444 CloseHandle(g_hChildStd_IN_Rd);
4445 CloseHandle(g_hChildStd_OUT_Wr);
4446
4447 if (options & SHELL_WRITE)
4448 {
4449 HANDLE thread =
4450 CreateThread(NULL, /* security attributes */
4451 0, /* default stack size */
4452 sub_process_writer, /* function to be executed */
4453 g_hChildStd_IN_Wr, /* parameter */
4454 0, /* creation flag, start immediately */
4455 NULL); /* we don't care about thread id */
4456 CloseHandle(thread);
4457 g_hChildStd_IN_Wr = NULL;
4458 }
4459
4460 /* Keep updating the window while waiting for the shell to finish. */
4461 for (;;)
4462 {
4463 MSG msg;
4464
Bram Moolenaar175d0702013-12-11 18:36:33 +01004465 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004466 {
4467 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004468 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004469 }
4470
4471 /* write pipe information in the window */
4472 if ((options & (SHELL_READ|SHELL_WRITE))
4473# ifdef FEAT_GUI
4474 || gui.in_use
4475# endif
4476 )
4477 {
4478 len = 0;
4479 if (!(options & SHELL_EXPAND)
4480 && ((options &
4481 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4482 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4483# ifdef FEAT_GUI
4484 || gui.in_use
4485# endif
4486 )
4487 && (ta_len > 0 || noread_cnt > 4))
4488 {
4489 if (ta_len == 0)
4490 {
4491 /* Get extra characters when we don't have any. Reset the
4492 * counter and timer. */
4493 noread_cnt = 0;
4494# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4495 gettimeofday(&start_tv, NULL);
4496# endif
4497 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4498 }
4499 if (ta_len > 0 || len > 0)
4500 {
4501 /*
4502 * For pipes: Check for CTRL-C: send interrupt signal to
4503 * child. Check for CTRL-D: EOF, close pipe to child.
4504 */
4505 if (len == 1 && cmd != NULL)
4506 {
4507 if (ta_buf[ta_len] == Ctrl_C)
4508 {
4509 /* Learn what exit code is expected, for
4510 * now put 9 as SIGKILL */
4511 TerminateProcess(pi.hProcess, 9);
4512 }
4513 if (ta_buf[ta_len] == Ctrl_D)
4514 {
4515 CloseHandle(g_hChildStd_IN_Wr);
4516 g_hChildStd_IN_Wr = NULL;
4517 }
4518 }
4519
4520 /* replace K_BS by <BS> and K_DEL by <DEL> */
4521 for (i = ta_len; i < ta_len + len; ++i)
4522 {
4523 if (ta_buf[i] == CSI && len - i > 2)
4524 {
4525 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4526 if (c == K_DEL || c == K_KDEL || c == K_BS)
4527 {
4528 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4529 (size_t)(len - i - 2));
4530 if (c == K_DEL || c == K_KDEL)
4531 ta_buf[i] = DEL;
4532 else
4533 ta_buf[i] = Ctrl_H;
4534 len -= 2;
4535 }
4536 }
4537 else if (ta_buf[i] == '\r')
4538 ta_buf[i] = '\n';
4539# ifdef FEAT_MBYTE
4540 if (has_mbyte)
4541 i += (*mb_ptr2len_len)(ta_buf + i,
4542 ta_len + len - i) - 1;
4543# endif
4544 }
4545
4546 /*
4547 * For pipes: echo the typed characters. For a pty this
4548 * does not seem to work.
4549 */
4550 for (i = ta_len; i < ta_len + len; ++i)
4551 {
4552 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4553 msg_putchar(ta_buf[i]);
4554# ifdef FEAT_MBYTE
4555 else if (has_mbyte)
4556 {
4557 int l = (*mb_ptr2len)(ta_buf + i);
4558
4559 msg_outtrans_len(ta_buf + i, l);
4560 i += l - 1;
4561 }
4562# endif
4563 else
4564 msg_outtrans_len(ta_buf + i, 1);
4565 }
4566 windgoto(msg_row, msg_col);
4567 out_flush();
4568
4569 ta_len += len;
4570
4571 /*
4572 * Write the characters to the child, unless EOF has been
4573 * typed for pipes. Write one character at a time, to
4574 * avoid losing too much typeahead. When writing buffer
4575 * lines, drop the typed characters (only check for
4576 * CTRL-C).
4577 */
4578 if (options & SHELL_WRITE)
4579 ta_len = 0;
4580 else if (g_hChildStd_IN_Wr != NULL)
4581 {
4582 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4583 1, &len, NULL);
4584 // if we are typing in, we want to keep things reactive
4585 delay = 1;
4586 if (len > 0)
4587 {
4588 ta_len -= len;
4589 mch_memmove(ta_buf, ta_buf + len, ta_len);
4590 }
4591 }
4592 }
4593 }
4594 }
4595
4596 if (ta_len)
4597 ui_inchar_undo(ta_buf, ta_len);
4598
4599 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4600 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004601 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004602 break;
4603 }
4604
4605 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004606 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004607
4608 /* We start waiting for a very short time and then increase it, so
4609 * that we respond quickly when the process is quick, and don't
4610 * consume too much overhead when it's slow. */
4611 if (delay < 50)
4612 delay += 10;
4613 }
4614
4615 /* Close the pipe */
4616 CloseHandle(g_hChildStd_OUT_Rd);
4617 if (g_hChildStd_IN_Wr != NULL)
4618 CloseHandle(g_hChildStd_IN_Wr);
4619
4620 WaitForSingleObject(pi.hProcess, INFINITE);
4621
4622 /* Get the command exit code */
4623 GetExitCodeProcess(pi.hProcess, &ret);
4624
4625 if (options & SHELL_READ)
4626 {
4627 if (ga.ga_len > 0)
4628 {
4629 append_ga_line(&ga);
4630 /* remember that the NL was missing */
4631 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4632 }
4633 else
4634 curbuf->b_no_eol_lnum = 0;
4635 ga_clear(&ga);
4636 }
4637
4638 /* Close the handles to the subprocess, so that it goes away */
4639 CloseHandle(pi.hThread);
4640 CloseHandle(pi.hProcess);
4641
4642 return ret;
4643}
4644
4645 static int
4646mch_system(char *cmd, int options)
4647{
4648 /* if we can pipe and the shelltemp option is off */
4649 if (allowPiping && !p_stmp)
4650 return mch_system_piped(cmd, options);
4651 else
4652 return mch_system_classic(cmd, options);
4653}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654#else
4655
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004656# ifdef FEAT_MBYTE
4657 static int
4658mch_system(char *cmd, int options)
4659{
4660 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4661 {
4662 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4663 if (wcmd != NULL)
4664 {
4665 int ret = _wsystem(wcmd);
4666 vim_free(wcmd);
4667 return ret;
4668 }
4669 }
4670 return system(cmd);
4671}
4672# else
4673# define mch_system(c, o) system(c)
4674# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675
4676#endif
4677
4678/*
4679 * Either execute a command by calling the shell or start a new shell
4680 */
4681 int
4682mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004683 char_u *cmd,
4684 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004685{
4686 int x = 0;
4687 int tmode = cur_tmode;
4688#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004689 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004690# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004691 int did_set_title = FALSE;
4692
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004693 /* Change the title to reflect that we are in a subshell. */
4694 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4695 {
4696 WCHAR szShellTitle[512];
4697
4698 if (GetConsoleTitleW(szShellTitle,
4699 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4700 {
4701 if (cmd == NULL)
4702 wcscat(szShellTitle, L" :sh");
4703 else
4704 {
4705 WCHAR *wn = enc_to_utf16(cmd, NULL);
4706
4707 if (wn != NULL)
4708 {
4709 wcscat(szShellTitle, L" - !");
4710 if ((wcslen(szShellTitle) + wcslen(wn) <
4711 sizeof(szShellTitle)/sizeof(WCHAR)))
4712 wcscat(szShellTitle, wn);
4713 SetConsoleTitleW(szShellTitle);
4714 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004715 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004716 }
4717 }
4718 }
4719 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004720 if (!did_set_title)
4721# endif
4722 /* Change the title to reflect that we are in a subshell. */
4723 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004725 if (cmd == NULL)
4726 strcat(szShellTitle, " :sh");
4727 else
4728 {
4729 strcat(szShellTitle, " - !");
4730 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4731 strcat(szShellTitle, cmd);
4732 }
4733 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004734 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735#endif
4736
4737 out_flush();
4738
4739#ifdef MCH_WRITE_DUMP
4740 if (fdDump)
4741 {
4742 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4743 fflush(fdDump);
4744 }
4745#endif
4746
4747 /*
4748 * Catch all deadly signals while running the external command, because a
4749 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4750 */
4751 signal(SIGINT, SIG_IGN);
4752#if defined(__GNUC__) && !defined(__MINGW32__)
4753 signal(SIGKILL, SIG_IGN);
4754#else
4755 signal(SIGBREAK, SIG_IGN);
4756#endif
4757 signal(SIGILL, SIG_IGN);
4758 signal(SIGFPE, SIG_IGN);
4759 signal(SIGSEGV, SIG_IGN);
4760 signal(SIGTERM, SIG_IGN);
4761 signal(SIGABRT, SIG_IGN);
4762
4763 if (options & SHELL_COOKED)
4764 settmode(TMODE_COOK); /* set to normal mode */
4765
4766 if (cmd == NULL)
4767 {
4768 x = mch_system(p_sh, options);
4769 }
4770 else
4771 {
4772 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004773 char_u *newcmd = NULL;
4774 char_u *cmdbase = cmd;
4775 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004776
4777 /* Skip a leading ", ( and "(. */
4778 if (*cmdbase == '"' )
4779 ++cmdbase;
4780 if (*cmdbase == '(')
4781 ++cmdbase;
4782
4783 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4784 {
4785 STARTUPINFO si;
4786 PROCESS_INFORMATION pi;
4787 DWORD flags = CREATE_NEW_CONSOLE;
4788 char_u *p;
4789
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004790 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004791 si.cb = sizeof(si);
4792 si.lpReserved = NULL;
4793 si.lpDesktop = NULL;
4794 si.lpTitle = NULL;
4795 si.dwFlags = 0;
4796 si.cbReserved2 = 0;
4797 si.lpReserved2 = NULL;
4798
4799 cmdbase = skipwhite(cmdbase + 5);
4800 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4801 && vim_iswhite(cmdbase[4]))
4802 {
4803 cmdbase = skipwhite(cmdbase + 4);
4804 si.dwFlags = STARTF_USESHOWWINDOW;
4805 si.wShowWindow = SW_SHOWMINNOACTIVE;
4806 }
4807 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4808 && vim_iswhite(cmdbase[2]))
4809 {
4810 cmdbase = skipwhite(cmdbase + 2);
4811 flags = CREATE_NO_WINDOW;
4812 si.dwFlags = STARTF_USESTDHANDLES;
4813 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004814 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004815 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004816 NULL, // Security att.
4817 OPEN_EXISTING, // Open flags
4818 FILE_ATTRIBUTE_NORMAL, // File att.
4819 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004820 si.hStdOutput = si.hStdInput;
4821 si.hStdError = si.hStdInput;
4822 }
4823
4824 /* Remove a trailing ", ) and )" if they have a match
4825 * at the start of the command. */
4826 if (cmdbase > cmd)
4827 {
4828 p = cmdbase + STRLEN(cmdbase);
4829 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4830 *--p = NUL;
4831 if (p > cmdbase && p[-1] == ')'
4832 && (*cmd =='(' || cmd[1] == '('))
4833 *--p = NUL;
4834 }
4835
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004836 newcmd = cmdbase;
4837 unescape_shellxquote(cmdbase, p_sxe);
4838
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004839 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004840 * If creating new console, arguments are passed to the
4841 * 'cmd.exe' as-is. If it's not, arguments are not treated
4842 * correctly for current 'cmd.exe'. So unescape characters in
4843 * shellxescape except '|' for avoiding to be treated as
4844 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004845 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004846 if (flags != CREATE_NEW_CONSOLE)
4847 {
4848 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004849 char_u *cmd_shell = mch_getenv("COMSPEC");
4850
4851 if (cmd_shell == NULL || *cmd_shell == NUL)
4852 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004853
4854 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4855 if (subcmd != NULL)
4856 {
4857 /* make "cmd.exe /c arguments" */
4858 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004859 newcmd = lalloc(cmdlen, TRUE);
4860 if (newcmd != NULL)
4861 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004862 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004863 else
4864 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004865 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004866 }
4867 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004868
4869 /*
4870 * Now, start the command as a process, so that it doesn't
4871 * inherit our handles which causes unpleasant dangling swap
4872 * files if we exit before the spawned process
4873 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004874 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004875 x = 0;
4876 else
4877 {
4878 x = -1;
4879#ifdef FEAT_GUI_W32
4880 EMSG(_("E371: Command not found"));
4881#endif
4882 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004883
4884 if (newcmd != cmdbase)
4885 vim_free(newcmd);
4886
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004887 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004888 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004889 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004890 CloseHandle(si.hStdInput);
4891 }
4892 /* Close the handles to the subprocess, so that it goes away */
4893 CloseHandle(pi.hThread);
4894 CloseHandle(pi.hProcess);
4895 }
4896 else
4897 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004898 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004899#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004900 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004901#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004902 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4903
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004904 newcmd = lalloc(cmdlen, TRUE);
4905 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906 {
4907#if defined(FEAT_GUI_W32)
4908 if (need_vimrun_warning)
4909 {
4910 MessageBox(NULL,
4911 _("VIMRUN.EXE not found in your $PATH.\n"
4912 "External commands will not pause after completion.\n"
4913 "See :help win32-vimrun for more information."),
4914 _("Vim Warning"),
4915 MB_ICONWARNING);
4916 need_vimrun_warning = FALSE;
4917 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004918 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004919 /* Use vimrun to execute the command. It opens a console
4920 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004921 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004922 vimrun_path,
4923 (msg_silent != 0 || (options & SHELL_DOOUT))
4924 ? "-s " : "",
4925 p_sh, p_shcf, cmd);
4926 else
4927#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004928 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004929 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004931 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004933 }
4934 }
4935
4936 if (tmode == TMODE_RAW)
4937 settmode(TMODE_RAW); /* set to raw mode */
4938
4939 /* Print the return value, unless "vimrun" was used. */
4940 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4941#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004942 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4943 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944#endif
4945 )
4946 {
4947 smsg(_("shell returned %d"), x);
4948 msg_putchar('\n');
4949 }
4950#ifdef FEAT_TITLE
4951 resettitle();
4952#endif
4953
4954 signal(SIGINT, SIG_DFL);
4955#if defined(__GNUC__) && !defined(__MINGW32__)
4956 signal(SIGKILL, SIG_DFL);
4957#else
4958 signal(SIGBREAK, SIG_DFL);
4959#endif
4960 signal(SIGILL, SIG_DFL);
4961 signal(SIGFPE, SIG_DFL);
4962 signal(SIGSEGV, SIG_DFL);
4963 signal(SIGTERM, SIG_DFL);
4964 signal(SIGABRT, SIG_DFL);
4965
4966 return x;
4967}
4968
4969
4970#ifndef FEAT_GUI_W32
4971
4972/*
4973 * Start termcap mode
4974 */
4975 static void
4976termcap_mode_start(void)
4977{
4978 DWORD cmodein;
4979
4980 if (g_fTermcapMode)
4981 return;
4982
4983 SaveConsoleBuffer(&g_cbNonTermcap);
4984
4985 if (g_cbTermcap.IsValid)
4986 {
4987 /*
4988 * We've been in termcap mode before. Restore certain screen
4989 * characteristics, including the buffer size and the window
4990 * size. Since we will be redrawing the screen, we don't need
4991 * to restore the actual contents of the buffer.
4992 */
4993 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4994 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4995 Rows = g_cbTermcap.Info.dwSize.Y;
4996 Columns = g_cbTermcap.Info.dwSize.X;
4997 }
4998 else
4999 {
5000 /*
5001 * This is our first time entering termcap mode. Clear the console
5002 * screen buffer, and resize the buffer to match the current window
5003 * size. We will use this as the size of our editing environment.
5004 */
5005 ClearConsoleBuffer(g_attrCurrent);
5006 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5007 }
5008
5009#ifdef FEAT_TITLE
5010 resettitle();
5011#endif
5012
5013 GetConsoleMode(g_hConIn, &cmodein);
5014#ifdef FEAT_MOUSE
5015 if (g_fMouseActive)
5016 cmodein |= ENABLE_MOUSE_INPUT;
5017 else
5018 cmodein &= ~ENABLE_MOUSE_INPUT;
5019#endif
5020 cmodein |= ENABLE_WINDOW_INPUT;
5021 SetConsoleMode(g_hConIn, cmodein);
5022
5023 redraw_later_clear();
5024 g_fTermcapMode = TRUE;
5025}
5026
5027
5028/*
5029 * End termcap mode
5030 */
5031 static void
5032termcap_mode_end(void)
5033{
5034 DWORD cmodein;
5035 ConsoleBuffer *cb;
5036 COORD coord;
5037 DWORD dwDummy;
5038
5039 if (!g_fTermcapMode)
5040 return;
5041
5042 SaveConsoleBuffer(&g_cbTermcap);
5043
5044 GetConsoleMode(g_hConIn, &cmodein);
5045 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5046 SetConsoleMode(g_hConIn, cmodein);
5047
5048#ifdef FEAT_RESTORE_ORIG_SCREEN
5049 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5050#else
5051 cb = &g_cbNonTermcap;
5052#endif
5053 RestoreConsoleBuffer(cb, p_rs);
5054 SetConsoleCursorInfo(g_hConOut, &g_cci);
5055
5056 if (p_rs || exiting)
5057 {
5058 /*
5059 * Clear anything that happens to be on the current line.
5060 */
5061 coord.X = 0;
5062 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5063 FillConsoleOutputCharacter(g_hConOut, ' ',
5064 cb->Info.dwSize.X, coord, &dwDummy);
5065 /*
5066 * The following is just for aesthetics. If we are exiting without
5067 * restoring the screen, then we want to have a prompt string
5068 * appear at the bottom line. However, the command interpreter
5069 * seems to always advance the cursor one line before displaying
5070 * the prompt string, which causes the screen to scroll. To
5071 * counter this, move the cursor up one line before exiting.
5072 */
5073 if (exiting && !p_rs)
5074 coord.Y--;
5075 /*
5076 * Position the cursor at the leftmost column of the desired row.
5077 */
5078 SetConsoleCursorPosition(g_hConOut, coord);
5079 }
5080
5081 g_fTermcapMode = FALSE;
5082}
5083#endif /* FEAT_GUI_W32 */
5084
5085
5086#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005087/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005088 void
5089mch_write(
5090 char_u *s,
5091 int len)
5092{
5093 /* never used */
5094}
5095
5096#else
5097
5098/*
5099 * clear `n' chars, starting from `coord'
5100 */
5101 static void
5102clear_chars(
5103 COORD coord,
5104 DWORD n)
5105{
5106 DWORD dwDummy;
5107
5108 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5109 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5110}
5111
5112
5113/*
5114 * Clear the screen
5115 */
5116 static void
5117clear_screen(void)
5118{
5119 g_coord.X = g_coord.Y = 0;
5120 clear_chars(g_coord, Rows * Columns);
5121}
5122
5123
5124/*
5125 * Clear to end of display
5126 */
5127 static void
5128clear_to_end_of_display(void)
5129{
5130 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5131 * Columns + (Columns - g_coord.X));
5132}
5133
5134
5135/*
5136 * Clear to end of line
5137 */
5138 static void
5139clear_to_end_of_line(void)
5140{
5141 clear_chars(g_coord, Columns - g_coord.X);
5142}
5143
5144
5145/*
5146 * Scroll the scroll region up by `cLines' lines
5147 */
5148 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005149scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005150{
5151 COORD oldcoord = g_coord;
5152
5153 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5154 delete_lines(cLines);
5155
5156 g_coord = oldcoord;
5157}
5158
5159
5160/*
5161 * Set the scroll region
5162 */
5163 static void
5164set_scroll_region(
5165 unsigned left,
5166 unsigned top,
5167 unsigned right,
5168 unsigned bottom)
5169{
5170 if (left >= right
5171 || top >= bottom
5172 || right > (unsigned) Columns - 1
5173 || bottom > (unsigned) Rows - 1)
5174 return;
5175
5176 g_srScrollRegion.Left = left;
5177 g_srScrollRegion.Top = top;
5178 g_srScrollRegion.Right = right;
5179 g_srScrollRegion.Bottom = bottom;
5180}
5181
5182
5183/*
5184 * Insert `cLines' lines at the current cursor position
5185 */
5186 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005187insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188{
5189 SMALL_RECT source;
5190 COORD dest;
5191 CHAR_INFO fill;
5192
5193 dest.X = 0;
5194 dest.Y = g_coord.Y + cLines;
5195
5196 source.Left = 0;
5197 source.Top = g_coord.Y;
5198 source.Right = g_srScrollRegion.Right;
5199 source.Bottom = g_srScrollRegion.Bottom - cLines;
5200
5201 fill.Char.AsciiChar = ' ';
5202 fill.Attributes = g_attrCurrent;
5203
5204 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5205
5206 /* Here we have to deal with a win32 console flake: If the scroll
5207 * region looks like abc and we scroll c to a and fill with d we get
5208 * cbd... if we scroll block c one line at a time to a, we get cdd...
5209 * vim expects cdd consistently... So we have to deal with that
5210 * here... (this also occurs scrolling the same way in the other
5211 * direction). */
5212
5213 if (source.Bottom < dest.Y)
5214 {
5215 COORD coord;
5216
5217 coord.X = 0;
5218 coord.Y = source.Bottom;
5219 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5220 }
5221}
5222
5223
5224/*
5225 * Delete `cLines' lines at the current cursor position
5226 */
5227 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005228delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005229{
5230 SMALL_RECT source;
5231 COORD dest;
5232 CHAR_INFO fill;
5233 int nb;
5234
5235 dest.X = 0;
5236 dest.Y = g_coord.Y;
5237
5238 source.Left = 0;
5239 source.Top = g_coord.Y + cLines;
5240 source.Right = g_srScrollRegion.Right;
5241 source.Bottom = g_srScrollRegion.Bottom;
5242
5243 fill.Char.AsciiChar = ' ';
5244 fill.Attributes = g_attrCurrent;
5245
5246 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5247
5248 /* Here we have to deal with a win32 console flake: If the scroll
5249 * region looks like abc and we scroll c to a and fill with d we get
5250 * cbd... if we scroll block c one line at a time to a, we get cdd...
5251 * vim expects cdd consistently... So we have to deal with that
5252 * here... (this also occurs scrolling the same way in the other
5253 * direction). */
5254
5255 nb = dest.Y + (source.Bottom - source.Top) + 1;
5256
5257 if (nb < source.Top)
5258 {
5259 COORD coord;
5260
5261 coord.X = 0;
5262 coord.Y = nb;
5263 clear_chars(coord, Columns * (source.Top - nb));
5264 }
5265}
5266
5267
5268/*
5269 * Set the cursor position
5270 */
5271 static void
5272gotoxy(
5273 unsigned x,
5274 unsigned y)
5275{
5276 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5277 return;
5278
5279 /* external cursor coords are 1-based; internal are 0-based */
5280 g_coord.X = x - 1;
5281 g_coord.Y = y - 1;
5282 SetConsoleCursorPosition(g_hConOut, g_coord);
5283}
5284
5285
5286/*
5287 * Set the current text attribute = (foreground | background)
5288 * See ../doc/os_win32.txt for the numbers.
5289 */
5290 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005291textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005292{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005293 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005294
5295 SetConsoleTextAttribute(g_hConOut, wAttr);
5296}
5297
5298
5299 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005300textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005301{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005302 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005303
5304 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5305}
5306
5307
5308 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005309textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005311 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005312
5313 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5314}
5315
5316
5317/*
5318 * restore the default text attribute (whatever we started with)
5319 */
5320 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005321normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005322{
5323 textattr(g_attrDefault);
5324}
5325
5326
5327static WORD g_attrPreStandout = 0;
5328
5329/*
5330 * Make the text standout, by brightening it
5331 */
5332 static void
5333standout(void)
5334{
5335 g_attrPreStandout = g_attrCurrent;
5336 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5337}
5338
5339
5340/*
5341 * Turn off standout mode
5342 */
5343 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005344standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345{
5346 if (g_attrPreStandout)
5347 {
5348 textattr(g_attrPreStandout);
5349 g_attrPreStandout = 0;
5350 }
5351}
5352
5353
5354/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005355 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005356 */
5357 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005358mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005359{
5360 char_u *p;
5361 int n;
5362
5363 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5364 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5365 if (T_ME[0] == ESC && T_ME[1] == '|')
5366 {
5367 p = T_ME + 2;
5368 n = getdigits(&p);
5369 if (*p == 'm' && n > 0)
5370 {
5371 cterm_normal_fg_color = (n & 0xf) + 1;
5372 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5373 }
5374 }
5375}
5376
5377
5378/*
5379 * visual bell: flash the screen
5380 */
5381 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005382visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383{
5384 COORD coordOrigin = {0, 0};
5385 WORD attrFlash = ~g_attrCurrent & 0xff;
5386
5387 DWORD dwDummy;
5388 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5389
5390 if (oldattrs == NULL)
5391 return;
5392 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5393 coordOrigin, &dwDummy);
5394 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5395 coordOrigin, &dwDummy);
5396
5397 Sleep(15); /* wait for 15 msec */
5398 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5399 coordOrigin, &dwDummy);
5400 vim_free(oldattrs);
5401}
5402
5403
5404/*
5405 * Make the cursor visible or invisible
5406 */
5407 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005408cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005409{
5410 s_cursor_visible = fVisible;
5411#ifdef MCH_CURSOR_SHAPE
5412 mch_update_cursor();
5413#endif
5414}
5415
5416
5417/*
5418 * write `cchToWrite' characters in `pchBuf' to the screen
5419 * Returns the number of characters actually written (at least one).
5420 */
5421 static BOOL
5422write_chars(
5423 LPCSTR pchBuf,
5424 DWORD cchToWrite)
5425{
5426 COORD coord = g_coord;
5427 DWORD written;
5428
5429 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
5430 coord, &written);
5431 /* When writing fails or didn't write a single character, pretend one
5432 * character was written, otherwise we get stuck. */
5433 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
5434 coord, &written) == 0
5435 || written == 0)
5436 written = 1;
5437
5438 g_coord.X += (SHORT) written;
5439
5440 while (g_coord.X > g_srScrollRegion.Right)
5441 {
5442 g_coord.X -= (SHORT) Columns;
5443 if (g_coord.Y < g_srScrollRegion.Bottom)
5444 g_coord.Y++;
5445 }
5446
5447 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5448
5449 return written;
5450}
5451
5452
5453/*
5454 * mch_write(): write the output buffer to the screen, translating ESC
5455 * sequences into calls to console output routines.
5456 */
5457 void
5458mch_write(
5459 char_u *s,
5460 int len)
5461{
5462 s[len] = NUL;
5463
5464 if (!term_console)
5465 {
5466 write(1, s, (unsigned)len);
5467 return;
5468 }
5469
5470 /* translate ESC | sequences into faked bios calls */
5471 while (len--)
5472 {
5473 /* optimization: use one single write_chars for runs of text,
5474 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005475 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476
5477 if (p_wd)
5478 {
5479 WaitForChar(p_wd);
5480 if (prefix != 0)
5481 prefix = 1;
5482 }
5483
5484 if (prefix != 0)
5485 {
5486 DWORD nWritten;
5487
5488 nWritten = write_chars(s, prefix);
5489#ifdef MCH_WRITE_DUMP
5490 if (fdDump)
5491 {
5492 fputc('>', fdDump);
5493 fwrite(s, sizeof(char_u), nWritten, fdDump);
5494 fputs("<\n", fdDump);
5495 }
5496#endif
5497 len -= (nWritten - 1);
5498 s += nWritten;
5499 }
5500 else if (s[0] == '\n')
5501 {
5502 /* \n, newline: go to the beginning of the next line or scroll */
5503 if (g_coord.Y == g_srScrollRegion.Bottom)
5504 {
5505 scroll(1);
5506 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5507 }
5508 else
5509 {
5510 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5511 }
5512#ifdef MCH_WRITE_DUMP
5513 if (fdDump)
5514 fputs("\\n\n", fdDump);
5515#endif
5516 s++;
5517 }
5518 else if (s[0] == '\r')
5519 {
5520 /* \r, carriage return: go to beginning of line */
5521 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5522#ifdef MCH_WRITE_DUMP
5523 if (fdDump)
5524 fputs("\\r\n", fdDump);
5525#endif
5526 s++;
5527 }
5528 else if (s[0] == '\b')
5529 {
5530 /* \b, backspace: move cursor one position left */
5531 if (g_coord.X > g_srScrollRegion.Left)
5532 g_coord.X--;
5533 else if (g_coord.Y > g_srScrollRegion.Top)
5534 {
5535 g_coord.X = g_srScrollRegion.Right;
5536 g_coord.Y--;
5537 }
5538 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5539#ifdef MCH_WRITE_DUMP
5540 if (fdDump)
5541 fputs("\\b\n", fdDump);
5542#endif
5543 s++;
5544 }
5545 else if (s[0] == '\a')
5546 {
5547 /* \a, bell */
5548 MessageBeep(0xFFFFFFFF);
5549#ifdef MCH_WRITE_DUMP
5550 if (fdDump)
5551 fputs("\\a\n", fdDump);
5552#endif
5553 s++;
5554 }
5555 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5556 {
5557#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005558 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005559#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005560 char_u *p;
5561 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562
5563 switch (s[2])
5564 {
5565 /* one or two numeric arguments, separated by ';' */
5566
5567 case '0': case '1': case '2': case '3': case '4':
5568 case '5': case '6': case '7': case '8': case '9':
5569 p = s + 2;
5570 arg1 = getdigits(&p); /* no check for length! */
5571 if (p > s + len)
5572 break;
5573
5574 if (*p == ';')
5575 {
5576 ++p;
5577 arg2 = getdigits(&p); /* no check for length! */
5578 if (p > s + len)
5579 break;
5580
5581 if (*p == 'H')
5582 gotoxy(arg2, arg1);
5583 else if (*p == 'r')
5584 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5585 }
5586 else if (*p == 'A')
5587 {
5588 /* move cursor up arg1 lines in same column */
5589 gotoxy(g_coord.X + 1,
5590 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5591 }
5592 else if (*p == 'C')
5593 {
5594 /* move cursor right arg1 columns in same line */
5595 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5596 g_coord.Y + 1);
5597 }
5598 else if (*p == 'H')
5599 {
5600 gotoxy(1, arg1);
5601 }
5602 else if (*p == 'L')
5603 {
5604 insert_lines(arg1);
5605 }
5606 else if (*p == 'm')
5607 {
5608 if (arg1 == 0)
5609 normvideo();
5610 else
5611 textattr((WORD) arg1);
5612 }
5613 else if (*p == 'f')
5614 {
5615 textcolor((WORD) arg1);
5616 }
5617 else if (*p == 'b')
5618 {
5619 textbackground((WORD) arg1);
5620 }
5621 else if (*p == 'M')
5622 {
5623 delete_lines(arg1);
5624 }
5625
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005626 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005627 s = p + 1;
5628 break;
5629
5630
5631 /* Three-character escape sequences */
5632
5633 case 'A':
5634 /* move cursor up one line in same column */
5635 gotoxy(g_coord.X + 1,
5636 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5637 goto got3;
5638
5639 case 'B':
5640 visual_bell();
5641 goto got3;
5642
5643 case 'C':
5644 /* move cursor right one column in same line */
5645 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5646 g_coord.Y + 1);
5647 goto got3;
5648
5649 case 'E':
5650 termcap_mode_end();
5651 goto got3;
5652
5653 case 'F':
5654 standout();
5655 goto got3;
5656
5657 case 'f':
5658 standend();
5659 goto got3;
5660
5661 case 'H':
5662 gotoxy(1, 1);
5663 goto got3;
5664
5665 case 'j':
5666 clear_to_end_of_display();
5667 goto got3;
5668
5669 case 'J':
5670 clear_screen();
5671 goto got3;
5672
5673 case 'K':
5674 clear_to_end_of_line();
5675 goto got3;
5676
5677 case 'L':
5678 insert_lines(1);
5679 goto got3;
5680
5681 case 'M':
5682 delete_lines(1);
5683 goto got3;
5684
5685 case 'S':
5686 termcap_mode_start();
5687 goto got3;
5688
5689 case 'V':
5690 cursor_visible(TRUE);
5691 goto got3;
5692
5693 case 'v':
5694 cursor_visible(FALSE);
5695 goto got3;
5696
5697 got3:
5698 s += 3;
5699 len -= 2;
5700 }
5701
5702#ifdef MCH_WRITE_DUMP
5703 if (fdDump)
5704 {
5705 fputs("ESC | ", fdDump);
5706 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5707 fputc('\n', fdDump);
5708 }
5709#endif
5710 }
5711 else
5712 {
5713 /* Write a single character */
5714 DWORD nWritten;
5715
5716 nWritten = write_chars(s, 1);
5717#ifdef MCH_WRITE_DUMP
5718 if (fdDump)
5719 {
5720 fputc('>', fdDump);
5721 fwrite(s, sizeof(char_u), nWritten, fdDump);
5722 fputs("<\n", fdDump);
5723 }
5724#endif
5725
5726 len -= (nWritten - 1);
5727 s += nWritten;
5728 }
5729 }
5730
5731#ifdef MCH_WRITE_DUMP
5732 if (fdDump)
5733 fflush(fdDump);
5734#endif
5735}
5736
5737#endif /* FEAT_GUI_W32 */
5738
5739
5740/*
5741 * Delay for half a second.
5742 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005743/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005744 void
5745mch_delay(
5746 long msec,
5747 int ignoreinput)
5748{
5749#ifdef FEAT_GUI_W32
5750 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005751#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005752 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005753# ifdef FEAT_MZSCHEME
5754 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5755 {
5756 int towait = p_mzq;
5757
5758 /* if msec is large enough, wait by portions in p_mzq */
5759 while (msec > 0)
5760 {
5761 mzvim_check_threads();
5762 if (msec < towait)
5763 towait = msec;
5764 Sleep(towait);
5765 msec -= towait;
5766 }
5767 }
5768 else
5769# endif
5770 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771 else
5772 WaitForChar(msec);
5773#endif
5774}
5775
5776
5777/*
5778 * this version of remove is not scared by a readonly (backup) file
5779 * Return 0 for success, -1 for failure.
5780 */
5781 int
5782mch_remove(char_u *name)
5783{
5784#ifdef FEAT_MBYTE
5785 WCHAR *wn = NULL;
5786 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005787#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005788
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005789 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5790
5791#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5793 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005794 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005795 if (wn != NULL)
5796 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797 n = DeleteFileW(wn) ? 0 : -1;
5798 vim_free(wn);
5799 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5800 return n;
5801 /* Retry with non-wide function (for Windows 98). */
5802 }
5803 }
5804#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005805 return DeleteFile(name) ? 0 : -1;
5806}
5807
5808
5809/*
5810 * check for an "interrupt signal": CTRL-break or CTRL-C
5811 */
5812 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005813mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005814{
5815#ifndef FEAT_GUI_W32 /* never used */
5816 if (g_fCtrlCPressed || g_fCBrkPressed)
5817 {
5818 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5819 got_int = TRUE;
5820 }
5821#endif
5822}
5823
5824
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825#ifdef FEAT_MBYTE
5826/*
5827 * Same code as below, but with wide functions and no comments.
5828 * Return 0 for success, non-zero for failure.
5829 */
5830 int
5831mch_wrename(WCHAR *wold, WCHAR *wnew)
5832{
5833 WCHAR *p;
5834 int i;
5835 WCHAR szTempFile[_MAX_PATH + 1];
5836 WCHAR szNewPath[_MAX_PATH + 1];
5837 HANDLE hf;
5838
5839 if (!mch_windows95())
5840 {
5841 p = wold;
5842 for (i = 0; wold[i] != NUL; ++i)
5843 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5844 && wold[i + 1] != 0)
5845 p = wold + i + 1;
5846 if ((int)(wold + i - p) < 8 || p[6] != '~')
5847 return (MoveFileW(wold, wnew) == 0);
5848 }
5849
5850 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5851 return -1;
5852 *p = NUL;
5853
5854 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5855 return -2;
5856
5857 if (!DeleteFileW(szTempFile))
5858 return -3;
5859
5860 if (!MoveFileW(wold, szTempFile))
5861 return -4;
5862
5863 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5864 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5865 return -5;
5866 if (!CloseHandle(hf))
5867 return -6;
5868
5869 if (!MoveFileW(szTempFile, wnew))
5870 {
5871 (void)MoveFileW(szTempFile, wold);
5872 return -7;
5873 }
5874
5875 DeleteFileW(szTempFile);
5876
5877 if (!DeleteFileW(wold))
5878 return -8;
5879
5880 return 0;
5881}
5882#endif
5883
5884
5885/*
5886 * mch_rename() works around a bug in rename (aka MoveFile) in
5887 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5888 * file whose short file name is "FOO.BAR" (its long file name will
5889 * be correct: "foo.bar~"). Because a file can be accessed by
5890 * either its SFN or its LFN, "foo.bar" has effectively been
5891 * renamed to "foo.bar", which is not at all what was wanted. This
5892 * seems to happen only when renaming files with three-character
5893 * extensions by appending a suffix that does not include ".".
5894 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5895 *
5896 * There is another problem, which isn't really a bug but isn't right either:
5897 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5898 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5899 * service pack 6. Doesn't seem to happen on Windows 98.
5900 *
5901 * Like rename(), returns 0 upon success, non-zero upon failure.
5902 * Should probably set errno appropriately when errors occur.
5903 */
5904 int
5905mch_rename(
5906 const char *pszOldFile,
5907 const char *pszNewFile)
5908{
5909 char szTempFile[_MAX_PATH+1];
5910 char szNewPath[_MAX_PATH+1];
5911 char *pszFilePart;
5912 HANDLE hf;
5913#ifdef FEAT_MBYTE
5914 WCHAR *wold = NULL;
5915 WCHAR *wnew = NULL;
5916 int retval = -1;
5917
5918 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5919 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005920 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5921 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005922 if (wold != NULL && wnew != NULL)
5923 retval = mch_wrename(wold, wnew);
5924 vim_free(wold);
5925 vim_free(wnew);
5926 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5927 return retval;
5928 /* Retry with non-wide function (for Windows 98). */
5929 }
5930#endif
5931
5932 /*
5933 * No need to play tricks if not running Windows 95, unless the file name
5934 * contains a "~" as the seventh character.
5935 */
5936 if (!mch_windows95())
5937 {
5938 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5939 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5940 return rename(pszOldFile, pszNewFile);
5941 }
5942
5943 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5944 * a directory, no error is returned and pszFilePart will be NULL. */
5945 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5946 || pszFilePart == NULL)
5947 return -1;
5948 *pszFilePart = NUL;
5949
5950 /* Get (and create) a unique temporary file name in directory of new file */
5951 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5952 return -2;
5953
5954 /* blow the temp file away */
5955 if (!DeleteFile(szTempFile))
5956 return -3;
5957
5958 /* rename old file to the temp file */
5959 if (!MoveFile(pszOldFile, szTempFile))
5960 return -4;
5961
5962 /* now create an empty file called pszOldFile; this prevents the operating
5963 * system using pszOldFile as an alias (SFN) if we're renaming within the
5964 * same directory. For example, we're editing a file called
5965 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5966 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5967 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005968 * cause all sorts of problems later in buf_write(). So, we create an
5969 * empty file called filena~1.txt and the system will have to find some
5970 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005971 */
5972 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5973 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5974 return -5;
5975 if (!CloseHandle(hf))
5976 return -6;
5977
5978 /* rename the temp file to the new file */
5979 if (!MoveFile(szTempFile, pszNewFile))
5980 {
5981 /* Renaming failed. Rename the file back to its old name, so that it
5982 * looks like nothing happened. */
5983 (void)MoveFile(szTempFile, pszOldFile);
5984
5985 return -7;
5986 }
5987
5988 /* Seems to be left around on Novell filesystems */
5989 DeleteFile(szTempFile);
5990
5991 /* finally, remove the empty old file */
5992 if (!DeleteFile(pszOldFile))
5993 return -8;
5994
5995 return 0; /* success */
5996}
5997
5998/*
5999 * Get the default shell for the current hardware platform
6000 */
6001 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006002default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006003{
6004 char* psz = NULL;
6005
6006 PlatformId();
6007
6008 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6009 psz = "cmd.exe";
6010 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6011 psz = "command.com";
6012
6013 return psz;
6014}
6015
6016/*
6017 * mch_access() extends access() to do more detailed check on network drives.
6018 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6019 */
6020 int
6021mch_access(char *n, int p)
6022{
6023 HANDLE hFile;
6024 DWORD am;
6025 int retval = -1; /* default: fail */
6026#ifdef FEAT_MBYTE
6027 WCHAR *wn = NULL;
6028
6029 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006030 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031#endif
6032
6033 if (mch_isdir(n))
6034 {
6035 char TempName[_MAX_PATH + 16] = "";
6036#ifdef FEAT_MBYTE
6037 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6038#endif
6039
6040 if (p & R_OK)
6041 {
6042 /* Read check is performed by seeing if we can do a find file on
6043 * the directory for any file. */
6044#ifdef FEAT_MBYTE
6045 if (wn != NULL)
6046 {
6047 int i;
6048 WIN32_FIND_DATAW d;
6049
6050 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6051 TempNameW[i] = wn[i];
6052 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6053 TempNameW[i++] = '\\';
6054 TempNameW[i++] = '*';
6055 TempNameW[i++] = 0;
6056
6057 hFile = FindFirstFileW(TempNameW, &d);
6058 if (hFile == INVALID_HANDLE_VALUE)
6059 {
6060 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6061 goto getout;
6062
6063 /* Retry with non-wide function (for Windows 98). */
6064 vim_free(wn);
6065 wn = NULL;
6066 }
6067 else
6068 (void)FindClose(hFile);
6069 }
6070 if (wn == NULL)
6071#endif
6072 {
6073 char *pch;
6074 WIN32_FIND_DATA d;
6075
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006076 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006077 pch = TempName + STRLEN(TempName) - 1;
6078 if (*pch != '\\' && *pch != '/')
6079 *++pch = '\\';
6080 *++pch = '*';
6081 *++pch = NUL;
6082
6083 hFile = FindFirstFile(TempName, &d);
6084 if (hFile == INVALID_HANDLE_VALUE)
6085 goto getout;
6086 (void)FindClose(hFile);
6087 }
6088 }
6089
6090 if (p & W_OK)
6091 {
6092 /* Trying to create a temporary file in the directory should catch
6093 * directories on read-only network shares. However, in
6094 * directories whose ACL allows writes but denies deletes will end
6095 * up keeping the temporary file :-(. */
6096#ifdef FEAT_MBYTE
6097 if (wn != NULL)
6098 {
6099 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6100 {
6101 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6102 goto getout;
6103
6104 /* Retry with non-wide function (for Windows 98). */
6105 vim_free(wn);
6106 wn = NULL;
6107 }
6108 else
6109 DeleteFileW(TempNameW);
6110 }
6111 if (wn == NULL)
6112#endif
6113 {
6114 if (!GetTempFileName(n, "VIM", 0, TempName))
6115 goto getout;
6116 mch_remove((char_u *)TempName);
6117 }
6118 }
6119 }
6120 else
6121 {
6122 /* Trying to open the file for the required access does ACL, read-only
6123 * network share, and file attribute checks. */
6124 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6125 | ((p & R_OK) ? GENERIC_READ : 0);
6126#ifdef FEAT_MBYTE
6127 if (wn != NULL)
6128 {
6129 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6130 if (hFile == INVALID_HANDLE_VALUE
6131 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6132 {
6133 /* Retry with non-wide function (for Windows 98). */
6134 vim_free(wn);
6135 wn = NULL;
6136 }
6137 }
6138 if (wn == NULL)
6139#endif
6140 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6141 if (hFile == INVALID_HANDLE_VALUE)
6142 goto getout;
6143 CloseHandle(hFile);
6144 }
6145
6146 retval = 0; /* success */
6147getout:
6148#ifdef FEAT_MBYTE
6149 vim_free(wn);
6150#endif
6151 return retval;
6152}
6153
6154#if defined(FEAT_MBYTE) || defined(PROTO)
6155/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006156 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006157 */
6158 int
6159mch_open(char *name, int flags, int mode)
6160{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006161 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6162# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006163 WCHAR *wn;
6164 int f;
6165
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006166 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006167 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006168 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006169 if (wn != NULL)
6170 {
6171 f = _wopen(wn, flags, mode);
6172 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006173 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006174 return f;
6175 /* Retry with non-wide function (for Windows 98). Can't use
6176 * GetLastError() here and it's unclear what errno gets set to if
6177 * the _wopen() fails for missing wide functions. */
6178 }
6179 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006180# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006181
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006182 /* open() can open a file which name is longer than _MAX_PATH bytes
6183 * and shorter than _MAX_PATH characters successfully, but sometimes it
6184 * causes unexpected error in another part. We make it an error explicitly
6185 * here. */
6186 if (strlen(name) >= _MAX_PATH)
6187 return -1;
6188
Bram Moolenaar071d4272004-06-13 20:20:40 +00006189 return open(name, flags, mode);
6190}
6191
6192/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006193 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006194 */
6195 FILE *
6196mch_fopen(char *name, char *mode)
6197{
6198 WCHAR *wn, *wm;
6199 FILE *f = NULL;
6200
6201 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6202# ifdef __BORLANDC__
6203 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6204 && g_PlatformId == VER_PLATFORM_WIN32_NT
6205# endif
6206 )
6207 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006208# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006209 /* Work around an annoying assertion in the Microsoft debug CRT
6210 * when mode's text/binary setting doesn't match _get_fmode(). */
6211 char newMode = mode[strlen(mode) - 1];
6212 int oldMode = 0;
6213
6214 _get_fmode(&oldMode);
6215 if (newMode == 't')
6216 _set_fmode(_O_TEXT);
6217 else if (newMode == 'b')
6218 _set_fmode(_O_BINARY);
6219# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006220 wn = enc_to_utf16(name, NULL);
6221 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222 if (wn != NULL && wm != NULL)
6223 f = _wfopen(wn, wm);
6224 vim_free(wn);
6225 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006226
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006227# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006228 _set_fmode(oldMode);
6229# endif
6230
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006231 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006232 return f;
6233 /* Retry with non-wide function (for Windows 98). Can't use
6234 * GetLastError() here and it's unclear what errno gets set to if
6235 * the _wfopen() fails for missing wide functions. */
6236 }
6237
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006238 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6239 * and shorter than _MAX_PATH characters successfully, but sometimes it
6240 * causes unexpected error in another part. We make it an error explicitly
6241 * here. */
6242 if (strlen(name) >= _MAX_PATH)
6243 return NULL;
6244
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245 return fopen(name, mode);
6246}
6247#endif
6248
6249#ifdef FEAT_MBYTE
6250/*
6251 * SUB STREAM (aka info stream) handling:
6252 *
6253 * NTFS can have sub streams for each file. Normal contents of file is
6254 * stored in the main stream, and extra contents (author information and
6255 * title and so on) can be stored in sub stream. After Windows 2000, user
6256 * can access and store those informations in sub streams via explorer's
6257 * property menuitem in right click menu. Those informations in sub streams
6258 * were lost when copying only the main stream. So we have to copy sub
6259 * streams.
6260 *
6261 * Incomplete explanation:
6262 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6263 * More useful info and an example:
6264 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6265 */
6266
6267/*
6268 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6269 * and write to stream "substream" of file "to".
6270 * Errors are ignored.
6271 */
6272 static void
6273copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6274{
6275 HANDLE hTo;
6276 WCHAR *to_name;
6277
6278 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6279 wcscpy(to_name, to);
6280 wcscat(to_name, substream);
6281
6282 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6283 FILE_ATTRIBUTE_NORMAL, NULL);
6284 if (hTo != INVALID_HANDLE_VALUE)
6285 {
6286 long done;
6287 DWORD todo;
6288 DWORD readcnt, written;
6289 char buf[4096];
6290
6291 /* Copy block of bytes at a time. Abort when something goes wrong. */
6292 for (done = 0; done < len; done += written)
6293 {
6294 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006295 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6296 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006297 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6298 FALSE, FALSE, context)
6299 || readcnt != todo
6300 || !WriteFile(hTo, buf, todo, &written, NULL)
6301 || written != todo)
6302 break;
6303 }
6304 CloseHandle(hTo);
6305 }
6306
6307 free(to_name);
6308}
6309
6310/*
6311 * Copy info streams from file "from" to file "to".
6312 */
6313 static void
6314copy_infostreams(char_u *from, char_u *to)
6315{
6316 WCHAR *fromw;
6317 WCHAR *tow;
6318 HANDLE sh;
6319 WIN32_STREAM_ID sid;
6320 int headersize;
6321 WCHAR streamname[_MAX_PATH];
6322 DWORD readcount;
6323 void *context = NULL;
6324 DWORD lo, hi;
6325 int len;
6326
6327 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006328 fromw = enc_to_utf16(from, NULL);
6329 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006330 if (fromw != NULL && tow != NULL)
6331 {
6332 /* Open the file for reading. */
6333 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6334 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6335 if (sh != INVALID_HANDLE_VALUE)
6336 {
6337 /* Use BackupRead() to find the info streams. Repeat until we
6338 * have done them all.*/
6339 for (;;)
6340 {
6341 /* Get the header to find the length of the stream name. If
6342 * the "readcount" is zero we have done all info streams. */
6343 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006344 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6346 &readcount, FALSE, FALSE, &context)
6347 || readcount == 0)
6348 break;
6349
6350 /* We only deal with streams that have a name. The normal
6351 * file data appears to be without a name, even though docs
6352 * suggest it is called "::$DATA". */
6353 if (sid.dwStreamNameSize > 0)
6354 {
6355 /* Read the stream name. */
6356 if (!BackupRead(sh, (LPBYTE)streamname,
6357 sid.dwStreamNameSize,
6358 &readcount, FALSE, FALSE, &context))
6359 break;
6360
6361 /* Copy an info stream with a name ":anything:$DATA".
6362 * Skip "::$DATA", it has no stream name (examples suggest
6363 * it might be used for the normal file contents).
6364 * Note that BackupRead() counts bytes, but the name is in
6365 * wide characters. */
6366 len = readcount / sizeof(WCHAR);
6367 streamname[len] = 0;
6368 if (len > 7 && wcsicmp(streamname + len - 6,
6369 L":$DATA") == 0)
6370 {
6371 streamname[len - 6] = 0;
6372 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006373 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006374 }
6375 }
6376
6377 /* Advance to the next stream. We might try seeking too far,
6378 * but BackupSeek() doesn't skip over stream borders, thus
6379 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006380 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381 &lo, &hi, &context);
6382 }
6383
6384 /* Clear the context. */
6385 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6386
6387 CloseHandle(sh);
6388 }
6389 }
6390 vim_free(fromw);
6391 vim_free(tow);
6392}
6393#endif
6394
6395/*
6396 * Copy file attributes from file "from" to file "to".
6397 * For Windows NT and later we copy info streams.
6398 * Always returns zero, errors are ignored.
6399 */
6400 int
6401mch_copy_file_attribute(char_u *from, char_u *to)
6402{
6403#ifdef FEAT_MBYTE
6404 /* File streams only work on Windows NT and later. */
6405 PlatformId();
6406 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6407 copy_infostreams(from, to);
6408#endif
6409 return 0;
6410}
6411
6412#if defined(MYRESETSTKOFLW) || defined(PROTO)
6413/*
6414 * Recreate a destroyed stack guard page in win32.
6415 * Written by Benjamin Peterson.
6416 */
6417
6418/* These magic numbers are from the MS header files */
6419#define MIN_STACK_WIN9X 17
6420#define MIN_STACK_WINNT 2
6421
6422/*
6423 * This function does the same thing as _resetstkoflw(), which is only
6424 * available in DevStudio .net and later.
6425 * Returns 0 for failure, 1 for success.
6426 */
6427 int
6428myresetstkoflw(void)
6429{
6430 BYTE *pStackPtr;
6431 BYTE *pGuardPage;
6432 BYTE *pStackBase;
6433 BYTE *pLowestPossiblePage;
6434 MEMORY_BASIC_INFORMATION mbi;
6435 SYSTEM_INFO si;
6436 DWORD nPageSize;
6437 DWORD dummy;
6438
6439 /* This code will not work on win32s. */
6440 PlatformId();
6441 if (g_PlatformId == VER_PLATFORM_WIN32s)
6442 return 0;
6443
6444 /* We need to know the system page size. */
6445 GetSystemInfo(&si);
6446 nPageSize = si.dwPageSize;
6447
6448 /* ...and the current stack pointer */
6449 pStackPtr = (BYTE*)_alloca(1);
6450
6451 /* ...and the base of the stack. */
6452 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6453 return 0;
6454 pStackBase = (BYTE*)mbi.AllocationBase;
6455
6456 /* ...and the page thats min_stack_req pages away from stack base; this is
6457 * the lowest page we could use. */
6458 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6459 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6460
6461 /* On Win95, we want the next page down from the end of the stack. */
6462 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6463 {
6464 /* Find the page that's only 1 page down from the page that the stack
6465 * ptr is in. */
6466 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6467 / (DWORD)nPageSize) - 1));
6468 if (pGuardPage < pLowestPossiblePage)
6469 return 0;
6470
6471 /* Apply the noaccess attribute to the page -- there's no guard
6472 * attribute in win95-type OSes. */
6473 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6474 return 0;
6475 }
6476 else
6477 {
6478 /* On NT, however, we want the first committed page in the stack Start
6479 * at the stack base and move forward through memory until we find a
6480 * committed block. */
6481 BYTE *pBlock = pStackBase;
6482
Bram Moolenaara466c992005-07-09 21:03:22 +00006483 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484 {
6485 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6486 return 0;
6487
6488 pBlock += mbi.RegionSize;
6489
6490 if (mbi.State & MEM_COMMIT)
6491 break;
6492 }
6493
6494 /* mbi now describes the first committed block in the stack. */
6495 if (mbi.Protect & PAGE_GUARD)
6496 return 1;
6497
6498 /* decide where the guard page should start */
6499 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6500 pGuardPage = pLowestPossiblePage;
6501 else
6502 pGuardPage = (BYTE*)mbi.BaseAddress;
6503
6504 /* allocate the guard page */
6505 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6506 return 0;
6507
6508 /* apply the guard attribute to the page */
6509 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6510 &dummy))
6511 return 0;
6512 }
6513
6514 return 1;
6515}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006516#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006518
6519#if defined(FEAT_MBYTE) || defined(PROTO)
6520/*
6521 * The command line arguments in UCS2
6522 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006523static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006524static LPWSTR *ArglistW = NULL;
6525static int global_argc = 0;
6526static char **global_argv;
6527
6528static int used_file_argc = 0; /* last argument in global_argv[] used
6529 for the argument list. */
6530static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6531 command line arguments added to
6532 the argument list */
6533static int used_file_count = 0; /* nr of entries in used_file_indexes */
6534static int used_file_literal = FALSE; /* take file names literally */
6535static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006536static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006537static int used_alist_count = 0;
6538
6539
6540/*
6541 * Get the command line arguments. Unicode version.
6542 * Returns argc. Zero when something fails.
6543 */
6544 int
6545get_cmd_argsW(char ***argvp)
6546{
6547 char **argv = NULL;
6548 int argc = 0;
6549 int i;
6550
Bram Moolenaar14993322014-09-09 12:25:33 +02006551 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006552 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6553 if (ArglistW != NULL)
6554 {
6555 argv = malloc((nArgsW + 1) * sizeof(char *));
6556 if (argv != NULL)
6557 {
6558 argc = nArgsW;
6559 argv[argc] = NULL;
6560 for (i = 0; i < argc; ++i)
6561 {
6562 int len;
6563
6564 /* Convert each Unicode argument to the current codepage. */
6565 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006566 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006567 (LPSTR *)&argv[i], &len, 0, 0);
6568 if (argv[i] == NULL)
6569 {
6570 /* Out of memory, clear everything. */
6571 while (i > 0)
6572 free(argv[--i]);
6573 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006574 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006575 argc = 0;
6576 }
6577 }
6578 }
6579 }
6580
6581 global_argc = argc;
6582 global_argv = argv;
6583 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006584 {
6585 if (used_file_indexes != NULL)
6586 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006587 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006588 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006589
6590 if (argvp != NULL)
6591 *argvp = argv;
6592 return argc;
6593}
6594
6595 void
6596free_cmd_argsW(void)
6597{
6598 if (ArglistW != NULL)
6599 {
6600 GlobalFree(ArglistW);
6601 ArglistW = NULL;
6602 }
6603}
6604
6605/*
6606 * Remember "name" is an argument that was added to the argument list.
6607 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6608 * is called.
6609 */
6610 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006611used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006612{
6613 int i;
6614
6615 if (used_file_indexes == NULL)
6616 return;
6617 for (i = used_file_argc + 1; i < global_argc; ++i)
6618 if (STRCMP(global_argv[i], name) == 0)
6619 {
6620 used_file_argc = i;
6621 used_file_indexes[used_file_count++] = i;
6622 break;
6623 }
6624 used_file_literal = literal;
6625 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006626 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006627}
6628
6629/*
6630 * Remember the length of the argument list as it was. If it changes then we
6631 * leave it alone when 'encoding' is set.
6632 */
6633 void
6634set_alist_count(void)
6635{
6636 used_alist_count = GARGCOUNT;
6637}
6638
6639/*
6640 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6641 * has been changed while starting up. Use the UCS-2 command line arguments
6642 * and convert them to 'encoding'.
6643 */
6644 void
6645fix_arg_enc(void)
6646{
6647 int i;
6648 int idx;
6649 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006650 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006651
6652 /* Safety checks:
6653 * - if argument count differs between the wide and non-wide argument
6654 * list, something must be wrong.
6655 * - the file name arguments must have been located.
6656 * - the length of the argument list wasn't changed by the user.
6657 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006658 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006659 || ArglistW == NULL
6660 || used_file_indexes == NULL
6661 || used_file_count == 0
6662 || used_alist_count != GARGCOUNT)
6663 return;
6664
Bram Moolenaar86b68352004-12-27 21:59:20 +00006665 /* Remember the buffer numbers for the arguments. */
6666 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6667 if (fnum_list == NULL)
6668 return; /* out of memory */
6669 for (i = 0; i < GARGCOUNT; ++i)
6670 fnum_list[i] = GARGLIST[i].ae_fnum;
6671
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006672 /* Clear the argument list. Make room for the new arguments. */
6673 alist_clear(&global_alist);
6674 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006675 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006676
6677 for (i = 0; i < used_file_count; ++i)
6678 {
6679 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006680 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006681 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006682 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006683#ifdef FEAT_DIFF
6684 /* When using diff mode may need to concatenate file name to
6685 * directory name. Just like it's done in main(). */
6686 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6687 && !mch_isdir(alist_name(&GARGLIST[0])))
6688 {
6689 char_u *r;
6690
6691 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6692 if (r != NULL)
6693 {
6694 vim_free(str);
6695 str = r;
6696 }
6697 }
6698#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006699 /* Re-use the old buffer by renaming it. When not using literal
6700 * names it's done by alist_expand() below. */
6701 if (used_file_literal)
6702 buf_set_name(fnum_list[i], str);
6703
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006704 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006705 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006706 }
6707
6708 if (!used_file_literal)
6709 {
6710 /* Now expand wildcards in the arguments. */
6711 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6712 * filename characters but are excluded from 'isfname' to make
6713 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6714 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006715 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006716 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6717 }
6718
6719 /* If wildcard expansion failed, we are editing the first file of the
6720 * arglist and there is no file name: Edit the first argument now. */
6721 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6722 {
6723 do_cmdline_cmd((char_u *)":rewind");
6724 if (GARGCOUNT == 1 && used_file_full_path)
6725 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6726 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006727
6728 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006729}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006730#endif