blob: cc5fc3dee9813be594d112d9743c0def1a5392dd [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;
Bram Moolenaaref269542016-01-19 13:22:12 +0100104typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000105typedef int HDC;
106typedef int HFONT;
107typedef int HICON;
108typedef int HINSTANCE;
109typedef int HWND;
110typedef int INPUT_RECORD;
111typedef int KEY_EVENT_RECORD;
112typedef int LOGFONT;
113typedef int LPBOOL;
114typedef int LPCTSTR;
115typedef int LPDWORD;
116typedef int LPSTR;
117typedef int LPTSTR;
118typedef int LPVOID;
119typedef int MOUSE_EVENT_RECORD;
120typedef int PACL;
121typedef int PDWORD;
122typedef int PHANDLE;
123typedef int PRINTDLG;
124typedef int PSECURITY_DESCRIPTOR;
125typedef int PSID;
126typedef int SECURITY_INFORMATION;
127typedef int SHORT;
128typedef int SMALL_RECT;
129typedef int TEXTMETRIC;
130typedef int TOKEN_INFORMATION_CLASS;
131typedef int TRUSTEE;
132typedef int WORD;
133typedef int WCHAR;
134typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100135typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200136typedef int SE_OBJECT_TYPE;
137typedef int PSNSECINFO;
138typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100139typedef int STARTUPINFO;
140typedef int PROCESS_INFORMATION;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000141#endif
142
143#ifndef FEAT_GUI_W32
144/* Undocumented API in kernel32.dll needed to work around dead key bug in
145 * console-mode applications in NT 4.0. If you switch keyboard layouts
146 * in a console app to a layout that includes dead keys and then hit a
147 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
148 * and Michael Dietrich for helping me figure out this workaround.
149 */
150
151/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
152#ifndef WINBASEAPI
153# define WINBASEAPI __stdcall
154#endif
155#if defined(__BORLANDC__)
156typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
157#else
158typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
159#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000160static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161#endif
162
163#if defined(__BORLANDC__)
164/* Strangely Borland uses a non-standard name. */
165# define wcsicmp(a, b) wcscmpi((a), (b))
166#endif
167
Bram Moolenaar82881492012-11-20 16:53:39 +0100168#ifndef PROTO
169
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200170/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200171#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100172LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200173BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
174BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
175BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
176#endif
177
Bram Moolenaar82881492012-11-20 16:53:39 +0100178#endif /* PROTO */
179
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180#ifndef FEAT_GUI_W32
181/* Win32 Console handles for input and output */
182static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
183static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
184
185/* Win32 Screen buffer,coordinate,console I/O information */
186static SMALL_RECT g_srScrollRegion;
187static COORD g_coord; /* 0-based, but external coords are 1-based */
188
189/* The attribute of the screen when the editor was started */
190static WORD g_attrDefault = 7; /* lightgray text on black background */
191static WORD g_attrCurrent;
192
193static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
194static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
195static int g_fForceExit = FALSE; /* set when forcefully exiting */
196
197static void termcap_mode_start(void);
198static void termcap_mode_end(void);
199static void clear_chars(COORD coord, DWORD n);
200static void clear_screen(void);
201static void clear_to_end_of_display(void);
202static void clear_to_end_of_line(void);
203static void scroll(unsigned cLines);
204static void set_scroll_region(unsigned left, unsigned top,
205 unsigned right, unsigned bottom);
206static void insert_lines(unsigned cLines);
207static void delete_lines(unsigned cLines);
208static void gotoxy(unsigned x, unsigned y);
209static void normvideo(void);
210static void textattr(WORD wAttr);
211static void textcolor(WORD wAttr);
212static void textbackground(WORD wAttr);
213static void standout(void);
214static void standend(void);
215static void visual_bell(void);
216static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200217static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
218static WCHAR tgetch(int *pmodifiers, WCHAR *pch2);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000219static void create_conin(void);
220static int s_cursor_visible = TRUE;
221static int did_create_conin = FALSE;
222#else
223static int s_dont_use_vimrun = TRUE;
224static int need_vimrun_warning = FALSE;
225static char *vimrun_path = "vimrun ";
226#endif
227
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200228static int win32_getattrs(char_u *name);
229static int win32_setattrs(char_u *name, int attrs);
230static int win32_set_archive(char_u *name);
231
Bram Moolenaar071d4272004-06-13 20:20:40 +0000232#ifndef FEAT_GUI_W32
233static int suppress_winsize = 1; /* don't fiddle with console */
234#endif
235
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200236static char_u *exe_path = NULL;
237
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100238static BOOL win8_or_later = FALSE;
239
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100240/*
241 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100242 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100243 */
244 static BOOL
245read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100246 HANDLE hInput,
247 INPUT_RECORD *lpBuffer,
248 DWORD nLength,
249 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100250{
251 enum
252 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100253 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100254 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100255 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100256 static DWORD s_dwIndex = 0;
257 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100258 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100259 int head;
260 int tail;
261 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100262
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200263 if (nLength == -2)
264 return (s_dwMax > 0) ? TRUE : FALSE;
265
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100266 if (!win8_or_later)
267 {
268 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200269 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
270 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100271 }
272
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100273 if (s_dwMax == 0)
274 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100275 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200276 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
277 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100278 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100279 s_dwIndex = 0;
280 s_dwMax = dwEvents;
281 if (dwEvents == 0)
282 {
283 *lpEvents = 0;
284 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100286
287 if (s_dwMax > 1)
288 {
289 head = 0;
290 tail = s_dwMax - 1;
291 while (head != tail)
292 {
293 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
294 && s_irCache[head + 1].EventType
295 == WINDOW_BUFFER_SIZE_EVENT)
296 {
297 /* Remove duplicate event to avoid flicker. */
298 for (i = head; i < tail; ++i)
299 s_irCache[i] = s_irCache[i + 1];
300 --tail;
301 continue;
302 }
303 head++;
304 }
305 s_dwMax = tail + 1;
306 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100307 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100308
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100309 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200310 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100311 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100312 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100313 return TRUE;
314}
315
316/*
317 * Version of PeekConsoleInput() that works with IME.
318 */
319 static BOOL
320peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100321 HANDLE hInput,
322 INPUT_RECORD *lpBuffer,
323 DWORD nLength,
324 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100325{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100326 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100327}
328
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200329 static DWORD
330msg_wait_for_multiple_objects(
331 DWORD nCount,
332 LPHANDLE pHandles,
333 BOOL fWaitAll,
334 DWORD dwMilliseconds,
335 DWORD dwWakeMask)
336{
337 if (read_console_input(NULL, NULL, -2, NULL))
338 return WAIT_OBJECT_0;
339 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
340 dwMilliseconds, dwWakeMask);
341}
342
343 static DWORD
344wait_for_single_object(
345 HANDLE hHandle,
346 DWORD dwMilliseconds)
347{
348 if (read_console_input(NULL, NULL, -2, NULL))
349 return WAIT_OBJECT_0;
350 return WaitForSingleObject(hHandle, dwMilliseconds);
351}
352
Bram Moolenaar071d4272004-06-13 20:20:40 +0000353 static void
354get_exe_name(void)
355{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100356 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
357 * as the maximum length that works (plus a NUL byte). */
358#define MAX_ENV_PATH_LEN 8192
359 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200360 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000361
362 if (exe_name == NULL)
363 {
364 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100365 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366 if (*temp != NUL)
367 exe_name = FullName_save((char_u *)temp, FALSE);
368 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000369
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200370 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000371 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200372 exe_path = vim_strnsave(exe_name,
373 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200374 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000375 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200376 /* Append our starting directory to $PATH, so that when doing
377 * "!xxd" it's found in our starting directory. Needed because
378 * SearchPath() also looks there. */
379 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100380 if (p == NULL
381 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200382 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100383 if (p == NULL || *p == NUL)
384 temp[0] = NUL;
385 else
386 {
387 STRCPY(temp, p);
388 STRCAT(temp, ";");
389 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200390 STRCAT(temp, exe_path);
391 vim_setenv((char_u *)"PATH", temp);
392 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000393 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000394 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000395}
396
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200397/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100398 * Unescape characters in "p" that appear in "escaped".
399 */
400 static void
401unescape_shellxquote(char_u *p, char_u *escaped)
402{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100403 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100404 int n;
405
406 while (*p != NUL)
407 {
408 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
409 mch_memmove(p, p + 1, l--);
410#ifdef FEAT_MBYTE
411 n = (*mb_ptr2len)(p);
412#else
413 n = 1;
414#endif
415 p += n;
416 l -= n;
417 }
418}
419
420/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200421 * Load library "name".
422 */
423 HINSTANCE
424vimLoadLib(char *name)
425{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200426 HINSTANCE dll = NULL;
427 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200428
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200429 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
430 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200431 if (exe_path == NULL)
432 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200433 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200434 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200435#ifdef FEAT_MBYTE
436 WCHAR old_dirw[MAXPATHL];
437
438 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
439 {
440 /* Change directory to where the executable is, both to make
441 * sure we find a .dll there and to avoid looking for a .dll
442 * in the current directory. */
443 SetCurrentDirectory(exe_path);
444 dll = LoadLibrary(name);
445 SetCurrentDirectoryW(old_dirw);
446 return dll;
447 }
448 /* Retry with non-wide function (for Windows 98). */
449 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
450#endif
451 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
452 {
453 /* Change directory to where the executable is, both to make
454 * sure we find a .dll there and to avoid looking for a .dll
455 * in the current directory. */
456 SetCurrentDirectory(exe_path);
457 dll = LoadLibrary(name);
458 SetCurrentDirectory(old_dir);
459 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200460 }
461 return dll;
462}
463
Bram Moolenaar071d4272004-06-13 20:20:40 +0000464#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
465# ifndef GETTEXT_DLL
466# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100467# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000468# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200469/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000470static char *null_libintl_gettext(const char *);
471static char *null_libintl_textdomain(const char *);
472static char *null_libintl_bindtextdomain(const char *, const char *);
473static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200475static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000476char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
477char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
478char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000480char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
481 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000482
483 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100484dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000485{
486 int i;
487 static struct
488 {
489 char *name;
490 FARPROC *ptr;
491 } libintl_entry[] =
492 {
493 {"gettext", (FARPROC*)&dyn_libintl_gettext},
494 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
495 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
496 {NULL, NULL}
497 };
498
499 /* No need to initialize twice. */
500 if (hLibintlDLL)
501 return 1;
502 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100503 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100504#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100505 if (!hLibintlDLL)
506 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100507#endif
508 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200510 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200512 verbose_enter();
513 EMSG2(_(e_loadlib), GETTEXT_DLL);
514 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200516 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000517 }
518 for (i = 0; libintl_entry[i].name != NULL
519 && libintl_entry[i].ptr != NULL; ++i)
520 {
521 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
522 libintl_entry[i].name)) == NULL)
523 {
524 dyn_libintl_end();
525 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000526 {
527 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000528 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000529 verbose_leave();
530 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000531 return 0;
532 }
533 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000534
535 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000536 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000537 "bind_textdomain_codeset");
538 if (dyn_libintl_bind_textdomain_codeset == NULL)
539 dyn_libintl_bind_textdomain_codeset =
540 null_libintl_bind_textdomain_codeset;
541
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542 return 1;
543}
544
545 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100546dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000547{
548 if (hLibintlDLL)
549 FreeLibrary(hLibintlDLL);
550 hLibintlDLL = NULL;
551 dyn_libintl_gettext = null_libintl_gettext;
552 dyn_libintl_textdomain = null_libintl_textdomain;
553 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000554 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555}
556
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000557/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000559null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000560{
561 return (char*)msgid;
562}
563
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000564/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000565 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000566null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000567{
568 return NULL;
569}
570
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000571/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000572 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000573null_libintl_bind_textdomain_codeset(const char *domainname,
574 const char *codeset)
575{
576 return NULL;
577}
578
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000579/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000580 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000581null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582{
583 return NULL;
584}
585
586#endif /* DYNAMIC_GETTEXT */
587
588/* This symbol is not defined in older versions of the SDK or Visual C++ */
589
590#ifndef VER_PLATFORM_WIN32_WINDOWS
591# define VER_PLATFORM_WIN32_WINDOWS 1
592#endif
593
594DWORD g_PlatformId;
595
596#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100597# ifndef PROTO
598# include <aclapi.h>
599# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200600# ifndef PROTECTED_DACL_SECURITY_INFORMATION
601# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
602# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100603
Bram Moolenaar071d4272004-06-13 20:20:40 +0000604/*
605 * These are needed to dynamically load the ADVAPI DLL, which is not
606 * implemented under Windows 95 (and causes VIM to crash)
607 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200608typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000609 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200610typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
612 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200613# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200614typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200615 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200616typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200617 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
618 PSECURITY_DESCRIPTOR *);
619# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000620
621static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
622static PSNSECINFO pSetNamedSecurityInfo;
623static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200624# ifdef FEAT_MBYTE
625static PSNSECINFOW pSetNamedSecurityInfoW;
626static PGNSECINFOW pGetNamedSecurityInfoW;
627# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000628#endif
629
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200630typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
631
632static BOOL allowPiping = FALSE;
633static PSETHANDLEINFORMATION pSetHandleInformation;
634
Bram Moolenaar27515922013-06-29 15:36:26 +0200635#ifdef HAVE_ACL
636/*
637 * Enables or disables the specified privilege.
638 */
639 static BOOL
640win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
641{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100642 BOOL bResult;
643 LUID luid;
644 HANDLE hToken;
645 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200646
647 if (!OpenProcessToken(GetCurrentProcess(),
648 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
649 return FALSE;
650
651 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
652 {
653 CloseHandle(hToken);
654 return FALSE;
655 }
656
Bram Moolenaar45500912014-07-09 20:51:07 +0200657 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200658 tokenPrivileges.Privileges[0].Luid = luid;
659 tokenPrivileges.Privileges[0].Attributes = bEnable ?
660 SE_PRIVILEGE_ENABLED : 0;
661
662 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
663 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
664
665 CloseHandle(hToken);
666
667 return bResult && GetLastError() == ERROR_SUCCESS;
668}
669#endif
670
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671/*
672 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
673 * VER_PLATFORM_WIN32_WINDOWS (Win95).
674 */
675 void
676PlatformId(void)
677{
678 static int done = FALSE;
679
680 if (!done)
681 {
682 OSVERSIONINFO ovi;
683
684 ovi.dwOSVersionInfoSize = sizeof(ovi);
685 GetVersionEx(&ovi);
686
687 g_PlatformId = ovi.dwPlatformId;
688
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100689 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
690 || ovi.dwMajorVersion > 6)
691 win8_or_later = TRUE;
692
Bram Moolenaar071d4272004-06-13 20:20:40 +0000693#ifdef HAVE_ACL
694 /*
695 * Load the ADVAPI runtime if we are on anything
696 * other than Windows 95
697 */
698 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
699 {
700 /*
701 * do this load. Problems: Doesn't unload at end of run (this is
702 * theoretically okay, since Windows should unload it when VIM
703 * terminates). Should we be using the 'mch_libcall' routines?
704 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
705 * time we verify security...
706 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200707 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708 if (advapi_lib != NULL)
709 {
710 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
711 "SetNamedSecurityInfoA");
712 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
713 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200714# ifdef FEAT_MBYTE
715 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
716 "SetNamedSecurityInfoW");
717 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
718 "GetNamedSecurityInfoW");
719# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000720 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200721 || pGetNamedSecurityInfo == NULL
722# ifdef FEAT_MBYTE
723 || pSetNamedSecurityInfoW == NULL
724 || pGetNamedSecurityInfoW == NULL
725# endif
726 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727 {
728 /* If we can't get the function addresses, set advapi_lib
729 * to NULL so that we don't use them. */
730 FreeLibrary(advapi_lib);
731 advapi_lib = NULL;
732 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200733 /* Enable privilege for getting or setting SACLs. */
734 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 }
736 }
737#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200738 /*
739 * If we are on windows NT, try to load the pipe functions, only
740 * available from Win2K.
741 */
742 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
743 {
744 HANDLE kernel32 = GetModuleHandle("kernel32");
745 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
746 kernel32, "SetHandleInformation");
747
748 allowPiping = pSetHandleInformation != NULL;
749 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 done = TRUE;
751 }
752}
753
754/*
755 * Return TRUE when running on Windows 95 (or 98 or ME).
756 * Only to be used after mch_init().
757 */
758 int
759mch_windows95(void)
760{
761 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
762}
763
764#ifdef FEAT_GUI_W32
765/*
766 * Used to work around the "can't do synchronous spawn"
767 * problem on Win32s, without resorting to Universal Thunk.
768 */
769static int old_num_windows;
770static int num_windows;
771
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000772/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000773 static BOOL CALLBACK
774win32ssynch_cb(HWND hwnd, LPARAM lparam)
775{
776 num_windows++;
777 return TRUE;
778}
779#endif
780
781#ifndef FEAT_GUI_W32
782
783#define SHIFT (SHIFT_PRESSED)
784#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
785#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
786#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
787
788
789/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
790 * We map function keys to their ANSI terminal equivalents, as produced
791 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
792 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
793 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
794 * combinations of function/arrow/etc keys.
795 */
796
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000797static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000798{
799 WORD wVirtKey;
800 BOOL fAnsiKey;
801 int chAlone;
802 int chShift;
803 int chCtrl;
804 int chAlt;
805} VirtKeyMap[] =
806{
807
808/* Key ANSI alone shift ctrl alt */
809 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
810
811 { VK_F1, TRUE, ';', 'T', '^', 'h', },
812 { VK_F2, TRUE, '<', 'U', '_', 'i', },
813 { VK_F3, TRUE, '=', 'V', '`', 'j', },
814 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
815 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
816 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
817 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
818 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
819 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
820 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
821 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
822 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
823
824 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
825 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
826 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
827 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
828 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
829 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
830 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
831 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
832 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
833 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
834
835 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
836
837#if 0
838 /* Most people don't have F13-F20, but what the hell... */
839 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
840 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
841 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
842 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
843 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
844 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
845 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
846 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
847#endif
848 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
849 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
850 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
851 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
852
853 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
854 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
855 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
856 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
857 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
858 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
859 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
860 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
861 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
862 /* Sorry, out of number space! <negri>*/
863 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
864
865};
866
867
868#ifdef _MSC_VER
869// The ToAscii bug destroys several registers. Need to turn off optimization
870// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000871# pragma warning(push)
872# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873# pragma optimize("", off)
874#endif
875
876#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200877# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200879# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000880#endif
881
882/* The return code indicates key code size. */
883 static int
884#ifdef __BORLANDC__
885 __stdcall
886#endif
887win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000888 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889{
890 UINT uMods = pker->dwControlKeyState;
891 static int s_iIsDead = 0;
892 static WORD awAnsiCode[2];
893 static BYTE abKeystate[256];
894
895
896 if (s_iIsDead == 2)
897 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200898 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899 s_iIsDead = 0;
900 return 1;
901 }
902
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200903 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904 return 1;
905
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200906 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907
908 // Should only be non-NULL on NT 4.0
909 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
910 {
911 CHAR szKLID[KL_NAMELENGTH];
912
913 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
914 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
915 }
916
917 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200918 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000919
920 if (uMods & SHIFT_PRESSED)
921 abKeystate[VK_SHIFT] = 0x80;
922 if (uMods & CAPSLOCK_ON)
923 abKeystate[VK_CAPITAL] = 1;
924
925 if ((uMods & ALT_GR) == ALT_GR)
926 {
927 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
928 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
929 }
930
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200931 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
932 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000933
934 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200935 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936
937 return s_iIsDead;
938}
939
940#ifdef _MSC_VER
941/* MUST switch optimization on again here, otherwise a call to
942 * decode_key_event() may crash (e.g. when hitting caps-lock) */
943# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000944# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000945
946# if (_MSC_VER < 1100)
947/* MUST turn off global optimisation for this next function, or
948 * pressing ctrl-minus in insert mode crashes Vim when built with
949 * VC4.1. -- negri. */
950# pragma optimize("g", off)
951# endif
952#endif
953
954static BOOL g_fJustGotFocus = FALSE;
955
956/*
957 * Decode a KEY_EVENT into one or two keystrokes
958 */
959 static BOOL
960decode_key_event(
961 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200962 WCHAR *pch,
963 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000964 int *pmodifiers,
965 BOOL fDoPost)
966{
967 int i;
968 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
969
970 *pch = *pch2 = NUL;
971 g_fJustGotFocus = FALSE;
972
973 /* ignore key up events */
974 if (!pker->bKeyDown)
975 return FALSE;
976
977 /* ignore some keystrokes */
978 switch (pker->wVirtualKeyCode)
979 {
980 /* modifiers */
981 case VK_SHIFT:
982 case VK_CONTROL:
983 case VK_MENU: /* Alt key */
984 return FALSE;
985
986 default:
987 break;
988 }
989
990 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200991 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992 {
993 /* Ctrl-6 is Ctrl-^ */
994 if (pker->wVirtualKeyCode == '6')
995 {
996 *pch = Ctrl_HAT;
997 return TRUE;
998 }
999 /* Ctrl-2 is Ctrl-@ */
1000 else if (pker->wVirtualKeyCode == '2')
1001 {
1002 *pch = NUL;
1003 return TRUE;
1004 }
1005 /* Ctrl-- is Ctrl-_ */
1006 else if (pker->wVirtualKeyCode == 0xBD)
1007 {
1008 *pch = Ctrl__;
1009 return TRUE;
1010 }
1011 }
1012
1013 /* Shift-TAB */
1014 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
1015 {
1016 *pch = K_NUL;
1017 *pch2 = '\017';
1018 return TRUE;
1019 }
1020
1021 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
1022 {
1023 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
1024 {
1025 if (nModifs == 0)
1026 *pch = VirtKeyMap[i].chAlone;
1027 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
1028 *pch = VirtKeyMap[i].chShift;
1029 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
1030 *pch = VirtKeyMap[i].chCtrl;
1031 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1032 *pch = VirtKeyMap[i].chAlt;
1033
1034 if (*pch != 0)
1035 {
1036 if (VirtKeyMap[i].fAnsiKey)
1037 {
1038 *pch2 = *pch;
1039 *pch = K_NUL;
1040 }
1041
1042 return TRUE;
1043 }
1044 }
1045 }
1046
1047 i = win32_kbd_patch_key(pker);
1048
1049 if (i < 0)
1050 *pch = NUL;
1051 else
1052 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001053 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001054
1055 if (pmodifiers != NULL)
1056 {
1057 /* Pass on the ALT key as a modifier, but only when not combined
1058 * with CTRL (which is ALTGR). */
1059 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1060 *pmodifiers |= MOD_MASK_ALT;
1061
1062 /* Pass on SHIFT only for special keys, because we don't know when
1063 * it's already included with the character. */
1064 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1065 *pmodifiers |= MOD_MASK_SHIFT;
1066
1067 /* Pass on CTRL only for non-special keys, because we don't know
1068 * when it's already included with the character. And not when
1069 * combined with ALT (which is ALTGR). */
1070 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1071 && *pch >= 0x20 && *pch < 0x80)
1072 *pmodifiers |= MOD_MASK_CTRL;
1073 }
1074 }
1075
1076 return (*pch != NUL);
1077}
1078
1079#ifdef _MSC_VER
1080# pragma optimize("", on)
1081#endif
1082
1083#endif /* FEAT_GUI_W32 */
1084
1085
1086#ifdef FEAT_MOUSE
1087
1088/*
1089 * For the GUI the mouse handling is in gui_w32.c.
1090 */
1091# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001092/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001094mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095{
1096}
1097# else
1098static int g_fMouseAvail = FALSE; /* mouse present */
1099static int g_fMouseActive = FALSE; /* mouse enabled */
1100static int g_nMouseClick = -1; /* mouse status */
1101static int g_xMouse; /* mouse x coordinate */
1102static int g_yMouse; /* mouse y coordinate */
1103
1104/*
1105 * Enable or disable mouse input
1106 */
1107 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001108mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109{
1110 DWORD cmodein;
1111
1112 if (!g_fMouseAvail)
1113 return;
1114
1115 g_fMouseActive = on;
1116 GetConsoleMode(g_hConIn, &cmodein);
1117
1118 if (g_fMouseActive)
1119 cmodein |= ENABLE_MOUSE_INPUT;
1120 else
1121 cmodein &= ~ENABLE_MOUSE_INPUT;
1122
1123 SetConsoleMode(g_hConIn, cmodein);
1124}
1125
Bram Moolenaar4d919d72016-02-05 22:36:41 +01001126#ifdef FEAT_CHANNEL
1127 static int
1128handle_channel_event(void)
1129{
1130 int ret;
1131 fd_set rfds;
1132 int maxfd;
1133
1134 FD_ZERO(&rfds);
1135 maxfd = channel_select_setup(-1, &rfds);
1136 if (maxfd >= 0)
1137 {
1138 struct timeval tv;
1139
1140 tv.tv_sec = 0;
1141 tv.tv_usec = 0;
1142 ret = select(maxfd + 1, &rfds, NULL, NULL, &tv);
1143 if (ret > 0 && channel_select_check(ret, &rfds) > 0)
1144 return TRUE;
1145 }
1146 return FALSE;
1147}
1148#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001149
1150/*
1151 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1152 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1153 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1154 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1155 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1156 * and we return the mouse position in g_xMouse and g_yMouse.
1157 *
1158 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1159 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1160 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1161 *
1162 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1163 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1164 *
1165 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1166 * moves, even if it stays within the same character cell. We ignore
1167 * all MOUSE_MOVED messages if the position hasn't really changed, and
1168 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1169 * we're only interested in MOUSE_DRAG).
1170 *
1171 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1172 * 2-button mouses by pressing the left & right buttons simultaneously.
1173 * In practice, it's almost impossible to click both at the same time,
1174 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1175 * in such cases, if the user is clicking quickly.
1176 */
1177 static BOOL
1178decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001179 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001180{
1181 static int s_nOldButton = -1;
1182 static int s_nOldMouseClick = -1;
1183 static int s_xOldMouse = -1;
1184 static int s_yOldMouse = -1;
1185 static linenr_T s_old_topline = 0;
1186#ifdef FEAT_DIFF
1187 static int s_old_topfill = 0;
1188#endif
1189 static int s_cClicks = 1;
1190 static BOOL s_fReleased = TRUE;
1191 static DWORD s_dwLastClickTime = 0;
1192 static BOOL s_fNextIsMiddle = FALSE;
1193
1194 static DWORD cButtons = 0; /* number of buttons supported */
1195
1196 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1197 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1198 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1199 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1200
1201 int nButton;
1202
1203 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1204 cButtons = 2;
1205
1206 if (!g_fMouseAvail || !g_fMouseActive)
1207 {
1208 g_nMouseClick = -1;
1209 return FALSE;
1210 }
1211
1212 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1213 if (g_fJustGotFocus)
1214 {
1215 g_fJustGotFocus = FALSE;
1216 return FALSE;
1217 }
1218
1219 /* unprocessed mouse click? */
1220 if (g_nMouseClick != -1)
1221 return TRUE;
1222
1223 nButton = -1;
1224 g_xMouse = pmer->dwMousePosition.X;
1225 g_yMouse = pmer->dwMousePosition.Y;
1226
1227 if (pmer->dwEventFlags == MOUSE_MOVED)
1228 {
1229 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1230 * events even when the mouse moves only within a char cell.) */
1231 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1232 return FALSE;
1233 }
1234
1235 /* If no buttons are pressed... */
1236 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1237 {
1238 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1239 if (s_fReleased)
1240 return FALSE;
1241
1242 nButton = MOUSE_RELEASE;
1243 s_fReleased = TRUE;
1244 }
1245 else /* one or more buttons pressed */
1246 {
1247 /* on a 2-button mouse, hold down left and right buttons
1248 * simultaneously to get MIDDLE. */
1249
1250 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1251 {
1252 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1253
1254 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001255 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001256 if (dwLR == LEFT || dwLR == RIGHT)
1257 {
1258 for (;;)
1259 {
1260 /* wait a short time for next input event */
1261 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1262 != WAIT_OBJECT_0)
1263 break;
1264 else
1265 {
1266 DWORD cRecords = 0;
1267 INPUT_RECORD ir;
1268 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1269
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001270 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001271
1272 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1273 || !(pmer2->dwButtonState & LEFT_RIGHT))
1274 break;
1275 else
1276 {
1277 if (pmer2->dwEventFlags != MOUSE_MOVED)
1278 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001279 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001280
1281 return decode_mouse_event(pmer2);
1282 }
1283 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1284 s_yOldMouse == pmer2->dwMousePosition.Y)
1285 {
1286 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001287 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001288
1289 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001290 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001291
1292 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1293 break;
1294 }
1295 else
1296 break;
1297 }
1298 }
1299 }
1300 }
1301 }
1302
1303 if (s_fNextIsMiddle)
1304 {
1305 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1306 ? MOUSE_DRAG : MOUSE_MIDDLE;
1307 s_fNextIsMiddle = FALSE;
1308 }
1309 else if (cButtons == 2 &&
1310 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1311 {
1312 nButton = MOUSE_MIDDLE;
1313
1314 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1315 {
1316 s_fNextIsMiddle = TRUE;
1317 nButton = MOUSE_RELEASE;
1318 }
1319 }
1320 else if ((pmer->dwButtonState & LEFT) == LEFT)
1321 nButton = MOUSE_LEFT;
1322 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1323 nButton = MOUSE_MIDDLE;
1324 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1325 nButton = MOUSE_RIGHT;
1326
1327 if (! s_fReleased && ! s_fNextIsMiddle
1328 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1329 return FALSE;
1330
1331 s_fReleased = s_fNextIsMiddle;
1332 }
1333
1334 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1335 {
1336 /* button pressed or released, without mouse moving */
1337 if (nButton != -1 && nButton != MOUSE_RELEASE)
1338 {
1339 DWORD dwCurrentTime = GetTickCount();
1340
1341 if (s_xOldMouse != g_xMouse
1342 || s_yOldMouse != g_yMouse
1343 || s_nOldButton != nButton
1344 || s_old_topline != curwin->w_topline
1345#ifdef FEAT_DIFF
1346 || s_old_topfill != curwin->w_topfill
1347#endif
1348 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1349 {
1350 s_cClicks = 1;
1351 }
1352 else if (++s_cClicks > 4)
1353 {
1354 s_cClicks = 1;
1355 }
1356
1357 s_dwLastClickTime = dwCurrentTime;
1358 }
1359 }
1360 else if (pmer->dwEventFlags == MOUSE_MOVED)
1361 {
1362 if (nButton != -1 && nButton != MOUSE_RELEASE)
1363 nButton = MOUSE_DRAG;
1364
1365 s_cClicks = 1;
1366 }
1367
1368 if (nButton == -1)
1369 return FALSE;
1370
1371 if (nButton != MOUSE_RELEASE)
1372 s_nOldButton = nButton;
1373
1374 g_nMouseClick = nButton;
1375
1376 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1377 g_nMouseClick |= MOUSE_SHIFT;
1378 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1379 g_nMouseClick |= MOUSE_CTRL;
1380 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1381 g_nMouseClick |= MOUSE_ALT;
1382
1383 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1384 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1385
1386 /* only pass on interesting (i.e., different) mouse events */
1387 if (s_xOldMouse == g_xMouse
1388 && s_yOldMouse == g_yMouse
1389 && s_nOldMouseClick == g_nMouseClick)
1390 {
1391 g_nMouseClick = -1;
1392 return FALSE;
1393 }
1394
1395 s_xOldMouse = g_xMouse;
1396 s_yOldMouse = g_yMouse;
1397 s_old_topline = curwin->w_topline;
1398#ifdef FEAT_DIFF
1399 s_old_topfill = curwin->w_topfill;
1400#endif
1401 s_nOldMouseClick = g_nMouseClick;
1402
1403 return TRUE;
1404}
1405
1406# endif /* FEAT_GUI_W32 */
1407#endif /* FEAT_MOUSE */
1408
1409
1410#ifdef MCH_CURSOR_SHAPE
1411/*
1412 * Set the shape of the cursor.
1413 * 'thickness' can be from 1 (thin) to 99 (block)
1414 */
1415 static void
1416mch_set_cursor_shape(int thickness)
1417{
1418 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1419 ConsoleCursorInfo.dwSize = thickness;
1420 ConsoleCursorInfo.bVisible = s_cursor_visible;
1421
1422 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1423 if (s_cursor_visible)
1424 SetConsoleCursorPosition(g_hConOut, g_coord);
1425}
1426
1427 void
1428mch_update_cursor(void)
1429{
1430 int idx;
1431 int thickness;
1432
1433 /*
1434 * How the cursor is drawn depends on the current mode.
1435 */
1436 idx = get_shape_idx(FALSE);
1437
1438 if (shape_table[idx].shape == SHAPE_BLOCK)
1439 thickness = 99; /* 100 doesn't work on W95 */
1440 else
1441 thickness = shape_table[idx].percentage;
1442 mch_set_cursor_shape(thickness);
1443}
1444#endif
1445
1446#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1447/*
1448 * Handle FOCUS_EVENT.
1449 */
1450 static void
1451handle_focus_event(INPUT_RECORD ir)
1452{
1453 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1454 ui_focus_change((int)g_fJustGotFocus);
1455}
1456
1457/*
1458 * Wait until console input from keyboard or mouse is available,
1459 * or the time is up.
1460 * Return TRUE if something is available FALSE if not.
1461 */
1462 static int
1463WaitForChar(long msec)
1464{
1465 DWORD dwNow = 0, dwEndTime = 0;
1466 INPUT_RECORD ir;
1467 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001468 WCHAR ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001469
1470 if (msec > 0)
1471 /* Wait until the specified time has elapsed. */
1472 dwEndTime = GetTickCount() + msec;
1473 else if (msec < 0)
1474 /* Wait forever. */
1475 dwEndTime = INFINITE;
1476
1477 /* We need to loop until the end of the time period, because
1478 * we might get multiple unusable mouse events in that time.
1479 */
1480 for (;;)
1481 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001482#ifdef MESSAGE_QUEUE
1483 parse_queued_messages();
1484#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001485#ifdef FEAT_MZSCHEME
1486 mzvim_check_threads();
1487#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488#ifdef FEAT_CLIENTSERVER
1489 serverProcessPendingMessages();
1490#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001491
1492#ifdef FEAT_CHANNEL
Bram Moolenaar4d919d72016-02-05 22:36:41 +01001493 if (handle_channel_event())
1494 return TRUE;
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001495#endif
1496
Bram Moolenaar071d4272004-06-13 20:20:40 +00001497 if (0
1498#ifdef FEAT_MOUSE
1499 || g_nMouseClick != -1
1500#endif
1501#ifdef FEAT_CLIENTSERVER
1502 || input_available()
1503#endif
1504 )
1505 return TRUE;
1506
1507 if (msec > 0)
1508 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001509 /* If the specified wait time has passed, return. Beware that
1510 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001512 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513 break;
1514 }
1515 if (msec != 0)
1516 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001517 DWORD dwWaitTime = dwEndTime - dwNow;
1518
1519#ifdef FEAT_MZSCHEME
1520 if (mzthreads_allowed() && p_mzq > 0
1521 && (msec < 0 || (long)dwWaitTime > p_mzq))
1522 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1523#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001524#ifdef FEAT_CLIENTSERVER
1525 /* Wait for either an event on the console input or a message in
1526 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001527 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001528 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001530 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531#endif
1532 continue;
1533 }
1534
1535 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001536 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537
1538#ifdef FEAT_MBYTE_IME
1539 if (State & CMDLINE && msg_row == Rows - 1)
1540 {
1541 CONSOLE_SCREEN_BUFFER_INFO csbi;
1542
1543 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1544 {
1545 if (csbi.dwCursorPosition.Y != msg_row)
1546 {
1547 /* The screen is now messed up, must redraw the
1548 * command line and later all the windows. */
1549 redraw_all_later(CLEAR);
1550 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1551 redrawcmd();
1552 }
1553 }
1554 }
1555#endif
1556
1557 if (cRecords > 0)
1558 {
1559 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1560 {
1561#ifdef FEAT_MBYTE_IME
1562 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1563 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001564 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1566 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001567 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568 continue;
1569 }
1570#endif
1571 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1572 NULL, FALSE))
1573 return TRUE;
1574 }
1575
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001576 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577
1578 if (ir.EventType == FOCUS_EVENT)
1579 handle_focus_event(ir);
1580 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1581 shell_resized();
1582#ifdef FEAT_MOUSE
1583 else if (ir.EventType == MOUSE_EVENT
1584 && decode_mouse_event(&ir.Event.MouseEvent))
1585 return TRUE;
1586#endif
1587 }
1588 else if (msec == 0)
1589 break;
1590 }
1591
1592#ifdef FEAT_CLIENTSERVER
1593 /* Something might have been received while we were waiting. */
1594 if (input_available())
1595 return TRUE;
1596#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001597
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 return FALSE;
1599}
1600
1601#ifndef FEAT_GUI_MSWIN
1602/*
1603 * return non-zero if a character is available
1604 */
1605 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001606mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607{
1608 return WaitForChar(0L);
1609}
1610#endif
1611
1612/*
1613 * Create the console input. Used when reading stdin doesn't work.
1614 */
1615 static void
1616create_conin(void)
1617{
1618 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1619 FILE_SHARE_READ|FILE_SHARE_WRITE,
1620 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001621 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622 did_create_conin = TRUE;
1623}
1624
1625/*
1626 * Get a keystroke or a mouse event
1627 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001628 static WCHAR
1629tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001631 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001632
1633 for (;;)
1634 {
1635 INPUT_RECORD ir;
1636 DWORD cRecords = 0;
1637
1638#ifdef FEAT_CLIENTSERVER
1639 (void)WaitForChar(-1L);
1640 if (input_available())
1641 return 0;
1642# ifdef FEAT_MOUSE
1643 if (g_nMouseClick != -1)
1644 return 0;
1645# endif
1646#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001647 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001648 {
1649 if (did_create_conin)
1650 read_error_exit();
1651 create_conin();
1652 continue;
1653 }
1654
1655 if (ir.EventType == KEY_EVENT)
1656 {
1657 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1658 pmodifiers, TRUE))
1659 return ch;
1660 }
1661 else if (ir.EventType == FOCUS_EVENT)
1662 handle_focus_event(ir);
1663 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1664 shell_resized();
1665#ifdef FEAT_MOUSE
1666 else if (ir.EventType == MOUSE_EVENT)
1667 {
1668 if (decode_mouse_event(&ir.Event.MouseEvent))
1669 return 0;
1670 }
1671#endif
1672 }
1673}
1674#endif /* !FEAT_GUI_W32 */
1675
1676
1677/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001678 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001679 * Get one or more characters from the keyboard or the mouse.
1680 * If time == 0, do not wait for characters.
1681 * If time == n, wait a short time for characters.
1682 * If time == -1, wait forever for characters.
1683 * Returns the number of characters read into buf.
1684 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001685/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686 int
1687mch_inchar(
1688 char_u *buf,
1689 int maxlen,
1690 long time,
1691 int tb_change_cnt)
1692{
1693#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1694
1695 int len;
1696 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697#define TYPEAHEADLEN 20
1698 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1699 static int typeaheadlen = 0;
1700
1701 /* First use any typeahead that was kept because "buf" was too small. */
1702 if (typeaheadlen > 0)
1703 goto theend;
1704
1705#ifdef FEAT_SNIFF
1706 if (want_sniff_request)
1707 {
1708 if (sniff_request_waiting)
1709 {
1710 /* return K_SNIFF */
1711 typeahead[typeaheadlen++] = CSI;
1712 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1713 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1714 sniff_request_waiting = 0;
1715 want_sniff_request = 0;
1716 goto theend;
1717 }
1718 else if (time < 0 || time > 250)
1719 {
1720 /* don't wait too long, a request might be pending */
1721 time = 250;
1722 }
1723 }
1724#endif
1725
1726 if (time >= 0)
1727 {
1728 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001730 }
1731 else /* time == -1, wait forever */
1732 {
1733 mch_set_winsize_now(); /* Allow winsize changes from now on */
1734
Bram Moolenaar3918c952005-03-15 22:34:55 +00001735 /*
1736 * If there is no character available within 2 seconds (default)
1737 * write the autoscript file to disk. Or cause the CursorHold event
1738 * to be triggered.
1739 */
1740 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001741 {
1742#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001743 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001745 buf[0] = K_SPECIAL;
1746 buf[1] = KS_EXTRA;
1747 buf[2] = (int)KE_CURSORHOLD;
1748 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 }
1750#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001751 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 }
1753 }
1754
1755 /*
1756 * Try to read as many characters as there are, until the buffer is full.
1757 */
1758
1759 /* we will get at least one key. Get more if they are available. */
1760 g_fCBrkPressed = FALSE;
1761
1762#ifdef MCH_WRITE_DUMP
1763 if (fdDump)
1764 fputc('[', fdDump);
1765#endif
1766
1767 /* Keep looping until there is something in the typeahead buffer and more
1768 * to get and still room in the buffer (up to two bytes for a char and
1769 * three bytes for a modifier). */
1770 while ((typeaheadlen == 0 || WaitForChar(0L))
1771 && typeaheadlen + 5 <= TYPEAHEADLEN)
1772 {
1773 if (typebuf_changed(tb_change_cnt))
1774 {
1775 /* "buf" may be invalid now if a client put something in the
1776 * typeahead buffer and "buf" is in the typeahead buffer. */
1777 typeaheadlen = 0;
1778 break;
1779 }
1780#ifdef FEAT_MOUSE
1781 if (g_nMouseClick != -1)
1782 {
1783# ifdef MCH_WRITE_DUMP
1784 if (fdDump)
1785 fprintf(fdDump, "{%02x @ %d, %d}",
1786 g_nMouseClick, g_xMouse, g_yMouse);
1787# endif
1788 typeahead[typeaheadlen++] = ESC + 128;
1789 typeahead[typeaheadlen++] = 'M';
1790 typeahead[typeaheadlen++] = g_nMouseClick;
1791 typeahead[typeaheadlen++] = g_xMouse + '!';
1792 typeahead[typeaheadlen++] = g_yMouse + '!';
1793 g_nMouseClick = -1;
1794 }
1795 else
1796#endif
1797 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001798 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 int modifiers = 0;
1800
1801 c = tgetch(&modifiers, &ch2);
1802
1803 if (typebuf_changed(tb_change_cnt))
1804 {
1805 /* "buf" may be invalid now if a client put something in the
1806 * typeahead buffer and "buf" is in the typeahead buffer. */
1807 typeaheadlen = 0;
1808 break;
1809 }
1810
1811 if (c == Ctrl_C && ctrl_c_interrupts)
1812 {
1813#if defined(FEAT_CLIENTSERVER)
1814 trash_input_buf();
1815#endif
1816 got_int = TRUE;
1817 }
1818
1819#ifdef FEAT_MOUSE
1820 if (g_nMouseClick == -1)
1821#endif
1822 {
1823 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001824 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001826#ifdef FEAT_MBYTE
1827 if (ch2 == NUL)
1828 {
1829 int i;
1830 char_u *p;
1831 WCHAR ch[2];
1832
1833 ch[0] = c;
1834 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1835 {
1836 ch[1] = tgetch(&modifiers, &ch2);
1837 n++;
1838 }
1839 p = utf16_to_enc(ch, &n);
1840 if (p != NULL)
1841 {
1842 for (i = 0; i < n; i++)
1843 typeahead[typeaheadlen + i] = p[i];
1844 vim_free(p);
1845 }
1846 }
1847 else
1848#endif
1849 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001850 if (ch2 != NUL)
1851 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001852 typeahead[typeaheadlen + n] = 3;
1853 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
Bram Moolenaar45500912014-07-09 20:51:07 +02001854 n += 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001856
Bram Moolenaar45500912014-07-09 20:51:07 +02001857 if (conv)
1858 {
1859 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001860
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001861 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001862 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001863 char_u *e = typeahead + TYPEAHEADLEN;
1864
1865 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001866 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001867 if (*p == K_NUL)
1868 {
1869 ++p;
1870 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1871 *p = 3;
1872 ++n;
1873 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001874 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001875 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001876 }
1877 }
1878
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 /* Use the ALT key to set the 8th bit of the character
1880 * when it's one byte, the 8th bit isn't set yet and not
1881 * using a double-byte encoding (would become a lead
1882 * byte). */
1883 if ((modifiers & MOD_MASK_ALT)
1884 && n == 1
1885 && (typeahead[typeaheadlen] & 0x80) == 0
1886#ifdef FEAT_MBYTE
1887 && !enc_dbcs
1888#endif
1889 )
1890 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001891#ifdef FEAT_MBYTE
1892 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1893 typeahead + typeaheadlen);
1894#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001896#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 modifiers &= ~MOD_MASK_ALT;
1898 }
1899
1900 if (modifiers != 0)
1901 {
1902 /* Prepend modifiers to the character. */
1903 mch_memmove(typeahead + typeaheadlen + 3,
1904 typeahead + typeaheadlen, n);
1905 typeahead[typeaheadlen++] = K_SPECIAL;
1906 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1907 typeahead[typeaheadlen++] = modifiers;
1908 }
1909
1910 typeaheadlen += n;
1911
1912#ifdef MCH_WRITE_DUMP
1913 if (fdDump)
1914 fputc(c, fdDump);
1915#endif
1916 }
1917 }
1918 }
1919
1920#ifdef MCH_WRITE_DUMP
1921 if (fdDump)
1922 {
1923 fputs("]\n", fdDump);
1924 fflush(fdDump);
1925 }
1926#endif
1927
Bram Moolenaar071d4272004-06-13 20:20:40 +00001928theend:
1929 /* Move typeahead to "buf", as much as fits. */
1930 len = 0;
1931 while (len < maxlen && typeaheadlen > 0)
1932 {
1933 buf[len++] = typeahead[0];
1934 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1935 }
1936 return len;
1937
1938#else /* FEAT_GUI_W32 */
1939 return 0;
1940#endif /* FEAT_GUI_W32 */
1941}
1942
Bram Moolenaar82881492012-11-20 16:53:39 +01001943#ifndef PROTO
1944# ifndef __MINGW32__
1945# include <shellapi.h> /* required for FindExecutable() */
1946# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947#endif
1948
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001949/*
1950 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001951 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001952 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 static int
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001954executable_exists(char *name, char_u **path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001956 char *dum;
1957 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001958 char *curpath, *newpath;
1959 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001960
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001961#ifdef FEAT_MBYTE
1962 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001963 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001964 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001965 WCHAR fnamew[_MAX_PATH];
1966 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001967 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001968
1969 if (p != NULL)
1970 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001971 wcurpath = _wgetenv(L"PATH");
1972 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1973 * sizeof(WCHAR));
1974 if (wnewpath == NULL)
1975 return FALSE;
1976 wcscpy(wnewpath, L".;");
1977 wcscat(wnewpath, wcurpath);
1978 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1979 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001980 vim_free(p);
1981 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1982 {
1983 if (n == 0)
1984 return FALSE;
1985 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1986 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02001987 if (path != NULL)
1988 *path = utf16_to_enc(fnamew, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001989 return TRUE;
1990 }
1991 /* Retry with non-wide function (for Windows 98). */
1992 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001994#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001995
1996 curpath = getenv("PATH");
1997 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1998 if (newpath == NULL)
1999 return FALSE;
2000 STRCPY(newpath, ".;");
2001 STRCAT(newpath, curpath);
2002 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
2003 vim_free(newpath);
2004 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002005 return FALSE;
2006 if (mch_isdir(fname))
2007 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002008 if (path != NULL)
2009 *path = vim_strsave(fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002010 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002011}
2012
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002013#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002014 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002015/*
2016 * Bad parameter handler.
2017 *
2018 * Certain MS CRT functions will intentionally crash when passed invalid
2019 * parameters to highlight possible security holes. Setting this function as
2020 * the bad parameter handler will prevent the crash.
2021 *
2022 * In debug builds the parameters contain CRT information that might help track
2023 * down the source of a problem, but in non-debug builds the arguments are all
2024 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2025 * worth allowing these to make debugging of issues easier.
2026 */
2027 static void
2028bad_param_handler(const wchar_t *expression,
2029 const wchar_t *function,
2030 const wchar_t *file,
2031 unsigned int line,
2032 uintptr_t pReserved)
2033{
2034}
2035
2036# define SET_INVALID_PARAM_HANDLER \
2037 ((void)_set_invalid_parameter_handler(bad_param_handler))
2038#else
2039# define SET_INVALID_PARAM_HANDLER
2040#endif
2041
Bram Moolenaar071d4272004-06-13 20:20:40 +00002042#ifdef FEAT_GUI_W32
2043
2044/*
2045 * GUI version of mch_init().
2046 */
2047 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002048mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049{
2050#ifndef __MINGW32__
2051 extern int _fmode;
2052#endif
2053
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002054 /* Silently handle invalid parameters to CRT functions */
2055 SET_INVALID_PARAM_HANDLER;
2056
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 /* Let critical errors result in a failure, not in a dialog box. Required
2058 * for the timestamp test to work on removed floppies. */
2059 SetErrorMode(SEM_FAILCRITICALERRORS);
2060
2061 _fmode = O_BINARY; /* we do our own CR-LF translation */
2062
2063 /* Specify window size. Is there a place to get the default from? */
2064 Rows = 25;
2065 Columns = 80;
2066
2067 /* Look for 'vimrun' */
2068 if (!gui_is_win32s())
2069 {
2070 char_u vimrun_location[_MAX_PATH + 4];
2071
2072 /* First try in same directory as gvim.exe */
2073 STRCPY(vimrun_location, exe_name);
2074 STRCPY(gettail(vimrun_location), "vimrun.exe");
2075 if (mch_getperm(vimrun_location) >= 0)
2076 {
2077 if (*skiptowhite(vimrun_location) != NUL)
2078 {
2079 /* Enclose path with white space in double quotes. */
2080 mch_memmove(vimrun_location + 1, vimrun_location,
2081 STRLEN(vimrun_location) + 1);
2082 *vimrun_location = '"';
2083 STRCPY(gettail(vimrun_location), "vimrun\" ");
2084 }
2085 else
2086 STRCPY(gettail(vimrun_location), "vimrun ");
2087
2088 vimrun_path = (char *)vim_strsave(vimrun_location);
2089 s_dont_use_vimrun = FALSE;
2090 }
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002091 else if (executable_exists("vimrun.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 s_dont_use_vimrun = FALSE;
2093
2094 /* Don't give the warning for a missing vimrun.exe right now, but only
2095 * when vimrun was supposed to be used. Don't bother people that do
2096 * not need vimrun.exe. */
2097 if (s_dont_use_vimrun)
2098 need_vimrun_warning = TRUE;
2099 }
2100
2101 /*
2102 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2103 * Otherwise the default "findstr /n" is used.
2104 */
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002105 if (!executable_exists("findstr.exe", NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002106 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2107
2108#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002109 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002110#endif
2111}
2112
2113
2114#else /* FEAT_GUI_W32 */
2115
2116#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2117#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2118
2119/*
2120 * ClearConsoleBuffer()
2121 * Description:
2122 * Clears the entire contents of the console screen buffer, using the
2123 * specified attribute.
2124 * Returns:
2125 * TRUE on success
2126 */
2127 static BOOL
2128ClearConsoleBuffer(WORD wAttribute)
2129{
2130 CONSOLE_SCREEN_BUFFER_INFO csbi;
2131 COORD coord;
2132 DWORD NumCells, dummy;
2133
2134 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2135 return FALSE;
2136
2137 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2138 coord.X = 0;
2139 coord.Y = 0;
2140 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2141 coord, &dummy))
2142 {
2143 return FALSE;
2144 }
2145 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2146 coord, &dummy))
2147 {
2148 return FALSE;
2149 }
2150
2151 return TRUE;
2152}
2153
2154/*
2155 * FitConsoleWindow()
2156 * Description:
2157 * Checks if the console window will fit within given buffer dimensions.
2158 * Also, if requested, will shrink the window to fit.
2159 * Returns:
2160 * TRUE on success
2161 */
2162 static BOOL
2163FitConsoleWindow(
2164 COORD dwBufferSize,
2165 BOOL WantAdjust)
2166{
2167 CONSOLE_SCREEN_BUFFER_INFO csbi;
2168 COORD dwWindowSize;
2169 BOOL NeedAdjust = FALSE;
2170
2171 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2172 {
2173 /*
2174 * A buffer resize will fail if the current console window does
2175 * not lie completely within that buffer. To avoid this, we might
2176 * have to move and possibly shrink the window.
2177 */
2178 if (csbi.srWindow.Right >= dwBufferSize.X)
2179 {
2180 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2181 if (dwWindowSize.X > dwBufferSize.X)
2182 dwWindowSize.X = dwBufferSize.X;
2183 csbi.srWindow.Right = dwBufferSize.X - 1;
2184 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2185 NeedAdjust = TRUE;
2186 }
2187 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2188 {
2189 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2190 if (dwWindowSize.Y > dwBufferSize.Y)
2191 dwWindowSize.Y = dwBufferSize.Y;
2192 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2193 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2194 NeedAdjust = TRUE;
2195 }
2196 if (NeedAdjust && WantAdjust)
2197 {
2198 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2199 return FALSE;
2200 }
2201 return TRUE;
2202 }
2203
2204 return FALSE;
2205}
2206
2207typedef struct ConsoleBufferStruct
2208{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002209 BOOL IsValid;
2210 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002211 PCHAR_INFO Buffer;
2212 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002213} ConsoleBuffer;
2214
2215/*
2216 * SaveConsoleBuffer()
2217 * Description:
2218 * Saves important information about the console buffer, including the
2219 * actual buffer contents. The saved information is suitable for later
2220 * restoration by RestoreConsoleBuffer().
2221 * Returns:
2222 * TRUE if all information was saved; FALSE otherwise
2223 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2224 */
2225 static BOOL
2226SaveConsoleBuffer(
2227 ConsoleBuffer *cb)
2228{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002229 DWORD NumCells;
2230 COORD BufferCoord;
2231 SMALL_RECT ReadRegion;
2232 WORD Y, Y_incr;
2233
Bram Moolenaar071d4272004-06-13 20:20:40 +00002234 if (cb == NULL)
2235 return FALSE;
2236
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002237 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002238 {
2239 cb->IsValid = FALSE;
2240 return FALSE;
2241 }
2242 cb->IsValid = TRUE;
2243
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002244 /*
2245 * Allocate a buffer large enough to hold the entire console screen
2246 * buffer. If this ConsoleBuffer structure has already been initialized
2247 * with a buffer of the correct size, then just use that one.
2248 */
2249 if (!cb->IsValid || cb->Buffer == NULL ||
2250 cb->BufferSize.X != cb->Info.dwSize.X ||
2251 cb->BufferSize.Y != cb->Info.dwSize.Y)
2252 {
2253 cb->BufferSize.X = cb->Info.dwSize.X;
2254 cb->BufferSize.Y = cb->Info.dwSize.Y;
2255 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2256 vim_free(cb->Buffer);
2257 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2258 if (cb->Buffer == NULL)
2259 return FALSE;
2260 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002261
2262 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002263 * We will now copy the console screen buffer into our buffer.
2264 * ReadConsoleOutput() seems to be limited as far as how much you
2265 * can read at a time. Empirically, this number seems to be about
2266 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2267 * in chunks until it is all copied. The chunks will all have the
2268 * same horizontal characteristics, so initialize them now. The
2269 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002271 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002272 ReadRegion.Left = 0;
2273 ReadRegion.Right = cb->Info.dwSize.X - 1;
2274 Y_incr = 12000 / cb->Info.dwSize.X;
2275 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002277 /*
2278 * Read into position (0, Y) in our buffer.
2279 */
2280 BufferCoord.Y = Y;
2281 /*
2282 * Read the region whose top left corner is (0, Y) and whose bottom
2283 * right corner is (width - 1, Y + Y_incr - 1). This should define
2284 * a region of size width by Y_incr. Don't worry if this region is
2285 * too large for the remaining buffer; it will be cropped.
2286 */
2287 ReadRegion.Top = Y;
2288 ReadRegion.Bottom = Y + Y_incr - 1;
2289 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2290 cb->Buffer, /* our buffer */
2291 cb->BufferSize, /* dimensions of our buffer */
2292 BufferCoord, /* offset in our buffer */
2293 &ReadRegion)) /* region to save */
2294 {
2295 vim_free(cb->Buffer);
2296 cb->Buffer = NULL;
2297 return FALSE;
2298 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 }
2300
2301 return TRUE;
2302}
2303
2304/*
2305 * RestoreConsoleBuffer()
2306 * Description:
2307 * Restores important information about the console buffer, including the
2308 * actual buffer contents, if desired. The information to restore is in
2309 * the same format used by SaveConsoleBuffer().
2310 * Returns:
2311 * TRUE on success
2312 */
2313 static BOOL
2314RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002315 ConsoleBuffer *cb,
2316 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002318 COORD BufferCoord;
2319 SMALL_RECT WriteRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320
2321 if (cb == NULL || !cb->IsValid)
2322 return FALSE;
2323
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002324 /*
2325 * Before restoring the buffer contents, clear the current buffer, and
2326 * restore the cursor position and window information. Doing this now
2327 * prevents old buffer contents from "flashing" onto the screen.
2328 */
2329 if (RestoreScreen)
2330 ClearConsoleBuffer(cb->Info.wAttributes);
2331
2332 FitConsoleWindow(cb->Info.dwSize, TRUE);
2333 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2334 return FALSE;
2335 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2336 return FALSE;
2337
2338 if (!RestoreScreen)
2339 {
2340 /*
2341 * No need to restore the screen buffer contents, so we're done.
2342 */
2343 return TRUE;
2344 }
2345
2346 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2347 return FALSE;
2348 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2349 return FALSE;
2350
2351 /*
2352 * Restore the screen buffer contents.
2353 */
2354 if (cb->Buffer != NULL)
2355 {
2356 BufferCoord.X = 0;
2357 BufferCoord.Y = 0;
2358 WriteRegion.Left = 0;
2359 WriteRegion.Top = 0;
2360 WriteRegion.Right = cb->Info.dwSize.X - 1;
2361 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2362 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2363 cb->Buffer, /* our buffer */
2364 cb->BufferSize, /* dimensions of our buffer */
2365 BufferCoord, /* offset in our buffer */
2366 &WriteRegion)) /* region to restore */
2367 {
2368 return FALSE;
2369 }
2370 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371
2372 return TRUE;
2373}
2374
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002375#define FEAT_RESTORE_ORIG_SCREEN
2376#ifdef FEAT_RESTORE_ORIG_SCREEN
2377static ConsoleBuffer g_cbOrig = { 0 };
2378#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379static ConsoleBuffer g_cbNonTermcap = { 0 };
2380static ConsoleBuffer g_cbTermcap = { 0 };
2381
2382#ifdef FEAT_TITLE
2383#ifdef __BORLANDC__
2384typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2385#else
2386typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2387#endif
2388char g_szOrigTitle[256] = { 0 };
2389HWND g_hWnd = NULL; /* also used in os_mswin.c */
2390static HICON g_hOrigIconSmall = NULL;
2391static HICON g_hOrigIcon = NULL;
2392static HICON g_hVimIcon = NULL;
2393static BOOL g_fCanChangeIcon = FALSE;
2394
2395/* ICON* are not defined in VC++ 4.0 */
2396#ifndef ICON_SMALL
2397#define ICON_SMALL 0
2398#endif
2399#ifndef ICON_BIG
2400#define ICON_BIG 1
2401#endif
2402/*
2403 * GetConsoleIcon()
2404 * Description:
2405 * Attempts to retrieve the small icon and/or the big icon currently in
2406 * use by a given window.
2407 * Returns:
2408 * TRUE on success
2409 */
2410 static BOOL
2411GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002412 HWND hWnd,
2413 HICON *phIconSmall,
2414 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415{
2416 if (hWnd == NULL)
2417 return FALSE;
2418
2419 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002420 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2421 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002423 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2424 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425 return TRUE;
2426}
2427
2428/*
2429 * SetConsoleIcon()
2430 * Description:
2431 * Attempts to change the small icon and/or the big icon currently in
2432 * use by a given window.
2433 * Returns:
2434 * TRUE on success
2435 */
2436 static BOOL
2437SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002438 HWND hWnd,
2439 HICON hIconSmall,
2440 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002441{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002442 HICON hPrevIconSmall;
2443 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002444
2445 if (hWnd == NULL)
2446 return FALSE;
2447
2448 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002449 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2450 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002451 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002452 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2453 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454 return TRUE;
2455}
2456
2457/*
2458 * SaveConsoleTitleAndIcon()
2459 * Description:
2460 * Saves the current console window title in g_szOrigTitle, for later
2461 * restoration. Also, attempts to obtain a handle to the console window,
2462 * and use it to save the small and big icons currently in use by the
2463 * console window. This is not always possible on some versions of Windows;
2464 * nor is it possible when running Vim remotely using Telnet (since the
2465 * console window the user sees is owned by a remote process).
2466 */
2467 static void
2468SaveConsoleTitleAndIcon(void)
2469{
2470 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2471
2472 /* Save the original title. */
2473 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2474 return;
2475
2476 /*
2477 * Obtain a handle to the console window using GetConsoleWindow() from
2478 * KERNEL32.DLL; we need to handle in order to change the window icon.
2479 * This function only exists on NT-based Windows, starting with Windows
2480 * 2000. On older operating systems, we can't change the window icon
2481 * anyway.
2482 */
2483 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2484 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2485 "GetConsoleWindow")) != NULL)
2486 {
2487 g_hWnd = (*GetConsoleWindowProc)();
2488 }
2489 if (g_hWnd == NULL)
2490 return;
2491
2492 /* Save the original console window icon. */
2493 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2494 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2495 return;
2496
2497 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002498 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
2499 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 if (g_hVimIcon != NULL)
2501 g_fCanChangeIcon = TRUE;
2502}
2503#endif
2504
2505static int g_fWindInitCalled = FALSE;
2506static int g_fTermcapMode = FALSE;
2507static CONSOLE_CURSOR_INFO g_cci;
2508static DWORD g_cmodein = 0;
2509static DWORD g_cmodeout = 0;
2510
2511/*
2512 * non-GUI version of mch_init().
2513 */
2514 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002515mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002517#ifndef FEAT_RESTORE_ORIG_SCREEN
2518 CONSOLE_SCREEN_BUFFER_INFO csbi;
2519#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520#ifndef __MINGW32__
2521 extern int _fmode;
2522#endif
2523
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002524 /* Silently handle invalid parameters to CRT functions */
2525 SET_INVALID_PARAM_HANDLER;
2526
Bram Moolenaar071d4272004-06-13 20:20:40 +00002527 /* Let critical errors result in a failure, not in a dialog box. Required
2528 * for the timestamp test to work on removed floppies. */
2529 SetErrorMode(SEM_FAILCRITICALERRORS);
2530
2531 _fmode = O_BINARY; /* we do our own CR-LF translation */
2532 out_flush();
2533
2534 /* Obtain handles for the standard Console I/O devices */
2535 if (read_cmd_fd == 0)
2536 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2537 else
2538 create_conin();
2539 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2540
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002541#ifdef FEAT_RESTORE_ORIG_SCREEN
2542 /* Save the initial console buffer for later restoration */
2543 SaveConsoleBuffer(&g_cbOrig);
2544 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2545#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002546 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002547 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2548 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2549#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 if (cterm_normal_fg_color == 0)
2551 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2552 if (cterm_normal_bg_color == 0)
2553 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2554
2555 /* set termcap codes to current text attributes */
2556 update_tcap(g_attrCurrent);
2557
2558 GetConsoleCursorInfo(g_hConOut, &g_cci);
2559 GetConsoleMode(g_hConIn, &g_cmodein);
2560 GetConsoleMode(g_hConOut, &g_cmodeout);
2561
2562#ifdef FEAT_TITLE
2563 SaveConsoleTitleAndIcon();
2564 /*
2565 * Set both the small and big icons of the console window to Vim's icon.
2566 * Note that Vim presently only has one size of icon (32x32), but it
2567 * automatically gets scaled down to 16x16 when setting the small icon.
2568 */
2569 if (g_fCanChangeIcon)
2570 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2571#endif
2572
2573 ui_get_shellsize();
2574
2575#ifdef MCH_WRITE_DUMP
2576 fdDump = fopen("dump", "wt");
2577
2578 if (fdDump)
2579 {
2580 time_t t;
2581
2582 time(&t);
2583 fputs(ctime(&t), fdDump);
2584 fflush(fdDump);
2585 }
2586#endif
2587
2588 g_fWindInitCalled = TRUE;
2589
2590#ifdef FEAT_MOUSE
2591 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2592#endif
2593
2594#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002595 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002596#endif
2597
2598 /* This will be NULL on anything but NT 4.0 */
2599 s_pfnGetConsoleKeyboardLayoutName =
2600 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2601 "GetConsoleKeyboardLayoutNameA");
2602}
2603
2604/*
2605 * non-GUI version of mch_exit().
2606 * Shut down and exit with status `r'
2607 * Careful: mch_exit() may be called before mch_init()!
2608 */
2609 void
2610mch_exit(int r)
2611{
2612 stoptermcap();
2613
2614 if (g_fWindInitCalled)
2615 settmode(TMODE_COOK);
2616
2617 ml_close_all(TRUE); /* remove all memfiles */
2618
2619 if (g_fWindInitCalled)
2620 {
2621#ifdef FEAT_TITLE
2622 mch_restore_title(3);
2623 /*
2624 * Restore both the small and big icons of the console window to
2625 * what they were at startup. Don't do this when the window is
2626 * closed, Vim would hang here.
2627 */
2628 if (g_fCanChangeIcon && !g_fForceExit)
2629 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2630#endif
2631
2632#ifdef MCH_WRITE_DUMP
2633 if (fdDump)
2634 {
2635 time_t t;
2636
2637 time(&t);
2638 fputs(ctime(&t), fdDump);
2639 fclose(fdDump);
2640 }
2641 fdDump = NULL;
2642#endif
2643 }
2644
2645 SetConsoleCursorInfo(g_hConOut, &g_cci);
2646 SetConsoleMode(g_hConIn, g_cmodein);
2647 SetConsoleMode(g_hConOut, g_cmodeout);
2648
2649#ifdef DYNAMIC_GETTEXT
2650 dyn_libintl_end();
2651#endif
2652
2653 exit(r);
2654}
2655#endif /* !FEAT_GUI_W32 */
2656
Bram Moolenaar071d4272004-06-13 20:20:40 +00002657/*
2658 * Do we have an interactive window?
2659 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002660/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002661 int
2662mch_check_win(
2663 int argc,
2664 char **argv)
2665{
2666 get_exe_name();
2667
2668#ifdef FEAT_GUI_W32
2669 return OK; /* GUI always has a tty */
2670#else
2671 if (isatty(1))
2672 return OK;
2673 return FAIL;
2674#endif
2675}
2676
2677
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002678#ifdef FEAT_MBYTE
2679/*
2680 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2681 * if it already exists. When "len" is > 0, also expand short to long
2682 * filenames.
2683 * Return FAIL if wide functions are not available, OK otherwise.
2684 * NOTE: much of this is identical to fname_case(), keep in sync!
2685 */
2686 static int
2687fname_casew(
2688 WCHAR *name,
2689 int len)
2690{
2691 WCHAR szTrueName[_MAX_PATH + 2];
2692 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2693 WCHAR *ptrue, *ptruePrev;
2694 WCHAR *porig, *porigPrev;
2695 int flen;
2696 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002697 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002698 int c;
2699 int slen;
2700
2701 flen = (int)wcslen(name);
2702 if (flen > _MAX_PATH)
2703 return OK;
2704
2705 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2706
2707 /* Build the new name in szTrueName[] one component at a time. */
2708 porig = name;
2709 ptrue = szTrueName;
2710
2711 if (iswalpha(porig[0]) && porig[1] == L':')
2712 {
2713 /* copy leading drive letter */
2714 *ptrue++ = *porig++;
2715 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002716 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002717 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002718
2719 while (*porig != NUL)
2720 {
2721 /* copy \ characters */
2722 while (*porig == psepc)
2723 *ptrue++ = *porig++;
2724
2725 ptruePrev = ptrue;
2726 porigPrev = porig;
2727 while (*porig != NUL && *porig != psepc)
2728 {
2729 *ptrue++ = *porig++;
2730 }
2731 *ptrue = NUL;
2732
2733 /* To avoid a slow failure append "\*" when searching a directory,
2734 * server or network share. */
2735 wcscpy(szTrueNameTemp, szTrueName);
2736 slen = (int)wcslen(szTrueNameTemp);
2737 if (*porig == psepc && slen + 2 < _MAX_PATH)
2738 wcscpy(szTrueNameTemp + slen, L"\\*");
2739
2740 /* Skip "", "." and "..". */
2741 if (ptrue > ptruePrev
2742 && (ptruePrev[0] != L'.'
2743 || (ptruePrev[1] != NUL
2744 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2745 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2746 != INVALID_HANDLE_VALUE)
2747 {
2748 c = *porig;
2749 *porig = NUL;
2750
2751 /* Only use the match when it's the same name (ignoring case) or
2752 * expansion is allowed and there is a match with the short name
2753 * and there is enough room. */
2754 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2755 || (len > 0
2756 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2757 && (int)(ptruePrev - szTrueName)
2758 + (int)wcslen(fb.cFileName) < len)))
2759 {
2760 wcscpy(ptruePrev, fb.cFileName);
2761
2762 /* Look for exact match and prefer it if found. Must be a
2763 * long name, otherwise there would be only one match. */
2764 while (FindNextFileW(hFind, &fb))
2765 {
2766 if (*fb.cAlternateFileName != NUL
2767 && (wcscoll(porigPrev, fb.cFileName) == 0
2768 || (len > 0
2769 && (_wcsicoll(porigPrev,
2770 fb.cAlternateFileName) == 0
2771 && (int)(ptruePrev - szTrueName)
2772 + (int)wcslen(fb.cFileName) < len))))
2773 {
2774 wcscpy(ptruePrev, fb.cFileName);
2775 break;
2776 }
2777 }
2778 }
2779 FindClose(hFind);
2780 *porig = c;
2781 ptrue = ptruePrev + wcslen(ptruePrev);
2782 }
2783 else if (hFind == INVALID_HANDLE_VALUE
2784 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2785 return FAIL;
2786 }
2787
2788 wcscpy(name, szTrueName);
2789 return OK;
2790}
2791#endif
2792
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793/*
2794 * fname_case(): Set the case of the file name, if it already exists.
2795 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002796 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797 */
2798 void
2799fname_case(
2800 char_u *name,
2801 int len)
2802{
2803 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002804 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002805 char *ptrue, *ptruePrev;
2806 char *porig, *porigPrev;
2807 int flen;
2808 WIN32_FIND_DATA fb;
2809 HANDLE hFind;
2810 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002811 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002812
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002813 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002814 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002815 return;
2816
2817 slash_adjust(name);
2818
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002819#ifdef FEAT_MBYTE
2820 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2821 {
2822 WCHAR *p = enc_to_utf16(name, NULL);
2823
2824 if (p != NULL)
2825 {
2826 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002827 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002828
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002829 wcsncpy(buf, p, _MAX_PATH);
2830 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002831 vim_free(p);
2832
2833 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2834 {
2835 q = utf16_to_enc(buf, NULL);
2836 if (q != NULL)
2837 {
2838 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2839 vim_free(q);
2840 return;
2841 }
2842 }
2843 }
2844 /* Retry with non-wide function (for Windows 98). */
2845 }
2846#endif
2847
2848 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2849 * So we should check this after calling wide function. */
2850 if (flen > _MAX_PATH)
2851 return;
2852
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853 /* Build the new name in szTrueName[] one component at a time. */
2854 porig = name;
2855 ptrue = szTrueName;
2856
2857 if (isalpha(porig[0]) && porig[1] == ':')
2858 {
2859 /* copy leading drive letter */
2860 *ptrue++ = *porig++;
2861 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002862 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002863 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864
2865 while (*porig != NUL)
2866 {
2867 /* copy \ characters */
2868 while (*porig == psepc)
2869 *ptrue++ = *porig++;
2870
2871 ptruePrev = ptrue;
2872 porigPrev = porig;
2873 while (*porig != NUL && *porig != psepc)
2874 {
2875#ifdef FEAT_MBYTE
2876 int l;
2877
2878 if (enc_dbcs)
2879 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002880 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 while (--l >= 0)
2882 *ptrue++ = *porig++;
2883 }
2884 else
2885#endif
2886 *ptrue++ = *porig++;
2887 }
2888 *ptrue = NUL;
2889
Bram Moolenaar464c9252010-10-13 20:37:41 +02002890 /* To avoid a slow failure append "\*" when searching a directory,
2891 * server or network share. */
2892 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002893 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002894 if (*porig == psepc && slen + 2 < _MAX_PATH)
2895 STRCPY(szTrueNameTemp + slen, "\\*");
2896
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 /* Skip "", "." and "..". */
2898 if (ptrue > ptruePrev
2899 && (ptruePrev[0] != '.'
2900 || (ptruePrev[1] != NUL
2901 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002902 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903 != INVALID_HANDLE_VALUE)
2904 {
2905 c = *porig;
2906 *porig = NUL;
2907
2908 /* Only use the match when it's the same name (ignoring case) or
2909 * expansion is allowed and there is a match with the short name
2910 * and there is enough room. */
2911 if (_stricoll(porigPrev, fb.cFileName) == 0
2912 || (len > 0
2913 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2914 && (int)(ptruePrev - szTrueName)
2915 + (int)strlen(fb.cFileName) < len)))
2916 {
2917 STRCPY(ptruePrev, fb.cFileName);
2918
2919 /* Look for exact match and prefer it if found. Must be a
2920 * long name, otherwise there would be only one match. */
2921 while (FindNextFile(hFind, &fb))
2922 {
2923 if (*fb.cAlternateFileName != NUL
2924 && (strcoll(porigPrev, fb.cFileName) == 0
2925 || (len > 0
2926 && (_stricoll(porigPrev,
2927 fb.cAlternateFileName) == 0
2928 && (int)(ptruePrev - szTrueName)
2929 + (int)strlen(fb.cFileName) < len))))
2930 {
2931 STRCPY(ptruePrev, fb.cFileName);
2932 break;
2933 }
2934 }
2935 }
2936 FindClose(hFind);
2937 *porig = c;
2938 ptrue = ptruePrev + strlen(ptruePrev);
2939 }
2940 }
2941
2942 STRCPY(name, szTrueName);
2943}
2944
2945
2946/*
2947 * Insert user name in s[len].
2948 */
2949 int
2950mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002951 char_u *s,
2952 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002953{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002954 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955 DWORD cch = sizeof szUserName;
2956
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002957#ifdef FEAT_MBYTE
2958 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2959 {
2960 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2961 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2962
2963 if (GetUserNameW(wszUserName, &wcch))
2964 {
2965 char_u *p = utf16_to_enc(wszUserName, NULL);
2966
2967 if (p != NULL)
2968 {
2969 vim_strncpy(s, p, len - 1);
2970 vim_free(p);
2971 return OK;
2972 }
2973 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01002974 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2975 return FAIL;
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002976 /* Retry with non-wide function (for Windows 98). */
2977 }
2978#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002979 if (GetUserName(szUserName, &cch))
2980 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002981 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002982 return OK;
2983 }
2984 s[0] = NUL;
2985 return FAIL;
2986}
2987
2988
2989/*
2990 * Insert host name in s[len].
2991 */
2992 void
2993mch_get_host_name(
2994 char_u *s,
2995 int len)
2996{
2997 DWORD cch = len;
2998
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002999#ifdef FEAT_MBYTE
3000 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3001 {
3002 WCHAR wszHostName[256 + 1];
3003 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
3004
3005 if (GetComputerNameW(wszHostName, &wcch))
3006 {
3007 char_u *p = utf16_to_enc(wszHostName, NULL);
3008
3009 if (p != NULL)
3010 {
3011 vim_strncpy(s, p, len - 1);
3012 vim_free(p);
3013 return;
3014 }
3015 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003016 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3017 return;
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003018 /* Retry with non-wide function (for Windows 98). */
3019 }
3020#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003021 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003022 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003023}
3024
3025
3026/*
3027 * return process ID
3028 */
3029 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003030mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031{
3032 return (long)GetCurrentProcessId();
3033}
3034
3035
3036/*
3037 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3038 * Return OK for success, FAIL for failure.
3039 */
3040 int
3041mch_dirname(
3042 char_u *buf,
3043 int len)
3044{
3045 /*
3046 * Originally this was:
3047 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3048 * But the Win32s known bug list says that getcwd() doesn't work
3049 * so use the Win32 system call instead. <Negri>
3050 */
3051#ifdef FEAT_MBYTE
3052 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3053 {
3054 WCHAR wbuf[_MAX_PATH + 1];
3055
3056 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3057 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003058 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059
3060 if (p != NULL)
3061 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003062 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063 vim_free(p);
3064 return OK;
3065 }
3066 }
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003067 else if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
3068 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003069 /* Retry with non-wide function (for Windows 98). */
3070 }
3071#endif
3072 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
3073}
3074
3075/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003076 * Get file permissions for "name".
3077 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003078 */
3079 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003080mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003082 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003083 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003085 n = mch_stat(name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003086 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087}
3088
3089
3090/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003091 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003092 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003093 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094 */
3095 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003096mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003098 long n = -1;
3099
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100#ifdef FEAT_MBYTE
3101 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3102 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003103 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003104
3105 if (p != NULL)
3106 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003107 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003108 vim_free(p);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01003109 if (n == -1 && g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003110 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003111 /* Retry with non-wide function (for Windows 98). */
3112 }
3113 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003114 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003116 n = _chmod(name, perm);
3117 if (n == -1)
3118 return FAIL;
3119
3120 win32_set_archive(name);
3121
3122 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123}
3124
3125/*
3126 * Set hidden flag for "name".
3127 */
3128 void
3129mch_hide(char_u *name)
3130{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003131 int attrs = win32_getattrs(name);
3132 if (attrs == -1)
3133 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003135 attrs |= FILE_ATTRIBUTE_HIDDEN;
3136 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003137}
3138
3139/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003140 * Return TRUE if file "name" exists and is hidden.
3141 */
3142 int
3143mch_ishidden(char_u *name)
3144{
3145 int f = win32_getattrs(name);
3146
3147 if (f == -1)
3148 return FALSE; /* file does not exist at all */
3149
3150 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3151}
3152
3153/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154 * return TRUE if "name" is a directory
3155 * return FALSE if "name" is not a directory or upon error
3156 */
3157 int
3158mch_isdir(char_u *name)
3159{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003160 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161
3162 if (f == -1)
3163 return FALSE; /* file does not exist at all */
3164
3165 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3166}
3167
3168/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003169 * return TRUE if "name" is a directory, NOT a symlink to a directory
3170 * return FALSE if "name" is not a directory
3171 * return FALSE for error
3172 */
3173 int
3174mch_isrealdir(char_u *name)
3175{
3176 return mch_isdir(name) && !mch_is_symbolic_link(name);
3177}
3178
3179/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003180 * Create directory "name".
3181 * Return 0 on success, -1 on error.
3182 */
3183 int
3184mch_mkdir(char_u *name)
3185{
3186#ifdef FEAT_MBYTE
3187 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3188 {
3189 WCHAR *p;
3190 int retval;
3191
3192 p = enc_to_utf16(name, NULL);
3193 if (p == NULL)
3194 return -1;
3195 retval = _wmkdir(p);
3196 vim_free(p);
3197 return retval;
3198 }
3199#endif
3200 return _mkdir(name);
3201}
3202
3203/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003204 * Delete directory "name".
3205 * Return 0 on success, -1 on error.
3206 */
3207 int
3208mch_rmdir(char_u *name)
3209{
3210#ifdef FEAT_MBYTE
3211 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3212 {
3213 WCHAR *p;
3214 int retval;
3215
3216 p = enc_to_utf16(name, NULL);
3217 if (p == NULL)
3218 return -1;
3219 retval = _wrmdir(p);
3220 vim_free(p);
3221 return retval;
3222 }
3223#endif
3224 return _rmdir(name);
3225}
3226
3227/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003228 * Return TRUE if file "fname" has more than one link.
3229 */
3230 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003231mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003232{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003233 BY_HANDLE_FILE_INFORMATION info;
3234
3235 return win32_fileinfo(fname, &info) == FILEINFO_OK
3236 && info.nNumberOfLinks > 1;
3237}
3238
3239/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003240 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241 */
3242 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003243mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003244{
3245 HANDLE hFind;
3246 int res = FALSE;
3247 WIN32_FIND_DATAA findDataA;
3248 DWORD fileFlags = 0, reparseTag = 0;
3249#ifdef FEAT_MBYTE
3250 WCHAR *wn = NULL;
3251 WIN32_FIND_DATAW findDataW;
3252
3253 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003254 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003255 if (wn != NULL)
3256 {
3257 hFind = FindFirstFileW(wn, &findDataW);
3258 vim_free(wn);
3259 if (hFind == INVALID_HANDLE_VALUE
3260 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3261 {
3262 /* Retry with non-wide function (for Windows 98). */
Bram Moolenaar203258c2016-01-17 22:15:16 +01003263 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003264 if (hFind != INVALID_HANDLE_VALUE)
3265 {
3266 fileFlags = findDataA.dwFileAttributes;
3267 reparseTag = findDataA.dwReserved0;
3268 }
3269 }
3270 else
3271 {
3272 fileFlags = findDataW.dwFileAttributes;
3273 reparseTag = findDataW.dwReserved0;
3274 }
3275 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003276 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003277#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003278 {
Bram Moolenaar203258c2016-01-17 22:15:16 +01003279 hFind = FindFirstFile(name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003280 if (hFind != INVALID_HANDLE_VALUE)
3281 {
3282 fileFlags = findDataA.dwFileAttributes;
3283 reparseTag = findDataA.dwReserved0;
3284 }
3285 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003286
3287 if (hFind != INVALID_HANDLE_VALUE)
3288 FindClose(hFind);
3289
3290 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003291 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3292 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003293 res = TRUE;
3294
3295 return res;
3296}
3297
3298/*
3299 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3300 * link.
3301 */
3302 int
3303mch_is_linked(char_u *fname)
3304{
3305 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3306 return TRUE;
3307 return FALSE;
3308}
3309
3310/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003311 * Get the by-handle-file-information for "fname".
3312 * Returns FILEINFO_OK when OK.
3313 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3314 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3315 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3316 */
3317 int
3318win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3319{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003320 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003321 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003322#ifdef FEAT_MBYTE
3323 WCHAR *wn = NULL;
3324
3325 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003326 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003327 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003328 if (wn == NULL)
3329 res = FILEINFO_ENC_FAIL;
3330 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003331 if (wn != NULL)
3332 {
3333 hFile = CreateFileW(wn, /* file name */
3334 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003335 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003336 NULL, /* security descriptor */
3337 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003338 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003339 NULL); /* handle to template file */
3340 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003341 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003342 {
3343 /* Retry with non-wide function (for Windows 98). */
3344 vim_free(wn);
3345 wn = NULL;
3346 }
3347 }
3348 if (wn == NULL)
3349#endif
3350 hFile = CreateFile(fname, /* file name */
3351 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003352 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003353 NULL, /* security descriptor */
3354 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003355 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003356 NULL); /* handle to template file */
3357
3358 if (hFile != INVALID_HANDLE_VALUE)
3359 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003360 if (GetFileInformationByHandle(hFile, info) != 0)
3361 res = FILEINFO_OK;
3362 else
3363 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003364 CloseHandle(hFile);
3365 }
3366
3367#ifdef FEAT_MBYTE
3368 vim_free(wn);
3369#endif
3370 return res;
3371}
3372
3373/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003374 * get file attributes for `name'
3375 * -1 : error
3376 * else FILE_ATTRIBUTE_* defined in winnt.h
3377 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003378 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003379win32_getattrs(char_u *name)
3380{
3381 int attr;
3382#ifdef FEAT_MBYTE
3383 WCHAR *p = NULL;
3384
3385 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3386 p = enc_to_utf16(name, NULL);
3387
3388 if (p != NULL)
3389 {
3390 attr = GetFileAttributesW(p);
3391 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3392 {
3393 /* Retry with non-wide function (for Windows 98). */
3394 vim_free(p);
3395 p = NULL;
3396 }
3397 }
3398 if (p == NULL)
3399#endif
3400 attr = GetFileAttributes((char *)name);
3401#ifdef FEAT_MBYTE
3402 vim_free(p);
3403#endif
3404 return attr;
3405}
3406
3407/*
3408 * set file attributes for `name' to `attrs'
3409 *
3410 * return -1 for failure, 0 otherwise
3411 */
3412 static
3413 int
3414win32_setattrs(char_u *name, int attrs)
3415{
3416 int res;
3417#ifdef FEAT_MBYTE
3418 WCHAR *p = NULL;
3419
3420 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3421 p = enc_to_utf16(name, NULL);
3422
3423 if (p != NULL)
3424 {
3425 res = SetFileAttributesW(p, attrs);
3426 if (res == FALSE
3427 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3428 {
3429 /* Retry with non-wide function (for Windows 98). */
3430 vim_free(p);
3431 p = NULL;
3432 }
3433 }
3434 if (p == NULL)
3435#endif
3436 res = SetFileAttributes((char *)name, attrs);
3437#ifdef FEAT_MBYTE
3438 vim_free(p);
3439#endif
3440 return res ? 0 : -1;
3441}
3442
3443/*
3444 * Set archive flag for "name".
3445 */
3446 static
3447 int
3448win32_set_archive(char_u *name)
3449{
3450 int attrs = win32_getattrs(name);
3451 if (attrs == -1)
3452 return -1;
3453
3454 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3455 return win32_setattrs(name, attrs);
3456}
3457
3458/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003459 * Return TRUE if file or directory "name" is writable (not readonly).
3460 * Strange semantics of Win32: a readonly directory is writable, but you can't
3461 * delete a file. Let's say this means it is writable.
3462 */
3463 int
3464mch_writable(char_u *name)
3465{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003466 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003467
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003468 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3469 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470}
3471
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472/*
3473 * Return 1 if "name" can be executed, 0 if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003474 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475 * Return -1 if unknown.
3476 */
3477 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003478mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003479{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003480 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003481 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003482 char_u *p;
3483
3484 if (len >= _MAX_PATH) /* safety check */
3485 return FALSE;
Bram Moolenaar77b77102015-03-21 22:18:41 +01003486 if (!use_path)
3487 {
3488 /* TODO: check if file is really executable. */
3489 return mch_getperm(name) != -1 && !mch_isdir(name);
3490 }
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003491
3492 /* If there already is an extension try using the name directly. Also do
3493 * this with a Unix-shell like 'shell'. */
3494 if (vim_strchr(gettail(name), '.') != NULL
3495 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003496 if (executable_exists((char *)name, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003497 return TRUE;
3498
3499 /*
3500 * Loop over all extensions in $PATHEXT.
3501 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003502 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003503 p = mch_getenv("PATHEXT");
3504 if (p == NULL)
3505 p = (char_u *)".com;.exe;.bat;.cmd";
3506 while (*p)
3507 {
3508 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3509 {
3510 /* A single "." means no extension is added. */
3511 buf[len] = NUL;
3512 ++p;
3513 if (*p)
3514 ++p;
3515 }
3516 else
3517 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaarc7f02552014-04-01 21:00:59 +02003518 if (executable_exists((char *)buf, path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003519 return TRUE;
3520 }
3521 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003523
3524/*
3525 * Check what "name" is:
3526 * NODE_NORMAL: file or directory (or doesn't exist)
3527 * NODE_WRITABLE: writable device, socket, fifo, etc.
3528 * NODE_OTHER: non-writable things
3529 */
3530 int
3531mch_nodetype(char_u *name)
3532{
3533 HANDLE hFile;
3534 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003535#ifdef FEAT_MBYTE
3536 WCHAR *wn = NULL;
3537#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538
Bram Moolenaar043545e2006-10-10 16:44:07 +00003539 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3540 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3541 * here. */
3542 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3543 return NODE_WRITABLE;
3544
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003545#ifdef FEAT_MBYTE
3546 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3547 {
3548 wn = enc_to_utf16(name, NULL);
3549 if (wn != NULL)
3550 {
3551 hFile = CreateFileW(wn, /* file name */
3552 GENERIC_WRITE, /* access mode */
3553 0, /* share mode */
3554 NULL, /* security descriptor */
3555 OPEN_EXISTING, /* creation disposition */
3556 0, /* file attributes */
3557 NULL); /* handle to template file */
3558 if (hFile == INVALID_HANDLE_VALUE
3559 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3560 {
3561 /* Retry with non-wide function (for Windows 98). */
3562 vim_free(wn);
3563 wn = NULL;
3564 }
3565 }
3566 }
3567 if (wn == NULL)
3568#endif
3569 hFile = CreateFile(name, /* file name */
3570 GENERIC_WRITE, /* access mode */
3571 0, /* share mode */
3572 NULL, /* security descriptor */
3573 OPEN_EXISTING, /* creation disposition */
3574 0, /* file attributes */
3575 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003576
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003577#ifdef FEAT_MBYTE
3578 vim_free(wn);
3579#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003580 if (hFile == INVALID_HANDLE_VALUE)
3581 return NODE_NORMAL;
3582
3583 type = GetFileType(hFile);
3584 CloseHandle(hFile);
3585 if (type == FILE_TYPE_CHAR)
3586 return NODE_WRITABLE;
3587 if (type == FILE_TYPE_DISK)
3588 return NODE_NORMAL;
3589 return NODE_OTHER;
3590}
3591
3592#ifdef HAVE_ACL
3593struct my_acl
3594{
3595 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3596 PSID pSidOwner;
3597 PSID pSidGroup;
3598 PACL pDacl;
3599 PACL pSacl;
3600};
3601#endif
3602
3603/*
3604 * Return a pointer to the ACL of file "fname" in allocated memory.
3605 * Return NULL if the ACL is not available for whatever reason.
3606 */
3607 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003608mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003609{
3610#ifndef HAVE_ACL
3611 return (vim_acl_T)NULL;
3612#else
3613 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003614 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615
3616 /* This only works on Windows NT and 2000. */
3617 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3618 {
3619 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3620 if (p != NULL)
3621 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003622# ifdef FEAT_MBYTE
3623 WCHAR *wn = NULL;
3624
3625 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3626 wn = enc_to_utf16(fname, NULL);
3627 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003629 /* Try to retrieve the entire security descriptor. */
3630 err = pGetNamedSecurityInfoW(
3631 wn, // Abstract filename
3632 SE_FILE_OBJECT, // File Object
3633 OWNER_SECURITY_INFORMATION |
3634 GROUP_SECURITY_INFORMATION |
3635 DACL_SECURITY_INFORMATION |
3636 SACL_SECURITY_INFORMATION,
3637 &p->pSidOwner, // Ownership information.
3638 &p->pSidGroup, // Group membership.
3639 &p->pDacl, // Discretionary information.
3640 &p->pSacl, // For auditing purposes.
3641 &p->pSecurityDescriptor);
3642 if (err == ERROR_ACCESS_DENIED ||
3643 err == ERROR_PRIVILEGE_NOT_HELD)
3644 {
3645 /* Retrieve only DACL. */
3646 (void)pGetNamedSecurityInfoW(
3647 wn,
3648 SE_FILE_OBJECT,
3649 DACL_SECURITY_INFORMATION,
3650 NULL,
3651 NULL,
3652 &p->pDacl,
3653 NULL,
3654 &p->pSecurityDescriptor);
3655 }
3656 if (p->pSecurityDescriptor == NULL)
3657 {
3658 mch_free_acl((vim_acl_T)p);
3659 p = NULL;
3660 }
3661 vim_free(wn);
3662 }
3663 else
3664# endif
3665 {
3666 /* Try to retrieve the entire security descriptor. */
3667 err = pGetNamedSecurityInfo(
3668 (LPSTR)fname, // Abstract filename
3669 SE_FILE_OBJECT, // File Object
3670 OWNER_SECURITY_INFORMATION |
3671 GROUP_SECURITY_INFORMATION |
3672 DACL_SECURITY_INFORMATION |
3673 SACL_SECURITY_INFORMATION,
3674 &p->pSidOwner, // Ownership information.
3675 &p->pSidGroup, // Group membership.
3676 &p->pDacl, // Discretionary information.
3677 &p->pSacl, // For auditing purposes.
3678 &p->pSecurityDescriptor);
3679 if (err == ERROR_ACCESS_DENIED ||
3680 err == ERROR_PRIVILEGE_NOT_HELD)
3681 {
3682 /* Retrieve only DACL. */
3683 (void)pGetNamedSecurityInfo(
3684 (LPSTR)fname,
3685 SE_FILE_OBJECT,
3686 DACL_SECURITY_INFORMATION,
3687 NULL,
3688 NULL,
3689 &p->pDacl,
3690 NULL,
3691 &p->pSecurityDescriptor);
3692 }
3693 if (p->pSecurityDescriptor == NULL)
3694 {
3695 mch_free_acl((vim_acl_T)p);
3696 p = NULL;
3697 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698 }
3699 }
3700 }
3701
3702 return (vim_acl_T)p;
3703#endif
3704}
3705
Bram Moolenaar27515922013-06-29 15:36:26 +02003706#ifdef HAVE_ACL
3707/*
3708 * Check if "acl" contains inherited ACE.
3709 */
3710 static BOOL
3711is_acl_inherited(PACL acl)
3712{
3713 DWORD i;
3714 ACL_SIZE_INFORMATION acl_info;
3715 PACCESS_ALLOWED_ACE ace;
3716
3717 acl_info.AceCount = 0;
3718 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3719 for (i = 0; i < acl_info.AceCount; i++)
3720 {
3721 GetAce(acl, i, (LPVOID *)&ace);
3722 if (ace->Header.AceFlags & INHERITED_ACE)
3723 return TRUE;
3724 }
3725 return FALSE;
3726}
3727#endif
3728
Bram Moolenaar071d4272004-06-13 20:20:40 +00003729/*
3730 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3731 * Errors are ignored.
3732 * This must only be called with "acl" equal to what mch_get_acl() returned.
3733 */
3734 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003735mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736{
3737#ifdef HAVE_ACL
3738 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003739 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740
3741 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003742 {
3743# ifdef FEAT_MBYTE
3744 WCHAR *wn = NULL;
3745# endif
3746
3747 /* Set security flags */
3748 if (p->pSidOwner)
3749 sec_info |= OWNER_SECURITY_INFORMATION;
3750 if (p->pSidGroup)
3751 sec_info |= GROUP_SECURITY_INFORMATION;
3752 if (p->pDacl)
3753 {
3754 sec_info |= DACL_SECURITY_INFORMATION;
3755 /* Do not inherit its parent's DACL.
3756 * If the DACL is inherited, Cygwin permissions would be changed.
3757 */
3758 if (!is_acl_inherited(p->pDacl))
3759 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3760 }
3761 if (p->pSacl)
3762 sec_info |= SACL_SECURITY_INFORMATION;
3763
3764# ifdef FEAT_MBYTE
3765 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3766 wn = enc_to_utf16(fname, NULL);
3767 if (wn != NULL)
3768 {
3769 (void)pSetNamedSecurityInfoW(
3770 wn, // Abstract filename
3771 SE_FILE_OBJECT, // File Object
3772 sec_info,
3773 p->pSidOwner, // Ownership information.
3774 p->pSidGroup, // Group membership.
3775 p->pDacl, // Discretionary information.
3776 p->pSacl // For auditing purposes.
3777 );
3778 vim_free(wn);
3779 }
3780 else
3781# endif
3782 {
3783 (void)pSetNamedSecurityInfo(
3784 (LPSTR)fname, // Abstract filename
3785 SE_FILE_OBJECT, // File Object
3786 sec_info,
3787 p->pSidOwner, // Ownership information.
3788 p->pSidGroup, // Group membership.
3789 p->pDacl, // Discretionary information.
3790 p->pSacl // For auditing purposes.
3791 );
3792 }
3793 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794#endif
3795}
3796
3797 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003798mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003799{
3800#ifdef HAVE_ACL
3801 struct my_acl *p = (struct my_acl *)acl;
3802
3803 if (p != NULL)
3804 {
3805 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3806 vim_free(p);
3807 }
3808#endif
3809}
3810
3811#ifndef FEAT_GUI_W32
3812
3813/*
3814 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3815 */
3816 static BOOL WINAPI
3817handler_routine(
3818 DWORD dwCtrlType)
3819{
3820 switch (dwCtrlType)
3821 {
3822 case CTRL_C_EVENT:
3823 if (ctrl_c_interrupts)
3824 g_fCtrlCPressed = TRUE;
3825 return TRUE;
3826
3827 case CTRL_BREAK_EVENT:
3828 g_fCBrkPressed = TRUE;
3829 return TRUE;
3830
3831 /* fatal events: shut down gracefully */
3832 case CTRL_CLOSE_EVENT:
3833 case CTRL_LOGOFF_EVENT:
3834 case CTRL_SHUTDOWN_EVENT:
3835 windgoto((int)Rows - 1, 0);
3836 g_fForceExit = TRUE;
3837
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003838 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839 (dwCtrlType == CTRL_CLOSE_EVENT
3840 ? _("close")
3841 : dwCtrlType == CTRL_LOGOFF_EVENT
3842 ? _("logoff")
3843 : _("shutdown")));
3844#ifdef DEBUG
3845 OutputDebugString(IObuff);
3846#endif
3847
3848 preserve_exit(); /* output IObuff, preserve files and exit */
3849
3850 return TRUE; /* not reached */
3851
3852 default:
3853 return FALSE;
3854 }
3855}
3856
3857
3858/*
3859 * set the tty in (raw) ? "raw" : "cooked" mode
3860 */
3861 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003862mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003863{
3864 DWORD cmodein;
3865 DWORD cmodeout;
3866 BOOL bEnableHandler;
3867
3868 GetConsoleMode(g_hConIn, &cmodein);
3869 GetConsoleMode(g_hConOut, &cmodeout);
3870 if (tmode == TMODE_RAW)
3871 {
3872 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3873 ENABLE_ECHO_INPUT);
3874#ifdef FEAT_MOUSE
3875 if (g_fMouseActive)
3876 cmodein |= ENABLE_MOUSE_INPUT;
3877#endif
3878 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3879 bEnableHandler = TRUE;
3880 }
3881 else /* cooked */
3882 {
3883 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3884 ENABLE_ECHO_INPUT);
3885 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3886 bEnableHandler = FALSE;
3887 }
3888 SetConsoleMode(g_hConIn, cmodein);
3889 SetConsoleMode(g_hConOut, cmodeout);
3890 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3891
3892#ifdef MCH_WRITE_DUMP
3893 if (fdDump)
3894 {
3895 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3896 tmode == TMODE_RAW ? "raw" :
3897 tmode == TMODE_COOK ? "cooked" : "normal",
3898 cmodein, cmodeout);
3899 fflush(fdDump);
3900 }
3901#endif
3902}
3903
3904
3905/*
3906 * Get the size of the current window in `Rows' and `Columns'
3907 * Return OK when size could be determined, FAIL otherwise.
3908 */
3909 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003910mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911{
3912 CONSOLE_SCREEN_BUFFER_INFO csbi;
3913
3914 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3915 {
3916 /*
3917 * For some reason, we are trying to get the screen dimensions
3918 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3919 * variables are really intended to mean the size of Vim screen
3920 * while in termcap mode.
3921 */
3922 Rows = g_cbTermcap.Info.dwSize.Y;
3923 Columns = g_cbTermcap.Info.dwSize.X;
3924 }
3925 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3926 {
3927 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3928 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3929 }
3930 else
3931 {
3932 Rows = 25;
3933 Columns = 80;
3934 }
3935 return OK;
3936}
3937
3938/*
3939 * Set a console window to `xSize' * `ySize'
3940 */
3941 static void
3942ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003943 HANDLE hConsole,
3944 int xSize,
3945 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003946{
3947 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3948 SMALL_RECT srWindowRect; /* hold the new console size */
3949 COORD coordScreen;
3950
3951#ifdef MCH_WRITE_DUMP
3952 if (fdDump)
3953 {
3954 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3955 fflush(fdDump);
3956 }
3957#endif
3958
3959 /* get the largest size we can size the console window to */
3960 coordScreen = GetLargestConsoleWindowSize(hConsole);
3961
3962 /* define the new console window size and scroll position */
3963 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3964 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3965 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3966
3967 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3968 {
3969 int sx, sy;
3970
3971 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3972 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3973 if (sy < ySize || sx < xSize)
3974 {
3975 /*
3976 * Increasing number of lines/columns, do buffer first.
3977 * Use the maximal size in x and y direction.
3978 */
3979 if (sy < ySize)
3980 coordScreen.Y = ySize;
3981 else
3982 coordScreen.Y = sy;
3983 if (sx < xSize)
3984 coordScreen.X = xSize;
3985 else
3986 coordScreen.X = sx;
3987 SetConsoleScreenBufferSize(hConsole, coordScreen);
3988 }
3989 }
3990
3991 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3992 {
3993#ifdef MCH_WRITE_DUMP
3994 if (fdDump)
3995 {
3996 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3997 GetLastError());
3998 fflush(fdDump);
3999 }
4000#endif
4001 }
4002
4003 /* define the new console buffer size */
4004 coordScreen.X = xSize;
4005 coordScreen.Y = ySize;
4006
4007 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
4008 {
4009#ifdef MCH_WRITE_DUMP
4010 if (fdDump)
4011 {
4012 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
4013 GetLastError());
4014 fflush(fdDump);
4015 }
4016#endif
4017 }
4018}
4019
4020
4021/*
4022 * Set the console window to `Rows' * `Columns'
4023 */
4024 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004025mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004026{
4027 COORD coordScreen;
4028
4029 /* Don't change window size while still starting up */
4030 if (suppress_winsize != 0)
4031 {
4032 suppress_winsize = 2;
4033 return;
4034 }
4035
4036 if (term_console)
4037 {
4038 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
4039
4040 /* Clamp Rows and Columns to reasonable values */
4041 if (Rows > coordScreen.Y)
4042 Rows = coordScreen.Y;
4043 if (Columns > coordScreen.X)
4044 Columns = coordScreen.X;
4045
4046 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4047 }
4048}
4049
4050/*
4051 * Rows and/or Columns has changed.
4052 */
4053 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004054mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055{
4056 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4057}
4058
4059
4060/*
4061 * Called when started up, to set the winsize that was delayed.
4062 */
4063 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004064mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065{
4066 if (suppress_winsize == 2)
4067 {
4068 suppress_winsize = 0;
4069 mch_set_shellsize();
4070 shell_resized();
4071 }
4072 suppress_winsize = 0;
4073}
4074#endif /* FEAT_GUI_W32 */
4075
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004076 static BOOL
4077vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004078 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004079 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004080 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004081 STARTUPINFO *si,
4082 PROCESS_INFORMATION *pi)
4083{
4084# ifdef FEAT_MBYTE
4085 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4086 {
4087 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4088
4089 if (wcmd != NULL)
4090 {
4091 BOOL ret;
4092 ret = CreateProcessW(
4093 NULL, /* Executable name */
4094 wcmd, /* Command to execute */
4095 NULL, /* Process security attributes */
4096 NULL, /* Thread security attributes */
4097 inherit_handles, /* Inherit handles */
4098 flags, /* Creation flags */
4099 NULL, /* Environment */
4100 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004101 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004102 pi); /* Process information */
4103 vim_free(wcmd);
4104 return ret;
4105 }
4106 }
4107#endif
4108 return CreateProcess(
4109 NULL, /* Executable name */
4110 cmd, /* Command to execute */
4111 NULL, /* Process security attributes */
4112 NULL, /* Thread security attributes */
4113 inherit_handles, /* Inherit handles */
4114 flags, /* Creation flags */
4115 NULL, /* Environment */
4116 NULL, /* Current directory */
4117 si, /* Startup information */
4118 pi); /* Process information */
4119}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120
4121
4122#if defined(FEAT_GUI_W32) || defined(PROTO)
4123
4124/*
4125 * Specialised version of system() for Win32 GUI mode.
4126 * This version proceeds as follows:
4127 * 1. Create a console window for use by the subprocess
4128 * 2. Run the subprocess (it gets the allocated console by default)
4129 * 3. Wait for the subprocess to terminate and get its exit code
4130 * 4. Prompt the user to press a key to close the console window
4131 */
4132 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004133mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134{
4135 STARTUPINFO si;
4136 PROCESS_INFORMATION pi;
4137 DWORD ret = 0;
4138 HWND hwnd = GetFocus();
4139
4140 si.cb = sizeof(si);
4141 si.lpReserved = NULL;
4142 si.lpDesktop = NULL;
4143 si.lpTitle = NULL;
4144 si.dwFlags = STARTF_USESHOWWINDOW;
4145 /*
4146 * It's nicer to run a filter command in a minimized window, but in
4147 * Windows 95 this makes the command MUCH slower. We can't do it under
4148 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004149 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150 */
4151 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004152 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 else
4154 si.wShowWindow = SW_SHOWNORMAL;
4155 si.cbReserved2 = 0;
4156 si.lpReserved2 = NULL;
4157
Bram Moolenaar942d6b22016-02-07 19:57:16 +01004158 /* There is a strange error on Windows 95 when using "c:\command.com".
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 * When the "c:\\" is left out it works OK...? */
4160 if (mch_windows95()
4161 && (STRNICMP(cmd, "c:/command.com", 14) == 0
4162 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
4163 cmd += 3;
4164
4165 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004166 vim_create_process(cmd, FALSE,
4167 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004168
4169 /* Wait for the command to terminate before continuing */
4170 if (g_PlatformId != VER_PLATFORM_WIN32s)
4171 {
4172#ifdef FEAT_GUI
4173 int delay = 1;
4174
4175 /* Keep updating the window while waiting for the shell to finish. */
4176 for (;;)
4177 {
4178 MSG msg;
4179
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004180 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 {
4182 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004183 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004184 delay = 1;
4185 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186 }
4187 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4188 break;
4189
4190 /* We start waiting for a very short time and then increase it, so
4191 * that we respond quickly when the process is quick, and don't
4192 * consume too much overhead when it's slow. */
4193 if (delay < 50)
4194 delay += 10;
4195 }
4196#else
4197 WaitForSingleObject(pi.hProcess, INFINITE);
4198#endif
4199
4200 /* Get the command exit code */
4201 GetExitCodeProcess(pi.hProcess, &ret);
4202 }
4203 else
4204 {
4205 /*
4206 * This ugly code is the only quick way of performing
4207 * a synchronous spawn under Win32s. Yuk.
4208 */
4209 num_windows = 0;
4210 EnumWindows(win32ssynch_cb, 0);
4211 old_num_windows = num_windows;
4212 do
4213 {
4214 Sleep(1000);
4215 num_windows = 0;
4216 EnumWindows(win32ssynch_cb, 0);
4217 } while (num_windows == old_num_windows);
4218 ret = 0;
4219 }
4220
4221 /* Close the handles to the subprocess, so that it goes away */
4222 CloseHandle(pi.hThread);
4223 CloseHandle(pi.hProcess);
4224
4225 /* Try to get input focus back. Doesn't always work though. */
4226 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4227
4228 return ret;
4229}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004230
4231/*
4232 * Thread launched by the gui to send the current buffer data to the
4233 * process. This way avoid to hang up vim totally if the children
4234 * process take a long time to process the lines.
4235 */
4236 static DWORD WINAPI
4237sub_process_writer(LPVOID param)
4238{
4239 HANDLE g_hChildStd_IN_Wr = param;
4240 linenr_T lnum = curbuf->b_op_start.lnum;
4241 DWORD len = 0;
4242 DWORD l;
4243 char_u *lp = ml_get(lnum);
4244 char_u *s;
4245 int written = 0;
4246
4247 for (;;)
4248 {
4249 l = (DWORD)STRLEN(lp + written);
4250 if (l == 0)
4251 len = 0;
4252 else if (lp[written] == NL)
4253 {
4254 /* NL -> NUL translation */
4255 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4256 }
4257 else
4258 {
4259 s = vim_strchr(lp + written, NL);
4260 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4261 s == NULL ? l : (DWORD)(s - (lp + written)),
4262 &len, NULL);
4263 }
4264 if (len == (int)l)
4265 {
4266 /* Finished a line, add a NL, unless this line should not have
4267 * one. */
4268 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004269 || (!curbuf->b_p_bin
4270 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004271 || (lnum != curbuf->b_no_eol_lnum
4272 && (lnum != curbuf->b_ml.ml_line_count
4273 || curbuf->b_p_eol)))
4274 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004275 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004276 }
4277
4278 ++lnum;
4279 if (lnum > curbuf->b_op_end.lnum)
4280 break;
4281
4282 lp = ml_get(lnum);
4283 written = 0;
4284 }
4285 else if (len > 0)
4286 written += len;
4287 }
4288
4289 /* finished all the lines, close pipe */
4290 CloseHandle(g_hChildStd_IN_Wr);
4291 ExitThread(0);
4292}
4293
4294
4295# define BUFLEN 100 /* length for buffer, stolen from unix version */
4296
4297/*
4298 * This function read from the children's stdout and write the
4299 * data on screen or in the buffer accordingly.
4300 */
4301 static void
4302dump_pipe(int options,
4303 HANDLE g_hChildStd_OUT_Rd,
4304 garray_T *ga,
4305 char_u buffer[],
4306 DWORD *buffer_off)
4307{
4308 DWORD availableBytes = 0;
4309 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004310 int ret;
4311 DWORD len;
4312 DWORD toRead;
4313 int repeatCount;
4314
4315 /* we query the pipe to see if there is any data to read
4316 * to avoid to perform a blocking read */
4317 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4318 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004319 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004320 NULL, /* number of read bytes */
4321 &availableBytes, /* available bytes total */
4322 NULL); /* byteLeft */
4323
4324 repeatCount = 0;
4325 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004326 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004327 {
4328 repeatCount++;
4329 toRead =
4330# ifdef FEAT_MBYTE
4331 (DWORD)(BUFLEN - *buffer_off);
4332# else
4333 (DWORD)BUFLEN;
4334# endif
4335 toRead = availableBytes < toRead ? availableBytes : toRead;
4336 ReadFile(g_hChildStd_OUT_Rd, buffer
4337# ifdef FEAT_MBYTE
4338 + *buffer_off, toRead
4339# else
4340 , toRead
4341# endif
4342 , &len, NULL);
4343
4344 /* If we haven't read anything, there is a problem */
4345 if (len == 0)
4346 break;
4347
4348 availableBytes -= len;
4349
4350 if (options & SHELL_READ)
4351 {
4352 /* Do NUL -> NL translation, append NL separated
4353 * lines to the current buffer. */
4354 for (i = 0; i < len; ++i)
4355 {
4356 if (buffer[i] == NL)
4357 append_ga_line(ga);
4358 else if (buffer[i] == NUL)
4359 ga_append(ga, NL);
4360 else
4361 ga_append(ga, buffer[i]);
4362 }
4363 }
4364# ifdef FEAT_MBYTE
4365 else if (has_mbyte)
4366 {
4367 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004368 int c;
4369 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004370
4371 len += *buffer_off;
4372 buffer[len] = NUL;
4373
4374 /* Check if the last character in buffer[] is
4375 * incomplete, keep these bytes for the next
4376 * round. */
4377 for (p = buffer; p < buffer + len; p += l)
4378 {
4379 l = mb_cptr2len(p);
4380 if (l == 0)
4381 l = 1; /* NUL byte? */
4382 else if (MB_BYTE2LEN(*p) != l)
4383 break;
4384 }
4385 if (p == buffer) /* no complete character */
4386 {
4387 /* avoid getting stuck at an illegal byte */
4388 if (len >= 12)
4389 ++p;
4390 else
4391 {
4392 *buffer_off = len;
4393 return;
4394 }
4395 }
4396 c = *p;
4397 *p = NUL;
4398 msg_puts(buffer);
4399 if (p < buffer + len)
4400 {
4401 *p = c;
4402 *buffer_off = (DWORD)((buffer + len) - p);
4403 mch_memmove(buffer, p, *buffer_off);
4404 return;
4405 }
4406 *buffer_off = 0;
4407 }
4408# endif /* FEAT_MBYTE */
4409 else
4410 {
4411 buffer[len] = NUL;
4412 msg_puts(buffer);
4413 }
4414
4415 windgoto(msg_row, msg_col);
4416 cursor_on();
4417 out_flush();
4418 }
4419}
4420
4421/*
4422 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4423 * for communication and doesn't open any new window.
4424 */
4425 static int
4426mch_system_piped(char *cmd, int options)
4427{
4428 STARTUPINFO si;
4429 PROCESS_INFORMATION pi;
4430 DWORD ret = 0;
4431
4432 HANDLE g_hChildStd_IN_Rd = NULL;
4433 HANDLE g_hChildStd_IN_Wr = NULL;
4434 HANDLE g_hChildStd_OUT_Rd = NULL;
4435 HANDLE g_hChildStd_OUT_Wr = NULL;
4436
4437 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4438 DWORD len;
4439
4440 /* buffer used to receive keys */
4441 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4442 int ta_len = 0; /* valid bytes in ta_buf[] */
4443
4444 DWORD i;
4445 int c;
4446 int noread_cnt = 0;
4447 garray_T ga;
4448 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004449 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004450 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004451
4452 SECURITY_ATTRIBUTES saAttr;
4453
4454 /* Set the bInheritHandle flag so pipe handles are inherited. */
4455 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4456 saAttr.bInheritHandle = TRUE;
4457 saAttr.lpSecurityDescriptor = NULL;
4458
4459 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4460 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4461 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4462 /* Create a pipe for the child process's STDIN. */
4463 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4464 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4465 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4466 {
4467 CloseHandle(g_hChildStd_IN_Rd);
4468 CloseHandle(g_hChildStd_IN_Wr);
4469 CloseHandle(g_hChildStd_OUT_Rd);
4470 CloseHandle(g_hChildStd_OUT_Wr);
4471 MSG_PUTS(_("\nCannot create pipes\n"));
4472 }
4473
4474 si.cb = sizeof(si);
4475 si.lpReserved = NULL;
4476 si.lpDesktop = NULL;
4477 si.lpTitle = NULL;
4478 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4479
4480 /* set-up our file redirection */
4481 si.hStdError = g_hChildStd_OUT_Wr;
4482 si.hStdOutput = g_hChildStd_OUT_Wr;
4483 si.hStdInput = g_hChildStd_IN_Rd;
4484 si.wShowWindow = SW_HIDE;
4485 si.cbReserved2 = 0;
4486 si.lpReserved2 = NULL;
4487
4488 if (options & SHELL_READ)
4489 ga_init2(&ga, 1, BUFLEN);
4490
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004491 if (cmd != NULL)
4492 {
4493 p = (char *)vim_strsave((char_u *)cmd);
4494 if (p != NULL)
4495 unescape_shellxquote((char_u *)p, p_sxe);
4496 else
4497 p = cmd;
4498 }
4499
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004500 /* Now, run the command.
4501 * About "Inherit handles" being TRUE: this command can be litigious,
4502 * handle inheritance was deactivated for pending temp file, but, if we
4503 * deactivate it, the pipes don't work for some reason. */
4504 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004505
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004506 if (p != cmd)
4507 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004508
4509 /* Close our unused side of the pipes */
4510 CloseHandle(g_hChildStd_IN_Rd);
4511 CloseHandle(g_hChildStd_OUT_Wr);
4512
4513 if (options & SHELL_WRITE)
4514 {
4515 HANDLE thread =
4516 CreateThread(NULL, /* security attributes */
4517 0, /* default stack size */
4518 sub_process_writer, /* function to be executed */
4519 g_hChildStd_IN_Wr, /* parameter */
4520 0, /* creation flag, start immediately */
4521 NULL); /* we don't care about thread id */
4522 CloseHandle(thread);
4523 g_hChildStd_IN_Wr = NULL;
4524 }
4525
4526 /* Keep updating the window while waiting for the shell to finish. */
4527 for (;;)
4528 {
4529 MSG msg;
4530
Bram Moolenaar175d0702013-12-11 18:36:33 +01004531 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004532 {
4533 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004534 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004535 }
4536
4537 /* write pipe information in the window */
4538 if ((options & (SHELL_READ|SHELL_WRITE))
4539# ifdef FEAT_GUI
4540 || gui.in_use
4541# endif
4542 )
4543 {
4544 len = 0;
4545 if (!(options & SHELL_EXPAND)
4546 && ((options &
4547 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4548 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4549# ifdef FEAT_GUI
4550 || gui.in_use
4551# endif
4552 )
4553 && (ta_len > 0 || noread_cnt > 4))
4554 {
4555 if (ta_len == 0)
4556 {
4557 /* Get extra characters when we don't have any. Reset the
4558 * counter and timer. */
4559 noread_cnt = 0;
4560# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4561 gettimeofday(&start_tv, NULL);
4562# endif
4563 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4564 }
4565 if (ta_len > 0 || len > 0)
4566 {
4567 /*
4568 * For pipes: Check for CTRL-C: send interrupt signal to
4569 * child. Check for CTRL-D: EOF, close pipe to child.
4570 */
4571 if (len == 1 && cmd != NULL)
4572 {
4573 if (ta_buf[ta_len] == Ctrl_C)
4574 {
4575 /* Learn what exit code is expected, for
4576 * now put 9 as SIGKILL */
4577 TerminateProcess(pi.hProcess, 9);
4578 }
4579 if (ta_buf[ta_len] == Ctrl_D)
4580 {
4581 CloseHandle(g_hChildStd_IN_Wr);
4582 g_hChildStd_IN_Wr = NULL;
4583 }
4584 }
4585
4586 /* replace K_BS by <BS> and K_DEL by <DEL> */
4587 for (i = ta_len; i < ta_len + len; ++i)
4588 {
4589 if (ta_buf[i] == CSI && len - i > 2)
4590 {
4591 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4592 if (c == K_DEL || c == K_KDEL || c == K_BS)
4593 {
4594 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4595 (size_t)(len - i - 2));
4596 if (c == K_DEL || c == K_KDEL)
4597 ta_buf[i] = DEL;
4598 else
4599 ta_buf[i] = Ctrl_H;
4600 len -= 2;
4601 }
4602 }
4603 else if (ta_buf[i] == '\r')
4604 ta_buf[i] = '\n';
4605# ifdef FEAT_MBYTE
4606 if (has_mbyte)
4607 i += (*mb_ptr2len_len)(ta_buf + i,
4608 ta_len + len - i) - 1;
4609# endif
4610 }
4611
4612 /*
4613 * For pipes: echo the typed characters. For a pty this
4614 * does not seem to work.
4615 */
4616 for (i = ta_len; i < ta_len + len; ++i)
4617 {
4618 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4619 msg_putchar(ta_buf[i]);
4620# ifdef FEAT_MBYTE
4621 else if (has_mbyte)
4622 {
4623 int l = (*mb_ptr2len)(ta_buf + i);
4624
4625 msg_outtrans_len(ta_buf + i, l);
4626 i += l - 1;
4627 }
4628# endif
4629 else
4630 msg_outtrans_len(ta_buf + i, 1);
4631 }
4632 windgoto(msg_row, msg_col);
4633 out_flush();
4634
4635 ta_len += len;
4636
4637 /*
4638 * Write the characters to the child, unless EOF has been
4639 * typed for pipes. Write one character at a time, to
4640 * avoid losing too much typeahead. When writing buffer
4641 * lines, drop the typed characters (only check for
4642 * CTRL-C).
4643 */
4644 if (options & SHELL_WRITE)
4645 ta_len = 0;
4646 else if (g_hChildStd_IN_Wr != NULL)
4647 {
4648 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4649 1, &len, NULL);
4650 // if we are typing in, we want to keep things reactive
4651 delay = 1;
4652 if (len > 0)
4653 {
4654 ta_len -= len;
4655 mch_memmove(ta_buf, ta_buf + len, ta_len);
4656 }
4657 }
4658 }
4659 }
4660 }
4661
4662 if (ta_len)
4663 ui_inchar_undo(ta_buf, ta_len);
4664
4665 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4666 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004667 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004668 break;
4669 }
4670
4671 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004672 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004673
4674 /* We start waiting for a very short time and then increase it, so
4675 * that we respond quickly when the process is quick, and don't
4676 * consume too much overhead when it's slow. */
4677 if (delay < 50)
4678 delay += 10;
4679 }
4680
4681 /* Close the pipe */
4682 CloseHandle(g_hChildStd_OUT_Rd);
4683 if (g_hChildStd_IN_Wr != NULL)
4684 CloseHandle(g_hChildStd_IN_Wr);
4685
4686 WaitForSingleObject(pi.hProcess, INFINITE);
4687
4688 /* Get the command exit code */
4689 GetExitCodeProcess(pi.hProcess, &ret);
4690
4691 if (options & SHELL_READ)
4692 {
4693 if (ga.ga_len > 0)
4694 {
4695 append_ga_line(&ga);
4696 /* remember that the NL was missing */
4697 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4698 }
4699 else
4700 curbuf->b_no_eol_lnum = 0;
4701 ga_clear(&ga);
4702 }
4703
4704 /* Close the handles to the subprocess, so that it goes away */
4705 CloseHandle(pi.hThread);
4706 CloseHandle(pi.hProcess);
4707
4708 return ret;
4709}
4710
4711 static int
4712mch_system(char *cmd, int options)
4713{
4714 /* if we can pipe and the shelltemp option is off */
4715 if (allowPiping && !p_stmp)
4716 return mch_system_piped(cmd, options);
4717 else
4718 return mch_system_classic(cmd, options);
4719}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004720#else
4721
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004722# ifdef FEAT_MBYTE
4723 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004724mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004725{
4726 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4727 {
4728 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4729 if (wcmd != NULL)
4730 {
4731 int ret = _wsystem(wcmd);
4732 vim_free(wcmd);
4733 return ret;
4734 }
4735 }
4736 return system(cmd);
4737}
4738# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004739# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004740# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004741
4742#endif
4743
4744/*
4745 * Either execute a command by calling the shell or start a new shell
4746 */
4747 int
4748mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004749 char_u *cmd,
4750 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004751{
4752 int x = 0;
4753 int tmode = cur_tmode;
4754#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004755 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004756# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004757 int did_set_title = FALSE;
4758
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004759 /* Change the title to reflect that we are in a subshell. */
4760 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4761 {
4762 WCHAR szShellTitle[512];
4763
4764 if (GetConsoleTitleW(szShellTitle,
4765 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4766 {
4767 if (cmd == NULL)
4768 wcscat(szShellTitle, L" :sh");
4769 else
4770 {
4771 WCHAR *wn = enc_to_utf16(cmd, NULL);
4772
4773 if (wn != NULL)
4774 {
4775 wcscat(szShellTitle, L" - !");
4776 if ((wcslen(szShellTitle) + wcslen(wn) <
4777 sizeof(szShellTitle)/sizeof(WCHAR)))
4778 wcscat(szShellTitle, wn);
4779 SetConsoleTitleW(szShellTitle);
4780 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004781 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004782 }
4783 }
4784 }
4785 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004786 if (!did_set_title)
4787# endif
4788 /* Change the title to reflect that we are in a subshell. */
4789 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004791 if (cmd == NULL)
4792 strcat(szShellTitle, " :sh");
4793 else
4794 {
4795 strcat(szShellTitle, " - !");
4796 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4797 strcat(szShellTitle, cmd);
4798 }
4799 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004800 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004801#endif
4802
4803 out_flush();
4804
4805#ifdef MCH_WRITE_DUMP
4806 if (fdDump)
4807 {
4808 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4809 fflush(fdDump);
4810 }
4811#endif
4812
4813 /*
4814 * Catch all deadly signals while running the external command, because a
4815 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4816 */
4817 signal(SIGINT, SIG_IGN);
4818#if defined(__GNUC__) && !defined(__MINGW32__)
4819 signal(SIGKILL, SIG_IGN);
4820#else
4821 signal(SIGBREAK, SIG_IGN);
4822#endif
4823 signal(SIGILL, SIG_IGN);
4824 signal(SIGFPE, SIG_IGN);
4825 signal(SIGSEGV, SIG_IGN);
4826 signal(SIGTERM, SIG_IGN);
4827 signal(SIGABRT, SIG_IGN);
4828
4829 if (options & SHELL_COOKED)
4830 settmode(TMODE_COOK); /* set to normal mode */
4831
4832 if (cmd == NULL)
4833 {
4834 x = mch_system(p_sh, options);
4835 }
4836 else
4837 {
4838 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004839 char_u *newcmd = NULL;
4840 char_u *cmdbase = cmd;
4841 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004842
4843 /* Skip a leading ", ( and "(. */
4844 if (*cmdbase == '"' )
4845 ++cmdbase;
4846 if (*cmdbase == '(')
4847 ++cmdbase;
4848
4849 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4850 {
4851 STARTUPINFO si;
4852 PROCESS_INFORMATION pi;
4853 DWORD flags = CREATE_NEW_CONSOLE;
4854 char_u *p;
4855
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004856 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004857 si.cb = sizeof(si);
4858 si.lpReserved = NULL;
4859 si.lpDesktop = NULL;
4860 si.lpTitle = NULL;
4861 si.dwFlags = 0;
4862 si.cbReserved2 = 0;
4863 si.lpReserved2 = NULL;
4864
4865 cmdbase = skipwhite(cmdbase + 5);
4866 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4867 && vim_iswhite(cmdbase[4]))
4868 {
4869 cmdbase = skipwhite(cmdbase + 4);
4870 si.dwFlags = STARTF_USESHOWWINDOW;
4871 si.wShowWindow = SW_SHOWMINNOACTIVE;
4872 }
4873 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4874 && vim_iswhite(cmdbase[2]))
4875 {
4876 cmdbase = skipwhite(cmdbase + 2);
4877 flags = CREATE_NO_WINDOW;
4878 si.dwFlags = STARTF_USESTDHANDLES;
4879 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004880 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004881 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004882 NULL, // Security att.
4883 OPEN_EXISTING, // Open flags
4884 FILE_ATTRIBUTE_NORMAL, // File att.
4885 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004886 si.hStdOutput = si.hStdInput;
4887 si.hStdError = si.hStdInput;
4888 }
4889
4890 /* Remove a trailing ", ) and )" if they have a match
4891 * at the start of the command. */
4892 if (cmdbase > cmd)
4893 {
4894 p = cmdbase + STRLEN(cmdbase);
4895 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4896 *--p = NUL;
4897 if (p > cmdbase && p[-1] == ')'
4898 && (*cmd =='(' || cmd[1] == '('))
4899 *--p = NUL;
4900 }
4901
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004902 newcmd = cmdbase;
4903 unescape_shellxquote(cmdbase, p_sxe);
4904
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004905 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004906 * If creating new console, arguments are passed to the
4907 * 'cmd.exe' as-is. If it's not, arguments are not treated
4908 * correctly for current 'cmd.exe'. So unescape characters in
4909 * shellxescape except '|' for avoiding to be treated as
4910 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004911 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004912 if (flags != CREATE_NEW_CONSOLE)
4913 {
4914 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004915 char_u *cmd_shell = mch_getenv("COMSPEC");
4916
4917 if (cmd_shell == NULL || *cmd_shell == NUL)
4918 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004919
4920 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4921 if (subcmd != NULL)
4922 {
4923 /* make "cmd.exe /c arguments" */
4924 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004925 newcmd = lalloc(cmdlen, TRUE);
4926 if (newcmd != NULL)
4927 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004928 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004929 else
4930 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004931 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004932 }
4933 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004934
4935 /*
4936 * Now, start the command as a process, so that it doesn't
4937 * inherit our handles which causes unpleasant dangling swap
4938 * files if we exit before the spawned process
4939 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004940 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004941 x = 0;
4942 else
4943 {
4944 x = -1;
4945#ifdef FEAT_GUI_W32
4946 EMSG(_("E371: Command not found"));
4947#endif
4948 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004949
4950 if (newcmd != cmdbase)
4951 vim_free(newcmd);
4952
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004953 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004954 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004955 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004956 CloseHandle(si.hStdInput);
4957 }
4958 /* Close the handles to the subprocess, so that it goes away */
4959 CloseHandle(pi.hThread);
4960 CloseHandle(pi.hProcess);
4961 }
4962 else
4963 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004964 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004965#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004966 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004967#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004968 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4969
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004970 newcmd = lalloc(cmdlen, TRUE);
4971 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004972 {
4973#if defined(FEAT_GUI_W32)
4974 if (need_vimrun_warning)
4975 {
4976 MessageBox(NULL,
4977 _("VIMRUN.EXE not found in your $PATH.\n"
4978 "External commands will not pause after completion.\n"
4979 "See :help win32-vimrun for more information."),
4980 _("Vim Warning"),
4981 MB_ICONWARNING);
4982 need_vimrun_warning = FALSE;
4983 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004984 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985 /* Use vimrun to execute the command. It opens a console
4986 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004987 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004988 vimrun_path,
4989 (msg_silent != 0 || (options & SHELL_DOOUT))
4990 ? "-s " : "",
4991 p_sh, p_shcf, cmd);
4992 else
4993#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004994 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004995 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004996 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004997 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004998 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999 }
5000 }
5001
5002 if (tmode == TMODE_RAW)
5003 settmode(TMODE_RAW); /* set to raw mode */
5004
5005 /* Print the return value, unless "vimrun" was used. */
5006 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
5007#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02005008 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
5009 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005010#endif
5011 )
5012 {
5013 smsg(_("shell returned %d"), x);
5014 msg_putchar('\n');
5015 }
5016#ifdef FEAT_TITLE
5017 resettitle();
5018#endif
5019
5020 signal(SIGINT, SIG_DFL);
5021#if defined(__GNUC__) && !defined(__MINGW32__)
5022 signal(SIGKILL, SIG_DFL);
5023#else
5024 signal(SIGBREAK, SIG_DFL);
5025#endif
5026 signal(SIGILL, SIG_DFL);
5027 signal(SIGFPE, SIG_DFL);
5028 signal(SIGSEGV, SIG_DFL);
5029 signal(SIGTERM, SIG_DFL);
5030 signal(SIGABRT, SIG_DFL);
5031
5032 return x;
5033}
5034
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005035#if defined(FEAT_JOB) || defined(PROTO)
5036 void
5037mch_start_job(char *cmd, job_T *job)
5038{
5039 STARTUPINFO si;
5040 PROCESS_INFORMATION pi;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005041 HANDLE jo;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005042
Bram Moolenaar76467df2016-02-12 19:30:26 +01005043 jo = CreateJobObject(NULL, NULL);
5044 if (jo == NULL)
5045 {
5046 job->jv_status = JOB_FAILED;
5047 return;
5048 }
5049
5050 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005051 ZeroMemory(&si, sizeof(si));
5052 si.cb = sizeof(si);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005053 si.dwFlags = STARTF_USESHOWWINDOW;
5054 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005055
5056 if (!vim_create_process(cmd, FALSE,
Bram Moolenaar76467df2016-02-12 19:30:26 +01005057 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005058 CREATE_DEFAULT_ERROR_MODE |
5059 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005060 CREATE_NEW_CONSOLE,
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005061 &si, &pi))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005062 {
5063 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005064 job->jv_status = JOB_FAILED;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005065 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005066 else
5067 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005068 if (!AssignProcessToJobObject(jo, pi.hProcess))
5069 {
5070 /* if failing, switch the way to terminate
5071 * process with TerminateProcess. */
5072 CloseHandle(jo);
5073 jo = NULL;
5074 }
5075 ResumeThread(pi.hThread);
5076 CloseHandle(job->jv_proc_info.hThread);
5077 job->jv_proc_info = pi;
5078 job->jv_job_object = jo;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005079 job->jv_status = JOB_STARTED;
5080 }
5081}
5082
5083 char *
5084mch_job_status(job_T *job)
5085{
5086 DWORD dwExitCode = 0;
5087
Bram Moolenaar76467df2016-02-12 19:30:26 +01005088 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5089 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005090 {
Bram Moolenaar76467df2016-02-12 19:30:26 +01005091 job->jv_status = JOB_ENDED;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005092 return "dead";
5093 }
5094 return "run";
5095}
5096
5097 int
5098mch_stop_job(job_T *job, char_u *how)
5099{
Bram Moolenaar76467df2016-02-12 19:30:26 +01005100 int ret = 0;
5101 int ctrl_c = STRCMP(how, "int") == 0;
5102
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005103 if (STRCMP(how, "kill") == 0)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005104 {
5105 if (job->jv_job_object != NULL)
5106 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
5107 else
5108 return TerminateProcess(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
5109 }
5110
5111 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5112 return FAIL;
5113 ret = GenerateConsoleCtrlEvent(
5114 ctrl_c ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5115 job->jv_proc_info.dwProcessId)
5116 ? OK : FAIL;
5117 FreeConsole();
5118 return ret;
5119}
5120
5121/*
5122 * Clear the data related to "job".
5123 */
5124 void
5125mch_clear_job(job_T *job)
5126{
5127 if (job->jv_status != JOB_FAILED)
5128 {
5129 if (job->jv_job_object != NULL)
5130 CloseHandle(job->jv_job_object);
5131 CloseHandle(job->jv_proc_info.hProcess);
5132 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005133}
5134#endif
5135
Bram Moolenaar071d4272004-06-13 20:20:40 +00005136
5137#ifndef FEAT_GUI_W32
5138
5139/*
5140 * Start termcap mode
5141 */
5142 static void
5143termcap_mode_start(void)
5144{
5145 DWORD cmodein;
5146
5147 if (g_fTermcapMode)
5148 return;
5149
5150 SaveConsoleBuffer(&g_cbNonTermcap);
5151
5152 if (g_cbTermcap.IsValid)
5153 {
5154 /*
5155 * We've been in termcap mode before. Restore certain screen
5156 * characteristics, including the buffer size and the window
5157 * size. Since we will be redrawing the screen, we don't need
5158 * to restore the actual contents of the buffer.
5159 */
5160 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5161 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5162 Rows = g_cbTermcap.Info.dwSize.Y;
5163 Columns = g_cbTermcap.Info.dwSize.X;
5164 }
5165 else
5166 {
5167 /*
5168 * This is our first time entering termcap mode. Clear the console
5169 * screen buffer, and resize the buffer to match the current window
5170 * size. We will use this as the size of our editing environment.
5171 */
5172 ClearConsoleBuffer(g_attrCurrent);
5173 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5174 }
5175
5176#ifdef FEAT_TITLE
5177 resettitle();
5178#endif
5179
5180 GetConsoleMode(g_hConIn, &cmodein);
5181#ifdef FEAT_MOUSE
5182 if (g_fMouseActive)
5183 cmodein |= ENABLE_MOUSE_INPUT;
5184 else
5185 cmodein &= ~ENABLE_MOUSE_INPUT;
5186#endif
5187 cmodein |= ENABLE_WINDOW_INPUT;
5188 SetConsoleMode(g_hConIn, cmodein);
5189
5190 redraw_later_clear();
5191 g_fTermcapMode = TRUE;
5192}
5193
5194
5195/*
5196 * End termcap mode
5197 */
5198 static void
5199termcap_mode_end(void)
5200{
5201 DWORD cmodein;
5202 ConsoleBuffer *cb;
5203 COORD coord;
5204 DWORD dwDummy;
5205
5206 if (!g_fTermcapMode)
5207 return;
5208
5209 SaveConsoleBuffer(&g_cbTermcap);
5210
5211 GetConsoleMode(g_hConIn, &cmodein);
5212 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5213 SetConsoleMode(g_hConIn, cmodein);
5214
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005215#ifdef FEAT_RESTORE_ORIG_SCREEN
5216 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5217#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005219#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005220 RestoreConsoleBuffer(cb, p_rs);
5221 SetConsoleCursorInfo(g_hConOut, &g_cci);
5222
5223 if (p_rs || exiting)
5224 {
5225 /*
5226 * Clear anything that happens to be on the current line.
5227 */
5228 coord.X = 0;
5229 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5230 FillConsoleOutputCharacter(g_hConOut, ' ',
5231 cb->Info.dwSize.X, coord, &dwDummy);
5232 /*
5233 * The following is just for aesthetics. If we are exiting without
5234 * restoring the screen, then we want to have a prompt string
5235 * appear at the bottom line. However, the command interpreter
5236 * seems to always advance the cursor one line before displaying
5237 * the prompt string, which causes the screen to scroll. To
5238 * counter this, move the cursor up one line before exiting.
5239 */
5240 if (exiting && !p_rs)
5241 coord.Y--;
5242 /*
5243 * Position the cursor at the leftmost column of the desired row.
5244 */
5245 SetConsoleCursorPosition(g_hConOut, coord);
5246 }
5247
5248 g_fTermcapMode = FALSE;
5249}
5250#endif /* FEAT_GUI_W32 */
5251
5252
5253#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005254/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005255 void
5256mch_write(
5257 char_u *s,
5258 int len)
5259{
5260 /* never used */
5261}
5262
5263#else
5264
5265/*
5266 * clear `n' chars, starting from `coord'
5267 */
5268 static void
5269clear_chars(
5270 COORD coord,
5271 DWORD n)
5272{
5273 DWORD dwDummy;
5274
5275 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5276 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5277}
5278
5279
5280/*
5281 * Clear the screen
5282 */
5283 static void
5284clear_screen(void)
5285{
5286 g_coord.X = g_coord.Y = 0;
5287 clear_chars(g_coord, Rows * Columns);
5288}
5289
5290
5291/*
5292 * Clear to end of display
5293 */
5294 static void
5295clear_to_end_of_display(void)
5296{
5297 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5298 * Columns + (Columns - g_coord.X));
5299}
5300
5301
5302/*
5303 * Clear to end of line
5304 */
5305 static void
5306clear_to_end_of_line(void)
5307{
5308 clear_chars(g_coord, Columns - g_coord.X);
5309}
5310
5311
5312/*
5313 * Scroll the scroll region up by `cLines' lines
5314 */
5315 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005316scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005317{
5318 COORD oldcoord = g_coord;
5319
5320 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5321 delete_lines(cLines);
5322
5323 g_coord = oldcoord;
5324}
5325
5326
5327/*
5328 * Set the scroll region
5329 */
5330 static void
5331set_scroll_region(
5332 unsigned left,
5333 unsigned top,
5334 unsigned right,
5335 unsigned bottom)
5336{
5337 if (left >= right
5338 || top >= bottom
5339 || right > (unsigned) Columns - 1
5340 || bottom > (unsigned) Rows - 1)
5341 return;
5342
5343 g_srScrollRegion.Left = left;
5344 g_srScrollRegion.Top = top;
5345 g_srScrollRegion.Right = right;
5346 g_srScrollRegion.Bottom = bottom;
5347}
5348
5349
5350/*
5351 * Insert `cLines' lines at the current cursor position
5352 */
5353 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005354insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005355{
5356 SMALL_RECT source;
5357 COORD dest;
5358 CHAR_INFO fill;
5359
5360 dest.X = 0;
5361 dest.Y = g_coord.Y + cLines;
5362
5363 source.Left = 0;
5364 source.Top = g_coord.Y;
5365 source.Right = g_srScrollRegion.Right;
5366 source.Bottom = g_srScrollRegion.Bottom - cLines;
5367
5368 fill.Char.AsciiChar = ' ';
5369 fill.Attributes = g_attrCurrent;
5370
5371 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5372
5373 /* Here we have to deal with a win32 console flake: If the scroll
5374 * region looks like abc and we scroll c to a and fill with d we get
5375 * cbd... if we scroll block c one line at a time to a, we get cdd...
5376 * vim expects cdd consistently... So we have to deal with that
5377 * here... (this also occurs scrolling the same way in the other
5378 * direction). */
5379
5380 if (source.Bottom < dest.Y)
5381 {
5382 COORD coord;
5383
5384 coord.X = 0;
5385 coord.Y = source.Bottom;
5386 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5387 }
5388}
5389
5390
5391/*
5392 * Delete `cLines' lines at the current cursor position
5393 */
5394 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005395delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005396{
5397 SMALL_RECT source;
5398 COORD dest;
5399 CHAR_INFO fill;
5400 int nb;
5401
5402 dest.X = 0;
5403 dest.Y = g_coord.Y;
5404
5405 source.Left = 0;
5406 source.Top = g_coord.Y + cLines;
5407 source.Right = g_srScrollRegion.Right;
5408 source.Bottom = g_srScrollRegion.Bottom;
5409
5410 fill.Char.AsciiChar = ' ';
5411 fill.Attributes = g_attrCurrent;
5412
5413 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5414
5415 /* Here we have to deal with a win32 console flake: If the scroll
5416 * region looks like abc and we scroll c to a and fill with d we get
5417 * cbd... if we scroll block c one line at a time to a, we get cdd...
5418 * vim expects cdd consistently... So we have to deal with that
5419 * here... (this also occurs scrolling the same way in the other
5420 * direction). */
5421
5422 nb = dest.Y + (source.Bottom - source.Top) + 1;
5423
5424 if (nb < source.Top)
5425 {
5426 COORD coord;
5427
5428 coord.X = 0;
5429 coord.Y = nb;
5430 clear_chars(coord, Columns * (source.Top - nb));
5431 }
5432}
5433
5434
5435/*
5436 * Set the cursor position
5437 */
5438 static void
5439gotoxy(
5440 unsigned x,
5441 unsigned y)
5442{
5443 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5444 return;
5445
5446 /* external cursor coords are 1-based; internal are 0-based */
5447 g_coord.X = x - 1;
5448 g_coord.Y = y - 1;
5449 SetConsoleCursorPosition(g_hConOut, g_coord);
5450}
5451
5452
5453/*
5454 * Set the current text attribute = (foreground | background)
5455 * See ../doc/os_win32.txt for the numbers.
5456 */
5457 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005458textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005459{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005460 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005461
5462 SetConsoleTextAttribute(g_hConOut, wAttr);
5463}
5464
5465
5466 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005467textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005468{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005469 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005470
5471 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5472}
5473
5474
5475 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005476textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005477{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005478 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005479
5480 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5481}
5482
5483
5484/*
5485 * restore the default text attribute (whatever we started with)
5486 */
5487 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005488normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005489{
5490 textattr(g_attrDefault);
5491}
5492
5493
5494static WORD g_attrPreStandout = 0;
5495
5496/*
5497 * Make the text standout, by brightening it
5498 */
5499 static void
5500standout(void)
5501{
5502 g_attrPreStandout = g_attrCurrent;
5503 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5504}
5505
5506
5507/*
5508 * Turn off standout mode
5509 */
5510 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005511standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512{
5513 if (g_attrPreStandout)
5514 {
5515 textattr(g_attrPreStandout);
5516 g_attrPreStandout = 0;
5517 }
5518}
5519
5520
5521/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005522 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 */
5524 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005525mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005526{
5527 char_u *p;
5528 int n;
5529
5530 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5531 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5532 if (T_ME[0] == ESC && T_ME[1] == '|')
5533 {
5534 p = T_ME + 2;
5535 n = getdigits(&p);
5536 if (*p == 'm' && n > 0)
5537 {
5538 cterm_normal_fg_color = (n & 0xf) + 1;
5539 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5540 }
5541 }
5542}
5543
5544
5545/*
5546 * visual bell: flash the screen
5547 */
5548 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005549visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550{
5551 COORD coordOrigin = {0, 0};
5552 WORD attrFlash = ~g_attrCurrent & 0xff;
5553
5554 DWORD dwDummy;
5555 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5556
5557 if (oldattrs == NULL)
5558 return;
5559 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5560 coordOrigin, &dwDummy);
5561 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5562 coordOrigin, &dwDummy);
5563
5564 Sleep(15); /* wait for 15 msec */
5565 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5566 coordOrigin, &dwDummy);
5567 vim_free(oldattrs);
5568}
5569
5570
5571/*
5572 * Make the cursor visible or invisible
5573 */
5574 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005575cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005576{
5577 s_cursor_visible = fVisible;
5578#ifdef MCH_CURSOR_SHAPE
5579 mch_update_cursor();
5580#endif
5581}
5582
5583
5584/*
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005585 * write `cbToWrite' bytes in `pchBuf' to the screen
5586 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005587 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005588 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005590 char_u *pchBuf,
5591 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592{
5593 COORD coord = g_coord;
5594 DWORD written;
5595
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005596#ifdef FEAT_MBYTE
5597 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5598 {
5599 static WCHAR *unicodebuf = NULL;
5600 static int unibuflen = 0;
5601 int length;
5602 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005603
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005604 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5605 if (unicodebuf == NULL || length > unibuflen)
5606 {
5607 vim_free(unicodebuf);
5608 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5609 unibuflen = length;
5610 }
5611 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5612 unicodebuf, unibuflen);
5613
5614 cells = mb_string2cells(pchBuf, cbToWrite);
5615 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5616 coord, &written);
5617 /* When writing fails or didn't write a single character, pretend one
5618 * character was written, otherwise we get stuck. */
5619 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5620 coord, &cchwritten) == 0
5621 || cchwritten == 0)
5622 cchwritten = 1;
5623
5624 if (cchwritten == length)
5625 {
5626 written = cbToWrite;
5627 g_coord.X += (SHORT)cells;
5628 }
5629 else
5630 {
5631 char_u *p = pchBuf;
5632 for (n = 0; n < cchwritten; n++)
5633 mb_cptr_adv(p);
5634 written = p - pchBuf;
5635 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5636 }
5637 }
5638 else
5639#endif
5640 {
5641 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5642 coord, &written);
5643 /* When writing fails or didn't write a single character, pretend one
5644 * character was written, otherwise we get stuck. */
5645 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5646 coord, &written) == 0
5647 || written == 0)
5648 written = 1;
5649
5650 g_coord.X += (SHORT) written;
5651 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005652
5653 while (g_coord.X > g_srScrollRegion.Right)
5654 {
5655 g_coord.X -= (SHORT) Columns;
5656 if (g_coord.Y < g_srScrollRegion.Bottom)
5657 g_coord.Y++;
5658 }
5659
5660 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5661
5662 return written;
5663}
5664
5665
5666/*
5667 * mch_write(): write the output buffer to the screen, translating ESC
5668 * sequences into calls to console output routines.
5669 */
5670 void
5671mch_write(
5672 char_u *s,
5673 int len)
5674{
5675 s[len] = NUL;
5676
5677 if (!term_console)
5678 {
5679 write(1, s, (unsigned)len);
5680 return;
5681 }
5682
5683 /* translate ESC | sequences into faked bios calls */
5684 while (len--)
5685 {
5686 /* optimization: use one single write_chars for runs of text,
5687 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005688 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005689
5690 if (p_wd)
5691 {
5692 WaitForChar(p_wd);
5693 if (prefix != 0)
5694 prefix = 1;
5695 }
5696
5697 if (prefix != 0)
5698 {
5699 DWORD nWritten;
5700
5701 nWritten = write_chars(s, prefix);
5702#ifdef MCH_WRITE_DUMP
5703 if (fdDump)
5704 {
5705 fputc('>', fdDump);
5706 fwrite(s, sizeof(char_u), nWritten, fdDump);
5707 fputs("<\n", fdDump);
5708 }
5709#endif
5710 len -= (nWritten - 1);
5711 s += nWritten;
5712 }
5713 else if (s[0] == '\n')
5714 {
5715 /* \n, newline: go to the beginning of the next line or scroll */
5716 if (g_coord.Y == g_srScrollRegion.Bottom)
5717 {
5718 scroll(1);
5719 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5720 }
5721 else
5722 {
5723 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5724 }
5725#ifdef MCH_WRITE_DUMP
5726 if (fdDump)
5727 fputs("\\n\n", fdDump);
5728#endif
5729 s++;
5730 }
5731 else if (s[0] == '\r')
5732 {
5733 /* \r, carriage return: go to beginning of line */
5734 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5735#ifdef MCH_WRITE_DUMP
5736 if (fdDump)
5737 fputs("\\r\n", fdDump);
5738#endif
5739 s++;
5740 }
5741 else if (s[0] == '\b')
5742 {
5743 /* \b, backspace: move cursor one position left */
5744 if (g_coord.X > g_srScrollRegion.Left)
5745 g_coord.X--;
5746 else if (g_coord.Y > g_srScrollRegion.Top)
5747 {
5748 g_coord.X = g_srScrollRegion.Right;
5749 g_coord.Y--;
5750 }
5751 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5752#ifdef MCH_WRITE_DUMP
5753 if (fdDump)
5754 fputs("\\b\n", fdDump);
5755#endif
5756 s++;
5757 }
5758 else if (s[0] == '\a')
5759 {
5760 /* \a, bell */
5761 MessageBeep(0xFFFFFFFF);
5762#ifdef MCH_WRITE_DUMP
5763 if (fdDump)
5764 fputs("\\a\n", fdDump);
5765#endif
5766 s++;
5767 }
5768 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5769 {
5770#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005771 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005772#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005773 char_u *p;
5774 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005775
5776 switch (s[2])
5777 {
5778 /* one or two numeric arguments, separated by ';' */
5779
5780 case '0': case '1': case '2': case '3': case '4':
5781 case '5': case '6': case '7': case '8': case '9':
5782 p = s + 2;
5783 arg1 = getdigits(&p); /* no check for length! */
5784 if (p > s + len)
5785 break;
5786
5787 if (*p == ';')
5788 {
5789 ++p;
5790 arg2 = getdigits(&p); /* no check for length! */
5791 if (p > s + len)
5792 break;
5793
5794 if (*p == 'H')
5795 gotoxy(arg2, arg1);
5796 else if (*p == 'r')
5797 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5798 }
5799 else if (*p == 'A')
5800 {
5801 /* move cursor up arg1 lines in same column */
5802 gotoxy(g_coord.X + 1,
5803 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5804 }
5805 else if (*p == 'C')
5806 {
5807 /* move cursor right arg1 columns in same line */
5808 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5809 g_coord.Y + 1);
5810 }
5811 else if (*p == 'H')
5812 {
5813 gotoxy(1, arg1);
5814 }
5815 else if (*p == 'L')
5816 {
5817 insert_lines(arg1);
5818 }
5819 else if (*p == 'm')
5820 {
5821 if (arg1 == 0)
5822 normvideo();
5823 else
5824 textattr((WORD) arg1);
5825 }
5826 else if (*p == 'f')
5827 {
5828 textcolor((WORD) arg1);
5829 }
5830 else if (*p == 'b')
5831 {
5832 textbackground((WORD) arg1);
5833 }
5834 else if (*p == 'M')
5835 {
5836 delete_lines(arg1);
5837 }
5838
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005839 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005840 s = p + 1;
5841 break;
5842
5843
5844 /* Three-character escape sequences */
5845
5846 case 'A':
5847 /* move cursor up one line in same column */
5848 gotoxy(g_coord.X + 1,
5849 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5850 goto got3;
5851
5852 case 'B':
5853 visual_bell();
5854 goto got3;
5855
5856 case 'C':
5857 /* move cursor right one column in same line */
5858 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5859 g_coord.Y + 1);
5860 goto got3;
5861
5862 case 'E':
5863 termcap_mode_end();
5864 goto got3;
5865
5866 case 'F':
5867 standout();
5868 goto got3;
5869
5870 case 'f':
5871 standend();
5872 goto got3;
5873
5874 case 'H':
5875 gotoxy(1, 1);
5876 goto got3;
5877
5878 case 'j':
5879 clear_to_end_of_display();
5880 goto got3;
5881
5882 case 'J':
5883 clear_screen();
5884 goto got3;
5885
5886 case 'K':
5887 clear_to_end_of_line();
5888 goto got3;
5889
5890 case 'L':
5891 insert_lines(1);
5892 goto got3;
5893
5894 case 'M':
5895 delete_lines(1);
5896 goto got3;
5897
5898 case 'S':
5899 termcap_mode_start();
5900 goto got3;
5901
5902 case 'V':
5903 cursor_visible(TRUE);
5904 goto got3;
5905
5906 case 'v':
5907 cursor_visible(FALSE);
5908 goto got3;
5909
5910 got3:
5911 s += 3;
5912 len -= 2;
5913 }
5914
5915#ifdef MCH_WRITE_DUMP
5916 if (fdDump)
5917 {
5918 fputs("ESC | ", fdDump);
5919 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5920 fputc('\n', fdDump);
5921 }
5922#endif
5923 }
5924 else
5925 {
5926 /* Write a single character */
5927 DWORD nWritten;
5928
5929 nWritten = write_chars(s, 1);
5930#ifdef MCH_WRITE_DUMP
5931 if (fdDump)
5932 {
5933 fputc('>', fdDump);
5934 fwrite(s, sizeof(char_u), nWritten, fdDump);
5935 fputs("<\n", fdDump);
5936 }
5937#endif
5938
5939 len -= (nWritten - 1);
5940 s += nWritten;
5941 }
5942 }
5943
5944#ifdef MCH_WRITE_DUMP
5945 if (fdDump)
5946 fflush(fdDump);
5947#endif
5948}
5949
5950#endif /* FEAT_GUI_W32 */
5951
5952
5953/*
5954 * Delay for half a second.
5955 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005956/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005957 void
5958mch_delay(
5959 long msec,
5960 int ignoreinput)
5961{
5962#ifdef FEAT_GUI_W32
5963 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005964#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005966# ifdef FEAT_MZSCHEME
5967 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5968 {
5969 int towait = p_mzq;
5970
5971 /* if msec is large enough, wait by portions in p_mzq */
5972 while (msec > 0)
5973 {
5974 mzvim_check_threads();
5975 if (msec < towait)
5976 towait = msec;
5977 Sleep(towait);
5978 msec -= towait;
5979 }
5980 }
5981 else
5982# endif
5983 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005984 else
5985 WaitForChar(msec);
5986#endif
5987}
5988
5989
5990/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01005991 * This version of remove is not scared by a readonly (backup) file.
5992 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993 * Return 0 for success, -1 for failure.
5994 */
5995 int
5996mch_remove(char_u *name)
5997{
5998#ifdef FEAT_MBYTE
5999 WCHAR *wn = NULL;
6000 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006001#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002
Bram Moolenaar203258c2016-01-17 22:15:16 +01006003 /*
6004 * On Windows, deleting a directory's symbolic link is done by
6005 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6006 */
6007 if (mch_isdir(name) && mch_is_symbolic_link(name))
6008 return mch_rmdir(name);
6009
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006010 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6011
6012#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006013 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6014 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006015 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006016 if (wn != NULL)
6017 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006018 n = DeleteFileW(wn) ? 0 : -1;
6019 vim_free(wn);
6020 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6021 return n;
6022 /* Retry with non-wide function (for Windows 98). */
6023 }
6024 }
6025#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026 return DeleteFile(name) ? 0 : -1;
6027}
6028
6029
6030/*
6031 * check for an "interrupt signal": CTRL-break or CTRL-C
6032 */
6033 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006034mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006035{
6036#ifndef FEAT_GUI_W32 /* never used */
6037 if (g_fCtrlCPressed || g_fCBrkPressed)
6038 {
6039 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6040 got_int = TRUE;
6041 }
6042#endif
6043}
6044
Bram Moolenaaree273972016-01-02 21:11:51 +01006045/* physical RAM to leave for the OS */
6046#define WINNT_RESERVE_BYTES (256*1024*1024)
6047#define WIN95_RESERVE_BYTES (8*1024*1024)
6048
6049/*
6050 * How much main memory in KiB that can be used by VIM.
6051 */
6052/*ARGSUSED*/
6053 long_u
6054mch_total_mem(int special)
6055{
6056 PlatformId();
6057#if (defined(_MSC_VER) && (WINVER > 0x0400)) || defined(MEMORYSTATUSEX)
6058 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6059 {
6060 MEMORYSTATUSEX ms;
6061
6062 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6063 * what fits in 32 bits. But it's not always available. */
6064 ms.dwLength = sizeof(MEMORYSTATUSEX);
6065 GlobalMemoryStatusEx(&ms);
6066 if (ms.ullAvailVirtual < ms.ullTotalPhys)
6067 {
6068 /* Process address space fits in physical RAM, use all of it. */
6069 return (long_u)(ms.ullAvailVirtual / 1024);
6070 }
6071 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
6072 {
6073 /* Catch old NT box or perverse hardware setup. */
6074 return (long_u)((ms.ullTotalPhys / 2) / 1024);
6075 }
6076 /* Use physical RAM less reserve for OS + data. */
6077 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
6078 }
6079 else
6080#endif
6081 {
6082 /* Pre-XP or 95 OS handling. */
6083 MEMORYSTATUS ms;
6084 long_u os_reserve_bytes;
6085
6086 ms.dwLength = sizeof(MEMORYSTATUS);
6087 GlobalMemoryStatus(&ms);
6088 if (ms.dwAvailVirtual < ms.dwTotalPhys)
6089 {
6090 /* Process address space fits in physical RAM, use all of it. */
6091 return (long_u)(ms.dwAvailVirtual / 1024);
6092 }
6093 os_reserve_bytes = (g_PlatformId == VER_PLATFORM_WIN32_NT)
6094 ? WINNT_RESERVE_BYTES
6095 : WIN95_RESERVE_BYTES;
6096 if (ms.dwTotalPhys <= os_reserve_bytes)
6097 {
6098 /* Catch old boxes or perverse hardware setup. */
6099 return (long_u)((ms.dwTotalPhys / 2) / 1024);
6100 }
6101 /* Use physical RAM less reserve for OS + data. */
6102 return (long_u)((ms.dwTotalPhys - os_reserve_bytes) / 1024);
6103 }
6104}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006105
Bram Moolenaar071d4272004-06-13 20:20:40 +00006106#ifdef FEAT_MBYTE
6107/*
6108 * Same code as below, but with wide functions and no comments.
6109 * Return 0 for success, non-zero for failure.
6110 */
6111 int
6112mch_wrename(WCHAR *wold, WCHAR *wnew)
6113{
6114 WCHAR *p;
6115 int i;
6116 WCHAR szTempFile[_MAX_PATH + 1];
6117 WCHAR szNewPath[_MAX_PATH + 1];
6118 HANDLE hf;
6119
6120 if (!mch_windows95())
6121 {
6122 p = wold;
6123 for (i = 0; wold[i] != NUL; ++i)
6124 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6125 && wold[i + 1] != 0)
6126 p = wold + i + 1;
6127 if ((int)(wold + i - p) < 8 || p[6] != '~')
6128 return (MoveFileW(wold, wnew) == 0);
6129 }
6130
6131 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6132 return -1;
6133 *p = NUL;
6134
6135 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6136 return -2;
6137
6138 if (!DeleteFileW(szTempFile))
6139 return -3;
6140
6141 if (!MoveFileW(wold, szTempFile))
6142 return -4;
6143
6144 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6145 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6146 return -5;
6147 if (!CloseHandle(hf))
6148 return -6;
6149
6150 if (!MoveFileW(szTempFile, wnew))
6151 {
6152 (void)MoveFileW(szTempFile, wold);
6153 return -7;
6154 }
6155
6156 DeleteFileW(szTempFile);
6157
6158 if (!DeleteFileW(wold))
6159 return -8;
6160
6161 return 0;
6162}
6163#endif
6164
6165
6166/*
6167 * mch_rename() works around a bug in rename (aka MoveFile) in
6168 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6169 * file whose short file name is "FOO.BAR" (its long file name will
6170 * be correct: "foo.bar~"). Because a file can be accessed by
6171 * either its SFN or its LFN, "foo.bar" has effectively been
6172 * renamed to "foo.bar", which is not at all what was wanted. This
6173 * seems to happen only when renaming files with three-character
6174 * extensions by appending a suffix that does not include ".".
6175 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6176 *
6177 * There is another problem, which isn't really a bug but isn't right either:
6178 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6179 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6180 * service pack 6. Doesn't seem to happen on Windows 98.
6181 *
6182 * Like rename(), returns 0 upon success, non-zero upon failure.
6183 * Should probably set errno appropriately when errors occur.
6184 */
6185 int
6186mch_rename(
6187 const char *pszOldFile,
6188 const char *pszNewFile)
6189{
6190 char szTempFile[_MAX_PATH+1];
6191 char szNewPath[_MAX_PATH+1];
6192 char *pszFilePart;
6193 HANDLE hf;
6194#ifdef FEAT_MBYTE
6195 WCHAR *wold = NULL;
6196 WCHAR *wnew = NULL;
6197 int retval = -1;
6198
6199 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6200 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006201 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6202 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 if (wold != NULL && wnew != NULL)
6204 retval = mch_wrename(wold, wnew);
6205 vim_free(wold);
6206 vim_free(wnew);
6207 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6208 return retval;
6209 /* Retry with non-wide function (for Windows 98). */
6210 }
6211#endif
6212
6213 /*
6214 * No need to play tricks if not running Windows 95, unless the file name
6215 * contains a "~" as the seventh character.
6216 */
6217 if (!mch_windows95())
6218 {
6219 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6220 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6221 return rename(pszOldFile, pszNewFile);
6222 }
6223
6224 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6225 * a directory, no error is returned and pszFilePart will be NULL. */
6226 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6227 || pszFilePart == NULL)
6228 return -1;
6229 *pszFilePart = NUL;
6230
6231 /* Get (and create) a unique temporary file name in directory of new file */
6232 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6233 return -2;
6234
6235 /* blow the temp file away */
6236 if (!DeleteFile(szTempFile))
6237 return -3;
6238
6239 /* rename old file to the temp file */
6240 if (!MoveFile(pszOldFile, szTempFile))
6241 return -4;
6242
6243 /* now create an empty file called pszOldFile; this prevents the operating
6244 * system using pszOldFile as an alias (SFN) if we're renaming within the
6245 * same directory. For example, we're editing a file called
6246 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6247 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6248 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006249 * cause all sorts of problems later in buf_write(). So, we create an
6250 * empty file called filena~1.txt and the system will have to find some
6251 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 */
6253 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6254 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6255 return -5;
6256 if (!CloseHandle(hf))
6257 return -6;
6258
6259 /* rename the temp file to the new file */
6260 if (!MoveFile(szTempFile, pszNewFile))
6261 {
6262 /* Renaming failed. Rename the file back to its old name, so that it
6263 * looks like nothing happened. */
6264 (void)MoveFile(szTempFile, pszOldFile);
6265
6266 return -7;
6267 }
6268
6269 /* Seems to be left around on Novell filesystems */
6270 DeleteFile(szTempFile);
6271
6272 /* finally, remove the empty old file */
6273 if (!DeleteFile(pszOldFile))
6274 return -8;
6275
6276 return 0; /* success */
6277}
6278
6279/*
6280 * Get the default shell for the current hardware platform
6281 */
6282 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006283default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006284{
6285 char* psz = NULL;
6286
6287 PlatformId();
6288
6289 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
6290 psz = "cmd.exe";
6291 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
6292 psz = "command.com";
6293
6294 return psz;
6295}
6296
6297/*
6298 * mch_access() extends access() to do more detailed check on network drives.
6299 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6300 */
6301 int
6302mch_access(char *n, int p)
6303{
6304 HANDLE hFile;
6305 DWORD am;
6306 int retval = -1; /* default: fail */
6307#ifdef FEAT_MBYTE
6308 WCHAR *wn = NULL;
6309
6310 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006311 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312#endif
6313
6314 if (mch_isdir(n))
6315 {
6316 char TempName[_MAX_PATH + 16] = "";
6317#ifdef FEAT_MBYTE
6318 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6319#endif
6320
6321 if (p & R_OK)
6322 {
6323 /* Read check is performed by seeing if we can do a find file on
6324 * the directory for any file. */
6325#ifdef FEAT_MBYTE
6326 if (wn != NULL)
6327 {
6328 int i;
6329 WIN32_FIND_DATAW d;
6330
6331 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6332 TempNameW[i] = wn[i];
6333 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6334 TempNameW[i++] = '\\';
6335 TempNameW[i++] = '*';
6336 TempNameW[i++] = 0;
6337
6338 hFile = FindFirstFileW(TempNameW, &d);
6339 if (hFile == INVALID_HANDLE_VALUE)
6340 {
6341 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6342 goto getout;
6343
6344 /* Retry with non-wide function (for Windows 98). */
6345 vim_free(wn);
6346 wn = NULL;
6347 }
6348 else
6349 (void)FindClose(hFile);
6350 }
6351 if (wn == NULL)
6352#endif
6353 {
6354 char *pch;
6355 WIN32_FIND_DATA d;
6356
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00006357 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006358 pch = TempName + STRLEN(TempName) - 1;
6359 if (*pch != '\\' && *pch != '/')
6360 *++pch = '\\';
6361 *++pch = '*';
6362 *++pch = NUL;
6363
6364 hFile = FindFirstFile(TempName, &d);
6365 if (hFile == INVALID_HANDLE_VALUE)
6366 goto getout;
6367 (void)FindClose(hFile);
6368 }
6369 }
6370
6371 if (p & W_OK)
6372 {
6373 /* Trying to create a temporary file in the directory should catch
6374 * directories on read-only network shares. However, in
6375 * directories whose ACL allows writes but denies deletes will end
6376 * up keeping the temporary file :-(. */
6377#ifdef FEAT_MBYTE
6378 if (wn != NULL)
6379 {
6380 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
6381 {
6382 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
6383 goto getout;
6384
6385 /* Retry with non-wide function (for Windows 98). */
6386 vim_free(wn);
6387 wn = NULL;
6388 }
6389 else
6390 DeleteFileW(TempNameW);
6391 }
6392 if (wn == NULL)
6393#endif
6394 {
6395 if (!GetTempFileName(n, "VIM", 0, TempName))
6396 goto getout;
6397 mch_remove((char_u *)TempName);
6398 }
6399 }
6400 }
6401 else
6402 {
6403 /* Trying to open the file for the required access does ACL, read-only
6404 * network share, and file attribute checks. */
6405 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6406 | ((p & R_OK) ? GENERIC_READ : 0);
6407#ifdef FEAT_MBYTE
6408 if (wn != NULL)
6409 {
6410 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6411 if (hFile == INVALID_HANDLE_VALUE
6412 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
6413 {
6414 /* Retry with non-wide function (for Windows 98). */
6415 vim_free(wn);
6416 wn = NULL;
6417 }
6418 }
6419 if (wn == NULL)
6420#endif
6421 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6422 if (hFile == INVALID_HANDLE_VALUE)
6423 goto getout;
6424 CloseHandle(hFile);
6425 }
6426
6427 retval = 0; /* success */
6428getout:
6429#ifdef FEAT_MBYTE
6430 vim_free(wn);
6431#endif
6432 return retval;
6433}
6434
6435#if defined(FEAT_MBYTE) || defined(PROTO)
6436/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006437 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006438 */
6439 int
6440mch_open(char *name, int flags, int mode)
6441{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006442 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6443# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006444 WCHAR *wn;
6445 int f;
6446
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006447 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006448 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006449 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006450 if (wn != NULL)
6451 {
6452 f = _wopen(wn, flags, mode);
6453 vim_free(wn);
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006454 if (f >= 0 || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006455 return f;
6456 /* Retry with non-wide function (for Windows 98). Can't use
6457 * GetLastError() here and it's unclear what errno gets set to if
6458 * the _wopen() fails for missing wide functions. */
6459 }
6460 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006461# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006462
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006463 /* open() can open a file which name is longer than _MAX_PATH bytes
6464 * and shorter than _MAX_PATH characters successfully, but sometimes it
6465 * causes unexpected error in another part. We make it an error explicitly
6466 * here. */
6467 if (strlen(name) >= _MAX_PATH)
6468 return -1;
6469
Bram Moolenaar071d4272004-06-13 20:20:40 +00006470 return open(name, flags, mode);
6471}
6472
6473/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006474 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006475 */
6476 FILE *
6477mch_fopen(char *name, char *mode)
6478{
6479 WCHAR *wn, *wm;
6480 FILE *f = NULL;
6481
6482 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
6483# ifdef __BORLANDC__
6484 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
6485 && g_PlatformId == VER_PLATFORM_WIN32_NT
6486# endif
6487 )
6488 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006489# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006490 /* Work around an annoying assertion in the Microsoft debug CRT
6491 * when mode's text/binary setting doesn't match _get_fmode(). */
6492 char newMode = mode[strlen(mode) - 1];
6493 int oldMode = 0;
6494
6495 _get_fmode(&oldMode);
6496 if (newMode == 't')
6497 _set_fmode(_O_TEXT);
6498 else if (newMode == 'b')
6499 _set_fmode(_O_BINARY);
6500# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006501 wn = enc_to_utf16(name, NULL);
6502 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006503 if (wn != NULL && wm != NULL)
6504 f = _wfopen(wn, wm);
6505 vim_free(wn);
6506 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006507
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006508# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006509 _set_fmode(oldMode);
6510# endif
6511
Bram Moolenaarcd981f22014-02-11 17:06:00 +01006512 if (f != NULL || g_PlatformId == VER_PLATFORM_WIN32_NT)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006513 return f;
6514 /* Retry with non-wide function (for Windows 98). Can't use
6515 * GetLastError() here and it's unclear what errno gets set to if
6516 * the _wfopen() fails for missing wide functions. */
6517 }
6518
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006519 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6520 * and shorter than _MAX_PATH characters successfully, but sometimes it
6521 * causes unexpected error in another part. We make it an error explicitly
6522 * here. */
6523 if (strlen(name) >= _MAX_PATH)
6524 return NULL;
6525
Bram Moolenaar071d4272004-06-13 20:20:40 +00006526 return fopen(name, mode);
6527}
6528#endif
6529
6530#ifdef FEAT_MBYTE
6531/*
6532 * SUB STREAM (aka info stream) handling:
6533 *
6534 * NTFS can have sub streams for each file. Normal contents of file is
6535 * stored in the main stream, and extra contents (author information and
6536 * title and so on) can be stored in sub stream. After Windows 2000, user
6537 * can access and store those informations in sub streams via explorer's
6538 * property menuitem in right click menu. Those informations in sub streams
6539 * were lost when copying only the main stream. So we have to copy sub
6540 * streams.
6541 *
6542 * Incomplete explanation:
6543 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6544 * More useful info and an example:
6545 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6546 */
6547
6548/*
6549 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6550 * and write to stream "substream" of file "to".
6551 * Errors are ignored.
6552 */
6553 static void
6554copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6555{
6556 HANDLE hTo;
6557 WCHAR *to_name;
6558
6559 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6560 wcscpy(to_name, to);
6561 wcscat(to_name, substream);
6562
6563 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6564 FILE_ATTRIBUTE_NORMAL, NULL);
6565 if (hTo != INVALID_HANDLE_VALUE)
6566 {
6567 long done;
6568 DWORD todo;
6569 DWORD readcnt, written;
6570 char buf[4096];
6571
6572 /* Copy block of bytes at a time. Abort when something goes wrong. */
6573 for (done = 0; done < len; done += written)
6574 {
6575 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006576 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6577 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006578 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6579 FALSE, FALSE, context)
6580 || readcnt != todo
6581 || !WriteFile(hTo, buf, todo, &written, NULL)
6582 || written != todo)
6583 break;
6584 }
6585 CloseHandle(hTo);
6586 }
6587
6588 free(to_name);
6589}
6590
6591/*
6592 * Copy info streams from file "from" to file "to".
6593 */
6594 static void
6595copy_infostreams(char_u *from, char_u *to)
6596{
6597 WCHAR *fromw;
6598 WCHAR *tow;
6599 HANDLE sh;
6600 WIN32_STREAM_ID sid;
6601 int headersize;
6602 WCHAR streamname[_MAX_PATH];
6603 DWORD readcount;
6604 void *context = NULL;
6605 DWORD lo, hi;
6606 int len;
6607
6608 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006609 fromw = enc_to_utf16(from, NULL);
6610 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006611 if (fromw != NULL && tow != NULL)
6612 {
6613 /* Open the file for reading. */
6614 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6615 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6616 if (sh != INVALID_HANDLE_VALUE)
6617 {
6618 /* Use BackupRead() to find the info streams. Repeat until we
6619 * have done them all.*/
6620 for (;;)
6621 {
6622 /* Get the header to find the length of the stream name. If
6623 * the "readcount" is zero we have done all info streams. */
6624 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006625 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006626 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6627 &readcount, FALSE, FALSE, &context)
6628 || readcount == 0)
6629 break;
6630
6631 /* We only deal with streams that have a name. The normal
6632 * file data appears to be without a name, even though docs
6633 * suggest it is called "::$DATA". */
6634 if (sid.dwStreamNameSize > 0)
6635 {
6636 /* Read the stream name. */
6637 if (!BackupRead(sh, (LPBYTE)streamname,
6638 sid.dwStreamNameSize,
6639 &readcount, FALSE, FALSE, &context))
6640 break;
6641
6642 /* Copy an info stream with a name ":anything:$DATA".
6643 * Skip "::$DATA", it has no stream name (examples suggest
6644 * it might be used for the normal file contents).
6645 * Note that BackupRead() counts bytes, but the name is in
6646 * wide characters. */
6647 len = readcount / sizeof(WCHAR);
6648 streamname[len] = 0;
6649 if (len > 7 && wcsicmp(streamname + len - 6,
6650 L":$DATA") == 0)
6651 {
6652 streamname[len - 6] = 0;
6653 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006654 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006655 }
6656 }
6657
6658 /* Advance to the next stream. We might try seeking too far,
6659 * but BackupSeek() doesn't skip over stream borders, thus
6660 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006661 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 &lo, &hi, &context);
6663 }
6664
6665 /* Clear the context. */
6666 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6667
6668 CloseHandle(sh);
6669 }
6670 }
6671 vim_free(fromw);
6672 vim_free(tow);
6673}
6674#endif
6675
6676/*
6677 * Copy file attributes from file "from" to file "to".
6678 * For Windows NT and later we copy info streams.
6679 * Always returns zero, errors are ignored.
6680 */
6681 int
6682mch_copy_file_attribute(char_u *from, char_u *to)
6683{
6684#ifdef FEAT_MBYTE
6685 /* File streams only work on Windows NT and later. */
6686 PlatformId();
6687 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6688 copy_infostreams(from, to);
6689#endif
6690 return 0;
6691}
6692
6693#if defined(MYRESETSTKOFLW) || defined(PROTO)
6694/*
6695 * Recreate a destroyed stack guard page in win32.
6696 * Written by Benjamin Peterson.
6697 */
6698
6699/* These magic numbers are from the MS header files */
6700#define MIN_STACK_WIN9X 17
6701#define MIN_STACK_WINNT 2
6702
6703/*
6704 * This function does the same thing as _resetstkoflw(), which is only
6705 * available in DevStudio .net and later.
6706 * Returns 0 for failure, 1 for success.
6707 */
6708 int
6709myresetstkoflw(void)
6710{
6711 BYTE *pStackPtr;
6712 BYTE *pGuardPage;
6713 BYTE *pStackBase;
6714 BYTE *pLowestPossiblePage;
6715 MEMORY_BASIC_INFORMATION mbi;
6716 SYSTEM_INFO si;
6717 DWORD nPageSize;
6718 DWORD dummy;
6719
6720 /* This code will not work on win32s. */
6721 PlatformId();
6722 if (g_PlatformId == VER_PLATFORM_WIN32s)
6723 return 0;
6724
6725 /* We need to know the system page size. */
6726 GetSystemInfo(&si);
6727 nPageSize = si.dwPageSize;
6728
6729 /* ...and the current stack pointer */
6730 pStackPtr = (BYTE*)_alloca(1);
6731
6732 /* ...and the base of the stack. */
6733 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6734 return 0;
6735 pStackBase = (BYTE*)mbi.AllocationBase;
6736
6737 /* ...and the page thats min_stack_req pages away from stack base; this is
6738 * the lowest page we could use. */
6739 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6740 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6741
6742 /* On Win95, we want the next page down from the end of the stack. */
6743 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6744 {
6745 /* Find the page that's only 1 page down from the page that the stack
6746 * ptr is in. */
6747 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6748 / (DWORD)nPageSize) - 1));
6749 if (pGuardPage < pLowestPossiblePage)
6750 return 0;
6751
6752 /* Apply the noaccess attribute to the page -- there's no guard
6753 * attribute in win95-type OSes. */
6754 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6755 return 0;
6756 }
6757 else
6758 {
6759 /* On NT, however, we want the first committed page in the stack Start
6760 * at the stack base and move forward through memory until we find a
6761 * committed block. */
6762 BYTE *pBlock = pStackBase;
6763
Bram Moolenaara466c992005-07-09 21:03:22 +00006764 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006765 {
6766 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6767 return 0;
6768
6769 pBlock += mbi.RegionSize;
6770
6771 if (mbi.State & MEM_COMMIT)
6772 break;
6773 }
6774
6775 /* mbi now describes the first committed block in the stack. */
6776 if (mbi.Protect & PAGE_GUARD)
6777 return 1;
6778
6779 /* decide where the guard page should start */
6780 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6781 pGuardPage = pLowestPossiblePage;
6782 else
6783 pGuardPage = (BYTE*)mbi.BaseAddress;
6784
6785 /* allocate the guard page */
6786 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6787 return 0;
6788
6789 /* apply the guard attribute to the page */
6790 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6791 &dummy))
6792 return 0;
6793 }
6794
6795 return 1;
6796}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006797#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006799
6800#if defined(FEAT_MBYTE) || defined(PROTO)
6801/*
6802 * The command line arguments in UCS2
6803 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006804static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006805static LPWSTR *ArglistW = NULL;
6806static int global_argc = 0;
6807static char **global_argv;
6808
6809static int used_file_argc = 0; /* last argument in global_argv[] used
6810 for the argument list. */
6811static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6812 command line arguments added to
6813 the argument list */
6814static int used_file_count = 0; /* nr of entries in used_file_indexes */
6815static int used_file_literal = FALSE; /* take file names literally */
6816static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006817static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006818static int used_alist_count = 0;
6819
6820
6821/*
6822 * Get the command line arguments. Unicode version.
6823 * Returns argc. Zero when something fails.
6824 */
6825 int
6826get_cmd_argsW(char ***argvp)
6827{
6828 char **argv = NULL;
6829 int argc = 0;
6830 int i;
6831
Bram Moolenaar14993322014-09-09 12:25:33 +02006832 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006833 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6834 if (ArglistW != NULL)
6835 {
6836 argv = malloc((nArgsW + 1) * sizeof(char *));
6837 if (argv != NULL)
6838 {
6839 argc = nArgsW;
6840 argv[argc] = NULL;
6841 for (i = 0; i < argc; ++i)
6842 {
6843 int len;
6844
6845 /* Convert each Unicode argument to the current codepage. */
6846 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006847 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006848 (LPSTR *)&argv[i], &len, 0, 0);
6849 if (argv[i] == NULL)
6850 {
6851 /* Out of memory, clear everything. */
6852 while (i > 0)
6853 free(argv[--i]);
6854 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006855 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006856 argc = 0;
6857 }
6858 }
6859 }
6860 }
6861
6862 global_argc = argc;
6863 global_argv = argv;
6864 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02006865 {
6866 if (used_file_indexes != NULL)
6867 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006868 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02006869 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006870
6871 if (argvp != NULL)
6872 *argvp = argv;
6873 return argc;
6874}
6875
6876 void
6877free_cmd_argsW(void)
6878{
6879 if (ArglistW != NULL)
6880 {
6881 GlobalFree(ArglistW);
6882 ArglistW = NULL;
6883 }
6884}
6885
6886/*
6887 * Remember "name" is an argument that was added to the argument list.
6888 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6889 * is called.
6890 */
6891 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006892used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006893{
6894 int i;
6895
6896 if (used_file_indexes == NULL)
6897 return;
6898 for (i = used_file_argc + 1; i < global_argc; ++i)
6899 if (STRCMP(global_argv[i], name) == 0)
6900 {
6901 used_file_argc = i;
6902 used_file_indexes[used_file_count++] = i;
6903 break;
6904 }
6905 used_file_literal = literal;
6906 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006907 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006908}
6909
6910/*
6911 * Remember the length of the argument list as it was. If it changes then we
6912 * leave it alone when 'encoding' is set.
6913 */
6914 void
6915set_alist_count(void)
6916{
6917 used_alist_count = GARGCOUNT;
6918}
6919
6920/*
6921 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6922 * has been changed while starting up. Use the UCS-2 command line arguments
6923 * and convert them to 'encoding'.
6924 */
6925 void
6926fix_arg_enc(void)
6927{
6928 int i;
6929 int idx;
6930 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006931 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006932
6933 /* Safety checks:
6934 * - if argument count differs between the wide and non-wide argument
6935 * list, something must be wrong.
6936 * - the file name arguments must have been located.
6937 * - the length of the argument list wasn't changed by the user.
6938 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006939 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006940 || ArglistW == NULL
6941 || used_file_indexes == NULL
6942 || used_file_count == 0
6943 || used_alist_count != GARGCOUNT)
6944 return;
6945
Bram Moolenaar86b68352004-12-27 21:59:20 +00006946 /* Remember the buffer numbers for the arguments. */
6947 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6948 if (fnum_list == NULL)
6949 return; /* out of memory */
6950 for (i = 0; i < GARGCOUNT; ++i)
6951 fnum_list[i] = GARGLIST[i].ae_fnum;
6952
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006953 /* Clear the argument list. Make room for the new arguments. */
6954 alist_clear(&global_alist);
6955 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006956 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006957
6958 for (i = 0; i < used_file_count; ++i)
6959 {
6960 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006961 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006962 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006963 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006964#ifdef FEAT_DIFF
6965 /* When using diff mode may need to concatenate file name to
6966 * directory name. Just like it's done in main(). */
6967 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6968 && !mch_isdir(alist_name(&GARGLIST[0])))
6969 {
6970 char_u *r;
6971
6972 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6973 if (r != NULL)
6974 {
6975 vim_free(str);
6976 str = r;
6977 }
6978 }
6979#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006980 /* Re-use the old buffer by renaming it. When not using literal
6981 * names it's done by alist_expand() below. */
6982 if (used_file_literal)
6983 buf_set_name(fnum_list[i], str);
6984
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006985 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006986 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006987 }
6988
6989 if (!used_file_literal)
6990 {
6991 /* Now expand wildcards in the arguments. */
6992 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6993 * filename characters but are excluded from 'isfname' to make
6994 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6995 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006996 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006997 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6998 }
6999
7000 /* If wildcard expansion failed, we are editing the first file of the
7001 * arglist and there is no file name: Edit the first argument now. */
7002 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7003 {
7004 do_cmdline_cmd((char_u *)":rewind");
7005 if (GARGCOUNT == 1 && used_file_full_path)
7006 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7007 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007008
7009 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007010}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007011#endif