blob: 4013353cf3b74d6d75e11de2d58330abcd5d4c70 [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
Bram Moolenaar12b559e2013-06-12 22:41:37 +020081/*
82 * Reparse Point
83 */
84#ifndef FILE_ATTRIBUTE_REPARSE_POINT
85# define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400
86#endif
87#ifndef IO_REPARSE_TAG_SYMLINK
88# define IO_REPARSE_TAG_SYMLINK 0xA000000C
89#endif
90
Bram Moolenaar071d4272004-06-13 20:20:40 +000091/* Record all output and all keyboard & mouse input */
92/* #define MCH_WRITE_DUMP */
93
94#ifdef MCH_WRITE_DUMP
95FILE* fdDump = NULL;
96#endif
97
98/*
99 * When generating prototypes for Win32 on Unix, these lines make the syntax
100 * errors disappear. They do not need to be correct.
101 */
102#ifdef PROTO
103#define WINAPI
104#define WINBASEAPI
105typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000106typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000107typedef int ACCESS_MASK;
108typedef int BOOL;
109typedef int COLORREF;
110typedef int CONSOLE_CURSOR_INFO;
111typedef int COORD;
112typedef int DWORD;
113typedef int HANDLE;
114typedef int HDC;
115typedef int HFONT;
116typedef int HICON;
117typedef int HINSTANCE;
118typedef int HWND;
119typedef int INPUT_RECORD;
120typedef int KEY_EVENT_RECORD;
121typedef int LOGFONT;
122typedef int LPBOOL;
123typedef int LPCTSTR;
124typedef int LPDWORD;
125typedef int LPSTR;
126typedef int LPTSTR;
127typedef int LPVOID;
128typedef int MOUSE_EVENT_RECORD;
129typedef int PACL;
130typedef int PDWORD;
131typedef int PHANDLE;
132typedef int PRINTDLG;
133typedef int PSECURITY_DESCRIPTOR;
134typedef int PSID;
135typedef int SECURITY_INFORMATION;
136typedef int SHORT;
137typedef int SMALL_RECT;
138typedef int TEXTMETRIC;
139typedef int TOKEN_INFORMATION_CLASS;
140typedef int TRUSTEE;
141typedef int WORD;
142typedef int WCHAR;
143typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100144typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200145typedef int SE_OBJECT_TYPE;
146typedef int PSNSECINFO;
147typedef int PSNSECINFOW;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
150#ifndef FEAT_GUI_W32
151/* Undocumented API in kernel32.dll needed to work around dead key bug in
152 * console-mode applications in NT 4.0. If you switch keyboard layouts
153 * in a console app to a layout that includes dead keys and then hit a
154 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
155 * and Michael Dietrich for helping me figure out this workaround.
156 */
157
158/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
159#ifndef WINBASEAPI
160# define WINBASEAPI __stdcall
161#endif
162#if defined(__BORLANDC__)
163typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
164#else
165typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
166#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000167static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168#endif
169
170#if defined(__BORLANDC__)
171/* Strangely Borland uses a non-standard name. */
172# define wcsicmp(a, b) wcscmpi((a), (b))
173#endif
174
Bram Moolenaar82881492012-11-20 16:53:39 +0100175#ifndef PROTO
176
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200177/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200178#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100179LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200180BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
181BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
182BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
183#endif
184
Bram Moolenaar82881492012-11-20 16:53:39 +0100185#endif /* PROTO */
186
Bram Moolenaar071d4272004-06-13 20:20:40 +0000187#ifndef FEAT_GUI_W32
188/* Win32 Console handles for input and output */
189static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
190static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
191
192/* Win32 Screen buffer,coordinate,console I/O information */
193static SMALL_RECT g_srScrollRegion;
194static COORD g_coord; /* 0-based, but external coords are 1-based */
195
196/* The attribute of the screen when the editor was started */
197static WORD g_attrDefault = 7; /* lightgray text on black background */
198static WORD g_attrCurrent;
199
200static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
201static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
202static int g_fForceExit = FALSE; /* set when forcefully exiting */
203
204static void termcap_mode_start(void);
205static void termcap_mode_end(void);
206static void clear_chars(COORD coord, DWORD n);
207static void clear_screen(void);
208static void clear_to_end_of_display(void);
209static void clear_to_end_of_line(void);
210static void scroll(unsigned cLines);
211static void set_scroll_region(unsigned left, unsigned top,
212 unsigned right, unsigned bottom);
213static void insert_lines(unsigned cLines);
214static void delete_lines(unsigned cLines);
215static void gotoxy(unsigned x, unsigned y);
216static void normvideo(void);
217static void textattr(WORD wAttr);
218static void textcolor(WORD wAttr);
219static void textbackground(WORD wAttr);
220static void standout(void);
221static void standend(void);
222static void visual_bell(void);
223static void cursor_visible(BOOL fVisible);
224static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
225static char_u tgetch(int *pmodifiers, char_u *pch2);
226static void create_conin(void);
227static int s_cursor_visible = TRUE;
228static int did_create_conin = FALSE;
229#else
230static int s_dont_use_vimrun = TRUE;
231static int need_vimrun_warning = FALSE;
232static char *vimrun_path = "vimrun ";
233#endif
234
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200235static int win32_getattrs(char_u *name);
236static int win32_setattrs(char_u *name, int attrs);
237static int win32_set_archive(char_u *name);
238
Bram Moolenaar071d4272004-06-13 20:20:40 +0000239#ifndef FEAT_GUI_W32
240static int suppress_winsize = 1; /* don't fiddle with console */
241#endif
242
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200243static char_u *exe_path = NULL;
244
Bram Moolenaar071d4272004-06-13 20:20:40 +0000245 static void
246get_exe_name(void)
247{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100248 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
249 * as the maximum length that works (plus a NUL byte). */
250#define MAX_ENV_PATH_LEN 8192
251 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200252 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000253
254 if (exe_name == NULL)
255 {
256 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100257 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000258 if (*temp != NUL)
259 exe_name = FullName_save((char_u *)temp, FALSE);
260 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000261
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200262 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000263 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200264 exe_path = vim_strnsave(exe_name,
265 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200266 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000267 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200268 /* Append our starting directory to $PATH, so that when doing
269 * "!xxd" it's found in our starting directory. Needed because
270 * SearchPath() also looks there. */
271 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100272 if (p == NULL
273 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200274 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100275 if (p == NULL || *p == NUL)
276 temp[0] = NUL;
277 else
278 {
279 STRCPY(temp, p);
280 STRCAT(temp, ";");
281 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200282 STRCAT(temp, exe_path);
283 vim_setenv((char_u *)"PATH", temp);
284 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000285 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287}
288
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200289/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100290 * Unescape characters in "p" that appear in "escaped".
291 */
292 static void
293unescape_shellxquote(char_u *p, char_u *escaped)
294{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100295 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100296 int n;
297
298 while (*p != NUL)
299 {
300 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
301 mch_memmove(p, p + 1, l--);
302#ifdef FEAT_MBYTE
303 n = (*mb_ptr2len)(p);
304#else
305 n = 1;
306#endif
307 p += n;
308 l -= n;
309 }
310}
311
312/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200313 * Load library "name".
314 */
315 HINSTANCE
316vimLoadLib(char *name)
317{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200318 HINSTANCE dll = NULL;
319 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200320
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200321 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
322 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200323 if (exe_path == NULL)
324 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200325 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200326 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200327#ifdef FEAT_MBYTE
328 WCHAR old_dirw[MAXPATHL];
329
330 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
331 {
332 /* Change directory to where the executable is, both to make
333 * sure we find a .dll there and to avoid looking for a .dll
334 * in the current directory. */
335 SetCurrentDirectory(exe_path);
336 dll = LoadLibrary(name);
337 SetCurrentDirectoryW(old_dirw);
338 return dll;
339 }
340 /* Retry with non-wide function (for Windows 98). */
341 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
342#endif
343 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
344 {
345 /* Change directory to where the executable is, both to make
346 * sure we find a .dll there and to avoid looking for a .dll
347 * in the current directory. */
348 SetCurrentDirectory(exe_path);
349 dll = LoadLibrary(name);
350 SetCurrentDirectory(old_dir);
351 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200352 }
353 return dll;
354}
355
Bram Moolenaar071d4272004-06-13 20:20:40 +0000356#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
357# ifndef GETTEXT_DLL
358# define GETTEXT_DLL "libintl.dll"
359# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200360/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000361static char *null_libintl_gettext(const char *);
362static char *null_libintl_textdomain(const char *);
363static char *null_libintl_bindtextdomain(const char *, const char *);
364static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200366static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000367char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
368char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
369char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000370 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000371char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
372 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373
374 int
375dyn_libintl_init(char *libname)
376{
377 int i;
378 static struct
379 {
380 char *name;
381 FARPROC *ptr;
382 } libintl_entry[] =
383 {
384 {"gettext", (FARPROC*)&dyn_libintl_gettext},
385 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
386 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
387 {NULL, NULL}
388 };
389
390 /* No need to initialize twice. */
391 if (hLibintlDLL)
392 return 1;
393 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200394 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000395 if (!hLibintlDLL)
396 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200397 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200399 verbose_enter();
400 EMSG2(_(e_loadlib), GETTEXT_DLL);
401 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000402 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200403 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 }
405 for (i = 0; libintl_entry[i].name != NULL
406 && libintl_entry[i].ptr != NULL; ++i)
407 {
408 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
409 libintl_entry[i].name)) == NULL)
410 {
411 dyn_libintl_end();
412 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000413 {
414 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000415 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000416 verbose_leave();
417 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 return 0;
419 }
420 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000421
422 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000423 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000424 "bind_textdomain_codeset");
425 if (dyn_libintl_bind_textdomain_codeset == NULL)
426 dyn_libintl_bind_textdomain_codeset =
427 null_libintl_bind_textdomain_codeset;
428
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429 return 1;
430}
431
432 void
433dyn_libintl_end()
434{
435 if (hLibintlDLL)
436 FreeLibrary(hLibintlDLL);
437 hLibintlDLL = NULL;
438 dyn_libintl_gettext = null_libintl_gettext;
439 dyn_libintl_textdomain = null_libintl_textdomain;
440 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000441 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442}
443
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000444/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000446null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447{
448 return (char*)msgid;
449}
450
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000451/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000453null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000454{
455 return NULL;
456}
457
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000458/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000460null_libintl_bind_textdomain_codeset(const char *domainname,
461 const char *codeset)
462{
463 return NULL;
464}
465
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000466/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000467 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000468null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000469{
470 return NULL;
471}
472
473#endif /* DYNAMIC_GETTEXT */
474
475/* This symbol is not defined in older versions of the SDK or Visual C++ */
476
477#ifndef VER_PLATFORM_WIN32_WINDOWS
478# define VER_PLATFORM_WIN32_WINDOWS 1
479#endif
480
481DWORD g_PlatformId;
482
483#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100484# ifndef PROTO
485# include <aclapi.h>
486# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200487# ifndef PROTECTED_DACL_SECURITY_INFORMATION
488# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
489# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100490
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491/*
492 * These are needed to dynamically load the ADVAPI DLL, which is not
493 * implemented under Windows 95 (and causes VIM to crash)
494 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200495typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200497typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
499 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200500# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200501typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200502 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200503typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200504 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
505 PSECURITY_DESCRIPTOR *);
506# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507
508static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
509static PSNSECINFO pSetNamedSecurityInfo;
510static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200511# ifdef FEAT_MBYTE
512static PSNSECINFOW pSetNamedSecurityInfoW;
513static PGNSECINFOW pGetNamedSecurityInfoW;
514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515#endif
516
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200517typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
518
519static BOOL allowPiping = FALSE;
520static PSETHANDLEINFORMATION pSetHandleInformation;
521
Bram Moolenaar27515922013-06-29 15:36:26 +0200522#ifdef HAVE_ACL
523/*
524 * Enables or disables the specified privilege.
525 */
526 static BOOL
527win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
528{
529 BOOL bResult;
530 LUID luid;
531 HANDLE hToken;
532 TOKEN_PRIVILEGES tokenPrivileges;
533
534 if (!OpenProcessToken(GetCurrentProcess(),
535 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
536 return FALSE;
537
538 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
539 {
540 CloseHandle(hToken);
541 return FALSE;
542 }
543
544 tokenPrivileges.PrivilegeCount = 1;
545 tokenPrivileges.Privileges[0].Luid = luid;
546 tokenPrivileges.Privileges[0].Attributes = bEnable ?
547 SE_PRIVILEGE_ENABLED : 0;
548
549 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
550 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
551
552 CloseHandle(hToken);
553
554 return bResult && GetLastError() == ERROR_SUCCESS;
555}
556#endif
557
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558/*
559 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
560 * VER_PLATFORM_WIN32_WINDOWS (Win95).
561 */
562 void
563PlatformId(void)
564{
565 static int done = FALSE;
566
567 if (!done)
568 {
569 OSVERSIONINFO ovi;
570
571 ovi.dwOSVersionInfoSize = sizeof(ovi);
572 GetVersionEx(&ovi);
573
574 g_PlatformId = ovi.dwPlatformId;
575
576#ifdef HAVE_ACL
577 /*
578 * Load the ADVAPI runtime if we are on anything
579 * other than Windows 95
580 */
581 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
582 {
583 /*
584 * do this load. Problems: Doesn't unload at end of run (this is
585 * theoretically okay, since Windows should unload it when VIM
586 * terminates). Should we be using the 'mch_libcall' routines?
587 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
588 * time we verify security...
589 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200590 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591 if (advapi_lib != NULL)
592 {
593 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
594 "SetNamedSecurityInfoA");
595 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
596 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200597# ifdef FEAT_MBYTE
598 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
599 "SetNamedSecurityInfoW");
600 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
601 "GetNamedSecurityInfoW");
602# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200604 || pGetNamedSecurityInfo == NULL
605# ifdef FEAT_MBYTE
606 || pSetNamedSecurityInfoW == NULL
607 || pGetNamedSecurityInfoW == NULL
608# endif
609 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 {
611 /* If we can't get the function addresses, set advapi_lib
612 * to NULL so that we don't use them. */
613 FreeLibrary(advapi_lib);
614 advapi_lib = NULL;
615 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200616 /* Enable privilege for getting or setting SACLs. */
617 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618 }
619 }
620#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200621 /*
622 * If we are on windows NT, try to load the pipe functions, only
623 * available from Win2K.
624 */
625 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
626 {
627 HANDLE kernel32 = GetModuleHandle("kernel32");
628 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
629 kernel32, "SetHandleInformation");
630
631 allowPiping = pSetHandleInformation != NULL;
632 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633 done = TRUE;
634 }
635}
636
637/*
638 * Return TRUE when running on Windows 95 (or 98 or ME).
639 * Only to be used after mch_init().
640 */
641 int
642mch_windows95(void)
643{
644 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
645}
646
647#ifdef FEAT_GUI_W32
648/*
649 * Used to work around the "can't do synchronous spawn"
650 * problem on Win32s, without resorting to Universal Thunk.
651 */
652static int old_num_windows;
653static int num_windows;
654
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000655/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000656 static BOOL CALLBACK
657win32ssynch_cb(HWND hwnd, LPARAM lparam)
658{
659 num_windows++;
660 return TRUE;
661}
662#endif
663
664#ifndef FEAT_GUI_W32
665
666#define SHIFT (SHIFT_PRESSED)
667#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
668#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
669#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
670
671
672/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
673 * We map function keys to their ANSI terminal equivalents, as produced
674 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
675 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
676 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
677 * combinations of function/arrow/etc keys.
678 */
679
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000680static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681{
682 WORD wVirtKey;
683 BOOL fAnsiKey;
684 int chAlone;
685 int chShift;
686 int chCtrl;
687 int chAlt;
688} VirtKeyMap[] =
689{
690
691/* Key ANSI alone shift ctrl alt */
692 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
693
694 { VK_F1, TRUE, ';', 'T', '^', 'h', },
695 { VK_F2, TRUE, '<', 'U', '_', 'i', },
696 { VK_F3, TRUE, '=', 'V', '`', 'j', },
697 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
698 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
699 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
700 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
701 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
702 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
703 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
704 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
705 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
706
707 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
708 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
709 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
710 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
711 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
712 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
713 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
714 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
715 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
716 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
717
718 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
719
720#if 0
721 /* Most people don't have F13-F20, but what the hell... */
722 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
723 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
724 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
725 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
726 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
727 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
728 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
729 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
730#endif
731 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
732 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
733 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
734 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
735
736 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
737 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
738 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
739 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
740 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
741 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
742 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
743 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
744 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
745 /* Sorry, out of number space! <negri>*/
746 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
747
748};
749
750
751#ifdef _MSC_VER
752// The ToAscii bug destroys several registers. Need to turn off optimization
753// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000754# pragma warning(push)
755# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000756# pragma optimize("", off)
757#endif
758
759#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
760# define AChar AsciiChar
761#else
762# define AChar uChar.AsciiChar
763#endif
764
765/* The return code indicates key code size. */
766 static int
767#ifdef __BORLANDC__
768 __stdcall
769#endif
770win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000771 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772{
773 UINT uMods = pker->dwControlKeyState;
774 static int s_iIsDead = 0;
775 static WORD awAnsiCode[2];
776 static BYTE abKeystate[256];
777
778
779 if (s_iIsDead == 2)
780 {
781 pker->AChar = (CHAR) awAnsiCode[1];
782 s_iIsDead = 0;
783 return 1;
784 }
785
786 if (pker->AChar != 0)
787 return 1;
788
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200789 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790
791 // Should only be non-NULL on NT 4.0
792 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
793 {
794 CHAR szKLID[KL_NAMELENGTH];
795
796 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
797 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
798 }
799
800 /* Clear any pending dead keys */
801 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
802
803 if (uMods & SHIFT_PRESSED)
804 abKeystate[VK_SHIFT] = 0x80;
805 if (uMods & CAPSLOCK_ON)
806 abKeystate[VK_CAPITAL] = 1;
807
808 if ((uMods & ALT_GR) == ALT_GR)
809 {
810 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
811 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
812 }
813
814 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
815 abKeystate, awAnsiCode, 0);
816
817 if (s_iIsDead > 0)
818 pker->AChar = (CHAR) awAnsiCode[0];
819
820 return s_iIsDead;
821}
822
823#ifdef _MSC_VER
824/* MUST switch optimization on again here, otherwise a call to
825 * decode_key_event() may crash (e.g. when hitting caps-lock) */
826# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000827# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000828
829# if (_MSC_VER < 1100)
830/* MUST turn off global optimisation for this next function, or
831 * pressing ctrl-minus in insert mode crashes Vim when built with
832 * VC4.1. -- negri. */
833# pragma optimize("g", off)
834# endif
835#endif
836
837static BOOL g_fJustGotFocus = FALSE;
838
839/*
840 * Decode a KEY_EVENT into one or two keystrokes
841 */
842 static BOOL
843decode_key_event(
844 KEY_EVENT_RECORD *pker,
845 char_u *pch,
846 char_u *pch2,
847 int *pmodifiers,
848 BOOL fDoPost)
849{
850 int i;
851 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
852
853 *pch = *pch2 = NUL;
854 g_fJustGotFocus = FALSE;
855
856 /* ignore key up events */
857 if (!pker->bKeyDown)
858 return FALSE;
859
860 /* ignore some keystrokes */
861 switch (pker->wVirtualKeyCode)
862 {
863 /* modifiers */
864 case VK_SHIFT:
865 case VK_CONTROL:
866 case VK_MENU: /* Alt key */
867 return FALSE;
868
869 default:
870 break;
871 }
872
873 /* special cases */
874 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
875 {
876 /* Ctrl-6 is Ctrl-^ */
877 if (pker->wVirtualKeyCode == '6')
878 {
879 *pch = Ctrl_HAT;
880 return TRUE;
881 }
882 /* Ctrl-2 is Ctrl-@ */
883 else if (pker->wVirtualKeyCode == '2')
884 {
885 *pch = NUL;
886 return TRUE;
887 }
888 /* Ctrl-- is Ctrl-_ */
889 else if (pker->wVirtualKeyCode == 0xBD)
890 {
891 *pch = Ctrl__;
892 return TRUE;
893 }
894 }
895
896 /* Shift-TAB */
897 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
898 {
899 *pch = K_NUL;
900 *pch2 = '\017';
901 return TRUE;
902 }
903
904 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
905 {
906 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
907 {
908 if (nModifs == 0)
909 *pch = VirtKeyMap[i].chAlone;
910 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
911 *pch = VirtKeyMap[i].chShift;
912 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
913 *pch = VirtKeyMap[i].chCtrl;
914 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
915 *pch = VirtKeyMap[i].chAlt;
916
917 if (*pch != 0)
918 {
919 if (VirtKeyMap[i].fAnsiKey)
920 {
921 *pch2 = *pch;
922 *pch = K_NUL;
923 }
924
925 return TRUE;
926 }
927 }
928 }
929
930 i = win32_kbd_patch_key(pker);
931
932 if (i < 0)
933 *pch = NUL;
934 else
935 {
936 *pch = (i > 0) ? pker->AChar : NUL;
937
938 if (pmodifiers != NULL)
939 {
940 /* Pass on the ALT key as a modifier, but only when not combined
941 * with CTRL (which is ALTGR). */
942 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
943 *pmodifiers |= MOD_MASK_ALT;
944
945 /* Pass on SHIFT only for special keys, because we don't know when
946 * it's already included with the character. */
947 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
948 *pmodifiers |= MOD_MASK_SHIFT;
949
950 /* Pass on CTRL only for non-special keys, because we don't know
951 * when it's already included with the character. And not when
952 * combined with ALT (which is ALTGR). */
953 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
954 && *pch >= 0x20 && *pch < 0x80)
955 *pmodifiers |= MOD_MASK_CTRL;
956 }
957 }
958
959 return (*pch != NUL);
960}
961
962#ifdef _MSC_VER
963# pragma optimize("", on)
964#endif
965
966#endif /* FEAT_GUI_W32 */
967
968
969#ifdef FEAT_MOUSE
970
971/*
972 * For the GUI the mouse handling is in gui_w32.c.
973 */
974# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000975/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000977mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978{
979}
980# else
981static int g_fMouseAvail = FALSE; /* mouse present */
982static int g_fMouseActive = FALSE; /* mouse enabled */
983static int g_nMouseClick = -1; /* mouse status */
984static int g_xMouse; /* mouse x coordinate */
985static int g_yMouse; /* mouse y coordinate */
986
987/*
988 * Enable or disable mouse input
989 */
990 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000991mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992{
993 DWORD cmodein;
994
995 if (!g_fMouseAvail)
996 return;
997
998 g_fMouseActive = on;
999 GetConsoleMode(g_hConIn, &cmodein);
1000
1001 if (g_fMouseActive)
1002 cmodein |= ENABLE_MOUSE_INPUT;
1003 else
1004 cmodein &= ~ENABLE_MOUSE_INPUT;
1005
1006 SetConsoleMode(g_hConIn, cmodein);
1007}
1008
1009
1010/*
1011 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1012 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1013 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1014 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1015 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1016 * and we return the mouse position in g_xMouse and g_yMouse.
1017 *
1018 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1019 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1020 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1021 *
1022 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1023 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1024 *
1025 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1026 * moves, even if it stays within the same character cell. We ignore
1027 * all MOUSE_MOVED messages if the position hasn't really changed, and
1028 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1029 * we're only interested in MOUSE_DRAG).
1030 *
1031 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1032 * 2-button mouses by pressing the left & right buttons simultaneously.
1033 * In practice, it's almost impossible to click both at the same time,
1034 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1035 * in such cases, if the user is clicking quickly.
1036 */
1037 static BOOL
1038decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001039 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040{
1041 static int s_nOldButton = -1;
1042 static int s_nOldMouseClick = -1;
1043 static int s_xOldMouse = -1;
1044 static int s_yOldMouse = -1;
1045 static linenr_T s_old_topline = 0;
1046#ifdef FEAT_DIFF
1047 static int s_old_topfill = 0;
1048#endif
1049 static int s_cClicks = 1;
1050 static BOOL s_fReleased = TRUE;
1051 static DWORD s_dwLastClickTime = 0;
1052 static BOOL s_fNextIsMiddle = FALSE;
1053
1054 static DWORD cButtons = 0; /* number of buttons supported */
1055
1056 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1057 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1058 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1059 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1060
1061 int nButton;
1062
1063 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1064 cButtons = 2;
1065
1066 if (!g_fMouseAvail || !g_fMouseActive)
1067 {
1068 g_nMouseClick = -1;
1069 return FALSE;
1070 }
1071
1072 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1073 if (g_fJustGotFocus)
1074 {
1075 g_fJustGotFocus = FALSE;
1076 return FALSE;
1077 }
1078
1079 /* unprocessed mouse click? */
1080 if (g_nMouseClick != -1)
1081 return TRUE;
1082
1083 nButton = -1;
1084 g_xMouse = pmer->dwMousePosition.X;
1085 g_yMouse = pmer->dwMousePosition.Y;
1086
1087 if (pmer->dwEventFlags == MOUSE_MOVED)
1088 {
1089 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1090 * events even when the mouse moves only within a char cell.) */
1091 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1092 return FALSE;
1093 }
1094
1095 /* If no buttons are pressed... */
1096 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1097 {
1098 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1099 if (s_fReleased)
1100 return FALSE;
1101
1102 nButton = MOUSE_RELEASE;
1103 s_fReleased = TRUE;
1104 }
1105 else /* one or more buttons pressed */
1106 {
1107 /* on a 2-button mouse, hold down left and right buttons
1108 * simultaneously to get MIDDLE. */
1109
1110 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1111 {
1112 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1113
1114 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001115 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116 if (dwLR == LEFT || dwLR == RIGHT)
1117 {
1118 for (;;)
1119 {
1120 /* wait a short time for next input event */
1121 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1122 != WAIT_OBJECT_0)
1123 break;
1124 else
1125 {
1126 DWORD cRecords = 0;
1127 INPUT_RECORD ir;
1128 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1129
1130 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1131
1132 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1133 || !(pmer2->dwButtonState & LEFT_RIGHT))
1134 break;
1135 else
1136 {
1137 if (pmer2->dwEventFlags != MOUSE_MOVED)
1138 {
1139 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1140
1141 return decode_mouse_event(pmer2);
1142 }
1143 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1144 s_yOldMouse == pmer2->dwMousePosition.Y)
1145 {
1146 /* throw away spurious mouse move */
1147 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1148
1149 /* are there any more mouse events in queue? */
1150 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1151
1152 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1153 break;
1154 }
1155 else
1156 break;
1157 }
1158 }
1159 }
1160 }
1161 }
1162
1163 if (s_fNextIsMiddle)
1164 {
1165 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1166 ? MOUSE_DRAG : MOUSE_MIDDLE;
1167 s_fNextIsMiddle = FALSE;
1168 }
1169 else if (cButtons == 2 &&
1170 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1171 {
1172 nButton = MOUSE_MIDDLE;
1173
1174 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1175 {
1176 s_fNextIsMiddle = TRUE;
1177 nButton = MOUSE_RELEASE;
1178 }
1179 }
1180 else if ((pmer->dwButtonState & LEFT) == LEFT)
1181 nButton = MOUSE_LEFT;
1182 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1183 nButton = MOUSE_MIDDLE;
1184 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1185 nButton = MOUSE_RIGHT;
1186
1187 if (! s_fReleased && ! s_fNextIsMiddle
1188 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1189 return FALSE;
1190
1191 s_fReleased = s_fNextIsMiddle;
1192 }
1193
1194 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1195 {
1196 /* button pressed or released, without mouse moving */
1197 if (nButton != -1 && nButton != MOUSE_RELEASE)
1198 {
1199 DWORD dwCurrentTime = GetTickCount();
1200
1201 if (s_xOldMouse != g_xMouse
1202 || s_yOldMouse != g_yMouse
1203 || s_nOldButton != nButton
1204 || s_old_topline != curwin->w_topline
1205#ifdef FEAT_DIFF
1206 || s_old_topfill != curwin->w_topfill
1207#endif
1208 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1209 {
1210 s_cClicks = 1;
1211 }
1212 else if (++s_cClicks > 4)
1213 {
1214 s_cClicks = 1;
1215 }
1216
1217 s_dwLastClickTime = dwCurrentTime;
1218 }
1219 }
1220 else if (pmer->dwEventFlags == MOUSE_MOVED)
1221 {
1222 if (nButton != -1 && nButton != MOUSE_RELEASE)
1223 nButton = MOUSE_DRAG;
1224
1225 s_cClicks = 1;
1226 }
1227
1228 if (nButton == -1)
1229 return FALSE;
1230
1231 if (nButton != MOUSE_RELEASE)
1232 s_nOldButton = nButton;
1233
1234 g_nMouseClick = nButton;
1235
1236 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1237 g_nMouseClick |= MOUSE_SHIFT;
1238 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1239 g_nMouseClick |= MOUSE_CTRL;
1240 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1241 g_nMouseClick |= MOUSE_ALT;
1242
1243 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1244 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1245
1246 /* only pass on interesting (i.e., different) mouse events */
1247 if (s_xOldMouse == g_xMouse
1248 && s_yOldMouse == g_yMouse
1249 && s_nOldMouseClick == g_nMouseClick)
1250 {
1251 g_nMouseClick = -1;
1252 return FALSE;
1253 }
1254
1255 s_xOldMouse = g_xMouse;
1256 s_yOldMouse = g_yMouse;
1257 s_old_topline = curwin->w_topline;
1258#ifdef FEAT_DIFF
1259 s_old_topfill = curwin->w_topfill;
1260#endif
1261 s_nOldMouseClick = g_nMouseClick;
1262
1263 return TRUE;
1264}
1265
1266# endif /* FEAT_GUI_W32 */
1267#endif /* FEAT_MOUSE */
1268
1269
1270#ifdef MCH_CURSOR_SHAPE
1271/*
1272 * Set the shape of the cursor.
1273 * 'thickness' can be from 1 (thin) to 99 (block)
1274 */
1275 static void
1276mch_set_cursor_shape(int thickness)
1277{
1278 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1279 ConsoleCursorInfo.dwSize = thickness;
1280 ConsoleCursorInfo.bVisible = s_cursor_visible;
1281
1282 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1283 if (s_cursor_visible)
1284 SetConsoleCursorPosition(g_hConOut, g_coord);
1285}
1286
1287 void
1288mch_update_cursor(void)
1289{
1290 int idx;
1291 int thickness;
1292
1293 /*
1294 * How the cursor is drawn depends on the current mode.
1295 */
1296 idx = get_shape_idx(FALSE);
1297
1298 if (shape_table[idx].shape == SHAPE_BLOCK)
1299 thickness = 99; /* 100 doesn't work on W95 */
1300 else
1301 thickness = shape_table[idx].percentage;
1302 mch_set_cursor_shape(thickness);
1303}
1304#endif
1305
1306#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1307/*
1308 * Handle FOCUS_EVENT.
1309 */
1310 static void
1311handle_focus_event(INPUT_RECORD ir)
1312{
1313 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1314 ui_focus_change((int)g_fJustGotFocus);
1315}
1316
1317/*
1318 * Wait until console input from keyboard or mouse is available,
1319 * or the time is up.
1320 * Return TRUE if something is available FALSE if not.
1321 */
1322 static int
1323WaitForChar(long msec)
1324{
1325 DWORD dwNow = 0, dwEndTime = 0;
1326 INPUT_RECORD ir;
1327 DWORD cRecords;
1328 char_u ch, ch2;
1329
1330 if (msec > 0)
1331 /* Wait until the specified time has elapsed. */
1332 dwEndTime = GetTickCount() + msec;
1333 else if (msec < 0)
1334 /* Wait forever. */
1335 dwEndTime = INFINITE;
1336
1337 /* We need to loop until the end of the time period, because
1338 * we might get multiple unusable mouse events in that time.
1339 */
1340 for (;;)
1341 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001342#ifdef FEAT_MZSCHEME
1343 mzvim_check_threads();
1344#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345#ifdef FEAT_CLIENTSERVER
1346 serverProcessPendingMessages();
1347#endif
1348 if (0
1349#ifdef FEAT_MOUSE
1350 || g_nMouseClick != -1
1351#endif
1352#ifdef FEAT_CLIENTSERVER
1353 || input_available()
1354#endif
1355 )
1356 return TRUE;
1357
1358 if (msec > 0)
1359 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001360 /* If the specified wait time has passed, return. Beware that
1361 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001363 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 break;
1365 }
1366 if (msec != 0)
1367 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001368 DWORD dwWaitTime = dwEndTime - dwNow;
1369
1370#ifdef FEAT_MZSCHEME
1371 if (mzthreads_allowed() && p_mzq > 0
1372 && (msec < 0 || (long)dwWaitTime > p_mzq))
1373 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1374#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001375#ifdef FEAT_CLIENTSERVER
1376 /* Wait for either an event on the console input or a message in
1377 * the client-server window. */
1378 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001379 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001380#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001381 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001382#endif
1383 continue;
1384 }
1385
1386 cRecords = 0;
1387 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1388
1389#ifdef FEAT_MBYTE_IME
1390 if (State & CMDLINE && msg_row == Rows - 1)
1391 {
1392 CONSOLE_SCREEN_BUFFER_INFO csbi;
1393
1394 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1395 {
1396 if (csbi.dwCursorPosition.Y != msg_row)
1397 {
1398 /* The screen is now messed up, must redraw the
1399 * command line and later all the windows. */
1400 redraw_all_later(CLEAR);
1401 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1402 redrawcmd();
1403 }
1404 }
1405 }
1406#endif
1407
1408 if (cRecords > 0)
1409 {
1410 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1411 {
1412#ifdef FEAT_MBYTE_IME
1413 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1414 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1415 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1416 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1417 {
1418 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1419 continue;
1420 }
1421#endif
1422 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1423 NULL, FALSE))
1424 return TRUE;
1425 }
1426
1427 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1428
1429 if (ir.EventType == FOCUS_EVENT)
1430 handle_focus_event(ir);
1431 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1432 shell_resized();
1433#ifdef FEAT_MOUSE
1434 else if (ir.EventType == MOUSE_EVENT
1435 && decode_mouse_event(&ir.Event.MouseEvent))
1436 return TRUE;
1437#endif
1438 }
1439 else if (msec == 0)
1440 break;
1441 }
1442
1443#ifdef FEAT_CLIENTSERVER
1444 /* Something might have been received while we were waiting. */
1445 if (input_available())
1446 return TRUE;
1447#endif
1448 return FALSE;
1449}
1450
1451#ifndef FEAT_GUI_MSWIN
1452/*
1453 * return non-zero if a character is available
1454 */
1455 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001456mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457{
1458 return WaitForChar(0L);
1459}
1460#endif
1461
1462/*
1463 * Create the console input. Used when reading stdin doesn't work.
1464 */
1465 static void
1466create_conin(void)
1467{
1468 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1469 FILE_SHARE_READ|FILE_SHARE_WRITE,
1470 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001471 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 did_create_conin = TRUE;
1473}
1474
1475/*
1476 * Get a keystroke or a mouse event
1477 */
1478 static char_u
1479tgetch(int *pmodifiers, char_u *pch2)
1480{
1481 char_u ch;
1482
1483 for (;;)
1484 {
1485 INPUT_RECORD ir;
1486 DWORD cRecords = 0;
1487
1488#ifdef FEAT_CLIENTSERVER
1489 (void)WaitForChar(-1L);
1490 if (input_available())
1491 return 0;
1492# ifdef FEAT_MOUSE
1493 if (g_nMouseClick != -1)
1494 return 0;
1495# endif
1496#endif
1497 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1498 {
1499 if (did_create_conin)
1500 read_error_exit();
1501 create_conin();
1502 continue;
1503 }
1504
1505 if (ir.EventType == KEY_EVENT)
1506 {
1507 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1508 pmodifiers, TRUE))
1509 return ch;
1510 }
1511 else if (ir.EventType == FOCUS_EVENT)
1512 handle_focus_event(ir);
1513 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1514 shell_resized();
1515#ifdef FEAT_MOUSE
1516 else if (ir.EventType == MOUSE_EVENT)
1517 {
1518 if (decode_mouse_event(&ir.Event.MouseEvent))
1519 return 0;
1520 }
1521#endif
1522 }
1523}
1524#endif /* !FEAT_GUI_W32 */
1525
1526
1527/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001528 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529 * Get one or more characters from the keyboard or the mouse.
1530 * If time == 0, do not wait for characters.
1531 * If time == n, wait a short time for characters.
1532 * If time == -1, wait forever for characters.
1533 * Returns the number of characters read into buf.
1534 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001535/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536 int
1537mch_inchar(
1538 char_u *buf,
1539 int maxlen,
1540 long time,
1541 int tb_change_cnt)
1542{
1543#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1544
1545 int len;
1546 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547#define TYPEAHEADLEN 20
1548 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1549 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001550#ifdef FEAT_MBYTE
1551 static char_u *rest = NULL; /* unconverted rest of previous read */
1552 static int restlen = 0;
1553 int unconverted;
1554#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555
1556 /* First use any typeahead that was kept because "buf" was too small. */
1557 if (typeaheadlen > 0)
1558 goto theend;
1559
1560#ifdef FEAT_SNIFF
1561 if (want_sniff_request)
1562 {
1563 if (sniff_request_waiting)
1564 {
1565 /* return K_SNIFF */
1566 typeahead[typeaheadlen++] = CSI;
1567 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1568 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1569 sniff_request_waiting = 0;
1570 want_sniff_request = 0;
1571 goto theend;
1572 }
1573 else if (time < 0 || time > 250)
1574 {
1575 /* don't wait too long, a request might be pending */
1576 time = 250;
1577 }
1578 }
1579#endif
1580
1581 if (time >= 0)
1582 {
1583 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585 }
1586 else /* time == -1, wait forever */
1587 {
1588 mch_set_winsize_now(); /* Allow winsize changes from now on */
1589
Bram Moolenaar3918c952005-03-15 22:34:55 +00001590 /*
1591 * If there is no character available within 2 seconds (default)
1592 * write the autoscript file to disk. Or cause the CursorHold event
1593 * to be triggered.
1594 */
1595 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596 {
1597#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001598 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001600 buf[0] = K_SPECIAL;
1601 buf[1] = KS_EXTRA;
1602 buf[2] = (int)KE_CURSORHOLD;
1603 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 }
1605#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001606 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 }
1608 }
1609
1610 /*
1611 * Try to read as many characters as there are, until the buffer is full.
1612 */
1613
1614 /* we will get at least one key. Get more if they are available. */
1615 g_fCBrkPressed = FALSE;
1616
1617#ifdef MCH_WRITE_DUMP
1618 if (fdDump)
1619 fputc('[', fdDump);
1620#endif
1621
1622 /* Keep looping until there is something in the typeahead buffer and more
1623 * to get and still room in the buffer (up to two bytes for a char and
1624 * three bytes for a modifier). */
1625 while ((typeaheadlen == 0 || WaitForChar(0L))
1626 && typeaheadlen + 5 <= TYPEAHEADLEN)
1627 {
1628 if (typebuf_changed(tb_change_cnt))
1629 {
1630 /* "buf" may be invalid now if a client put something in the
1631 * typeahead buffer and "buf" is in the typeahead buffer. */
1632 typeaheadlen = 0;
1633 break;
1634 }
1635#ifdef FEAT_MOUSE
1636 if (g_nMouseClick != -1)
1637 {
1638# ifdef MCH_WRITE_DUMP
1639 if (fdDump)
1640 fprintf(fdDump, "{%02x @ %d, %d}",
1641 g_nMouseClick, g_xMouse, g_yMouse);
1642# endif
1643 typeahead[typeaheadlen++] = ESC + 128;
1644 typeahead[typeaheadlen++] = 'M';
1645 typeahead[typeaheadlen++] = g_nMouseClick;
1646 typeahead[typeaheadlen++] = g_xMouse + '!';
1647 typeahead[typeaheadlen++] = g_yMouse + '!';
1648 g_nMouseClick = -1;
1649 }
1650 else
1651#endif
1652 {
1653 char_u ch2 = NUL;
1654 int modifiers = 0;
1655
1656 c = tgetch(&modifiers, &ch2);
1657
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001658#ifdef FEAT_MBYTE
1659 /* stolen from fill_input_buf() in ui.c */
1660 if (rest != NULL)
1661 {
1662 /* Use remainder of previous call, starts with an invalid
1663 * character that may become valid when reading more. */
1664 if (restlen > TYPEAHEADLEN - typeaheadlen)
1665 unconverted = TYPEAHEADLEN - typeaheadlen;
1666 else
1667 unconverted = restlen;
1668 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1669 if (unconverted == restlen)
1670 {
1671 vim_free(rest);
1672 rest = NULL;
1673 }
1674 else
1675 {
1676 restlen -= unconverted;
1677 mch_memmove(rest, rest + unconverted, restlen);
1678 }
1679 typeaheadlen += unconverted;
1680 }
1681 else
1682 unconverted = 0;
1683#endif
1684
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685 if (typebuf_changed(tb_change_cnt))
1686 {
1687 /* "buf" may be invalid now if a client put something in the
1688 * typeahead buffer and "buf" is in the typeahead buffer. */
1689 typeaheadlen = 0;
1690 break;
1691 }
1692
1693 if (c == Ctrl_C && ctrl_c_interrupts)
1694 {
1695#if defined(FEAT_CLIENTSERVER)
1696 trash_input_buf();
1697#endif
1698 got_int = TRUE;
1699 }
1700
1701#ifdef FEAT_MOUSE
1702 if (g_nMouseClick == -1)
1703#endif
1704 {
1705 int n = 1;
1706
1707 /* A key may have one or two bytes. */
1708 typeahead[typeaheadlen] = c;
1709 if (ch2 != NUL)
1710 {
1711 typeahead[typeaheadlen + 1] = ch2;
1712 ++n;
1713 }
1714#ifdef FEAT_MBYTE
1715 /* Only convert normal characters, not special keys. Need to
1716 * convert before applying ALT, otherwise mapping <M-x> breaks
1717 * when 'tenc' is set. */
1718 if (input_conv.vc_type != CONV_NONE
1719 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001720 {
1721 typeaheadlen -= unconverted;
1722 n = convert_input_safe(typeahead + typeaheadlen,
1723 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1724 rest == NULL ? &rest : NULL, &restlen);
1725 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726#endif
1727
1728 /* Use the ALT key to set the 8th bit of the character
1729 * when it's one byte, the 8th bit isn't set yet and not
1730 * using a double-byte encoding (would become a lead
1731 * byte). */
1732 if ((modifiers & MOD_MASK_ALT)
1733 && n == 1
1734 && (typeahead[typeaheadlen] & 0x80) == 0
1735#ifdef FEAT_MBYTE
1736 && !enc_dbcs
1737#endif
1738 )
1739 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001740#ifdef FEAT_MBYTE
1741 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1742 typeahead + typeaheadlen);
1743#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001745#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 modifiers &= ~MOD_MASK_ALT;
1747 }
1748
1749 if (modifiers != 0)
1750 {
1751 /* Prepend modifiers to the character. */
1752 mch_memmove(typeahead + typeaheadlen + 3,
1753 typeahead + typeaheadlen, n);
1754 typeahead[typeaheadlen++] = K_SPECIAL;
1755 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1756 typeahead[typeaheadlen++] = modifiers;
1757 }
1758
1759 typeaheadlen += n;
1760
1761#ifdef MCH_WRITE_DUMP
1762 if (fdDump)
1763 fputc(c, fdDump);
1764#endif
1765 }
1766 }
1767 }
1768
1769#ifdef MCH_WRITE_DUMP
1770 if (fdDump)
1771 {
1772 fputs("]\n", fdDump);
1773 fflush(fdDump);
1774 }
1775#endif
1776
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777theend:
1778 /* Move typeahead to "buf", as much as fits. */
1779 len = 0;
1780 while (len < maxlen && typeaheadlen > 0)
1781 {
1782 buf[len++] = typeahead[0];
1783 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1784 }
1785 return len;
1786
1787#else /* FEAT_GUI_W32 */
1788 return 0;
1789#endif /* FEAT_GUI_W32 */
1790}
1791
Bram Moolenaar82881492012-11-20 16:53:39 +01001792#ifndef PROTO
1793# ifndef __MINGW32__
1794# include <shellapi.h> /* required for FindExecutable() */
1795# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796#endif
1797
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001798/*
1799 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001800 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001801 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 static int
1803executable_exists(char *name)
1804{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001805 char *dum;
1806 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001808#ifdef FEAT_MBYTE
1809 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001811 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001812 WCHAR fnamew[_MAX_PATH];
1813 WCHAR *dumw;
1814 long n;
1815
1816 if (p != NULL)
1817 {
1818 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1819 vim_free(p);
1820 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1821 {
1822 if (n == 0)
1823 return FALSE;
1824 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1825 return FALSE;
1826 return TRUE;
1827 }
1828 /* Retry with non-wide function (for Windows 98). */
1829 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001831#endif
1832 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1833 return FALSE;
1834 if (mch_isdir(fname))
1835 return FALSE;
1836 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837}
1838
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001839#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001840 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001841/*
1842 * Bad parameter handler.
1843 *
1844 * Certain MS CRT functions will intentionally crash when passed invalid
1845 * parameters to highlight possible security holes. Setting this function as
1846 * the bad parameter handler will prevent the crash.
1847 *
1848 * In debug builds the parameters contain CRT information that might help track
1849 * down the source of a problem, but in non-debug builds the arguments are all
1850 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1851 * worth allowing these to make debugging of issues easier.
1852 */
1853 static void
1854bad_param_handler(const wchar_t *expression,
1855 const wchar_t *function,
1856 const wchar_t *file,
1857 unsigned int line,
1858 uintptr_t pReserved)
1859{
1860}
1861
1862# define SET_INVALID_PARAM_HANDLER \
1863 ((void)_set_invalid_parameter_handler(bad_param_handler))
1864#else
1865# define SET_INVALID_PARAM_HANDLER
1866#endif
1867
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868#ifdef FEAT_GUI_W32
1869
1870/*
1871 * GUI version of mch_init().
1872 */
1873 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001874mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875{
1876#ifndef __MINGW32__
1877 extern int _fmode;
1878#endif
1879
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001880 /* Silently handle invalid parameters to CRT functions */
1881 SET_INVALID_PARAM_HANDLER;
1882
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 /* Let critical errors result in a failure, not in a dialog box. Required
1884 * for the timestamp test to work on removed floppies. */
1885 SetErrorMode(SEM_FAILCRITICALERRORS);
1886
1887 _fmode = O_BINARY; /* we do our own CR-LF translation */
1888
1889 /* Specify window size. Is there a place to get the default from? */
1890 Rows = 25;
1891 Columns = 80;
1892
1893 /* Look for 'vimrun' */
1894 if (!gui_is_win32s())
1895 {
1896 char_u vimrun_location[_MAX_PATH + 4];
1897
1898 /* First try in same directory as gvim.exe */
1899 STRCPY(vimrun_location, exe_name);
1900 STRCPY(gettail(vimrun_location), "vimrun.exe");
1901 if (mch_getperm(vimrun_location) >= 0)
1902 {
1903 if (*skiptowhite(vimrun_location) != NUL)
1904 {
1905 /* Enclose path with white space in double quotes. */
1906 mch_memmove(vimrun_location + 1, vimrun_location,
1907 STRLEN(vimrun_location) + 1);
1908 *vimrun_location = '"';
1909 STRCPY(gettail(vimrun_location), "vimrun\" ");
1910 }
1911 else
1912 STRCPY(gettail(vimrun_location), "vimrun ");
1913
1914 vimrun_path = (char *)vim_strsave(vimrun_location);
1915 s_dont_use_vimrun = FALSE;
1916 }
1917 else if (executable_exists("vimrun.exe"))
1918 s_dont_use_vimrun = FALSE;
1919
1920 /* Don't give the warning for a missing vimrun.exe right now, but only
1921 * when vimrun was supposed to be used. Don't bother people that do
1922 * not need vimrun.exe. */
1923 if (s_dont_use_vimrun)
1924 need_vimrun_warning = TRUE;
1925 }
1926
1927 /*
1928 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1929 * Otherwise the default "findstr /n" is used.
1930 */
1931 if (!executable_exists("findstr.exe"))
1932 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1933
1934#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001935 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936#endif
1937}
1938
1939
1940#else /* FEAT_GUI_W32 */
1941
1942#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1943#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1944
1945/*
1946 * ClearConsoleBuffer()
1947 * Description:
1948 * Clears the entire contents of the console screen buffer, using the
1949 * specified attribute.
1950 * Returns:
1951 * TRUE on success
1952 */
1953 static BOOL
1954ClearConsoleBuffer(WORD wAttribute)
1955{
1956 CONSOLE_SCREEN_BUFFER_INFO csbi;
1957 COORD coord;
1958 DWORD NumCells, dummy;
1959
1960 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1961 return FALSE;
1962
1963 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1964 coord.X = 0;
1965 coord.Y = 0;
1966 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1967 coord, &dummy))
1968 {
1969 return FALSE;
1970 }
1971 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1972 coord, &dummy))
1973 {
1974 return FALSE;
1975 }
1976
1977 return TRUE;
1978}
1979
1980/*
1981 * FitConsoleWindow()
1982 * Description:
1983 * Checks if the console window will fit within given buffer dimensions.
1984 * Also, if requested, will shrink the window to fit.
1985 * Returns:
1986 * TRUE on success
1987 */
1988 static BOOL
1989FitConsoleWindow(
1990 COORD dwBufferSize,
1991 BOOL WantAdjust)
1992{
1993 CONSOLE_SCREEN_BUFFER_INFO csbi;
1994 COORD dwWindowSize;
1995 BOOL NeedAdjust = FALSE;
1996
1997 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1998 {
1999 /*
2000 * A buffer resize will fail if the current console window does
2001 * not lie completely within that buffer. To avoid this, we might
2002 * have to move and possibly shrink the window.
2003 */
2004 if (csbi.srWindow.Right >= dwBufferSize.X)
2005 {
2006 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2007 if (dwWindowSize.X > dwBufferSize.X)
2008 dwWindowSize.X = dwBufferSize.X;
2009 csbi.srWindow.Right = dwBufferSize.X - 1;
2010 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2011 NeedAdjust = TRUE;
2012 }
2013 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2014 {
2015 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2016 if (dwWindowSize.Y > dwBufferSize.Y)
2017 dwWindowSize.Y = dwBufferSize.Y;
2018 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2019 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2020 NeedAdjust = TRUE;
2021 }
2022 if (NeedAdjust && WantAdjust)
2023 {
2024 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2025 return FALSE;
2026 }
2027 return TRUE;
2028 }
2029
2030 return FALSE;
2031}
2032
2033typedef struct ConsoleBufferStruct
2034{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002035 BOOL IsValid;
2036 CONSOLE_SCREEN_BUFFER_INFO Info;
2037 PCHAR_INFO Buffer;
2038 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039} ConsoleBuffer;
2040
2041/*
2042 * SaveConsoleBuffer()
2043 * Description:
2044 * Saves important information about the console buffer, including the
2045 * actual buffer contents. The saved information is suitable for later
2046 * restoration by RestoreConsoleBuffer().
2047 * Returns:
2048 * TRUE if all information was saved; FALSE otherwise
2049 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2050 */
2051 static BOOL
2052SaveConsoleBuffer(
2053 ConsoleBuffer *cb)
2054{
2055 DWORD NumCells;
2056 COORD BufferCoord;
2057 SMALL_RECT ReadRegion;
2058 WORD Y, Y_incr;
2059
2060 if (cb == NULL)
2061 return FALSE;
2062
2063 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2064 {
2065 cb->IsValid = FALSE;
2066 return FALSE;
2067 }
2068 cb->IsValid = TRUE;
2069
2070 /*
2071 * Allocate a buffer large enough to hold the entire console screen
2072 * buffer. If this ConsoleBuffer structure has already been initialized
2073 * with a buffer of the correct size, then just use that one.
2074 */
2075 if (!cb->IsValid || cb->Buffer == NULL ||
2076 cb->BufferSize.X != cb->Info.dwSize.X ||
2077 cb->BufferSize.Y != cb->Info.dwSize.Y)
2078 {
2079 cb->BufferSize.X = cb->Info.dwSize.X;
2080 cb->BufferSize.Y = cb->Info.dwSize.Y;
2081 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002082 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2084 if (cb->Buffer == NULL)
2085 return FALSE;
2086 }
2087
2088 /*
2089 * We will now copy the console screen buffer into our buffer.
2090 * ReadConsoleOutput() seems to be limited as far as how much you
2091 * can read at a time. Empirically, this number seems to be about
2092 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2093 * in chunks until it is all copied. The chunks will all have the
2094 * same horizontal characteristics, so initialize them now. The
2095 * height of each chunk will be (12000 / width).
2096 */
2097 BufferCoord.X = 0;
2098 ReadRegion.Left = 0;
2099 ReadRegion.Right = cb->Info.dwSize.X - 1;
2100 Y_incr = 12000 / cb->Info.dwSize.X;
2101 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2102 {
2103 /*
2104 * Read into position (0, Y) in our buffer.
2105 */
2106 BufferCoord.Y = Y;
2107 /*
2108 * Read the region whose top left corner is (0, Y) and whose bottom
2109 * right corner is (width - 1, Y + Y_incr - 1). This should define
2110 * a region of size width by Y_incr. Don't worry if this region is
2111 * too large for the remaining buffer; it will be cropped.
2112 */
2113 ReadRegion.Top = Y;
2114 ReadRegion.Bottom = Y + Y_incr - 1;
2115 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2116 cb->Buffer, /* our buffer */
2117 cb->BufferSize, /* dimensions of our buffer */
2118 BufferCoord, /* offset in our buffer */
2119 &ReadRegion)) /* region to save */
2120 {
2121 vim_free(cb->Buffer);
2122 cb->Buffer = NULL;
2123 return FALSE;
2124 }
2125 }
2126
2127 return TRUE;
2128}
2129
2130/*
2131 * RestoreConsoleBuffer()
2132 * Description:
2133 * Restores important information about the console buffer, including the
2134 * actual buffer contents, if desired. The information to restore is in
2135 * the same format used by SaveConsoleBuffer().
2136 * Returns:
2137 * TRUE on success
2138 */
2139 static BOOL
2140RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002141 ConsoleBuffer *cb,
2142 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002143{
2144 COORD BufferCoord;
2145 SMALL_RECT WriteRegion;
2146
2147 if (cb == NULL || !cb->IsValid)
2148 return FALSE;
2149
2150 /*
2151 * Before restoring the buffer contents, clear the current buffer, and
2152 * restore the cursor position and window information. Doing this now
2153 * prevents old buffer contents from "flashing" onto the screen.
2154 */
2155 if (RestoreScreen)
2156 ClearConsoleBuffer(cb->Info.wAttributes);
2157
2158 FitConsoleWindow(cb->Info.dwSize, TRUE);
2159 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2160 return FALSE;
2161 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2162 return FALSE;
2163
2164 if (!RestoreScreen)
2165 {
2166 /*
2167 * No need to restore the screen buffer contents, so we're done.
2168 */
2169 return TRUE;
2170 }
2171
2172 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2173 return FALSE;
2174 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2175 return FALSE;
2176
2177 /*
2178 * Restore the screen buffer contents.
2179 */
2180 if (cb->Buffer != NULL)
2181 {
2182 BufferCoord.X = 0;
2183 BufferCoord.Y = 0;
2184 WriteRegion.Left = 0;
2185 WriteRegion.Top = 0;
2186 WriteRegion.Right = cb->Info.dwSize.X - 1;
2187 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2188 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2189 cb->Buffer, /* our buffer */
2190 cb->BufferSize, /* dimensions of our buffer */
2191 BufferCoord, /* offset in our buffer */
2192 &WriteRegion)) /* region to restore */
2193 {
2194 return FALSE;
2195 }
2196 }
2197
2198 return TRUE;
2199}
2200
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002201#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202#ifdef FEAT_RESTORE_ORIG_SCREEN
2203static ConsoleBuffer g_cbOrig = { 0 };
2204#endif
2205static ConsoleBuffer g_cbNonTermcap = { 0 };
2206static ConsoleBuffer g_cbTermcap = { 0 };
2207
2208#ifdef FEAT_TITLE
2209#ifdef __BORLANDC__
2210typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2211#else
2212typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2213#endif
2214char g_szOrigTitle[256] = { 0 };
2215HWND g_hWnd = NULL; /* also used in os_mswin.c */
2216static HICON g_hOrigIconSmall = NULL;
2217static HICON g_hOrigIcon = NULL;
2218static HICON g_hVimIcon = NULL;
2219static BOOL g_fCanChangeIcon = FALSE;
2220
2221/* ICON* are not defined in VC++ 4.0 */
2222#ifndef ICON_SMALL
2223#define ICON_SMALL 0
2224#endif
2225#ifndef ICON_BIG
2226#define ICON_BIG 1
2227#endif
2228/*
2229 * GetConsoleIcon()
2230 * Description:
2231 * Attempts to retrieve the small icon and/or the big icon currently in
2232 * use by a given window.
2233 * Returns:
2234 * TRUE on success
2235 */
2236 static BOOL
2237GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002238 HWND hWnd,
2239 HICON *phIconSmall,
2240 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002241{
2242 if (hWnd == NULL)
2243 return FALSE;
2244
2245 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002246 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2247 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002248 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002249 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2250 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 return TRUE;
2252}
2253
2254/*
2255 * SetConsoleIcon()
2256 * Description:
2257 * Attempts to change the small icon and/or the big icon currently in
2258 * use by a given window.
2259 * Returns:
2260 * TRUE on success
2261 */
2262 static BOOL
2263SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002264 HWND hWnd,
2265 HICON hIconSmall,
2266 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002267{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002268 HICON hPrevIconSmall;
2269 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270
2271 if (hWnd == NULL)
2272 return FALSE;
2273
2274 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002275 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2276 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002278 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2279 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280 return TRUE;
2281}
2282
2283/*
2284 * SaveConsoleTitleAndIcon()
2285 * Description:
2286 * Saves the current console window title in g_szOrigTitle, for later
2287 * restoration. Also, attempts to obtain a handle to the console window,
2288 * and use it to save the small and big icons currently in use by the
2289 * console window. This is not always possible on some versions of Windows;
2290 * nor is it possible when running Vim remotely using Telnet (since the
2291 * console window the user sees is owned by a remote process).
2292 */
2293 static void
2294SaveConsoleTitleAndIcon(void)
2295{
2296 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2297
2298 /* Save the original title. */
2299 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2300 return;
2301
2302 /*
2303 * Obtain a handle to the console window using GetConsoleWindow() from
2304 * KERNEL32.DLL; we need to handle in order to change the window icon.
2305 * This function only exists on NT-based Windows, starting with Windows
2306 * 2000. On older operating systems, we can't change the window icon
2307 * anyway.
2308 */
2309 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2310 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2311 "GetConsoleWindow")) != NULL)
2312 {
2313 g_hWnd = (*GetConsoleWindowProc)();
2314 }
2315 if (g_hWnd == NULL)
2316 return;
2317
2318 /* Save the original console window icon. */
2319 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2320 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2321 return;
2322
2323 /* Extract the first icon contained in the Vim executable. */
2324 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2325 if (g_hVimIcon != NULL)
2326 g_fCanChangeIcon = TRUE;
2327}
2328#endif
2329
2330static int g_fWindInitCalled = FALSE;
2331static int g_fTermcapMode = FALSE;
2332static CONSOLE_CURSOR_INFO g_cci;
2333static DWORD g_cmodein = 0;
2334static DWORD g_cmodeout = 0;
2335
2336/*
2337 * non-GUI version of mch_init().
2338 */
2339 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002340mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341{
2342#ifndef FEAT_RESTORE_ORIG_SCREEN
2343 CONSOLE_SCREEN_BUFFER_INFO csbi;
2344#endif
2345#ifndef __MINGW32__
2346 extern int _fmode;
2347#endif
2348
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002349 /* Silently handle invalid parameters to CRT functions */
2350 SET_INVALID_PARAM_HANDLER;
2351
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 /* Let critical errors result in a failure, not in a dialog box. Required
2353 * for the timestamp test to work on removed floppies. */
2354 SetErrorMode(SEM_FAILCRITICALERRORS);
2355
2356 _fmode = O_BINARY; /* we do our own CR-LF translation */
2357 out_flush();
2358
2359 /* Obtain handles for the standard Console I/O devices */
2360 if (read_cmd_fd == 0)
2361 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2362 else
2363 create_conin();
2364 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2365
2366#ifdef FEAT_RESTORE_ORIG_SCREEN
2367 /* Save the initial console buffer for later restoration */
2368 SaveConsoleBuffer(&g_cbOrig);
2369 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2370#else
2371 /* Get current text attributes */
2372 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2373 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2374#endif
2375 if (cterm_normal_fg_color == 0)
2376 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2377 if (cterm_normal_bg_color == 0)
2378 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2379
2380 /* set termcap codes to current text attributes */
2381 update_tcap(g_attrCurrent);
2382
2383 GetConsoleCursorInfo(g_hConOut, &g_cci);
2384 GetConsoleMode(g_hConIn, &g_cmodein);
2385 GetConsoleMode(g_hConOut, &g_cmodeout);
2386
2387#ifdef FEAT_TITLE
2388 SaveConsoleTitleAndIcon();
2389 /*
2390 * Set both the small and big icons of the console window to Vim's icon.
2391 * Note that Vim presently only has one size of icon (32x32), but it
2392 * automatically gets scaled down to 16x16 when setting the small icon.
2393 */
2394 if (g_fCanChangeIcon)
2395 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2396#endif
2397
2398 ui_get_shellsize();
2399
2400#ifdef MCH_WRITE_DUMP
2401 fdDump = fopen("dump", "wt");
2402
2403 if (fdDump)
2404 {
2405 time_t t;
2406
2407 time(&t);
2408 fputs(ctime(&t), fdDump);
2409 fflush(fdDump);
2410 }
2411#endif
2412
2413 g_fWindInitCalled = TRUE;
2414
2415#ifdef FEAT_MOUSE
2416 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2417#endif
2418
2419#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002420 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421#endif
2422
2423 /* This will be NULL on anything but NT 4.0 */
2424 s_pfnGetConsoleKeyboardLayoutName =
2425 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2426 "GetConsoleKeyboardLayoutNameA");
2427}
2428
2429/*
2430 * non-GUI version of mch_exit().
2431 * Shut down and exit with status `r'
2432 * Careful: mch_exit() may be called before mch_init()!
2433 */
2434 void
2435mch_exit(int r)
2436{
2437 stoptermcap();
2438
2439 if (g_fWindInitCalled)
2440 settmode(TMODE_COOK);
2441
2442 ml_close_all(TRUE); /* remove all memfiles */
2443
2444 if (g_fWindInitCalled)
2445 {
2446#ifdef FEAT_TITLE
2447 mch_restore_title(3);
2448 /*
2449 * Restore both the small and big icons of the console window to
2450 * what they were at startup. Don't do this when the window is
2451 * closed, Vim would hang here.
2452 */
2453 if (g_fCanChangeIcon && !g_fForceExit)
2454 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2455#endif
2456
2457#ifdef MCH_WRITE_DUMP
2458 if (fdDump)
2459 {
2460 time_t t;
2461
2462 time(&t);
2463 fputs(ctime(&t), fdDump);
2464 fclose(fdDump);
2465 }
2466 fdDump = NULL;
2467#endif
2468 }
2469
2470 SetConsoleCursorInfo(g_hConOut, &g_cci);
2471 SetConsoleMode(g_hConIn, g_cmodein);
2472 SetConsoleMode(g_hConOut, g_cmodeout);
2473
2474#ifdef DYNAMIC_GETTEXT
2475 dyn_libintl_end();
2476#endif
2477
2478 exit(r);
2479}
2480#endif /* !FEAT_GUI_W32 */
2481
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482/*
2483 * Do we have an interactive window?
2484 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002485/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 int
2487mch_check_win(
2488 int argc,
2489 char **argv)
2490{
2491 get_exe_name();
2492
2493#ifdef FEAT_GUI_W32
2494 return OK; /* GUI always has a tty */
2495#else
2496 if (isatty(1))
2497 return OK;
2498 return FAIL;
2499#endif
2500}
2501
2502
2503/*
2504 * fname_case(): Set the case of the file name, if it already exists.
2505 * When "len" is > 0, also expand short to long filenames.
2506 */
2507 void
2508fname_case(
2509 char_u *name,
2510 int len)
2511{
2512 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002513 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 char *ptrue, *ptruePrev;
2515 char *porig, *porigPrev;
2516 int flen;
2517 WIN32_FIND_DATA fb;
2518 HANDLE hFind;
2519 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002520 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002522 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 if (flen == 0 || flen > _MAX_PATH)
2524 return;
2525
2526 slash_adjust(name);
2527
2528 /* Build the new name in szTrueName[] one component at a time. */
2529 porig = name;
2530 ptrue = szTrueName;
2531
2532 if (isalpha(porig[0]) && porig[1] == ':')
2533 {
2534 /* copy leading drive letter */
2535 *ptrue++ = *porig++;
2536 *ptrue++ = *porig++;
2537 *ptrue = NUL; /* in case nothing follows */
2538 }
2539
2540 while (*porig != NUL)
2541 {
2542 /* copy \ characters */
2543 while (*porig == psepc)
2544 *ptrue++ = *porig++;
2545
2546 ptruePrev = ptrue;
2547 porigPrev = porig;
2548 while (*porig != NUL && *porig != psepc)
2549 {
2550#ifdef FEAT_MBYTE
2551 int l;
2552
2553 if (enc_dbcs)
2554 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002555 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002556 while (--l >= 0)
2557 *ptrue++ = *porig++;
2558 }
2559 else
2560#endif
2561 *ptrue++ = *porig++;
2562 }
2563 *ptrue = NUL;
2564
Bram Moolenaar464c9252010-10-13 20:37:41 +02002565 /* To avoid a slow failure append "\*" when searching a directory,
2566 * server or network share. */
2567 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002568 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002569 if (*porig == psepc && slen + 2 < _MAX_PATH)
2570 STRCPY(szTrueNameTemp + slen, "\\*");
2571
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 /* Skip "", "." and "..". */
2573 if (ptrue > ptruePrev
2574 && (ptruePrev[0] != '.'
2575 || (ptruePrev[1] != NUL
2576 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002577 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 != INVALID_HANDLE_VALUE)
2579 {
2580 c = *porig;
2581 *porig = NUL;
2582
2583 /* Only use the match when it's the same name (ignoring case) or
2584 * expansion is allowed and there is a match with the short name
2585 * and there is enough room. */
2586 if (_stricoll(porigPrev, fb.cFileName) == 0
2587 || (len > 0
2588 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2589 && (int)(ptruePrev - szTrueName)
2590 + (int)strlen(fb.cFileName) < len)))
2591 {
2592 STRCPY(ptruePrev, fb.cFileName);
2593
2594 /* Look for exact match and prefer it if found. Must be a
2595 * long name, otherwise there would be only one match. */
2596 while (FindNextFile(hFind, &fb))
2597 {
2598 if (*fb.cAlternateFileName != NUL
2599 && (strcoll(porigPrev, fb.cFileName) == 0
2600 || (len > 0
2601 && (_stricoll(porigPrev,
2602 fb.cAlternateFileName) == 0
2603 && (int)(ptruePrev - szTrueName)
2604 + (int)strlen(fb.cFileName) < len))))
2605 {
2606 STRCPY(ptruePrev, fb.cFileName);
2607 break;
2608 }
2609 }
2610 }
2611 FindClose(hFind);
2612 *porig = c;
2613 ptrue = ptruePrev + strlen(ptruePrev);
2614 }
2615 }
2616
2617 STRCPY(name, szTrueName);
2618}
2619
2620
2621/*
2622 * Insert user name in s[len].
2623 */
2624 int
2625mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002626 char_u *s,
2627 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002628{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002629 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 DWORD cch = sizeof szUserName;
2631
2632 if (GetUserName(szUserName, &cch))
2633 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002634 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635 return OK;
2636 }
2637 s[0] = NUL;
2638 return FAIL;
2639}
2640
2641
2642/*
2643 * Insert host name in s[len].
2644 */
2645 void
2646mch_get_host_name(
2647 char_u *s,
2648 int len)
2649{
2650 DWORD cch = len;
2651
2652 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002653 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002654}
2655
2656
2657/*
2658 * return process ID
2659 */
2660 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002661mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662{
2663 return (long)GetCurrentProcessId();
2664}
2665
2666
2667/*
2668 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2669 * Return OK for success, FAIL for failure.
2670 */
2671 int
2672mch_dirname(
2673 char_u *buf,
2674 int len)
2675{
2676 /*
2677 * Originally this was:
2678 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2679 * But the Win32s known bug list says that getcwd() doesn't work
2680 * so use the Win32 system call instead. <Negri>
2681 */
2682#ifdef FEAT_MBYTE
2683 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2684 {
2685 WCHAR wbuf[_MAX_PATH + 1];
2686
2687 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2688 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002689 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690
2691 if (p != NULL)
2692 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002693 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694 vim_free(p);
2695 return OK;
2696 }
2697 }
2698 /* Retry with non-wide function (for Windows 98). */
2699 }
2700#endif
2701 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2702}
2703
2704/*
2705 * get file permissions for `name'
2706 * -1 : error
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002707 * else mode_t
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708 */
2709 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002710mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002712 struct stat st;
2713 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002715 n = mch_stat(name, &st);
2716 return n == 0 ? (int)st.st_mode : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717}
2718
2719
2720/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002721 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002722 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002723 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724 */
2725 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002726mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002728 long n = -1;
2729
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730#ifdef FEAT_MBYTE
2731 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2732 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002733 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734
2735 if (p != NULL)
2736 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002737 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002739 if (n == -1 && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2740 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741 /* Retry with non-wide function (for Windows 98). */
2742 }
2743 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002744 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002746 n = _chmod(name, perm);
2747 if (n == -1)
2748 return FAIL;
2749
2750 win32_set_archive(name);
2751
2752 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002753}
2754
2755/*
2756 * Set hidden flag for "name".
2757 */
2758 void
2759mch_hide(char_u *name)
2760{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002761 int attrs = win32_getattrs(name);
2762 if (attrs == -1)
2763 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002765 attrs |= FILE_ATTRIBUTE_HIDDEN;
2766 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767}
2768
2769/*
2770 * return TRUE if "name" is a directory
2771 * return FALSE if "name" is not a directory or upon error
2772 */
2773 int
2774mch_isdir(char_u *name)
2775{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002776 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777
2778 if (f == -1)
2779 return FALSE; /* file does not exist at all */
2780
2781 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2782}
2783
2784/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002785 * Create directory "name".
2786 * Return 0 on success, -1 on error.
2787 */
2788 int
2789mch_mkdir(char_u *name)
2790{
2791#ifdef FEAT_MBYTE
2792 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2793 {
2794 WCHAR *p;
2795 int retval;
2796
2797 p = enc_to_utf16(name, NULL);
2798 if (p == NULL)
2799 return -1;
2800 retval = _wmkdir(p);
2801 vim_free(p);
2802 return retval;
2803 }
2804#endif
2805 return _mkdir(name);
2806}
2807
2808/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002809 * Return TRUE if file "fname" has more than one link.
2810 */
2811 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002812mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002813{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002814 BY_HANDLE_FILE_INFORMATION info;
2815
2816 return win32_fileinfo(fname, &info) == FILEINFO_OK
2817 && info.nNumberOfLinks > 1;
2818}
2819
2820/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002821 * Return TRUE if file "fname" is a symbolic link.
2822 */
2823 int
2824mch_is_symbolic_link(char_u *fname)
2825{
2826 HANDLE hFind;
2827 int res = FALSE;
2828 WIN32_FIND_DATAA findDataA;
2829 DWORD fileFlags = 0, reparseTag = 0;
2830#ifdef FEAT_MBYTE
2831 WCHAR *wn = NULL;
2832 WIN32_FIND_DATAW findDataW;
2833
2834 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2835 wn = enc_to_utf16(fname, NULL);
2836 if (wn != NULL)
2837 {
2838 hFind = FindFirstFileW(wn, &findDataW);
2839 vim_free(wn);
2840 if (hFind == INVALID_HANDLE_VALUE
2841 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2842 {
2843 /* Retry with non-wide function (for Windows 98). */
2844 hFind = FindFirstFile(fname, &findDataA);
2845 if (hFind != INVALID_HANDLE_VALUE)
2846 {
2847 fileFlags = findDataA.dwFileAttributes;
2848 reparseTag = findDataA.dwReserved0;
2849 }
2850 }
2851 else
2852 {
2853 fileFlags = findDataW.dwFileAttributes;
2854 reparseTag = findDataW.dwReserved0;
2855 }
2856 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002857 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002858#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002859 {
2860 hFind = FindFirstFile(fname, &findDataA);
2861 if (hFind != INVALID_HANDLE_VALUE)
2862 {
2863 fileFlags = findDataA.dwFileAttributes;
2864 reparseTag = findDataA.dwReserved0;
2865 }
2866 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002867
2868 if (hFind != INVALID_HANDLE_VALUE)
2869 FindClose(hFind);
2870
2871 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
2872 && reparseTag == IO_REPARSE_TAG_SYMLINK)
2873 res = TRUE;
2874
2875 return res;
2876}
2877
2878/*
2879 * Return TRUE if file "fname" has more than one link or if it is a symbolic
2880 * link.
2881 */
2882 int
2883mch_is_linked(char_u *fname)
2884{
2885 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
2886 return TRUE;
2887 return FALSE;
2888}
2889
2890/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002891 * Get the by-handle-file-information for "fname".
2892 * Returns FILEINFO_OK when OK.
2893 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
2894 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
2895 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
2896 */
2897 int
2898win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
2899{
Bram Moolenaar03f48552006-02-28 23:52:23 +00002900 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002901 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002902#ifdef FEAT_MBYTE
2903 WCHAR *wn = NULL;
2904
2905 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002906 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002907 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002908 if (wn == NULL)
2909 res = FILEINFO_ENC_FAIL;
2910 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00002911 if (wn != NULL)
2912 {
2913 hFile = CreateFileW(wn, /* file name */
2914 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002915 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002916 NULL, /* security descriptor */
2917 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002918 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002919 NULL); /* handle to template file */
2920 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002921 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002922 {
2923 /* Retry with non-wide function (for Windows 98). */
2924 vim_free(wn);
2925 wn = NULL;
2926 }
2927 }
2928 if (wn == NULL)
2929#endif
2930 hFile = CreateFile(fname, /* file name */
2931 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002932 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002933 NULL, /* security descriptor */
2934 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002935 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002936 NULL); /* handle to template file */
2937
2938 if (hFile != INVALID_HANDLE_VALUE)
2939 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002940 if (GetFileInformationByHandle(hFile, info) != 0)
2941 res = FILEINFO_OK;
2942 else
2943 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002944 CloseHandle(hFile);
2945 }
2946
2947#ifdef FEAT_MBYTE
2948 vim_free(wn);
2949#endif
2950 return res;
2951}
2952
2953/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002954 * get file attributes for `name'
2955 * -1 : error
2956 * else FILE_ATTRIBUTE_* defined in winnt.h
2957 */
2958 static
2959 int
2960win32_getattrs(char_u *name)
2961{
2962 int attr;
2963#ifdef FEAT_MBYTE
2964 WCHAR *p = NULL;
2965
2966 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2967 p = enc_to_utf16(name, NULL);
2968
2969 if (p != NULL)
2970 {
2971 attr = GetFileAttributesW(p);
2972 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2973 {
2974 /* Retry with non-wide function (for Windows 98). */
2975 vim_free(p);
2976 p = NULL;
2977 }
2978 }
2979 if (p == NULL)
2980#endif
2981 attr = GetFileAttributes((char *)name);
2982#ifdef FEAT_MBYTE
2983 vim_free(p);
2984#endif
2985 return attr;
2986}
2987
2988/*
2989 * set file attributes for `name' to `attrs'
2990 *
2991 * return -1 for failure, 0 otherwise
2992 */
2993 static
2994 int
2995win32_setattrs(char_u *name, int attrs)
2996{
2997 int res;
2998#ifdef FEAT_MBYTE
2999 WCHAR *p = NULL;
3000
3001 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3002 p = enc_to_utf16(name, NULL);
3003
3004 if (p != NULL)
3005 {
3006 res = SetFileAttributesW(p, attrs);
3007 if (res == FALSE
3008 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3009 {
3010 /* Retry with non-wide function (for Windows 98). */
3011 vim_free(p);
3012 p = NULL;
3013 }
3014 }
3015 if (p == NULL)
3016#endif
3017 res = SetFileAttributes((char *)name, attrs);
3018#ifdef FEAT_MBYTE
3019 vim_free(p);
3020#endif
3021 return res ? 0 : -1;
3022}
3023
3024/*
3025 * Set archive flag for "name".
3026 */
3027 static
3028 int
3029win32_set_archive(char_u *name)
3030{
3031 int attrs = win32_getattrs(name);
3032 if (attrs == -1)
3033 return -1;
3034
3035 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3036 return win32_setattrs(name, attrs);
3037}
3038
3039/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 * Return TRUE if file or directory "name" is writable (not readonly).
3041 * Strange semantics of Win32: a readonly directory is writable, but you can't
3042 * delete a file. Let's say this means it is writable.
3043 */
3044 int
3045mch_writable(char_u *name)
3046{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003047 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003049 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3050 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051}
3052
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053/*
3054 * Return 1 if "name" can be executed, 0 if not.
3055 * Return -1 if unknown.
3056 */
3057 int
3058mch_can_exe(char_u *name)
3059{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003060 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003061 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003062 char_u *p;
3063
3064 if (len >= _MAX_PATH) /* safety check */
3065 return FALSE;
3066
3067 /* If there already is an extension try using the name directly. Also do
3068 * this with a Unix-shell like 'shell'. */
3069 if (vim_strchr(gettail(name), '.') != NULL
3070 || strstr((char *)gettail(p_sh), "sh") != NULL)
3071 if (executable_exists((char *)name))
3072 return TRUE;
3073
3074 /*
3075 * Loop over all extensions in $PATHEXT.
3076 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003077 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003078 p = mch_getenv("PATHEXT");
3079 if (p == NULL)
3080 p = (char_u *)".com;.exe;.bat;.cmd";
3081 while (*p)
3082 {
3083 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3084 {
3085 /* A single "." means no extension is added. */
3086 buf[len] = NUL;
3087 ++p;
3088 if (*p)
3089 ++p;
3090 }
3091 else
3092 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
3093 if (executable_exists((char *)buf))
3094 return TRUE;
3095 }
3096 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098
3099/*
3100 * Check what "name" is:
3101 * NODE_NORMAL: file or directory (or doesn't exist)
3102 * NODE_WRITABLE: writable device, socket, fifo, etc.
3103 * NODE_OTHER: non-writable things
3104 */
3105 int
3106mch_nodetype(char_u *name)
3107{
3108 HANDLE hFile;
3109 int type;
3110
Bram Moolenaar043545e2006-10-10 16:44:07 +00003111 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3112 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3113 * here. */
3114 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3115 return NODE_WRITABLE;
3116
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117 hFile = CreateFile(name, /* file name */
3118 GENERIC_WRITE, /* access mode */
3119 0, /* share mode */
3120 NULL, /* security descriptor */
3121 OPEN_EXISTING, /* creation disposition */
3122 0, /* file attributes */
3123 NULL); /* handle to template file */
3124
3125 if (hFile == INVALID_HANDLE_VALUE)
3126 return NODE_NORMAL;
3127
3128 type = GetFileType(hFile);
3129 CloseHandle(hFile);
3130 if (type == FILE_TYPE_CHAR)
3131 return NODE_WRITABLE;
3132 if (type == FILE_TYPE_DISK)
3133 return NODE_NORMAL;
3134 return NODE_OTHER;
3135}
3136
3137#ifdef HAVE_ACL
3138struct my_acl
3139{
3140 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3141 PSID pSidOwner;
3142 PSID pSidGroup;
3143 PACL pDacl;
3144 PACL pSacl;
3145};
3146#endif
3147
3148/*
3149 * Return a pointer to the ACL of file "fname" in allocated memory.
3150 * Return NULL if the ACL is not available for whatever reason.
3151 */
3152 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003153mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003154{
3155#ifndef HAVE_ACL
3156 return (vim_acl_T)NULL;
3157#else
3158 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003159 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160
3161 /* This only works on Windows NT and 2000. */
3162 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3163 {
3164 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3165 if (p != NULL)
3166 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003167# ifdef FEAT_MBYTE
3168 WCHAR *wn = NULL;
3169
3170 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3171 wn = enc_to_utf16(fname, NULL);
3172 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003174 /* Try to retrieve the entire security descriptor. */
3175 err = pGetNamedSecurityInfoW(
3176 wn, // Abstract filename
3177 SE_FILE_OBJECT, // File Object
3178 OWNER_SECURITY_INFORMATION |
3179 GROUP_SECURITY_INFORMATION |
3180 DACL_SECURITY_INFORMATION |
3181 SACL_SECURITY_INFORMATION,
3182 &p->pSidOwner, // Ownership information.
3183 &p->pSidGroup, // Group membership.
3184 &p->pDacl, // Discretionary information.
3185 &p->pSacl, // For auditing purposes.
3186 &p->pSecurityDescriptor);
3187 if (err == ERROR_ACCESS_DENIED ||
3188 err == ERROR_PRIVILEGE_NOT_HELD)
3189 {
3190 /* Retrieve only DACL. */
3191 (void)pGetNamedSecurityInfoW(
3192 wn,
3193 SE_FILE_OBJECT,
3194 DACL_SECURITY_INFORMATION,
3195 NULL,
3196 NULL,
3197 &p->pDacl,
3198 NULL,
3199 &p->pSecurityDescriptor);
3200 }
3201 if (p->pSecurityDescriptor == NULL)
3202 {
3203 mch_free_acl((vim_acl_T)p);
3204 p = NULL;
3205 }
3206 vim_free(wn);
3207 }
3208 else
3209# endif
3210 {
3211 /* Try to retrieve the entire security descriptor. */
3212 err = pGetNamedSecurityInfo(
3213 (LPSTR)fname, // Abstract filename
3214 SE_FILE_OBJECT, // File Object
3215 OWNER_SECURITY_INFORMATION |
3216 GROUP_SECURITY_INFORMATION |
3217 DACL_SECURITY_INFORMATION |
3218 SACL_SECURITY_INFORMATION,
3219 &p->pSidOwner, // Ownership information.
3220 &p->pSidGroup, // Group membership.
3221 &p->pDacl, // Discretionary information.
3222 &p->pSacl, // For auditing purposes.
3223 &p->pSecurityDescriptor);
3224 if (err == ERROR_ACCESS_DENIED ||
3225 err == ERROR_PRIVILEGE_NOT_HELD)
3226 {
3227 /* Retrieve only DACL. */
3228 (void)pGetNamedSecurityInfo(
3229 (LPSTR)fname,
3230 SE_FILE_OBJECT,
3231 DACL_SECURITY_INFORMATION,
3232 NULL,
3233 NULL,
3234 &p->pDacl,
3235 NULL,
3236 &p->pSecurityDescriptor);
3237 }
3238 if (p->pSecurityDescriptor == NULL)
3239 {
3240 mch_free_acl((vim_acl_T)p);
3241 p = NULL;
3242 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 }
3244 }
3245 }
3246
3247 return (vim_acl_T)p;
3248#endif
3249}
3250
Bram Moolenaar27515922013-06-29 15:36:26 +02003251#ifdef HAVE_ACL
3252/*
3253 * Check if "acl" contains inherited ACE.
3254 */
3255 static BOOL
3256is_acl_inherited(PACL acl)
3257{
3258 DWORD i;
3259 ACL_SIZE_INFORMATION acl_info;
3260 PACCESS_ALLOWED_ACE ace;
3261
3262 acl_info.AceCount = 0;
3263 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3264 for (i = 0; i < acl_info.AceCount; i++)
3265 {
3266 GetAce(acl, i, (LPVOID *)&ace);
3267 if (ace->Header.AceFlags & INHERITED_ACE)
3268 return TRUE;
3269 }
3270 return FALSE;
3271}
3272#endif
3273
Bram Moolenaar071d4272004-06-13 20:20:40 +00003274/*
3275 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3276 * Errors are ignored.
3277 * This must only be called with "acl" equal to what mch_get_acl() returned.
3278 */
3279 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003280mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003281{
3282#ifdef HAVE_ACL
3283 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003284 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003285
3286 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003287 {
3288# ifdef FEAT_MBYTE
3289 WCHAR *wn = NULL;
3290# endif
3291
3292 /* Set security flags */
3293 if (p->pSidOwner)
3294 sec_info |= OWNER_SECURITY_INFORMATION;
3295 if (p->pSidGroup)
3296 sec_info |= GROUP_SECURITY_INFORMATION;
3297 if (p->pDacl)
3298 {
3299 sec_info |= DACL_SECURITY_INFORMATION;
3300 /* Do not inherit its parent's DACL.
3301 * If the DACL is inherited, Cygwin permissions would be changed.
3302 */
3303 if (!is_acl_inherited(p->pDacl))
3304 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3305 }
3306 if (p->pSacl)
3307 sec_info |= SACL_SECURITY_INFORMATION;
3308
3309# ifdef FEAT_MBYTE
3310 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3311 wn = enc_to_utf16(fname, NULL);
3312 if (wn != NULL)
3313 {
3314 (void)pSetNamedSecurityInfoW(
3315 wn, // Abstract filename
3316 SE_FILE_OBJECT, // File Object
3317 sec_info,
3318 p->pSidOwner, // Ownership information.
3319 p->pSidGroup, // Group membership.
3320 p->pDacl, // Discretionary information.
3321 p->pSacl // For auditing purposes.
3322 );
3323 vim_free(wn);
3324 }
3325 else
3326# endif
3327 {
3328 (void)pSetNamedSecurityInfo(
3329 (LPSTR)fname, // Abstract filename
3330 SE_FILE_OBJECT, // File Object
3331 sec_info,
3332 p->pSidOwner, // Ownership information.
3333 p->pSidGroup, // Group membership.
3334 p->pDacl, // Discretionary information.
3335 p->pSacl // For auditing purposes.
3336 );
3337 }
3338 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003339#endif
3340}
3341
3342 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003343mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344{
3345#ifdef HAVE_ACL
3346 struct my_acl *p = (struct my_acl *)acl;
3347
3348 if (p != NULL)
3349 {
3350 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3351 vim_free(p);
3352 }
3353#endif
3354}
3355
3356#ifndef FEAT_GUI_W32
3357
3358/*
3359 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3360 */
3361 static BOOL WINAPI
3362handler_routine(
3363 DWORD dwCtrlType)
3364{
3365 switch (dwCtrlType)
3366 {
3367 case CTRL_C_EVENT:
3368 if (ctrl_c_interrupts)
3369 g_fCtrlCPressed = TRUE;
3370 return TRUE;
3371
3372 case CTRL_BREAK_EVENT:
3373 g_fCBrkPressed = TRUE;
3374 return TRUE;
3375
3376 /* fatal events: shut down gracefully */
3377 case CTRL_CLOSE_EVENT:
3378 case CTRL_LOGOFF_EVENT:
3379 case CTRL_SHUTDOWN_EVENT:
3380 windgoto((int)Rows - 1, 0);
3381 g_fForceExit = TRUE;
3382
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003383 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003384 (dwCtrlType == CTRL_CLOSE_EVENT
3385 ? _("close")
3386 : dwCtrlType == CTRL_LOGOFF_EVENT
3387 ? _("logoff")
3388 : _("shutdown")));
3389#ifdef DEBUG
3390 OutputDebugString(IObuff);
3391#endif
3392
3393 preserve_exit(); /* output IObuff, preserve files and exit */
3394
3395 return TRUE; /* not reached */
3396
3397 default:
3398 return FALSE;
3399 }
3400}
3401
3402
3403/*
3404 * set the tty in (raw) ? "raw" : "cooked" mode
3405 */
3406 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003407mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003408{
3409 DWORD cmodein;
3410 DWORD cmodeout;
3411 BOOL bEnableHandler;
3412
3413 GetConsoleMode(g_hConIn, &cmodein);
3414 GetConsoleMode(g_hConOut, &cmodeout);
3415 if (tmode == TMODE_RAW)
3416 {
3417 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3418 ENABLE_ECHO_INPUT);
3419#ifdef FEAT_MOUSE
3420 if (g_fMouseActive)
3421 cmodein |= ENABLE_MOUSE_INPUT;
3422#endif
3423 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3424 bEnableHandler = TRUE;
3425 }
3426 else /* cooked */
3427 {
3428 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3429 ENABLE_ECHO_INPUT);
3430 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3431 bEnableHandler = FALSE;
3432 }
3433 SetConsoleMode(g_hConIn, cmodein);
3434 SetConsoleMode(g_hConOut, cmodeout);
3435 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3436
3437#ifdef MCH_WRITE_DUMP
3438 if (fdDump)
3439 {
3440 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3441 tmode == TMODE_RAW ? "raw" :
3442 tmode == TMODE_COOK ? "cooked" : "normal",
3443 cmodein, cmodeout);
3444 fflush(fdDump);
3445 }
3446#endif
3447}
3448
3449
3450/*
3451 * Get the size of the current window in `Rows' and `Columns'
3452 * Return OK when size could be determined, FAIL otherwise.
3453 */
3454 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003455mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003456{
3457 CONSOLE_SCREEN_BUFFER_INFO csbi;
3458
3459 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3460 {
3461 /*
3462 * For some reason, we are trying to get the screen dimensions
3463 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3464 * variables are really intended to mean the size of Vim screen
3465 * while in termcap mode.
3466 */
3467 Rows = g_cbTermcap.Info.dwSize.Y;
3468 Columns = g_cbTermcap.Info.dwSize.X;
3469 }
3470 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3471 {
3472 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3473 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3474 }
3475 else
3476 {
3477 Rows = 25;
3478 Columns = 80;
3479 }
3480 return OK;
3481}
3482
3483/*
3484 * Set a console window to `xSize' * `ySize'
3485 */
3486 static void
3487ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003488 HANDLE hConsole,
3489 int xSize,
3490 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491{
3492 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3493 SMALL_RECT srWindowRect; /* hold the new console size */
3494 COORD coordScreen;
3495
3496#ifdef MCH_WRITE_DUMP
3497 if (fdDump)
3498 {
3499 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3500 fflush(fdDump);
3501 }
3502#endif
3503
3504 /* get the largest size we can size the console window to */
3505 coordScreen = GetLargestConsoleWindowSize(hConsole);
3506
3507 /* define the new console window size and scroll position */
3508 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3509 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3510 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3511
3512 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3513 {
3514 int sx, sy;
3515
3516 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3517 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3518 if (sy < ySize || sx < xSize)
3519 {
3520 /*
3521 * Increasing number of lines/columns, do buffer first.
3522 * Use the maximal size in x and y direction.
3523 */
3524 if (sy < ySize)
3525 coordScreen.Y = ySize;
3526 else
3527 coordScreen.Y = sy;
3528 if (sx < xSize)
3529 coordScreen.X = xSize;
3530 else
3531 coordScreen.X = sx;
3532 SetConsoleScreenBufferSize(hConsole, coordScreen);
3533 }
3534 }
3535
3536 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3537 {
3538#ifdef MCH_WRITE_DUMP
3539 if (fdDump)
3540 {
3541 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3542 GetLastError());
3543 fflush(fdDump);
3544 }
3545#endif
3546 }
3547
3548 /* define the new console buffer size */
3549 coordScreen.X = xSize;
3550 coordScreen.Y = ySize;
3551
3552 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3553 {
3554#ifdef MCH_WRITE_DUMP
3555 if (fdDump)
3556 {
3557 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3558 GetLastError());
3559 fflush(fdDump);
3560 }
3561#endif
3562 }
3563}
3564
3565
3566/*
3567 * Set the console window to `Rows' * `Columns'
3568 */
3569 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003570mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003571{
3572 COORD coordScreen;
3573
3574 /* Don't change window size while still starting up */
3575 if (suppress_winsize != 0)
3576 {
3577 suppress_winsize = 2;
3578 return;
3579 }
3580
3581 if (term_console)
3582 {
3583 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3584
3585 /* Clamp Rows and Columns to reasonable values */
3586 if (Rows > coordScreen.Y)
3587 Rows = coordScreen.Y;
3588 if (Columns > coordScreen.X)
3589 Columns = coordScreen.X;
3590
3591 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3592 }
3593}
3594
3595/*
3596 * Rows and/or Columns has changed.
3597 */
3598 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003599mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003600{
3601 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3602}
3603
3604
3605/*
3606 * Called when started up, to set the winsize that was delayed.
3607 */
3608 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003609mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610{
3611 if (suppress_winsize == 2)
3612 {
3613 suppress_winsize = 0;
3614 mch_set_shellsize();
3615 shell_resized();
3616 }
3617 suppress_winsize = 0;
3618}
3619#endif /* FEAT_GUI_W32 */
3620
3621
3622
3623#if defined(FEAT_GUI_W32) || defined(PROTO)
3624
3625/*
3626 * Specialised version of system() for Win32 GUI mode.
3627 * This version proceeds as follows:
3628 * 1. Create a console window for use by the subprocess
3629 * 2. Run the subprocess (it gets the allocated console by default)
3630 * 3. Wait for the subprocess to terminate and get its exit code
3631 * 4. Prompt the user to press a key to close the console window
3632 */
3633 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003634mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635{
3636 STARTUPINFO si;
3637 PROCESS_INFORMATION pi;
3638 DWORD ret = 0;
3639 HWND hwnd = GetFocus();
3640
3641 si.cb = sizeof(si);
3642 si.lpReserved = NULL;
3643 si.lpDesktop = NULL;
3644 si.lpTitle = NULL;
3645 si.dwFlags = STARTF_USESHOWWINDOW;
3646 /*
3647 * It's nicer to run a filter command in a minimized window, but in
3648 * Windows 95 this makes the command MUCH slower. We can't do it under
3649 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003650 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003651 */
3652 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003653 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003654 else
3655 si.wShowWindow = SW_SHOWNORMAL;
3656 si.cbReserved2 = 0;
3657 si.lpReserved2 = NULL;
3658
3659 /* There is a strange error on Windows 95 when using "c:\\command.com".
3660 * When the "c:\\" is left out it works OK...? */
3661 if (mch_windows95()
3662 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3663 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3664 cmd += 3;
3665
3666 /* Now, run the command */
3667 CreateProcess(NULL, /* Executable name */
3668 cmd, /* Command to execute */
3669 NULL, /* Process security attributes */
3670 NULL, /* Thread security attributes */
3671 FALSE, /* Inherit handles */
3672 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3673 CREATE_NEW_CONSOLE,
3674 NULL, /* Environment */
3675 NULL, /* Current directory */
3676 &si, /* Startup information */
3677 &pi); /* Process information */
3678
3679
3680 /* Wait for the command to terminate before continuing */
3681 if (g_PlatformId != VER_PLATFORM_WIN32s)
3682 {
3683#ifdef FEAT_GUI
3684 int delay = 1;
3685
3686 /* Keep updating the window while waiting for the shell to finish. */
3687 for (;;)
3688 {
3689 MSG msg;
3690
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003691 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003692 {
3693 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003694 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003695 delay = 1;
3696 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697 }
3698 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3699 break;
3700
3701 /* We start waiting for a very short time and then increase it, so
3702 * that we respond quickly when the process is quick, and don't
3703 * consume too much overhead when it's slow. */
3704 if (delay < 50)
3705 delay += 10;
3706 }
3707#else
3708 WaitForSingleObject(pi.hProcess, INFINITE);
3709#endif
3710
3711 /* Get the command exit code */
3712 GetExitCodeProcess(pi.hProcess, &ret);
3713 }
3714 else
3715 {
3716 /*
3717 * This ugly code is the only quick way of performing
3718 * a synchronous spawn under Win32s. Yuk.
3719 */
3720 num_windows = 0;
3721 EnumWindows(win32ssynch_cb, 0);
3722 old_num_windows = num_windows;
3723 do
3724 {
3725 Sleep(1000);
3726 num_windows = 0;
3727 EnumWindows(win32ssynch_cb, 0);
3728 } while (num_windows == old_num_windows);
3729 ret = 0;
3730 }
3731
3732 /* Close the handles to the subprocess, so that it goes away */
3733 CloseHandle(pi.hThread);
3734 CloseHandle(pi.hProcess);
3735
3736 /* Try to get input focus back. Doesn't always work though. */
3737 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3738
3739 return ret;
3740}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003741
3742/*
3743 * Thread launched by the gui to send the current buffer data to the
3744 * process. This way avoid to hang up vim totally if the children
3745 * process take a long time to process the lines.
3746 */
3747 static DWORD WINAPI
3748sub_process_writer(LPVOID param)
3749{
3750 HANDLE g_hChildStd_IN_Wr = param;
3751 linenr_T lnum = curbuf->b_op_start.lnum;
3752 DWORD len = 0;
3753 DWORD l;
3754 char_u *lp = ml_get(lnum);
3755 char_u *s;
3756 int written = 0;
3757
3758 for (;;)
3759 {
3760 l = (DWORD)STRLEN(lp + written);
3761 if (l == 0)
3762 len = 0;
3763 else if (lp[written] == NL)
3764 {
3765 /* NL -> NUL translation */
3766 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3767 }
3768 else
3769 {
3770 s = vim_strchr(lp + written, NL);
3771 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3772 s == NULL ? l : (DWORD)(s - (lp + written)),
3773 &len, NULL);
3774 }
3775 if (len == (int)l)
3776 {
3777 /* Finished a line, add a NL, unless this line should not have
3778 * one. */
3779 if (lnum != curbuf->b_op_end.lnum
3780 || !curbuf->b_p_bin
3781 || (lnum != curbuf->b_no_eol_lnum
3782 && (lnum != curbuf->b_ml.ml_line_count
3783 || curbuf->b_p_eol)))
3784 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01003785 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003786 }
3787
3788 ++lnum;
3789 if (lnum > curbuf->b_op_end.lnum)
3790 break;
3791
3792 lp = ml_get(lnum);
3793 written = 0;
3794 }
3795 else if (len > 0)
3796 written += len;
3797 }
3798
3799 /* finished all the lines, close pipe */
3800 CloseHandle(g_hChildStd_IN_Wr);
3801 ExitThread(0);
3802}
3803
3804
3805# define BUFLEN 100 /* length for buffer, stolen from unix version */
3806
3807/*
3808 * This function read from the children's stdout and write the
3809 * data on screen or in the buffer accordingly.
3810 */
3811 static void
3812dump_pipe(int options,
3813 HANDLE g_hChildStd_OUT_Rd,
3814 garray_T *ga,
3815 char_u buffer[],
3816 DWORD *buffer_off)
3817{
3818 DWORD availableBytes = 0;
3819 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003820 int ret;
3821 DWORD len;
3822 DWORD toRead;
3823 int repeatCount;
3824
3825 /* we query the pipe to see if there is any data to read
3826 * to avoid to perform a blocking read */
3827 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3828 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003829 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003830 NULL, /* number of read bytes */
3831 &availableBytes, /* available bytes total */
3832 NULL); /* byteLeft */
3833
3834 repeatCount = 0;
3835 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003836 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003837 {
3838 repeatCount++;
3839 toRead =
3840# ifdef FEAT_MBYTE
3841 (DWORD)(BUFLEN - *buffer_off);
3842# else
3843 (DWORD)BUFLEN;
3844# endif
3845 toRead = availableBytes < toRead ? availableBytes : toRead;
3846 ReadFile(g_hChildStd_OUT_Rd, buffer
3847# ifdef FEAT_MBYTE
3848 + *buffer_off, toRead
3849# else
3850 , toRead
3851# endif
3852 , &len, NULL);
3853
3854 /* If we haven't read anything, there is a problem */
3855 if (len == 0)
3856 break;
3857
3858 availableBytes -= len;
3859
3860 if (options & SHELL_READ)
3861 {
3862 /* Do NUL -> NL translation, append NL separated
3863 * lines to the current buffer. */
3864 for (i = 0; i < len; ++i)
3865 {
3866 if (buffer[i] == NL)
3867 append_ga_line(ga);
3868 else if (buffer[i] == NUL)
3869 ga_append(ga, NL);
3870 else
3871 ga_append(ga, buffer[i]);
3872 }
3873 }
3874# ifdef FEAT_MBYTE
3875 else if (has_mbyte)
3876 {
3877 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003878 int c;
3879 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003880
3881 len += *buffer_off;
3882 buffer[len] = NUL;
3883
3884 /* Check if the last character in buffer[] is
3885 * incomplete, keep these bytes for the next
3886 * round. */
3887 for (p = buffer; p < buffer + len; p += l)
3888 {
3889 l = mb_cptr2len(p);
3890 if (l == 0)
3891 l = 1; /* NUL byte? */
3892 else if (MB_BYTE2LEN(*p) != l)
3893 break;
3894 }
3895 if (p == buffer) /* no complete character */
3896 {
3897 /* avoid getting stuck at an illegal byte */
3898 if (len >= 12)
3899 ++p;
3900 else
3901 {
3902 *buffer_off = len;
3903 return;
3904 }
3905 }
3906 c = *p;
3907 *p = NUL;
3908 msg_puts(buffer);
3909 if (p < buffer + len)
3910 {
3911 *p = c;
3912 *buffer_off = (DWORD)((buffer + len) - p);
3913 mch_memmove(buffer, p, *buffer_off);
3914 return;
3915 }
3916 *buffer_off = 0;
3917 }
3918# endif /* FEAT_MBYTE */
3919 else
3920 {
3921 buffer[len] = NUL;
3922 msg_puts(buffer);
3923 }
3924
3925 windgoto(msg_row, msg_col);
3926 cursor_on();
3927 out_flush();
3928 }
3929}
3930
3931/*
3932 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
3933 * for communication and doesn't open any new window.
3934 */
3935 static int
3936mch_system_piped(char *cmd, int options)
3937{
3938 STARTUPINFO si;
3939 PROCESS_INFORMATION pi;
3940 DWORD ret = 0;
3941
3942 HANDLE g_hChildStd_IN_Rd = NULL;
3943 HANDLE g_hChildStd_IN_Wr = NULL;
3944 HANDLE g_hChildStd_OUT_Rd = NULL;
3945 HANDLE g_hChildStd_OUT_Wr = NULL;
3946
3947 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
3948 DWORD len;
3949
3950 /* buffer used to receive keys */
3951 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3952 int ta_len = 0; /* valid bytes in ta_buf[] */
3953
3954 DWORD i;
3955 int c;
3956 int noread_cnt = 0;
3957 garray_T ga;
3958 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003959 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003960 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003961
3962 SECURITY_ATTRIBUTES saAttr;
3963
3964 /* Set the bInheritHandle flag so pipe handles are inherited. */
3965 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
3966 saAttr.bInheritHandle = TRUE;
3967 saAttr.lpSecurityDescriptor = NULL;
3968
3969 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
3970 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
3971 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
3972 /* Create a pipe for the child process's STDIN. */
3973 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
3974 /* Ensure the write handle to the pipe for STDIN is not inherited. */
3975 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
3976 {
3977 CloseHandle(g_hChildStd_IN_Rd);
3978 CloseHandle(g_hChildStd_IN_Wr);
3979 CloseHandle(g_hChildStd_OUT_Rd);
3980 CloseHandle(g_hChildStd_OUT_Wr);
3981 MSG_PUTS(_("\nCannot create pipes\n"));
3982 }
3983
3984 si.cb = sizeof(si);
3985 si.lpReserved = NULL;
3986 si.lpDesktop = NULL;
3987 si.lpTitle = NULL;
3988 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
3989
3990 /* set-up our file redirection */
3991 si.hStdError = g_hChildStd_OUT_Wr;
3992 si.hStdOutput = g_hChildStd_OUT_Wr;
3993 si.hStdInput = g_hChildStd_IN_Rd;
3994 si.wShowWindow = SW_HIDE;
3995 si.cbReserved2 = 0;
3996 si.lpReserved2 = NULL;
3997
3998 if (options & SHELL_READ)
3999 ga_init2(&ga, 1, BUFLEN);
4000
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004001 if (cmd != NULL)
4002 {
4003 p = (char *)vim_strsave((char_u *)cmd);
4004 if (p != NULL)
4005 unescape_shellxquote((char_u *)p, p_sxe);
4006 else
4007 p = cmd;
4008 }
4009
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004010 /* Now, run the command */
4011 CreateProcess(NULL, /* Executable name */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004012 p, /* Command to execute */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004013 NULL, /* Process security attributes */
4014 NULL, /* Thread security attributes */
4015
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004016 // this command can be litigious, handle inheritance was
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004017 // deactivated for pending temp file, but, if we deactivate
4018 // it, the pipes don't work for some reason.
4019 TRUE, /* Inherit handles, first deactivated,
4020 * but needed */
4021 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
4022 NULL, /* Environment */
4023 NULL, /* Current directory */
4024 &si, /* Startup information */
4025 &pi); /* Process information */
4026
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004027 if (p != cmd)
4028 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004029
4030 /* Close our unused side of the pipes */
4031 CloseHandle(g_hChildStd_IN_Rd);
4032 CloseHandle(g_hChildStd_OUT_Wr);
4033
4034 if (options & SHELL_WRITE)
4035 {
4036 HANDLE thread =
4037 CreateThread(NULL, /* security attributes */
4038 0, /* default stack size */
4039 sub_process_writer, /* function to be executed */
4040 g_hChildStd_IN_Wr, /* parameter */
4041 0, /* creation flag, start immediately */
4042 NULL); /* we don't care about thread id */
4043 CloseHandle(thread);
4044 g_hChildStd_IN_Wr = NULL;
4045 }
4046
4047 /* Keep updating the window while waiting for the shell to finish. */
4048 for (;;)
4049 {
4050 MSG msg;
4051
4052 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4053 {
4054 TranslateMessage(&msg);
4055 DispatchMessage(&msg);
4056 }
4057
4058 /* write pipe information in the window */
4059 if ((options & (SHELL_READ|SHELL_WRITE))
4060# ifdef FEAT_GUI
4061 || gui.in_use
4062# endif
4063 )
4064 {
4065 len = 0;
4066 if (!(options & SHELL_EXPAND)
4067 && ((options &
4068 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4069 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4070# ifdef FEAT_GUI
4071 || gui.in_use
4072# endif
4073 )
4074 && (ta_len > 0 || noread_cnt > 4))
4075 {
4076 if (ta_len == 0)
4077 {
4078 /* Get extra characters when we don't have any. Reset the
4079 * counter and timer. */
4080 noread_cnt = 0;
4081# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4082 gettimeofday(&start_tv, NULL);
4083# endif
4084 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4085 }
4086 if (ta_len > 0 || len > 0)
4087 {
4088 /*
4089 * For pipes: Check for CTRL-C: send interrupt signal to
4090 * child. Check for CTRL-D: EOF, close pipe to child.
4091 */
4092 if (len == 1 && cmd != NULL)
4093 {
4094 if (ta_buf[ta_len] == Ctrl_C)
4095 {
4096 /* Learn what exit code is expected, for
4097 * now put 9 as SIGKILL */
4098 TerminateProcess(pi.hProcess, 9);
4099 }
4100 if (ta_buf[ta_len] == Ctrl_D)
4101 {
4102 CloseHandle(g_hChildStd_IN_Wr);
4103 g_hChildStd_IN_Wr = NULL;
4104 }
4105 }
4106
4107 /* replace K_BS by <BS> and K_DEL by <DEL> */
4108 for (i = ta_len; i < ta_len + len; ++i)
4109 {
4110 if (ta_buf[i] == CSI && len - i > 2)
4111 {
4112 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4113 if (c == K_DEL || c == K_KDEL || c == K_BS)
4114 {
4115 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4116 (size_t)(len - i - 2));
4117 if (c == K_DEL || c == K_KDEL)
4118 ta_buf[i] = DEL;
4119 else
4120 ta_buf[i] = Ctrl_H;
4121 len -= 2;
4122 }
4123 }
4124 else if (ta_buf[i] == '\r')
4125 ta_buf[i] = '\n';
4126# ifdef FEAT_MBYTE
4127 if (has_mbyte)
4128 i += (*mb_ptr2len_len)(ta_buf + i,
4129 ta_len + len - i) - 1;
4130# endif
4131 }
4132
4133 /*
4134 * For pipes: echo the typed characters. For a pty this
4135 * does not seem to work.
4136 */
4137 for (i = ta_len; i < ta_len + len; ++i)
4138 {
4139 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4140 msg_putchar(ta_buf[i]);
4141# ifdef FEAT_MBYTE
4142 else if (has_mbyte)
4143 {
4144 int l = (*mb_ptr2len)(ta_buf + i);
4145
4146 msg_outtrans_len(ta_buf + i, l);
4147 i += l - 1;
4148 }
4149# endif
4150 else
4151 msg_outtrans_len(ta_buf + i, 1);
4152 }
4153 windgoto(msg_row, msg_col);
4154 out_flush();
4155
4156 ta_len += len;
4157
4158 /*
4159 * Write the characters to the child, unless EOF has been
4160 * typed for pipes. Write one character at a time, to
4161 * avoid losing too much typeahead. When writing buffer
4162 * lines, drop the typed characters (only check for
4163 * CTRL-C).
4164 */
4165 if (options & SHELL_WRITE)
4166 ta_len = 0;
4167 else if (g_hChildStd_IN_Wr != NULL)
4168 {
4169 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4170 1, &len, NULL);
4171 // if we are typing in, we want to keep things reactive
4172 delay = 1;
4173 if (len > 0)
4174 {
4175 ta_len -= len;
4176 mch_memmove(ta_buf, ta_buf + len, ta_len);
4177 }
4178 }
4179 }
4180 }
4181 }
4182
4183 if (ta_len)
4184 ui_inchar_undo(ta_buf, ta_len);
4185
4186 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4187 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004188 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004189 break;
4190 }
4191
4192 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004193 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004194
4195 /* We start waiting for a very short time and then increase it, so
4196 * that we respond quickly when the process is quick, and don't
4197 * consume too much overhead when it's slow. */
4198 if (delay < 50)
4199 delay += 10;
4200 }
4201
4202 /* Close the pipe */
4203 CloseHandle(g_hChildStd_OUT_Rd);
4204 if (g_hChildStd_IN_Wr != NULL)
4205 CloseHandle(g_hChildStd_IN_Wr);
4206
4207 WaitForSingleObject(pi.hProcess, INFINITE);
4208
4209 /* Get the command exit code */
4210 GetExitCodeProcess(pi.hProcess, &ret);
4211
4212 if (options & SHELL_READ)
4213 {
4214 if (ga.ga_len > 0)
4215 {
4216 append_ga_line(&ga);
4217 /* remember that the NL was missing */
4218 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4219 }
4220 else
4221 curbuf->b_no_eol_lnum = 0;
4222 ga_clear(&ga);
4223 }
4224
4225 /* Close the handles to the subprocess, so that it goes away */
4226 CloseHandle(pi.hThread);
4227 CloseHandle(pi.hProcess);
4228
4229 return ret;
4230}
4231
4232 static int
4233mch_system(char *cmd, int options)
4234{
4235 /* if we can pipe and the shelltemp option is off */
4236 if (allowPiping && !p_stmp)
4237 return mch_system_piped(cmd, options);
4238 else
4239 return mch_system_classic(cmd, options);
4240}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004241#else
4242
4243# define mch_system(c, o) system(c)
4244
4245#endif
4246
4247/*
4248 * Either execute a command by calling the shell or start a new shell
4249 */
4250 int
4251mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004252 char_u *cmd,
4253 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004254{
4255 int x = 0;
4256 int tmode = cur_tmode;
4257#ifdef FEAT_TITLE
4258 char szShellTitle[512];
4259
4260 /* Change the title to reflect that we are in a subshell. */
4261 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
4262 {
4263 if (cmd == NULL)
4264 strcat(szShellTitle, " :sh");
4265 else
4266 {
4267 strcat(szShellTitle, " - !");
4268 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4269 strcat(szShellTitle, cmd);
4270 }
4271 mch_settitle(szShellTitle, NULL);
4272 }
4273#endif
4274
4275 out_flush();
4276
4277#ifdef MCH_WRITE_DUMP
4278 if (fdDump)
4279 {
4280 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4281 fflush(fdDump);
4282 }
4283#endif
4284
4285 /*
4286 * Catch all deadly signals while running the external command, because a
4287 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4288 */
4289 signal(SIGINT, SIG_IGN);
4290#if defined(__GNUC__) && !defined(__MINGW32__)
4291 signal(SIGKILL, SIG_IGN);
4292#else
4293 signal(SIGBREAK, SIG_IGN);
4294#endif
4295 signal(SIGILL, SIG_IGN);
4296 signal(SIGFPE, SIG_IGN);
4297 signal(SIGSEGV, SIG_IGN);
4298 signal(SIGTERM, SIG_IGN);
4299 signal(SIGABRT, SIG_IGN);
4300
4301 if (options & SHELL_COOKED)
4302 settmode(TMODE_COOK); /* set to normal mode */
4303
4304 if (cmd == NULL)
4305 {
4306 x = mch_system(p_sh, options);
4307 }
4308 else
4309 {
4310 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004311 char_u *newcmd = NULL;
4312 char_u *cmdbase = cmd;
4313 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004314
4315 /* Skip a leading ", ( and "(. */
4316 if (*cmdbase == '"' )
4317 ++cmdbase;
4318 if (*cmdbase == '(')
4319 ++cmdbase;
4320
4321 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4322 {
4323 STARTUPINFO si;
4324 PROCESS_INFORMATION pi;
4325 DWORD flags = CREATE_NEW_CONSOLE;
4326 char_u *p;
4327
4328 si.cb = sizeof(si);
4329 si.lpReserved = NULL;
4330 si.lpDesktop = NULL;
4331 si.lpTitle = NULL;
4332 si.dwFlags = 0;
4333 si.cbReserved2 = 0;
4334 si.lpReserved2 = NULL;
4335
4336 cmdbase = skipwhite(cmdbase + 5);
4337 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4338 && vim_iswhite(cmdbase[4]))
4339 {
4340 cmdbase = skipwhite(cmdbase + 4);
4341 si.dwFlags = STARTF_USESHOWWINDOW;
4342 si.wShowWindow = SW_SHOWMINNOACTIVE;
4343 }
4344 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4345 && vim_iswhite(cmdbase[2]))
4346 {
4347 cmdbase = skipwhite(cmdbase + 2);
4348 flags = CREATE_NO_WINDOW;
4349 si.dwFlags = STARTF_USESTDHANDLES;
4350 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004351 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004352 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004353 NULL, // Security att.
4354 OPEN_EXISTING, // Open flags
4355 FILE_ATTRIBUTE_NORMAL, // File att.
4356 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004357 si.hStdOutput = si.hStdInput;
4358 si.hStdError = si.hStdInput;
4359 }
4360
4361 /* Remove a trailing ", ) and )" if they have a match
4362 * at the start of the command. */
4363 if (cmdbase > cmd)
4364 {
4365 p = cmdbase + STRLEN(cmdbase);
4366 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4367 *--p = NUL;
4368 if (p > cmdbase && p[-1] == ')'
4369 && (*cmd =='(' || cmd[1] == '('))
4370 *--p = NUL;
4371 }
4372
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004373 newcmd = cmdbase;
4374 unescape_shellxquote(cmdbase, p_sxe);
4375
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004376 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004377 * If creating new console, arguments are passed to the
4378 * 'cmd.exe' as-is. If it's not, arguments are not treated
4379 * correctly for current 'cmd.exe'. So unescape characters in
4380 * shellxescape except '|' for avoiding to be treated as
4381 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004382 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004383 if (flags != CREATE_NEW_CONSOLE)
4384 {
4385 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004386 char_u *cmd_shell = mch_getenv("COMSPEC");
4387
4388 if (cmd_shell == NULL || *cmd_shell == NUL)
4389 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004390
4391 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4392 if (subcmd != NULL)
4393 {
4394 /* make "cmd.exe /c arguments" */
4395 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004396 newcmd = lalloc(cmdlen, TRUE);
4397 if (newcmd != NULL)
4398 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004399 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004400 else
4401 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004402 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004403 }
4404 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004405
4406 /*
4407 * Now, start the command as a process, so that it doesn't
4408 * inherit our handles which causes unpleasant dangling swap
4409 * files if we exit before the spawned process
4410 */
4411 if (CreateProcess(NULL, // Executable name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004412 newcmd, // Command to execute
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004413 NULL, // Process security attributes
4414 NULL, // Thread security attributes
4415 FALSE, // Inherit handles
4416 flags, // Creation flags
4417 NULL, // Environment
4418 NULL, // Current directory
4419 &si, // Startup information
4420 &pi)) // Process information
4421 x = 0;
4422 else
4423 {
4424 x = -1;
4425#ifdef FEAT_GUI_W32
4426 EMSG(_("E371: Command not found"));
4427#endif
4428 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004429
4430 if (newcmd != cmdbase)
4431 vim_free(newcmd);
4432
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004433 if (si.hStdInput != NULL)
4434 {
4435 /* Close the handle to \\.\NUL */
4436 CloseHandle(si.hStdInput);
4437 }
4438 /* Close the handles to the subprocess, so that it goes away */
4439 CloseHandle(pi.hThread);
4440 CloseHandle(pi.hProcess);
4441 }
4442 else
4443 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004444 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004446 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004447#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004448 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4449
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004450 newcmd = lalloc(cmdlen, TRUE);
4451 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004452 {
4453#if defined(FEAT_GUI_W32)
4454 if (need_vimrun_warning)
4455 {
4456 MessageBox(NULL,
4457 _("VIMRUN.EXE not found in your $PATH.\n"
4458 "External commands will not pause after completion.\n"
4459 "See :help win32-vimrun for more information."),
4460 _("Vim Warning"),
4461 MB_ICONWARNING);
4462 need_vimrun_warning = FALSE;
4463 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004464 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004465 /* Use vimrun to execute the command. It opens a console
4466 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004467 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004468 vimrun_path,
4469 (msg_silent != 0 || (options & SHELL_DOOUT))
4470 ? "-s " : "",
4471 p_sh, p_shcf, cmd);
4472 else
4473#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004474 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004475 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004477 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004478 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479 }
4480 }
4481
4482 if (tmode == TMODE_RAW)
4483 settmode(TMODE_RAW); /* set to raw mode */
4484
4485 /* Print the return value, unless "vimrun" was used. */
4486 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4487#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004488 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4489 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004490#endif
4491 )
4492 {
4493 smsg(_("shell returned %d"), x);
4494 msg_putchar('\n');
4495 }
4496#ifdef FEAT_TITLE
4497 resettitle();
4498#endif
4499
4500 signal(SIGINT, SIG_DFL);
4501#if defined(__GNUC__) && !defined(__MINGW32__)
4502 signal(SIGKILL, SIG_DFL);
4503#else
4504 signal(SIGBREAK, SIG_DFL);
4505#endif
4506 signal(SIGILL, SIG_DFL);
4507 signal(SIGFPE, SIG_DFL);
4508 signal(SIGSEGV, SIG_DFL);
4509 signal(SIGTERM, SIG_DFL);
4510 signal(SIGABRT, SIG_DFL);
4511
4512 return x;
4513}
4514
4515
4516#ifndef FEAT_GUI_W32
4517
4518/*
4519 * Start termcap mode
4520 */
4521 static void
4522termcap_mode_start(void)
4523{
4524 DWORD cmodein;
4525
4526 if (g_fTermcapMode)
4527 return;
4528
4529 SaveConsoleBuffer(&g_cbNonTermcap);
4530
4531 if (g_cbTermcap.IsValid)
4532 {
4533 /*
4534 * We've been in termcap mode before. Restore certain screen
4535 * characteristics, including the buffer size and the window
4536 * size. Since we will be redrawing the screen, we don't need
4537 * to restore the actual contents of the buffer.
4538 */
4539 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4540 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4541 Rows = g_cbTermcap.Info.dwSize.Y;
4542 Columns = g_cbTermcap.Info.dwSize.X;
4543 }
4544 else
4545 {
4546 /*
4547 * This is our first time entering termcap mode. Clear the console
4548 * screen buffer, and resize the buffer to match the current window
4549 * size. We will use this as the size of our editing environment.
4550 */
4551 ClearConsoleBuffer(g_attrCurrent);
4552 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4553 }
4554
4555#ifdef FEAT_TITLE
4556 resettitle();
4557#endif
4558
4559 GetConsoleMode(g_hConIn, &cmodein);
4560#ifdef FEAT_MOUSE
4561 if (g_fMouseActive)
4562 cmodein |= ENABLE_MOUSE_INPUT;
4563 else
4564 cmodein &= ~ENABLE_MOUSE_INPUT;
4565#endif
4566 cmodein |= ENABLE_WINDOW_INPUT;
4567 SetConsoleMode(g_hConIn, cmodein);
4568
4569 redraw_later_clear();
4570 g_fTermcapMode = TRUE;
4571}
4572
4573
4574/*
4575 * End termcap mode
4576 */
4577 static void
4578termcap_mode_end(void)
4579{
4580 DWORD cmodein;
4581 ConsoleBuffer *cb;
4582 COORD coord;
4583 DWORD dwDummy;
4584
4585 if (!g_fTermcapMode)
4586 return;
4587
4588 SaveConsoleBuffer(&g_cbTermcap);
4589
4590 GetConsoleMode(g_hConIn, &cmodein);
4591 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4592 SetConsoleMode(g_hConIn, cmodein);
4593
4594#ifdef FEAT_RESTORE_ORIG_SCREEN
4595 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4596#else
4597 cb = &g_cbNonTermcap;
4598#endif
4599 RestoreConsoleBuffer(cb, p_rs);
4600 SetConsoleCursorInfo(g_hConOut, &g_cci);
4601
4602 if (p_rs || exiting)
4603 {
4604 /*
4605 * Clear anything that happens to be on the current line.
4606 */
4607 coord.X = 0;
4608 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4609 FillConsoleOutputCharacter(g_hConOut, ' ',
4610 cb->Info.dwSize.X, coord, &dwDummy);
4611 /*
4612 * The following is just for aesthetics. If we are exiting without
4613 * restoring the screen, then we want to have a prompt string
4614 * appear at the bottom line. However, the command interpreter
4615 * seems to always advance the cursor one line before displaying
4616 * the prompt string, which causes the screen to scroll. To
4617 * counter this, move the cursor up one line before exiting.
4618 */
4619 if (exiting && !p_rs)
4620 coord.Y--;
4621 /*
4622 * Position the cursor at the leftmost column of the desired row.
4623 */
4624 SetConsoleCursorPosition(g_hConOut, coord);
4625 }
4626
4627 g_fTermcapMode = FALSE;
4628}
4629#endif /* FEAT_GUI_W32 */
4630
4631
4632#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004633/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 void
4635mch_write(
4636 char_u *s,
4637 int len)
4638{
4639 /* never used */
4640}
4641
4642#else
4643
4644/*
4645 * clear `n' chars, starting from `coord'
4646 */
4647 static void
4648clear_chars(
4649 COORD coord,
4650 DWORD n)
4651{
4652 DWORD dwDummy;
4653
4654 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4655 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4656}
4657
4658
4659/*
4660 * Clear the screen
4661 */
4662 static void
4663clear_screen(void)
4664{
4665 g_coord.X = g_coord.Y = 0;
4666 clear_chars(g_coord, Rows * Columns);
4667}
4668
4669
4670/*
4671 * Clear to end of display
4672 */
4673 static void
4674clear_to_end_of_display(void)
4675{
4676 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4677 * Columns + (Columns - g_coord.X));
4678}
4679
4680
4681/*
4682 * Clear to end of line
4683 */
4684 static void
4685clear_to_end_of_line(void)
4686{
4687 clear_chars(g_coord, Columns - g_coord.X);
4688}
4689
4690
4691/*
4692 * Scroll the scroll region up by `cLines' lines
4693 */
4694 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004695scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004696{
4697 COORD oldcoord = g_coord;
4698
4699 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4700 delete_lines(cLines);
4701
4702 g_coord = oldcoord;
4703}
4704
4705
4706/*
4707 * Set the scroll region
4708 */
4709 static void
4710set_scroll_region(
4711 unsigned left,
4712 unsigned top,
4713 unsigned right,
4714 unsigned bottom)
4715{
4716 if (left >= right
4717 || top >= bottom
4718 || right > (unsigned) Columns - 1
4719 || bottom > (unsigned) Rows - 1)
4720 return;
4721
4722 g_srScrollRegion.Left = left;
4723 g_srScrollRegion.Top = top;
4724 g_srScrollRegion.Right = right;
4725 g_srScrollRegion.Bottom = bottom;
4726}
4727
4728
4729/*
4730 * Insert `cLines' lines at the current cursor position
4731 */
4732 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004733insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004734{
4735 SMALL_RECT source;
4736 COORD dest;
4737 CHAR_INFO fill;
4738
4739 dest.X = 0;
4740 dest.Y = g_coord.Y + cLines;
4741
4742 source.Left = 0;
4743 source.Top = g_coord.Y;
4744 source.Right = g_srScrollRegion.Right;
4745 source.Bottom = g_srScrollRegion.Bottom - cLines;
4746
4747 fill.Char.AsciiChar = ' ';
4748 fill.Attributes = g_attrCurrent;
4749
4750 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4751
4752 /* Here we have to deal with a win32 console flake: If the scroll
4753 * region looks like abc and we scroll c to a and fill with d we get
4754 * cbd... if we scroll block c one line at a time to a, we get cdd...
4755 * vim expects cdd consistently... So we have to deal with that
4756 * here... (this also occurs scrolling the same way in the other
4757 * direction). */
4758
4759 if (source.Bottom < dest.Y)
4760 {
4761 COORD coord;
4762
4763 coord.X = 0;
4764 coord.Y = source.Bottom;
4765 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4766 }
4767}
4768
4769
4770/*
4771 * Delete `cLines' lines at the current cursor position
4772 */
4773 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004774delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004775{
4776 SMALL_RECT source;
4777 COORD dest;
4778 CHAR_INFO fill;
4779 int nb;
4780
4781 dest.X = 0;
4782 dest.Y = g_coord.Y;
4783
4784 source.Left = 0;
4785 source.Top = g_coord.Y + cLines;
4786 source.Right = g_srScrollRegion.Right;
4787 source.Bottom = g_srScrollRegion.Bottom;
4788
4789 fill.Char.AsciiChar = ' ';
4790 fill.Attributes = g_attrCurrent;
4791
4792 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4793
4794 /* Here we have to deal with a win32 console flake: If the scroll
4795 * region looks like abc and we scroll c to a and fill with d we get
4796 * cbd... if we scroll block c one line at a time to a, we get cdd...
4797 * vim expects cdd consistently... So we have to deal with that
4798 * here... (this also occurs scrolling the same way in the other
4799 * direction). */
4800
4801 nb = dest.Y + (source.Bottom - source.Top) + 1;
4802
4803 if (nb < source.Top)
4804 {
4805 COORD coord;
4806
4807 coord.X = 0;
4808 coord.Y = nb;
4809 clear_chars(coord, Columns * (source.Top - nb));
4810 }
4811}
4812
4813
4814/*
4815 * Set the cursor position
4816 */
4817 static void
4818gotoxy(
4819 unsigned x,
4820 unsigned y)
4821{
4822 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4823 return;
4824
4825 /* external cursor coords are 1-based; internal are 0-based */
4826 g_coord.X = x - 1;
4827 g_coord.Y = y - 1;
4828 SetConsoleCursorPosition(g_hConOut, g_coord);
4829}
4830
4831
4832/*
4833 * Set the current text attribute = (foreground | background)
4834 * See ../doc/os_win32.txt for the numbers.
4835 */
4836 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004837textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004838{
4839 g_attrCurrent = wAttr;
4840
4841 SetConsoleTextAttribute(g_hConOut, wAttr);
4842}
4843
4844
4845 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004846textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847{
4848 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
4849
4850 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4851}
4852
4853
4854 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004855textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004856{
4857 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
4858
4859 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4860}
4861
4862
4863/*
4864 * restore the default text attribute (whatever we started with)
4865 */
4866 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004867normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868{
4869 textattr(g_attrDefault);
4870}
4871
4872
4873static WORD g_attrPreStandout = 0;
4874
4875/*
4876 * Make the text standout, by brightening it
4877 */
4878 static void
4879standout(void)
4880{
4881 g_attrPreStandout = g_attrCurrent;
4882 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
4883}
4884
4885
4886/*
4887 * Turn off standout mode
4888 */
4889 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004890standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004891{
4892 if (g_attrPreStandout)
4893 {
4894 textattr(g_attrPreStandout);
4895 g_attrPreStandout = 0;
4896 }
4897}
4898
4899
4900/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00004901 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004902 */
4903 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004904mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004905{
4906 char_u *p;
4907 int n;
4908
4909 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
4910 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
4911 if (T_ME[0] == ESC && T_ME[1] == '|')
4912 {
4913 p = T_ME + 2;
4914 n = getdigits(&p);
4915 if (*p == 'm' && n > 0)
4916 {
4917 cterm_normal_fg_color = (n & 0xf) + 1;
4918 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
4919 }
4920 }
4921}
4922
4923
4924/*
4925 * visual bell: flash the screen
4926 */
4927 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004928visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004929{
4930 COORD coordOrigin = {0, 0};
4931 WORD attrFlash = ~g_attrCurrent & 0xff;
4932
4933 DWORD dwDummy;
4934 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
4935
4936 if (oldattrs == NULL)
4937 return;
4938 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4939 coordOrigin, &dwDummy);
4940 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
4941 coordOrigin, &dwDummy);
4942
4943 Sleep(15); /* wait for 15 msec */
4944 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4945 coordOrigin, &dwDummy);
4946 vim_free(oldattrs);
4947}
4948
4949
4950/*
4951 * Make the cursor visible or invisible
4952 */
4953 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004954cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004955{
4956 s_cursor_visible = fVisible;
4957#ifdef MCH_CURSOR_SHAPE
4958 mch_update_cursor();
4959#endif
4960}
4961
4962
4963/*
4964 * write `cchToWrite' characters in `pchBuf' to the screen
4965 * Returns the number of characters actually written (at least one).
4966 */
4967 static BOOL
4968write_chars(
4969 LPCSTR pchBuf,
4970 DWORD cchToWrite)
4971{
4972 COORD coord = g_coord;
4973 DWORD written;
4974
4975 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
4976 coord, &written);
4977 /* When writing fails or didn't write a single character, pretend one
4978 * character was written, otherwise we get stuck. */
4979 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
4980 coord, &written) == 0
4981 || written == 0)
4982 written = 1;
4983
4984 g_coord.X += (SHORT) written;
4985
4986 while (g_coord.X > g_srScrollRegion.Right)
4987 {
4988 g_coord.X -= (SHORT) Columns;
4989 if (g_coord.Y < g_srScrollRegion.Bottom)
4990 g_coord.Y++;
4991 }
4992
4993 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4994
4995 return written;
4996}
4997
4998
4999/*
5000 * mch_write(): write the output buffer to the screen, translating ESC
5001 * sequences into calls to console output routines.
5002 */
5003 void
5004mch_write(
5005 char_u *s,
5006 int len)
5007{
5008 s[len] = NUL;
5009
5010 if (!term_console)
5011 {
5012 write(1, s, (unsigned)len);
5013 return;
5014 }
5015
5016 /* translate ESC | sequences into faked bios calls */
5017 while (len--)
5018 {
5019 /* optimization: use one single write_chars for runs of text,
5020 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005021 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005022
5023 if (p_wd)
5024 {
5025 WaitForChar(p_wd);
5026 if (prefix != 0)
5027 prefix = 1;
5028 }
5029
5030 if (prefix != 0)
5031 {
5032 DWORD nWritten;
5033
5034 nWritten = write_chars(s, prefix);
5035#ifdef MCH_WRITE_DUMP
5036 if (fdDump)
5037 {
5038 fputc('>', fdDump);
5039 fwrite(s, sizeof(char_u), nWritten, fdDump);
5040 fputs("<\n", fdDump);
5041 }
5042#endif
5043 len -= (nWritten - 1);
5044 s += nWritten;
5045 }
5046 else if (s[0] == '\n')
5047 {
5048 /* \n, newline: go to the beginning of the next line or scroll */
5049 if (g_coord.Y == g_srScrollRegion.Bottom)
5050 {
5051 scroll(1);
5052 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5053 }
5054 else
5055 {
5056 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5057 }
5058#ifdef MCH_WRITE_DUMP
5059 if (fdDump)
5060 fputs("\\n\n", fdDump);
5061#endif
5062 s++;
5063 }
5064 else if (s[0] == '\r')
5065 {
5066 /* \r, carriage return: go to beginning of line */
5067 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5068#ifdef MCH_WRITE_DUMP
5069 if (fdDump)
5070 fputs("\\r\n", fdDump);
5071#endif
5072 s++;
5073 }
5074 else if (s[0] == '\b')
5075 {
5076 /* \b, backspace: move cursor one position left */
5077 if (g_coord.X > g_srScrollRegion.Left)
5078 g_coord.X--;
5079 else if (g_coord.Y > g_srScrollRegion.Top)
5080 {
5081 g_coord.X = g_srScrollRegion.Right;
5082 g_coord.Y--;
5083 }
5084 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5085#ifdef MCH_WRITE_DUMP
5086 if (fdDump)
5087 fputs("\\b\n", fdDump);
5088#endif
5089 s++;
5090 }
5091 else if (s[0] == '\a')
5092 {
5093 /* \a, bell */
5094 MessageBeep(0xFFFFFFFF);
5095#ifdef MCH_WRITE_DUMP
5096 if (fdDump)
5097 fputs("\\a\n", fdDump);
5098#endif
5099 s++;
5100 }
5101 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5102 {
5103#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005104 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005105#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005106 char_u *p;
5107 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005108
5109 switch (s[2])
5110 {
5111 /* one or two numeric arguments, separated by ';' */
5112
5113 case '0': case '1': case '2': case '3': case '4':
5114 case '5': case '6': case '7': case '8': case '9':
5115 p = s + 2;
5116 arg1 = getdigits(&p); /* no check for length! */
5117 if (p > s + len)
5118 break;
5119
5120 if (*p == ';')
5121 {
5122 ++p;
5123 arg2 = getdigits(&p); /* no check for length! */
5124 if (p > s + len)
5125 break;
5126
5127 if (*p == 'H')
5128 gotoxy(arg2, arg1);
5129 else if (*p == 'r')
5130 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5131 }
5132 else if (*p == 'A')
5133 {
5134 /* move cursor up arg1 lines in same column */
5135 gotoxy(g_coord.X + 1,
5136 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5137 }
5138 else if (*p == 'C')
5139 {
5140 /* move cursor right arg1 columns in same line */
5141 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5142 g_coord.Y + 1);
5143 }
5144 else if (*p == 'H')
5145 {
5146 gotoxy(1, arg1);
5147 }
5148 else if (*p == 'L')
5149 {
5150 insert_lines(arg1);
5151 }
5152 else if (*p == 'm')
5153 {
5154 if (arg1 == 0)
5155 normvideo();
5156 else
5157 textattr((WORD) arg1);
5158 }
5159 else if (*p == 'f')
5160 {
5161 textcolor((WORD) arg1);
5162 }
5163 else if (*p == 'b')
5164 {
5165 textbackground((WORD) arg1);
5166 }
5167 else if (*p == 'M')
5168 {
5169 delete_lines(arg1);
5170 }
5171
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005172 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 s = p + 1;
5174 break;
5175
5176
5177 /* Three-character escape sequences */
5178
5179 case 'A':
5180 /* move cursor up one line in same column */
5181 gotoxy(g_coord.X + 1,
5182 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5183 goto got3;
5184
5185 case 'B':
5186 visual_bell();
5187 goto got3;
5188
5189 case 'C':
5190 /* move cursor right one column in same line */
5191 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5192 g_coord.Y + 1);
5193 goto got3;
5194
5195 case 'E':
5196 termcap_mode_end();
5197 goto got3;
5198
5199 case 'F':
5200 standout();
5201 goto got3;
5202
5203 case 'f':
5204 standend();
5205 goto got3;
5206
5207 case 'H':
5208 gotoxy(1, 1);
5209 goto got3;
5210
5211 case 'j':
5212 clear_to_end_of_display();
5213 goto got3;
5214
5215 case 'J':
5216 clear_screen();
5217 goto got3;
5218
5219 case 'K':
5220 clear_to_end_of_line();
5221 goto got3;
5222
5223 case 'L':
5224 insert_lines(1);
5225 goto got3;
5226
5227 case 'M':
5228 delete_lines(1);
5229 goto got3;
5230
5231 case 'S':
5232 termcap_mode_start();
5233 goto got3;
5234
5235 case 'V':
5236 cursor_visible(TRUE);
5237 goto got3;
5238
5239 case 'v':
5240 cursor_visible(FALSE);
5241 goto got3;
5242
5243 got3:
5244 s += 3;
5245 len -= 2;
5246 }
5247
5248#ifdef MCH_WRITE_DUMP
5249 if (fdDump)
5250 {
5251 fputs("ESC | ", fdDump);
5252 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5253 fputc('\n', fdDump);
5254 }
5255#endif
5256 }
5257 else
5258 {
5259 /* Write a single character */
5260 DWORD nWritten;
5261
5262 nWritten = write_chars(s, 1);
5263#ifdef MCH_WRITE_DUMP
5264 if (fdDump)
5265 {
5266 fputc('>', fdDump);
5267 fwrite(s, sizeof(char_u), nWritten, fdDump);
5268 fputs("<\n", fdDump);
5269 }
5270#endif
5271
5272 len -= (nWritten - 1);
5273 s += nWritten;
5274 }
5275 }
5276
5277#ifdef MCH_WRITE_DUMP
5278 if (fdDump)
5279 fflush(fdDump);
5280#endif
5281}
5282
5283#endif /* FEAT_GUI_W32 */
5284
5285
5286/*
5287 * Delay for half a second.
5288 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005289/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005290 void
5291mch_delay(
5292 long msec,
5293 int ignoreinput)
5294{
5295#ifdef FEAT_GUI_W32
5296 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005297#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005298 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005299# ifdef FEAT_MZSCHEME
5300 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5301 {
5302 int towait = p_mzq;
5303
5304 /* if msec is large enough, wait by portions in p_mzq */
5305 while (msec > 0)
5306 {
5307 mzvim_check_threads();
5308 if (msec < towait)
5309 towait = msec;
5310 Sleep(towait);
5311 msec -= towait;
5312 }
5313 }
5314 else
5315# endif
5316 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005317 else
5318 WaitForChar(msec);
5319#endif
5320}
5321
5322
5323/*
5324 * this version of remove is not scared by a readonly (backup) file
5325 * Return 0 for success, -1 for failure.
5326 */
5327 int
5328mch_remove(char_u *name)
5329{
5330#ifdef FEAT_MBYTE
5331 WCHAR *wn = NULL;
5332 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005333#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005334
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005335 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5336
5337#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005338 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5339 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005340 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005341 if (wn != NULL)
5342 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005343 n = DeleteFileW(wn) ? 0 : -1;
5344 vim_free(wn);
5345 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5346 return n;
5347 /* Retry with non-wide function (for Windows 98). */
5348 }
5349 }
5350#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005351 return DeleteFile(name) ? 0 : -1;
5352}
5353
5354
5355/*
5356 * check for an "interrupt signal": CTRL-break or CTRL-C
5357 */
5358 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005359mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005360{
5361#ifndef FEAT_GUI_W32 /* never used */
5362 if (g_fCtrlCPressed || g_fCBrkPressed)
5363 {
5364 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5365 got_int = TRUE;
5366 }
5367#endif
5368}
5369
5370
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371#ifdef FEAT_MBYTE
5372/*
5373 * Same code as below, but with wide functions and no comments.
5374 * Return 0 for success, non-zero for failure.
5375 */
5376 int
5377mch_wrename(WCHAR *wold, WCHAR *wnew)
5378{
5379 WCHAR *p;
5380 int i;
5381 WCHAR szTempFile[_MAX_PATH + 1];
5382 WCHAR szNewPath[_MAX_PATH + 1];
5383 HANDLE hf;
5384
5385 if (!mch_windows95())
5386 {
5387 p = wold;
5388 for (i = 0; wold[i] != NUL; ++i)
5389 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5390 && wold[i + 1] != 0)
5391 p = wold + i + 1;
5392 if ((int)(wold + i - p) < 8 || p[6] != '~')
5393 return (MoveFileW(wold, wnew) == 0);
5394 }
5395
5396 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5397 return -1;
5398 *p = NUL;
5399
5400 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5401 return -2;
5402
5403 if (!DeleteFileW(szTempFile))
5404 return -3;
5405
5406 if (!MoveFileW(wold, szTempFile))
5407 return -4;
5408
5409 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5410 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5411 return -5;
5412 if (!CloseHandle(hf))
5413 return -6;
5414
5415 if (!MoveFileW(szTempFile, wnew))
5416 {
5417 (void)MoveFileW(szTempFile, wold);
5418 return -7;
5419 }
5420
5421 DeleteFileW(szTempFile);
5422
5423 if (!DeleteFileW(wold))
5424 return -8;
5425
5426 return 0;
5427}
5428#endif
5429
5430
5431/*
5432 * mch_rename() works around a bug in rename (aka MoveFile) in
5433 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5434 * file whose short file name is "FOO.BAR" (its long file name will
5435 * be correct: "foo.bar~"). Because a file can be accessed by
5436 * either its SFN or its LFN, "foo.bar" has effectively been
5437 * renamed to "foo.bar", which is not at all what was wanted. This
5438 * seems to happen only when renaming files with three-character
5439 * extensions by appending a suffix that does not include ".".
5440 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5441 *
5442 * There is another problem, which isn't really a bug but isn't right either:
5443 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5444 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5445 * service pack 6. Doesn't seem to happen on Windows 98.
5446 *
5447 * Like rename(), returns 0 upon success, non-zero upon failure.
5448 * Should probably set errno appropriately when errors occur.
5449 */
5450 int
5451mch_rename(
5452 const char *pszOldFile,
5453 const char *pszNewFile)
5454{
5455 char szTempFile[_MAX_PATH+1];
5456 char szNewPath[_MAX_PATH+1];
5457 char *pszFilePart;
5458 HANDLE hf;
5459#ifdef FEAT_MBYTE
5460 WCHAR *wold = NULL;
5461 WCHAR *wnew = NULL;
5462 int retval = -1;
5463
5464 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5465 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005466 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5467 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005468 if (wold != NULL && wnew != NULL)
5469 retval = mch_wrename(wold, wnew);
5470 vim_free(wold);
5471 vim_free(wnew);
5472 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5473 return retval;
5474 /* Retry with non-wide function (for Windows 98). */
5475 }
5476#endif
5477
5478 /*
5479 * No need to play tricks if not running Windows 95, unless the file name
5480 * contains a "~" as the seventh character.
5481 */
5482 if (!mch_windows95())
5483 {
5484 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5485 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5486 return rename(pszOldFile, pszNewFile);
5487 }
5488
5489 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5490 * a directory, no error is returned and pszFilePart will be NULL. */
5491 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5492 || pszFilePart == NULL)
5493 return -1;
5494 *pszFilePart = NUL;
5495
5496 /* Get (and create) a unique temporary file name in directory of new file */
5497 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5498 return -2;
5499
5500 /* blow the temp file away */
5501 if (!DeleteFile(szTempFile))
5502 return -3;
5503
5504 /* rename old file to the temp file */
5505 if (!MoveFile(pszOldFile, szTempFile))
5506 return -4;
5507
5508 /* now create an empty file called pszOldFile; this prevents the operating
5509 * system using pszOldFile as an alias (SFN) if we're renaming within the
5510 * same directory. For example, we're editing a file called
5511 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5512 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5513 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005514 * cause all sorts of problems later in buf_write(). So, we create an
5515 * empty file called filena~1.txt and the system will have to find some
5516 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005517 */
5518 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5519 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5520 return -5;
5521 if (!CloseHandle(hf))
5522 return -6;
5523
5524 /* rename the temp file to the new file */
5525 if (!MoveFile(szTempFile, pszNewFile))
5526 {
5527 /* Renaming failed. Rename the file back to its old name, so that it
5528 * looks like nothing happened. */
5529 (void)MoveFile(szTempFile, pszOldFile);
5530
5531 return -7;
5532 }
5533
5534 /* Seems to be left around on Novell filesystems */
5535 DeleteFile(szTempFile);
5536
5537 /* finally, remove the empty old file */
5538 if (!DeleteFile(pszOldFile))
5539 return -8;
5540
5541 return 0; /* success */
5542}
5543
5544/*
5545 * Get the default shell for the current hardware platform
5546 */
5547 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005548default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005549{
5550 char* psz = NULL;
5551
5552 PlatformId();
5553
5554 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5555 psz = "cmd.exe";
5556 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5557 psz = "command.com";
5558
5559 return psz;
5560}
5561
5562/*
5563 * mch_access() extends access() to do more detailed check on network drives.
5564 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5565 */
5566 int
5567mch_access(char *n, int p)
5568{
5569 HANDLE hFile;
5570 DWORD am;
5571 int retval = -1; /* default: fail */
5572#ifdef FEAT_MBYTE
5573 WCHAR *wn = NULL;
5574
5575 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005576 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577#endif
5578
5579 if (mch_isdir(n))
5580 {
5581 char TempName[_MAX_PATH + 16] = "";
5582#ifdef FEAT_MBYTE
5583 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5584#endif
5585
5586 if (p & R_OK)
5587 {
5588 /* Read check is performed by seeing if we can do a find file on
5589 * the directory for any file. */
5590#ifdef FEAT_MBYTE
5591 if (wn != NULL)
5592 {
5593 int i;
5594 WIN32_FIND_DATAW d;
5595
5596 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5597 TempNameW[i] = wn[i];
5598 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5599 TempNameW[i++] = '\\';
5600 TempNameW[i++] = '*';
5601 TempNameW[i++] = 0;
5602
5603 hFile = FindFirstFileW(TempNameW, &d);
5604 if (hFile == INVALID_HANDLE_VALUE)
5605 {
5606 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5607 goto getout;
5608
5609 /* Retry with non-wide function (for Windows 98). */
5610 vim_free(wn);
5611 wn = NULL;
5612 }
5613 else
5614 (void)FindClose(hFile);
5615 }
5616 if (wn == NULL)
5617#endif
5618 {
5619 char *pch;
5620 WIN32_FIND_DATA d;
5621
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005622 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005623 pch = TempName + STRLEN(TempName) - 1;
5624 if (*pch != '\\' && *pch != '/')
5625 *++pch = '\\';
5626 *++pch = '*';
5627 *++pch = NUL;
5628
5629 hFile = FindFirstFile(TempName, &d);
5630 if (hFile == INVALID_HANDLE_VALUE)
5631 goto getout;
5632 (void)FindClose(hFile);
5633 }
5634 }
5635
5636 if (p & W_OK)
5637 {
5638 /* Trying to create a temporary file in the directory should catch
5639 * directories on read-only network shares. However, in
5640 * directories whose ACL allows writes but denies deletes will end
5641 * up keeping the temporary file :-(. */
5642#ifdef FEAT_MBYTE
5643 if (wn != NULL)
5644 {
5645 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5646 {
5647 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5648 goto getout;
5649
5650 /* Retry with non-wide function (for Windows 98). */
5651 vim_free(wn);
5652 wn = NULL;
5653 }
5654 else
5655 DeleteFileW(TempNameW);
5656 }
5657 if (wn == NULL)
5658#endif
5659 {
5660 if (!GetTempFileName(n, "VIM", 0, TempName))
5661 goto getout;
5662 mch_remove((char_u *)TempName);
5663 }
5664 }
5665 }
5666 else
5667 {
5668 /* Trying to open the file for the required access does ACL, read-only
5669 * network share, and file attribute checks. */
5670 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5671 | ((p & R_OK) ? GENERIC_READ : 0);
5672#ifdef FEAT_MBYTE
5673 if (wn != NULL)
5674 {
5675 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5676 if (hFile == INVALID_HANDLE_VALUE
5677 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5678 {
5679 /* Retry with non-wide function (for Windows 98). */
5680 vim_free(wn);
5681 wn = NULL;
5682 }
5683 }
5684 if (wn == NULL)
5685#endif
5686 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5687 if (hFile == INVALID_HANDLE_VALUE)
5688 goto getout;
5689 CloseHandle(hFile);
5690 }
5691
5692 retval = 0; /* success */
5693getout:
5694#ifdef FEAT_MBYTE
5695 vim_free(wn);
5696#endif
5697 return retval;
5698}
5699
5700#if defined(FEAT_MBYTE) || defined(PROTO)
5701/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005702 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703 */
5704 int
5705mch_open(char *name, int flags, int mode)
5706{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005707 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5708# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005709 WCHAR *wn;
5710 int f;
5711
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005712 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005713 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005714 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005715 if (wn != NULL)
5716 {
5717 f = _wopen(wn, flags, mode);
5718 vim_free(wn);
5719 if (f >= 0)
5720 return f;
5721 /* Retry with non-wide function (for Windows 98). Can't use
5722 * GetLastError() here and it's unclear what errno gets set to if
5723 * the _wopen() fails for missing wide functions. */
5724 }
5725 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005726# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005727
5728 return open(name, flags, mode);
5729}
5730
5731/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005732 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733 */
5734 FILE *
5735mch_fopen(char *name, char *mode)
5736{
5737 WCHAR *wn, *wm;
5738 FILE *f = NULL;
5739
5740 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5741# ifdef __BORLANDC__
5742 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5743 && g_PlatformId == VER_PLATFORM_WIN32_NT
5744# endif
5745 )
5746 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005747# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005748 /* Work around an annoying assertion in the Microsoft debug CRT
5749 * when mode's text/binary setting doesn't match _get_fmode(). */
5750 char newMode = mode[strlen(mode) - 1];
5751 int oldMode = 0;
5752
5753 _get_fmode(&oldMode);
5754 if (newMode == 't')
5755 _set_fmode(_O_TEXT);
5756 else if (newMode == 'b')
5757 _set_fmode(_O_BINARY);
5758# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005759 wn = enc_to_utf16(name, NULL);
5760 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005761 if (wn != NULL && wm != NULL)
5762 f = _wfopen(wn, wm);
5763 vim_free(wn);
5764 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005765
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005766# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005767 _set_fmode(oldMode);
5768# endif
5769
Bram Moolenaar071d4272004-06-13 20:20:40 +00005770 if (f != NULL)
5771 return f;
5772 /* Retry with non-wide function (for Windows 98). Can't use
5773 * GetLastError() here and it's unclear what errno gets set to if
5774 * the _wfopen() fails for missing wide functions. */
5775 }
5776
5777 return fopen(name, mode);
5778}
5779#endif
5780
5781#ifdef FEAT_MBYTE
5782/*
5783 * SUB STREAM (aka info stream) handling:
5784 *
5785 * NTFS can have sub streams for each file. Normal contents of file is
5786 * stored in the main stream, and extra contents (author information and
5787 * title and so on) can be stored in sub stream. After Windows 2000, user
5788 * can access and store those informations in sub streams via explorer's
5789 * property menuitem in right click menu. Those informations in sub streams
5790 * were lost when copying only the main stream. So we have to copy sub
5791 * streams.
5792 *
5793 * Incomplete explanation:
5794 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5795 * More useful info and an example:
5796 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5797 */
5798
5799/*
5800 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5801 * and write to stream "substream" of file "to".
5802 * Errors are ignored.
5803 */
5804 static void
5805copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5806{
5807 HANDLE hTo;
5808 WCHAR *to_name;
5809
5810 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5811 wcscpy(to_name, to);
5812 wcscat(to_name, substream);
5813
5814 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5815 FILE_ATTRIBUTE_NORMAL, NULL);
5816 if (hTo != INVALID_HANDLE_VALUE)
5817 {
5818 long done;
5819 DWORD todo;
5820 DWORD readcnt, written;
5821 char buf[4096];
5822
5823 /* Copy block of bytes at a time. Abort when something goes wrong. */
5824 for (done = 0; done < len; done += written)
5825 {
5826 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005827 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5828 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005829 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5830 FALSE, FALSE, context)
5831 || readcnt != todo
5832 || !WriteFile(hTo, buf, todo, &written, NULL)
5833 || written != todo)
5834 break;
5835 }
5836 CloseHandle(hTo);
5837 }
5838
5839 free(to_name);
5840}
5841
5842/*
5843 * Copy info streams from file "from" to file "to".
5844 */
5845 static void
5846copy_infostreams(char_u *from, char_u *to)
5847{
5848 WCHAR *fromw;
5849 WCHAR *tow;
5850 HANDLE sh;
5851 WIN32_STREAM_ID sid;
5852 int headersize;
5853 WCHAR streamname[_MAX_PATH];
5854 DWORD readcount;
5855 void *context = NULL;
5856 DWORD lo, hi;
5857 int len;
5858
5859 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005860 fromw = enc_to_utf16(from, NULL);
5861 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 if (fromw != NULL && tow != NULL)
5863 {
5864 /* Open the file for reading. */
5865 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
5866 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5867 if (sh != INVALID_HANDLE_VALUE)
5868 {
5869 /* Use BackupRead() to find the info streams. Repeat until we
5870 * have done them all.*/
5871 for (;;)
5872 {
5873 /* Get the header to find the length of the stream name. If
5874 * the "readcount" is zero we have done all info streams. */
5875 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005876 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005877 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
5878 &readcount, FALSE, FALSE, &context)
5879 || readcount == 0)
5880 break;
5881
5882 /* We only deal with streams that have a name. The normal
5883 * file data appears to be without a name, even though docs
5884 * suggest it is called "::$DATA". */
5885 if (sid.dwStreamNameSize > 0)
5886 {
5887 /* Read the stream name. */
5888 if (!BackupRead(sh, (LPBYTE)streamname,
5889 sid.dwStreamNameSize,
5890 &readcount, FALSE, FALSE, &context))
5891 break;
5892
5893 /* Copy an info stream with a name ":anything:$DATA".
5894 * Skip "::$DATA", it has no stream name (examples suggest
5895 * it might be used for the normal file contents).
5896 * Note that BackupRead() counts bytes, but the name is in
5897 * wide characters. */
5898 len = readcount / sizeof(WCHAR);
5899 streamname[len] = 0;
5900 if (len > 7 && wcsicmp(streamname + len - 6,
5901 L":$DATA") == 0)
5902 {
5903 streamname[len - 6] = 0;
5904 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00005905 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005906 }
5907 }
5908
5909 /* Advance to the next stream. We might try seeking too far,
5910 * but BackupSeek() doesn't skip over stream borders, thus
5911 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005912 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005913 &lo, &hi, &context);
5914 }
5915
5916 /* Clear the context. */
5917 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
5918
5919 CloseHandle(sh);
5920 }
5921 }
5922 vim_free(fromw);
5923 vim_free(tow);
5924}
5925#endif
5926
5927/*
5928 * Copy file attributes from file "from" to file "to".
5929 * For Windows NT and later we copy info streams.
5930 * Always returns zero, errors are ignored.
5931 */
5932 int
5933mch_copy_file_attribute(char_u *from, char_u *to)
5934{
5935#ifdef FEAT_MBYTE
5936 /* File streams only work on Windows NT and later. */
5937 PlatformId();
5938 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5939 copy_infostreams(from, to);
5940#endif
5941 return 0;
5942}
5943
5944#if defined(MYRESETSTKOFLW) || defined(PROTO)
5945/*
5946 * Recreate a destroyed stack guard page in win32.
5947 * Written by Benjamin Peterson.
5948 */
5949
5950/* These magic numbers are from the MS header files */
5951#define MIN_STACK_WIN9X 17
5952#define MIN_STACK_WINNT 2
5953
5954/*
5955 * This function does the same thing as _resetstkoflw(), which is only
5956 * available in DevStudio .net and later.
5957 * Returns 0 for failure, 1 for success.
5958 */
5959 int
5960myresetstkoflw(void)
5961{
5962 BYTE *pStackPtr;
5963 BYTE *pGuardPage;
5964 BYTE *pStackBase;
5965 BYTE *pLowestPossiblePage;
5966 MEMORY_BASIC_INFORMATION mbi;
5967 SYSTEM_INFO si;
5968 DWORD nPageSize;
5969 DWORD dummy;
5970
5971 /* This code will not work on win32s. */
5972 PlatformId();
5973 if (g_PlatformId == VER_PLATFORM_WIN32s)
5974 return 0;
5975
5976 /* We need to know the system page size. */
5977 GetSystemInfo(&si);
5978 nPageSize = si.dwPageSize;
5979
5980 /* ...and the current stack pointer */
5981 pStackPtr = (BYTE*)_alloca(1);
5982
5983 /* ...and the base of the stack. */
5984 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
5985 return 0;
5986 pStackBase = (BYTE*)mbi.AllocationBase;
5987
5988 /* ...and the page thats min_stack_req pages away from stack base; this is
5989 * the lowest page we could use. */
5990 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
5991 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
5992
5993 /* On Win95, we want the next page down from the end of the stack. */
5994 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
5995 {
5996 /* Find the page that's only 1 page down from the page that the stack
5997 * ptr is in. */
5998 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
5999 / (DWORD)nPageSize) - 1));
6000 if (pGuardPage < pLowestPossiblePage)
6001 return 0;
6002
6003 /* Apply the noaccess attribute to the page -- there's no guard
6004 * attribute in win95-type OSes. */
6005 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6006 return 0;
6007 }
6008 else
6009 {
6010 /* On NT, however, we want the first committed page in the stack Start
6011 * at the stack base and move forward through memory until we find a
6012 * committed block. */
6013 BYTE *pBlock = pStackBase;
6014
Bram Moolenaara466c992005-07-09 21:03:22 +00006015 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006016 {
6017 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6018 return 0;
6019
6020 pBlock += mbi.RegionSize;
6021
6022 if (mbi.State & MEM_COMMIT)
6023 break;
6024 }
6025
6026 /* mbi now describes the first committed block in the stack. */
6027 if (mbi.Protect & PAGE_GUARD)
6028 return 1;
6029
6030 /* decide where the guard page should start */
6031 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6032 pGuardPage = pLowestPossiblePage;
6033 else
6034 pGuardPage = (BYTE*)mbi.BaseAddress;
6035
6036 /* allocate the guard page */
6037 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6038 return 0;
6039
6040 /* apply the guard attribute to the page */
6041 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6042 &dummy))
6043 return 0;
6044 }
6045
6046 return 1;
6047}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006048#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006049
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006050
6051#if defined(FEAT_MBYTE) || defined(PROTO)
6052/*
6053 * The command line arguments in UCS2
6054 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006055static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006056static LPWSTR *ArglistW = NULL;
6057static int global_argc = 0;
6058static char **global_argv;
6059
6060static int used_file_argc = 0; /* last argument in global_argv[] used
6061 for the argument list. */
6062static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6063 command line arguments added to
6064 the argument list */
6065static int used_file_count = 0; /* nr of entries in used_file_indexes */
6066static int used_file_literal = FALSE; /* take file names literally */
6067static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006068static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006069static int used_alist_count = 0;
6070
6071
6072/*
6073 * Get the command line arguments. Unicode version.
6074 * Returns argc. Zero when something fails.
6075 */
6076 int
6077get_cmd_argsW(char ***argvp)
6078{
6079 char **argv = NULL;
6080 int argc = 0;
6081 int i;
6082
6083 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6084 if (ArglistW != NULL)
6085 {
6086 argv = malloc((nArgsW + 1) * sizeof(char *));
6087 if (argv != NULL)
6088 {
6089 argc = nArgsW;
6090 argv[argc] = NULL;
6091 for (i = 0; i < argc; ++i)
6092 {
6093 int len;
6094
6095 /* Convert each Unicode argument to the current codepage. */
6096 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006097 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006098 (LPSTR *)&argv[i], &len, 0, 0);
6099 if (argv[i] == NULL)
6100 {
6101 /* Out of memory, clear everything. */
6102 while (i > 0)
6103 free(argv[--i]);
6104 free(argv);
6105 argc = 0;
6106 }
6107 }
6108 }
6109 }
6110
6111 global_argc = argc;
6112 global_argv = argv;
6113 if (argc > 0)
6114 used_file_indexes = malloc(argc * sizeof(int));
6115
6116 if (argvp != NULL)
6117 *argvp = argv;
6118 return argc;
6119}
6120
6121 void
6122free_cmd_argsW(void)
6123{
6124 if (ArglistW != NULL)
6125 {
6126 GlobalFree(ArglistW);
6127 ArglistW = NULL;
6128 }
6129}
6130
6131/*
6132 * Remember "name" is an argument that was added to the argument list.
6133 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6134 * is called.
6135 */
6136 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006137used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006138{
6139 int i;
6140
6141 if (used_file_indexes == NULL)
6142 return;
6143 for (i = used_file_argc + 1; i < global_argc; ++i)
6144 if (STRCMP(global_argv[i], name) == 0)
6145 {
6146 used_file_argc = i;
6147 used_file_indexes[used_file_count++] = i;
6148 break;
6149 }
6150 used_file_literal = literal;
6151 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006152 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006153}
6154
6155/*
6156 * Remember the length of the argument list as it was. If it changes then we
6157 * leave it alone when 'encoding' is set.
6158 */
6159 void
6160set_alist_count(void)
6161{
6162 used_alist_count = GARGCOUNT;
6163}
6164
6165/*
6166 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6167 * has been changed while starting up. Use the UCS-2 command line arguments
6168 * and convert them to 'encoding'.
6169 */
6170 void
6171fix_arg_enc(void)
6172{
6173 int i;
6174 int idx;
6175 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006176 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006177
6178 /* Safety checks:
6179 * - if argument count differs between the wide and non-wide argument
6180 * list, something must be wrong.
6181 * - the file name arguments must have been located.
6182 * - the length of the argument list wasn't changed by the user.
6183 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006184 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006185 || ArglistW == NULL
6186 || used_file_indexes == NULL
6187 || used_file_count == 0
6188 || used_alist_count != GARGCOUNT)
6189 return;
6190
Bram Moolenaar86b68352004-12-27 21:59:20 +00006191 /* Remember the buffer numbers for the arguments. */
6192 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6193 if (fnum_list == NULL)
6194 return; /* out of memory */
6195 for (i = 0; i < GARGCOUNT; ++i)
6196 fnum_list[i] = GARGLIST[i].ae_fnum;
6197
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006198 /* Clear the argument list. Make room for the new arguments. */
6199 alist_clear(&global_alist);
6200 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006201 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006202
6203 for (i = 0; i < used_file_count; ++i)
6204 {
6205 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006206 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006207 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006208 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006209#ifdef FEAT_DIFF
6210 /* When using diff mode may need to concatenate file name to
6211 * directory name. Just like it's done in main(). */
6212 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6213 && !mch_isdir(alist_name(&GARGLIST[0])))
6214 {
6215 char_u *r;
6216
6217 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6218 if (r != NULL)
6219 {
6220 vim_free(str);
6221 str = r;
6222 }
6223 }
6224#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006225 /* Re-use the old buffer by renaming it. When not using literal
6226 * names it's done by alist_expand() below. */
6227 if (used_file_literal)
6228 buf_set_name(fnum_list[i], str);
6229
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006230 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006231 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006232 }
6233
6234 if (!used_file_literal)
6235 {
6236 /* Now expand wildcards in the arguments. */
6237 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6238 * filename characters but are excluded from 'isfname' to make
6239 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6240 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006241 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006242 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6243 }
6244
6245 /* If wildcard expansion failed, we are editing the first file of the
6246 * arglist and there is no file name: Edit the first argument now. */
6247 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6248 {
6249 do_cmdline_cmd((char_u *)":rewind");
6250 if (GARGCOUNT == 1 && used_file_full_path)
6251 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6252 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006253
6254 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006255}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006256#endif