blob: e9dbfc5ff1e50dfddcf0f1de0b2da7ac15f41d8e [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
53#ifdef __MINGW32__
54# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
55# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
56# endif
57# ifndef RIGHTMOST_BUTTON_PRESSED
58# define RIGHTMOST_BUTTON_PRESSED 0x0002
59# endif
60# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
61# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
62# endif
63# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
64# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
65# endif
66# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
67# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
68# endif
69
70/*
71 * EventFlags
72 */
73# ifndef MOUSE_MOVED
74# define MOUSE_MOVED 0x0001
75# endif
76# ifndef DOUBLE_CLICK
77# define DOUBLE_CLICK 0x0002
78# endif
79#endif
80
81/* Record all output and all keyboard & mouse input */
82/* #define MCH_WRITE_DUMP */
83
84#ifdef MCH_WRITE_DUMP
85FILE* fdDump = NULL;
86#endif
87
88/*
89 * When generating prototypes for Win32 on Unix, these lines make the syntax
90 * errors disappear. They do not need to be correct.
91 */
92#ifdef PROTO
93#define WINAPI
94#define WINBASEAPI
95typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000096typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000097typedef int ACCESS_MASK;
98typedef int BOOL;
99typedef int COLORREF;
100typedef int CONSOLE_CURSOR_INFO;
101typedef int COORD;
102typedef int DWORD;
103typedef int HANDLE;
104typedef int HDC;
105typedef int HFONT;
106typedef int HICON;
107typedef int HINSTANCE;
108typedef int HWND;
109typedef int INPUT_RECORD;
110typedef int KEY_EVENT_RECORD;
111typedef int LOGFONT;
112typedef int LPBOOL;
113typedef int LPCTSTR;
114typedef int LPDWORD;
115typedef int LPSTR;
116typedef int LPTSTR;
117typedef int LPVOID;
118typedef int MOUSE_EVENT_RECORD;
119typedef int PACL;
120typedef int PDWORD;
121typedef int PHANDLE;
122typedef int PRINTDLG;
123typedef int PSECURITY_DESCRIPTOR;
124typedef int PSID;
125typedef int SECURITY_INFORMATION;
126typedef int SHORT;
127typedef int SMALL_RECT;
128typedef int TEXTMETRIC;
129typedef int TOKEN_INFORMATION_CLASS;
130typedef int TRUSTEE;
131typedef int WORD;
132typedef int WCHAR;
133typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100134typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000135#endif
136
137#ifndef FEAT_GUI_W32
138/* Undocumented API in kernel32.dll needed to work around dead key bug in
139 * console-mode applications in NT 4.0. If you switch keyboard layouts
140 * in a console app to a layout that includes dead keys and then hit a
141 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
142 * and Michael Dietrich for helping me figure out this workaround.
143 */
144
145/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
146#ifndef WINBASEAPI
147# define WINBASEAPI __stdcall
148#endif
149#if defined(__BORLANDC__)
150typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
151#else
152typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
153#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000154static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000155#endif
156
157#if defined(__BORLANDC__)
158/* Strangely Borland uses a non-standard name. */
159# define wcsicmp(a, b) wcscmpi((a), (b))
160#endif
161
Bram Moolenaar82881492012-11-20 16:53:39 +0100162#ifndef PROTO
163
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200164/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200165#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100166LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200167BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
168BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
169BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
170#endif
171
Bram Moolenaar82881492012-11-20 16:53:39 +0100172#endif /* PROTO */
173
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174#ifndef FEAT_GUI_W32
175/* Win32 Console handles for input and output */
176static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
177static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
178
179/* Win32 Screen buffer,coordinate,console I/O information */
180static SMALL_RECT g_srScrollRegion;
181static COORD g_coord; /* 0-based, but external coords are 1-based */
182
183/* The attribute of the screen when the editor was started */
184static WORD g_attrDefault = 7; /* lightgray text on black background */
185static WORD g_attrCurrent;
186
187static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
188static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
189static int g_fForceExit = FALSE; /* set when forcefully exiting */
190
191static void termcap_mode_start(void);
192static void termcap_mode_end(void);
193static void clear_chars(COORD coord, DWORD n);
194static void clear_screen(void);
195static void clear_to_end_of_display(void);
196static void clear_to_end_of_line(void);
197static void scroll(unsigned cLines);
198static void set_scroll_region(unsigned left, unsigned top,
199 unsigned right, unsigned bottom);
200static void insert_lines(unsigned cLines);
201static void delete_lines(unsigned cLines);
202static void gotoxy(unsigned x, unsigned y);
203static void normvideo(void);
204static void textattr(WORD wAttr);
205static void textcolor(WORD wAttr);
206static void textbackground(WORD wAttr);
207static void standout(void);
208static void standend(void);
209static void visual_bell(void);
210static void cursor_visible(BOOL fVisible);
211static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
212static char_u tgetch(int *pmodifiers, char_u *pch2);
213static void create_conin(void);
214static int s_cursor_visible = TRUE;
215static int did_create_conin = FALSE;
216#else
217static int s_dont_use_vimrun = TRUE;
218static int need_vimrun_warning = FALSE;
219static char *vimrun_path = "vimrun ";
220#endif
221
222#ifndef FEAT_GUI_W32
223static int suppress_winsize = 1; /* don't fiddle with console */
224#endif
225
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200226static char_u *exe_path = NULL;
227
Bram Moolenaar071d4272004-06-13 20:20:40 +0000228 static void
229get_exe_name(void)
230{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100231 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
232 * as the maximum length that works (plus a NUL byte). */
233#define MAX_ENV_PATH_LEN 8192
234 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200235 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236
237 if (exe_name == NULL)
238 {
239 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100240 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000241 if (*temp != NUL)
242 exe_name = FullName_save((char_u *)temp, FALSE);
243 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000244
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200245 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000246 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200247 exe_path = vim_strnsave(exe_name,
248 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200249 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000250 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200251 /* Append our starting directory to $PATH, so that when doing
252 * "!xxd" it's found in our starting directory. Needed because
253 * SearchPath() also looks there. */
254 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100255 if (p == NULL
256 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200257 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100258 if (p == NULL || *p == NUL)
259 temp[0] = NUL;
260 else
261 {
262 STRCPY(temp, p);
263 STRCAT(temp, ";");
264 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200265 STRCAT(temp, exe_path);
266 vim_setenv((char_u *)"PATH", temp);
267 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000268 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000269 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000270}
271
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200272/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100273 * Unescape characters in "p" that appear in "escaped".
274 */
275 static void
276unescape_shellxquote(char_u *p, char_u *escaped)
277{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100278 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100279 int n;
280
281 while (*p != NUL)
282 {
283 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
284 mch_memmove(p, p + 1, l--);
285#ifdef FEAT_MBYTE
286 n = (*mb_ptr2len)(p);
287#else
288 n = 1;
289#endif
290 p += n;
291 l -= n;
292 }
293}
294
295/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200296 * Load library "name".
297 */
298 HINSTANCE
299vimLoadLib(char *name)
300{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200301 HINSTANCE dll = NULL;
302 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200303
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200304 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
305 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200306 if (exe_path == NULL)
307 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200308 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200309 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200310#ifdef FEAT_MBYTE
311 WCHAR old_dirw[MAXPATHL];
312
313 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
314 {
315 /* Change directory to where the executable is, both to make
316 * sure we find a .dll there and to avoid looking for a .dll
317 * in the current directory. */
318 SetCurrentDirectory(exe_path);
319 dll = LoadLibrary(name);
320 SetCurrentDirectoryW(old_dirw);
321 return dll;
322 }
323 /* Retry with non-wide function (for Windows 98). */
324 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
325#endif
326 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
327 {
328 /* Change directory to where the executable is, both to make
329 * sure we find a .dll there and to avoid looking for a .dll
330 * in the current directory. */
331 SetCurrentDirectory(exe_path);
332 dll = LoadLibrary(name);
333 SetCurrentDirectory(old_dir);
334 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200335 }
336 return dll;
337}
338
Bram Moolenaar071d4272004-06-13 20:20:40 +0000339#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
340# ifndef GETTEXT_DLL
341# define GETTEXT_DLL "libintl.dll"
342# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200343/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000344static char *null_libintl_gettext(const char *);
345static char *null_libintl_textdomain(const char *);
346static char *null_libintl_bindtextdomain(const char *, const char *);
347static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000348
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200349static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000350char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
351char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
352char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000353 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000354char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
355 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000356
357 int
358dyn_libintl_init(char *libname)
359{
360 int i;
361 static struct
362 {
363 char *name;
364 FARPROC *ptr;
365 } libintl_entry[] =
366 {
367 {"gettext", (FARPROC*)&dyn_libintl_gettext},
368 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
369 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
370 {NULL, NULL}
371 };
372
373 /* No need to initialize twice. */
374 if (hLibintlDLL)
375 return 1;
376 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200377 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000378 if (!hLibintlDLL)
379 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200380 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000381 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200382 verbose_enter();
383 EMSG2(_(e_loadlib), GETTEXT_DLL);
384 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000385 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200386 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000387 }
388 for (i = 0; libintl_entry[i].name != NULL
389 && libintl_entry[i].ptr != NULL; ++i)
390 {
391 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
392 libintl_entry[i].name)) == NULL)
393 {
394 dyn_libintl_end();
395 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000396 {
397 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000399 verbose_leave();
400 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401 return 0;
402 }
403 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000404
405 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000406 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000407 "bind_textdomain_codeset");
408 if (dyn_libintl_bind_textdomain_codeset == NULL)
409 dyn_libintl_bind_textdomain_codeset =
410 null_libintl_bind_textdomain_codeset;
411
Bram Moolenaar071d4272004-06-13 20:20:40 +0000412 return 1;
413}
414
415 void
416dyn_libintl_end()
417{
418 if (hLibintlDLL)
419 FreeLibrary(hLibintlDLL);
420 hLibintlDLL = NULL;
421 dyn_libintl_gettext = null_libintl_gettext;
422 dyn_libintl_textdomain = null_libintl_textdomain;
423 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000424 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425}
426
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000427/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000429null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430{
431 return (char*)msgid;
432}
433
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000434/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000435 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000436null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437{
438 return NULL;
439}
440
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000441/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000443null_libintl_bind_textdomain_codeset(const char *domainname,
444 const char *codeset)
445{
446 return NULL;
447}
448
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000449/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000450 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000451null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452{
453 return NULL;
454}
455
456#endif /* DYNAMIC_GETTEXT */
457
458/* This symbol is not defined in older versions of the SDK or Visual C++ */
459
460#ifndef VER_PLATFORM_WIN32_WINDOWS
461# define VER_PLATFORM_WIN32_WINDOWS 1
462#endif
463
464DWORD g_PlatformId;
465
466#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100467# ifndef PROTO
468# include <aclapi.h>
469# endif
470
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471/*
472 * These are needed to dynamically load the ADVAPI DLL, which is not
473 * implemented under Windows 95 (and causes VIM to crash)
474 */
475typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
476 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
477typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
478 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
479 PSECURITY_DESCRIPTOR *);
480
481static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
482static PSNSECINFO pSetNamedSecurityInfo;
483static PGNSECINFO pGetNamedSecurityInfo;
484#endif
485
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200486typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
487
488static BOOL allowPiping = FALSE;
489static PSETHANDLEINFORMATION pSetHandleInformation;
490
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491/*
492 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
493 * VER_PLATFORM_WIN32_WINDOWS (Win95).
494 */
495 void
496PlatformId(void)
497{
498 static int done = FALSE;
499
500 if (!done)
501 {
502 OSVERSIONINFO ovi;
503
504 ovi.dwOSVersionInfoSize = sizeof(ovi);
505 GetVersionEx(&ovi);
506
507 g_PlatformId = ovi.dwPlatformId;
508
509#ifdef HAVE_ACL
510 /*
511 * Load the ADVAPI runtime if we are on anything
512 * other than Windows 95
513 */
514 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
515 {
516 /*
517 * do this load. Problems: Doesn't unload at end of run (this is
518 * theoretically okay, since Windows should unload it when VIM
519 * terminates). Should we be using the 'mch_libcall' routines?
520 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
521 * time we verify security...
522 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200523 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524 if (advapi_lib != NULL)
525 {
526 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
527 "SetNamedSecurityInfoA");
528 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
529 "GetNamedSecurityInfoA");
530 if (pSetNamedSecurityInfo == NULL
531 || pGetNamedSecurityInfo == NULL)
532 {
533 /* If we can't get the function addresses, set advapi_lib
534 * to NULL so that we don't use them. */
535 FreeLibrary(advapi_lib);
536 advapi_lib = NULL;
537 }
538 }
539 }
540#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200541 /*
542 * If we are on windows NT, try to load the pipe functions, only
543 * available from Win2K.
544 */
545 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
546 {
547 HANDLE kernel32 = GetModuleHandle("kernel32");
548 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
549 kernel32, "SetHandleInformation");
550
551 allowPiping = pSetHandleInformation != NULL;
552 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000553 done = TRUE;
554 }
555}
556
557/*
558 * Return TRUE when running on Windows 95 (or 98 or ME).
559 * Only to be used after mch_init().
560 */
561 int
562mch_windows95(void)
563{
564 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
565}
566
567#ifdef FEAT_GUI_W32
568/*
569 * Used to work around the "can't do synchronous spawn"
570 * problem on Win32s, without resorting to Universal Thunk.
571 */
572static int old_num_windows;
573static int num_windows;
574
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000575/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000576 static BOOL CALLBACK
577win32ssynch_cb(HWND hwnd, LPARAM lparam)
578{
579 num_windows++;
580 return TRUE;
581}
582#endif
583
584#ifndef FEAT_GUI_W32
585
586#define SHIFT (SHIFT_PRESSED)
587#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
588#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
589#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
590
591
592/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
593 * We map function keys to their ANSI terminal equivalents, as produced
594 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
595 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
596 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
597 * combinations of function/arrow/etc keys.
598 */
599
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000600static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000601{
602 WORD wVirtKey;
603 BOOL fAnsiKey;
604 int chAlone;
605 int chShift;
606 int chCtrl;
607 int chAlt;
608} VirtKeyMap[] =
609{
610
611/* Key ANSI alone shift ctrl alt */
612 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
613
614 { VK_F1, TRUE, ';', 'T', '^', 'h', },
615 { VK_F2, TRUE, '<', 'U', '_', 'i', },
616 { VK_F3, TRUE, '=', 'V', '`', 'j', },
617 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
618 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
619 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
620 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
621 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
622 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
623 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
624 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
625 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
626
627 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
628 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
629 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
630 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
631 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
632 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
633 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
634 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
635 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
636 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
637
638 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
639
640#if 0
641 /* Most people don't have F13-F20, but what the hell... */
642 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
643 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
644 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
645 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
646 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
647 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
648 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
649 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
650#endif
651 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
652 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
653 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
654 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
655
656 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
657 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
658 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
659 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
660 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
661 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
662 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
663 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
664 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
665 /* Sorry, out of number space! <negri>*/
666 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
667
668};
669
670
671#ifdef _MSC_VER
672// The ToAscii bug destroys several registers. Need to turn off optimization
673// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000674# pragma warning(push)
675# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000676# pragma optimize("", off)
677#endif
678
679#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
680# define AChar AsciiChar
681#else
682# define AChar uChar.AsciiChar
683#endif
684
685/* The return code indicates key code size. */
686 static int
687#ifdef __BORLANDC__
688 __stdcall
689#endif
690win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000691 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692{
693 UINT uMods = pker->dwControlKeyState;
694 static int s_iIsDead = 0;
695 static WORD awAnsiCode[2];
696 static BYTE abKeystate[256];
697
698
699 if (s_iIsDead == 2)
700 {
701 pker->AChar = (CHAR) awAnsiCode[1];
702 s_iIsDead = 0;
703 return 1;
704 }
705
706 if (pker->AChar != 0)
707 return 1;
708
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200709 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000710
711 // Should only be non-NULL on NT 4.0
712 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
713 {
714 CHAR szKLID[KL_NAMELENGTH];
715
716 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
717 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
718 }
719
720 /* Clear any pending dead keys */
721 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
722
723 if (uMods & SHIFT_PRESSED)
724 abKeystate[VK_SHIFT] = 0x80;
725 if (uMods & CAPSLOCK_ON)
726 abKeystate[VK_CAPITAL] = 1;
727
728 if ((uMods & ALT_GR) == ALT_GR)
729 {
730 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
731 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
732 }
733
734 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
735 abKeystate, awAnsiCode, 0);
736
737 if (s_iIsDead > 0)
738 pker->AChar = (CHAR) awAnsiCode[0];
739
740 return s_iIsDead;
741}
742
743#ifdef _MSC_VER
744/* MUST switch optimization on again here, otherwise a call to
745 * decode_key_event() may crash (e.g. when hitting caps-lock) */
746# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000747# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000748
749# if (_MSC_VER < 1100)
750/* MUST turn off global optimisation for this next function, or
751 * pressing ctrl-minus in insert mode crashes Vim when built with
752 * VC4.1. -- negri. */
753# pragma optimize("g", off)
754# endif
755#endif
756
757static BOOL g_fJustGotFocus = FALSE;
758
759/*
760 * Decode a KEY_EVENT into one or two keystrokes
761 */
762 static BOOL
763decode_key_event(
764 KEY_EVENT_RECORD *pker,
765 char_u *pch,
766 char_u *pch2,
767 int *pmodifiers,
768 BOOL fDoPost)
769{
770 int i;
771 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
772
773 *pch = *pch2 = NUL;
774 g_fJustGotFocus = FALSE;
775
776 /* ignore key up events */
777 if (!pker->bKeyDown)
778 return FALSE;
779
780 /* ignore some keystrokes */
781 switch (pker->wVirtualKeyCode)
782 {
783 /* modifiers */
784 case VK_SHIFT:
785 case VK_CONTROL:
786 case VK_MENU: /* Alt key */
787 return FALSE;
788
789 default:
790 break;
791 }
792
793 /* special cases */
794 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
795 {
796 /* Ctrl-6 is Ctrl-^ */
797 if (pker->wVirtualKeyCode == '6')
798 {
799 *pch = Ctrl_HAT;
800 return TRUE;
801 }
802 /* Ctrl-2 is Ctrl-@ */
803 else if (pker->wVirtualKeyCode == '2')
804 {
805 *pch = NUL;
806 return TRUE;
807 }
808 /* Ctrl-- is Ctrl-_ */
809 else if (pker->wVirtualKeyCode == 0xBD)
810 {
811 *pch = Ctrl__;
812 return TRUE;
813 }
814 }
815
816 /* Shift-TAB */
817 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
818 {
819 *pch = K_NUL;
820 *pch2 = '\017';
821 return TRUE;
822 }
823
824 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
825 {
826 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
827 {
828 if (nModifs == 0)
829 *pch = VirtKeyMap[i].chAlone;
830 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
831 *pch = VirtKeyMap[i].chShift;
832 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
833 *pch = VirtKeyMap[i].chCtrl;
834 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
835 *pch = VirtKeyMap[i].chAlt;
836
837 if (*pch != 0)
838 {
839 if (VirtKeyMap[i].fAnsiKey)
840 {
841 *pch2 = *pch;
842 *pch = K_NUL;
843 }
844
845 return TRUE;
846 }
847 }
848 }
849
850 i = win32_kbd_patch_key(pker);
851
852 if (i < 0)
853 *pch = NUL;
854 else
855 {
856 *pch = (i > 0) ? pker->AChar : NUL;
857
858 if (pmodifiers != NULL)
859 {
860 /* Pass on the ALT key as a modifier, but only when not combined
861 * with CTRL (which is ALTGR). */
862 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
863 *pmodifiers |= MOD_MASK_ALT;
864
865 /* Pass on SHIFT only for special keys, because we don't know when
866 * it's already included with the character. */
867 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
868 *pmodifiers |= MOD_MASK_SHIFT;
869
870 /* Pass on CTRL only for non-special keys, because we don't know
871 * when it's already included with the character. And not when
872 * combined with ALT (which is ALTGR). */
873 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
874 && *pch >= 0x20 && *pch < 0x80)
875 *pmodifiers |= MOD_MASK_CTRL;
876 }
877 }
878
879 return (*pch != NUL);
880}
881
882#ifdef _MSC_VER
883# pragma optimize("", on)
884#endif
885
886#endif /* FEAT_GUI_W32 */
887
888
889#ifdef FEAT_MOUSE
890
891/*
892 * For the GUI the mouse handling is in gui_w32.c.
893 */
894# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000895/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000897mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898{
899}
900# else
901static int g_fMouseAvail = FALSE; /* mouse present */
902static int g_fMouseActive = FALSE; /* mouse enabled */
903static int g_nMouseClick = -1; /* mouse status */
904static int g_xMouse; /* mouse x coordinate */
905static int g_yMouse; /* mouse y coordinate */
906
907/*
908 * Enable or disable mouse input
909 */
910 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000911mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000912{
913 DWORD cmodein;
914
915 if (!g_fMouseAvail)
916 return;
917
918 g_fMouseActive = on;
919 GetConsoleMode(g_hConIn, &cmodein);
920
921 if (g_fMouseActive)
922 cmodein |= ENABLE_MOUSE_INPUT;
923 else
924 cmodein &= ~ENABLE_MOUSE_INPUT;
925
926 SetConsoleMode(g_hConIn, cmodein);
927}
928
929
930/*
931 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
932 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
933 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
934 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
935 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
936 * and we return the mouse position in g_xMouse and g_yMouse.
937 *
938 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
939 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
940 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
941 *
942 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
943 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
944 *
945 * Windows will send us MOUSE_MOVED notifications whenever the mouse
946 * moves, even if it stays within the same character cell. We ignore
947 * all MOUSE_MOVED messages if the position hasn't really changed, and
948 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
949 * we're only interested in MOUSE_DRAG).
950 *
951 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
952 * 2-button mouses by pressing the left & right buttons simultaneously.
953 * In practice, it's almost impossible to click both at the same time,
954 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
955 * in such cases, if the user is clicking quickly.
956 */
957 static BOOL
958decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000959 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960{
961 static int s_nOldButton = -1;
962 static int s_nOldMouseClick = -1;
963 static int s_xOldMouse = -1;
964 static int s_yOldMouse = -1;
965 static linenr_T s_old_topline = 0;
966#ifdef FEAT_DIFF
967 static int s_old_topfill = 0;
968#endif
969 static int s_cClicks = 1;
970 static BOOL s_fReleased = TRUE;
971 static DWORD s_dwLastClickTime = 0;
972 static BOOL s_fNextIsMiddle = FALSE;
973
974 static DWORD cButtons = 0; /* number of buttons supported */
975
976 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
977 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
978 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
979 const DWORD LEFT_RIGHT = LEFT | RIGHT;
980
981 int nButton;
982
983 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
984 cButtons = 2;
985
986 if (!g_fMouseAvail || !g_fMouseActive)
987 {
988 g_nMouseClick = -1;
989 return FALSE;
990 }
991
992 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
993 if (g_fJustGotFocus)
994 {
995 g_fJustGotFocus = FALSE;
996 return FALSE;
997 }
998
999 /* unprocessed mouse click? */
1000 if (g_nMouseClick != -1)
1001 return TRUE;
1002
1003 nButton = -1;
1004 g_xMouse = pmer->dwMousePosition.X;
1005 g_yMouse = pmer->dwMousePosition.Y;
1006
1007 if (pmer->dwEventFlags == MOUSE_MOVED)
1008 {
1009 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1010 * events even when the mouse moves only within a char cell.) */
1011 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1012 return FALSE;
1013 }
1014
1015 /* If no buttons are pressed... */
1016 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1017 {
1018 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1019 if (s_fReleased)
1020 return FALSE;
1021
1022 nButton = MOUSE_RELEASE;
1023 s_fReleased = TRUE;
1024 }
1025 else /* one or more buttons pressed */
1026 {
1027 /* on a 2-button mouse, hold down left and right buttons
1028 * simultaneously to get MIDDLE. */
1029
1030 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1031 {
1032 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1033
1034 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001035 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001036 if (dwLR == LEFT || dwLR == RIGHT)
1037 {
1038 for (;;)
1039 {
1040 /* wait a short time for next input event */
1041 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1042 != WAIT_OBJECT_0)
1043 break;
1044 else
1045 {
1046 DWORD cRecords = 0;
1047 INPUT_RECORD ir;
1048 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1049
1050 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1051
1052 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1053 || !(pmer2->dwButtonState & LEFT_RIGHT))
1054 break;
1055 else
1056 {
1057 if (pmer2->dwEventFlags != MOUSE_MOVED)
1058 {
1059 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1060
1061 return decode_mouse_event(pmer2);
1062 }
1063 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1064 s_yOldMouse == pmer2->dwMousePosition.Y)
1065 {
1066 /* throw away spurious mouse move */
1067 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1068
1069 /* are there any more mouse events in queue? */
1070 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1071
1072 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1073 break;
1074 }
1075 else
1076 break;
1077 }
1078 }
1079 }
1080 }
1081 }
1082
1083 if (s_fNextIsMiddle)
1084 {
1085 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1086 ? MOUSE_DRAG : MOUSE_MIDDLE;
1087 s_fNextIsMiddle = FALSE;
1088 }
1089 else if (cButtons == 2 &&
1090 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1091 {
1092 nButton = MOUSE_MIDDLE;
1093
1094 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1095 {
1096 s_fNextIsMiddle = TRUE;
1097 nButton = MOUSE_RELEASE;
1098 }
1099 }
1100 else if ((pmer->dwButtonState & LEFT) == LEFT)
1101 nButton = MOUSE_LEFT;
1102 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1103 nButton = MOUSE_MIDDLE;
1104 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1105 nButton = MOUSE_RIGHT;
1106
1107 if (! s_fReleased && ! s_fNextIsMiddle
1108 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1109 return FALSE;
1110
1111 s_fReleased = s_fNextIsMiddle;
1112 }
1113
1114 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1115 {
1116 /* button pressed or released, without mouse moving */
1117 if (nButton != -1 && nButton != MOUSE_RELEASE)
1118 {
1119 DWORD dwCurrentTime = GetTickCount();
1120
1121 if (s_xOldMouse != g_xMouse
1122 || s_yOldMouse != g_yMouse
1123 || s_nOldButton != nButton
1124 || s_old_topline != curwin->w_topline
1125#ifdef FEAT_DIFF
1126 || s_old_topfill != curwin->w_topfill
1127#endif
1128 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1129 {
1130 s_cClicks = 1;
1131 }
1132 else if (++s_cClicks > 4)
1133 {
1134 s_cClicks = 1;
1135 }
1136
1137 s_dwLastClickTime = dwCurrentTime;
1138 }
1139 }
1140 else if (pmer->dwEventFlags == MOUSE_MOVED)
1141 {
1142 if (nButton != -1 && nButton != MOUSE_RELEASE)
1143 nButton = MOUSE_DRAG;
1144
1145 s_cClicks = 1;
1146 }
1147
1148 if (nButton == -1)
1149 return FALSE;
1150
1151 if (nButton != MOUSE_RELEASE)
1152 s_nOldButton = nButton;
1153
1154 g_nMouseClick = nButton;
1155
1156 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1157 g_nMouseClick |= MOUSE_SHIFT;
1158 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1159 g_nMouseClick |= MOUSE_CTRL;
1160 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1161 g_nMouseClick |= MOUSE_ALT;
1162
1163 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1164 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1165
1166 /* only pass on interesting (i.e., different) mouse events */
1167 if (s_xOldMouse == g_xMouse
1168 && s_yOldMouse == g_yMouse
1169 && s_nOldMouseClick == g_nMouseClick)
1170 {
1171 g_nMouseClick = -1;
1172 return FALSE;
1173 }
1174
1175 s_xOldMouse = g_xMouse;
1176 s_yOldMouse = g_yMouse;
1177 s_old_topline = curwin->w_topline;
1178#ifdef FEAT_DIFF
1179 s_old_topfill = curwin->w_topfill;
1180#endif
1181 s_nOldMouseClick = g_nMouseClick;
1182
1183 return TRUE;
1184}
1185
1186# endif /* FEAT_GUI_W32 */
1187#endif /* FEAT_MOUSE */
1188
1189
1190#ifdef MCH_CURSOR_SHAPE
1191/*
1192 * Set the shape of the cursor.
1193 * 'thickness' can be from 1 (thin) to 99 (block)
1194 */
1195 static void
1196mch_set_cursor_shape(int thickness)
1197{
1198 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1199 ConsoleCursorInfo.dwSize = thickness;
1200 ConsoleCursorInfo.bVisible = s_cursor_visible;
1201
1202 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1203 if (s_cursor_visible)
1204 SetConsoleCursorPosition(g_hConOut, g_coord);
1205}
1206
1207 void
1208mch_update_cursor(void)
1209{
1210 int idx;
1211 int thickness;
1212
1213 /*
1214 * How the cursor is drawn depends on the current mode.
1215 */
1216 idx = get_shape_idx(FALSE);
1217
1218 if (shape_table[idx].shape == SHAPE_BLOCK)
1219 thickness = 99; /* 100 doesn't work on W95 */
1220 else
1221 thickness = shape_table[idx].percentage;
1222 mch_set_cursor_shape(thickness);
1223}
1224#endif
1225
1226#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1227/*
1228 * Handle FOCUS_EVENT.
1229 */
1230 static void
1231handle_focus_event(INPUT_RECORD ir)
1232{
1233 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1234 ui_focus_change((int)g_fJustGotFocus);
1235}
1236
1237/*
1238 * Wait until console input from keyboard or mouse is available,
1239 * or the time is up.
1240 * Return TRUE if something is available FALSE if not.
1241 */
1242 static int
1243WaitForChar(long msec)
1244{
1245 DWORD dwNow = 0, dwEndTime = 0;
1246 INPUT_RECORD ir;
1247 DWORD cRecords;
1248 char_u ch, ch2;
1249
1250 if (msec > 0)
1251 /* Wait until the specified time has elapsed. */
1252 dwEndTime = GetTickCount() + msec;
1253 else if (msec < 0)
1254 /* Wait forever. */
1255 dwEndTime = INFINITE;
1256
1257 /* We need to loop until the end of the time period, because
1258 * we might get multiple unusable mouse events in that time.
1259 */
1260 for (;;)
1261 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001262#ifdef FEAT_MZSCHEME
1263 mzvim_check_threads();
1264#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001265#ifdef FEAT_CLIENTSERVER
1266 serverProcessPendingMessages();
1267#endif
1268 if (0
1269#ifdef FEAT_MOUSE
1270 || g_nMouseClick != -1
1271#endif
1272#ifdef FEAT_CLIENTSERVER
1273 || input_available()
1274#endif
1275 )
1276 return TRUE;
1277
1278 if (msec > 0)
1279 {
1280 /* If the specified wait time has passed, return. */
1281 dwNow = GetTickCount();
1282 if (dwNow >= dwEndTime)
1283 break;
1284 }
1285 if (msec != 0)
1286 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001287 DWORD dwWaitTime = dwEndTime - dwNow;
1288
1289#ifdef FEAT_MZSCHEME
1290 if (mzthreads_allowed() && p_mzq > 0
1291 && (msec < 0 || (long)dwWaitTime > p_mzq))
1292 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1293#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001294#ifdef FEAT_CLIENTSERVER
1295 /* Wait for either an event on the console input or a message in
1296 * the client-server window. */
1297 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001298 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001299#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001300 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001301#endif
1302 continue;
1303 }
1304
1305 cRecords = 0;
1306 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1307
1308#ifdef FEAT_MBYTE_IME
1309 if (State & CMDLINE && msg_row == Rows - 1)
1310 {
1311 CONSOLE_SCREEN_BUFFER_INFO csbi;
1312
1313 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1314 {
1315 if (csbi.dwCursorPosition.Y != msg_row)
1316 {
1317 /* The screen is now messed up, must redraw the
1318 * command line and later all the windows. */
1319 redraw_all_later(CLEAR);
1320 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1321 redrawcmd();
1322 }
1323 }
1324 }
1325#endif
1326
1327 if (cRecords > 0)
1328 {
1329 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1330 {
1331#ifdef FEAT_MBYTE_IME
1332 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1333 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1334 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1335 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1336 {
1337 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1338 continue;
1339 }
1340#endif
1341 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1342 NULL, FALSE))
1343 return TRUE;
1344 }
1345
1346 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1347
1348 if (ir.EventType == FOCUS_EVENT)
1349 handle_focus_event(ir);
1350 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1351 shell_resized();
1352#ifdef FEAT_MOUSE
1353 else if (ir.EventType == MOUSE_EVENT
1354 && decode_mouse_event(&ir.Event.MouseEvent))
1355 return TRUE;
1356#endif
1357 }
1358 else if (msec == 0)
1359 break;
1360 }
1361
1362#ifdef FEAT_CLIENTSERVER
1363 /* Something might have been received while we were waiting. */
1364 if (input_available())
1365 return TRUE;
1366#endif
1367 return FALSE;
1368}
1369
1370#ifndef FEAT_GUI_MSWIN
1371/*
1372 * return non-zero if a character is available
1373 */
1374 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001375mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001376{
1377 return WaitForChar(0L);
1378}
1379#endif
1380
1381/*
1382 * Create the console input. Used when reading stdin doesn't work.
1383 */
1384 static void
1385create_conin(void)
1386{
1387 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1388 FILE_SHARE_READ|FILE_SHARE_WRITE,
1389 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001390 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001391 did_create_conin = TRUE;
1392}
1393
1394/*
1395 * Get a keystroke or a mouse event
1396 */
1397 static char_u
1398tgetch(int *pmodifiers, char_u *pch2)
1399{
1400 char_u ch;
1401
1402 for (;;)
1403 {
1404 INPUT_RECORD ir;
1405 DWORD cRecords = 0;
1406
1407#ifdef FEAT_CLIENTSERVER
1408 (void)WaitForChar(-1L);
1409 if (input_available())
1410 return 0;
1411# ifdef FEAT_MOUSE
1412 if (g_nMouseClick != -1)
1413 return 0;
1414# endif
1415#endif
1416 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1417 {
1418 if (did_create_conin)
1419 read_error_exit();
1420 create_conin();
1421 continue;
1422 }
1423
1424 if (ir.EventType == KEY_EVENT)
1425 {
1426 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1427 pmodifiers, TRUE))
1428 return ch;
1429 }
1430 else if (ir.EventType == FOCUS_EVENT)
1431 handle_focus_event(ir);
1432 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1433 shell_resized();
1434#ifdef FEAT_MOUSE
1435 else if (ir.EventType == MOUSE_EVENT)
1436 {
1437 if (decode_mouse_event(&ir.Event.MouseEvent))
1438 return 0;
1439 }
1440#endif
1441 }
1442}
1443#endif /* !FEAT_GUI_W32 */
1444
1445
1446/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001447 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001448 * Get one or more characters from the keyboard or the mouse.
1449 * If time == 0, do not wait for characters.
1450 * If time == n, wait a short time for characters.
1451 * If time == -1, wait forever for characters.
1452 * Returns the number of characters read into buf.
1453 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001454/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 int
1456mch_inchar(
1457 char_u *buf,
1458 int maxlen,
1459 long time,
1460 int tb_change_cnt)
1461{
1462#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1463
1464 int len;
1465 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001466#define TYPEAHEADLEN 20
1467 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1468 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001469#ifdef FEAT_MBYTE
1470 static char_u *rest = NULL; /* unconverted rest of previous read */
1471 static int restlen = 0;
1472 int unconverted;
1473#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001474
1475 /* First use any typeahead that was kept because "buf" was too small. */
1476 if (typeaheadlen > 0)
1477 goto theend;
1478
1479#ifdef FEAT_SNIFF
1480 if (want_sniff_request)
1481 {
1482 if (sniff_request_waiting)
1483 {
1484 /* return K_SNIFF */
1485 typeahead[typeaheadlen++] = CSI;
1486 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1487 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1488 sniff_request_waiting = 0;
1489 want_sniff_request = 0;
1490 goto theend;
1491 }
1492 else if (time < 0 || time > 250)
1493 {
1494 /* don't wait too long, a request might be pending */
1495 time = 250;
1496 }
1497 }
1498#endif
1499
1500 if (time >= 0)
1501 {
1502 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 }
1505 else /* time == -1, wait forever */
1506 {
1507 mch_set_winsize_now(); /* Allow winsize changes from now on */
1508
Bram Moolenaar3918c952005-03-15 22:34:55 +00001509 /*
1510 * If there is no character available within 2 seconds (default)
1511 * write the autoscript file to disk. Or cause the CursorHold event
1512 * to be triggered.
1513 */
1514 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001515 {
1516#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001517 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001519 buf[0] = K_SPECIAL;
1520 buf[1] = KS_EXTRA;
1521 buf[2] = (int)KE_CURSORHOLD;
1522 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 }
1524#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001525 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526 }
1527 }
1528
1529 /*
1530 * Try to read as many characters as there are, until the buffer is full.
1531 */
1532
1533 /* we will get at least one key. Get more if they are available. */
1534 g_fCBrkPressed = FALSE;
1535
1536#ifdef MCH_WRITE_DUMP
1537 if (fdDump)
1538 fputc('[', fdDump);
1539#endif
1540
1541 /* Keep looping until there is something in the typeahead buffer and more
1542 * to get and still room in the buffer (up to two bytes for a char and
1543 * three bytes for a modifier). */
1544 while ((typeaheadlen == 0 || WaitForChar(0L))
1545 && typeaheadlen + 5 <= TYPEAHEADLEN)
1546 {
1547 if (typebuf_changed(tb_change_cnt))
1548 {
1549 /* "buf" may be invalid now if a client put something in the
1550 * typeahead buffer and "buf" is in the typeahead buffer. */
1551 typeaheadlen = 0;
1552 break;
1553 }
1554#ifdef FEAT_MOUSE
1555 if (g_nMouseClick != -1)
1556 {
1557# ifdef MCH_WRITE_DUMP
1558 if (fdDump)
1559 fprintf(fdDump, "{%02x @ %d, %d}",
1560 g_nMouseClick, g_xMouse, g_yMouse);
1561# endif
1562 typeahead[typeaheadlen++] = ESC + 128;
1563 typeahead[typeaheadlen++] = 'M';
1564 typeahead[typeaheadlen++] = g_nMouseClick;
1565 typeahead[typeaheadlen++] = g_xMouse + '!';
1566 typeahead[typeaheadlen++] = g_yMouse + '!';
1567 g_nMouseClick = -1;
1568 }
1569 else
1570#endif
1571 {
1572 char_u ch2 = NUL;
1573 int modifiers = 0;
1574
1575 c = tgetch(&modifiers, &ch2);
1576
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001577#ifdef FEAT_MBYTE
1578 /* stolen from fill_input_buf() in ui.c */
1579 if (rest != NULL)
1580 {
1581 /* Use remainder of previous call, starts with an invalid
1582 * character that may become valid when reading more. */
1583 if (restlen > TYPEAHEADLEN - typeaheadlen)
1584 unconverted = TYPEAHEADLEN - typeaheadlen;
1585 else
1586 unconverted = restlen;
1587 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1588 if (unconverted == restlen)
1589 {
1590 vim_free(rest);
1591 rest = NULL;
1592 }
1593 else
1594 {
1595 restlen -= unconverted;
1596 mch_memmove(rest, rest + unconverted, restlen);
1597 }
1598 typeaheadlen += unconverted;
1599 }
1600 else
1601 unconverted = 0;
1602#endif
1603
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 if (typebuf_changed(tb_change_cnt))
1605 {
1606 /* "buf" may be invalid now if a client put something in the
1607 * typeahead buffer and "buf" is in the typeahead buffer. */
1608 typeaheadlen = 0;
1609 break;
1610 }
1611
1612 if (c == Ctrl_C && ctrl_c_interrupts)
1613 {
1614#if defined(FEAT_CLIENTSERVER)
1615 trash_input_buf();
1616#endif
1617 got_int = TRUE;
1618 }
1619
1620#ifdef FEAT_MOUSE
1621 if (g_nMouseClick == -1)
1622#endif
1623 {
1624 int n = 1;
1625
1626 /* A key may have one or two bytes. */
1627 typeahead[typeaheadlen] = c;
1628 if (ch2 != NUL)
1629 {
1630 typeahead[typeaheadlen + 1] = ch2;
1631 ++n;
1632 }
1633#ifdef FEAT_MBYTE
1634 /* Only convert normal characters, not special keys. Need to
1635 * convert before applying ALT, otherwise mapping <M-x> breaks
1636 * when 'tenc' is set. */
1637 if (input_conv.vc_type != CONV_NONE
1638 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001639 {
1640 typeaheadlen -= unconverted;
1641 n = convert_input_safe(typeahead + typeaheadlen,
1642 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1643 rest == NULL ? &rest : NULL, &restlen);
1644 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001645#endif
1646
1647 /* Use the ALT key to set the 8th bit of the character
1648 * when it's one byte, the 8th bit isn't set yet and not
1649 * using a double-byte encoding (would become a lead
1650 * byte). */
1651 if ((modifiers & MOD_MASK_ALT)
1652 && n == 1
1653 && (typeahead[typeaheadlen] & 0x80) == 0
1654#ifdef FEAT_MBYTE
1655 && !enc_dbcs
1656#endif
1657 )
1658 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001659#ifdef FEAT_MBYTE
1660 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1661 typeahead + typeaheadlen);
1662#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001663 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001664#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665 modifiers &= ~MOD_MASK_ALT;
1666 }
1667
1668 if (modifiers != 0)
1669 {
1670 /* Prepend modifiers to the character. */
1671 mch_memmove(typeahead + typeaheadlen + 3,
1672 typeahead + typeaheadlen, n);
1673 typeahead[typeaheadlen++] = K_SPECIAL;
1674 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1675 typeahead[typeaheadlen++] = modifiers;
1676 }
1677
1678 typeaheadlen += n;
1679
1680#ifdef MCH_WRITE_DUMP
1681 if (fdDump)
1682 fputc(c, fdDump);
1683#endif
1684 }
1685 }
1686 }
1687
1688#ifdef MCH_WRITE_DUMP
1689 if (fdDump)
1690 {
1691 fputs("]\n", fdDump);
1692 fflush(fdDump);
1693 }
1694#endif
1695
Bram Moolenaar071d4272004-06-13 20:20:40 +00001696theend:
1697 /* Move typeahead to "buf", as much as fits. */
1698 len = 0;
1699 while (len < maxlen && typeaheadlen > 0)
1700 {
1701 buf[len++] = typeahead[0];
1702 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1703 }
1704 return len;
1705
1706#else /* FEAT_GUI_W32 */
1707 return 0;
1708#endif /* FEAT_GUI_W32 */
1709}
1710
Bram Moolenaar82881492012-11-20 16:53:39 +01001711#ifndef PROTO
1712# ifndef __MINGW32__
1713# include <shellapi.h> /* required for FindExecutable() */
1714# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001715#endif
1716
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001717/*
1718 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001719 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001720 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001721 static int
1722executable_exists(char *name)
1723{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001724 char *dum;
1725 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001727#ifdef FEAT_MBYTE
1728 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001729 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001730 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001731 WCHAR fnamew[_MAX_PATH];
1732 WCHAR *dumw;
1733 long n;
1734
1735 if (p != NULL)
1736 {
1737 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1738 vim_free(p);
1739 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1740 {
1741 if (n == 0)
1742 return FALSE;
1743 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1744 return FALSE;
1745 return TRUE;
1746 }
1747 /* Retry with non-wide function (for Windows 98). */
1748 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001750#endif
1751 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1752 return FALSE;
1753 if (mch_isdir(fname))
1754 return FALSE;
1755 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756}
1757
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001758#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001759 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001760/*
1761 * Bad parameter handler.
1762 *
1763 * Certain MS CRT functions will intentionally crash when passed invalid
1764 * parameters to highlight possible security holes. Setting this function as
1765 * the bad parameter handler will prevent the crash.
1766 *
1767 * In debug builds the parameters contain CRT information that might help track
1768 * down the source of a problem, but in non-debug builds the arguments are all
1769 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1770 * worth allowing these to make debugging of issues easier.
1771 */
1772 static void
1773bad_param_handler(const wchar_t *expression,
1774 const wchar_t *function,
1775 const wchar_t *file,
1776 unsigned int line,
1777 uintptr_t pReserved)
1778{
1779}
1780
1781# define SET_INVALID_PARAM_HANDLER \
1782 ((void)_set_invalid_parameter_handler(bad_param_handler))
1783#else
1784# define SET_INVALID_PARAM_HANDLER
1785#endif
1786
Bram Moolenaar071d4272004-06-13 20:20:40 +00001787#ifdef FEAT_GUI_W32
1788
1789/*
1790 * GUI version of mch_init().
1791 */
1792 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001793mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001794{
1795#ifndef __MINGW32__
1796 extern int _fmode;
1797#endif
1798
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001799 /* Silently handle invalid parameters to CRT functions */
1800 SET_INVALID_PARAM_HANDLER;
1801
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 /* Let critical errors result in a failure, not in a dialog box. Required
1803 * for the timestamp test to work on removed floppies. */
1804 SetErrorMode(SEM_FAILCRITICALERRORS);
1805
1806 _fmode = O_BINARY; /* we do our own CR-LF translation */
1807
1808 /* Specify window size. Is there a place to get the default from? */
1809 Rows = 25;
1810 Columns = 80;
1811
1812 /* Look for 'vimrun' */
1813 if (!gui_is_win32s())
1814 {
1815 char_u vimrun_location[_MAX_PATH + 4];
1816
1817 /* First try in same directory as gvim.exe */
1818 STRCPY(vimrun_location, exe_name);
1819 STRCPY(gettail(vimrun_location), "vimrun.exe");
1820 if (mch_getperm(vimrun_location) >= 0)
1821 {
1822 if (*skiptowhite(vimrun_location) != NUL)
1823 {
1824 /* Enclose path with white space in double quotes. */
1825 mch_memmove(vimrun_location + 1, vimrun_location,
1826 STRLEN(vimrun_location) + 1);
1827 *vimrun_location = '"';
1828 STRCPY(gettail(vimrun_location), "vimrun\" ");
1829 }
1830 else
1831 STRCPY(gettail(vimrun_location), "vimrun ");
1832
1833 vimrun_path = (char *)vim_strsave(vimrun_location);
1834 s_dont_use_vimrun = FALSE;
1835 }
1836 else if (executable_exists("vimrun.exe"))
1837 s_dont_use_vimrun = FALSE;
1838
1839 /* Don't give the warning for a missing vimrun.exe right now, but only
1840 * when vimrun was supposed to be used. Don't bother people that do
1841 * not need vimrun.exe. */
1842 if (s_dont_use_vimrun)
1843 need_vimrun_warning = TRUE;
1844 }
1845
1846 /*
1847 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1848 * Otherwise the default "findstr /n" is used.
1849 */
1850 if (!executable_exists("findstr.exe"))
1851 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1852
1853#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001854 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855#endif
1856}
1857
1858
1859#else /* FEAT_GUI_W32 */
1860
1861#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1862#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1863
1864/*
1865 * ClearConsoleBuffer()
1866 * Description:
1867 * Clears the entire contents of the console screen buffer, using the
1868 * specified attribute.
1869 * Returns:
1870 * TRUE on success
1871 */
1872 static BOOL
1873ClearConsoleBuffer(WORD wAttribute)
1874{
1875 CONSOLE_SCREEN_BUFFER_INFO csbi;
1876 COORD coord;
1877 DWORD NumCells, dummy;
1878
1879 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1880 return FALSE;
1881
1882 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1883 coord.X = 0;
1884 coord.Y = 0;
1885 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1886 coord, &dummy))
1887 {
1888 return FALSE;
1889 }
1890 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1891 coord, &dummy))
1892 {
1893 return FALSE;
1894 }
1895
1896 return TRUE;
1897}
1898
1899/*
1900 * FitConsoleWindow()
1901 * Description:
1902 * Checks if the console window will fit within given buffer dimensions.
1903 * Also, if requested, will shrink the window to fit.
1904 * Returns:
1905 * TRUE on success
1906 */
1907 static BOOL
1908FitConsoleWindow(
1909 COORD dwBufferSize,
1910 BOOL WantAdjust)
1911{
1912 CONSOLE_SCREEN_BUFFER_INFO csbi;
1913 COORD dwWindowSize;
1914 BOOL NeedAdjust = FALSE;
1915
1916 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1917 {
1918 /*
1919 * A buffer resize will fail if the current console window does
1920 * not lie completely within that buffer. To avoid this, we might
1921 * have to move and possibly shrink the window.
1922 */
1923 if (csbi.srWindow.Right >= dwBufferSize.X)
1924 {
1925 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1926 if (dwWindowSize.X > dwBufferSize.X)
1927 dwWindowSize.X = dwBufferSize.X;
1928 csbi.srWindow.Right = dwBufferSize.X - 1;
1929 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1930 NeedAdjust = TRUE;
1931 }
1932 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1933 {
1934 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1935 if (dwWindowSize.Y > dwBufferSize.Y)
1936 dwWindowSize.Y = dwBufferSize.Y;
1937 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1938 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1939 NeedAdjust = TRUE;
1940 }
1941 if (NeedAdjust && WantAdjust)
1942 {
1943 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1944 return FALSE;
1945 }
1946 return TRUE;
1947 }
1948
1949 return FALSE;
1950}
1951
1952typedef struct ConsoleBufferStruct
1953{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001954 BOOL IsValid;
1955 CONSOLE_SCREEN_BUFFER_INFO Info;
1956 PCHAR_INFO Buffer;
1957 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001958} ConsoleBuffer;
1959
1960/*
1961 * SaveConsoleBuffer()
1962 * Description:
1963 * Saves important information about the console buffer, including the
1964 * actual buffer contents. The saved information is suitable for later
1965 * restoration by RestoreConsoleBuffer().
1966 * Returns:
1967 * TRUE if all information was saved; FALSE otherwise
1968 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1969 */
1970 static BOOL
1971SaveConsoleBuffer(
1972 ConsoleBuffer *cb)
1973{
1974 DWORD NumCells;
1975 COORD BufferCoord;
1976 SMALL_RECT ReadRegion;
1977 WORD Y, Y_incr;
1978
1979 if (cb == NULL)
1980 return FALSE;
1981
1982 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1983 {
1984 cb->IsValid = FALSE;
1985 return FALSE;
1986 }
1987 cb->IsValid = TRUE;
1988
1989 /*
1990 * Allocate a buffer large enough to hold the entire console screen
1991 * buffer. If this ConsoleBuffer structure has already been initialized
1992 * with a buffer of the correct size, then just use that one.
1993 */
1994 if (!cb->IsValid || cb->Buffer == NULL ||
1995 cb->BufferSize.X != cb->Info.dwSize.X ||
1996 cb->BufferSize.Y != cb->Info.dwSize.Y)
1997 {
1998 cb->BufferSize.X = cb->Info.dwSize.X;
1999 cb->BufferSize.Y = cb->Info.dwSize.Y;
2000 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002001 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2003 if (cb->Buffer == NULL)
2004 return FALSE;
2005 }
2006
2007 /*
2008 * We will now copy the console screen buffer into our buffer.
2009 * ReadConsoleOutput() seems to be limited as far as how much you
2010 * can read at a time. Empirically, this number seems to be about
2011 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2012 * in chunks until it is all copied. The chunks will all have the
2013 * same horizontal characteristics, so initialize them now. The
2014 * height of each chunk will be (12000 / width).
2015 */
2016 BufferCoord.X = 0;
2017 ReadRegion.Left = 0;
2018 ReadRegion.Right = cb->Info.dwSize.X - 1;
2019 Y_incr = 12000 / cb->Info.dwSize.X;
2020 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2021 {
2022 /*
2023 * Read into position (0, Y) in our buffer.
2024 */
2025 BufferCoord.Y = Y;
2026 /*
2027 * Read the region whose top left corner is (0, Y) and whose bottom
2028 * right corner is (width - 1, Y + Y_incr - 1). This should define
2029 * a region of size width by Y_incr. Don't worry if this region is
2030 * too large for the remaining buffer; it will be cropped.
2031 */
2032 ReadRegion.Top = Y;
2033 ReadRegion.Bottom = Y + Y_incr - 1;
2034 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2035 cb->Buffer, /* our buffer */
2036 cb->BufferSize, /* dimensions of our buffer */
2037 BufferCoord, /* offset in our buffer */
2038 &ReadRegion)) /* region to save */
2039 {
2040 vim_free(cb->Buffer);
2041 cb->Buffer = NULL;
2042 return FALSE;
2043 }
2044 }
2045
2046 return TRUE;
2047}
2048
2049/*
2050 * RestoreConsoleBuffer()
2051 * Description:
2052 * Restores important information about the console buffer, including the
2053 * actual buffer contents, if desired. The information to restore is in
2054 * the same format used by SaveConsoleBuffer().
2055 * Returns:
2056 * TRUE on success
2057 */
2058 static BOOL
2059RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002060 ConsoleBuffer *cb,
2061 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062{
2063 COORD BufferCoord;
2064 SMALL_RECT WriteRegion;
2065
2066 if (cb == NULL || !cb->IsValid)
2067 return FALSE;
2068
2069 /*
2070 * Before restoring the buffer contents, clear the current buffer, and
2071 * restore the cursor position and window information. Doing this now
2072 * prevents old buffer contents from "flashing" onto the screen.
2073 */
2074 if (RestoreScreen)
2075 ClearConsoleBuffer(cb->Info.wAttributes);
2076
2077 FitConsoleWindow(cb->Info.dwSize, TRUE);
2078 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2079 return FALSE;
2080 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2081 return FALSE;
2082
2083 if (!RestoreScreen)
2084 {
2085 /*
2086 * No need to restore the screen buffer contents, so we're done.
2087 */
2088 return TRUE;
2089 }
2090
2091 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2092 return FALSE;
2093 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2094 return FALSE;
2095
2096 /*
2097 * Restore the screen buffer contents.
2098 */
2099 if (cb->Buffer != NULL)
2100 {
2101 BufferCoord.X = 0;
2102 BufferCoord.Y = 0;
2103 WriteRegion.Left = 0;
2104 WriteRegion.Top = 0;
2105 WriteRegion.Right = cb->Info.dwSize.X - 1;
2106 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2107 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2108 cb->Buffer, /* our buffer */
2109 cb->BufferSize, /* dimensions of our buffer */
2110 BufferCoord, /* offset in our buffer */
2111 &WriteRegion)) /* region to restore */
2112 {
2113 return FALSE;
2114 }
2115 }
2116
2117 return TRUE;
2118}
2119
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002120#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002121#ifdef FEAT_RESTORE_ORIG_SCREEN
2122static ConsoleBuffer g_cbOrig = { 0 };
2123#endif
2124static ConsoleBuffer g_cbNonTermcap = { 0 };
2125static ConsoleBuffer g_cbTermcap = { 0 };
2126
2127#ifdef FEAT_TITLE
2128#ifdef __BORLANDC__
2129typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2130#else
2131typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2132#endif
2133char g_szOrigTitle[256] = { 0 };
2134HWND g_hWnd = NULL; /* also used in os_mswin.c */
2135static HICON g_hOrigIconSmall = NULL;
2136static HICON g_hOrigIcon = NULL;
2137static HICON g_hVimIcon = NULL;
2138static BOOL g_fCanChangeIcon = FALSE;
2139
2140/* ICON* are not defined in VC++ 4.0 */
2141#ifndef ICON_SMALL
2142#define ICON_SMALL 0
2143#endif
2144#ifndef ICON_BIG
2145#define ICON_BIG 1
2146#endif
2147/*
2148 * GetConsoleIcon()
2149 * Description:
2150 * Attempts to retrieve the small icon and/or the big icon currently in
2151 * use by a given window.
2152 * Returns:
2153 * TRUE on success
2154 */
2155 static BOOL
2156GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002157 HWND hWnd,
2158 HICON *phIconSmall,
2159 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002160{
2161 if (hWnd == NULL)
2162 return FALSE;
2163
2164 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002165 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2166 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002167 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002168 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2169 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002170 return TRUE;
2171}
2172
2173/*
2174 * SetConsoleIcon()
2175 * Description:
2176 * Attempts to change the small icon and/or the big icon currently in
2177 * use by a given window.
2178 * Returns:
2179 * TRUE on success
2180 */
2181 static BOOL
2182SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002183 HWND hWnd,
2184 HICON hIconSmall,
2185 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002186{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002187 HICON hPrevIconSmall;
2188 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189
2190 if (hWnd == NULL)
2191 return FALSE;
2192
2193 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002194 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2195 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002196 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002197 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2198 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002199 return TRUE;
2200}
2201
2202/*
2203 * SaveConsoleTitleAndIcon()
2204 * Description:
2205 * Saves the current console window title in g_szOrigTitle, for later
2206 * restoration. Also, attempts to obtain a handle to the console window,
2207 * and use it to save the small and big icons currently in use by the
2208 * console window. This is not always possible on some versions of Windows;
2209 * nor is it possible when running Vim remotely using Telnet (since the
2210 * console window the user sees is owned by a remote process).
2211 */
2212 static void
2213SaveConsoleTitleAndIcon(void)
2214{
2215 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2216
2217 /* Save the original title. */
2218 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2219 return;
2220
2221 /*
2222 * Obtain a handle to the console window using GetConsoleWindow() from
2223 * KERNEL32.DLL; we need to handle in order to change the window icon.
2224 * This function only exists on NT-based Windows, starting with Windows
2225 * 2000. On older operating systems, we can't change the window icon
2226 * anyway.
2227 */
2228 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2229 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2230 "GetConsoleWindow")) != NULL)
2231 {
2232 g_hWnd = (*GetConsoleWindowProc)();
2233 }
2234 if (g_hWnd == NULL)
2235 return;
2236
2237 /* Save the original console window icon. */
2238 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2239 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2240 return;
2241
2242 /* Extract the first icon contained in the Vim executable. */
2243 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2244 if (g_hVimIcon != NULL)
2245 g_fCanChangeIcon = TRUE;
2246}
2247#endif
2248
2249static int g_fWindInitCalled = FALSE;
2250static int g_fTermcapMode = FALSE;
2251static CONSOLE_CURSOR_INFO g_cci;
2252static DWORD g_cmodein = 0;
2253static DWORD g_cmodeout = 0;
2254
2255/*
2256 * non-GUI version of mch_init().
2257 */
2258 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002259mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260{
2261#ifndef FEAT_RESTORE_ORIG_SCREEN
2262 CONSOLE_SCREEN_BUFFER_INFO csbi;
2263#endif
2264#ifndef __MINGW32__
2265 extern int _fmode;
2266#endif
2267
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002268 /* Silently handle invalid parameters to CRT functions */
2269 SET_INVALID_PARAM_HANDLER;
2270
Bram Moolenaar071d4272004-06-13 20:20:40 +00002271 /* Let critical errors result in a failure, not in a dialog box. Required
2272 * for the timestamp test to work on removed floppies. */
2273 SetErrorMode(SEM_FAILCRITICALERRORS);
2274
2275 _fmode = O_BINARY; /* we do our own CR-LF translation */
2276 out_flush();
2277
2278 /* Obtain handles for the standard Console I/O devices */
2279 if (read_cmd_fd == 0)
2280 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2281 else
2282 create_conin();
2283 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2284
2285#ifdef FEAT_RESTORE_ORIG_SCREEN
2286 /* Save the initial console buffer for later restoration */
2287 SaveConsoleBuffer(&g_cbOrig);
2288 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2289#else
2290 /* Get current text attributes */
2291 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2292 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2293#endif
2294 if (cterm_normal_fg_color == 0)
2295 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2296 if (cterm_normal_bg_color == 0)
2297 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2298
2299 /* set termcap codes to current text attributes */
2300 update_tcap(g_attrCurrent);
2301
2302 GetConsoleCursorInfo(g_hConOut, &g_cci);
2303 GetConsoleMode(g_hConIn, &g_cmodein);
2304 GetConsoleMode(g_hConOut, &g_cmodeout);
2305
2306#ifdef FEAT_TITLE
2307 SaveConsoleTitleAndIcon();
2308 /*
2309 * Set both the small and big icons of the console window to Vim's icon.
2310 * Note that Vim presently only has one size of icon (32x32), but it
2311 * automatically gets scaled down to 16x16 when setting the small icon.
2312 */
2313 if (g_fCanChangeIcon)
2314 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2315#endif
2316
2317 ui_get_shellsize();
2318
2319#ifdef MCH_WRITE_DUMP
2320 fdDump = fopen("dump", "wt");
2321
2322 if (fdDump)
2323 {
2324 time_t t;
2325
2326 time(&t);
2327 fputs(ctime(&t), fdDump);
2328 fflush(fdDump);
2329 }
2330#endif
2331
2332 g_fWindInitCalled = TRUE;
2333
2334#ifdef FEAT_MOUSE
2335 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2336#endif
2337
2338#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002339 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002340#endif
2341
2342 /* This will be NULL on anything but NT 4.0 */
2343 s_pfnGetConsoleKeyboardLayoutName =
2344 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2345 "GetConsoleKeyboardLayoutNameA");
2346}
2347
2348/*
2349 * non-GUI version of mch_exit().
2350 * Shut down and exit with status `r'
2351 * Careful: mch_exit() may be called before mch_init()!
2352 */
2353 void
2354mch_exit(int r)
2355{
2356 stoptermcap();
2357
2358 if (g_fWindInitCalled)
2359 settmode(TMODE_COOK);
2360
2361 ml_close_all(TRUE); /* remove all memfiles */
2362
2363 if (g_fWindInitCalled)
2364 {
2365#ifdef FEAT_TITLE
2366 mch_restore_title(3);
2367 /*
2368 * Restore both the small and big icons of the console window to
2369 * what they were at startup. Don't do this when the window is
2370 * closed, Vim would hang here.
2371 */
2372 if (g_fCanChangeIcon && !g_fForceExit)
2373 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2374#endif
2375
2376#ifdef MCH_WRITE_DUMP
2377 if (fdDump)
2378 {
2379 time_t t;
2380
2381 time(&t);
2382 fputs(ctime(&t), fdDump);
2383 fclose(fdDump);
2384 }
2385 fdDump = NULL;
2386#endif
2387 }
2388
2389 SetConsoleCursorInfo(g_hConOut, &g_cci);
2390 SetConsoleMode(g_hConIn, g_cmodein);
2391 SetConsoleMode(g_hConOut, g_cmodeout);
2392
2393#ifdef DYNAMIC_GETTEXT
2394 dyn_libintl_end();
2395#endif
2396
2397 exit(r);
2398}
2399#endif /* !FEAT_GUI_W32 */
2400
Bram Moolenaar071d4272004-06-13 20:20:40 +00002401/*
2402 * Do we have an interactive window?
2403 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002404/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002405 int
2406mch_check_win(
2407 int argc,
2408 char **argv)
2409{
2410 get_exe_name();
2411
2412#ifdef FEAT_GUI_W32
2413 return OK; /* GUI always has a tty */
2414#else
2415 if (isatty(1))
2416 return OK;
2417 return FAIL;
2418#endif
2419}
2420
2421
2422/*
2423 * fname_case(): Set the case of the file name, if it already exists.
2424 * When "len" is > 0, also expand short to long filenames.
2425 */
2426 void
2427fname_case(
2428 char_u *name,
2429 int len)
2430{
2431 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002432 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 char *ptrue, *ptruePrev;
2434 char *porig, *porigPrev;
2435 int flen;
2436 WIN32_FIND_DATA fb;
2437 HANDLE hFind;
2438 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002439 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002440
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002441 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002442 if (flen == 0 || flen > _MAX_PATH)
2443 return;
2444
2445 slash_adjust(name);
2446
2447 /* Build the new name in szTrueName[] one component at a time. */
2448 porig = name;
2449 ptrue = szTrueName;
2450
2451 if (isalpha(porig[0]) && porig[1] == ':')
2452 {
2453 /* copy leading drive letter */
2454 *ptrue++ = *porig++;
2455 *ptrue++ = *porig++;
2456 *ptrue = NUL; /* in case nothing follows */
2457 }
2458
2459 while (*porig != NUL)
2460 {
2461 /* copy \ characters */
2462 while (*porig == psepc)
2463 *ptrue++ = *porig++;
2464
2465 ptruePrev = ptrue;
2466 porigPrev = porig;
2467 while (*porig != NUL && *porig != psepc)
2468 {
2469#ifdef FEAT_MBYTE
2470 int l;
2471
2472 if (enc_dbcs)
2473 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002474 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002475 while (--l >= 0)
2476 *ptrue++ = *porig++;
2477 }
2478 else
2479#endif
2480 *ptrue++ = *porig++;
2481 }
2482 *ptrue = NUL;
2483
Bram Moolenaar464c9252010-10-13 20:37:41 +02002484 /* To avoid a slow failure append "\*" when searching a directory,
2485 * server or network share. */
2486 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002487 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002488 if (*porig == psepc && slen + 2 < _MAX_PATH)
2489 STRCPY(szTrueNameTemp + slen, "\\*");
2490
Bram Moolenaar071d4272004-06-13 20:20:40 +00002491 /* Skip "", "." and "..". */
2492 if (ptrue > ptruePrev
2493 && (ptruePrev[0] != '.'
2494 || (ptruePrev[1] != NUL
2495 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002496 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 != INVALID_HANDLE_VALUE)
2498 {
2499 c = *porig;
2500 *porig = NUL;
2501
2502 /* Only use the match when it's the same name (ignoring case) or
2503 * expansion is allowed and there is a match with the short name
2504 * and there is enough room. */
2505 if (_stricoll(porigPrev, fb.cFileName) == 0
2506 || (len > 0
2507 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2508 && (int)(ptruePrev - szTrueName)
2509 + (int)strlen(fb.cFileName) < len)))
2510 {
2511 STRCPY(ptruePrev, fb.cFileName);
2512
2513 /* Look for exact match and prefer it if found. Must be a
2514 * long name, otherwise there would be only one match. */
2515 while (FindNextFile(hFind, &fb))
2516 {
2517 if (*fb.cAlternateFileName != NUL
2518 && (strcoll(porigPrev, fb.cFileName) == 0
2519 || (len > 0
2520 && (_stricoll(porigPrev,
2521 fb.cAlternateFileName) == 0
2522 && (int)(ptruePrev - szTrueName)
2523 + (int)strlen(fb.cFileName) < len))))
2524 {
2525 STRCPY(ptruePrev, fb.cFileName);
2526 break;
2527 }
2528 }
2529 }
2530 FindClose(hFind);
2531 *porig = c;
2532 ptrue = ptruePrev + strlen(ptruePrev);
2533 }
2534 }
2535
2536 STRCPY(name, szTrueName);
2537}
2538
2539
2540/*
2541 * Insert user name in s[len].
2542 */
2543 int
2544mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002545 char_u *s,
2546 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002547{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002548 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549 DWORD cch = sizeof szUserName;
2550
2551 if (GetUserName(szUserName, &cch))
2552 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002553 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554 return OK;
2555 }
2556 s[0] = NUL;
2557 return FAIL;
2558}
2559
2560
2561/*
2562 * Insert host name in s[len].
2563 */
2564 void
2565mch_get_host_name(
2566 char_u *s,
2567 int len)
2568{
2569 DWORD cch = len;
2570
2571 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002572 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573}
2574
2575
2576/*
2577 * return process ID
2578 */
2579 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002580mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002581{
2582 return (long)GetCurrentProcessId();
2583}
2584
2585
2586/*
2587 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2588 * Return OK for success, FAIL for failure.
2589 */
2590 int
2591mch_dirname(
2592 char_u *buf,
2593 int len)
2594{
2595 /*
2596 * Originally this was:
2597 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2598 * But the Win32s known bug list says that getcwd() doesn't work
2599 * so use the Win32 system call instead. <Negri>
2600 */
2601#ifdef FEAT_MBYTE
2602 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2603 {
2604 WCHAR wbuf[_MAX_PATH + 1];
2605
2606 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2607 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002608 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002609
2610 if (p != NULL)
2611 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002612 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002613 vim_free(p);
2614 return OK;
2615 }
2616 }
2617 /* Retry with non-wide function (for Windows 98). */
2618 }
2619#endif
2620 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2621}
2622
2623/*
2624 * get file permissions for `name'
2625 * -1 : error
2626 * else FILE_ATTRIBUTE_* defined in winnt.h
2627 */
2628 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002629mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630{
2631#ifdef FEAT_MBYTE
2632 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2633 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002634 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635 long n;
2636
2637 if (p != NULL)
2638 {
2639 n = (long)GetFileAttributesW(p);
2640 vim_free(p);
2641 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2642 return n;
2643 /* Retry with non-wide function (for Windows 98). */
2644 }
2645 }
2646#endif
2647 return (long)GetFileAttributes((char *)name);
2648}
2649
2650
2651/*
2652 * set file permission for `name' to `perm'
2653 */
2654 int
2655mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002656 char_u *name,
2657 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002658{
2659 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2660#ifdef FEAT_MBYTE
2661 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2662 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002663 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664 long n;
2665
2666 if (p != NULL)
2667 {
2668 n = (long)SetFileAttributesW(p, perm);
2669 vim_free(p);
2670 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2671 return n ? OK : FAIL;
2672 /* Retry with non-wide function (for Windows 98). */
2673 }
2674 }
2675#endif
2676 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2677}
2678
2679/*
2680 * Set hidden flag for "name".
2681 */
2682 void
2683mch_hide(char_u *name)
2684{
2685 int perm;
2686#ifdef FEAT_MBYTE
2687 WCHAR *p = NULL;
2688
2689 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002690 p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002691#endif
2692
2693#ifdef FEAT_MBYTE
2694 if (p != NULL)
2695 {
2696 perm = GetFileAttributesW(p);
2697 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2698 {
2699 /* Retry with non-wide function (for Windows 98). */
2700 vim_free(p);
2701 p = NULL;
2702 }
2703 }
2704 if (p == NULL)
2705#endif
2706 perm = GetFileAttributes((char *)name);
2707 if (perm >= 0)
2708 {
2709 perm |= FILE_ATTRIBUTE_HIDDEN;
2710#ifdef FEAT_MBYTE
2711 if (p != NULL)
2712 {
2713 if (SetFileAttributesW(p, perm) == 0
2714 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2715 {
2716 /* Retry with non-wide function (for Windows 98). */
2717 vim_free(p);
2718 p = NULL;
2719 }
2720 }
2721 if (p == NULL)
2722#endif
2723 SetFileAttributes((char *)name, perm);
2724 }
2725#ifdef FEAT_MBYTE
2726 vim_free(p);
2727#endif
2728}
2729
2730/*
2731 * return TRUE if "name" is a directory
2732 * return FALSE if "name" is not a directory or upon error
2733 */
2734 int
2735mch_isdir(char_u *name)
2736{
2737 int f = mch_getperm(name);
2738
2739 if (f == -1)
2740 return FALSE; /* file does not exist at all */
2741
2742 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2743}
2744
2745/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002746 * Create directory "name".
2747 * Return 0 on success, -1 on error.
2748 */
2749 int
2750mch_mkdir(char_u *name)
2751{
2752#ifdef FEAT_MBYTE
2753 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2754 {
2755 WCHAR *p;
2756 int retval;
2757
2758 p = enc_to_utf16(name, NULL);
2759 if (p == NULL)
2760 return -1;
2761 retval = _wmkdir(p);
2762 vim_free(p);
2763 return retval;
2764 }
2765#endif
2766 return _mkdir(name);
2767}
2768
2769/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002770 * Return TRUE if file "fname" has more than one link.
2771 */
2772 int
2773mch_is_linked(char_u *fname)
2774{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002775 BY_HANDLE_FILE_INFORMATION info;
2776
2777 return win32_fileinfo(fname, &info) == FILEINFO_OK
2778 && info.nNumberOfLinks > 1;
2779}
2780
2781/*
2782 * Get the by-handle-file-information for "fname".
2783 * Returns FILEINFO_OK when OK.
2784 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
2785 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
2786 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
2787 */
2788 int
2789win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
2790{
Bram Moolenaar03f48552006-02-28 23:52:23 +00002791 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002792 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002793#ifdef FEAT_MBYTE
2794 WCHAR *wn = NULL;
2795
2796 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002797 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002798 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002799 if (wn == NULL)
2800 res = FILEINFO_ENC_FAIL;
2801 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00002802 if (wn != NULL)
2803 {
2804 hFile = CreateFileW(wn, /* file name */
2805 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002806 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002807 NULL, /* security descriptor */
2808 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002809 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002810 NULL); /* handle to template file */
2811 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002812 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002813 {
2814 /* Retry with non-wide function (for Windows 98). */
2815 vim_free(wn);
2816 wn = NULL;
2817 }
2818 }
2819 if (wn == NULL)
2820#endif
2821 hFile = CreateFile(fname, /* file name */
2822 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002823 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002824 NULL, /* security descriptor */
2825 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002826 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002827 NULL); /* handle to template file */
2828
2829 if (hFile != INVALID_HANDLE_VALUE)
2830 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002831 if (GetFileInformationByHandle(hFile, info) != 0)
2832 res = FILEINFO_OK;
2833 else
2834 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002835 CloseHandle(hFile);
2836 }
2837
2838#ifdef FEAT_MBYTE
2839 vim_free(wn);
2840#endif
2841 return res;
2842}
2843
2844/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845 * Return TRUE if file or directory "name" is writable (not readonly).
2846 * Strange semantics of Win32: a readonly directory is writable, but you can't
2847 * delete a file. Let's say this means it is writable.
2848 */
2849 int
2850mch_writable(char_u *name)
2851{
2852 int perm = mch_getperm(name);
2853
2854 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2855 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2856}
2857
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858/*
2859 * Return 1 if "name" can be executed, 0 if not.
2860 * Return -1 if unknown.
2861 */
2862 int
2863mch_can_exe(char_u *name)
2864{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002865 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002866 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002867 char_u *p;
2868
2869 if (len >= _MAX_PATH) /* safety check */
2870 return FALSE;
2871
2872 /* If there already is an extension try using the name directly. Also do
2873 * this with a Unix-shell like 'shell'. */
2874 if (vim_strchr(gettail(name), '.') != NULL
2875 || strstr((char *)gettail(p_sh), "sh") != NULL)
2876 if (executable_exists((char *)name))
2877 return TRUE;
2878
2879 /*
2880 * Loop over all extensions in $PATHEXT.
2881 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002882 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002883 p = mch_getenv("PATHEXT");
2884 if (p == NULL)
2885 p = (char_u *)".com;.exe;.bat;.cmd";
2886 while (*p)
2887 {
2888 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2889 {
2890 /* A single "." means no extension is added. */
2891 buf[len] = NUL;
2892 ++p;
2893 if (*p)
2894 ++p;
2895 }
2896 else
2897 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2898 if (executable_exists((char *)buf))
2899 return TRUE;
2900 }
2901 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002902}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903
2904/*
2905 * Check what "name" is:
2906 * NODE_NORMAL: file or directory (or doesn't exist)
2907 * NODE_WRITABLE: writable device, socket, fifo, etc.
2908 * NODE_OTHER: non-writable things
2909 */
2910 int
2911mch_nodetype(char_u *name)
2912{
2913 HANDLE hFile;
2914 int type;
2915
Bram Moolenaar043545e2006-10-10 16:44:07 +00002916 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
2917 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
2918 * here. */
2919 if (STRNCMP(name, "\\\\.\\", 4) == 0)
2920 return NODE_WRITABLE;
2921
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922 hFile = CreateFile(name, /* file name */
2923 GENERIC_WRITE, /* access mode */
2924 0, /* share mode */
2925 NULL, /* security descriptor */
2926 OPEN_EXISTING, /* creation disposition */
2927 0, /* file attributes */
2928 NULL); /* handle to template file */
2929
2930 if (hFile == INVALID_HANDLE_VALUE)
2931 return NODE_NORMAL;
2932
2933 type = GetFileType(hFile);
2934 CloseHandle(hFile);
2935 if (type == FILE_TYPE_CHAR)
2936 return NODE_WRITABLE;
2937 if (type == FILE_TYPE_DISK)
2938 return NODE_NORMAL;
2939 return NODE_OTHER;
2940}
2941
2942#ifdef HAVE_ACL
2943struct my_acl
2944{
2945 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2946 PSID pSidOwner;
2947 PSID pSidGroup;
2948 PACL pDacl;
2949 PACL pSacl;
2950};
2951#endif
2952
2953/*
2954 * Return a pointer to the ACL of file "fname" in allocated memory.
2955 * Return NULL if the ACL is not available for whatever reason.
2956 */
2957 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002958mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959{
2960#ifndef HAVE_ACL
2961 return (vim_acl_T)NULL;
2962#else
2963 struct my_acl *p = NULL;
2964
2965 /* This only works on Windows NT and 2000. */
2966 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2967 {
2968 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2969 if (p != NULL)
2970 {
2971 if (pGetNamedSecurityInfo(
2972 (LPTSTR)fname, // Abstract filename
2973 SE_FILE_OBJECT, // File Object
2974 // Retrieve the entire security descriptor.
2975 OWNER_SECURITY_INFORMATION |
2976 GROUP_SECURITY_INFORMATION |
2977 DACL_SECURITY_INFORMATION |
2978 SACL_SECURITY_INFORMATION,
2979 &p->pSidOwner, // Ownership information.
2980 &p->pSidGroup, // Group membership.
2981 &p->pDacl, // Discretionary information.
2982 &p->pSacl, // For auditing purposes.
2983 &p->pSecurityDescriptor
2984 ) != ERROR_SUCCESS)
2985 {
2986 mch_free_acl((vim_acl_T)p);
2987 p = NULL;
2988 }
2989 }
2990 }
2991
2992 return (vim_acl_T)p;
2993#endif
2994}
2995
2996/*
2997 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2998 * Errors are ignored.
2999 * This must only be called with "acl" equal to what mch_get_acl() returned.
3000 */
3001 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003002mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003003{
3004#ifdef HAVE_ACL
3005 struct my_acl *p = (struct my_acl *)acl;
3006
3007 if (p != NULL && advapi_lib != NULL)
3008 (void)pSetNamedSecurityInfo(
3009 (LPTSTR)fname, // Abstract filename
3010 SE_FILE_OBJECT, // File Object
3011 // Retrieve the entire security descriptor.
3012 OWNER_SECURITY_INFORMATION |
3013 GROUP_SECURITY_INFORMATION |
3014 DACL_SECURITY_INFORMATION |
3015 SACL_SECURITY_INFORMATION,
3016 p->pSidOwner, // Ownership information.
3017 p->pSidGroup, // Group membership.
3018 p->pDacl, // Discretionary information.
3019 p->pSacl // For auditing purposes.
3020 );
3021#endif
3022}
3023
3024 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003025mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003026{
3027#ifdef HAVE_ACL
3028 struct my_acl *p = (struct my_acl *)acl;
3029
3030 if (p != NULL)
3031 {
3032 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3033 vim_free(p);
3034 }
3035#endif
3036}
3037
3038#ifndef FEAT_GUI_W32
3039
3040/*
3041 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3042 */
3043 static BOOL WINAPI
3044handler_routine(
3045 DWORD dwCtrlType)
3046{
3047 switch (dwCtrlType)
3048 {
3049 case CTRL_C_EVENT:
3050 if (ctrl_c_interrupts)
3051 g_fCtrlCPressed = TRUE;
3052 return TRUE;
3053
3054 case CTRL_BREAK_EVENT:
3055 g_fCBrkPressed = TRUE;
3056 return TRUE;
3057
3058 /* fatal events: shut down gracefully */
3059 case CTRL_CLOSE_EVENT:
3060 case CTRL_LOGOFF_EVENT:
3061 case CTRL_SHUTDOWN_EVENT:
3062 windgoto((int)Rows - 1, 0);
3063 g_fForceExit = TRUE;
3064
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003065 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003066 (dwCtrlType == CTRL_CLOSE_EVENT
3067 ? _("close")
3068 : dwCtrlType == CTRL_LOGOFF_EVENT
3069 ? _("logoff")
3070 : _("shutdown")));
3071#ifdef DEBUG
3072 OutputDebugString(IObuff);
3073#endif
3074
3075 preserve_exit(); /* output IObuff, preserve files and exit */
3076
3077 return TRUE; /* not reached */
3078
3079 default:
3080 return FALSE;
3081 }
3082}
3083
3084
3085/*
3086 * set the tty in (raw) ? "raw" : "cooked" mode
3087 */
3088 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003089mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090{
3091 DWORD cmodein;
3092 DWORD cmodeout;
3093 BOOL bEnableHandler;
3094
3095 GetConsoleMode(g_hConIn, &cmodein);
3096 GetConsoleMode(g_hConOut, &cmodeout);
3097 if (tmode == TMODE_RAW)
3098 {
3099 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3100 ENABLE_ECHO_INPUT);
3101#ifdef FEAT_MOUSE
3102 if (g_fMouseActive)
3103 cmodein |= ENABLE_MOUSE_INPUT;
3104#endif
3105 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3106 bEnableHandler = TRUE;
3107 }
3108 else /* cooked */
3109 {
3110 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3111 ENABLE_ECHO_INPUT);
3112 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3113 bEnableHandler = FALSE;
3114 }
3115 SetConsoleMode(g_hConIn, cmodein);
3116 SetConsoleMode(g_hConOut, cmodeout);
3117 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3118
3119#ifdef MCH_WRITE_DUMP
3120 if (fdDump)
3121 {
3122 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3123 tmode == TMODE_RAW ? "raw" :
3124 tmode == TMODE_COOK ? "cooked" : "normal",
3125 cmodein, cmodeout);
3126 fflush(fdDump);
3127 }
3128#endif
3129}
3130
3131
3132/*
3133 * Get the size of the current window in `Rows' and `Columns'
3134 * Return OK when size could be determined, FAIL otherwise.
3135 */
3136 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003137mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003138{
3139 CONSOLE_SCREEN_BUFFER_INFO csbi;
3140
3141 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3142 {
3143 /*
3144 * For some reason, we are trying to get the screen dimensions
3145 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3146 * variables are really intended to mean the size of Vim screen
3147 * while in termcap mode.
3148 */
3149 Rows = g_cbTermcap.Info.dwSize.Y;
3150 Columns = g_cbTermcap.Info.dwSize.X;
3151 }
3152 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3153 {
3154 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3155 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3156 }
3157 else
3158 {
3159 Rows = 25;
3160 Columns = 80;
3161 }
3162 return OK;
3163}
3164
3165/*
3166 * Set a console window to `xSize' * `ySize'
3167 */
3168 static void
3169ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003170 HANDLE hConsole,
3171 int xSize,
3172 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003173{
3174 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3175 SMALL_RECT srWindowRect; /* hold the new console size */
3176 COORD coordScreen;
3177
3178#ifdef MCH_WRITE_DUMP
3179 if (fdDump)
3180 {
3181 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3182 fflush(fdDump);
3183 }
3184#endif
3185
3186 /* get the largest size we can size the console window to */
3187 coordScreen = GetLargestConsoleWindowSize(hConsole);
3188
3189 /* define the new console window size and scroll position */
3190 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3191 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3192 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3193
3194 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3195 {
3196 int sx, sy;
3197
3198 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3199 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3200 if (sy < ySize || sx < xSize)
3201 {
3202 /*
3203 * Increasing number of lines/columns, do buffer first.
3204 * Use the maximal size in x and y direction.
3205 */
3206 if (sy < ySize)
3207 coordScreen.Y = ySize;
3208 else
3209 coordScreen.Y = sy;
3210 if (sx < xSize)
3211 coordScreen.X = xSize;
3212 else
3213 coordScreen.X = sx;
3214 SetConsoleScreenBufferSize(hConsole, coordScreen);
3215 }
3216 }
3217
3218 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3219 {
3220#ifdef MCH_WRITE_DUMP
3221 if (fdDump)
3222 {
3223 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3224 GetLastError());
3225 fflush(fdDump);
3226 }
3227#endif
3228 }
3229
3230 /* define the new console buffer size */
3231 coordScreen.X = xSize;
3232 coordScreen.Y = ySize;
3233
3234 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3235 {
3236#ifdef MCH_WRITE_DUMP
3237 if (fdDump)
3238 {
3239 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3240 GetLastError());
3241 fflush(fdDump);
3242 }
3243#endif
3244 }
3245}
3246
3247
3248/*
3249 * Set the console window to `Rows' * `Columns'
3250 */
3251 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003252mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003253{
3254 COORD coordScreen;
3255
3256 /* Don't change window size while still starting up */
3257 if (suppress_winsize != 0)
3258 {
3259 suppress_winsize = 2;
3260 return;
3261 }
3262
3263 if (term_console)
3264 {
3265 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3266
3267 /* Clamp Rows and Columns to reasonable values */
3268 if (Rows > coordScreen.Y)
3269 Rows = coordScreen.Y;
3270 if (Columns > coordScreen.X)
3271 Columns = coordScreen.X;
3272
3273 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3274 }
3275}
3276
3277/*
3278 * Rows and/or Columns has changed.
3279 */
3280 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003281mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003282{
3283 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3284}
3285
3286
3287/*
3288 * Called when started up, to set the winsize that was delayed.
3289 */
3290 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003291mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292{
3293 if (suppress_winsize == 2)
3294 {
3295 suppress_winsize = 0;
3296 mch_set_shellsize();
3297 shell_resized();
3298 }
3299 suppress_winsize = 0;
3300}
3301#endif /* FEAT_GUI_W32 */
3302
3303
3304
3305#if defined(FEAT_GUI_W32) || defined(PROTO)
3306
3307/*
3308 * Specialised version of system() for Win32 GUI mode.
3309 * This version proceeds as follows:
3310 * 1. Create a console window for use by the subprocess
3311 * 2. Run the subprocess (it gets the allocated console by default)
3312 * 3. Wait for the subprocess to terminate and get its exit code
3313 * 4. Prompt the user to press a key to close the console window
3314 */
3315 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003316mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003317{
3318 STARTUPINFO si;
3319 PROCESS_INFORMATION pi;
3320 DWORD ret = 0;
3321 HWND hwnd = GetFocus();
3322
3323 si.cb = sizeof(si);
3324 si.lpReserved = NULL;
3325 si.lpDesktop = NULL;
3326 si.lpTitle = NULL;
3327 si.dwFlags = STARTF_USESHOWWINDOW;
3328 /*
3329 * It's nicer to run a filter command in a minimized window, but in
3330 * Windows 95 this makes the command MUCH slower. We can't do it under
3331 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003332 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333 */
3334 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003335 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336 else
3337 si.wShowWindow = SW_SHOWNORMAL;
3338 si.cbReserved2 = 0;
3339 si.lpReserved2 = NULL;
3340
3341 /* There is a strange error on Windows 95 when using "c:\\command.com".
3342 * When the "c:\\" is left out it works OK...? */
3343 if (mch_windows95()
3344 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3345 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3346 cmd += 3;
3347
3348 /* Now, run the command */
3349 CreateProcess(NULL, /* Executable name */
3350 cmd, /* Command to execute */
3351 NULL, /* Process security attributes */
3352 NULL, /* Thread security attributes */
3353 FALSE, /* Inherit handles */
3354 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3355 CREATE_NEW_CONSOLE,
3356 NULL, /* Environment */
3357 NULL, /* Current directory */
3358 &si, /* Startup information */
3359 &pi); /* Process information */
3360
3361
3362 /* Wait for the command to terminate before continuing */
3363 if (g_PlatformId != VER_PLATFORM_WIN32s)
3364 {
3365#ifdef FEAT_GUI
3366 int delay = 1;
3367
3368 /* Keep updating the window while waiting for the shell to finish. */
3369 for (;;)
3370 {
3371 MSG msg;
3372
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003373 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374 {
3375 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003376 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003377 delay = 1;
3378 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 }
3380 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3381 break;
3382
3383 /* We start waiting for a very short time and then increase it, so
3384 * that we respond quickly when the process is quick, and don't
3385 * consume too much overhead when it's slow. */
3386 if (delay < 50)
3387 delay += 10;
3388 }
3389#else
3390 WaitForSingleObject(pi.hProcess, INFINITE);
3391#endif
3392
3393 /* Get the command exit code */
3394 GetExitCodeProcess(pi.hProcess, &ret);
3395 }
3396 else
3397 {
3398 /*
3399 * This ugly code is the only quick way of performing
3400 * a synchronous spawn under Win32s. Yuk.
3401 */
3402 num_windows = 0;
3403 EnumWindows(win32ssynch_cb, 0);
3404 old_num_windows = num_windows;
3405 do
3406 {
3407 Sleep(1000);
3408 num_windows = 0;
3409 EnumWindows(win32ssynch_cb, 0);
3410 } while (num_windows == old_num_windows);
3411 ret = 0;
3412 }
3413
3414 /* Close the handles to the subprocess, so that it goes away */
3415 CloseHandle(pi.hThread);
3416 CloseHandle(pi.hProcess);
3417
3418 /* Try to get input focus back. Doesn't always work though. */
3419 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3420
3421 return ret;
3422}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003423
3424/*
3425 * Thread launched by the gui to send the current buffer data to the
3426 * process. This way avoid to hang up vim totally if the children
3427 * process take a long time to process the lines.
3428 */
3429 static DWORD WINAPI
3430sub_process_writer(LPVOID param)
3431{
3432 HANDLE g_hChildStd_IN_Wr = param;
3433 linenr_T lnum = curbuf->b_op_start.lnum;
3434 DWORD len = 0;
3435 DWORD l;
3436 char_u *lp = ml_get(lnum);
3437 char_u *s;
3438 int written = 0;
3439
3440 for (;;)
3441 {
3442 l = (DWORD)STRLEN(lp + written);
3443 if (l == 0)
3444 len = 0;
3445 else if (lp[written] == NL)
3446 {
3447 /* NL -> NUL translation */
3448 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3449 }
3450 else
3451 {
3452 s = vim_strchr(lp + written, NL);
3453 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3454 s == NULL ? l : (DWORD)(s - (lp + written)),
3455 &len, NULL);
3456 }
3457 if (len == (int)l)
3458 {
3459 /* Finished a line, add a NL, unless this line should not have
3460 * one. */
3461 if (lnum != curbuf->b_op_end.lnum
3462 || !curbuf->b_p_bin
3463 || (lnum != curbuf->b_no_eol_lnum
3464 && (lnum != curbuf->b_ml.ml_line_count
3465 || curbuf->b_p_eol)))
3466 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01003467 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003468 }
3469
3470 ++lnum;
3471 if (lnum > curbuf->b_op_end.lnum)
3472 break;
3473
3474 lp = ml_get(lnum);
3475 written = 0;
3476 }
3477 else if (len > 0)
3478 written += len;
3479 }
3480
3481 /* finished all the lines, close pipe */
3482 CloseHandle(g_hChildStd_IN_Wr);
3483 ExitThread(0);
3484}
3485
3486
3487# define BUFLEN 100 /* length for buffer, stolen from unix version */
3488
3489/*
3490 * This function read from the children's stdout and write the
3491 * data on screen or in the buffer accordingly.
3492 */
3493 static void
3494dump_pipe(int options,
3495 HANDLE g_hChildStd_OUT_Rd,
3496 garray_T *ga,
3497 char_u buffer[],
3498 DWORD *buffer_off)
3499{
3500 DWORD availableBytes = 0;
3501 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003502 int ret;
3503 DWORD len;
3504 DWORD toRead;
3505 int repeatCount;
3506
3507 /* we query the pipe to see if there is any data to read
3508 * to avoid to perform a blocking read */
3509 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3510 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003511 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003512 NULL, /* number of read bytes */
3513 &availableBytes, /* available bytes total */
3514 NULL); /* byteLeft */
3515
3516 repeatCount = 0;
3517 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003518 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003519 {
3520 repeatCount++;
3521 toRead =
3522# ifdef FEAT_MBYTE
3523 (DWORD)(BUFLEN - *buffer_off);
3524# else
3525 (DWORD)BUFLEN;
3526# endif
3527 toRead = availableBytes < toRead ? availableBytes : toRead;
3528 ReadFile(g_hChildStd_OUT_Rd, buffer
3529# ifdef FEAT_MBYTE
3530 + *buffer_off, toRead
3531# else
3532 , toRead
3533# endif
3534 , &len, NULL);
3535
3536 /* If we haven't read anything, there is a problem */
3537 if (len == 0)
3538 break;
3539
3540 availableBytes -= len;
3541
3542 if (options & SHELL_READ)
3543 {
3544 /* Do NUL -> NL translation, append NL separated
3545 * lines to the current buffer. */
3546 for (i = 0; i < len; ++i)
3547 {
3548 if (buffer[i] == NL)
3549 append_ga_line(ga);
3550 else if (buffer[i] == NUL)
3551 ga_append(ga, NL);
3552 else
3553 ga_append(ga, buffer[i]);
3554 }
3555 }
3556# ifdef FEAT_MBYTE
3557 else if (has_mbyte)
3558 {
3559 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003560 int c;
3561 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003562
3563 len += *buffer_off;
3564 buffer[len] = NUL;
3565
3566 /* Check if the last character in buffer[] is
3567 * incomplete, keep these bytes for the next
3568 * round. */
3569 for (p = buffer; p < buffer + len; p += l)
3570 {
3571 l = mb_cptr2len(p);
3572 if (l == 0)
3573 l = 1; /* NUL byte? */
3574 else if (MB_BYTE2LEN(*p) != l)
3575 break;
3576 }
3577 if (p == buffer) /* no complete character */
3578 {
3579 /* avoid getting stuck at an illegal byte */
3580 if (len >= 12)
3581 ++p;
3582 else
3583 {
3584 *buffer_off = len;
3585 return;
3586 }
3587 }
3588 c = *p;
3589 *p = NUL;
3590 msg_puts(buffer);
3591 if (p < buffer + len)
3592 {
3593 *p = c;
3594 *buffer_off = (DWORD)((buffer + len) - p);
3595 mch_memmove(buffer, p, *buffer_off);
3596 return;
3597 }
3598 *buffer_off = 0;
3599 }
3600# endif /* FEAT_MBYTE */
3601 else
3602 {
3603 buffer[len] = NUL;
3604 msg_puts(buffer);
3605 }
3606
3607 windgoto(msg_row, msg_col);
3608 cursor_on();
3609 out_flush();
3610 }
3611}
3612
3613/*
3614 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
3615 * for communication and doesn't open any new window.
3616 */
3617 static int
3618mch_system_piped(char *cmd, int options)
3619{
3620 STARTUPINFO si;
3621 PROCESS_INFORMATION pi;
3622 DWORD ret = 0;
3623
3624 HANDLE g_hChildStd_IN_Rd = NULL;
3625 HANDLE g_hChildStd_IN_Wr = NULL;
3626 HANDLE g_hChildStd_OUT_Rd = NULL;
3627 HANDLE g_hChildStd_OUT_Wr = NULL;
3628
3629 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
3630 DWORD len;
3631
3632 /* buffer used to receive keys */
3633 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3634 int ta_len = 0; /* valid bytes in ta_buf[] */
3635
3636 DWORD i;
3637 int c;
3638 int noread_cnt = 0;
3639 garray_T ga;
3640 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003641 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003642 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003643
3644 SECURITY_ATTRIBUTES saAttr;
3645
3646 /* Set the bInheritHandle flag so pipe handles are inherited. */
3647 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
3648 saAttr.bInheritHandle = TRUE;
3649 saAttr.lpSecurityDescriptor = NULL;
3650
3651 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
3652 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
3653 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
3654 /* Create a pipe for the child process's STDIN. */
3655 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
3656 /* Ensure the write handle to the pipe for STDIN is not inherited. */
3657 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
3658 {
3659 CloseHandle(g_hChildStd_IN_Rd);
3660 CloseHandle(g_hChildStd_IN_Wr);
3661 CloseHandle(g_hChildStd_OUT_Rd);
3662 CloseHandle(g_hChildStd_OUT_Wr);
3663 MSG_PUTS(_("\nCannot create pipes\n"));
3664 }
3665
3666 si.cb = sizeof(si);
3667 si.lpReserved = NULL;
3668 si.lpDesktop = NULL;
3669 si.lpTitle = NULL;
3670 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
3671
3672 /* set-up our file redirection */
3673 si.hStdError = g_hChildStd_OUT_Wr;
3674 si.hStdOutput = g_hChildStd_OUT_Wr;
3675 si.hStdInput = g_hChildStd_IN_Rd;
3676 si.wShowWindow = SW_HIDE;
3677 si.cbReserved2 = 0;
3678 si.lpReserved2 = NULL;
3679
3680 if (options & SHELL_READ)
3681 ga_init2(&ga, 1, BUFLEN);
3682
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003683 if (cmd != NULL)
3684 {
3685 p = (char *)vim_strsave((char_u *)cmd);
3686 if (p != NULL)
3687 unescape_shellxquote((char_u *)p, p_sxe);
3688 else
3689 p = cmd;
3690 }
3691
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003692 /* Now, run the command */
3693 CreateProcess(NULL, /* Executable name */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003694 p, /* Command to execute */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003695 NULL, /* Process security attributes */
3696 NULL, /* Thread security attributes */
3697
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003698 // this command can be litigious, handle inheritance was
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003699 // deactivated for pending temp file, but, if we deactivate
3700 // it, the pipes don't work for some reason.
3701 TRUE, /* Inherit handles, first deactivated,
3702 * but needed */
3703 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
3704 NULL, /* Environment */
3705 NULL, /* Current directory */
3706 &si, /* Startup information */
3707 &pi); /* Process information */
3708
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003709 if (p != cmd)
3710 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003711
3712 /* Close our unused side of the pipes */
3713 CloseHandle(g_hChildStd_IN_Rd);
3714 CloseHandle(g_hChildStd_OUT_Wr);
3715
3716 if (options & SHELL_WRITE)
3717 {
3718 HANDLE thread =
3719 CreateThread(NULL, /* security attributes */
3720 0, /* default stack size */
3721 sub_process_writer, /* function to be executed */
3722 g_hChildStd_IN_Wr, /* parameter */
3723 0, /* creation flag, start immediately */
3724 NULL); /* we don't care about thread id */
3725 CloseHandle(thread);
3726 g_hChildStd_IN_Wr = NULL;
3727 }
3728
3729 /* Keep updating the window while waiting for the shell to finish. */
3730 for (;;)
3731 {
3732 MSG msg;
3733
3734 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3735 {
3736 TranslateMessage(&msg);
3737 DispatchMessage(&msg);
3738 }
3739
3740 /* write pipe information in the window */
3741 if ((options & (SHELL_READ|SHELL_WRITE))
3742# ifdef FEAT_GUI
3743 || gui.in_use
3744# endif
3745 )
3746 {
3747 len = 0;
3748 if (!(options & SHELL_EXPAND)
3749 && ((options &
3750 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
3751 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
3752# ifdef FEAT_GUI
3753 || gui.in_use
3754# endif
3755 )
3756 && (ta_len > 0 || noread_cnt > 4))
3757 {
3758 if (ta_len == 0)
3759 {
3760 /* Get extra characters when we don't have any. Reset the
3761 * counter and timer. */
3762 noread_cnt = 0;
3763# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
3764 gettimeofday(&start_tv, NULL);
3765# endif
3766 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
3767 }
3768 if (ta_len > 0 || len > 0)
3769 {
3770 /*
3771 * For pipes: Check for CTRL-C: send interrupt signal to
3772 * child. Check for CTRL-D: EOF, close pipe to child.
3773 */
3774 if (len == 1 && cmd != NULL)
3775 {
3776 if (ta_buf[ta_len] == Ctrl_C)
3777 {
3778 /* Learn what exit code is expected, for
3779 * now put 9 as SIGKILL */
3780 TerminateProcess(pi.hProcess, 9);
3781 }
3782 if (ta_buf[ta_len] == Ctrl_D)
3783 {
3784 CloseHandle(g_hChildStd_IN_Wr);
3785 g_hChildStd_IN_Wr = NULL;
3786 }
3787 }
3788
3789 /* replace K_BS by <BS> and K_DEL by <DEL> */
3790 for (i = ta_len; i < ta_len + len; ++i)
3791 {
3792 if (ta_buf[i] == CSI && len - i > 2)
3793 {
3794 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
3795 if (c == K_DEL || c == K_KDEL || c == K_BS)
3796 {
3797 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
3798 (size_t)(len - i - 2));
3799 if (c == K_DEL || c == K_KDEL)
3800 ta_buf[i] = DEL;
3801 else
3802 ta_buf[i] = Ctrl_H;
3803 len -= 2;
3804 }
3805 }
3806 else if (ta_buf[i] == '\r')
3807 ta_buf[i] = '\n';
3808# ifdef FEAT_MBYTE
3809 if (has_mbyte)
3810 i += (*mb_ptr2len_len)(ta_buf + i,
3811 ta_len + len - i) - 1;
3812# endif
3813 }
3814
3815 /*
3816 * For pipes: echo the typed characters. For a pty this
3817 * does not seem to work.
3818 */
3819 for (i = ta_len; i < ta_len + len; ++i)
3820 {
3821 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
3822 msg_putchar(ta_buf[i]);
3823# ifdef FEAT_MBYTE
3824 else if (has_mbyte)
3825 {
3826 int l = (*mb_ptr2len)(ta_buf + i);
3827
3828 msg_outtrans_len(ta_buf + i, l);
3829 i += l - 1;
3830 }
3831# endif
3832 else
3833 msg_outtrans_len(ta_buf + i, 1);
3834 }
3835 windgoto(msg_row, msg_col);
3836 out_flush();
3837
3838 ta_len += len;
3839
3840 /*
3841 * Write the characters to the child, unless EOF has been
3842 * typed for pipes. Write one character at a time, to
3843 * avoid losing too much typeahead. When writing buffer
3844 * lines, drop the typed characters (only check for
3845 * CTRL-C).
3846 */
3847 if (options & SHELL_WRITE)
3848 ta_len = 0;
3849 else if (g_hChildStd_IN_Wr != NULL)
3850 {
3851 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
3852 1, &len, NULL);
3853 // if we are typing in, we want to keep things reactive
3854 delay = 1;
3855 if (len > 0)
3856 {
3857 ta_len -= len;
3858 mch_memmove(ta_buf, ta_buf + len, ta_len);
3859 }
3860 }
3861 }
3862 }
3863 }
3864
3865 if (ta_len)
3866 ui_inchar_undo(ta_buf, ta_len);
3867
3868 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3869 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003870 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003871 break;
3872 }
3873
3874 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003875 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003876
3877 /* We start waiting for a very short time and then increase it, so
3878 * that we respond quickly when the process is quick, and don't
3879 * consume too much overhead when it's slow. */
3880 if (delay < 50)
3881 delay += 10;
3882 }
3883
3884 /* Close the pipe */
3885 CloseHandle(g_hChildStd_OUT_Rd);
3886 if (g_hChildStd_IN_Wr != NULL)
3887 CloseHandle(g_hChildStd_IN_Wr);
3888
3889 WaitForSingleObject(pi.hProcess, INFINITE);
3890
3891 /* Get the command exit code */
3892 GetExitCodeProcess(pi.hProcess, &ret);
3893
3894 if (options & SHELL_READ)
3895 {
3896 if (ga.ga_len > 0)
3897 {
3898 append_ga_line(&ga);
3899 /* remember that the NL was missing */
3900 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
3901 }
3902 else
3903 curbuf->b_no_eol_lnum = 0;
3904 ga_clear(&ga);
3905 }
3906
3907 /* Close the handles to the subprocess, so that it goes away */
3908 CloseHandle(pi.hThread);
3909 CloseHandle(pi.hProcess);
3910
3911 return ret;
3912}
3913
3914 static int
3915mch_system(char *cmd, int options)
3916{
3917 /* if we can pipe and the shelltemp option is off */
3918 if (allowPiping && !p_stmp)
3919 return mch_system_piped(cmd, options);
3920 else
3921 return mch_system_classic(cmd, options);
3922}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003923#else
3924
3925# define mch_system(c, o) system(c)
3926
3927#endif
3928
3929/*
3930 * Either execute a command by calling the shell or start a new shell
3931 */
3932 int
3933mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003934 char_u *cmd,
3935 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003936{
3937 int x = 0;
3938 int tmode = cur_tmode;
3939#ifdef FEAT_TITLE
3940 char szShellTitle[512];
3941
3942 /* Change the title to reflect that we are in a subshell. */
3943 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3944 {
3945 if (cmd == NULL)
3946 strcat(szShellTitle, " :sh");
3947 else
3948 {
3949 strcat(szShellTitle, " - !");
3950 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3951 strcat(szShellTitle, cmd);
3952 }
3953 mch_settitle(szShellTitle, NULL);
3954 }
3955#endif
3956
3957 out_flush();
3958
3959#ifdef MCH_WRITE_DUMP
3960 if (fdDump)
3961 {
3962 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3963 fflush(fdDump);
3964 }
3965#endif
3966
3967 /*
3968 * Catch all deadly signals while running the external command, because a
3969 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3970 */
3971 signal(SIGINT, SIG_IGN);
3972#if defined(__GNUC__) && !defined(__MINGW32__)
3973 signal(SIGKILL, SIG_IGN);
3974#else
3975 signal(SIGBREAK, SIG_IGN);
3976#endif
3977 signal(SIGILL, SIG_IGN);
3978 signal(SIGFPE, SIG_IGN);
3979 signal(SIGSEGV, SIG_IGN);
3980 signal(SIGTERM, SIG_IGN);
3981 signal(SIGABRT, SIG_IGN);
3982
3983 if (options & SHELL_COOKED)
3984 settmode(TMODE_COOK); /* set to normal mode */
3985
3986 if (cmd == NULL)
3987 {
3988 x = mch_system(p_sh, options);
3989 }
3990 else
3991 {
3992 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01003993 char_u *newcmd = NULL;
3994 char_u *cmdbase = cmd;
3995 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003996
3997 /* Skip a leading ", ( and "(. */
3998 if (*cmdbase == '"' )
3999 ++cmdbase;
4000 if (*cmdbase == '(')
4001 ++cmdbase;
4002
4003 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4004 {
4005 STARTUPINFO si;
4006 PROCESS_INFORMATION pi;
4007 DWORD flags = CREATE_NEW_CONSOLE;
4008 char_u *p;
4009
4010 si.cb = sizeof(si);
4011 si.lpReserved = NULL;
4012 si.lpDesktop = NULL;
4013 si.lpTitle = NULL;
4014 si.dwFlags = 0;
4015 si.cbReserved2 = 0;
4016 si.lpReserved2 = NULL;
4017
4018 cmdbase = skipwhite(cmdbase + 5);
4019 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4020 && vim_iswhite(cmdbase[4]))
4021 {
4022 cmdbase = skipwhite(cmdbase + 4);
4023 si.dwFlags = STARTF_USESHOWWINDOW;
4024 si.wShowWindow = SW_SHOWMINNOACTIVE;
4025 }
4026 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4027 && vim_iswhite(cmdbase[2]))
4028 {
4029 cmdbase = skipwhite(cmdbase + 2);
4030 flags = CREATE_NO_WINDOW;
4031 si.dwFlags = STARTF_USESTDHANDLES;
4032 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004033 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004034 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004035 NULL, // Security att.
4036 OPEN_EXISTING, // Open flags
4037 FILE_ATTRIBUTE_NORMAL, // File att.
4038 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004039 si.hStdOutput = si.hStdInput;
4040 si.hStdError = si.hStdInput;
4041 }
4042
4043 /* Remove a trailing ", ) and )" if they have a match
4044 * at the start of the command. */
4045 if (cmdbase > cmd)
4046 {
4047 p = cmdbase + STRLEN(cmdbase);
4048 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4049 *--p = NUL;
4050 if (p > cmdbase && p[-1] == ')'
4051 && (*cmd =='(' || cmd[1] == '('))
4052 *--p = NUL;
4053 }
4054
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004055 newcmd = cmdbase;
4056 unescape_shellxquote(cmdbase, p_sxe);
4057
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004058 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004059 * If creating new console, arguments are passed to the
4060 * 'cmd.exe' as-is. If it's not, arguments are not treated
4061 * correctly for current 'cmd.exe'. So unescape characters in
4062 * shellxescape except '|' for avoiding to be treated as
4063 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004064 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004065 if (flags != CREATE_NEW_CONSOLE)
4066 {
4067 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004068 char_u *cmd_shell = mch_getenv("COMSPEC");
4069
4070 if (cmd_shell == NULL || *cmd_shell == NUL)
4071 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004072
4073 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4074 if (subcmd != NULL)
4075 {
4076 /* make "cmd.exe /c arguments" */
4077 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004078 newcmd = lalloc(cmdlen, TRUE);
4079 if (newcmd != NULL)
4080 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004081 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004082 else
4083 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004084 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004085 }
4086 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004087
4088 /*
4089 * Now, start the command as a process, so that it doesn't
4090 * inherit our handles which causes unpleasant dangling swap
4091 * files if we exit before the spawned process
4092 */
4093 if (CreateProcess(NULL, // Executable name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004094 newcmd, // Command to execute
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004095 NULL, // Process security attributes
4096 NULL, // Thread security attributes
4097 FALSE, // Inherit handles
4098 flags, // Creation flags
4099 NULL, // Environment
4100 NULL, // Current directory
4101 &si, // Startup information
4102 &pi)) // Process information
4103 x = 0;
4104 else
4105 {
4106 x = -1;
4107#ifdef FEAT_GUI_W32
4108 EMSG(_("E371: Command not found"));
4109#endif
4110 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004111
4112 if (newcmd != cmdbase)
4113 vim_free(newcmd);
4114
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004115 if (si.hStdInput != NULL)
4116 {
4117 /* Close the handle to \\.\NUL */
4118 CloseHandle(si.hStdInput);
4119 }
4120 /* Close the handles to the subprocess, so that it goes away */
4121 CloseHandle(pi.hThread);
4122 CloseHandle(pi.hProcess);
4123 }
4124 else
4125 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004126 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004127#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004128 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004130 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4131
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004132 newcmd = lalloc(cmdlen, TRUE);
4133 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134 {
4135#if defined(FEAT_GUI_W32)
4136 if (need_vimrun_warning)
4137 {
4138 MessageBox(NULL,
4139 _("VIMRUN.EXE not found in your $PATH.\n"
4140 "External commands will not pause after completion.\n"
4141 "See :help win32-vimrun for more information."),
4142 _("Vim Warning"),
4143 MB_ICONWARNING);
4144 need_vimrun_warning = FALSE;
4145 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004146 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004147 /* Use vimrun to execute the command. It opens a console
4148 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004149 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150 vimrun_path,
4151 (msg_silent != 0 || (options & SHELL_DOOUT))
4152 ? "-s " : "",
4153 p_sh, p_shcf, cmd);
4154 else
4155#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004156 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004157 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004158 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004159 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161 }
4162 }
4163
4164 if (tmode == TMODE_RAW)
4165 settmode(TMODE_RAW); /* set to raw mode */
4166
4167 /* Print the return value, unless "vimrun" was used. */
4168 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4169#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004170 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4171 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172#endif
4173 )
4174 {
4175 smsg(_("shell returned %d"), x);
4176 msg_putchar('\n');
4177 }
4178#ifdef FEAT_TITLE
4179 resettitle();
4180#endif
4181
4182 signal(SIGINT, SIG_DFL);
4183#if defined(__GNUC__) && !defined(__MINGW32__)
4184 signal(SIGKILL, SIG_DFL);
4185#else
4186 signal(SIGBREAK, SIG_DFL);
4187#endif
4188 signal(SIGILL, SIG_DFL);
4189 signal(SIGFPE, SIG_DFL);
4190 signal(SIGSEGV, SIG_DFL);
4191 signal(SIGTERM, SIG_DFL);
4192 signal(SIGABRT, SIG_DFL);
4193
4194 return x;
4195}
4196
4197
4198#ifndef FEAT_GUI_W32
4199
4200/*
4201 * Start termcap mode
4202 */
4203 static void
4204termcap_mode_start(void)
4205{
4206 DWORD cmodein;
4207
4208 if (g_fTermcapMode)
4209 return;
4210
4211 SaveConsoleBuffer(&g_cbNonTermcap);
4212
4213 if (g_cbTermcap.IsValid)
4214 {
4215 /*
4216 * We've been in termcap mode before. Restore certain screen
4217 * characteristics, including the buffer size and the window
4218 * size. Since we will be redrawing the screen, we don't need
4219 * to restore the actual contents of the buffer.
4220 */
4221 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4222 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4223 Rows = g_cbTermcap.Info.dwSize.Y;
4224 Columns = g_cbTermcap.Info.dwSize.X;
4225 }
4226 else
4227 {
4228 /*
4229 * This is our first time entering termcap mode. Clear the console
4230 * screen buffer, and resize the buffer to match the current window
4231 * size. We will use this as the size of our editing environment.
4232 */
4233 ClearConsoleBuffer(g_attrCurrent);
4234 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4235 }
4236
4237#ifdef FEAT_TITLE
4238 resettitle();
4239#endif
4240
4241 GetConsoleMode(g_hConIn, &cmodein);
4242#ifdef FEAT_MOUSE
4243 if (g_fMouseActive)
4244 cmodein |= ENABLE_MOUSE_INPUT;
4245 else
4246 cmodein &= ~ENABLE_MOUSE_INPUT;
4247#endif
4248 cmodein |= ENABLE_WINDOW_INPUT;
4249 SetConsoleMode(g_hConIn, cmodein);
4250
4251 redraw_later_clear();
4252 g_fTermcapMode = TRUE;
4253}
4254
4255
4256/*
4257 * End termcap mode
4258 */
4259 static void
4260termcap_mode_end(void)
4261{
4262 DWORD cmodein;
4263 ConsoleBuffer *cb;
4264 COORD coord;
4265 DWORD dwDummy;
4266
4267 if (!g_fTermcapMode)
4268 return;
4269
4270 SaveConsoleBuffer(&g_cbTermcap);
4271
4272 GetConsoleMode(g_hConIn, &cmodein);
4273 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4274 SetConsoleMode(g_hConIn, cmodein);
4275
4276#ifdef FEAT_RESTORE_ORIG_SCREEN
4277 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4278#else
4279 cb = &g_cbNonTermcap;
4280#endif
4281 RestoreConsoleBuffer(cb, p_rs);
4282 SetConsoleCursorInfo(g_hConOut, &g_cci);
4283
4284 if (p_rs || exiting)
4285 {
4286 /*
4287 * Clear anything that happens to be on the current line.
4288 */
4289 coord.X = 0;
4290 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4291 FillConsoleOutputCharacter(g_hConOut, ' ',
4292 cb->Info.dwSize.X, coord, &dwDummy);
4293 /*
4294 * The following is just for aesthetics. If we are exiting without
4295 * restoring the screen, then we want to have a prompt string
4296 * appear at the bottom line. However, the command interpreter
4297 * seems to always advance the cursor one line before displaying
4298 * the prompt string, which causes the screen to scroll. To
4299 * counter this, move the cursor up one line before exiting.
4300 */
4301 if (exiting && !p_rs)
4302 coord.Y--;
4303 /*
4304 * Position the cursor at the leftmost column of the desired row.
4305 */
4306 SetConsoleCursorPosition(g_hConOut, coord);
4307 }
4308
4309 g_fTermcapMode = FALSE;
4310}
4311#endif /* FEAT_GUI_W32 */
4312
4313
4314#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004315/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004316 void
4317mch_write(
4318 char_u *s,
4319 int len)
4320{
4321 /* never used */
4322}
4323
4324#else
4325
4326/*
4327 * clear `n' chars, starting from `coord'
4328 */
4329 static void
4330clear_chars(
4331 COORD coord,
4332 DWORD n)
4333{
4334 DWORD dwDummy;
4335
4336 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4337 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4338}
4339
4340
4341/*
4342 * Clear the screen
4343 */
4344 static void
4345clear_screen(void)
4346{
4347 g_coord.X = g_coord.Y = 0;
4348 clear_chars(g_coord, Rows * Columns);
4349}
4350
4351
4352/*
4353 * Clear to end of display
4354 */
4355 static void
4356clear_to_end_of_display(void)
4357{
4358 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4359 * Columns + (Columns - g_coord.X));
4360}
4361
4362
4363/*
4364 * Clear to end of line
4365 */
4366 static void
4367clear_to_end_of_line(void)
4368{
4369 clear_chars(g_coord, Columns - g_coord.X);
4370}
4371
4372
4373/*
4374 * Scroll the scroll region up by `cLines' lines
4375 */
4376 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004377scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004378{
4379 COORD oldcoord = g_coord;
4380
4381 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4382 delete_lines(cLines);
4383
4384 g_coord = oldcoord;
4385}
4386
4387
4388/*
4389 * Set the scroll region
4390 */
4391 static void
4392set_scroll_region(
4393 unsigned left,
4394 unsigned top,
4395 unsigned right,
4396 unsigned bottom)
4397{
4398 if (left >= right
4399 || top >= bottom
4400 || right > (unsigned) Columns - 1
4401 || bottom > (unsigned) Rows - 1)
4402 return;
4403
4404 g_srScrollRegion.Left = left;
4405 g_srScrollRegion.Top = top;
4406 g_srScrollRegion.Right = right;
4407 g_srScrollRegion.Bottom = bottom;
4408}
4409
4410
4411/*
4412 * Insert `cLines' lines at the current cursor position
4413 */
4414 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004415insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004416{
4417 SMALL_RECT source;
4418 COORD dest;
4419 CHAR_INFO fill;
4420
4421 dest.X = 0;
4422 dest.Y = g_coord.Y + cLines;
4423
4424 source.Left = 0;
4425 source.Top = g_coord.Y;
4426 source.Right = g_srScrollRegion.Right;
4427 source.Bottom = g_srScrollRegion.Bottom - cLines;
4428
4429 fill.Char.AsciiChar = ' ';
4430 fill.Attributes = g_attrCurrent;
4431
4432 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4433
4434 /* Here we have to deal with a win32 console flake: If the scroll
4435 * region looks like abc and we scroll c to a and fill with d we get
4436 * cbd... if we scroll block c one line at a time to a, we get cdd...
4437 * vim expects cdd consistently... So we have to deal with that
4438 * here... (this also occurs scrolling the same way in the other
4439 * direction). */
4440
4441 if (source.Bottom < dest.Y)
4442 {
4443 COORD coord;
4444
4445 coord.X = 0;
4446 coord.Y = source.Bottom;
4447 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4448 }
4449}
4450
4451
4452/*
4453 * Delete `cLines' lines at the current cursor position
4454 */
4455 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004456delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457{
4458 SMALL_RECT source;
4459 COORD dest;
4460 CHAR_INFO fill;
4461 int nb;
4462
4463 dest.X = 0;
4464 dest.Y = g_coord.Y;
4465
4466 source.Left = 0;
4467 source.Top = g_coord.Y + cLines;
4468 source.Right = g_srScrollRegion.Right;
4469 source.Bottom = g_srScrollRegion.Bottom;
4470
4471 fill.Char.AsciiChar = ' ';
4472 fill.Attributes = g_attrCurrent;
4473
4474 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4475
4476 /* Here we have to deal with a win32 console flake: If the scroll
4477 * region looks like abc and we scroll c to a and fill with d we get
4478 * cbd... if we scroll block c one line at a time to a, we get cdd...
4479 * vim expects cdd consistently... So we have to deal with that
4480 * here... (this also occurs scrolling the same way in the other
4481 * direction). */
4482
4483 nb = dest.Y + (source.Bottom - source.Top) + 1;
4484
4485 if (nb < source.Top)
4486 {
4487 COORD coord;
4488
4489 coord.X = 0;
4490 coord.Y = nb;
4491 clear_chars(coord, Columns * (source.Top - nb));
4492 }
4493}
4494
4495
4496/*
4497 * Set the cursor position
4498 */
4499 static void
4500gotoxy(
4501 unsigned x,
4502 unsigned y)
4503{
4504 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4505 return;
4506
4507 /* external cursor coords are 1-based; internal are 0-based */
4508 g_coord.X = x - 1;
4509 g_coord.Y = y - 1;
4510 SetConsoleCursorPosition(g_hConOut, g_coord);
4511}
4512
4513
4514/*
4515 * Set the current text attribute = (foreground | background)
4516 * See ../doc/os_win32.txt for the numbers.
4517 */
4518 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004519textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520{
4521 g_attrCurrent = wAttr;
4522
4523 SetConsoleTextAttribute(g_hConOut, wAttr);
4524}
4525
4526
4527 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004528textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004529{
4530 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
4531
4532 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4533}
4534
4535
4536 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004537textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004538{
4539 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
4540
4541 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4542}
4543
4544
4545/*
4546 * restore the default text attribute (whatever we started with)
4547 */
4548 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004549normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004550{
4551 textattr(g_attrDefault);
4552}
4553
4554
4555static WORD g_attrPreStandout = 0;
4556
4557/*
4558 * Make the text standout, by brightening it
4559 */
4560 static void
4561standout(void)
4562{
4563 g_attrPreStandout = g_attrCurrent;
4564 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
4565}
4566
4567
4568/*
4569 * Turn off standout mode
4570 */
4571 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004572standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004573{
4574 if (g_attrPreStandout)
4575 {
4576 textattr(g_attrPreStandout);
4577 g_attrPreStandout = 0;
4578 }
4579}
4580
4581
4582/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00004583 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004584 */
4585 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004586mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004587{
4588 char_u *p;
4589 int n;
4590
4591 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
4592 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
4593 if (T_ME[0] == ESC && T_ME[1] == '|')
4594 {
4595 p = T_ME + 2;
4596 n = getdigits(&p);
4597 if (*p == 'm' && n > 0)
4598 {
4599 cterm_normal_fg_color = (n & 0xf) + 1;
4600 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
4601 }
4602 }
4603}
4604
4605
4606/*
4607 * visual bell: flash the screen
4608 */
4609 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004610visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611{
4612 COORD coordOrigin = {0, 0};
4613 WORD attrFlash = ~g_attrCurrent & 0xff;
4614
4615 DWORD dwDummy;
4616 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
4617
4618 if (oldattrs == NULL)
4619 return;
4620 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4621 coordOrigin, &dwDummy);
4622 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
4623 coordOrigin, &dwDummy);
4624
4625 Sleep(15); /* wait for 15 msec */
4626 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4627 coordOrigin, &dwDummy);
4628 vim_free(oldattrs);
4629}
4630
4631
4632/*
4633 * Make the cursor visible or invisible
4634 */
4635 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004636cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004637{
4638 s_cursor_visible = fVisible;
4639#ifdef MCH_CURSOR_SHAPE
4640 mch_update_cursor();
4641#endif
4642}
4643
4644
4645/*
4646 * write `cchToWrite' characters in `pchBuf' to the screen
4647 * Returns the number of characters actually written (at least one).
4648 */
4649 static BOOL
4650write_chars(
4651 LPCSTR pchBuf,
4652 DWORD cchToWrite)
4653{
4654 COORD coord = g_coord;
4655 DWORD written;
4656
4657 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
4658 coord, &written);
4659 /* When writing fails or didn't write a single character, pretend one
4660 * character was written, otherwise we get stuck. */
4661 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
4662 coord, &written) == 0
4663 || written == 0)
4664 written = 1;
4665
4666 g_coord.X += (SHORT) written;
4667
4668 while (g_coord.X > g_srScrollRegion.Right)
4669 {
4670 g_coord.X -= (SHORT) Columns;
4671 if (g_coord.Y < g_srScrollRegion.Bottom)
4672 g_coord.Y++;
4673 }
4674
4675 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4676
4677 return written;
4678}
4679
4680
4681/*
4682 * mch_write(): write the output buffer to the screen, translating ESC
4683 * sequences into calls to console output routines.
4684 */
4685 void
4686mch_write(
4687 char_u *s,
4688 int len)
4689{
4690 s[len] = NUL;
4691
4692 if (!term_console)
4693 {
4694 write(1, s, (unsigned)len);
4695 return;
4696 }
4697
4698 /* translate ESC | sequences into faked bios calls */
4699 while (len--)
4700 {
4701 /* optimization: use one single write_chars for runs of text,
4702 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004703 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004704
4705 if (p_wd)
4706 {
4707 WaitForChar(p_wd);
4708 if (prefix != 0)
4709 prefix = 1;
4710 }
4711
4712 if (prefix != 0)
4713 {
4714 DWORD nWritten;
4715
4716 nWritten = write_chars(s, prefix);
4717#ifdef MCH_WRITE_DUMP
4718 if (fdDump)
4719 {
4720 fputc('>', fdDump);
4721 fwrite(s, sizeof(char_u), nWritten, fdDump);
4722 fputs("<\n", fdDump);
4723 }
4724#endif
4725 len -= (nWritten - 1);
4726 s += nWritten;
4727 }
4728 else if (s[0] == '\n')
4729 {
4730 /* \n, newline: go to the beginning of the next line or scroll */
4731 if (g_coord.Y == g_srScrollRegion.Bottom)
4732 {
4733 scroll(1);
4734 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
4735 }
4736 else
4737 {
4738 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
4739 }
4740#ifdef MCH_WRITE_DUMP
4741 if (fdDump)
4742 fputs("\\n\n", fdDump);
4743#endif
4744 s++;
4745 }
4746 else if (s[0] == '\r')
4747 {
4748 /* \r, carriage return: go to beginning of line */
4749 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
4750#ifdef MCH_WRITE_DUMP
4751 if (fdDump)
4752 fputs("\\r\n", fdDump);
4753#endif
4754 s++;
4755 }
4756 else if (s[0] == '\b')
4757 {
4758 /* \b, backspace: move cursor one position left */
4759 if (g_coord.X > g_srScrollRegion.Left)
4760 g_coord.X--;
4761 else if (g_coord.Y > g_srScrollRegion.Top)
4762 {
4763 g_coord.X = g_srScrollRegion.Right;
4764 g_coord.Y--;
4765 }
4766 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4767#ifdef MCH_WRITE_DUMP
4768 if (fdDump)
4769 fputs("\\b\n", fdDump);
4770#endif
4771 s++;
4772 }
4773 else if (s[0] == '\a')
4774 {
4775 /* \a, bell */
4776 MessageBeep(0xFFFFFFFF);
4777#ifdef MCH_WRITE_DUMP
4778 if (fdDump)
4779 fputs("\\a\n", fdDump);
4780#endif
4781 s++;
4782 }
4783 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
4784 {
4785#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004786 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004787#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004788 char_u *p;
4789 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004790
4791 switch (s[2])
4792 {
4793 /* one or two numeric arguments, separated by ';' */
4794
4795 case '0': case '1': case '2': case '3': case '4':
4796 case '5': case '6': case '7': case '8': case '9':
4797 p = s + 2;
4798 arg1 = getdigits(&p); /* no check for length! */
4799 if (p > s + len)
4800 break;
4801
4802 if (*p == ';')
4803 {
4804 ++p;
4805 arg2 = getdigits(&p); /* no check for length! */
4806 if (p > s + len)
4807 break;
4808
4809 if (*p == 'H')
4810 gotoxy(arg2, arg1);
4811 else if (*p == 'r')
4812 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4813 }
4814 else if (*p == 'A')
4815 {
4816 /* move cursor up arg1 lines in same column */
4817 gotoxy(g_coord.X + 1,
4818 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4819 }
4820 else if (*p == 'C')
4821 {
4822 /* move cursor right arg1 columns in same line */
4823 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4824 g_coord.Y + 1);
4825 }
4826 else if (*p == 'H')
4827 {
4828 gotoxy(1, arg1);
4829 }
4830 else if (*p == 'L')
4831 {
4832 insert_lines(arg1);
4833 }
4834 else if (*p == 'm')
4835 {
4836 if (arg1 == 0)
4837 normvideo();
4838 else
4839 textattr((WORD) arg1);
4840 }
4841 else if (*p == 'f')
4842 {
4843 textcolor((WORD) arg1);
4844 }
4845 else if (*p == 'b')
4846 {
4847 textbackground((WORD) arg1);
4848 }
4849 else if (*p == 'M')
4850 {
4851 delete_lines(arg1);
4852 }
4853
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00004854 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 s = p + 1;
4856 break;
4857
4858
4859 /* Three-character escape sequences */
4860
4861 case 'A':
4862 /* move cursor up one line in same column */
4863 gotoxy(g_coord.X + 1,
4864 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4865 goto got3;
4866
4867 case 'B':
4868 visual_bell();
4869 goto got3;
4870
4871 case 'C':
4872 /* move cursor right one column in same line */
4873 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4874 g_coord.Y + 1);
4875 goto got3;
4876
4877 case 'E':
4878 termcap_mode_end();
4879 goto got3;
4880
4881 case 'F':
4882 standout();
4883 goto got3;
4884
4885 case 'f':
4886 standend();
4887 goto got3;
4888
4889 case 'H':
4890 gotoxy(1, 1);
4891 goto got3;
4892
4893 case 'j':
4894 clear_to_end_of_display();
4895 goto got3;
4896
4897 case 'J':
4898 clear_screen();
4899 goto got3;
4900
4901 case 'K':
4902 clear_to_end_of_line();
4903 goto got3;
4904
4905 case 'L':
4906 insert_lines(1);
4907 goto got3;
4908
4909 case 'M':
4910 delete_lines(1);
4911 goto got3;
4912
4913 case 'S':
4914 termcap_mode_start();
4915 goto got3;
4916
4917 case 'V':
4918 cursor_visible(TRUE);
4919 goto got3;
4920
4921 case 'v':
4922 cursor_visible(FALSE);
4923 goto got3;
4924
4925 got3:
4926 s += 3;
4927 len -= 2;
4928 }
4929
4930#ifdef MCH_WRITE_DUMP
4931 if (fdDump)
4932 {
4933 fputs("ESC | ", fdDump);
4934 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4935 fputc('\n', fdDump);
4936 }
4937#endif
4938 }
4939 else
4940 {
4941 /* Write a single character */
4942 DWORD nWritten;
4943
4944 nWritten = write_chars(s, 1);
4945#ifdef MCH_WRITE_DUMP
4946 if (fdDump)
4947 {
4948 fputc('>', fdDump);
4949 fwrite(s, sizeof(char_u), nWritten, fdDump);
4950 fputs("<\n", fdDump);
4951 }
4952#endif
4953
4954 len -= (nWritten - 1);
4955 s += nWritten;
4956 }
4957 }
4958
4959#ifdef MCH_WRITE_DUMP
4960 if (fdDump)
4961 fflush(fdDump);
4962#endif
4963}
4964
4965#endif /* FEAT_GUI_W32 */
4966
4967
4968/*
4969 * Delay for half a second.
4970 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004971/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004972 void
4973mch_delay(
4974 long msec,
4975 int ignoreinput)
4976{
4977#ifdef FEAT_GUI_W32
4978 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004979#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004980 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004981# ifdef FEAT_MZSCHEME
4982 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4983 {
4984 int towait = p_mzq;
4985
4986 /* if msec is large enough, wait by portions in p_mzq */
4987 while (msec > 0)
4988 {
4989 mzvim_check_threads();
4990 if (msec < towait)
4991 towait = msec;
4992 Sleep(towait);
4993 msec -= towait;
4994 }
4995 }
4996 else
4997# endif
4998 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004999 else
5000 WaitForChar(msec);
5001#endif
5002}
5003
5004
5005/*
5006 * this version of remove is not scared by a readonly (backup) file
5007 * Return 0 for success, -1 for failure.
5008 */
5009 int
5010mch_remove(char_u *name)
5011{
5012#ifdef FEAT_MBYTE
5013 WCHAR *wn = NULL;
5014 int n;
5015
5016 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5017 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005018 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005019 if (wn != NULL)
5020 {
5021 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
5022 n = DeleteFileW(wn) ? 0 : -1;
5023 vim_free(wn);
5024 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5025 return n;
5026 /* Retry with non-wide function (for Windows 98). */
5027 }
5028 }
5029#endif
5030 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
5031 return DeleteFile(name) ? 0 : -1;
5032}
5033
5034
5035/*
5036 * check for an "interrupt signal": CTRL-break or CTRL-C
5037 */
5038 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005039mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040{
5041#ifndef FEAT_GUI_W32 /* never used */
5042 if (g_fCtrlCPressed || g_fCBrkPressed)
5043 {
5044 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5045 got_int = TRUE;
5046 }
5047#endif
5048}
5049
5050
Bram Moolenaar071d4272004-06-13 20:20:40 +00005051#ifdef FEAT_MBYTE
5052/*
5053 * Same code as below, but with wide functions and no comments.
5054 * Return 0 for success, non-zero for failure.
5055 */
5056 int
5057mch_wrename(WCHAR *wold, WCHAR *wnew)
5058{
5059 WCHAR *p;
5060 int i;
5061 WCHAR szTempFile[_MAX_PATH + 1];
5062 WCHAR szNewPath[_MAX_PATH + 1];
5063 HANDLE hf;
5064
5065 if (!mch_windows95())
5066 {
5067 p = wold;
5068 for (i = 0; wold[i] != NUL; ++i)
5069 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5070 && wold[i + 1] != 0)
5071 p = wold + i + 1;
5072 if ((int)(wold + i - p) < 8 || p[6] != '~')
5073 return (MoveFileW(wold, wnew) == 0);
5074 }
5075
5076 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5077 return -1;
5078 *p = NUL;
5079
5080 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5081 return -2;
5082
5083 if (!DeleteFileW(szTempFile))
5084 return -3;
5085
5086 if (!MoveFileW(wold, szTempFile))
5087 return -4;
5088
5089 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5090 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5091 return -5;
5092 if (!CloseHandle(hf))
5093 return -6;
5094
5095 if (!MoveFileW(szTempFile, wnew))
5096 {
5097 (void)MoveFileW(szTempFile, wold);
5098 return -7;
5099 }
5100
5101 DeleteFileW(szTempFile);
5102
5103 if (!DeleteFileW(wold))
5104 return -8;
5105
5106 return 0;
5107}
5108#endif
5109
5110
5111/*
5112 * mch_rename() works around a bug in rename (aka MoveFile) in
5113 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5114 * file whose short file name is "FOO.BAR" (its long file name will
5115 * be correct: "foo.bar~"). Because a file can be accessed by
5116 * either its SFN or its LFN, "foo.bar" has effectively been
5117 * renamed to "foo.bar", which is not at all what was wanted. This
5118 * seems to happen only when renaming files with three-character
5119 * extensions by appending a suffix that does not include ".".
5120 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5121 *
5122 * There is another problem, which isn't really a bug but isn't right either:
5123 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5124 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5125 * service pack 6. Doesn't seem to happen on Windows 98.
5126 *
5127 * Like rename(), returns 0 upon success, non-zero upon failure.
5128 * Should probably set errno appropriately when errors occur.
5129 */
5130 int
5131mch_rename(
5132 const char *pszOldFile,
5133 const char *pszNewFile)
5134{
5135 char szTempFile[_MAX_PATH+1];
5136 char szNewPath[_MAX_PATH+1];
5137 char *pszFilePart;
5138 HANDLE hf;
5139#ifdef FEAT_MBYTE
5140 WCHAR *wold = NULL;
5141 WCHAR *wnew = NULL;
5142 int retval = -1;
5143
5144 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5145 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005146 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5147 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005148 if (wold != NULL && wnew != NULL)
5149 retval = mch_wrename(wold, wnew);
5150 vim_free(wold);
5151 vim_free(wnew);
5152 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5153 return retval;
5154 /* Retry with non-wide function (for Windows 98). */
5155 }
5156#endif
5157
5158 /*
5159 * No need to play tricks if not running Windows 95, unless the file name
5160 * contains a "~" as the seventh character.
5161 */
5162 if (!mch_windows95())
5163 {
5164 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5165 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5166 return rename(pszOldFile, pszNewFile);
5167 }
5168
5169 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5170 * a directory, no error is returned and pszFilePart will be NULL. */
5171 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5172 || pszFilePart == NULL)
5173 return -1;
5174 *pszFilePart = NUL;
5175
5176 /* Get (and create) a unique temporary file name in directory of new file */
5177 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5178 return -2;
5179
5180 /* blow the temp file away */
5181 if (!DeleteFile(szTempFile))
5182 return -3;
5183
5184 /* rename old file to the temp file */
5185 if (!MoveFile(pszOldFile, szTempFile))
5186 return -4;
5187
5188 /* now create an empty file called pszOldFile; this prevents the operating
5189 * system using pszOldFile as an alias (SFN) if we're renaming within the
5190 * same directory. For example, we're editing a file called
5191 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5192 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5193 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005194 * cause all sorts of problems later in buf_write(). So, we create an
5195 * empty file called filena~1.txt and the system will have to find some
5196 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005197 */
5198 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5199 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5200 return -5;
5201 if (!CloseHandle(hf))
5202 return -6;
5203
5204 /* rename the temp file to the new file */
5205 if (!MoveFile(szTempFile, pszNewFile))
5206 {
5207 /* Renaming failed. Rename the file back to its old name, so that it
5208 * looks like nothing happened. */
5209 (void)MoveFile(szTempFile, pszOldFile);
5210
5211 return -7;
5212 }
5213
5214 /* Seems to be left around on Novell filesystems */
5215 DeleteFile(szTempFile);
5216
5217 /* finally, remove the empty old file */
5218 if (!DeleteFile(pszOldFile))
5219 return -8;
5220
5221 return 0; /* success */
5222}
5223
5224/*
5225 * Get the default shell for the current hardware platform
5226 */
5227 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005228default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005229{
5230 char* psz = NULL;
5231
5232 PlatformId();
5233
5234 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5235 psz = "cmd.exe";
5236 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5237 psz = "command.com";
5238
5239 return psz;
5240}
5241
5242/*
5243 * mch_access() extends access() to do more detailed check on network drives.
5244 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5245 */
5246 int
5247mch_access(char *n, int p)
5248{
5249 HANDLE hFile;
5250 DWORD am;
5251 int retval = -1; /* default: fail */
5252#ifdef FEAT_MBYTE
5253 WCHAR *wn = NULL;
5254
5255 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005256 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005257#endif
5258
5259 if (mch_isdir(n))
5260 {
5261 char TempName[_MAX_PATH + 16] = "";
5262#ifdef FEAT_MBYTE
5263 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5264#endif
5265
5266 if (p & R_OK)
5267 {
5268 /* Read check is performed by seeing if we can do a find file on
5269 * the directory for any file. */
5270#ifdef FEAT_MBYTE
5271 if (wn != NULL)
5272 {
5273 int i;
5274 WIN32_FIND_DATAW d;
5275
5276 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5277 TempNameW[i] = wn[i];
5278 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5279 TempNameW[i++] = '\\';
5280 TempNameW[i++] = '*';
5281 TempNameW[i++] = 0;
5282
5283 hFile = FindFirstFileW(TempNameW, &d);
5284 if (hFile == INVALID_HANDLE_VALUE)
5285 {
5286 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5287 goto getout;
5288
5289 /* Retry with non-wide function (for Windows 98). */
5290 vim_free(wn);
5291 wn = NULL;
5292 }
5293 else
5294 (void)FindClose(hFile);
5295 }
5296 if (wn == NULL)
5297#endif
5298 {
5299 char *pch;
5300 WIN32_FIND_DATA d;
5301
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005302 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005303 pch = TempName + STRLEN(TempName) - 1;
5304 if (*pch != '\\' && *pch != '/')
5305 *++pch = '\\';
5306 *++pch = '*';
5307 *++pch = NUL;
5308
5309 hFile = FindFirstFile(TempName, &d);
5310 if (hFile == INVALID_HANDLE_VALUE)
5311 goto getout;
5312 (void)FindClose(hFile);
5313 }
5314 }
5315
5316 if (p & W_OK)
5317 {
5318 /* Trying to create a temporary file in the directory should catch
5319 * directories on read-only network shares. However, in
5320 * directories whose ACL allows writes but denies deletes will end
5321 * up keeping the temporary file :-(. */
5322#ifdef FEAT_MBYTE
5323 if (wn != NULL)
5324 {
5325 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5326 {
5327 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5328 goto getout;
5329
5330 /* Retry with non-wide function (for Windows 98). */
5331 vim_free(wn);
5332 wn = NULL;
5333 }
5334 else
5335 DeleteFileW(TempNameW);
5336 }
5337 if (wn == NULL)
5338#endif
5339 {
5340 if (!GetTempFileName(n, "VIM", 0, TempName))
5341 goto getout;
5342 mch_remove((char_u *)TempName);
5343 }
5344 }
5345 }
5346 else
5347 {
5348 /* Trying to open the file for the required access does ACL, read-only
5349 * network share, and file attribute checks. */
5350 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5351 | ((p & R_OK) ? GENERIC_READ : 0);
5352#ifdef FEAT_MBYTE
5353 if (wn != NULL)
5354 {
5355 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5356 if (hFile == INVALID_HANDLE_VALUE
5357 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5358 {
5359 /* Retry with non-wide function (for Windows 98). */
5360 vim_free(wn);
5361 wn = NULL;
5362 }
5363 }
5364 if (wn == NULL)
5365#endif
5366 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5367 if (hFile == INVALID_HANDLE_VALUE)
5368 goto getout;
5369 CloseHandle(hFile);
5370 }
5371
5372 retval = 0; /* success */
5373getout:
5374#ifdef FEAT_MBYTE
5375 vim_free(wn);
5376#endif
5377 return retval;
5378}
5379
5380#if defined(FEAT_MBYTE) || defined(PROTO)
5381/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005382 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005383 */
5384 int
5385mch_open(char *name, int flags, int mode)
5386{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005387 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5388# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005389 WCHAR *wn;
5390 int f;
5391
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005392 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005393 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005394 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005395 if (wn != NULL)
5396 {
5397 f = _wopen(wn, flags, mode);
5398 vim_free(wn);
5399 if (f >= 0)
5400 return f;
5401 /* Retry with non-wide function (for Windows 98). Can't use
5402 * GetLastError() here and it's unclear what errno gets set to if
5403 * the _wopen() fails for missing wide functions. */
5404 }
5405 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005406# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005407
5408 return open(name, flags, mode);
5409}
5410
5411/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005412 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413 */
5414 FILE *
5415mch_fopen(char *name, char *mode)
5416{
5417 WCHAR *wn, *wm;
5418 FILE *f = NULL;
5419
5420 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5421# ifdef __BORLANDC__
5422 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5423 && g_PlatformId == VER_PLATFORM_WIN32_NT
5424# endif
5425 )
5426 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005427# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005428 /* Work around an annoying assertion in the Microsoft debug CRT
5429 * when mode's text/binary setting doesn't match _get_fmode(). */
5430 char newMode = mode[strlen(mode) - 1];
5431 int oldMode = 0;
5432
5433 _get_fmode(&oldMode);
5434 if (newMode == 't')
5435 _set_fmode(_O_TEXT);
5436 else if (newMode == 'b')
5437 _set_fmode(_O_BINARY);
5438# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005439 wn = enc_to_utf16(name, NULL);
5440 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005441 if (wn != NULL && wm != NULL)
5442 f = _wfopen(wn, wm);
5443 vim_free(wn);
5444 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005445
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005446# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005447 _set_fmode(oldMode);
5448# endif
5449
Bram Moolenaar071d4272004-06-13 20:20:40 +00005450 if (f != NULL)
5451 return f;
5452 /* Retry with non-wide function (for Windows 98). Can't use
5453 * GetLastError() here and it's unclear what errno gets set to if
5454 * the _wfopen() fails for missing wide functions. */
5455 }
5456
5457 return fopen(name, mode);
5458}
5459#endif
5460
5461#ifdef FEAT_MBYTE
5462/*
5463 * SUB STREAM (aka info stream) handling:
5464 *
5465 * NTFS can have sub streams for each file. Normal contents of file is
5466 * stored in the main stream, and extra contents (author information and
5467 * title and so on) can be stored in sub stream. After Windows 2000, user
5468 * can access and store those informations in sub streams via explorer's
5469 * property menuitem in right click menu. Those informations in sub streams
5470 * were lost when copying only the main stream. So we have to copy sub
5471 * streams.
5472 *
5473 * Incomplete explanation:
5474 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5475 * More useful info and an example:
5476 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5477 */
5478
5479/*
5480 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5481 * and write to stream "substream" of file "to".
5482 * Errors are ignored.
5483 */
5484 static void
5485copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5486{
5487 HANDLE hTo;
5488 WCHAR *to_name;
5489
5490 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5491 wcscpy(to_name, to);
5492 wcscat(to_name, substream);
5493
5494 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5495 FILE_ATTRIBUTE_NORMAL, NULL);
5496 if (hTo != INVALID_HANDLE_VALUE)
5497 {
5498 long done;
5499 DWORD todo;
5500 DWORD readcnt, written;
5501 char buf[4096];
5502
5503 /* Copy block of bytes at a time. Abort when something goes wrong. */
5504 for (done = 0; done < len; done += written)
5505 {
5506 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005507 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5508 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005509 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5510 FALSE, FALSE, context)
5511 || readcnt != todo
5512 || !WriteFile(hTo, buf, todo, &written, NULL)
5513 || written != todo)
5514 break;
5515 }
5516 CloseHandle(hTo);
5517 }
5518
5519 free(to_name);
5520}
5521
5522/*
5523 * Copy info streams from file "from" to file "to".
5524 */
5525 static void
5526copy_infostreams(char_u *from, char_u *to)
5527{
5528 WCHAR *fromw;
5529 WCHAR *tow;
5530 HANDLE sh;
5531 WIN32_STREAM_ID sid;
5532 int headersize;
5533 WCHAR streamname[_MAX_PATH];
5534 DWORD readcount;
5535 void *context = NULL;
5536 DWORD lo, hi;
5537 int len;
5538
5539 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005540 fromw = enc_to_utf16(from, NULL);
5541 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542 if (fromw != NULL && tow != NULL)
5543 {
5544 /* Open the file for reading. */
5545 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
5546 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5547 if (sh != INVALID_HANDLE_VALUE)
5548 {
5549 /* Use BackupRead() to find the info streams. Repeat until we
5550 * have done them all.*/
5551 for (;;)
5552 {
5553 /* Get the header to find the length of the stream name. If
5554 * the "readcount" is zero we have done all info streams. */
5555 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005556 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005557 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
5558 &readcount, FALSE, FALSE, &context)
5559 || readcount == 0)
5560 break;
5561
5562 /* We only deal with streams that have a name. The normal
5563 * file data appears to be without a name, even though docs
5564 * suggest it is called "::$DATA". */
5565 if (sid.dwStreamNameSize > 0)
5566 {
5567 /* Read the stream name. */
5568 if (!BackupRead(sh, (LPBYTE)streamname,
5569 sid.dwStreamNameSize,
5570 &readcount, FALSE, FALSE, &context))
5571 break;
5572
5573 /* Copy an info stream with a name ":anything:$DATA".
5574 * Skip "::$DATA", it has no stream name (examples suggest
5575 * it might be used for the normal file contents).
5576 * Note that BackupRead() counts bytes, but the name is in
5577 * wide characters. */
5578 len = readcount / sizeof(WCHAR);
5579 streamname[len] = 0;
5580 if (len > 7 && wcsicmp(streamname + len - 6,
5581 L":$DATA") == 0)
5582 {
5583 streamname[len - 6] = 0;
5584 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00005585 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005586 }
5587 }
5588
5589 /* Advance to the next stream. We might try seeking too far,
5590 * but BackupSeek() doesn't skip over stream borders, thus
5591 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005592 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 &lo, &hi, &context);
5594 }
5595
5596 /* Clear the context. */
5597 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
5598
5599 CloseHandle(sh);
5600 }
5601 }
5602 vim_free(fromw);
5603 vim_free(tow);
5604}
5605#endif
5606
5607/*
5608 * Copy file attributes from file "from" to file "to".
5609 * For Windows NT and later we copy info streams.
5610 * Always returns zero, errors are ignored.
5611 */
5612 int
5613mch_copy_file_attribute(char_u *from, char_u *to)
5614{
5615#ifdef FEAT_MBYTE
5616 /* File streams only work on Windows NT and later. */
5617 PlatformId();
5618 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5619 copy_infostreams(from, to);
5620#endif
5621 return 0;
5622}
5623
5624#if defined(MYRESETSTKOFLW) || defined(PROTO)
5625/*
5626 * Recreate a destroyed stack guard page in win32.
5627 * Written by Benjamin Peterson.
5628 */
5629
5630/* These magic numbers are from the MS header files */
5631#define MIN_STACK_WIN9X 17
5632#define MIN_STACK_WINNT 2
5633
5634/*
5635 * This function does the same thing as _resetstkoflw(), which is only
5636 * available in DevStudio .net and later.
5637 * Returns 0 for failure, 1 for success.
5638 */
5639 int
5640myresetstkoflw(void)
5641{
5642 BYTE *pStackPtr;
5643 BYTE *pGuardPage;
5644 BYTE *pStackBase;
5645 BYTE *pLowestPossiblePage;
5646 MEMORY_BASIC_INFORMATION mbi;
5647 SYSTEM_INFO si;
5648 DWORD nPageSize;
5649 DWORD dummy;
5650
5651 /* This code will not work on win32s. */
5652 PlatformId();
5653 if (g_PlatformId == VER_PLATFORM_WIN32s)
5654 return 0;
5655
5656 /* We need to know the system page size. */
5657 GetSystemInfo(&si);
5658 nPageSize = si.dwPageSize;
5659
5660 /* ...and the current stack pointer */
5661 pStackPtr = (BYTE*)_alloca(1);
5662
5663 /* ...and the base of the stack. */
5664 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
5665 return 0;
5666 pStackBase = (BYTE*)mbi.AllocationBase;
5667
5668 /* ...and the page thats min_stack_req pages away from stack base; this is
5669 * the lowest page we could use. */
5670 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
5671 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
5672
5673 /* On Win95, we want the next page down from the end of the stack. */
5674 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
5675 {
5676 /* Find the page that's only 1 page down from the page that the stack
5677 * ptr is in. */
5678 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
5679 / (DWORD)nPageSize) - 1));
5680 if (pGuardPage < pLowestPossiblePage)
5681 return 0;
5682
5683 /* Apply the noaccess attribute to the page -- there's no guard
5684 * attribute in win95-type OSes. */
5685 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
5686 return 0;
5687 }
5688 else
5689 {
5690 /* On NT, however, we want the first committed page in the stack Start
5691 * at the stack base and move forward through memory until we find a
5692 * committed block. */
5693 BYTE *pBlock = pStackBase;
5694
Bram Moolenaara466c992005-07-09 21:03:22 +00005695 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005696 {
5697 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
5698 return 0;
5699
5700 pBlock += mbi.RegionSize;
5701
5702 if (mbi.State & MEM_COMMIT)
5703 break;
5704 }
5705
5706 /* mbi now describes the first committed block in the stack. */
5707 if (mbi.Protect & PAGE_GUARD)
5708 return 1;
5709
5710 /* decide where the guard page should start */
5711 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
5712 pGuardPage = pLowestPossiblePage;
5713 else
5714 pGuardPage = (BYTE*)mbi.BaseAddress;
5715
5716 /* allocate the guard page */
5717 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
5718 return 0;
5719
5720 /* apply the guard attribute to the page */
5721 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
5722 &dummy))
5723 return 0;
5724 }
5725
5726 return 1;
5727}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005728#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005729
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005730
5731#if defined(FEAT_MBYTE) || defined(PROTO)
5732/*
5733 * The command line arguments in UCS2
5734 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005735static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005736static LPWSTR *ArglistW = NULL;
5737static int global_argc = 0;
5738static char **global_argv;
5739
5740static int used_file_argc = 0; /* last argument in global_argv[] used
5741 for the argument list. */
5742static int *used_file_indexes = NULL; /* indexes in global_argv[] for
5743 command line arguments added to
5744 the argument list */
5745static int used_file_count = 0; /* nr of entries in used_file_indexes */
5746static int used_file_literal = FALSE; /* take file names literally */
5747static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005748static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005749static int used_alist_count = 0;
5750
5751
5752/*
5753 * Get the command line arguments. Unicode version.
5754 * Returns argc. Zero when something fails.
5755 */
5756 int
5757get_cmd_argsW(char ***argvp)
5758{
5759 char **argv = NULL;
5760 int argc = 0;
5761 int i;
5762
5763 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
5764 if (ArglistW != NULL)
5765 {
5766 argv = malloc((nArgsW + 1) * sizeof(char *));
5767 if (argv != NULL)
5768 {
5769 argc = nArgsW;
5770 argv[argc] = NULL;
5771 for (i = 0; i < argc; ++i)
5772 {
5773 int len;
5774
5775 /* Convert each Unicode argument to the current codepage. */
5776 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005777 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005778 (LPSTR *)&argv[i], &len, 0, 0);
5779 if (argv[i] == NULL)
5780 {
5781 /* Out of memory, clear everything. */
5782 while (i > 0)
5783 free(argv[--i]);
5784 free(argv);
5785 argc = 0;
5786 }
5787 }
5788 }
5789 }
5790
5791 global_argc = argc;
5792 global_argv = argv;
5793 if (argc > 0)
5794 used_file_indexes = malloc(argc * sizeof(int));
5795
5796 if (argvp != NULL)
5797 *argvp = argv;
5798 return argc;
5799}
5800
5801 void
5802free_cmd_argsW(void)
5803{
5804 if (ArglistW != NULL)
5805 {
5806 GlobalFree(ArglistW);
5807 ArglistW = NULL;
5808 }
5809}
5810
5811/*
5812 * Remember "name" is an argument that was added to the argument list.
5813 * This avoids that we have to re-parse the argument list when fix_arg_enc()
5814 * is called.
5815 */
5816 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005817used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005818{
5819 int i;
5820
5821 if (used_file_indexes == NULL)
5822 return;
5823 for (i = used_file_argc + 1; i < global_argc; ++i)
5824 if (STRCMP(global_argv[i], name) == 0)
5825 {
5826 used_file_argc = i;
5827 used_file_indexes[used_file_count++] = i;
5828 break;
5829 }
5830 used_file_literal = literal;
5831 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005832 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005833}
5834
5835/*
5836 * Remember the length of the argument list as it was. If it changes then we
5837 * leave it alone when 'encoding' is set.
5838 */
5839 void
5840set_alist_count(void)
5841{
5842 used_alist_count = GARGCOUNT;
5843}
5844
5845/*
5846 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5847 * has been changed while starting up. Use the UCS-2 command line arguments
5848 * and convert them to 'encoding'.
5849 */
5850 void
5851fix_arg_enc(void)
5852{
5853 int i;
5854 int idx;
5855 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005856 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005857
5858 /* Safety checks:
5859 * - if argument count differs between the wide and non-wide argument
5860 * list, something must be wrong.
5861 * - the file name arguments must have been located.
5862 * - the length of the argument list wasn't changed by the user.
5863 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005864 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005865 || ArglistW == NULL
5866 || used_file_indexes == NULL
5867 || used_file_count == 0
5868 || used_alist_count != GARGCOUNT)
5869 return;
5870
Bram Moolenaar86b68352004-12-27 21:59:20 +00005871 /* Remember the buffer numbers for the arguments. */
5872 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5873 if (fnum_list == NULL)
5874 return; /* out of memory */
5875 for (i = 0; i < GARGCOUNT; ++i)
5876 fnum_list[i] = GARGLIST[i].ae_fnum;
5877
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005878 /* Clear the argument list. Make room for the new arguments. */
5879 alist_clear(&global_alist);
5880 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005881 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005882
5883 for (i = 0; i < used_file_count; ++i)
5884 {
5885 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005886 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005887 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005888 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005889#ifdef FEAT_DIFF
5890 /* When using diff mode may need to concatenate file name to
5891 * directory name. Just like it's done in main(). */
5892 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
5893 && !mch_isdir(alist_name(&GARGLIST[0])))
5894 {
5895 char_u *r;
5896
5897 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
5898 if (r != NULL)
5899 {
5900 vim_free(str);
5901 str = r;
5902 }
5903 }
5904#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00005905 /* Re-use the old buffer by renaming it. When not using literal
5906 * names it's done by alist_expand() below. */
5907 if (used_file_literal)
5908 buf_set_name(fnum_list[i], str);
5909
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005910 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005911 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005912 }
5913
5914 if (!used_file_literal)
5915 {
5916 /* Now expand wildcards in the arguments. */
5917 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5918 * filename characters but are excluded from 'isfname' to make
5919 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5920 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005921 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005922 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5923 }
5924
5925 /* If wildcard expansion failed, we are editing the first file of the
5926 * arglist and there is no file name: Edit the first argument now. */
5927 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5928 {
5929 do_cmdline_cmd((char_u *)":rewind");
5930 if (GARGCOUNT == 1 && used_file_full_path)
5931 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5932 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005933
5934 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005935}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936#endif