blob: db3c794dabfbb3a8b039bd94a4cd4129d9f56f72 [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 {
1360 /* If the specified wait time has passed, return. */
1361 dwNow = GetTickCount();
1362 if (dwNow >= dwEndTime)
1363 break;
1364 }
1365 if (msec != 0)
1366 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001367 DWORD dwWaitTime = dwEndTime - dwNow;
1368
1369#ifdef FEAT_MZSCHEME
1370 if (mzthreads_allowed() && p_mzq > 0
1371 && (msec < 0 || (long)dwWaitTime > p_mzq))
1372 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1373#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001374#ifdef FEAT_CLIENTSERVER
1375 /* Wait for either an event on the console input or a message in
1376 * the client-server window. */
1377 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001378 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001379#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001380 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001381#endif
1382 continue;
1383 }
1384
1385 cRecords = 0;
1386 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1387
1388#ifdef FEAT_MBYTE_IME
1389 if (State & CMDLINE && msg_row == Rows - 1)
1390 {
1391 CONSOLE_SCREEN_BUFFER_INFO csbi;
1392
1393 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1394 {
1395 if (csbi.dwCursorPosition.Y != msg_row)
1396 {
1397 /* The screen is now messed up, must redraw the
1398 * command line and later all the windows. */
1399 redraw_all_later(CLEAR);
1400 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1401 redrawcmd();
1402 }
1403 }
1404 }
1405#endif
1406
1407 if (cRecords > 0)
1408 {
1409 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1410 {
1411#ifdef FEAT_MBYTE_IME
1412 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1413 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1414 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1415 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1416 {
1417 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1418 continue;
1419 }
1420#endif
1421 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1422 NULL, FALSE))
1423 return TRUE;
1424 }
1425
1426 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1427
1428 if (ir.EventType == FOCUS_EVENT)
1429 handle_focus_event(ir);
1430 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1431 shell_resized();
1432#ifdef FEAT_MOUSE
1433 else if (ir.EventType == MOUSE_EVENT
1434 && decode_mouse_event(&ir.Event.MouseEvent))
1435 return TRUE;
1436#endif
1437 }
1438 else if (msec == 0)
1439 break;
1440 }
1441
1442#ifdef FEAT_CLIENTSERVER
1443 /* Something might have been received while we were waiting. */
1444 if (input_available())
1445 return TRUE;
1446#endif
1447 return FALSE;
1448}
1449
1450#ifndef FEAT_GUI_MSWIN
1451/*
1452 * return non-zero if a character is available
1453 */
1454 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001455mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001456{
1457 return WaitForChar(0L);
1458}
1459#endif
1460
1461/*
1462 * Create the console input. Used when reading stdin doesn't work.
1463 */
1464 static void
1465create_conin(void)
1466{
1467 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1468 FILE_SHARE_READ|FILE_SHARE_WRITE,
1469 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001470 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001471 did_create_conin = TRUE;
1472}
1473
1474/*
1475 * Get a keystroke or a mouse event
1476 */
1477 static char_u
1478tgetch(int *pmodifiers, char_u *pch2)
1479{
1480 char_u ch;
1481
1482 for (;;)
1483 {
1484 INPUT_RECORD ir;
1485 DWORD cRecords = 0;
1486
1487#ifdef FEAT_CLIENTSERVER
1488 (void)WaitForChar(-1L);
1489 if (input_available())
1490 return 0;
1491# ifdef FEAT_MOUSE
1492 if (g_nMouseClick != -1)
1493 return 0;
1494# endif
1495#endif
1496 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1497 {
1498 if (did_create_conin)
1499 read_error_exit();
1500 create_conin();
1501 continue;
1502 }
1503
1504 if (ir.EventType == KEY_EVENT)
1505 {
1506 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1507 pmodifiers, TRUE))
1508 return ch;
1509 }
1510 else if (ir.EventType == FOCUS_EVENT)
1511 handle_focus_event(ir);
1512 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1513 shell_resized();
1514#ifdef FEAT_MOUSE
1515 else if (ir.EventType == MOUSE_EVENT)
1516 {
1517 if (decode_mouse_event(&ir.Event.MouseEvent))
1518 return 0;
1519 }
1520#endif
1521 }
1522}
1523#endif /* !FEAT_GUI_W32 */
1524
1525
1526/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001527 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001528 * Get one or more characters from the keyboard or the mouse.
1529 * If time == 0, do not wait for characters.
1530 * If time == n, wait a short time for characters.
1531 * If time == -1, wait forever for characters.
1532 * Returns the number of characters read into buf.
1533 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001534/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001535 int
1536mch_inchar(
1537 char_u *buf,
1538 int maxlen,
1539 long time,
1540 int tb_change_cnt)
1541{
1542#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1543
1544 int len;
1545 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001546#define TYPEAHEADLEN 20
1547 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1548 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001549#ifdef FEAT_MBYTE
1550 static char_u *rest = NULL; /* unconverted rest of previous read */
1551 static int restlen = 0;
1552 int unconverted;
1553#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001554
1555 /* First use any typeahead that was kept because "buf" was too small. */
1556 if (typeaheadlen > 0)
1557 goto theend;
1558
1559#ifdef FEAT_SNIFF
1560 if (want_sniff_request)
1561 {
1562 if (sniff_request_waiting)
1563 {
1564 /* return K_SNIFF */
1565 typeahead[typeaheadlen++] = CSI;
1566 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1567 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1568 sniff_request_waiting = 0;
1569 want_sniff_request = 0;
1570 goto theend;
1571 }
1572 else if (time < 0 || time > 250)
1573 {
1574 /* don't wait too long, a request might be pending */
1575 time = 250;
1576 }
1577 }
1578#endif
1579
1580 if (time >= 0)
1581 {
1582 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 }
1585 else /* time == -1, wait forever */
1586 {
1587 mch_set_winsize_now(); /* Allow winsize changes from now on */
1588
Bram Moolenaar3918c952005-03-15 22:34:55 +00001589 /*
1590 * If there is no character available within 2 seconds (default)
1591 * write the autoscript file to disk. Or cause the CursorHold event
1592 * to be triggered.
1593 */
1594 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 {
1596#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001597 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001599 buf[0] = K_SPECIAL;
1600 buf[1] = KS_EXTRA;
1601 buf[2] = (int)KE_CURSORHOLD;
1602 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 }
1604#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001605 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606 }
1607 }
1608
1609 /*
1610 * Try to read as many characters as there are, until the buffer is full.
1611 */
1612
1613 /* we will get at least one key. Get more if they are available. */
1614 g_fCBrkPressed = FALSE;
1615
1616#ifdef MCH_WRITE_DUMP
1617 if (fdDump)
1618 fputc('[', fdDump);
1619#endif
1620
1621 /* Keep looping until there is something in the typeahead buffer and more
1622 * to get and still room in the buffer (up to two bytes for a char and
1623 * three bytes for a modifier). */
1624 while ((typeaheadlen == 0 || WaitForChar(0L))
1625 && typeaheadlen + 5 <= TYPEAHEADLEN)
1626 {
1627 if (typebuf_changed(tb_change_cnt))
1628 {
1629 /* "buf" may be invalid now if a client put something in the
1630 * typeahead buffer and "buf" is in the typeahead buffer. */
1631 typeaheadlen = 0;
1632 break;
1633 }
1634#ifdef FEAT_MOUSE
1635 if (g_nMouseClick != -1)
1636 {
1637# ifdef MCH_WRITE_DUMP
1638 if (fdDump)
1639 fprintf(fdDump, "{%02x @ %d, %d}",
1640 g_nMouseClick, g_xMouse, g_yMouse);
1641# endif
1642 typeahead[typeaheadlen++] = ESC + 128;
1643 typeahead[typeaheadlen++] = 'M';
1644 typeahead[typeaheadlen++] = g_nMouseClick;
1645 typeahead[typeaheadlen++] = g_xMouse + '!';
1646 typeahead[typeaheadlen++] = g_yMouse + '!';
1647 g_nMouseClick = -1;
1648 }
1649 else
1650#endif
1651 {
1652 char_u ch2 = NUL;
1653 int modifiers = 0;
1654
1655 c = tgetch(&modifiers, &ch2);
1656
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001657#ifdef FEAT_MBYTE
1658 /* stolen from fill_input_buf() in ui.c */
1659 if (rest != NULL)
1660 {
1661 /* Use remainder of previous call, starts with an invalid
1662 * character that may become valid when reading more. */
1663 if (restlen > TYPEAHEADLEN - typeaheadlen)
1664 unconverted = TYPEAHEADLEN - typeaheadlen;
1665 else
1666 unconverted = restlen;
1667 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1668 if (unconverted == restlen)
1669 {
1670 vim_free(rest);
1671 rest = NULL;
1672 }
1673 else
1674 {
1675 restlen -= unconverted;
1676 mch_memmove(rest, rest + unconverted, restlen);
1677 }
1678 typeaheadlen += unconverted;
1679 }
1680 else
1681 unconverted = 0;
1682#endif
1683
Bram Moolenaar071d4272004-06-13 20:20:40 +00001684 if (typebuf_changed(tb_change_cnt))
1685 {
1686 /* "buf" may be invalid now if a client put something in the
1687 * typeahead buffer and "buf" is in the typeahead buffer. */
1688 typeaheadlen = 0;
1689 break;
1690 }
1691
1692 if (c == Ctrl_C && ctrl_c_interrupts)
1693 {
1694#if defined(FEAT_CLIENTSERVER)
1695 trash_input_buf();
1696#endif
1697 got_int = TRUE;
1698 }
1699
1700#ifdef FEAT_MOUSE
1701 if (g_nMouseClick == -1)
1702#endif
1703 {
1704 int n = 1;
1705
1706 /* A key may have one or two bytes. */
1707 typeahead[typeaheadlen] = c;
1708 if (ch2 != NUL)
1709 {
1710 typeahead[typeaheadlen + 1] = ch2;
1711 ++n;
1712 }
1713#ifdef FEAT_MBYTE
1714 /* Only convert normal characters, not special keys. Need to
1715 * convert before applying ALT, otherwise mapping <M-x> breaks
1716 * when 'tenc' is set. */
1717 if (input_conv.vc_type != CONV_NONE
1718 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001719 {
1720 typeaheadlen -= unconverted;
1721 n = convert_input_safe(typeahead + typeaheadlen,
1722 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1723 rest == NULL ? &rest : NULL, &restlen);
1724 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725#endif
1726
1727 /* Use the ALT key to set the 8th bit of the character
1728 * when it's one byte, the 8th bit isn't set yet and not
1729 * using a double-byte encoding (would become a lead
1730 * byte). */
1731 if ((modifiers & MOD_MASK_ALT)
1732 && n == 1
1733 && (typeahead[typeaheadlen] & 0x80) == 0
1734#ifdef FEAT_MBYTE
1735 && !enc_dbcs
1736#endif
1737 )
1738 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001739#ifdef FEAT_MBYTE
1740 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1741 typeahead + typeaheadlen);
1742#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001743 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001744#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 modifiers &= ~MOD_MASK_ALT;
1746 }
1747
1748 if (modifiers != 0)
1749 {
1750 /* Prepend modifiers to the character. */
1751 mch_memmove(typeahead + typeaheadlen + 3,
1752 typeahead + typeaheadlen, n);
1753 typeahead[typeaheadlen++] = K_SPECIAL;
1754 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1755 typeahead[typeaheadlen++] = modifiers;
1756 }
1757
1758 typeaheadlen += n;
1759
1760#ifdef MCH_WRITE_DUMP
1761 if (fdDump)
1762 fputc(c, fdDump);
1763#endif
1764 }
1765 }
1766 }
1767
1768#ifdef MCH_WRITE_DUMP
1769 if (fdDump)
1770 {
1771 fputs("]\n", fdDump);
1772 fflush(fdDump);
1773 }
1774#endif
1775
Bram Moolenaar071d4272004-06-13 20:20:40 +00001776theend:
1777 /* Move typeahead to "buf", as much as fits. */
1778 len = 0;
1779 while (len < maxlen && typeaheadlen > 0)
1780 {
1781 buf[len++] = typeahead[0];
1782 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1783 }
1784 return len;
1785
1786#else /* FEAT_GUI_W32 */
1787 return 0;
1788#endif /* FEAT_GUI_W32 */
1789}
1790
Bram Moolenaar82881492012-11-20 16:53:39 +01001791#ifndef PROTO
1792# ifndef __MINGW32__
1793# include <shellapi.h> /* required for FindExecutable() */
1794# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795#endif
1796
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001797/*
1798 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001799 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001800 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001801 static int
1802executable_exists(char *name)
1803{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001804 char *dum;
1805 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001807#ifdef FEAT_MBYTE
1808 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001809 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001810 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001811 WCHAR fnamew[_MAX_PATH];
1812 WCHAR *dumw;
1813 long n;
1814
1815 if (p != NULL)
1816 {
1817 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1818 vim_free(p);
1819 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1820 {
1821 if (n == 0)
1822 return FALSE;
1823 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1824 return FALSE;
1825 return TRUE;
1826 }
1827 /* Retry with non-wide function (for Windows 98). */
1828 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001829 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001830#endif
1831 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1832 return FALSE;
1833 if (mch_isdir(fname))
1834 return FALSE;
1835 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836}
1837
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001838#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001839 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001840/*
1841 * Bad parameter handler.
1842 *
1843 * Certain MS CRT functions will intentionally crash when passed invalid
1844 * parameters to highlight possible security holes. Setting this function as
1845 * the bad parameter handler will prevent the crash.
1846 *
1847 * In debug builds the parameters contain CRT information that might help track
1848 * down the source of a problem, but in non-debug builds the arguments are all
1849 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1850 * worth allowing these to make debugging of issues easier.
1851 */
1852 static void
1853bad_param_handler(const wchar_t *expression,
1854 const wchar_t *function,
1855 const wchar_t *file,
1856 unsigned int line,
1857 uintptr_t pReserved)
1858{
1859}
1860
1861# define SET_INVALID_PARAM_HANDLER \
1862 ((void)_set_invalid_parameter_handler(bad_param_handler))
1863#else
1864# define SET_INVALID_PARAM_HANDLER
1865#endif
1866
Bram Moolenaar071d4272004-06-13 20:20:40 +00001867#ifdef FEAT_GUI_W32
1868
1869/*
1870 * GUI version of mch_init().
1871 */
1872 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001873mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001874{
1875#ifndef __MINGW32__
1876 extern int _fmode;
1877#endif
1878
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001879 /* Silently handle invalid parameters to CRT functions */
1880 SET_INVALID_PARAM_HANDLER;
1881
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882 /* Let critical errors result in a failure, not in a dialog box. Required
1883 * for the timestamp test to work on removed floppies. */
1884 SetErrorMode(SEM_FAILCRITICALERRORS);
1885
1886 _fmode = O_BINARY; /* we do our own CR-LF translation */
1887
1888 /* Specify window size. Is there a place to get the default from? */
1889 Rows = 25;
1890 Columns = 80;
1891
1892 /* Look for 'vimrun' */
1893 if (!gui_is_win32s())
1894 {
1895 char_u vimrun_location[_MAX_PATH + 4];
1896
1897 /* First try in same directory as gvim.exe */
1898 STRCPY(vimrun_location, exe_name);
1899 STRCPY(gettail(vimrun_location), "vimrun.exe");
1900 if (mch_getperm(vimrun_location) >= 0)
1901 {
1902 if (*skiptowhite(vimrun_location) != NUL)
1903 {
1904 /* Enclose path with white space in double quotes. */
1905 mch_memmove(vimrun_location + 1, vimrun_location,
1906 STRLEN(vimrun_location) + 1);
1907 *vimrun_location = '"';
1908 STRCPY(gettail(vimrun_location), "vimrun\" ");
1909 }
1910 else
1911 STRCPY(gettail(vimrun_location), "vimrun ");
1912
1913 vimrun_path = (char *)vim_strsave(vimrun_location);
1914 s_dont_use_vimrun = FALSE;
1915 }
1916 else if (executable_exists("vimrun.exe"))
1917 s_dont_use_vimrun = FALSE;
1918
1919 /* Don't give the warning for a missing vimrun.exe right now, but only
1920 * when vimrun was supposed to be used. Don't bother people that do
1921 * not need vimrun.exe. */
1922 if (s_dont_use_vimrun)
1923 need_vimrun_warning = TRUE;
1924 }
1925
1926 /*
1927 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1928 * Otherwise the default "findstr /n" is used.
1929 */
1930 if (!executable_exists("findstr.exe"))
1931 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1932
1933#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001934 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935#endif
1936}
1937
1938
1939#else /* FEAT_GUI_W32 */
1940
1941#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1942#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1943
1944/*
1945 * ClearConsoleBuffer()
1946 * Description:
1947 * Clears the entire contents of the console screen buffer, using the
1948 * specified attribute.
1949 * Returns:
1950 * TRUE on success
1951 */
1952 static BOOL
1953ClearConsoleBuffer(WORD wAttribute)
1954{
1955 CONSOLE_SCREEN_BUFFER_INFO csbi;
1956 COORD coord;
1957 DWORD NumCells, dummy;
1958
1959 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1960 return FALSE;
1961
1962 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1963 coord.X = 0;
1964 coord.Y = 0;
1965 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1966 coord, &dummy))
1967 {
1968 return FALSE;
1969 }
1970 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1971 coord, &dummy))
1972 {
1973 return FALSE;
1974 }
1975
1976 return TRUE;
1977}
1978
1979/*
1980 * FitConsoleWindow()
1981 * Description:
1982 * Checks if the console window will fit within given buffer dimensions.
1983 * Also, if requested, will shrink the window to fit.
1984 * Returns:
1985 * TRUE on success
1986 */
1987 static BOOL
1988FitConsoleWindow(
1989 COORD dwBufferSize,
1990 BOOL WantAdjust)
1991{
1992 CONSOLE_SCREEN_BUFFER_INFO csbi;
1993 COORD dwWindowSize;
1994 BOOL NeedAdjust = FALSE;
1995
1996 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1997 {
1998 /*
1999 * A buffer resize will fail if the current console window does
2000 * not lie completely within that buffer. To avoid this, we might
2001 * have to move and possibly shrink the window.
2002 */
2003 if (csbi.srWindow.Right >= dwBufferSize.X)
2004 {
2005 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2006 if (dwWindowSize.X > dwBufferSize.X)
2007 dwWindowSize.X = dwBufferSize.X;
2008 csbi.srWindow.Right = dwBufferSize.X - 1;
2009 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2010 NeedAdjust = TRUE;
2011 }
2012 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2013 {
2014 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2015 if (dwWindowSize.Y > dwBufferSize.Y)
2016 dwWindowSize.Y = dwBufferSize.Y;
2017 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2018 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2019 NeedAdjust = TRUE;
2020 }
2021 if (NeedAdjust && WantAdjust)
2022 {
2023 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2024 return FALSE;
2025 }
2026 return TRUE;
2027 }
2028
2029 return FALSE;
2030}
2031
2032typedef struct ConsoleBufferStruct
2033{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002034 BOOL IsValid;
2035 CONSOLE_SCREEN_BUFFER_INFO Info;
2036 PCHAR_INFO Buffer;
2037 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002038} ConsoleBuffer;
2039
2040/*
2041 * SaveConsoleBuffer()
2042 * Description:
2043 * Saves important information about the console buffer, including the
2044 * actual buffer contents. The saved information is suitable for later
2045 * restoration by RestoreConsoleBuffer().
2046 * Returns:
2047 * TRUE if all information was saved; FALSE otherwise
2048 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2049 */
2050 static BOOL
2051SaveConsoleBuffer(
2052 ConsoleBuffer *cb)
2053{
2054 DWORD NumCells;
2055 COORD BufferCoord;
2056 SMALL_RECT ReadRegion;
2057 WORD Y, Y_incr;
2058
2059 if (cb == NULL)
2060 return FALSE;
2061
2062 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2063 {
2064 cb->IsValid = FALSE;
2065 return FALSE;
2066 }
2067 cb->IsValid = TRUE;
2068
2069 /*
2070 * Allocate a buffer large enough to hold the entire console screen
2071 * buffer. If this ConsoleBuffer structure has already been initialized
2072 * with a buffer of the correct size, then just use that one.
2073 */
2074 if (!cb->IsValid || cb->Buffer == NULL ||
2075 cb->BufferSize.X != cb->Info.dwSize.X ||
2076 cb->BufferSize.Y != cb->Info.dwSize.Y)
2077 {
2078 cb->BufferSize.X = cb->Info.dwSize.X;
2079 cb->BufferSize.Y = cb->Info.dwSize.Y;
2080 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002081 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2083 if (cb->Buffer == NULL)
2084 return FALSE;
2085 }
2086
2087 /*
2088 * We will now copy the console screen buffer into our buffer.
2089 * ReadConsoleOutput() seems to be limited as far as how much you
2090 * can read at a time. Empirically, this number seems to be about
2091 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2092 * in chunks until it is all copied. The chunks will all have the
2093 * same horizontal characteristics, so initialize them now. The
2094 * height of each chunk will be (12000 / width).
2095 */
2096 BufferCoord.X = 0;
2097 ReadRegion.Left = 0;
2098 ReadRegion.Right = cb->Info.dwSize.X - 1;
2099 Y_incr = 12000 / cb->Info.dwSize.X;
2100 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2101 {
2102 /*
2103 * Read into position (0, Y) in our buffer.
2104 */
2105 BufferCoord.Y = Y;
2106 /*
2107 * Read the region whose top left corner is (0, Y) and whose bottom
2108 * right corner is (width - 1, Y + Y_incr - 1). This should define
2109 * a region of size width by Y_incr. Don't worry if this region is
2110 * too large for the remaining buffer; it will be cropped.
2111 */
2112 ReadRegion.Top = Y;
2113 ReadRegion.Bottom = Y + Y_incr - 1;
2114 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2115 cb->Buffer, /* our buffer */
2116 cb->BufferSize, /* dimensions of our buffer */
2117 BufferCoord, /* offset in our buffer */
2118 &ReadRegion)) /* region to save */
2119 {
2120 vim_free(cb->Buffer);
2121 cb->Buffer = NULL;
2122 return FALSE;
2123 }
2124 }
2125
2126 return TRUE;
2127}
2128
2129/*
2130 * RestoreConsoleBuffer()
2131 * Description:
2132 * Restores important information about the console buffer, including the
2133 * actual buffer contents, if desired. The information to restore is in
2134 * the same format used by SaveConsoleBuffer().
2135 * Returns:
2136 * TRUE on success
2137 */
2138 static BOOL
2139RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002140 ConsoleBuffer *cb,
2141 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002142{
2143 COORD BufferCoord;
2144 SMALL_RECT WriteRegion;
2145
2146 if (cb == NULL || !cb->IsValid)
2147 return FALSE;
2148
2149 /*
2150 * Before restoring the buffer contents, clear the current buffer, and
2151 * restore the cursor position and window information. Doing this now
2152 * prevents old buffer contents from "flashing" onto the screen.
2153 */
2154 if (RestoreScreen)
2155 ClearConsoleBuffer(cb->Info.wAttributes);
2156
2157 FitConsoleWindow(cb->Info.dwSize, TRUE);
2158 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2159 return FALSE;
2160 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2161 return FALSE;
2162
2163 if (!RestoreScreen)
2164 {
2165 /*
2166 * No need to restore the screen buffer contents, so we're done.
2167 */
2168 return TRUE;
2169 }
2170
2171 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2172 return FALSE;
2173 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2174 return FALSE;
2175
2176 /*
2177 * Restore the screen buffer contents.
2178 */
2179 if (cb->Buffer != NULL)
2180 {
2181 BufferCoord.X = 0;
2182 BufferCoord.Y = 0;
2183 WriteRegion.Left = 0;
2184 WriteRegion.Top = 0;
2185 WriteRegion.Right = cb->Info.dwSize.X - 1;
2186 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2187 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2188 cb->Buffer, /* our buffer */
2189 cb->BufferSize, /* dimensions of our buffer */
2190 BufferCoord, /* offset in our buffer */
2191 &WriteRegion)) /* region to restore */
2192 {
2193 return FALSE;
2194 }
2195 }
2196
2197 return TRUE;
2198}
2199
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002200#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002201#ifdef FEAT_RESTORE_ORIG_SCREEN
2202static ConsoleBuffer g_cbOrig = { 0 };
2203#endif
2204static ConsoleBuffer g_cbNonTermcap = { 0 };
2205static ConsoleBuffer g_cbTermcap = { 0 };
2206
2207#ifdef FEAT_TITLE
2208#ifdef __BORLANDC__
2209typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2210#else
2211typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2212#endif
2213char g_szOrigTitle[256] = { 0 };
2214HWND g_hWnd = NULL; /* also used in os_mswin.c */
2215static HICON g_hOrigIconSmall = NULL;
2216static HICON g_hOrigIcon = NULL;
2217static HICON g_hVimIcon = NULL;
2218static BOOL g_fCanChangeIcon = FALSE;
2219
2220/* ICON* are not defined in VC++ 4.0 */
2221#ifndef ICON_SMALL
2222#define ICON_SMALL 0
2223#endif
2224#ifndef ICON_BIG
2225#define ICON_BIG 1
2226#endif
2227/*
2228 * GetConsoleIcon()
2229 * Description:
2230 * Attempts to retrieve the small icon and/or the big icon currently in
2231 * use by a given window.
2232 * Returns:
2233 * TRUE on success
2234 */
2235 static BOOL
2236GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002237 HWND hWnd,
2238 HICON *phIconSmall,
2239 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240{
2241 if (hWnd == NULL)
2242 return FALSE;
2243
2244 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002245 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2246 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002248 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2249 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250 return TRUE;
2251}
2252
2253/*
2254 * SetConsoleIcon()
2255 * Description:
2256 * Attempts to change the small icon and/or the big icon currently in
2257 * use by a given window.
2258 * Returns:
2259 * TRUE on success
2260 */
2261 static BOOL
2262SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002263 HWND hWnd,
2264 HICON hIconSmall,
2265 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002267 HICON hPrevIconSmall;
2268 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002269
2270 if (hWnd == NULL)
2271 return FALSE;
2272
2273 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002274 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2275 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002277 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2278 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002279 return TRUE;
2280}
2281
2282/*
2283 * SaveConsoleTitleAndIcon()
2284 * Description:
2285 * Saves the current console window title in g_szOrigTitle, for later
2286 * restoration. Also, attempts to obtain a handle to the console window,
2287 * and use it to save the small and big icons currently in use by the
2288 * console window. This is not always possible on some versions of Windows;
2289 * nor is it possible when running Vim remotely using Telnet (since the
2290 * console window the user sees is owned by a remote process).
2291 */
2292 static void
2293SaveConsoleTitleAndIcon(void)
2294{
2295 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2296
2297 /* Save the original title. */
2298 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2299 return;
2300
2301 /*
2302 * Obtain a handle to the console window using GetConsoleWindow() from
2303 * KERNEL32.DLL; we need to handle in order to change the window icon.
2304 * This function only exists on NT-based Windows, starting with Windows
2305 * 2000. On older operating systems, we can't change the window icon
2306 * anyway.
2307 */
2308 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2309 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2310 "GetConsoleWindow")) != NULL)
2311 {
2312 g_hWnd = (*GetConsoleWindowProc)();
2313 }
2314 if (g_hWnd == NULL)
2315 return;
2316
2317 /* Save the original console window icon. */
2318 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2319 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2320 return;
2321
2322 /* Extract the first icon contained in the Vim executable. */
2323 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2324 if (g_hVimIcon != NULL)
2325 g_fCanChangeIcon = TRUE;
2326}
2327#endif
2328
2329static int g_fWindInitCalled = FALSE;
2330static int g_fTermcapMode = FALSE;
2331static CONSOLE_CURSOR_INFO g_cci;
2332static DWORD g_cmodein = 0;
2333static DWORD g_cmodeout = 0;
2334
2335/*
2336 * non-GUI version of mch_init().
2337 */
2338 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002339mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340{
2341#ifndef FEAT_RESTORE_ORIG_SCREEN
2342 CONSOLE_SCREEN_BUFFER_INFO csbi;
2343#endif
2344#ifndef __MINGW32__
2345 extern int _fmode;
2346#endif
2347
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002348 /* Silently handle invalid parameters to CRT functions */
2349 SET_INVALID_PARAM_HANDLER;
2350
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 /* Let critical errors result in a failure, not in a dialog box. Required
2352 * for the timestamp test to work on removed floppies. */
2353 SetErrorMode(SEM_FAILCRITICALERRORS);
2354
2355 _fmode = O_BINARY; /* we do our own CR-LF translation */
2356 out_flush();
2357
2358 /* Obtain handles for the standard Console I/O devices */
2359 if (read_cmd_fd == 0)
2360 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2361 else
2362 create_conin();
2363 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2364
2365#ifdef FEAT_RESTORE_ORIG_SCREEN
2366 /* Save the initial console buffer for later restoration */
2367 SaveConsoleBuffer(&g_cbOrig);
2368 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2369#else
2370 /* Get current text attributes */
2371 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2372 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2373#endif
2374 if (cterm_normal_fg_color == 0)
2375 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2376 if (cterm_normal_bg_color == 0)
2377 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2378
2379 /* set termcap codes to current text attributes */
2380 update_tcap(g_attrCurrent);
2381
2382 GetConsoleCursorInfo(g_hConOut, &g_cci);
2383 GetConsoleMode(g_hConIn, &g_cmodein);
2384 GetConsoleMode(g_hConOut, &g_cmodeout);
2385
2386#ifdef FEAT_TITLE
2387 SaveConsoleTitleAndIcon();
2388 /*
2389 * Set both the small and big icons of the console window to Vim's icon.
2390 * Note that Vim presently only has one size of icon (32x32), but it
2391 * automatically gets scaled down to 16x16 when setting the small icon.
2392 */
2393 if (g_fCanChangeIcon)
2394 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2395#endif
2396
2397 ui_get_shellsize();
2398
2399#ifdef MCH_WRITE_DUMP
2400 fdDump = fopen("dump", "wt");
2401
2402 if (fdDump)
2403 {
2404 time_t t;
2405
2406 time(&t);
2407 fputs(ctime(&t), fdDump);
2408 fflush(fdDump);
2409 }
2410#endif
2411
2412 g_fWindInitCalled = TRUE;
2413
2414#ifdef FEAT_MOUSE
2415 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2416#endif
2417
2418#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002419 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420#endif
2421
2422 /* This will be NULL on anything but NT 4.0 */
2423 s_pfnGetConsoleKeyboardLayoutName =
2424 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2425 "GetConsoleKeyboardLayoutNameA");
2426}
2427
2428/*
2429 * non-GUI version of mch_exit().
2430 * Shut down and exit with status `r'
2431 * Careful: mch_exit() may be called before mch_init()!
2432 */
2433 void
2434mch_exit(int r)
2435{
2436 stoptermcap();
2437
2438 if (g_fWindInitCalled)
2439 settmode(TMODE_COOK);
2440
2441 ml_close_all(TRUE); /* remove all memfiles */
2442
2443 if (g_fWindInitCalled)
2444 {
2445#ifdef FEAT_TITLE
2446 mch_restore_title(3);
2447 /*
2448 * Restore both the small and big icons of the console window to
2449 * what they were at startup. Don't do this when the window is
2450 * closed, Vim would hang here.
2451 */
2452 if (g_fCanChangeIcon && !g_fForceExit)
2453 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2454#endif
2455
2456#ifdef MCH_WRITE_DUMP
2457 if (fdDump)
2458 {
2459 time_t t;
2460
2461 time(&t);
2462 fputs(ctime(&t), fdDump);
2463 fclose(fdDump);
2464 }
2465 fdDump = NULL;
2466#endif
2467 }
2468
2469 SetConsoleCursorInfo(g_hConOut, &g_cci);
2470 SetConsoleMode(g_hConIn, g_cmodein);
2471 SetConsoleMode(g_hConOut, g_cmodeout);
2472
2473#ifdef DYNAMIC_GETTEXT
2474 dyn_libintl_end();
2475#endif
2476
2477 exit(r);
2478}
2479#endif /* !FEAT_GUI_W32 */
2480
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481/*
2482 * Do we have an interactive window?
2483 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002484/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 int
2486mch_check_win(
2487 int argc,
2488 char **argv)
2489{
2490 get_exe_name();
2491
2492#ifdef FEAT_GUI_W32
2493 return OK; /* GUI always has a tty */
2494#else
2495 if (isatty(1))
2496 return OK;
2497 return FAIL;
2498#endif
2499}
2500
2501
2502/*
2503 * fname_case(): Set the case of the file name, if it already exists.
2504 * When "len" is > 0, also expand short to long filenames.
2505 */
2506 void
2507fname_case(
2508 char_u *name,
2509 int len)
2510{
2511 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002512 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 char *ptrue, *ptruePrev;
2514 char *porig, *porigPrev;
2515 int flen;
2516 WIN32_FIND_DATA fb;
2517 HANDLE hFind;
2518 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002519 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002520
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002521 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 if (flen == 0 || flen > _MAX_PATH)
2523 return;
2524
2525 slash_adjust(name);
2526
2527 /* Build the new name in szTrueName[] one component at a time. */
2528 porig = name;
2529 ptrue = szTrueName;
2530
2531 if (isalpha(porig[0]) && porig[1] == ':')
2532 {
2533 /* copy leading drive letter */
2534 *ptrue++ = *porig++;
2535 *ptrue++ = *porig++;
2536 *ptrue = NUL; /* in case nothing follows */
2537 }
2538
2539 while (*porig != NUL)
2540 {
2541 /* copy \ characters */
2542 while (*porig == psepc)
2543 *ptrue++ = *porig++;
2544
2545 ptruePrev = ptrue;
2546 porigPrev = porig;
2547 while (*porig != NUL && *porig != psepc)
2548 {
2549#ifdef FEAT_MBYTE
2550 int l;
2551
2552 if (enc_dbcs)
2553 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002554 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002555 while (--l >= 0)
2556 *ptrue++ = *porig++;
2557 }
2558 else
2559#endif
2560 *ptrue++ = *porig++;
2561 }
2562 *ptrue = NUL;
2563
Bram Moolenaar464c9252010-10-13 20:37:41 +02002564 /* To avoid a slow failure append "\*" when searching a directory,
2565 * server or network share. */
2566 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002567 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002568 if (*porig == psepc && slen + 2 < _MAX_PATH)
2569 STRCPY(szTrueNameTemp + slen, "\\*");
2570
Bram Moolenaar071d4272004-06-13 20:20:40 +00002571 /* Skip "", "." and "..". */
2572 if (ptrue > ptruePrev
2573 && (ptruePrev[0] != '.'
2574 || (ptruePrev[1] != NUL
2575 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002576 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002577 != INVALID_HANDLE_VALUE)
2578 {
2579 c = *porig;
2580 *porig = NUL;
2581
2582 /* Only use the match when it's the same name (ignoring case) or
2583 * expansion is allowed and there is a match with the short name
2584 * and there is enough room. */
2585 if (_stricoll(porigPrev, fb.cFileName) == 0
2586 || (len > 0
2587 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2588 && (int)(ptruePrev - szTrueName)
2589 + (int)strlen(fb.cFileName) < len)))
2590 {
2591 STRCPY(ptruePrev, fb.cFileName);
2592
2593 /* Look for exact match and prefer it if found. Must be a
2594 * long name, otherwise there would be only one match. */
2595 while (FindNextFile(hFind, &fb))
2596 {
2597 if (*fb.cAlternateFileName != NUL
2598 && (strcoll(porigPrev, fb.cFileName) == 0
2599 || (len > 0
2600 && (_stricoll(porigPrev,
2601 fb.cAlternateFileName) == 0
2602 && (int)(ptruePrev - szTrueName)
2603 + (int)strlen(fb.cFileName) < len))))
2604 {
2605 STRCPY(ptruePrev, fb.cFileName);
2606 break;
2607 }
2608 }
2609 }
2610 FindClose(hFind);
2611 *porig = c;
2612 ptrue = ptruePrev + strlen(ptruePrev);
2613 }
2614 }
2615
2616 STRCPY(name, szTrueName);
2617}
2618
2619
2620/*
2621 * Insert user name in s[len].
2622 */
2623 int
2624mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002625 char_u *s,
2626 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002627{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002628 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002629 DWORD cch = sizeof szUserName;
2630
2631 if (GetUserName(szUserName, &cch))
2632 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002633 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 return OK;
2635 }
2636 s[0] = NUL;
2637 return FAIL;
2638}
2639
2640
2641/*
2642 * Insert host name in s[len].
2643 */
2644 void
2645mch_get_host_name(
2646 char_u *s,
2647 int len)
2648{
2649 DWORD cch = len;
2650
2651 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002652 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002653}
2654
2655
2656/*
2657 * return process ID
2658 */
2659 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002660mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002661{
2662 return (long)GetCurrentProcessId();
2663}
2664
2665
2666/*
2667 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2668 * Return OK for success, FAIL for failure.
2669 */
2670 int
2671mch_dirname(
2672 char_u *buf,
2673 int len)
2674{
2675 /*
2676 * Originally this was:
2677 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2678 * But the Win32s known bug list says that getcwd() doesn't work
2679 * so use the Win32 system call instead. <Negri>
2680 */
2681#ifdef FEAT_MBYTE
2682 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2683 {
2684 WCHAR wbuf[_MAX_PATH + 1];
2685
2686 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2687 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002688 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002689
2690 if (p != NULL)
2691 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002692 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693 vim_free(p);
2694 return OK;
2695 }
2696 }
2697 /* Retry with non-wide function (for Windows 98). */
2698 }
2699#endif
2700 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2701}
2702
2703/*
2704 * get file permissions for `name'
2705 * -1 : error
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002706 * else mode_t
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707 */
2708 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002709mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002711 struct stat st;
2712 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002714 n = mch_stat(name, &st);
2715 return n == 0 ? (int)st.st_mode : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716}
2717
2718
2719/*
2720 * set file permission for `name' to `perm'
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002721 *
2722 * return FAIL for failure, OK otherwise
Bram Moolenaar071d4272004-06-13 20:20:40 +00002723 */
2724 int
2725mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002726 char_u *name,
2727 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002729 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730#ifdef FEAT_MBYTE
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002731 WCHAR *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2733 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002734 p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002735
2736 if (p != NULL)
2737 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002738 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002739 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002740 if (n == -1 && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2741 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742 /* Retry with non-wide function (for Windows 98). */
2743 }
2744 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002745 if (p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002747 n = _chmod(name, perm);
2748 if (n == -1)
2749 return FAIL;
2750
2751 win32_set_archive(name);
2752
2753 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754}
2755
2756/*
2757 * Set hidden flag for "name".
2758 */
2759 void
2760mch_hide(char_u *name)
2761{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002762 int attrs = win32_getattrs(name);
2763 if (attrs == -1)
2764 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002766 attrs |= FILE_ATTRIBUTE_HIDDEN;
2767 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768}
2769
2770/*
2771 * return TRUE if "name" is a directory
2772 * return FALSE if "name" is not a directory or upon error
2773 */
2774 int
2775mch_isdir(char_u *name)
2776{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002777 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778
2779 if (f == -1)
2780 return FALSE; /* file does not exist at all */
2781
2782 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2783}
2784
2785/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002786 * Create directory "name".
2787 * Return 0 on success, -1 on error.
2788 */
2789 int
2790mch_mkdir(char_u *name)
2791{
2792#ifdef FEAT_MBYTE
2793 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2794 {
2795 WCHAR *p;
2796 int retval;
2797
2798 p = enc_to_utf16(name, NULL);
2799 if (p == NULL)
2800 return -1;
2801 retval = _wmkdir(p);
2802 vim_free(p);
2803 return retval;
2804 }
2805#endif
2806 return _mkdir(name);
2807}
2808
2809/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002810 * Return TRUE if file "fname" has more than one link.
2811 */
2812 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002813mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002814{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002815 BY_HANDLE_FILE_INFORMATION info;
2816
2817 return win32_fileinfo(fname, &info) == FILEINFO_OK
2818 && info.nNumberOfLinks > 1;
2819}
2820
2821/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002822 * Return TRUE if file "fname" is a symbolic link.
2823 */
2824 int
2825mch_is_symbolic_link(char_u *fname)
2826{
2827 HANDLE hFind;
2828 int res = FALSE;
2829 WIN32_FIND_DATAA findDataA;
2830 DWORD fileFlags = 0, reparseTag = 0;
2831#ifdef FEAT_MBYTE
2832 WCHAR *wn = NULL;
2833 WIN32_FIND_DATAW findDataW;
2834
2835 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2836 wn = enc_to_utf16(fname, NULL);
2837 if (wn != NULL)
2838 {
2839 hFind = FindFirstFileW(wn, &findDataW);
2840 vim_free(wn);
2841 if (hFind == INVALID_HANDLE_VALUE
2842 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2843 {
2844 /* Retry with non-wide function (for Windows 98). */
2845 hFind = FindFirstFile(fname, &findDataA);
2846 if (hFind != INVALID_HANDLE_VALUE)
2847 {
2848 fileFlags = findDataA.dwFileAttributes;
2849 reparseTag = findDataA.dwReserved0;
2850 }
2851 }
2852 else
2853 {
2854 fileFlags = findDataW.dwFileAttributes;
2855 reparseTag = findDataW.dwReserved0;
2856 }
2857 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002858 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002859#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002860 {
2861 hFind = FindFirstFile(fname, &findDataA);
2862 if (hFind != INVALID_HANDLE_VALUE)
2863 {
2864 fileFlags = findDataA.dwFileAttributes;
2865 reparseTag = findDataA.dwReserved0;
2866 }
2867 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002868
2869 if (hFind != INVALID_HANDLE_VALUE)
2870 FindClose(hFind);
2871
2872 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
2873 && reparseTag == IO_REPARSE_TAG_SYMLINK)
2874 res = TRUE;
2875
2876 return res;
2877}
2878
2879/*
2880 * Return TRUE if file "fname" has more than one link or if it is a symbolic
2881 * link.
2882 */
2883 int
2884mch_is_linked(char_u *fname)
2885{
2886 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
2887 return TRUE;
2888 return FALSE;
2889}
2890
2891/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002892 * Get the by-handle-file-information for "fname".
2893 * Returns FILEINFO_OK when OK.
2894 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
2895 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
2896 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
2897 */
2898 int
2899win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
2900{
Bram Moolenaar03f48552006-02-28 23:52:23 +00002901 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002902 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002903#ifdef FEAT_MBYTE
2904 WCHAR *wn = NULL;
2905
2906 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002907 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002908 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002909 if (wn == NULL)
2910 res = FILEINFO_ENC_FAIL;
2911 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00002912 if (wn != NULL)
2913 {
2914 hFile = CreateFileW(wn, /* file name */
2915 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002916 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002917 NULL, /* security descriptor */
2918 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002919 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002920 NULL); /* handle to template file */
2921 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002922 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002923 {
2924 /* Retry with non-wide function (for Windows 98). */
2925 vim_free(wn);
2926 wn = NULL;
2927 }
2928 }
2929 if (wn == NULL)
2930#endif
2931 hFile = CreateFile(fname, /* file name */
2932 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002933 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002934 NULL, /* security descriptor */
2935 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002936 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002937 NULL); /* handle to template file */
2938
2939 if (hFile != INVALID_HANDLE_VALUE)
2940 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002941 if (GetFileInformationByHandle(hFile, info) != 0)
2942 res = FILEINFO_OK;
2943 else
2944 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002945 CloseHandle(hFile);
2946 }
2947
2948#ifdef FEAT_MBYTE
2949 vim_free(wn);
2950#endif
2951 return res;
2952}
2953
2954/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002955 * get file attributes for `name'
2956 * -1 : error
2957 * else FILE_ATTRIBUTE_* defined in winnt.h
2958 */
2959 static
2960 int
2961win32_getattrs(char_u *name)
2962{
2963 int attr;
2964#ifdef FEAT_MBYTE
2965 WCHAR *p = NULL;
2966
2967 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2968 p = enc_to_utf16(name, NULL);
2969
2970 if (p != NULL)
2971 {
2972 attr = GetFileAttributesW(p);
2973 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2974 {
2975 /* Retry with non-wide function (for Windows 98). */
2976 vim_free(p);
2977 p = NULL;
2978 }
2979 }
2980 if (p == NULL)
2981#endif
2982 attr = GetFileAttributes((char *)name);
2983#ifdef FEAT_MBYTE
2984 vim_free(p);
2985#endif
2986 return attr;
2987}
2988
2989/*
2990 * set file attributes for `name' to `attrs'
2991 *
2992 * return -1 for failure, 0 otherwise
2993 */
2994 static
2995 int
2996win32_setattrs(char_u *name, int attrs)
2997{
2998 int res;
2999#ifdef FEAT_MBYTE
3000 WCHAR *p = NULL;
3001
3002 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3003 p = enc_to_utf16(name, NULL);
3004
3005 if (p != NULL)
3006 {
3007 res = SetFileAttributesW(p, attrs);
3008 if (res == FALSE
3009 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3010 {
3011 /* Retry with non-wide function (for Windows 98). */
3012 vim_free(p);
3013 p = NULL;
3014 }
3015 }
3016 if (p == NULL)
3017#endif
3018 res = SetFileAttributes((char *)name, attrs);
3019#ifdef FEAT_MBYTE
3020 vim_free(p);
3021#endif
3022 return res ? 0 : -1;
3023}
3024
3025/*
3026 * Set archive flag for "name".
3027 */
3028 static
3029 int
3030win32_set_archive(char_u *name)
3031{
3032 int attrs = win32_getattrs(name);
3033 if (attrs == -1)
3034 return -1;
3035
3036 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3037 return win32_setattrs(name, attrs);
3038}
3039
3040/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003041 * Return TRUE if file or directory "name" is writable (not readonly).
3042 * Strange semantics of Win32: a readonly directory is writable, but you can't
3043 * delete a file. Let's say this means it is writable.
3044 */
3045 int
3046mch_writable(char_u *name)
3047{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003048 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003050 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3051 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052}
3053
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054/*
3055 * Return 1 if "name" can be executed, 0 if not.
3056 * Return -1 if unknown.
3057 */
3058 int
3059mch_can_exe(char_u *name)
3060{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003061 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003062 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003063 char_u *p;
3064
3065 if (len >= _MAX_PATH) /* safety check */
3066 return FALSE;
3067
3068 /* If there already is an extension try using the name directly. Also do
3069 * this with a Unix-shell like 'shell'. */
3070 if (vim_strchr(gettail(name), '.') != NULL
3071 || strstr((char *)gettail(p_sh), "sh") != NULL)
3072 if (executable_exists((char *)name))
3073 return TRUE;
3074
3075 /*
3076 * Loop over all extensions in $PATHEXT.
3077 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003078 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003079 p = mch_getenv("PATHEXT");
3080 if (p == NULL)
3081 p = (char_u *)".com;.exe;.bat;.cmd";
3082 while (*p)
3083 {
3084 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3085 {
3086 /* A single "." means no extension is added. */
3087 buf[len] = NUL;
3088 ++p;
3089 if (*p)
3090 ++p;
3091 }
3092 else
3093 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
3094 if (executable_exists((char *)buf))
3095 return TRUE;
3096 }
3097 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003099
3100/*
3101 * Check what "name" is:
3102 * NODE_NORMAL: file or directory (or doesn't exist)
3103 * NODE_WRITABLE: writable device, socket, fifo, etc.
3104 * NODE_OTHER: non-writable things
3105 */
3106 int
3107mch_nodetype(char_u *name)
3108{
3109 HANDLE hFile;
3110 int type;
3111
Bram Moolenaar043545e2006-10-10 16:44:07 +00003112 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3113 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3114 * here. */
3115 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3116 return NODE_WRITABLE;
3117
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118 hFile = CreateFile(name, /* file name */
3119 GENERIC_WRITE, /* access mode */
3120 0, /* share mode */
3121 NULL, /* security descriptor */
3122 OPEN_EXISTING, /* creation disposition */
3123 0, /* file attributes */
3124 NULL); /* handle to template file */
3125
3126 if (hFile == INVALID_HANDLE_VALUE)
3127 return NODE_NORMAL;
3128
3129 type = GetFileType(hFile);
3130 CloseHandle(hFile);
3131 if (type == FILE_TYPE_CHAR)
3132 return NODE_WRITABLE;
3133 if (type == FILE_TYPE_DISK)
3134 return NODE_NORMAL;
3135 return NODE_OTHER;
3136}
3137
3138#ifdef HAVE_ACL
3139struct my_acl
3140{
3141 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3142 PSID pSidOwner;
3143 PSID pSidGroup;
3144 PACL pDacl;
3145 PACL pSacl;
3146};
3147#endif
3148
3149/*
3150 * Return a pointer to the ACL of file "fname" in allocated memory.
3151 * Return NULL if the ACL is not available for whatever reason.
3152 */
3153 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003154mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155{
3156#ifndef HAVE_ACL
3157 return (vim_acl_T)NULL;
3158#else
3159 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003160 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003161
3162 /* This only works on Windows NT and 2000. */
3163 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3164 {
3165 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3166 if (p != NULL)
3167 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003168# ifdef FEAT_MBYTE
3169 WCHAR *wn = NULL;
3170
3171 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3172 wn = enc_to_utf16(fname, NULL);
3173 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003174 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003175 /* Try to retrieve the entire security descriptor. */
3176 err = pGetNamedSecurityInfoW(
3177 wn, // Abstract filename
3178 SE_FILE_OBJECT, // File Object
3179 OWNER_SECURITY_INFORMATION |
3180 GROUP_SECURITY_INFORMATION |
3181 DACL_SECURITY_INFORMATION |
3182 SACL_SECURITY_INFORMATION,
3183 &p->pSidOwner, // Ownership information.
3184 &p->pSidGroup, // Group membership.
3185 &p->pDacl, // Discretionary information.
3186 &p->pSacl, // For auditing purposes.
3187 &p->pSecurityDescriptor);
3188 if (err == ERROR_ACCESS_DENIED ||
3189 err == ERROR_PRIVILEGE_NOT_HELD)
3190 {
3191 /* Retrieve only DACL. */
3192 (void)pGetNamedSecurityInfoW(
3193 wn,
3194 SE_FILE_OBJECT,
3195 DACL_SECURITY_INFORMATION,
3196 NULL,
3197 NULL,
3198 &p->pDacl,
3199 NULL,
3200 &p->pSecurityDescriptor);
3201 }
3202 if (p->pSecurityDescriptor == NULL)
3203 {
3204 mch_free_acl((vim_acl_T)p);
3205 p = NULL;
3206 }
3207 vim_free(wn);
3208 }
3209 else
3210# endif
3211 {
3212 /* Try to retrieve the entire security descriptor. */
3213 err = pGetNamedSecurityInfo(
3214 (LPSTR)fname, // Abstract filename
3215 SE_FILE_OBJECT, // File Object
3216 OWNER_SECURITY_INFORMATION |
3217 GROUP_SECURITY_INFORMATION |
3218 DACL_SECURITY_INFORMATION |
3219 SACL_SECURITY_INFORMATION,
3220 &p->pSidOwner, // Ownership information.
3221 &p->pSidGroup, // Group membership.
3222 &p->pDacl, // Discretionary information.
3223 &p->pSacl, // For auditing purposes.
3224 &p->pSecurityDescriptor);
3225 if (err == ERROR_ACCESS_DENIED ||
3226 err == ERROR_PRIVILEGE_NOT_HELD)
3227 {
3228 /* Retrieve only DACL. */
3229 (void)pGetNamedSecurityInfo(
3230 (LPSTR)fname,
3231 SE_FILE_OBJECT,
3232 DACL_SECURITY_INFORMATION,
3233 NULL,
3234 NULL,
3235 &p->pDacl,
3236 NULL,
3237 &p->pSecurityDescriptor);
3238 }
3239 if (p->pSecurityDescriptor == NULL)
3240 {
3241 mch_free_acl((vim_acl_T)p);
3242 p = NULL;
3243 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244 }
3245 }
3246 }
3247
3248 return (vim_acl_T)p;
3249#endif
3250}
3251
Bram Moolenaar27515922013-06-29 15:36:26 +02003252#ifdef HAVE_ACL
3253/*
3254 * Check if "acl" contains inherited ACE.
3255 */
3256 static BOOL
3257is_acl_inherited(PACL acl)
3258{
3259 DWORD i;
3260 ACL_SIZE_INFORMATION acl_info;
3261 PACCESS_ALLOWED_ACE ace;
3262
3263 acl_info.AceCount = 0;
3264 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3265 for (i = 0; i < acl_info.AceCount; i++)
3266 {
3267 GetAce(acl, i, (LPVOID *)&ace);
3268 if (ace->Header.AceFlags & INHERITED_ACE)
3269 return TRUE;
3270 }
3271 return FALSE;
3272}
3273#endif
3274
Bram Moolenaar071d4272004-06-13 20:20:40 +00003275/*
3276 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3277 * Errors are ignored.
3278 * This must only be called with "acl" equal to what mch_get_acl() returned.
3279 */
3280 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003281mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003282{
3283#ifdef HAVE_ACL
3284 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003285 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003286
3287 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003288 {
3289# ifdef FEAT_MBYTE
3290 WCHAR *wn = NULL;
3291# endif
3292
3293 /* Set security flags */
3294 if (p->pSidOwner)
3295 sec_info |= OWNER_SECURITY_INFORMATION;
3296 if (p->pSidGroup)
3297 sec_info |= GROUP_SECURITY_INFORMATION;
3298 if (p->pDacl)
3299 {
3300 sec_info |= DACL_SECURITY_INFORMATION;
3301 /* Do not inherit its parent's DACL.
3302 * If the DACL is inherited, Cygwin permissions would be changed.
3303 */
3304 if (!is_acl_inherited(p->pDacl))
3305 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3306 }
3307 if (p->pSacl)
3308 sec_info |= SACL_SECURITY_INFORMATION;
3309
3310# ifdef FEAT_MBYTE
3311 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3312 wn = enc_to_utf16(fname, NULL);
3313 if (wn != NULL)
3314 {
3315 (void)pSetNamedSecurityInfoW(
3316 wn, // Abstract filename
3317 SE_FILE_OBJECT, // File Object
3318 sec_info,
3319 p->pSidOwner, // Ownership information.
3320 p->pSidGroup, // Group membership.
3321 p->pDacl, // Discretionary information.
3322 p->pSacl // For auditing purposes.
3323 );
3324 vim_free(wn);
3325 }
3326 else
3327# endif
3328 {
3329 (void)pSetNamedSecurityInfo(
3330 (LPSTR)fname, // Abstract filename
3331 SE_FILE_OBJECT, // File Object
3332 sec_info,
3333 p->pSidOwner, // Ownership information.
3334 p->pSidGroup, // Group membership.
3335 p->pDacl, // Discretionary information.
3336 p->pSacl // For auditing purposes.
3337 );
3338 }
3339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340#endif
3341}
3342
3343 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003344mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003345{
3346#ifdef HAVE_ACL
3347 struct my_acl *p = (struct my_acl *)acl;
3348
3349 if (p != NULL)
3350 {
3351 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3352 vim_free(p);
3353 }
3354#endif
3355}
3356
3357#ifndef FEAT_GUI_W32
3358
3359/*
3360 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3361 */
3362 static BOOL WINAPI
3363handler_routine(
3364 DWORD dwCtrlType)
3365{
3366 switch (dwCtrlType)
3367 {
3368 case CTRL_C_EVENT:
3369 if (ctrl_c_interrupts)
3370 g_fCtrlCPressed = TRUE;
3371 return TRUE;
3372
3373 case CTRL_BREAK_EVENT:
3374 g_fCBrkPressed = TRUE;
3375 return TRUE;
3376
3377 /* fatal events: shut down gracefully */
3378 case CTRL_CLOSE_EVENT:
3379 case CTRL_LOGOFF_EVENT:
3380 case CTRL_SHUTDOWN_EVENT:
3381 windgoto((int)Rows - 1, 0);
3382 g_fForceExit = TRUE;
3383
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003384 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385 (dwCtrlType == CTRL_CLOSE_EVENT
3386 ? _("close")
3387 : dwCtrlType == CTRL_LOGOFF_EVENT
3388 ? _("logoff")
3389 : _("shutdown")));
3390#ifdef DEBUG
3391 OutputDebugString(IObuff);
3392#endif
3393
3394 preserve_exit(); /* output IObuff, preserve files and exit */
3395
3396 return TRUE; /* not reached */
3397
3398 default:
3399 return FALSE;
3400 }
3401}
3402
3403
3404/*
3405 * set the tty in (raw) ? "raw" : "cooked" mode
3406 */
3407 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003408mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003409{
3410 DWORD cmodein;
3411 DWORD cmodeout;
3412 BOOL bEnableHandler;
3413
3414 GetConsoleMode(g_hConIn, &cmodein);
3415 GetConsoleMode(g_hConOut, &cmodeout);
3416 if (tmode == TMODE_RAW)
3417 {
3418 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3419 ENABLE_ECHO_INPUT);
3420#ifdef FEAT_MOUSE
3421 if (g_fMouseActive)
3422 cmodein |= ENABLE_MOUSE_INPUT;
3423#endif
3424 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3425 bEnableHandler = TRUE;
3426 }
3427 else /* cooked */
3428 {
3429 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3430 ENABLE_ECHO_INPUT);
3431 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3432 bEnableHandler = FALSE;
3433 }
3434 SetConsoleMode(g_hConIn, cmodein);
3435 SetConsoleMode(g_hConOut, cmodeout);
3436 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3437
3438#ifdef MCH_WRITE_DUMP
3439 if (fdDump)
3440 {
3441 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3442 tmode == TMODE_RAW ? "raw" :
3443 tmode == TMODE_COOK ? "cooked" : "normal",
3444 cmodein, cmodeout);
3445 fflush(fdDump);
3446 }
3447#endif
3448}
3449
3450
3451/*
3452 * Get the size of the current window in `Rows' and `Columns'
3453 * Return OK when size could be determined, FAIL otherwise.
3454 */
3455 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003456mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003457{
3458 CONSOLE_SCREEN_BUFFER_INFO csbi;
3459
3460 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3461 {
3462 /*
3463 * For some reason, we are trying to get the screen dimensions
3464 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3465 * variables are really intended to mean the size of Vim screen
3466 * while in termcap mode.
3467 */
3468 Rows = g_cbTermcap.Info.dwSize.Y;
3469 Columns = g_cbTermcap.Info.dwSize.X;
3470 }
3471 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3472 {
3473 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3474 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3475 }
3476 else
3477 {
3478 Rows = 25;
3479 Columns = 80;
3480 }
3481 return OK;
3482}
3483
3484/*
3485 * Set a console window to `xSize' * `ySize'
3486 */
3487 static void
3488ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003489 HANDLE hConsole,
3490 int xSize,
3491 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492{
3493 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3494 SMALL_RECT srWindowRect; /* hold the new console size */
3495 COORD coordScreen;
3496
3497#ifdef MCH_WRITE_DUMP
3498 if (fdDump)
3499 {
3500 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3501 fflush(fdDump);
3502 }
3503#endif
3504
3505 /* get the largest size we can size the console window to */
3506 coordScreen = GetLargestConsoleWindowSize(hConsole);
3507
3508 /* define the new console window size and scroll position */
3509 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3510 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3511 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3512
3513 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3514 {
3515 int sx, sy;
3516
3517 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3518 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3519 if (sy < ySize || sx < xSize)
3520 {
3521 /*
3522 * Increasing number of lines/columns, do buffer first.
3523 * Use the maximal size in x and y direction.
3524 */
3525 if (sy < ySize)
3526 coordScreen.Y = ySize;
3527 else
3528 coordScreen.Y = sy;
3529 if (sx < xSize)
3530 coordScreen.X = xSize;
3531 else
3532 coordScreen.X = sx;
3533 SetConsoleScreenBufferSize(hConsole, coordScreen);
3534 }
3535 }
3536
3537 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3538 {
3539#ifdef MCH_WRITE_DUMP
3540 if (fdDump)
3541 {
3542 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3543 GetLastError());
3544 fflush(fdDump);
3545 }
3546#endif
3547 }
3548
3549 /* define the new console buffer size */
3550 coordScreen.X = xSize;
3551 coordScreen.Y = ySize;
3552
3553 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3554 {
3555#ifdef MCH_WRITE_DUMP
3556 if (fdDump)
3557 {
3558 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3559 GetLastError());
3560 fflush(fdDump);
3561 }
3562#endif
3563 }
3564}
3565
3566
3567/*
3568 * Set the console window to `Rows' * `Columns'
3569 */
3570 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003571mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003572{
3573 COORD coordScreen;
3574
3575 /* Don't change window size while still starting up */
3576 if (suppress_winsize != 0)
3577 {
3578 suppress_winsize = 2;
3579 return;
3580 }
3581
3582 if (term_console)
3583 {
3584 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3585
3586 /* Clamp Rows and Columns to reasonable values */
3587 if (Rows > coordScreen.Y)
3588 Rows = coordScreen.Y;
3589 if (Columns > coordScreen.X)
3590 Columns = coordScreen.X;
3591
3592 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3593 }
3594}
3595
3596/*
3597 * Rows and/or Columns has changed.
3598 */
3599 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003600mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601{
3602 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3603}
3604
3605
3606/*
3607 * Called when started up, to set the winsize that was delayed.
3608 */
3609 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003610mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003611{
3612 if (suppress_winsize == 2)
3613 {
3614 suppress_winsize = 0;
3615 mch_set_shellsize();
3616 shell_resized();
3617 }
3618 suppress_winsize = 0;
3619}
3620#endif /* FEAT_GUI_W32 */
3621
3622
3623
3624#if defined(FEAT_GUI_W32) || defined(PROTO)
3625
3626/*
3627 * Specialised version of system() for Win32 GUI mode.
3628 * This version proceeds as follows:
3629 * 1. Create a console window for use by the subprocess
3630 * 2. Run the subprocess (it gets the allocated console by default)
3631 * 3. Wait for the subprocess to terminate and get its exit code
3632 * 4. Prompt the user to press a key to close the console window
3633 */
3634 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003635mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003636{
3637 STARTUPINFO si;
3638 PROCESS_INFORMATION pi;
3639 DWORD ret = 0;
3640 HWND hwnd = GetFocus();
3641
3642 si.cb = sizeof(si);
3643 si.lpReserved = NULL;
3644 si.lpDesktop = NULL;
3645 si.lpTitle = NULL;
3646 si.dwFlags = STARTF_USESHOWWINDOW;
3647 /*
3648 * It's nicer to run a filter command in a minimized window, but in
3649 * Windows 95 this makes the command MUCH slower. We can't do it under
3650 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003651 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652 */
3653 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003654 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655 else
3656 si.wShowWindow = SW_SHOWNORMAL;
3657 si.cbReserved2 = 0;
3658 si.lpReserved2 = NULL;
3659
3660 /* There is a strange error on Windows 95 when using "c:\\command.com".
3661 * When the "c:\\" is left out it works OK...? */
3662 if (mch_windows95()
3663 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3664 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3665 cmd += 3;
3666
3667 /* Now, run the command */
3668 CreateProcess(NULL, /* Executable name */
3669 cmd, /* Command to execute */
3670 NULL, /* Process security attributes */
3671 NULL, /* Thread security attributes */
3672 FALSE, /* Inherit handles */
3673 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3674 CREATE_NEW_CONSOLE,
3675 NULL, /* Environment */
3676 NULL, /* Current directory */
3677 &si, /* Startup information */
3678 &pi); /* Process information */
3679
3680
3681 /* Wait for the command to terminate before continuing */
3682 if (g_PlatformId != VER_PLATFORM_WIN32s)
3683 {
3684#ifdef FEAT_GUI
3685 int delay = 1;
3686
3687 /* Keep updating the window while waiting for the shell to finish. */
3688 for (;;)
3689 {
3690 MSG msg;
3691
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003692 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003693 {
3694 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003695 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003696 delay = 1;
3697 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698 }
3699 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3700 break;
3701
3702 /* We start waiting for a very short time and then increase it, so
3703 * that we respond quickly when the process is quick, and don't
3704 * consume too much overhead when it's slow. */
3705 if (delay < 50)
3706 delay += 10;
3707 }
3708#else
3709 WaitForSingleObject(pi.hProcess, INFINITE);
3710#endif
3711
3712 /* Get the command exit code */
3713 GetExitCodeProcess(pi.hProcess, &ret);
3714 }
3715 else
3716 {
3717 /*
3718 * This ugly code is the only quick way of performing
3719 * a synchronous spawn under Win32s. Yuk.
3720 */
3721 num_windows = 0;
3722 EnumWindows(win32ssynch_cb, 0);
3723 old_num_windows = num_windows;
3724 do
3725 {
3726 Sleep(1000);
3727 num_windows = 0;
3728 EnumWindows(win32ssynch_cb, 0);
3729 } while (num_windows == old_num_windows);
3730 ret = 0;
3731 }
3732
3733 /* Close the handles to the subprocess, so that it goes away */
3734 CloseHandle(pi.hThread);
3735 CloseHandle(pi.hProcess);
3736
3737 /* Try to get input focus back. Doesn't always work though. */
3738 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3739
3740 return ret;
3741}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003742
3743/*
3744 * Thread launched by the gui to send the current buffer data to the
3745 * process. This way avoid to hang up vim totally if the children
3746 * process take a long time to process the lines.
3747 */
3748 static DWORD WINAPI
3749sub_process_writer(LPVOID param)
3750{
3751 HANDLE g_hChildStd_IN_Wr = param;
3752 linenr_T lnum = curbuf->b_op_start.lnum;
3753 DWORD len = 0;
3754 DWORD l;
3755 char_u *lp = ml_get(lnum);
3756 char_u *s;
3757 int written = 0;
3758
3759 for (;;)
3760 {
3761 l = (DWORD)STRLEN(lp + written);
3762 if (l == 0)
3763 len = 0;
3764 else if (lp[written] == NL)
3765 {
3766 /* NL -> NUL translation */
3767 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3768 }
3769 else
3770 {
3771 s = vim_strchr(lp + written, NL);
3772 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3773 s == NULL ? l : (DWORD)(s - (lp + written)),
3774 &len, NULL);
3775 }
3776 if (len == (int)l)
3777 {
3778 /* Finished a line, add a NL, unless this line should not have
3779 * one. */
3780 if (lnum != curbuf->b_op_end.lnum
3781 || !curbuf->b_p_bin
3782 || (lnum != curbuf->b_no_eol_lnum
3783 && (lnum != curbuf->b_ml.ml_line_count
3784 || curbuf->b_p_eol)))
3785 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01003786 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003787 }
3788
3789 ++lnum;
3790 if (lnum > curbuf->b_op_end.lnum)
3791 break;
3792
3793 lp = ml_get(lnum);
3794 written = 0;
3795 }
3796 else if (len > 0)
3797 written += len;
3798 }
3799
3800 /* finished all the lines, close pipe */
3801 CloseHandle(g_hChildStd_IN_Wr);
3802 ExitThread(0);
3803}
3804
3805
3806# define BUFLEN 100 /* length for buffer, stolen from unix version */
3807
3808/*
3809 * This function read from the children's stdout and write the
3810 * data on screen or in the buffer accordingly.
3811 */
3812 static void
3813dump_pipe(int options,
3814 HANDLE g_hChildStd_OUT_Rd,
3815 garray_T *ga,
3816 char_u buffer[],
3817 DWORD *buffer_off)
3818{
3819 DWORD availableBytes = 0;
3820 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003821 int ret;
3822 DWORD len;
3823 DWORD toRead;
3824 int repeatCount;
3825
3826 /* we query the pipe to see if there is any data to read
3827 * to avoid to perform a blocking read */
3828 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3829 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003830 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003831 NULL, /* number of read bytes */
3832 &availableBytes, /* available bytes total */
3833 NULL); /* byteLeft */
3834
3835 repeatCount = 0;
3836 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003837 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003838 {
3839 repeatCount++;
3840 toRead =
3841# ifdef FEAT_MBYTE
3842 (DWORD)(BUFLEN - *buffer_off);
3843# else
3844 (DWORD)BUFLEN;
3845# endif
3846 toRead = availableBytes < toRead ? availableBytes : toRead;
3847 ReadFile(g_hChildStd_OUT_Rd, buffer
3848# ifdef FEAT_MBYTE
3849 + *buffer_off, toRead
3850# else
3851 , toRead
3852# endif
3853 , &len, NULL);
3854
3855 /* If we haven't read anything, there is a problem */
3856 if (len == 0)
3857 break;
3858
3859 availableBytes -= len;
3860
3861 if (options & SHELL_READ)
3862 {
3863 /* Do NUL -> NL translation, append NL separated
3864 * lines to the current buffer. */
3865 for (i = 0; i < len; ++i)
3866 {
3867 if (buffer[i] == NL)
3868 append_ga_line(ga);
3869 else if (buffer[i] == NUL)
3870 ga_append(ga, NL);
3871 else
3872 ga_append(ga, buffer[i]);
3873 }
3874 }
3875# ifdef FEAT_MBYTE
3876 else if (has_mbyte)
3877 {
3878 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003879 int c;
3880 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003881
3882 len += *buffer_off;
3883 buffer[len] = NUL;
3884
3885 /* Check if the last character in buffer[] is
3886 * incomplete, keep these bytes for the next
3887 * round. */
3888 for (p = buffer; p < buffer + len; p += l)
3889 {
3890 l = mb_cptr2len(p);
3891 if (l == 0)
3892 l = 1; /* NUL byte? */
3893 else if (MB_BYTE2LEN(*p) != l)
3894 break;
3895 }
3896 if (p == buffer) /* no complete character */
3897 {
3898 /* avoid getting stuck at an illegal byte */
3899 if (len >= 12)
3900 ++p;
3901 else
3902 {
3903 *buffer_off = len;
3904 return;
3905 }
3906 }
3907 c = *p;
3908 *p = NUL;
3909 msg_puts(buffer);
3910 if (p < buffer + len)
3911 {
3912 *p = c;
3913 *buffer_off = (DWORD)((buffer + len) - p);
3914 mch_memmove(buffer, p, *buffer_off);
3915 return;
3916 }
3917 *buffer_off = 0;
3918 }
3919# endif /* FEAT_MBYTE */
3920 else
3921 {
3922 buffer[len] = NUL;
3923 msg_puts(buffer);
3924 }
3925
3926 windgoto(msg_row, msg_col);
3927 cursor_on();
3928 out_flush();
3929 }
3930}
3931
3932/*
3933 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
3934 * for communication and doesn't open any new window.
3935 */
3936 static int
3937mch_system_piped(char *cmd, int options)
3938{
3939 STARTUPINFO si;
3940 PROCESS_INFORMATION pi;
3941 DWORD ret = 0;
3942
3943 HANDLE g_hChildStd_IN_Rd = NULL;
3944 HANDLE g_hChildStd_IN_Wr = NULL;
3945 HANDLE g_hChildStd_OUT_Rd = NULL;
3946 HANDLE g_hChildStd_OUT_Wr = NULL;
3947
3948 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
3949 DWORD len;
3950
3951 /* buffer used to receive keys */
3952 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3953 int ta_len = 0; /* valid bytes in ta_buf[] */
3954
3955 DWORD i;
3956 int c;
3957 int noread_cnt = 0;
3958 garray_T ga;
3959 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003960 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003961 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003962
3963 SECURITY_ATTRIBUTES saAttr;
3964
3965 /* Set the bInheritHandle flag so pipe handles are inherited. */
3966 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
3967 saAttr.bInheritHandle = TRUE;
3968 saAttr.lpSecurityDescriptor = NULL;
3969
3970 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
3971 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
3972 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
3973 /* Create a pipe for the child process's STDIN. */
3974 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
3975 /* Ensure the write handle to the pipe for STDIN is not inherited. */
3976 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
3977 {
3978 CloseHandle(g_hChildStd_IN_Rd);
3979 CloseHandle(g_hChildStd_IN_Wr);
3980 CloseHandle(g_hChildStd_OUT_Rd);
3981 CloseHandle(g_hChildStd_OUT_Wr);
3982 MSG_PUTS(_("\nCannot create pipes\n"));
3983 }
3984
3985 si.cb = sizeof(si);
3986 si.lpReserved = NULL;
3987 si.lpDesktop = NULL;
3988 si.lpTitle = NULL;
3989 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
3990
3991 /* set-up our file redirection */
3992 si.hStdError = g_hChildStd_OUT_Wr;
3993 si.hStdOutput = g_hChildStd_OUT_Wr;
3994 si.hStdInput = g_hChildStd_IN_Rd;
3995 si.wShowWindow = SW_HIDE;
3996 si.cbReserved2 = 0;
3997 si.lpReserved2 = NULL;
3998
3999 if (options & SHELL_READ)
4000 ga_init2(&ga, 1, BUFLEN);
4001
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004002 if (cmd != NULL)
4003 {
4004 p = (char *)vim_strsave((char_u *)cmd);
4005 if (p != NULL)
4006 unescape_shellxquote((char_u *)p, p_sxe);
4007 else
4008 p = cmd;
4009 }
4010
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004011 /* Now, run the command */
4012 CreateProcess(NULL, /* Executable name */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004013 p, /* Command to execute */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004014 NULL, /* Process security attributes */
4015 NULL, /* Thread security attributes */
4016
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004017 // this command can be litigious, handle inheritance was
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004018 // deactivated for pending temp file, but, if we deactivate
4019 // it, the pipes don't work for some reason.
4020 TRUE, /* Inherit handles, first deactivated,
4021 * but needed */
4022 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
4023 NULL, /* Environment */
4024 NULL, /* Current directory */
4025 &si, /* Startup information */
4026 &pi); /* Process information */
4027
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004028 if (p != cmd)
4029 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004030
4031 /* Close our unused side of the pipes */
4032 CloseHandle(g_hChildStd_IN_Rd);
4033 CloseHandle(g_hChildStd_OUT_Wr);
4034
4035 if (options & SHELL_WRITE)
4036 {
4037 HANDLE thread =
4038 CreateThread(NULL, /* security attributes */
4039 0, /* default stack size */
4040 sub_process_writer, /* function to be executed */
4041 g_hChildStd_IN_Wr, /* parameter */
4042 0, /* creation flag, start immediately */
4043 NULL); /* we don't care about thread id */
4044 CloseHandle(thread);
4045 g_hChildStd_IN_Wr = NULL;
4046 }
4047
4048 /* Keep updating the window while waiting for the shell to finish. */
4049 for (;;)
4050 {
4051 MSG msg;
4052
4053 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4054 {
4055 TranslateMessage(&msg);
4056 DispatchMessage(&msg);
4057 }
4058
4059 /* write pipe information in the window */
4060 if ((options & (SHELL_READ|SHELL_WRITE))
4061# ifdef FEAT_GUI
4062 || gui.in_use
4063# endif
4064 )
4065 {
4066 len = 0;
4067 if (!(options & SHELL_EXPAND)
4068 && ((options &
4069 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4070 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4071# ifdef FEAT_GUI
4072 || gui.in_use
4073# endif
4074 )
4075 && (ta_len > 0 || noread_cnt > 4))
4076 {
4077 if (ta_len == 0)
4078 {
4079 /* Get extra characters when we don't have any. Reset the
4080 * counter and timer. */
4081 noread_cnt = 0;
4082# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4083 gettimeofday(&start_tv, NULL);
4084# endif
4085 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4086 }
4087 if (ta_len > 0 || len > 0)
4088 {
4089 /*
4090 * For pipes: Check for CTRL-C: send interrupt signal to
4091 * child. Check for CTRL-D: EOF, close pipe to child.
4092 */
4093 if (len == 1 && cmd != NULL)
4094 {
4095 if (ta_buf[ta_len] == Ctrl_C)
4096 {
4097 /* Learn what exit code is expected, for
4098 * now put 9 as SIGKILL */
4099 TerminateProcess(pi.hProcess, 9);
4100 }
4101 if (ta_buf[ta_len] == Ctrl_D)
4102 {
4103 CloseHandle(g_hChildStd_IN_Wr);
4104 g_hChildStd_IN_Wr = NULL;
4105 }
4106 }
4107
4108 /* replace K_BS by <BS> and K_DEL by <DEL> */
4109 for (i = ta_len; i < ta_len + len; ++i)
4110 {
4111 if (ta_buf[i] == CSI && len - i > 2)
4112 {
4113 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4114 if (c == K_DEL || c == K_KDEL || c == K_BS)
4115 {
4116 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4117 (size_t)(len - i - 2));
4118 if (c == K_DEL || c == K_KDEL)
4119 ta_buf[i] = DEL;
4120 else
4121 ta_buf[i] = Ctrl_H;
4122 len -= 2;
4123 }
4124 }
4125 else if (ta_buf[i] == '\r')
4126 ta_buf[i] = '\n';
4127# ifdef FEAT_MBYTE
4128 if (has_mbyte)
4129 i += (*mb_ptr2len_len)(ta_buf + i,
4130 ta_len + len - i) - 1;
4131# endif
4132 }
4133
4134 /*
4135 * For pipes: echo the typed characters. For a pty this
4136 * does not seem to work.
4137 */
4138 for (i = ta_len; i < ta_len + len; ++i)
4139 {
4140 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4141 msg_putchar(ta_buf[i]);
4142# ifdef FEAT_MBYTE
4143 else if (has_mbyte)
4144 {
4145 int l = (*mb_ptr2len)(ta_buf + i);
4146
4147 msg_outtrans_len(ta_buf + i, l);
4148 i += l - 1;
4149 }
4150# endif
4151 else
4152 msg_outtrans_len(ta_buf + i, 1);
4153 }
4154 windgoto(msg_row, msg_col);
4155 out_flush();
4156
4157 ta_len += len;
4158
4159 /*
4160 * Write the characters to the child, unless EOF has been
4161 * typed for pipes. Write one character at a time, to
4162 * avoid losing too much typeahead. When writing buffer
4163 * lines, drop the typed characters (only check for
4164 * CTRL-C).
4165 */
4166 if (options & SHELL_WRITE)
4167 ta_len = 0;
4168 else if (g_hChildStd_IN_Wr != NULL)
4169 {
4170 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4171 1, &len, NULL);
4172 // if we are typing in, we want to keep things reactive
4173 delay = 1;
4174 if (len > 0)
4175 {
4176 ta_len -= len;
4177 mch_memmove(ta_buf, ta_buf + len, ta_len);
4178 }
4179 }
4180 }
4181 }
4182 }
4183
4184 if (ta_len)
4185 ui_inchar_undo(ta_buf, ta_len);
4186
4187 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4188 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004189 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004190 break;
4191 }
4192
4193 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004194 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004195
4196 /* We start waiting for a very short time and then increase it, so
4197 * that we respond quickly when the process is quick, and don't
4198 * consume too much overhead when it's slow. */
4199 if (delay < 50)
4200 delay += 10;
4201 }
4202
4203 /* Close the pipe */
4204 CloseHandle(g_hChildStd_OUT_Rd);
4205 if (g_hChildStd_IN_Wr != NULL)
4206 CloseHandle(g_hChildStd_IN_Wr);
4207
4208 WaitForSingleObject(pi.hProcess, INFINITE);
4209
4210 /* Get the command exit code */
4211 GetExitCodeProcess(pi.hProcess, &ret);
4212
4213 if (options & SHELL_READ)
4214 {
4215 if (ga.ga_len > 0)
4216 {
4217 append_ga_line(&ga);
4218 /* remember that the NL was missing */
4219 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4220 }
4221 else
4222 curbuf->b_no_eol_lnum = 0;
4223 ga_clear(&ga);
4224 }
4225
4226 /* Close the handles to the subprocess, so that it goes away */
4227 CloseHandle(pi.hThread);
4228 CloseHandle(pi.hProcess);
4229
4230 return ret;
4231}
4232
4233 static int
4234mch_system(char *cmd, int options)
4235{
4236 /* if we can pipe and the shelltemp option is off */
4237 if (allowPiping && !p_stmp)
4238 return mch_system_piped(cmd, options);
4239 else
4240 return mch_system_classic(cmd, options);
4241}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004242#else
4243
4244# define mch_system(c, o) system(c)
4245
4246#endif
4247
4248/*
4249 * Either execute a command by calling the shell or start a new shell
4250 */
4251 int
4252mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004253 char_u *cmd,
4254 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004255{
4256 int x = 0;
4257 int tmode = cur_tmode;
4258#ifdef FEAT_TITLE
4259 char szShellTitle[512];
4260
4261 /* Change the title to reflect that we are in a subshell. */
4262 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
4263 {
4264 if (cmd == NULL)
4265 strcat(szShellTitle, " :sh");
4266 else
4267 {
4268 strcat(szShellTitle, " - !");
4269 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4270 strcat(szShellTitle, cmd);
4271 }
4272 mch_settitle(szShellTitle, NULL);
4273 }
4274#endif
4275
4276 out_flush();
4277
4278#ifdef MCH_WRITE_DUMP
4279 if (fdDump)
4280 {
4281 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4282 fflush(fdDump);
4283 }
4284#endif
4285
4286 /*
4287 * Catch all deadly signals while running the external command, because a
4288 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4289 */
4290 signal(SIGINT, SIG_IGN);
4291#if defined(__GNUC__) && !defined(__MINGW32__)
4292 signal(SIGKILL, SIG_IGN);
4293#else
4294 signal(SIGBREAK, SIG_IGN);
4295#endif
4296 signal(SIGILL, SIG_IGN);
4297 signal(SIGFPE, SIG_IGN);
4298 signal(SIGSEGV, SIG_IGN);
4299 signal(SIGTERM, SIG_IGN);
4300 signal(SIGABRT, SIG_IGN);
4301
4302 if (options & SHELL_COOKED)
4303 settmode(TMODE_COOK); /* set to normal mode */
4304
4305 if (cmd == NULL)
4306 {
4307 x = mch_system(p_sh, options);
4308 }
4309 else
4310 {
4311 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004312 char_u *newcmd = NULL;
4313 char_u *cmdbase = cmd;
4314 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004315
4316 /* Skip a leading ", ( and "(. */
4317 if (*cmdbase == '"' )
4318 ++cmdbase;
4319 if (*cmdbase == '(')
4320 ++cmdbase;
4321
4322 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4323 {
4324 STARTUPINFO si;
4325 PROCESS_INFORMATION pi;
4326 DWORD flags = CREATE_NEW_CONSOLE;
4327 char_u *p;
4328
4329 si.cb = sizeof(si);
4330 si.lpReserved = NULL;
4331 si.lpDesktop = NULL;
4332 si.lpTitle = NULL;
4333 si.dwFlags = 0;
4334 si.cbReserved2 = 0;
4335 si.lpReserved2 = NULL;
4336
4337 cmdbase = skipwhite(cmdbase + 5);
4338 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4339 && vim_iswhite(cmdbase[4]))
4340 {
4341 cmdbase = skipwhite(cmdbase + 4);
4342 si.dwFlags = STARTF_USESHOWWINDOW;
4343 si.wShowWindow = SW_SHOWMINNOACTIVE;
4344 }
4345 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4346 && vim_iswhite(cmdbase[2]))
4347 {
4348 cmdbase = skipwhite(cmdbase + 2);
4349 flags = CREATE_NO_WINDOW;
4350 si.dwFlags = STARTF_USESTDHANDLES;
4351 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004352 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004353 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004354 NULL, // Security att.
4355 OPEN_EXISTING, // Open flags
4356 FILE_ATTRIBUTE_NORMAL, // File att.
4357 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004358 si.hStdOutput = si.hStdInput;
4359 si.hStdError = si.hStdInput;
4360 }
4361
4362 /* Remove a trailing ", ) and )" if they have a match
4363 * at the start of the command. */
4364 if (cmdbase > cmd)
4365 {
4366 p = cmdbase + STRLEN(cmdbase);
4367 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4368 *--p = NUL;
4369 if (p > cmdbase && p[-1] == ')'
4370 && (*cmd =='(' || cmd[1] == '('))
4371 *--p = NUL;
4372 }
4373
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004374 newcmd = cmdbase;
4375 unescape_shellxquote(cmdbase, p_sxe);
4376
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004377 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004378 * If creating new console, arguments are passed to the
4379 * 'cmd.exe' as-is. If it's not, arguments are not treated
4380 * correctly for current 'cmd.exe'. So unescape characters in
4381 * shellxescape except '|' for avoiding to be treated as
4382 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004383 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004384 if (flags != CREATE_NEW_CONSOLE)
4385 {
4386 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004387 char_u *cmd_shell = mch_getenv("COMSPEC");
4388
4389 if (cmd_shell == NULL || *cmd_shell == NUL)
4390 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004391
4392 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4393 if (subcmd != NULL)
4394 {
4395 /* make "cmd.exe /c arguments" */
4396 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004397 newcmd = lalloc(cmdlen, TRUE);
4398 if (newcmd != NULL)
4399 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004400 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004401 else
4402 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004403 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004404 }
4405 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004406
4407 /*
4408 * Now, start the command as a process, so that it doesn't
4409 * inherit our handles which causes unpleasant dangling swap
4410 * files if we exit before the spawned process
4411 */
4412 if (CreateProcess(NULL, // Executable name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004413 newcmd, // Command to execute
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004414 NULL, // Process security attributes
4415 NULL, // Thread security attributes
4416 FALSE, // Inherit handles
4417 flags, // Creation flags
4418 NULL, // Environment
4419 NULL, // Current directory
4420 &si, // Startup information
4421 &pi)) // Process information
4422 x = 0;
4423 else
4424 {
4425 x = -1;
4426#ifdef FEAT_GUI_W32
4427 EMSG(_("E371: Command not found"));
4428#endif
4429 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004430
4431 if (newcmd != cmdbase)
4432 vim_free(newcmd);
4433
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004434 if (si.hStdInput != NULL)
4435 {
4436 /* Close the handle to \\.\NUL */
4437 CloseHandle(si.hStdInput);
4438 }
4439 /* Close the handles to the subprocess, so that it goes away */
4440 CloseHandle(pi.hThread);
4441 CloseHandle(pi.hProcess);
4442 }
4443 else
4444 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004445 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004446#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004447 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004449 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4450
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004451 newcmd = lalloc(cmdlen, TRUE);
4452 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453 {
4454#if defined(FEAT_GUI_W32)
4455 if (need_vimrun_warning)
4456 {
4457 MessageBox(NULL,
4458 _("VIMRUN.EXE not found in your $PATH.\n"
4459 "External commands will not pause after completion.\n"
4460 "See :help win32-vimrun for more information."),
4461 _("Vim Warning"),
4462 MB_ICONWARNING);
4463 need_vimrun_warning = FALSE;
4464 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004465 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004466 /* Use vimrun to execute the command. It opens a console
4467 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004468 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004469 vimrun_path,
4470 (msg_silent != 0 || (options & SHELL_DOOUT))
4471 ? "-s " : "",
4472 p_sh, p_shcf, cmd);
4473 else
4474#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004475 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004476 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004478 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004479 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004480 }
4481 }
4482
4483 if (tmode == TMODE_RAW)
4484 settmode(TMODE_RAW); /* set to raw mode */
4485
4486 /* Print the return value, unless "vimrun" was used. */
4487 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4488#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004489 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4490 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004491#endif
4492 )
4493 {
4494 smsg(_("shell returned %d"), x);
4495 msg_putchar('\n');
4496 }
4497#ifdef FEAT_TITLE
4498 resettitle();
4499#endif
4500
4501 signal(SIGINT, SIG_DFL);
4502#if defined(__GNUC__) && !defined(__MINGW32__)
4503 signal(SIGKILL, SIG_DFL);
4504#else
4505 signal(SIGBREAK, SIG_DFL);
4506#endif
4507 signal(SIGILL, SIG_DFL);
4508 signal(SIGFPE, SIG_DFL);
4509 signal(SIGSEGV, SIG_DFL);
4510 signal(SIGTERM, SIG_DFL);
4511 signal(SIGABRT, SIG_DFL);
4512
4513 return x;
4514}
4515
4516
4517#ifndef FEAT_GUI_W32
4518
4519/*
4520 * Start termcap mode
4521 */
4522 static void
4523termcap_mode_start(void)
4524{
4525 DWORD cmodein;
4526
4527 if (g_fTermcapMode)
4528 return;
4529
4530 SaveConsoleBuffer(&g_cbNonTermcap);
4531
4532 if (g_cbTermcap.IsValid)
4533 {
4534 /*
4535 * We've been in termcap mode before. Restore certain screen
4536 * characteristics, including the buffer size and the window
4537 * size. Since we will be redrawing the screen, we don't need
4538 * to restore the actual contents of the buffer.
4539 */
4540 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4541 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4542 Rows = g_cbTermcap.Info.dwSize.Y;
4543 Columns = g_cbTermcap.Info.dwSize.X;
4544 }
4545 else
4546 {
4547 /*
4548 * This is our first time entering termcap mode. Clear the console
4549 * screen buffer, and resize the buffer to match the current window
4550 * size. We will use this as the size of our editing environment.
4551 */
4552 ClearConsoleBuffer(g_attrCurrent);
4553 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4554 }
4555
4556#ifdef FEAT_TITLE
4557 resettitle();
4558#endif
4559
4560 GetConsoleMode(g_hConIn, &cmodein);
4561#ifdef FEAT_MOUSE
4562 if (g_fMouseActive)
4563 cmodein |= ENABLE_MOUSE_INPUT;
4564 else
4565 cmodein &= ~ENABLE_MOUSE_INPUT;
4566#endif
4567 cmodein |= ENABLE_WINDOW_INPUT;
4568 SetConsoleMode(g_hConIn, cmodein);
4569
4570 redraw_later_clear();
4571 g_fTermcapMode = TRUE;
4572}
4573
4574
4575/*
4576 * End termcap mode
4577 */
4578 static void
4579termcap_mode_end(void)
4580{
4581 DWORD cmodein;
4582 ConsoleBuffer *cb;
4583 COORD coord;
4584 DWORD dwDummy;
4585
4586 if (!g_fTermcapMode)
4587 return;
4588
4589 SaveConsoleBuffer(&g_cbTermcap);
4590
4591 GetConsoleMode(g_hConIn, &cmodein);
4592 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4593 SetConsoleMode(g_hConIn, cmodein);
4594
4595#ifdef FEAT_RESTORE_ORIG_SCREEN
4596 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4597#else
4598 cb = &g_cbNonTermcap;
4599#endif
4600 RestoreConsoleBuffer(cb, p_rs);
4601 SetConsoleCursorInfo(g_hConOut, &g_cci);
4602
4603 if (p_rs || exiting)
4604 {
4605 /*
4606 * Clear anything that happens to be on the current line.
4607 */
4608 coord.X = 0;
4609 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4610 FillConsoleOutputCharacter(g_hConOut, ' ',
4611 cb->Info.dwSize.X, coord, &dwDummy);
4612 /*
4613 * The following is just for aesthetics. If we are exiting without
4614 * restoring the screen, then we want to have a prompt string
4615 * appear at the bottom line. However, the command interpreter
4616 * seems to always advance the cursor one line before displaying
4617 * the prompt string, which causes the screen to scroll. To
4618 * counter this, move the cursor up one line before exiting.
4619 */
4620 if (exiting && !p_rs)
4621 coord.Y--;
4622 /*
4623 * Position the cursor at the leftmost column of the desired row.
4624 */
4625 SetConsoleCursorPosition(g_hConOut, coord);
4626 }
4627
4628 g_fTermcapMode = FALSE;
4629}
4630#endif /* FEAT_GUI_W32 */
4631
4632
4633#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004634/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004635 void
4636mch_write(
4637 char_u *s,
4638 int len)
4639{
4640 /* never used */
4641}
4642
4643#else
4644
4645/*
4646 * clear `n' chars, starting from `coord'
4647 */
4648 static void
4649clear_chars(
4650 COORD coord,
4651 DWORD n)
4652{
4653 DWORD dwDummy;
4654
4655 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4656 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4657}
4658
4659
4660/*
4661 * Clear the screen
4662 */
4663 static void
4664clear_screen(void)
4665{
4666 g_coord.X = g_coord.Y = 0;
4667 clear_chars(g_coord, Rows * Columns);
4668}
4669
4670
4671/*
4672 * Clear to end of display
4673 */
4674 static void
4675clear_to_end_of_display(void)
4676{
4677 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4678 * Columns + (Columns - g_coord.X));
4679}
4680
4681
4682/*
4683 * Clear to end of line
4684 */
4685 static void
4686clear_to_end_of_line(void)
4687{
4688 clear_chars(g_coord, Columns - g_coord.X);
4689}
4690
4691
4692/*
4693 * Scroll the scroll region up by `cLines' lines
4694 */
4695 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004696scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004697{
4698 COORD oldcoord = g_coord;
4699
4700 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4701 delete_lines(cLines);
4702
4703 g_coord = oldcoord;
4704}
4705
4706
4707/*
4708 * Set the scroll region
4709 */
4710 static void
4711set_scroll_region(
4712 unsigned left,
4713 unsigned top,
4714 unsigned right,
4715 unsigned bottom)
4716{
4717 if (left >= right
4718 || top >= bottom
4719 || right > (unsigned) Columns - 1
4720 || bottom > (unsigned) Rows - 1)
4721 return;
4722
4723 g_srScrollRegion.Left = left;
4724 g_srScrollRegion.Top = top;
4725 g_srScrollRegion.Right = right;
4726 g_srScrollRegion.Bottom = bottom;
4727}
4728
4729
4730/*
4731 * Insert `cLines' lines at the current cursor position
4732 */
4733 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004734insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004735{
4736 SMALL_RECT source;
4737 COORD dest;
4738 CHAR_INFO fill;
4739
4740 dest.X = 0;
4741 dest.Y = g_coord.Y + cLines;
4742
4743 source.Left = 0;
4744 source.Top = g_coord.Y;
4745 source.Right = g_srScrollRegion.Right;
4746 source.Bottom = g_srScrollRegion.Bottom - cLines;
4747
4748 fill.Char.AsciiChar = ' ';
4749 fill.Attributes = g_attrCurrent;
4750
4751 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4752
4753 /* Here we have to deal with a win32 console flake: If the scroll
4754 * region looks like abc and we scroll c to a and fill with d we get
4755 * cbd... if we scroll block c one line at a time to a, we get cdd...
4756 * vim expects cdd consistently... So we have to deal with that
4757 * here... (this also occurs scrolling the same way in the other
4758 * direction). */
4759
4760 if (source.Bottom < dest.Y)
4761 {
4762 COORD coord;
4763
4764 coord.X = 0;
4765 coord.Y = source.Bottom;
4766 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4767 }
4768}
4769
4770
4771/*
4772 * Delete `cLines' lines at the current cursor position
4773 */
4774 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004775delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776{
4777 SMALL_RECT source;
4778 COORD dest;
4779 CHAR_INFO fill;
4780 int nb;
4781
4782 dest.X = 0;
4783 dest.Y = g_coord.Y;
4784
4785 source.Left = 0;
4786 source.Top = g_coord.Y + cLines;
4787 source.Right = g_srScrollRegion.Right;
4788 source.Bottom = g_srScrollRegion.Bottom;
4789
4790 fill.Char.AsciiChar = ' ';
4791 fill.Attributes = g_attrCurrent;
4792
4793 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4794
4795 /* Here we have to deal with a win32 console flake: If the scroll
4796 * region looks like abc and we scroll c to a and fill with d we get
4797 * cbd... if we scroll block c one line at a time to a, we get cdd...
4798 * vim expects cdd consistently... So we have to deal with that
4799 * here... (this also occurs scrolling the same way in the other
4800 * direction). */
4801
4802 nb = dest.Y + (source.Bottom - source.Top) + 1;
4803
4804 if (nb < source.Top)
4805 {
4806 COORD coord;
4807
4808 coord.X = 0;
4809 coord.Y = nb;
4810 clear_chars(coord, Columns * (source.Top - nb));
4811 }
4812}
4813
4814
4815/*
4816 * Set the cursor position
4817 */
4818 static void
4819gotoxy(
4820 unsigned x,
4821 unsigned y)
4822{
4823 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4824 return;
4825
4826 /* external cursor coords are 1-based; internal are 0-based */
4827 g_coord.X = x - 1;
4828 g_coord.Y = y - 1;
4829 SetConsoleCursorPosition(g_hConOut, g_coord);
4830}
4831
4832
4833/*
4834 * Set the current text attribute = (foreground | background)
4835 * See ../doc/os_win32.txt for the numbers.
4836 */
4837 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004838textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004839{
4840 g_attrCurrent = wAttr;
4841
4842 SetConsoleTextAttribute(g_hConOut, wAttr);
4843}
4844
4845
4846 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004847textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004848{
4849 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
4850
4851 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4852}
4853
4854
4855 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004856textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857{
4858 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
4859
4860 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4861}
4862
4863
4864/*
4865 * restore the default text attribute (whatever we started with)
4866 */
4867 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004868normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004869{
4870 textattr(g_attrDefault);
4871}
4872
4873
4874static WORD g_attrPreStandout = 0;
4875
4876/*
4877 * Make the text standout, by brightening it
4878 */
4879 static void
4880standout(void)
4881{
4882 g_attrPreStandout = g_attrCurrent;
4883 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
4884}
4885
4886
4887/*
4888 * Turn off standout mode
4889 */
4890 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004891standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004892{
4893 if (g_attrPreStandout)
4894 {
4895 textattr(g_attrPreStandout);
4896 g_attrPreStandout = 0;
4897 }
4898}
4899
4900
4901/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00004902 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903 */
4904 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004905mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906{
4907 char_u *p;
4908 int n;
4909
4910 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
4911 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
4912 if (T_ME[0] == ESC && T_ME[1] == '|')
4913 {
4914 p = T_ME + 2;
4915 n = getdigits(&p);
4916 if (*p == 'm' && n > 0)
4917 {
4918 cterm_normal_fg_color = (n & 0xf) + 1;
4919 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
4920 }
4921 }
4922}
4923
4924
4925/*
4926 * visual bell: flash the screen
4927 */
4928 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004929visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930{
4931 COORD coordOrigin = {0, 0};
4932 WORD attrFlash = ~g_attrCurrent & 0xff;
4933
4934 DWORD dwDummy;
4935 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
4936
4937 if (oldattrs == NULL)
4938 return;
4939 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4940 coordOrigin, &dwDummy);
4941 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
4942 coordOrigin, &dwDummy);
4943
4944 Sleep(15); /* wait for 15 msec */
4945 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4946 coordOrigin, &dwDummy);
4947 vim_free(oldattrs);
4948}
4949
4950
4951/*
4952 * Make the cursor visible or invisible
4953 */
4954 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004955cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004956{
4957 s_cursor_visible = fVisible;
4958#ifdef MCH_CURSOR_SHAPE
4959 mch_update_cursor();
4960#endif
4961}
4962
4963
4964/*
4965 * write `cchToWrite' characters in `pchBuf' to the screen
4966 * Returns the number of characters actually written (at least one).
4967 */
4968 static BOOL
4969write_chars(
4970 LPCSTR pchBuf,
4971 DWORD cchToWrite)
4972{
4973 COORD coord = g_coord;
4974 DWORD written;
4975
4976 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
4977 coord, &written);
4978 /* When writing fails or didn't write a single character, pretend one
4979 * character was written, otherwise we get stuck. */
4980 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
4981 coord, &written) == 0
4982 || written == 0)
4983 written = 1;
4984
4985 g_coord.X += (SHORT) written;
4986
4987 while (g_coord.X > g_srScrollRegion.Right)
4988 {
4989 g_coord.X -= (SHORT) Columns;
4990 if (g_coord.Y < g_srScrollRegion.Bottom)
4991 g_coord.Y++;
4992 }
4993
4994 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4995
4996 return written;
4997}
4998
4999
5000/*
5001 * mch_write(): write the output buffer to the screen, translating ESC
5002 * sequences into calls to console output routines.
5003 */
5004 void
5005mch_write(
5006 char_u *s,
5007 int len)
5008{
5009 s[len] = NUL;
5010
5011 if (!term_console)
5012 {
5013 write(1, s, (unsigned)len);
5014 return;
5015 }
5016
5017 /* translate ESC | sequences into faked bios calls */
5018 while (len--)
5019 {
5020 /* optimization: use one single write_chars for runs of text,
5021 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005022 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023
5024 if (p_wd)
5025 {
5026 WaitForChar(p_wd);
5027 if (prefix != 0)
5028 prefix = 1;
5029 }
5030
5031 if (prefix != 0)
5032 {
5033 DWORD nWritten;
5034
5035 nWritten = write_chars(s, prefix);
5036#ifdef MCH_WRITE_DUMP
5037 if (fdDump)
5038 {
5039 fputc('>', fdDump);
5040 fwrite(s, sizeof(char_u), nWritten, fdDump);
5041 fputs("<\n", fdDump);
5042 }
5043#endif
5044 len -= (nWritten - 1);
5045 s += nWritten;
5046 }
5047 else if (s[0] == '\n')
5048 {
5049 /* \n, newline: go to the beginning of the next line or scroll */
5050 if (g_coord.Y == g_srScrollRegion.Bottom)
5051 {
5052 scroll(1);
5053 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5054 }
5055 else
5056 {
5057 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5058 }
5059#ifdef MCH_WRITE_DUMP
5060 if (fdDump)
5061 fputs("\\n\n", fdDump);
5062#endif
5063 s++;
5064 }
5065 else if (s[0] == '\r')
5066 {
5067 /* \r, carriage return: go to beginning of line */
5068 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5069#ifdef MCH_WRITE_DUMP
5070 if (fdDump)
5071 fputs("\\r\n", fdDump);
5072#endif
5073 s++;
5074 }
5075 else if (s[0] == '\b')
5076 {
5077 /* \b, backspace: move cursor one position left */
5078 if (g_coord.X > g_srScrollRegion.Left)
5079 g_coord.X--;
5080 else if (g_coord.Y > g_srScrollRegion.Top)
5081 {
5082 g_coord.X = g_srScrollRegion.Right;
5083 g_coord.Y--;
5084 }
5085 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5086#ifdef MCH_WRITE_DUMP
5087 if (fdDump)
5088 fputs("\\b\n", fdDump);
5089#endif
5090 s++;
5091 }
5092 else if (s[0] == '\a')
5093 {
5094 /* \a, bell */
5095 MessageBeep(0xFFFFFFFF);
5096#ifdef MCH_WRITE_DUMP
5097 if (fdDump)
5098 fputs("\\a\n", fdDump);
5099#endif
5100 s++;
5101 }
5102 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5103 {
5104#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005105 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005107 char_u *p;
5108 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005109
5110 switch (s[2])
5111 {
5112 /* one or two numeric arguments, separated by ';' */
5113
5114 case '0': case '1': case '2': case '3': case '4':
5115 case '5': case '6': case '7': case '8': case '9':
5116 p = s + 2;
5117 arg1 = getdigits(&p); /* no check for length! */
5118 if (p > s + len)
5119 break;
5120
5121 if (*p == ';')
5122 {
5123 ++p;
5124 arg2 = getdigits(&p); /* no check for length! */
5125 if (p > s + len)
5126 break;
5127
5128 if (*p == 'H')
5129 gotoxy(arg2, arg1);
5130 else if (*p == 'r')
5131 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5132 }
5133 else if (*p == 'A')
5134 {
5135 /* move cursor up arg1 lines in same column */
5136 gotoxy(g_coord.X + 1,
5137 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5138 }
5139 else if (*p == 'C')
5140 {
5141 /* move cursor right arg1 columns in same line */
5142 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5143 g_coord.Y + 1);
5144 }
5145 else if (*p == 'H')
5146 {
5147 gotoxy(1, arg1);
5148 }
5149 else if (*p == 'L')
5150 {
5151 insert_lines(arg1);
5152 }
5153 else if (*p == 'm')
5154 {
5155 if (arg1 == 0)
5156 normvideo();
5157 else
5158 textattr((WORD) arg1);
5159 }
5160 else if (*p == 'f')
5161 {
5162 textcolor((WORD) arg1);
5163 }
5164 else if (*p == 'b')
5165 {
5166 textbackground((WORD) arg1);
5167 }
5168 else if (*p == 'M')
5169 {
5170 delete_lines(arg1);
5171 }
5172
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005173 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005174 s = p + 1;
5175 break;
5176
5177
5178 /* Three-character escape sequences */
5179
5180 case 'A':
5181 /* move cursor up one line in same column */
5182 gotoxy(g_coord.X + 1,
5183 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5184 goto got3;
5185
5186 case 'B':
5187 visual_bell();
5188 goto got3;
5189
5190 case 'C':
5191 /* move cursor right one column in same line */
5192 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5193 g_coord.Y + 1);
5194 goto got3;
5195
5196 case 'E':
5197 termcap_mode_end();
5198 goto got3;
5199
5200 case 'F':
5201 standout();
5202 goto got3;
5203
5204 case 'f':
5205 standend();
5206 goto got3;
5207
5208 case 'H':
5209 gotoxy(1, 1);
5210 goto got3;
5211
5212 case 'j':
5213 clear_to_end_of_display();
5214 goto got3;
5215
5216 case 'J':
5217 clear_screen();
5218 goto got3;
5219
5220 case 'K':
5221 clear_to_end_of_line();
5222 goto got3;
5223
5224 case 'L':
5225 insert_lines(1);
5226 goto got3;
5227
5228 case 'M':
5229 delete_lines(1);
5230 goto got3;
5231
5232 case 'S':
5233 termcap_mode_start();
5234 goto got3;
5235
5236 case 'V':
5237 cursor_visible(TRUE);
5238 goto got3;
5239
5240 case 'v':
5241 cursor_visible(FALSE);
5242 goto got3;
5243
5244 got3:
5245 s += 3;
5246 len -= 2;
5247 }
5248
5249#ifdef MCH_WRITE_DUMP
5250 if (fdDump)
5251 {
5252 fputs("ESC | ", fdDump);
5253 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5254 fputc('\n', fdDump);
5255 }
5256#endif
5257 }
5258 else
5259 {
5260 /* Write a single character */
5261 DWORD nWritten;
5262
5263 nWritten = write_chars(s, 1);
5264#ifdef MCH_WRITE_DUMP
5265 if (fdDump)
5266 {
5267 fputc('>', fdDump);
5268 fwrite(s, sizeof(char_u), nWritten, fdDump);
5269 fputs("<\n", fdDump);
5270 }
5271#endif
5272
5273 len -= (nWritten - 1);
5274 s += nWritten;
5275 }
5276 }
5277
5278#ifdef MCH_WRITE_DUMP
5279 if (fdDump)
5280 fflush(fdDump);
5281#endif
5282}
5283
5284#endif /* FEAT_GUI_W32 */
5285
5286
5287/*
5288 * Delay for half a second.
5289 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005290/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291 void
5292mch_delay(
5293 long msec,
5294 int ignoreinput)
5295{
5296#ifdef FEAT_GUI_W32
5297 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005298#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005299 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005300# ifdef FEAT_MZSCHEME
5301 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5302 {
5303 int towait = p_mzq;
5304
5305 /* if msec is large enough, wait by portions in p_mzq */
5306 while (msec > 0)
5307 {
5308 mzvim_check_threads();
5309 if (msec < towait)
5310 towait = msec;
5311 Sleep(towait);
5312 msec -= towait;
5313 }
5314 }
5315 else
5316# endif
5317 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005318 else
5319 WaitForChar(msec);
5320#endif
5321}
5322
5323
5324/*
5325 * this version of remove is not scared by a readonly (backup) file
5326 * Return 0 for success, -1 for failure.
5327 */
5328 int
5329mch_remove(char_u *name)
5330{
5331#ifdef FEAT_MBYTE
5332 WCHAR *wn = NULL;
5333 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005334#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005335
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005336 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5337
5338#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005339 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5340 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005341 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342 if (wn != NULL)
5343 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005344 n = DeleteFileW(wn) ? 0 : -1;
5345 vim_free(wn);
5346 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5347 return n;
5348 /* Retry with non-wide function (for Windows 98). */
5349 }
5350 }
5351#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005352 return DeleteFile(name) ? 0 : -1;
5353}
5354
5355
5356/*
5357 * check for an "interrupt signal": CTRL-break or CTRL-C
5358 */
5359 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005360mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005361{
5362#ifndef FEAT_GUI_W32 /* never used */
5363 if (g_fCtrlCPressed || g_fCBrkPressed)
5364 {
5365 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5366 got_int = TRUE;
5367 }
5368#endif
5369}
5370
5371
Bram Moolenaar071d4272004-06-13 20:20:40 +00005372#ifdef FEAT_MBYTE
5373/*
5374 * Same code as below, but with wide functions and no comments.
5375 * Return 0 for success, non-zero for failure.
5376 */
5377 int
5378mch_wrename(WCHAR *wold, WCHAR *wnew)
5379{
5380 WCHAR *p;
5381 int i;
5382 WCHAR szTempFile[_MAX_PATH + 1];
5383 WCHAR szNewPath[_MAX_PATH + 1];
5384 HANDLE hf;
5385
5386 if (!mch_windows95())
5387 {
5388 p = wold;
5389 for (i = 0; wold[i] != NUL; ++i)
5390 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5391 && wold[i + 1] != 0)
5392 p = wold + i + 1;
5393 if ((int)(wold + i - p) < 8 || p[6] != '~')
5394 return (MoveFileW(wold, wnew) == 0);
5395 }
5396
5397 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5398 return -1;
5399 *p = NUL;
5400
5401 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5402 return -2;
5403
5404 if (!DeleteFileW(szTempFile))
5405 return -3;
5406
5407 if (!MoveFileW(wold, szTempFile))
5408 return -4;
5409
5410 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5411 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5412 return -5;
5413 if (!CloseHandle(hf))
5414 return -6;
5415
5416 if (!MoveFileW(szTempFile, wnew))
5417 {
5418 (void)MoveFileW(szTempFile, wold);
5419 return -7;
5420 }
5421
5422 DeleteFileW(szTempFile);
5423
5424 if (!DeleteFileW(wold))
5425 return -8;
5426
5427 return 0;
5428}
5429#endif
5430
5431
5432/*
5433 * mch_rename() works around a bug in rename (aka MoveFile) in
5434 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5435 * file whose short file name is "FOO.BAR" (its long file name will
5436 * be correct: "foo.bar~"). Because a file can be accessed by
5437 * either its SFN or its LFN, "foo.bar" has effectively been
5438 * renamed to "foo.bar", which is not at all what was wanted. This
5439 * seems to happen only when renaming files with three-character
5440 * extensions by appending a suffix that does not include ".".
5441 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5442 *
5443 * There is another problem, which isn't really a bug but isn't right either:
5444 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5445 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5446 * service pack 6. Doesn't seem to happen on Windows 98.
5447 *
5448 * Like rename(), returns 0 upon success, non-zero upon failure.
5449 * Should probably set errno appropriately when errors occur.
5450 */
5451 int
5452mch_rename(
5453 const char *pszOldFile,
5454 const char *pszNewFile)
5455{
5456 char szTempFile[_MAX_PATH+1];
5457 char szNewPath[_MAX_PATH+1];
5458 char *pszFilePart;
5459 HANDLE hf;
5460#ifdef FEAT_MBYTE
5461 WCHAR *wold = NULL;
5462 WCHAR *wnew = NULL;
5463 int retval = -1;
5464
5465 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5466 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005467 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5468 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005469 if (wold != NULL && wnew != NULL)
5470 retval = mch_wrename(wold, wnew);
5471 vim_free(wold);
5472 vim_free(wnew);
5473 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5474 return retval;
5475 /* Retry with non-wide function (for Windows 98). */
5476 }
5477#endif
5478
5479 /*
5480 * No need to play tricks if not running Windows 95, unless the file name
5481 * contains a "~" as the seventh character.
5482 */
5483 if (!mch_windows95())
5484 {
5485 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5486 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5487 return rename(pszOldFile, pszNewFile);
5488 }
5489
5490 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5491 * a directory, no error is returned and pszFilePart will be NULL. */
5492 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5493 || pszFilePart == NULL)
5494 return -1;
5495 *pszFilePart = NUL;
5496
5497 /* Get (and create) a unique temporary file name in directory of new file */
5498 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5499 return -2;
5500
5501 /* blow the temp file away */
5502 if (!DeleteFile(szTempFile))
5503 return -3;
5504
5505 /* rename old file to the temp file */
5506 if (!MoveFile(pszOldFile, szTempFile))
5507 return -4;
5508
5509 /* now create an empty file called pszOldFile; this prevents the operating
5510 * system using pszOldFile as an alias (SFN) if we're renaming within the
5511 * same directory. For example, we're editing a file called
5512 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5513 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5514 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005515 * cause all sorts of problems later in buf_write(). So, we create an
5516 * empty file called filena~1.txt and the system will have to find some
5517 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005518 */
5519 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5520 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5521 return -5;
5522 if (!CloseHandle(hf))
5523 return -6;
5524
5525 /* rename the temp file to the new file */
5526 if (!MoveFile(szTempFile, pszNewFile))
5527 {
5528 /* Renaming failed. Rename the file back to its old name, so that it
5529 * looks like nothing happened. */
5530 (void)MoveFile(szTempFile, pszOldFile);
5531
5532 return -7;
5533 }
5534
5535 /* Seems to be left around on Novell filesystems */
5536 DeleteFile(szTempFile);
5537
5538 /* finally, remove the empty old file */
5539 if (!DeleteFile(pszOldFile))
5540 return -8;
5541
5542 return 0; /* success */
5543}
5544
5545/*
5546 * Get the default shell for the current hardware platform
5547 */
5548 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005549default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005550{
5551 char* psz = NULL;
5552
5553 PlatformId();
5554
5555 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5556 psz = "cmd.exe";
5557 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5558 psz = "command.com";
5559
5560 return psz;
5561}
5562
5563/*
5564 * mch_access() extends access() to do more detailed check on network drives.
5565 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5566 */
5567 int
5568mch_access(char *n, int p)
5569{
5570 HANDLE hFile;
5571 DWORD am;
5572 int retval = -1; /* default: fail */
5573#ifdef FEAT_MBYTE
5574 WCHAR *wn = NULL;
5575
5576 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005577 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005578#endif
5579
5580 if (mch_isdir(n))
5581 {
5582 char TempName[_MAX_PATH + 16] = "";
5583#ifdef FEAT_MBYTE
5584 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5585#endif
5586
5587 if (p & R_OK)
5588 {
5589 /* Read check is performed by seeing if we can do a find file on
5590 * the directory for any file. */
5591#ifdef FEAT_MBYTE
5592 if (wn != NULL)
5593 {
5594 int i;
5595 WIN32_FIND_DATAW d;
5596
5597 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5598 TempNameW[i] = wn[i];
5599 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5600 TempNameW[i++] = '\\';
5601 TempNameW[i++] = '*';
5602 TempNameW[i++] = 0;
5603
5604 hFile = FindFirstFileW(TempNameW, &d);
5605 if (hFile == INVALID_HANDLE_VALUE)
5606 {
5607 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5608 goto getout;
5609
5610 /* Retry with non-wide function (for Windows 98). */
5611 vim_free(wn);
5612 wn = NULL;
5613 }
5614 else
5615 (void)FindClose(hFile);
5616 }
5617 if (wn == NULL)
5618#endif
5619 {
5620 char *pch;
5621 WIN32_FIND_DATA d;
5622
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005623 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 pch = TempName + STRLEN(TempName) - 1;
5625 if (*pch != '\\' && *pch != '/')
5626 *++pch = '\\';
5627 *++pch = '*';
5628 *++pch = NUL;
5629
5630 hFile = FindFirstFile(TempName, &d);
5631 if (hFile == INVALID_HANDLE_VALUE)
5632 goto getout;
5633 (void)FindClose(hFile);
5634 }
5635 }
5636
5637 if (p & W_OK)
5638 {
5639 /* Trying to create a temporary file in the directory should catch
5640 * directories on read-only network shares. However, in
5641 * directories whose ACL allows writes but denies deletes will end
5642 * up keeping the temporary file :-(. */
5643#ifdef FEAT_MBYTE
5644 if (wn != NULL)
5645 {
5646 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5647 {
5648 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5649 goto getout;
5650
5651 /* Retry with non-wide function (for Windows 98). */
5652 vim_free(wn);
5653 wn = NULL;
5654 }
5655 else
5656 DeleteFileW(TempNameW);
5657 }
5658 if (wn == NULL)
5659#endif
5660 {
5661 if (!GetTempFileName(n, "VIM", 0, TempName))
5662 goto getout;
5663 mch_remove((char_u *)TempName);
5664 }
5665 }
5666 }
5667 else
5668 {
5669 /* Trying to open the file for the required access does ACL, read-only
5670 * network share, and file attribute checks. */
5671 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5672 | ((p & R_OK) ? GENERIC_READ : 0);
5673#ifdef FEAT_MBYTE
5674 if (wn != NULL)
5675 {
5676 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5677 if (hFile == INVALID_HANDLE_VALUE
5678 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5679 {
5680 /* Retry with non-wide function (for Windows 98). */
5681 vim_free(wn);
5682 wn = NULL;
5683 }
5684 }
5685 if (wn == NULL)
5686#endif
5687 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5688 if (hFile == INVALID_HANDLE_VALUE)
5689 goto getout;
5690 CloseHandle(hFile);
5691 }
5692
5693 retval = 0; /* success */
5694getout:
5695#ifdef FEAT_MBYTE
5696 vim_free(wn);
5697#endif
5698 return retval;
5699}
5700
5701#if defined(FEAT_MBYTE) || defined(PROTO)
5702/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005703 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 */
5705 int
5706mch_open(char *name, int flags, int mode)
5707{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005708 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5709# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005710 WCHAR *wn;
5711 int f;
5712
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005713 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005714 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005715 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005716 if (wn != NULL)
5717 {
5718 f = _wopen(wn, flags, mode);
5719 vim_free(wn);
5720 if (f >= 0)
5721 return f;
5722 /* Retry with non-wide function (for Windows 98). Can't use
5723 * GetLastError() here and it's unclear what errno gets set to if
5724 * the _wopen() fails for missing wide functions. */
5725 }
5726 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005727# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005728
5729 return open(name, flags, mode);
5730}
5731
5732/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005733 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005734 */
5735 FILE *
5736mch_fopen(char *name, char *mode)
5737{
5738 WCHAR *wn, *wm;
5739 FILE *f = NULL;
5740
5741 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5742# ifdef __BORLANDC__
5743 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5744 && g_PlatformId == VER_PLATFORM_WIN32_NT
5745# endif
5746 )
5747 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005748# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005749 /* Work around an annoying assertion in the Microsoft debug CRT
5750 * when mode's text/binary setting doesn't match _get_fmode(). */
5751 char newMode = mode[strlen(mode) - 1];
5752 int oldMode = 0;
5753
5754 _get_fmode(&oldMode);
5755 if (newMode == 't')
5756 _set_fmode(_O_TEXT);
5757 else if (newMode == 'b')
5758 _set_fmode(_O_BINARY);
5759# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005760 wn = enc_to_utf16(name, NULL);
5761 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005762 if (wn != NULL && wm != NULL)
5763 f = _wfopen(wn, wm);
5764 vim_free(wn);
5765 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005766
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005767# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005768 _set_fmode(oldMode);
5769# endif
5770
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771 if (f != NULL)
5772 return f;
5773 /* Retry with non-wide function (for Windows 98). Can't use
5774 * GetLastError() here and it's unclear what errno gets set to if
5775 * the _wfopen() fails for missing wide functions. */
5776 }
5777
5778 return fopen(name, mode);
5779}
5780#endif
5781
5782#ifdef FEAT_MBYTE
5783/*
5784 * SUB STREAM (aka info stream) handling:
5785 *
5786 * NTFS can have sub streams for each file. Normal contents of file is
5787 * stored in the main stream, and extra contents (author information and
5788 * title and so on) can be stored in sub stream. After Windows 2000, user
5789 * can access and store those informations in sub streams via explorer's
5790 * property menuitem in right click menu. Those informations in sub streams
5791 * were lost when copying only the main stream. So we have to copy sub
5792 * streams.
5793 *
5794 * Incomplete explanation:
5795 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5796 * More useful info and an example:
5797 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5798 */
5799
5800/*
5801 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5802 * and write to stream "substream" of file "to".
5803 * Errors are ignored.
5804 */
5805 static void
5806copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5807{
5808 HANDLE hTo;
5809 WCHAR *to_name;
5810
5811 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5812 wcscpy(to_name, to);
5813 wcscat(to_name, substream);
5814
5815 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5816 FILE_ATTRIBUTE_NORMAL, NULL);
5817 if (hTo != INVALID_HANDLE_VALUE)
5818 {
5819 long done;
5820 DWORD todo;
5821 DWORD readcnt, written;
5822 char buf[4096];
5823
5824 /* Copy block of bytes at a time. Abort when something goes wrong. */
5825 for (done = 0; done < len; done += written)
5826 {
5827 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005828 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5829 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005830 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5831 FALSE, FALSE, context)
5832 || readcnt != todo
5833 || !WriteFile(hTo, buf, todo, &written, NULL)
5834 || written != todo)
5835 break;
5836 }
5837 CloseHandle(hTo);
5838 }
5839
5840 free(to_name);
5841}
5842
5843/*
5844 * Copy info streams from file "from" to file "to".
5845 */
5846 static void
5847copy_infostreams(char_u *from, char_u *to)
5848{
5849 WCHAR *fromw;
5850 WCHAR *tow;
5851 HANDLE sh;
5852 WIN32_STREAM_ID sid;
5853 int headersize;
5854 WCHAR streamname[_MAX_PATH];
5855 DWORD readcount;
5856 void *context = NULL;
5857 DWORD lo, hi;
5858 int len;
5859
5860 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005861 fromw = enc_to_utf16(from, NULL);
5862 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005863 if (fromw != NULL && tow != NULL)
5864 {
5865 /* Open the file for reading. */
5866 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
5867 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5868 if (sh != INVALID_HANDLE_VALUE)
5869 {
5870 /* Use BackupRead() to find the info streams. Repeat until we
5871 * have done them all.*/
5872 for (;;)
5873 {
5874 /* Get the header to find the length of the stream name. If
5875 * the "readcount" is zero we have done all info streams. */
5876 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005877 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
5879 &readcount, FALSE, FALSE, &context)
5880 || readcount == 0)
5881 break;
5882
5883 /* We only deal with streams that have a name. The normal
5884 * file data appears to be without a name, even though docs
5885 * suggest it is called "::$DATA". */
5886 if (sid.dwStreamNameSize > 0)
5887 {
5888 /* Read the stream name. */
5889 if (!BackupRead(sh, (LPBYTE)streamname,
5890 sid.dwStreamNameSize,
5891 &readcount, FALSE, FALSE, &context))
5892 break;
5893
5894 /* Copy an info stream with a name ":anything:$DATA".
5895 * Skip "::$DATA", it has no stream name (examples suggest
5896 * it might be used for the normal file contents).
5897 * Note that BackupRead() counts bytes, but the name is in
5898 * wide characters. */
5899 len = readcount / sizeof(WCHAR);
5900 streamname[len] = 0;
5901 if (len > 7 && wcsicmp(streamname + len - 6,
5902 L":$DATA") == 0)
5903 {
5904 streamname[len - 6] = 0;
5905 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00005906 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907 }
5908 }
5909
5910 /* Advance to the next stream. We might try seeking too far,
5911 * but BackupSeek() doesn't skip over stream borders, thus
5912 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005913 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005914 &lo, &hi, &context);
5915 }
5916
5917 /* Clear the context. */
5918 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
5919
5920 CloseHandle(sh);
5921 }
5922 }
5923 vim_free(fromw);
5924 vim_free(tow);
5925}
5926#endif
5927
5928/*
5929 * Copy file attributes from file "from" to file "to".
5930 * For Windows NT and later we copy info streams.
5931 * Always returns zero, errors are ignored.
5932 */
5933 int
5934mch_copy_file_attribute(char_u *from, char_u *to)
5935{
5936#ifdef FEAT_MBYTE
5937 /* File streams only work on Windows NT and later. */
5938 PlatformId();
5939 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5940 copy_infostreams(from, to);
5941#endif
5942 return 0;
5943}
5944
5945#if defined(MYRESETSTKOFLW) || defined(PROTO)
5946/*
5947 * Recreate a destroyed stack guard page in win32.
5948 * Written by Benjamin Peterson.
5949 */
5950
5951/* These magic numbers are from the MS header files */
5952#define MIN_STACK_WIN9X 17
5953#define MIN_STACK_WINNT 2
5954
5955/*
5956 * This function does the same thing as _resetstkoflw(), which is only
5957 * available in DevStudio .net and later.
5958 * Returns 0 for failure, 1 for success.
5959 */
5960 int
5961myresetstkoflw(void)
5962{
5963 BYTE *pStackPtr;
5964 BYTE *pGuardPage;
5965 BYTE *pStackBase;
5966 BYTE *pLowestPossiblePage;
5967 MEMORY_BASIC_INFORMATION mbi;
5968 SYSTEM_INFO si;
5969 DWORD nPageSize;
5970 DWORD dummy;
5971
5972 /* This code will not work on win32s. */
5973 PlatformId();
5974 if (g_PlatformId == VER_PLATFORM_WIN32s)
5975 return 0;
5976
5977 /* We need to know the system page size. */
5978 GetSystemInfo(&si);
5979 nPageSize = si.dwPageSize;
5980
5981 /* ...and the current stack pointer */
5982 pStackPtr = (BYTE*)_alloca(1);
5983
5984 /* ...and the base of the stack. */
5985 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
5986 return 0;
5987 pStackBase = (BYTE*)mbi.AllocationBase;
5988
5989 /* ...and the page thats min_stack_req pages away from stack base; this is
5990 * the lowest page we could use. */
5991 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
5992 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
5993
5994 /* On Win95, we want the next page down from the end of the stack. */
5995 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
5996 {
5997 /* Find the page that's only 1 page down from the page that the stack
5998 * ptr is in. */
5999 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6000 / (DWORD)nPageSize) - 1));
6001 if (pGuardPage < pLowestPossiblePage)
6002 return 0;
6003
6004 /* Apply the noaccess attribute to the page -- there's no guard
6005 * attribute in win95-type OSes. */
6006 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6007 return 0;
6008 }
6009 else
6010 {
6011 /* On NT, however, we want the first committed page in the stack Start
6012 * at the stack base and move forward through memory until we find a
6013 * committed block. */
6014 BYTE *pBlock = pStackBase;
6015
Bram Moolenaara466c992005-07-09 21:03:22 +00006016 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006017 {
6018 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6019 return 0;
6020
6021 pBlock += mbi.RegionSize;
6022
6023 if (mbi.State & MEM_COMMIT)
6024 break;
6025 }
6026
6027 /* mbi now describes the first committed block in the stack. */
6028 if (mbi.Protect & PAGE_GUARD)
6029 return 1;
6030
6031 /* decide where the guard page should start */
6032 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6033 pGuardPage = pLowestPossiblePage;
6034 else
6035 pGuardPage = (BYTE*)mbi.BaseAddress;
6036
6037 /* allocate the guard page */
6038 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6039 return 0;
6040
6041 /* apply the guard attribute to the page */
6042 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6043 &dummy))
6044 return 0;
6045 }
6046
6047 return 1;
6048}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006049#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006050
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006051
6052#if defined(FEAT_MBYTE) || defined(PROTO)
6053/*
6054 * The command line arguments in UCS2
6055 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006056static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006057static LPWSTR *ArglistW = NULL;
6058static int global_argc = 0;
6059static char **global_argv;
6060
6061static int used_file_argc = 0; /* last argument in global_argv[] used
6062 for the argument list. */
6063static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6064 command line arguments added to
6065 the argument list */
6066static int used_file_count = 0; /* nr of entries in used_file_indexes */
6067static int used_file_literal = FALSE; /* take file names literally */
6068static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006069static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006070static int used_alist_count = 0;
6071
6072
6073/*
6074 * Get the command line arguments. Unicode version.
6075 * Returns argc. Zero when something fails.
6076 */
6077 int
6078get_cmd_argsW(char ***argvp)
6079{
6080 char **argv = NULL;
6081 int argc = 0;
6082 int i;
6083
6084 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6085 if (ArglistW != NULL)
6086 {
6087 argv = malloc((nArgsW + 1) * sizeof(char *));
6088 if (argv != NULL)
6089 {
6090 argc = nArgsW;
6091 argv[argc] = NULL;
6092 for (i = 0; i < argc; ++i)
6093 {
6094 int len;
6095
6096 /* Convert each Unicode argument to the current codepage. */
6097 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006098 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006099 (LPSTR *)&argv[i], &len, 0, 0);
6100 if (argv[i] == NULL)
6101 {
6102 /* Out of memory, clear everything. */
6103 while (i > 0)
6104 free(argv[--i]);
6105 free(argv);
6106 argc = 0;
6107 }
6108 }
6109 }
6110 }
6111
6112 global_argc = argc;
6113 global_argv = argv;
6114 if (argc > 0)
6115 used_file_indexes = malloc(argc * sizeof(int));
6116
6117 if (argvp != NULL)
6118 *argvp = argv;
6119 return argc;
6120}
6121
6122 void
6123free_cmd_argsW(void)
6124{
6125 if (ArglistW != NULL)
6126 {
6127 GlobalFree(ArglistW);
6128 ArglistW = NULL;
6129 }
6130}
6131
6132/*
6133 * Remember "name" is an argument that was added to the argument list.
6134 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6135 * is called.
6136 */
6137 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006138used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006139{
6140 int i;
6141
6142 if (used_file_indexes == NULL)
6143 return;
6144 for (i = used_file_argc + 1; i < global_argc; ++i)
6145 if (STRCMP(global_argv[i], name) == 0)
6146 {
6147 used_file_argc = i;
6148 used_file_indexes[used_file_count++] = i;
6149 break;
6150 }
6151 used_file_literal = literal;
6152 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006153 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006154}
6155
6156/*
6157 * Remember the length of the argument list as it was. If it changes then we
6158 * leave it alone when 'encoding' is set.
6159 */
6160 void
6161set_alist_count(void)
6162{
6163 used_alist_count = GARGCOUNT;
6164}
6165
6166/*
6167 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6168 * has been changed while starting up. Use the UCS-2 command line arguments
6169 * and convert them to 'encoding'.
6170 */
6171 void
6172fix_arg_enc(void)
6173{
6174 int i;
6175 int idx;
6176 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006177 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006178
6179 /* Safety checks:
6180 * - if argument count differs between the wide and non-wide argument
6181 * list, something must be wrong.
6182 * - the file name arguments must have been located.
6183 * - the length of the argument list wasn't changed by the user.
6184 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006185 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006186 || ArglistW == NULL
6187 || used_file_indexes == NULL
6188 || used_file_count == 0
6189 || used_alist_count != GARGCOUNT)
6190 return;
6191
Bram Moolenaar86b68352004-12-27 21:59:20 +00006192 /* Remember the buffer numbers for the arguments. */
6193 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6194 if (fnum_list == NULL)
6195 return; /* out of memory */
6196 for (i = 0; i < GARGCOUNT; ++i)
6197 fnum_list[i] = GARGLIST[i].ae_fnum;
6198
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006199 /* Clear the argument list. Make room for the new arguments. */
6200 alist_clear(&global_alist);
6201 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006202 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006203
6204 for (i = 0; i < used_file_count; ++i)
6205 {
6206 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006207 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006208 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006209 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006210#ifdef FEAT_DIFF
6211 /* When using diff mode may need to concatenate file name to
6212 * directory name. Just like it's done in main(). */
6213 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6214 && !mch_isdir(alist_name(&GARGLIST[0])))
6215 {
6216 char_u *r;
6217
6218 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6219 if (r != NULL)
6220 {
6221 vim_free(str);
6222 str = r;
6223 }
6224 }
6225#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006226 /* Re-use the old buffer by renaming it. When not using literal
6227 * names it's done by alist_expand() below. */
6228 if (used_file_literal)
6229 buf_set_name(fnum_list[i], str);
6230
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006231 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006232 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006233 }
6234
6235 if (!used_file_literal)
6236 {
6237 /* Now expand wildcards in the arguments. */
6238 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6239 * filename characters but are excluded from 'isfname' to make
6240 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6241 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006242 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006243 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6244 }
6245
6246 /* If wildcard expansion failed, we are editing the first file of the
6247 * arglist and there is no file name: Edit the first argument now. */
6248 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6249 {
6250 do_cmdline_cmd((char_u *)":rewind");
6251 if (GARGCOUNT == 1 && used_file_full_path)
6252 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6253 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006254
6255 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006256}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257#endif