blob: cd29b8738a131bb5dac877522cd164ddef5e5fa2 [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
53#ifdef __MINGW32__
54# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
55# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
56# endif
57# ifndef RIGHTMOST_BUTTON_PRESSED
58# define RIGHTMOST_BUTTON_PRESSED 0x0002
59# endif
60# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
61# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
62# endif
63# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
64# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
65# endif
66# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
67# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
68# endif
69
70/*
71 * EventFlags
72 */
73# ifndef MOUSE_MOVED
74# define MOUSE_MOVED 0x0001
75# endif
76# ifndef DOUBLE_CLICK
77# define DOUBLE_CLICK 0x0002
78# endif
79#endif
80
81/* Record all output and all keyboard & mouse input */
82/* #define MCH_WRITE_DUMP */
83
84#ifdef MCH_WRITE_DUMP
85FILE* fdDump = NULL;
86#endif
87
88/*
89 * When generating prototypes for Win32 on Unix, these lines make the syntax
90 * errors disappear. They do not need to be correct.
91 */
92#ifdef PROTO
93#define WINAPI
94#define WINBASEAPI
95typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000096typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000097typedef int ACCESS_MASK;
98typedef int BOOL;
99typedef int COLORREF;
100typedef int CONSOLE_CURSOR_INFO;
101typedef int COORD;
102typedef int DWORD;
103typedef int HANDLE;
104typedef int HDC;
105typedef int HFONT;
106typedef int HICON;
107typedef int HINSTANCE;
108typedef int HWND;
109typedef int INPUT_RECORD;
110typedef int KEY_EVENT_RECORD;
111typedef int LOGFONT;
112typedef int LPBOOL;
113typedef int LPCTSTR;
114typedef int LPDWORD;
115typedef int LPSTR;
116typedef int LPTSTR;
117typedef int LPVOID;
118typedef int MOUSE_EVENT_RECORD;
119typedef int PACL;
120typedef int PDWORD;
121typedef int PHANDLE;
122typedef int PRINTDLG;
123typedef int PSECURITY_DESCRIPTOR;
124typedef int PSID;
125typedef int SECURITY_INFORMATION;
126typedef int SHORT;
127typedef int SMALL_RECT;
128typedef int TEXTMETRIC;
129typedef int TOKEN_INFORMATION_CLASS;
130typedef int TRUSTEE;
131typedef int WORD;
132typedef int WCHAR;
133typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100134typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200135typedef int SE_OBJECT_TYPE;
136typedef int PSNSECINFO;
137typedef int PSNSECINFOW;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000138#endif
139
140#ifndef FEAT_GUI_W32
141/* Undocumented API in kernel32.dll needed to work around dead key bug in
142 * console-mode applications in NT 4.0. If you switch keyboard layouts
143 * in a console app to a layout that includes dead keys and then hit a
144 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
145 * and Michael Dietrich for helping me figure out this workaround.
146 */
147
148/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
149#ifndef WINBASEAPI
150# define WINBASEAPI __stdcall
151#endif
152#if defined(__BORLANDC__)
153typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
154#else
155typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
156#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000157static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158#endif
159
160#if defined(__BORLANDC__)
161/* Strangely Borland uses a non-standard name. */
162# define wcsicmp(a, b) wcscmpi((a), (b))
163#endif
164
Bram Moolenaar82881492012-11-20 16:53:39 +0100165#ifndef PROTO
166
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200167/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200168#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100169LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200170BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
171BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
172BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
173#endif
174
Bram Moolenaar82881492012-11-20 16:53:39 +0100175#endif /* PROTO */
176
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177#ifndef FEAT_GUI_W32
178/* Win32 Console handles for input and output */
179static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
180static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
181
182/* Win32 Screen buffer,coordinate,console I/O information */
183static SMALL_RECT g_srScrollRegion;
184static COORD g_coord; /* 0-based, but external coords are 1-based */
185
186/* The attribute of the screen when the editor was started */
187static WORD g_attrDefault = 7; /* lightgray text on black background */
188static WORD g_attrCurrent;
189
190static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
191static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
192static int g_fForceExit = FALSE; /* set when forcefully exiting */
193
194static void termcap_mode_start(void);
195static void termcap_mode_end(void);
196static void clear_chars(COORD coord, DWORD n);
197static void clear_screen(void);
198static void clear_to_end_of_display(void);
199static void clear_to_end_of_line(void);
200static void scroll(unsigned cLines);
201static void set_scroll_region(unsigned left, unsigned top,
202 unsigned right, unsigned bottom);
203static void insert_lines(unsigned cLines);
204static void delete_lines(unsigned cLines);
205static void gotoxy(unsigned x, unsigned y);
206static void normvideo(void);
207static void textattr(WORD wAttr);
208static void textcolor(WORD wAttr);
209static void textbackground(WORD wAttr);
210static void standout(void);
211static void standend(void);
212static void visual_bell(void);
213static void cursor_visible(BOOL fVisible);
214static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
215static char_u tgetch(int *pmodifiers, char_u *pch2);
216static void create_conin(void);
217static int s_cursor_visible = TRUE;
218static int did_create_conin = FALSE;
219#else
220static int s_dont_use_vimrun = TRUE;
221static int need_vimrun_warning = FALSE;
222static char *vimrun_path = "vimrun ";
223#endif
224
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200225static int win32_getattrs(char_u *name);
226static int win32_setattrs(char_u *name, int attrs);
227static int win32_set_archive(char_u *name);
228
Bram Moolenaar071d4272004-06-13 20:20:40 +0000229#ifndef FEAT_GUI_W32
230static int suppress_winsize = 1; /* don't fiddle with console */
231#endif
232
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200233static char_u *exe_path = NULL;
234
Bram Moolenaar071d4272004-06-13 20:20:40 +0000235 static void
236get_exe_name(void)
237{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100238 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
239 * as the maximum length that works (plus a NUL byte). */
240#define MAX_ENV_PATH_LEN 8192
241 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200242 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243
244 if (exe_name == NULL)
245 {
246 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100247 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000248 if (*temp != NUL)
249 exe_name = FullName_save((char_u *)temp, FALSE);
250 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000251
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200252 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000253 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200254 exe_path = vim_strnsave(exe_name,
255 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200256 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000257 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200258 /* Append our starting directory to $PATH, so that when doing
259 * "!xxd" it's found in our starting directory. Needed because
260 * SearchPath() also looks there. */
261 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100262 if (p == NULL
263 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200264 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100265 if (p == NULL || *p == NUL)
266 temp[0] = NUL;
267 else
268 {
269 STRCPY(temp, p);
270 STRCAT(temp, ";");
271 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200272 STRCAT(temp, exe_path);
273 vim_setenv((char_u *)"PATH", temp);
274 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000275 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000276 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000277}
278
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200279/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100280 * Unescape characters in "p" that appear in "escaped".
281 */
282 static void
283unescape_shellxquote(char_u *p, char_u *escaped)
284{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100285 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100286 int n;
287
288 while (*p != NUL)
289 {
290 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
291 mch_memmove(p, p + 1, l--);
292#ifdef FEAT_MBYTE
293 n = (*mb_ptr2len)(p);
294#else
295 n = 1;
296#endif
297 p += n;
298 l -= n;
299 }
300}
301
302/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200303 * Load library "name".
304 */
305 HINSTANCE
306vimLoadLib(char *name)
307{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200308 HINSTANCE dll = NULL;
309 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200310
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200311 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
312 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200313 if (exe_path == NULL)
314 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200315 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200316 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200317#ifdef FEAT_MBYTE
318 WCHAR old_dirw[MAXPATHL];
319
320 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
321 {
322 /* Change directory to where the executable is, both to make
323 * sure we find a .dll there and to avoid looking for a .dll
324 * in the current directory. */
325 SetCurrentDirectory(exe_path);
326 dll = LoadLibrary(name);
327 SetCurrentDirectoryW(old_dirw);
328 return dll;
329 }
330 /* Retry with non-wide function (for Windows 98). */
331 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
332#endif
333 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
334 {
335 /* Change directory to where the executable is, both to make
336 * sure we find a .dll there and to avoid looking for a .dll
337 * in the current directory. */
338 SetCurrentDirectory(exe_path);
339 dll = LoadLibrary(name);
340 SetCurrentDirectory(old_dir);
341 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200342 }
343 return dll;
344}
345
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
347# ifndef GETTEXT_DLL
348# define GETTEXT_DLL "libintl.dll"
349# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200350/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000351static char *null_libintl_gettext(const char *);
352static char *null_libintl_textdomain(const char *);
353static char *null_libintl_bindtextdomain(const char *, const char *);
354static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000355
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200356static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000357char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
358char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
359char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000360 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000361char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
362 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000363
364 int
365dyn_libintl_init(char *libname)
366{
367 int i;
368 static struct
369 {
370 char *name;
371 FARPROC *ptr;
372 } libintl_entry[] =
373 {
374 {"gettext", (FARPROC*)&dyn_libintl_gettext},
375 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
376 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
377 {NULL, NULL}
378 };
379
380 /* No need to initialize twice. */
381 if (hLibintlDLL)
382 return 1;
383 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200384 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000385 if (!hLibintlDLL)
386 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200387 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000388 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200389 verbose_enter();
390 EMSG2(_(e_loadlib), GETTEXT_DLL);
391 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200393 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394 }
395 for (i = 0; libintl_entry[i].name != NULL
396 && libintl_entry[i].ptr != NULL; ++i)
397 {
398 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
399 libintl_entry[i].name)) == NULL)
400 {
401 dyn_libintl_end();
402 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000403 {
404 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000405 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000406 verbose_leave();
407 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000408 return 0;
409 }
410 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000411
412 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000413 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000414 "bind_textdomain_codeset");
415 if (dyn_libintl_bind_textdomain_codeset == NULL)
416 dyn_libintl_bind_textdomain_codeset =
417 null_libintl_bind_textdomain_codeset;
418
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 return 1;
420}
421
422 void
423dyn_libintl_end()
424{
425 if (hLibintlDLL)
426 FreeLibrary(hLibintlDLL);
427 hLibintlDLL = NULL;
428 dyn_libintl_gettext = null_libintl_gettext;
429 dyn_libintl_textdomain = null_libintl_textdomain;
430 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000431 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000432}
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_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437{
438 return (char*)msgid;
439}
440
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000441/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000443null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444{
445 return NULL;
446}
447
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000448/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000450null_libintl_bind_textdomain_codeset(const char *domainname,
451 const char *codeset)
452{
453 return NULL;
454}
455
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000456/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000457 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000458null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459{
460 return NULL;
461}
462
463#endif /* DYNAMIC_GETTEXT */
464
465/* This symbol is not defined in older versions of the SDK or Visual C++ */
466
467#ifndef VER_PLATFORM_WIN32_WINDOWS
468# define VER_PLATFORM_WIN32_WINDOWS 1
469#endif
470
471DWORD g_PlatformId;
472
473#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100474# ifndef PROTO
475# include <aclapi.h>
476# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200477# ifndef PROTECTED_DACL_SECURITY_INFORMATION
478# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
479# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100480
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481/*
482 * These are needed to dynamically load the ADVAPI DLL, which is not
483 * implemented under Windows 95 (and causes VIM to crash)
484 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200485typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200487typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000488 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
489 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200490# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200491typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200492 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200493typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200494 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
495 PSECURITY_DESCRIPTOR *);
496# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000497
498static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
499static PSNSECINFO pSetNamedSecurityInfo;
500static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200501# ifdef FEAT_MBYTE
502static PSNSECINFOW pSetNamedSecurityInfoW;
503static PGNSECINFOW pGetNamedSecurityInfoW;
504# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505#endif
506
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200507typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
508
509static BOOL allowPiping = FALSE;
510static PSETHANDLEINFORMATION pSetHandleInformation;
511
Bram Moolenaar27515922013-06-29 15:36:26 +0200512#ifdef HAVE_ACL
513/*
514 * Enables or disables the specified privilege.
515 */
516 static BOOL
517win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
518{
519 BOOL bResult;
520 LUID luid;
521 HANDLE hToken;
522 TOKEN_PRIVILEGES tokenPrivileges;
523
524 if (!OpenProcessToken(GetCurrentProcess(),
525 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
526 return FALSE;
527
528 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
529 {
530 CloseHandle(hToken);
531 return FALSE;
532 }
533
534 tokenPrivileges.PrivilegeCount = 1;
535 tokenPrivileges.Privileges[0].Luid = luid;
536 tokenPrivileges.Privileges[0].Attributes = bEnable ?
537 SE_PRIVILEGE_ENABLED : 0;
538
539 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
540 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
541
542 CloseHandle(hToken);
543
544 return bResult && GetLastError() == ERROR_SUCCESS;
545}
546#endif
547
Bram Moolenaar071d4272004-06-13 20:20:40 +0000548/*
549 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
550 * VER_PLATFORM_WIN32_WINDOWS (Win95).
551 */
552 void
553PlatformId(void)
554{
555 static int done = FALSE;
556
557 if (!done)
558 {
559 OSVERSIONINFO ovi;
560
561 ovi.dwOSVersionInfoSize = sizeof(ovi);
562 GetVersionEx(&ovi);
563
564 g_PlatformId = ovi.dwPlatformId;
565
566#ifdef HAVE_ACL
567 /*
568 * Load the ADVAPI runtime if we are on anything
569 * other than Windows 95
570 */
571 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
572 {
573 /*
574 * do this load. Problems: Doesn't unload at end of run (this is
575 * theoretically okay, since Windows should unload it when VIM
576 * terminates). Should we be using the 'mch_libcall' routines?
577 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
578 * time we verify security...
579 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200580 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000581 if (advapi_lib != NULL)
582 {
583 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
584 "SetNamedSecurityInfoA");
585 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
586 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200587# ifdef FEAT_MBYTE
588 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
589 "SetNamedSecurityInfoW");
590 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
591 "GetNamedSecurityInfoW");
592# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000593 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200594 || pGetNamedSecurityInfo == NULL
595# ifdef FEAT_MBYTE
596 || pSetNamedSecurityInfoW == NULL
597 || pGetNamedSecurityInfoW == NULL
598# endif
599 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000600 {
601 /* If we can't get the function addresses, set advapi_lib
602 * to NULL so that we don't use them. */
603 FreeLibrary(advapi_lib);
604 advapi_lib = NULL;
605 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200606 /* Enable privilege for getting or setting SACLs. */
607 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608 }
609 }
610#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200611 /*
612 * If we are on windows NT, try to load the pipe functions, only
613 * available from Win2K.
614 */
615 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
616 {
617 HANDLE kernel32 = GetModuleHandle("kernel32");
618 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
619 kernel32, "SetHandleInformation");
620
621 allowPiping = pSetHandleInformation != NULL;
622 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623 done = TRUE;
624 }
625}
626
627/*
628 * Return TRUE when running on Windows 95 (or 98 or ME).
629 * Only to be used after mch_init().
630 */
631 int
632mch_windows95(void)
633{
634 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
635}
636
637#ifdef FEAT_GUI_W32
638/*
639 * Used to work around the "can't do synchronous spawn"
640 * problem on Win32s, without resorting to Universal Thunk.
641 */
642static int old_num_windows;
643static int num_windows;
644
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000645/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000646 static BOOL CALLBACK
647win32ssynch_cb(HWND hwnd, LPARAM lparam)
648{
649 num_windows++;
650 return TRUE;
651}
652#endif
653
654#ifndef FEAT_GUI_W32
655
656#define SHIFT (SHIFT_PRESSED)
657#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
658#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
659#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
660
661
662/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
663 * We map function keys to their ANSI terminal equivalents, as produced
664 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
665 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
666 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
667 * combinations of function/arrow/etc keys.
668 */
669
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000670static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671{
672 WORD wVirtKey;
673 BOOL fAnsiKey;
674 int chAlone;
675 int chShift;
676 int chCtrl;
677 int chAlt;
678} VirtKeyMap[] =
679{
680
681/* Key ANSI alone shift ctrl alt */
682 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
683
684 { VK_F1, TRUE, ';', 'T', '^', 'h', },
685 { VK_F2, TRUE, '<', 'U', '_', 'i', },
686 { VK_F3, TRUE, '=', 'V', '`', 'j', },
687 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
688 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
689 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
690 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
691 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
692 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
693 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
694 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
695 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
696
697 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
698 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
699 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
700 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
701 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
702 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
703 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
704 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
705 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
706 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
707
708 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
709
710#if 0
711 /* Most people don't have F13-F20, but what the hell... */
712 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
713 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
714 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
715 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
716 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
717 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
718 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
719 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
720#endif
721 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
722 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
723 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
724 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
725
726 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
727 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
728 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
729 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
730 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
731 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
732 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
733 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
734 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
735 /* Sorry, out of number space! <negri>*/
736 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
737
738};
739
740
741#ifdef _MSC_VER
742// The ToAscii bug destroys several registers. Need to turn off optimization
743// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000744# pragma warning(push)
745# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746# pragma optimize("", off)
747#endif
748
749#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
750# define AChar AsciiChar
751#else
752# define AChar uChar.AsciiChar
753#endif
754
755/* The return code indicates key code size. */
756 static int
757#ifdef __BORLANDC__
758 __stdcall
759#endif
760win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000761 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000762{
763 UINT uMods = pker->dwControlKeyState;
764 static int s_iIsDead = 0;
765 static WORD awAnsiCode[2];
766 static BYTE abKeystate[256];
767
768
769 if (s_iIsDead == 2)
770 {
771 pker->AChar = (CHAR) awAnsiCode[1];
772 s_iIsDead = 0;
773 return 1;
774 }
775
776 if (pker->AChar != 0)
777 return 1;
778
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200779 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000780
781 // Should only be non-NULL on NT 4.0
782 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
783 {
784 CHAR szKLID[KL_NAMELENGTH];
785
786 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
787 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
788 }
789
790 /* Clear any pending dead keys */
791 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
792
793 if (uMods & SHIFT_PRESSED)
794 abKeystate[VK_SHIFT] = 0x80;
795 if (uMods & CAPSLOCK_ON)
796 abKeystate[VK_CAPITAL] = 1;
797
798 if ((uMods & ALT_GR) == ALT_GR)
799 {
800 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
801 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
802 }
803
804 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
805 abKeystate, awAnsiCode, 0);
806
807 if (s_iIsDead > 0)
808 pker->AChar = (CHAR) awAnsiCode[0];
809
810 return s_iIsDead;
811}
812
813#ifdef _MSC_VER
814/* MUST switch optimization on again here, otherwise a call to
815 * decode_key_event() may crash (e.g. when hitting caps-lock) */
816# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000817# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818
819# if (_MSC_VER < 1100)
820/* MUST turn off global optimisation for this next function, or
821 * pressing ctrl-minus in insert mode crashes Vim when built with
822 * VC4.1. -- negri. */
823# pragma optimize("g", off)
824# endif
825#endif
826
827static BOOL g_fJustGotFocus = FALSE;
828
829/*
830 * Decode a KEY_EVENT into one or two keystrokes
831 */
832 static BOOL
833decode_key_event(
834 KEY_EVENT_RECORD *pker,
835 char_u *pch,
836 char_u *pch2,
837 int *pmodifiers,
838 BOOL fDoPost)
839{
840 int i;
841 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
842
843 *pch = *pch2 = NUL;
844 g_fJustGotFocus = FALSE;
845
846 /* ignore key up events */
847 if (!pker->bKeyDown)
848 return FALSE;
849
850 /* ignore some keystrokes */
851 switch (pker->wVirtualKeyCode)
852 {
853 /* modifiers */
854 case VK_SHIFT:
855 case VK_CONTROL:
856 case VK_MENU: /* Alt key */
857 return FALSE;
858
859 default:
860 break;
861 }
862
863 /* special cases */
864 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
865 {
866 /* Ctrl-6 is Ctrl-^ */
867 if (pker->wVirtualKeyCode == '6')
868 {
869 *pch = Ctrl_HAT;
870 return TRUE;
871 }
872 /* Ctrl-2 is Ctrl-@ */
873 else if (pker->wVirtualKeyCode == '2')
874 {
875 *pch = NUL;
876 return TRUE;
877 }
878 /* Ctrl-- is Ctrl-_ */
879 else if (pker->wVirtualKeyCode == 0xBD)
880 {
881 *pch = Ctrl__;
882 return TRUE;
883 }
884 }
885
886 /* Shift-TAB */
887 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
888 {
889 *pch = K_NUL;
890 *pch2 = '\017';
891 return TRUE;
892 }
893
894 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
895 {
896 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
897 {
898 if (nModifs == 0)
899 *pch = VirtKeyMap[i].chAlone;
900 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
901 *pch = VirtKeyMap[i].chShift;
902 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
903 *pch = VirtKeyMap[i].chCtrl;
904 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
905 *pch = VirtKeyMap[i].chAlt;
906
907 if (*pch != 0)
908 {
909 if (VirtKeyMap[i].fAnsiKey)
910 {
911 *pch2 = *pch;
912 *pch = K_NUL;
913 }
914
915 return TRUE;
916 }
917 }
918 }
919
920 i = win32_kbd_patch_key(pker);
921
922 if (i < 0)
923 *pch = NUL;
924 else
925 {
926 *pch = (i > 0) ? pker->AChar : NUL;
927
928 if (pmodifiers != NULL)
929 {
930 /* Pass on the ALT key as a modifier, but only when not combined
931 * with CTRL (which is ALTGR). */
932 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
933 *pmodifiers |= MOD_MASK_ALT;
934
935 /* Pass on SHIFT only for special keys, because we don't know when
936 * it's already included with the character. */
937 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
938 *pmodifiers |= MOD_MASK_SHIFT;
939
940 /* Pass on CTRL only for non-special keys, because we don't know
941 * when it's already included with the character. And not when
942 * combined with ALT (which is ALTGR). */
943 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
944 && *pch >= 0x20 && *pch < 0x80)
945 *pmodifiers |= MOD_MASK_CTRL;
946 }
947 }
948
949 return (*pch != NUL);
950}
951
952#ifdef _MSC_VER
953# pragma optimize("", on)
954#endif
955
956#endif /* FEAT_GUI_W32 */
957
958
959#ifdef FEAT_MOUSE
960
961/*
962 * For the GUI the mouse handling is in gui_w32.c.
963 */
964# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000965/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000967mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968{
969}
970# else
971static int g_fMouseAvail = FALSE; /* mouse present */
972static int g_fMouseActive = FALSE; /* mouse enabled */
973static int g_nMouseClick = -1; /* mouse status */
974static int g_xMouse; /* mouse x coordinate */
975static int g_yMouse; /* mouse y coordinate */
976
977/*
978 * Enable or disable mouse input
979 */
980 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000981mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000982{
983 DWORD cmodein;
984
985 if (!g_fMouseAvail)
986 return;
987
988 g_fMouseActive = on;
989 GetConsoleMode(g_hConIn, &cmodein);
990
991 if (g_fMouseActive)
992 cmodein |= ENABLE_MOUSE_INPUT;
993 else
994 cmodein &= ~ENABLE_MOUSE_INPUT;
995
996 SetConsoleMode(g_hConIn, cmodein);
997}
998
999
1000/*
1001 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1002 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1003 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1004 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1005 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1006 * and we return the mouse position in g_xMouse and g_yMouse.
1007 *
1008 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1009 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1010 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1011 *
1012 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1013 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1014 *
1015 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1016 * moves, even if it stays within the same character cell. We ignore
1017 * all MOUSE_MOVED messages if the position hasn't really changed, and
1018 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1019 * we're only interested in MOUSE_DRAG).
1020 *
1021 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1022 * 2-button mouses by pressing the left & right buttons simultaneously.
1023 * In practice, it's almost impossible to click both at the same time,
1024 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1025 * in such cases, if the user is clicking quickly.
1026 */
1027 static BOOL
1028decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001029 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030{
1031 static int s_nOldButton = -1;
1032 static int s_nOldMouseClick = -1;
1033 static int s_xOldMouse = -1;
1034 static int s_yOldMouse = -1;
1035 static linenr_T s_old_topline = 0;
1036#ifdef FEAT_DIFF
1037 static int s_old_topfill = 0;
1038#endif
1039 static int s_cClicks = 1;
1040 static BOOL s_fReleased = TRUE;
1041 static DWORD s_dwLastClickTime = 0;
1042 static BOOL s_fNextIsMiddle = FALSE;
1043
1044 static DWORD cButtons = 0; /* number of buttons supported */
1045
1046 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1047 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1048 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1049 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1050
1051 int nButton;
1052
1053 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1054 cButtons = 2;
1055
1056 if (!g_fMouseAvail || !g_fMouseActive)
1057 {
1058 g_nMouseClick = -1;
1059 return FALSE;
1060 }
1061
1062 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1063 if (g_fJustGotFocus)
1064 {
1065 g_fJustGotFocus = FALSE;
1066 return FALSE;
1067 }
1068
1069 /* unprocessed mouse click? */
1070 if (g_nMouseClick != -1)
1071 return TRUE;
1072
1073 nButton = -1;
1074 g_xMouse = pmer->dwMousePosition.X;
1075 g_yMouse = pmer->dwMousePosition.Y;
1076
1077 if (pmer->dwEventFlags == MOUSE_MOVED)
1078 {
1079 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1080 * events even when the mouse moves only within a char cell.) */
1081 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1082 return FALSE;
1083 }
1084
1085 /* If no buttons are pressed... */
1086 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1087 {
1088 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1089 if (s_fReleased)
1090 return FALSE;
1091
1092 nButton = MOUSE_RELEASE;
1093 s_fReleased = TRUE;
1094 }
1095 else /* one or more buttons pressed */
1096 {
1097 /* on a 2-button mouse, hold down left and right buttons
1098 * simultaneously to get MIDDLE. */
1099
1100 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1101 {
1102 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1103
1104 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001105 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001106 if (dwLR == LEFT || dwLR == RIGHT)
1107 {
1108 for (;;)
1109 {
1110 /* wait a short time for next input event */
1111 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1112 != WAIT_OBJECT_0)
1113 break;
1114 else
1115 {
1116 DWORD cRecords = 0;
1117 INPUT_RECORD ir;
1118 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1119
1120 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1121
1122 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1123 || !(pmer2->dwButtonState & LEFT_RIGHT))
1124 break;
1125 else
1126 {
1127 if (pmer2->dwEventFlags != MOUSE_MOVED)
1128 {
1129 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1130
1131 return decode_mouse_event(pmer2);
1132 }
1133 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1134 s_yOldMouse == pmer2->dwMousePosition.Y)
1135 {
1136 /* throw away spurious mouse move */
1137 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1138
1139 /* are there any more mouse events in queue? */
1140 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1141
1142 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1143 break;
1144 }
1145 else
1146 break;
1147 }
1148 }
1149 }
1150 }
1151 }
1152
1153 if (s_fNextIsMiddle)
1154 {
1155 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1156 ? MOUSE_DRAG : MOUSE_MIDDLE;
1157 s_fNextIsMiddle = FALSE;
1158 }
1159 else if (cButtons == 2 &&
1160 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1161 {
1162 nButton = MOUSE_MIDDLE;
1163
1164 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1165 {
1166 s_fNextIsMiddle = TRUE;
1167 nButton = MOUSE_RELEASE;
1168 }
1169 }
1170 else if ((pmer->dwButtonState & LEFT) == LEFT)
1171 nButton = MOUSE_LEFT;
1172 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1173 nButton = MOUSE_MIDDLE;
1174 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1175 nButton = MOUSE_RIGHT;
1176
1177 if (! s_fReleased && ! s_fNextIsMiddle
1178 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1179 return FALSE;
1180
1181 s_fReleased = s_fNextIsMiddle;
1182 }
1183
1184 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1185 {
1186 /* button pressed or released, without mouse moving */
1187 if (nButton != -1 && nButton != MOUSE_RELEASE)
1188 {
1189 DWORD dwCurrentTime = GetTickCount();
1190
1191 if (s_xOldMouse != g_xMouse
1192 || s_yOldMouse != g_yMouse
1193 || s_nOldButton != nButton
1194 || s_old_topline != curwin->w_topline
1195#ifdef FEAT_DIFF
1196 || s_old_topfill != curwin->w_topfill
1197#endif
1198 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1199 {
1200 s_cClicks = 1;
1201 }
1202 else if (++s_cClicks > 4)
1203 {
1204 s_cClicks = 1;
1205 }
1206
1207 s_dwLastClickTime = dwCurrentTime;
1208 }
1209 }
1210 else if (pmer->dwEventFlags == MOUSE_MOVED)
1211 {
1212 if (nButton != -1 && nButton != MOUSE_RELEASE)
1213 nButton = MOUSE_DRAG;
1214
1215 s_cClicks = 1;
1216 }
1217
1218 if (nButton == -1)
1219 return FALSE;
1220
1221 if (nButton != MOUSE_RELEASE)
1222 s_nOldButton = nButton;
1223
1224 g_nMouseClick = nButton;
1225
1226 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1227 g_nMouseClick |= MOUSE_SHIFT;
1228 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1229 g_nMouseClick |= MOUSE_CTRL;
1230 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1231 g_nMouseClick |= MOUSE_ALT;
1232
1233 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1234 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1235
1236 /* only pass on interesting (i.e., different) mouse events */
1237 if (s_xOldMouse == g_xMouse
1238 && s_yOldMouse == g_yMouse
1239 && s_nOldMouseClick == g_nMouseClick)
1240 {
1241 g_nMouseClick = -1;
1242 return FALSE;
1243 }
1244
1245 s_xOldMouse = g_xMouse;
1246 s_yOldMouse = g_yMouse;
1247 s_old_topline = curwin->w_topline;
1248#ifdef FEAT_DIFF
1249 s_old_topfill = curwin->w_topfill;
1250#endif
1251 s_nOldMouseClick = g_nMouseClick;
1252
1253 return TRUE;
1254}
1255
1256# endif /* FEAT_GUI_W32 */
1257#endif /* FEAT_MOUSE */
1258
1259
1260#ifdef MCH_CURSOR_SHAPE
1261/*
1262 * Set the shape of the cursor.
1263 * 'thickness' can be from 1 (thin) to 99 (block)
1264 */
1265 static void
1266mch_set_cursor_shape(int thickness)
1267{
1268 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1269 ConsoleCursorInfo.dwSize = thickness;
1270 ConsoleCursorInfo.bVisible = s_cursor_visible;
1271
1272 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1273 if (s_cursor_visible)
1274 SetConsoleCursorPosition(g_hConOut, g_coord);
1275}
1276
1277 void
1278mch_update_cursor(void)
1279{
1280 int idx;
1281 int thickness;
1282
1283 /*
1284 * How the cursor is drawn depends on the current mode.
1285 */
1286 idx = get_shape_idx(FALSE);
1287
1288 if (shape_table[idx].shape == SHAPE_BLOCK)
1289 thickness = 99; /* 100 doesn't work on W95 */
1290 else
1291 thickness = shape_table[idx].percentage;
1292 mch_set_cursor_shape(thickness);
1293}
1294#endif
1295
1296#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1297/*
1298 * Handle FOCUS_EVENT.
1299 */
1300 static void
1301handle_focus_event(INPUT_RECORD ir)
1302{
1303 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1304 ui_focus_change((int)g_fJustGotFocus);
1305}
1306
1307/*
1308 * Wait until console input from keyboard or mouse is available,
1309 * or the time is up.
1310 * Return TRUE if something is available FALSE if not.
1311 */
1312 static int
1313WaitForChar(long msec)
1314{
1315 DWORD dwNow = 0, dwEndTime = 0;
1316 INPUT_RECORD ir;
1317 DWORD cRecords;
1318 char_u ch, ch2;
1319
1320 if (msec > 0)
1321 /* Wait until the specified time has elapsed. */
1322 dwEndTime = GetTickCount() + msec;
1323 else if (msec < 0)
1324 /* Wait forever. */
1325 dwEndTime = INFINITE;
1326
1327 /* We need to loop until the end of the time period, because
1328 * we might get multiple unusable mouse events in that time.
1329 */
1330 for (;;)
1331 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001332#ifdef FEAT_MZSCHEME
1333 mzvim_check_threads();
1334#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335#ifdef FEAT_CLIENTSERVER
1336 serverProcessPendingMessages();
1337#endif
1338 if (0
1339#ifdef FEAT_MOUSE
1340 || g_nMouseClick != -1
1341#endif
1342#ifdef FEAT_CLIENTSERVER
1343 || input_available()
1344#endif
1345 )
1346 return TRUE;
1347
1348 if (msec > 0)
1349 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001350 /* If the specified wait time has passed, return. Beware that
1351 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001352 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001353 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001354 break;
1355 }
1356 if (msec != 0)
1357 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001358 DWORD dwWaitTime = dwEndTime - dwNow;
1359
1360#ifdef FEAT_MZSCHEME
1361 if (mzthreads_allowed() && p_mzq > 0
1362 && (msec < 0 || (long)dwWaitTime > p_mzq))
1363 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1364#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001365#ifdef FEAT_CLIENTSERVER
1366 /* Wait for either an event on the console input or a message in
1367 * the client-server window. */
1368 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001369 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001370#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001371 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372#endif
1373 continue;
1374 }
1375
1376 cRecords = 0;
1377 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1378
1379#ifdef FEAT_MBYTE_IME
1380 if (State & CMDLINE && msg_row == Rows - 1)
1381 {
1382 CONSOLE_SCREEN_BUFFER_INFO csbi;
1383
1384 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1385 {
1386 if (csbi.dwCursorPosition.Y != msg_row)
1387 {
1388 /* The screen is now messed up, must redraw the
1389 * command line and later all the windows. */
1390 redraw_all_later(CLEAR);
1391 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1392 redrawcmd();
1393 }
1394 }
1395 }
1396#endif
1397
1398 if (cRecords > 0)
1399 {
1400 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1401 {
1402#ifdef FEAT_MBYTE_IME
1403 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1404 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1405 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1406 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1407 {
1408 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1409 continue;
1410 }
1411#endif
1412 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1413 NULL, FALSE))
1414 return TRUE;
1415 }
1416
1417 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1418
1419 if (ir.EventType == FOCUS_EVENT)
1420 handle_focus_event(ir);
1421 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1422 shell_resized();
1423#ifdef FEAT_MOUSE
1424 else if (ir.EventType == MOUSE_EVENT
1425 && decode_mouse_event(&ir.Event.MouseEvent))
1426 return TRUE;
1427#endif
1428 }
1429 else if (msec == 0)
1430 break;
1431 }
1432
1433#ifdef FEAT_CLIENTSERVER
1434 /* Something might have been received while we were waiting. */
1435 if (input_available())
1436 return TRUE;
1437#endif
1438 return FALSE;
1439}
1440
1441#ifndef FEAT_GUI_MSWIN
1442/*
1443 * return non-zero if a character is available
1444 */
1445 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001446mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447{
1448 return WaitForChar(0L);
1449}
1450#endif
1451
1452/*
1453 * Create the console input. Used when reading stdin doesn't work.
1454 */
1455 static void
1456create_conin(void)
1457{
1458 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1459 FILE_SHARE_READ|FILE_SHARE_WRITE,
1460 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001461 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001462 did_create_conin = TRUE;
1463}
1464
1465/*
1466 * Get a keystroke or a mouse event
1467 */
1468 static char_u
1469tgetch(int *pmodifiers, char_u *pch2)
1470{
1471 char_u ch;
1472
1473 for (;;)
1474 {
1475 INPUT_RECORD ir;
1476 DWORD cRecords = 0;
1477
1478#ifdef FEAT_CLIENTSERVER
1479 (void)WaitForChar(-1L);
1480 if (input_available())
1481 return 0;
1482# ifdef FEAT_MOUSE
1483 if (g_nMouseClick != -1)
1484 return 0;
1485# endif
1486#endif
1487 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1488 {
1489 if (did_create_conin)
1490 read_error_exit();
1491 create_conin();
1492 continue;
1493 }
1494
1495 if (ir.EventType == KEY_EVENT)
1496 {
1497 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1498 pmodifiers, TRUE))
1499 return ch;
1500 }
1501 else if (ir.EventType == FOCUS_EVENT)
1502 handle_focus_event(ir);
1503 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1504 shell_resized();
1505#ifdef FEAT_MOUSE
1506 else if (ir.EventType == MOUSE_EVENT)
1507 {
1508 if (decode_mouse_event(&ir.Event.MouseEvent))
1509 return 0;
1510 }
1511#endif
1512 }
1513}
1514#endif /* !FEAT_GUI_W32 */
1515
1516
1517/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001518 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001519 * Get one or more characters from the keyboard or the mouse.
1520 * If time == 0, do not wait for characters.
1521 * If time == n, wait a short time for characters.
1522 * If time == -1, wait forever for characters.
1523 * Returns the number of characters read into buf.
1524 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001525/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526 int
1527mch_inchar(
1528 char_u *buf,
1529 int maxlen,
1530 long time,
1531 int tb_change_cnt)
1532{
1533#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1534
1535 int len;
1536 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001537#define TYPEAHEADLEN 20
1538 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1539 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001540#ifdef FEAT_MBYTE
1541 static char_u *rest = NULL; /* unconverted rest of previous read */
1542 static int restlen = 0;
1543 int unconverted;
1544#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545
1546 /* First use any typeahead that was kept because "buf" was too small. */
1547 if (typeaheadlen > 0)
1548 goto theend;
1549
1550#ifdef FEAT_SNIFF
1551 if (want_sniff_request)
1552 {
1553 if (sniff_request_waiting)
1554 {
1555 /* return K_SNIFF */
1556 typeahead[typeaheadlen++] = CSI;
1557 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1558 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1559 sniff_request_waiting = 0;
1560 want_sniff_request = 0;
1561 goto theend;
1562 }
1563 else if (time < 0 || time > 250)
1564 {
1565 /* don't wait too long, a request might be pending */
1566 time = 250;
1567 }
1568 }
1569#endif
1570
1571 if (time >= 0)
1572 {
1573 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001574 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001575 }
1576 else /* time == -1, wait forever */
1577 {
1578 mch_set_winsize_now(); /* Allow winsize changes from now on */
1579
Bram Moolenaar3918c952005-03-15 22:34:55 +00001580 /*
1581 * If there is no character available within 2 seconds (default)
1582 * write the autoscript file to disk. Or cause the CursorHold event
1583 * to be triggered.
1584 */
1585 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586 {
1587#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001588 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001589 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001590 buf[0] = K_SPECIAL;
1591 buf[1] = KS_EXTRA;
1592 buf[2] = (int)KE_CURSORHOLD;
1593 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 }
1595#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001596 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001597 }
1598 }
1599
1600 /*
1601 * Try to read as many characters as there are, until the buffer is full.
1602 */
1603
1604 /* we will get at least one key. Get more if they are available. */
1605 g_fCBrkPressed = FALSE;
1606
1607#ifdef MCH_WRITE_DUMP
1608 if (fdDump)
1609 fputc('[', fdDump);
1610#endif
1611
1612 /* Keep looping until there is something in the typeahead buffer and more
1613 * to get and still room in the buffer (up to two bytes for a char and
1614 * three bytes for a modifier). */
1615 while ((typeaheadlen == 0 || WaitForChar(0L))
1616 && typeaheadlen + 5 <= TYPEAHEADLEN)
1617 {
1618 if (typebuf_changed(tb_change_cnt))
1619 {
1620 /* "buf" may be invalid now if a client put something in the
1621 * typeahead buffer and "buf" is in the typeahead buffer. */
1622 typeaheadlen = 0;
1623 break;
1624 }
1625#ifdef FEAT_MOUSE
1626 if (g_nMouseClick != -1)
1627 {
1628# ifdef MCH_WRITE_DUMP
1629 if (fdDump)
1630 fprintf(fdDump, "{%02x @ %d, %d}",
1631 g_nMouseClick, g_xMouse, g_yMouse);
1632# endif
1633 typeahead[typeaheadlen++] = ESC + 128;
1634 typeahead[typeaheadlen++] = 'M';
1635 typeahead[typeaheadlen++] = g_nMouseClick;
1636 typeahead[typeaheadlen++] = g_xMouse + '!';
1637 typeahead[typeaheadlen++] = g_yMouse + '!';
1638 g_nMouseClick = -1;
1639 }
1640 else
1641#endif
1642 {
1643 char_u ch2 = NUL;
1644 int modifiers = 0;
1645
1646 c = tgetch(&modifiers, &ch2);
1647
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001648#ifdef FEAT_MBYTE
1649 /* stolen from fill_input_buf() in ui.c */
1650 if (rest != NULL)
1651 {
1652 /* Use remainder of previous call, starts with an invalid
1653 * character that may become valid when reading more. */
1654 if (restlen > TYPEAHEADLEN - typeaheadlen)
1655 unconverted = TYPEAHEADLEN - typeaheadlen;
1656 else
1657 unconverted = restlen;
1658 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1659 if (unconverted == restlen)
1660 {
1661 vim_free(rest);
1662 rest = NULL;
1663 }
1664 else
1665 {
1666 restlen -= unconverted;
1667 mch_memmove(rest, rest + unconverted, restlen);
1668 }
1669 typeaheadlen += unconverted;
1670 }
1671 else
1672 unconverted = 0;
1673#endif
1674
Bram Moolenaar071d4272004-06-13 20:20:40 +00001675 if (typebuf_changed(tb_change_cnt))
1676 {
1677 /* "buf" may be invalid now if a client put something in the
1678 * typeahead buffer and "buf" is in the typeahead buffer. */
1679 typeaheadlen = 0;
1680 break;
1681 }
1682
1683 if (c == Ctrl_C && ctrl_c_interrupts)
1684 {
1685#if defined(FEAT_CLIENTSERVER)
1686 trash_input_buf();
1687#endif
1688 got_int = TRUE;
1689 }
1690
1691#ifdef FEAT_MOUSE
1692 if (g_nMouseClick == -1)
1693#endif
1694 {
1695 int n = 1;
1696
1697 /* A key may have one or two bytes. */
1698 typeahead[typeaheadlen] = c;
1699 if (ch2 != NUL)
1700 {
1701 typeahead[typeaheadlen + 1] = ch2;
1702 ++n;
1703 }
1704#ifdef FEAT_MBYTE
1705 /* Only convert normal characters, not special keys. Need to
1706 * convert before applying ALT, otherwise mapping <M-x> breaks
1707 * when 'tenc' is set. */
1708 if (input_conv.vc_type != CONV_NONE
1709 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001710 {
1711 typeaheadlen -= unconverted;
1712 n = convert_input_safe(typeahead + typeaheadlen,
1713 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1714 rest == NULL ? &rest : NULL, &restlen);
1715 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001716#endif
1717
1718 /* Use the ALT key to set the 8th bit of the character
1719 * when it's one byte, the 8th bit isn't set yet and not
1720 * using a double-byte encoding (would become a lead
1721 * byte). */
1722 if ((modifiers & MOD_MASK_ALT)
1723 && n == 1
1724 && (typeahead[typeaheadlen] & 0x80) == 0
1725#ifdef FEAT_MBYTE
1726 && !enc_dbcs
1727#endif
1728 )
1729 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001730#ifdef FEAT_MBYTE
1731 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1732 typeahead + typeaheadlen);
1733#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001735#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001736 modifiers &= ~MOD_MASK_ALT;
1737 }
1738
1739 if (modifiers != 0)
1740 {
1741 /* Prepend modifiers to the character. */
1742 mch_memmove(typeahead + typeaheadlen + 3,
1743 typeahead + typeaheadlen, n);
1744 typeahead[typeaheadlen++] = K_SPECIAL;
1745 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1746 typeahead[typeaheadlen++] = modifiers;
1747 }
1748
1749 typeaheadlen += n;
1750
1751#ifdef MCH_WRITE_DUMP
1752 if (fdDump)
1753 fputc(c, fdDump);
1754#endif
1755 }
1756 }
1757 }
1758
1759#ifdef MCH_WRITE_DUMP
1760 if (fdDump)
1761 {
1762 fputs("]\n", fdDump);
1763 fflush(fdDump);
1764 }
1765#endif
1766
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767theend:
1768 /* Move typeahead to "buf", as much as fits. */
1769 len = 0;
1770 while (len < maxlen && typeaheadlen > 0)
1771 {
1772 buf[len++] = typeahead[0];
1773 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1774 }
1775 return len;
1776
1777#else /* FEAT_GUI_W32 */
1778 return 0;
1779#endif /* FEAT_GUI_W32 */
1780}
1781
Bram Moolenaar82881492012-11-20 16:53:39 +01001782#ifndef PROTO
1783# ifndef __MINGW32__
1784# include <shellapi.h> /* required for FindExecutable() */
1785# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001786#endif
1787
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001788/*
1789 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001790 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001791 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792 static int
1793executable_exists(char *name)
1794{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001795 char *dum;
1796 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001798#ifdef FEAT_MBYTE
1799 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001801 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001802 WCHAR fnamew[_MAX_PATH];
1803 WCHAR *dumw;
1804 long n;
1805
1806 if (p != NULL)
1807 {
1808 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1809 vim_free(p);
1810 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1811 {
1812 if (n == 0)
1813 return FALSE;
1814 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1815 return FALSE;
1816 return TRUE;
1817 }
1818 /* Retry with non-wide function (for Windows 98). */
1819 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001820 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001821#endif
1822 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1823 return FALSE;
1824 if (mch_isdir(fname))
1825 return FALSE;
1826 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001827}
1828
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001829#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001830 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001831/*
1832 * Bad parameter handler.
1833 *
1834 * Certain MS CRT functions will intentionally crash when passed invalid
1835 * parameters to highlight possible security holes. Setting this function as
1836 * the bad parameter handler will prevent the crash.
1837 *
1838 * In debug builds the parameters contain CRT information that might help track
1839 * down the source of a problem, but in non-debug builds the arguments are all
1840 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1841 * worth allowing these to make debugging of issues easier.
1842 */
1843 static void
1844bad_param_handler(const wchar_t *expression,
1845 const wchar_t *function,
1846 const wchar_t *file,
1847 unsigned int line,
1848 uintptr_t pReserved)
1849{
1850}
1851
1852# define SET_INVALID_PARAM_HANDLER \
1853 ((void)_set_invalid_parameter_handler(bad_param_handler))
1854#else
1855# define SET_INVALID_PARAM_HANDLER
1856#endif
1857
Bram Moolenaar071d4272004-06-13 20:20:40 +00001858#ifdef FEAT_GUI_W32
1859
1860/*
1861 * GUI version of mch_init().
1862 */
1863 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001864mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865{
1866#ifndef __MINGW32__
1867 extern int _fmode;
1868#endif
1869
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001870 /* Silently handle invalid parameters to CRT functions */
1871 SET_INVALID_PARAM_HANDLER;
1872
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873 /* Let critical errors result in a failure, not in a dialog box. Required
1874 * for the timestamp test to work on removed floppies. */
1875 SetErrorMode(SEM_FAILCRITICALERRORS);
1876
1877 _fmode = O_BINARY; /* we do our own CR-LF translation */
1878
1879 /* Specify window size. Is there a place to get the default from? */
1880 Rows = 25;
1881 Columns = 80;
1882
1883 /* Look for 'vimrun' */
1884 if (!gui_is_win32s())
1885 {
1886 char_u vimrun_location[_MAX_PATH + 4];
1887
1888 /* First try in same directory as gvim.exe */
1889 STRCPY(vimrun_location, exe_name);
1890 STRCPY(gettail(vimrun_location), "vimrun.exe");
1891 if (mch_getperm(vimrun_location) >= 0)
1892 {
1893 if (*skiptowhite(vimrun_location) != NUL)
1894 {
1895 /* Enclose path with white space in double quotes. */
1896 mch_memmove(vimrun_location + 1, vimrun_location,
1897 STRLEN(vimrun_location) + 1);
1898 *vimrun_location = '"';
1899 STRCPY(gettail(vimrun_location), "vimrun\" ");
1900 }
1901 else
1902 STRCPY(gettail(vimrun_location), "vimrun ");
1903
1904 vimrun_path = (char *)vim_strsave(vimrun_location);
1905 s_dont_use_vimrun = FALSE;
1906 }
1907 else if (executable_exists("vimrun.exe"))
1908 s_dont_use_vimrun = FALSE;
1909
1910 /* Don't give the warning for a missing vimrun.exe right now, but only
1911 * when vimrun was supposed to be used. Don't bother people that do
1912 * not need vimrun.exe. */
1913 if (s_dont_use_vimrun)
1914 need_vimrun_warning = TRUE;
1915 }
1916
1917 /*
1918 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1919 * Otherwise the default "findstr /n" is used.
1920 */
1921 if (!executable_exists("findstr.exe"))
1922 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1923
1924#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001925 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001926#endif
1927}
1928
1929
1930#else /* FEAT_GUI_W32 */
1931
1932#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1933#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1934
1935/*
1936 * ClearConsoleBuffer()
1937 * Description:
1938 * Clears the entire contents of the console screen buffer, using the
1939 * specified attribute.
1940 * Returns:
1941 * TRUE on success
1942 */
1943 static BOOL
1944ClearConsoleBuffer(WORD wAttribute)
1945{
1946 CONSOLE_SCREEN_BUFFER_INFO csbi;
1947 COORD coord;
1948 DWORD NumCells, dummy;
1949
1950 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1951 return FALSE;
1952
1953 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1954 coord.X = 0;
1955 coord.Y = 0;
1956 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1957 coord, &dummy))
1958 {
1959 return FALSE;
1960 }
1961 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1962 coord, &dummy))
1963 {
1964 return FALSE;
1965 }
1966
1967 return TRUE;
1968}
1969
1970/*
1971 * FitConsoleWindow()
1972 * Description:
1973 * Checks if the console window will fit within given buffer dimensions.
1974 * Also, if requested, will shrink the window to fit.
1975 * Returns:
1976 * TRUE on success
1977 */
1978 static BOOL
1979FitConsoleWindow(
1980 COORD dwBufferSize,
1981 BOOL WantAdjust)
1982{
1983 CONSOLE_SCREEN_BUFFER_INFO csbi;
1984 COORD dwWindowSize;
1985 BOOL NeedAdjust = FALSE;
1986
1987 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1988 {
1989 /*
1990 * A buffer resize will fail if the current console window does
1991 * not lie completely within that buffer. To avoid this, we might
1992 * have to move and possibly shrink the window.
1993 */
1994 if (csbi.srWindow.Right >= dwBufferSize.X)
1995 {
1996 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1997 if (dwWindowSize.X > dwBufferSize.X)
1998 dwWindowSize.X = dwBufferSize.X;
1999 csbi.srWindow.Right = dwBufferSize.X - 1;
2000 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2001 NeedAdjust = TRUE;
2002 }
2003 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2004 {
2005 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2006 if (dwWindowSize.Y > dwBufferSize.Y)
2007 dwWindowSize.Y = dwBufferSize.Y;
2008 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2009 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2010 NeedAdjust = TRUE;
2011 }
2012 if (NeedAdjust && WantAdjust)
2013 {
2014 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2015 return FALSE;
2016 }
2017 return TRUE;
2018 }
2019
2020 return FALSE;
2021}
2022
2023typedef struct ConsoleBufferStruct
2024{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002025 BOOL IsValid;
2026 CONSOLE_SCREEN_BUFFER_INFO Info;
2027 PCHAR_INFO Buffer;
2028 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029} ConsoleBuffer;
2030
2031/*
2032 * SaveConsoleBuffer()
2033 * Description:
2034 * Saves important information about the console buffer, including the
2035 * actual buffer contents. The saved information is suitable for later
2036 * restoration by RestoreConsoleBuffer().
2037 * Returns:
2038 * TRUE if all information was saved; FALSE otherwise
2039 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2040 */
2041 static BOOL
2042SaveConsoleBuffer(
2043 ConsoleBuffer *cb)
2044{
2045 DWORD NumCells;
2046 COORD BufferCoord;
2047 SMALL_RECT ReadRegion;
2048 WORD Y, Y_incr;
2049
2050 if (cb == NULL)
2051 return FALSE;
2052
2053 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2054 {
2055 cb->IsValid = FALSE;
2056 return FALSE;
2057 }
2058 cb->IsValid = TRUE;
2059
2060 /*
2061 * Allocate a buffer large enough to hold the entire console screen
2062 * buffer. If this ConsoleBuffer structure has already been initialized
2063 * with a buffer of the correct size, then just use that one.
2064 */
2065 if (!cb->IsValid || cb->Buffer == NULL ||
2066 cb->BufferSize.X != cb->Info.dwSize.X ||
2067 cb->BufferSize.Y != cb->Info.dwSize.Y)
2068 {
2069 cb->BufferSize.X = cb->Info.dwSize.X;
2070 cb->BufferSize.Y = cb->Info.dwSize.Y;
2071 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002072 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2074 if (cb->Buffer == NULL)
2075 return FALSE;
2076 }
2077
2078 /*
2079 * We will now copy the console screen buffer into our buffer.
2080 * ReadConsoleOutput() seems to be limited as far as how much you
2081 * can read at a time. Empirically, this number seems to be about
2082 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2083 * in chunks until it is all copied. The chunks will all have the
2084 * same horizontal characteristics, so initialize them now. The
2085 * height of each chunk will be (12000 / width).
2086 */
2087 BufferCoord.X = 0;
2088 ReadRegion.Left = 0;
2089 ReadRegion.Right = cb->Info.dwSize.X - 1;
2090 Y_incr = 12000 / cb->Info.dwSize.X;
2091 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2092 {
2093 /*
2094 * Read into position (0, Y) in our buffer.
2095 */
2096 BufferCoord.Y = Y;
2097 /*
2098 * Read the region whose top left corner is (0, Y) and whose bottom
2099 * right corner is (width - 1, Y + Y_incr - 1). This should define
2100 * a region of size width by Y_incr. Don't worry if this region is
2101 * too large for the remaining buffer; it will be cropped.
2102 */
2103 ReadRegion.Top = Y;
2104 ReadRegion.Bottom = Y + Y_incr - 1;
2105 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2106 cb->Buffer, /* our buffer */
2107 cb->BufferSize, /* dimensions of our buffer */
2108 BufferCoord, /* offset in our buffer */
2109 &ReadRegion)) /* region to save */
2110 {
2111 vim_free(cb->Buffer);
2112 cb->Buffer = NULL;
2113 return FALSE;
2114 }
2115 }
2116
2117 return TRUE;
2118}
2119
2120/*
2121 * RestoreConsoleBuffer()
2122 * Description:
2123 * Restores important information about the console buffer, including the
2124 * actual buffer contents, if desired. The information to restore is in
2125 * the same format used by SaveConsoleBuffer().
2126 * Returns:
2127 * TRUE on success
2128 */
2129 static BOOL
2130RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002131 ConsoleBuffer *cb,
2132 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002133{
2134 COORD BufferCoord;
2135 SMALL_RECT WriteRegion;
2136
2137 if (cb == NULL || !cb->IsValid)
2138 return FALSE;
2139
2140 /*
2141 * Before restoring the buffer contents, clear the current buffer, and
2142 * restore the cursor position and window information. Doing this now
2143 * prevents old buffer contents from "flashing" onto the screen.
2144 */
2145 if (RestoreScreen)
2146 ClearConsoleBuffer(cb->Info.wAttributes);
2147
2148 FitConsoleWindow(cb->Info.dwSize, TRUE);
2149 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2150 return FALSE;
2151 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2152 return FALSE;
2153
2154 if (!RestoreScreen)
2155 {
2156 /*
2157 * No need to restore the screen buffer contents, so we're done.
2158 */
2159 return TRUE;
2160 }
2161
2162 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2163 return FALSE;
2164 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2165 return FALSE;
2166
2167 /*
2168 * Restore the screen buffer contents.
2169 */
2170 if (cb->Buffer != NULL)
2171 {
2172 BufferCoord.X = 0;
2173 BufferCoord.Y = 0;
2174 WriteRegion.Left = 0;
2175 WriteRegion.Top = 0;
2176 WriteRegion.Right = cb->Info.dwSize.X - 1;
2177 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2178 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2179 cb->Buffer, /* our buffer */
2180 cb->BufferSize, /* dimensions of our buffer */
2181 BufferCoord, /* offset in our buffer */
2182 &WriteRegion)) /* region to restore */
2183 {
2184 return FALSE;
2185 }
2186 }
2187
2188 return TRUE;
2189}
2190
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002191#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002192#ifdef FEAT_RESTORE_ORIG_SCREEN
2193static ConsoleBuffer g_cbOrig = { 0 };
2194#endif
2195static ConsoleBuffer g_cbNonTermcap = { 0 };
2196static ConsoleBuffer g_cbTermcap = { 0 };
2197
2198#ifdef FEAT_TITLE
2199#ifdef __BORLANDC__
2200typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2201#else
2202typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2203#endif
2204char g_szOrigTitle[256] = { 0 };
2205HWND g_hWnd = NULL; /* also used in os_mswin.c */
2206static HICON g_hOrigIconSmall = NULL;
2207static HICON g_hOrigIcon = NULL;
2208static HICON g_hVimIcon = NULL;
2209static BOOL g_fCanChangeIcon = FALSE;
2210
2211/* ICON* are not defined in VC++ 4.0 */
2212#ifndef ICON_SMALL
2213#define ICON_SMALL 0
2214#endif
2215#ifndef ICON_BIG
2216#define ICON_BIG 1
2217#endif
2218/*
2219 * GetConsoleIcon()
2220 * Description:
2221 * Attempts to retrieve the small icon and/or the big icon currently in
2222 * use by a given window.
2223 * Returns:
2224 * TRUE on success
2225 */
2226 static BOOL
2227GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002228 HWND hWnd,
2229 HICON *phIconSmall,
2230 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002231{
2232 if (hWnd == NULL)
2233 return FALSE;
2234
2235 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002236 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2237 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002238 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002239 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2240 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002241 return TRUE;
2242}
2243
2244/*
2245 * SetConsoleIcon()
2246 * Description:
2247 * Attempts to change the small icon and/or the big icon currently in
2248 * use by a given window.
2249 * Returns:
2250 * TRUE on success
2251 */
2252 static BOOL
2253SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002254 HWND hWnd,
2255 HICON hIconSmall,
2256 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002258 HICON hPrevIconSmall;
2259 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002260
2261 if (hWnd == NULL)
2262 return FALSE;
2263
2264 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002265 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2266 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002267 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002268 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2269 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270 return TRUE;
2271}
2272
2273/*
2274 * SaveConsoleTitleAndIcon()
2275 * Description:
2276 * Saves the current console window title in g_szOrigTitle, for later
2277 * restoration. Also, attempts to obtain a handle to the console window,
2278 * and use it to save the small and big icons currently in use by the
2279 * console window. This is not always possible on some versions of Windows;
2280 * nor is it possible when running Vim remotely using Telnet (since the
2281 * console window the user sees is owned by a remote process).
2282 */
2283 static void
2284SaveConsoleTitleAndIcon(void)
2285{
2286 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2287
2288 /* Save the original title. */
2289 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2290 return;
2291
2292 /*
2293 * Obtain a handle to the console window using GetConsoleWindow() from
2294 * KERNEL32.DLL; we need to handle in order to change the window icon.
2295 * This function only exists on NT-based Windows, starting with Windows
2296 * 2000. On older operating systems, we can't change the window icon
2297 * anyway.
2298 */
2299 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2300 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2301 "GetConsoleWindow")) != NULL)
2302 {
2303 g_hWnd = (*GetConsoleWindowProc)();
2304 }
2305 if (g_hWnd == NULL)
2306 return;
2307
2308 /* Save the original console window icon. */
2309 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2310 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2311 return;
2312
2313 /* Extract the first icon contained in the Vim executable. */
2314 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2315 if (g_hVimIcon != NULL)
2316 g_fCanChangeIcon = TRUE;
2317}
2318#endif
2319
2320static int g_fWindInitCalled = FALSE;
2321static int g_fTermcapMode = FALSE;
2322static CONSOLE_CURSOR_INFO g_cci;
2323static DWORD g_cmodein = 0;
2324static DWORD g_cmodeout = 0;
2325
2326/*
2327 * non-GUI version of mch_init().
2328 */
2329 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002330mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331{
2332#ifndef FEAT_RESTORE_ORIG_SCREEN
2333 CONSOLE_SCREEN_BUFFER_INFO csbi;
2334#endif
2335#ifndef __MINGW32__
2336 extern int _fmode;
2337#endif
2338
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002339 /* Silently handle invalid parameters to CRT functions */
2340 SET_INVALID_PARAM_HANDLER;
2341
Bram Moolenaar071d4272004-06-13 20:20:40 +00002342 /* Let critical errors result in a failure, not in a dialog box. Required
2343 * for the timestamp test to work on removed floppies. */
2344 SetErrorMode(SEM_FAILCRITICALERRORS);
2345
2346 _fmode = O_BINARY; /* we do our own CR-LF translation */
2347 out_flush();
2348
2349 /* Obtain handles for the standard Console I/O devices */
2350 if (read_cmd_fd == 0)
2351 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2352 else
2353 create_conin();
2354 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2355
2356#ifdef FEAT_RESTORE_ORIG_SCREEN
2357 /* Save the initial console buffer for later restoration */
2358 SaveConsoleBuffer(&g_cbOrig);
2359 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2360#else
2361 /* Get current text attributes */
2362 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2363 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2364#endif
2365 if (cterm_normal_fg_color == 0)
2366 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2367 if (cterm_normal_bg_color == 0)
2368 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2369
2370 /* set termcap codes to current text attributes */
2371 update_tcap(g_attrCurrent);
2372
2373 GetConsoleCursorInfo(g_hConOut, &g_cci);
2374 GetConsoleMode(g_hConIn, &g_cmodein);
2375 GetConsoleMode(g_hConOut, &g_cmodeout);
2376
2377#ifdef FEAT_TITLE
2378 SaveConsoleTitleAndIcon();
2379 /*
2380 * Set both the small and big icons of the console window to Vim's icon.
2381 * Note that Vim presently only has one size of icon (32x32), but it
2382 * automatically gets scaled down to 16x16 when setting the small icon.
2383 */
2384 if (g_fCanChangeIcon)
2385 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2386#endif
2387
2388 ui_get_shellsize();
2389
2390#ifdef MCH_WRITE_DUMP
2391 fdDump = fopen("dump", "wt");
2392
2393 if (fdDump)
2394 {
2395 time_t t;
2396
2397 time(&t);
2398 fputs(ctime(&t), fdDump);
2399 fflush(fdDump);
2400 }
2401#endif
2402
2403 g_fWindInitCalled = TRUE;
2404
2405#ifdef FEAT_MOUSE
2406 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2407#endif
2408
2409#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002410 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411#endif
2412
2413 /* This will be NULL on anything but NT 4.0 */
2414 s_pfnGetConsoleKeyboardLayoutName =
2415 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2416 "GetConsoleKeyboardLayoutNameA");
2417}
2418
2419/*
2420 * non-GUI version of mch_exit().
2421 * Shut down and exit with status `r'
2422 * Careful: mch_exit() may be called before mch_init()!
2423 */
2424 void
2425mch_exit(int r)
2426{
2427 stoptermcap();
2428
2429 if (g_fWindInitCalled)
2430 settmode(TMODE_COOK);
2431
2432 ml_close_all(TRUE); /* remove all memfiles */
2433
2434 if (g_fWindInitCalled)
2435 {
2436#ifdef FEAT_TITLE
2437 mch_restore_title(3);
2438 /*
2439 * Restore both the small and big icons of the console window to
2440 * what they were at startup. Don't do this when the window is
2441 * closed, Vim would hang here.
2442 */
2443 if (g_fCanChangeIcon && !g_fForceExit)
2444 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2445#endif
2446
2447#ifdef MCH_WRITE_DUMP
2448 if (fdDump)
2449 {
2450 time_t t;
2451
2452 time(&t);
2453 fputs(ctime(&t), fdDump);
2454 fclose(fdDump);
2455 }
2456 fdDump = NULL;
2457#endif
2458 }
2459
2460 SetConsoleCursorInfo(g_hConOut, &g_cci);
2461 SetConsoleMode(g_hConIn, g_cmodein);
2462 SetConsoleMode(g_hConOut, g_cmodeout);
2463
2464#ifdef DYNAMIC_GETTEXT
2465 dyn_libintl_end();
2466#endif
2467
2468 exit(r);
2469}
2470#endif /* !FEAT_GUI_W32 */
2471
Bram Moolenaar071d4272004-06-13 20:20:40 +00002472/*
2473 * Do we have an interactive window?
2474 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002475/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002476 int
2477mch_check_win(
2478 int argc,
2479 char **argv)
2480{
2481 get_exe_name();
2482
2483#ifdef FEAT_GUI_W32
2484 return OK; /* GUI always has a tty */
2485#else
2486 if (isatty(1))
2487 return OK;
2488 return FAIL;
2489#endif
2490}
2491
2492
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002493#ifdef FEAT_MBYTE
2494/*
2495 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2496 * if it already exists. When "len" is > 0, also expand short to long
2497 * filenames.
2498 * Return FAIL if wide functions are not available, OK otherwise.
2499 * NOTE: much of this is identical to fname_case(), keep in sync!
2500 */
2501 static int
2502fname_casew(
2503 WCHAR *name,
2504 int len)
2505{
2506 WCHAR szTrueName[_MAX_PATH + 2];
2507 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2508 WCHAR *ptrue, *ptruePrev;
2509 WCHAR *porig, *porigPrev;
2510 int flen;
2511 WIN32_FIND_DATAW fb;
2512 HANDLE hFind;
2513 int c;
2514 int slen;
2515
2516 flen = (int)wcslen(name);
2517 if (flen > _MAX_PATH)
2518 return OK;
2519
2520 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2521
2522 /* Build the new name in szTrueName[] one component at a time. */
2523 porig = name;
2524 ptrue = szTrueName;
2525
2526 if (iswalpha(porig[0]) && porig[1] == L':')
2527 {
2528 /* copy leading drive letter */
2529 *ptrue++ = *porig++;
2530 *ptrue++ = *porig++;
2531 *ptrue = NUL; /* in case nothing follows */
2532 }
2533
2534 while (*porig != NUL)
2535 {
2536 /* copy \ characters */
2537 while (*porig == psepc)
2538 *ptrue++ = *porig++;
2539
2540 ptruePrev = ptrue;
2541 porigPrev = porig;
2542 while (*porig != NUL && *porig != psepc)
2543 {
2544 *ptrue++ = *porig++;
2545 }
2546 *ptrue = NUL;
2547
2548 /* To avoid a slow failure append "\*" when searching a directory,
2549 * server or network share. */
2550 wcscpy(szTrueNameTemp, szTrueName);
2551 slen = (int)wcslen(szTrueNameTemp);
2552 if (*porig == psepc && slen + 2 < _MAX_PATH)
2553 wcscpy(szTrueNameTemp + slen, L"\\*");
2554
2555 /* Skip "", "." and "..". */
2556 if (ptrue > ptruePrev
2557 && (ptruePrev[0] != L'.'
2558 || (ptruePrev[1] != NUL
2559 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2560 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2561 != INVALID_HANDLE_VALUE)
2562 {
2563 c = *porig;
2564 *porig = NUL;
2565
2566 /* Only use the match when it's the same name (ignoring case) or
2567 * expansion is allowed and there is a match with the short name
2568 * and there is enough room. */
2569 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2570 || (len > 0
2571 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2572 && (int)(ptruePrev - szTrueName)
2573 + (int)wcslen(fb.cFileName) < len)))
2574 {
2575 wcscpy(ptruePrev, fb.cFileName);
2576
2577 /* Look for exact match and prefer it if found. Must be a
2578 * long name, otherwise there would be only one match. */
2579 while (FindNextFileW(hFind, &fb))
2580 {
2581 if (*fb.cAlternateFileName != NUL
2582 && (wcscoll(porigPrev, fb.cFileName) == 0
2583 || (len > 0
2584 && (_wcsicoll(porigPrev,
2585 fb.cAlternateFileName) == 0
2586 && (int)(ptruePrev - szTrueName)
2587 + (int)wcslen(fb.cFileName) < len))))
2588 {
2589 wcscpy(ptruePrev, fb.cFileName);
2590 break;
2591 }
2592 }
2593 }
2594 FindClose(hFind);
2595 *porig = c;
2596 ptrue = ptruePrev + wcslen(ptruePrev);
2597 }
2598 else if (hFind == INVALID_HANDLE_VALUE
2599 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2600 return FAIL;
2601 }
2602
2603 wcscpy(name, szTrueName);
2604 return OK;
2605}
2606#endif
2607
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608/*
2609 * fname_case(): Set the case of the file name, if it already exists.
2610 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002611 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002612 */
2613 void
2614fname_case(
2615 char_u *name,
2616 int len)
2617{
2618 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002619 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002620 char *ptrue, *ptruePrev;
2621 char *porig, *porigPrev;
2622 int flen;
2623 WIN32_FIND_DATA fb;
2624 HANDLE hFind;
2625 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002626 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002627
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002628 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002629 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 return;
2631
2632 slash_adjust(name);
2633
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002634#ifdef FEAT_MBYTE
2635 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2636 {
2637 WCHAR *p = enc_to_utf16(name, NULL);
2638
2639 if (p != NULL)
2640 {
2641 char_u *q;
2642 WCHAR buf[_MAX_PATH + 2];
2643
2644 wcscpy(buf, p);
2645 vim_free(p);
2646
2647 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2648 {
2649 q = utf16_to_enc(buf, NULL);
2650 if (q != NULL)
2651 {
2652 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2653 vim_free(q);
2654 return;
2655 }
2656 }
2657 }
2658 /* Retry with non-wide function (for Windows 98). */
2659 }
2660#endif
2661
2662 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2663 * So we should check this after calling wide function. */
2664 if (flen > _MAX_PATH)
2665 return;
2666
Bram Moolenaar071d4272004-06-13 20:20:40 +00002667 /* Build the new name in szTrueName[] one component at a time. */
2668 porig = name;
2669 ptrue = szTrueName;
2670
2671 if (isalpha(porig[0]) && porig[1] == ':')
2672 {
2673 /* copy leading drive letter */
2674 *ptrue++ = *porig++;
2675 *ptrue++ = *porig++;
2676 *ptrue = NUL; /* in case nothing follows */
2677 }
2678
2679 while (*porig != NUL)
2680 {
2681 /* copy \ characters */
2682 while (*porig == psepc)
2683 *ptrue++ = *porig++;
2684
2685 ptruePrev = ptrue;
2686 porigPrev = porig;
2687 while (*porig != NUL && *porig != psepc)
2688 {
2689#ifdef FEAT_MBYTE
2690 int l;
2691
2692 if (enc_dbcs)
2693 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002694 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002695 while (--l >= 0)
2696 *ptrue++ = *porig++;
2697 }
2698 else
2699#endif
2700 *ptrue++ = *porig++;
2701 }
2702 *ptrue = NUL;
2703
Bram Moolenaar464c9252010-10-13 20:37:41 +02002704 /* To avoid a slow failure append "\*" when searching a directory,
2705 * server or network share. */
2706 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002707 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002708 if (*porig == psepc && slen + 2 < _MAX_PATH)
2709 STRCPY(szTrueNameTemp + slen, "\\*");
2710
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 /* Skip "", "." and "..". */
2712 if (ptrue > ptruePrev
2713 && (ptruePrev[0] != '.'
2714 || (ptruePrev[1] != NUL
2715 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002716 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 != INVALID_HANDLE_VALUE)
2718 {
2719 c = *porig;
2720 *porig = NUL;
2721
2722 /* Only use the match when it's the same name (ignoring case) or
2723 * expansion is allowed and there is a match with the short name
2724 * and there is enough room. */
2725 if (_stricoll(porigPrev, fb.cFileName) == 0
2726 || (len > 0
2727 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2728 && (int)(ptruePrev - szTrueName)
2729 + (int)strlen(fb.cFileName) < len)))
2730 {
2731 STRCPY(ptruePrev, fb.cFileName);
2732
2733 /* Look for exact match and prefer it if found. Must be a
2734 * long name, otherwise there would be only one match. */
2735 while (FindNextFile(hFind, &fb))
2736 {
2737 if (*fb.cAlternateFileName != NUL
2738 && (strcoll(porigPrev, fb.cFileName) == 0
2739 || (len > 0
2740 && (_stricoll(porigPrev,
2741 fb.cAlternateFileName) == 0
2742 && (int)(ptruePrev - szTrueName)
2743 + (int)strlen(fb.cFileName) < len))))
2744 {
2745 STRCPY(ptruePrev, fb.cFileName);
2746 break;
2747 }
2748 }
2749 }
2750 FindClose(hFind);
2751 *porig = c;
2752 ptrue = ptruePrev + strlen(ptruePrev);
2753 }
2754 }
2755
2756 STRCPY(name, szTrueName);
2757}
2758
2759
2760/*
2761 * Insert user name in s[len].
2762 */
2763 int
2764mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002765 char_u *s,
2766 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002768 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002769 DWORD cch = sizeof szUserName;
2770
2771 if (GetUserName(szUserName, &cch))
2772 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002773 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 return OK;
2775 }
2776 s[0] = NUL;
2777 return FAIL;
2778}
2779
2780
2781/*
2782 * Insert host name in s[len].
2783 */
2784 void
2785mch_get_host_name(
2786 char_u *s,
2787 int len)
2788{
2789 DWORD cch = len;
2790
2791 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002792 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793}
2794
2795
2796/*
2797 * return process ID
2798 */
2799 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002800mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801{
2802 return (long)GetCurrentProcessId();
2803}
2804
2805
2806/*
2807 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2808 * Return OK for success, FAIL for failure.
2809 */
2810 int
2811mch_dirname(
2812 char_u *buf,
2813 int len)
2814{
2815 /*
2816 * Originally this was:
2817 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2818 * But the Win32s known bug list says that getcwd() doesn't work
2819 * so use the Win32 system call instead. <Negri>
2820 */
2821#ifdef FEAT_MBYTE
2822 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2823 {
2824 WCHAR wbuf[_MAX_PATH + 1];
2825
2826 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2827 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002828 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829
2830 if (p != NULL)
2831 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002832 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833 vim_free(p);
2834 return OK;
2835 }
2836 }
2837 /* Retry with non-wide function (for Windows 98). */
2838 }
2839#endif
2840 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2841}
2842
2843/*
2844 * get file permissions for `name'
2845 * -1 : error
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002846 * else mode_t
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847 */
2848 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002849mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002851 struct stat st;
2852 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002854 n = mch_stat(name, &st);
2855 return n == 0 ? (int)st.st_mode : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856}
2857
2858
2859/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002860 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002861 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002862 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863 */
2864 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002865mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002867 long n = -1;
2868
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869#ifdef FEAT_MBYTE
2870 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2871 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002872 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873
2874 if (p != NULL)
2875 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002876 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002878 if (n == -1 && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2879 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880 /* Retry with non-wide function (for Windows 98). */
2881 }
2882 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002883 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002885 n = _chmod(name, perm);
2886 if (n == -1)
2887 return FAIL;
2888
2889 win32_set_archive(name);
2890
2891 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002892}
2893
2894/*
2895 * Set hidden flag for "name".
2896 */
2897 void
2898mch_hide(char_u *name)
2899{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002900 int attrs = win32_getattrs(name);
2901 if (attrs == -1)
2902 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002904 attrs |= FILE_ATTRIBUTE_HIDDEN;
2905 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906}
2907
2908/*
2909 * return TRUE if "name" is a directory
2910 * return FALSE if "name" is not a directory or upon error
2911 */
2912 int
2913mch_isdir(char_u *name)
2914{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002915 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916
2917 if (f == -1)
2918 return FALSE; /* file does not exist at all */
2919
2920 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2921}
2922
2923/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002924 * Create directory "name".
2925 * Return 0 on success, -1 on error.
2926 */
2927 int
2928mch_mkdir(char_u *name)
2929{
2930#ifdef FEAT_MBYTE
2931 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2932 {
2933 WCHAR *p;
2934 int retval;
2935
2936 p = enc_to_utf16(name, NULL);
2937 if (p == NULL)
2938 return -1;
2939 retval = _wmkdir(p);
2940 vim_free(p);
2941 return retval;
2942 }
2943#endif
2944 return _mkdir(name);
2945}
2946
2947/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002948 * Return TRUE if file "fname" has more than one link.
2949 */
2950 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002951mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002952{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002953 BY_HANDLE_FILE_INFORMATION info;
2954
2955 return win32_fileinfo(fname, &info) == FILEINFO_OK
2956 && info.nNumberOfLinks > 1;
2957}
2958
2959/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002960 * Return TRUE if file "fname" is a symbolic link.
2961 */
2962 int
2963mch_is_symbolic_link(char_u *fname)
2964{
2965 HANDLE hFind;
2966 int res = FALSE;
2967 WIN32_FIND_DATAA findDataA;
2968 DWORD fileFlags = 0, reparseTag = 0;
2969#ifdef FEAT_MBYTE
2970 WCHAR *wn = NULL;
2971 WIN32_FIND_DATAW findDataW;
2972
2973 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2974 wn = enc_to_utf16(fname, NULL);
2975 if (wn != NULL)
2976 {
2977 hFind = FindFirstFileW(wn, &findDataW);
2978 vim_free(wn);
2979 if (hFind == INVALID_HANDLE_VALUE
2980 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2981 {
2982 /* Retry with non-wide function (for Windows 98). */
2983 hFind = FindFirstFile(fname, &findDataA);
2984 if (hFind != INVALID_HANDLE_VALUE)
2985 {
2986 fileFlags = findDataA.dwFileAttributes;
2987 reparseTag = findDataA.dwReserved0;
2988 }
2989 }
2990 else
2991 {
2992 fileFlags = findDataW.dwFileAttributes;
2993 reparseTag = findDataW.dwReserved0;
2994 }
2995 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002996 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002997#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002998 {
2999 hFind = FindFirstFile(fname, &findDataA);
3000 if (hFind != INVALID_HANDLE_VALUE)
3001 {
3002 fileFlags = findDataA.dwFileAttributes;
3003 reparseTag = findDataA.dwReserved0;
3004 }
3005 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003006
3007 if (hFind != INVALID_HANDLE_VALUE)
3008 FindClose(hFind);
3009
3010 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3011 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3012 res = TRUE;
3013
3014 return res;
3015}
3016
3017/*
3018 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3019 * link.
3020 */
3021 int
3022mch_is_linked(char_u *fname)
3023{
3024 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3025 return TRUE;
3026 return FALSE;
3027}
3028
3029/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003030 * Get the by-handle-file-information for "fname".
3031 * Returns FILEINFO_OK when OK.
3032 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3033 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3034 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3035 */
3036 int
3037win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3038{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003039 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003040 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003041#ifdef FEAT_MBYTE
3042 WCHAR *wn = NULL;
3043
3044 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003045 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003046 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003047 if (wn == NULL)
3048 res = FILEINFO_ENC_FAIL;
3049 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003050 if (wn != NULL)
3051 {
3052 hFile = CreateFileW(wn, /* file name */
3053 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003054 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003055 NULL, /* security descriptor */
3056 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003057 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003058 NULL); /* handle to template file */
3059 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003060 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003061 {
3062 /* Retry with non-wide function (for Windows 98). */
3063 vim_free(wn);
3064 wn = NULL;
3065 }
3066 }
3067 if (wn == NULL)
3068#endif
3069 hFile = CreateFile(fname, /* file name */
3070 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003071 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003072 NULL, /* security descriptor */
3073 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003074 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003075 NULL); /* handle to template file */
3076
3077 if (hFile != INVALID_HANDLE_VALUE)
3078 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003079 if (GetFileInformationByHandle(hFile, info) != 0)
3080 res = FILEINFO_OK;
3081 else
3082 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003083 CloseHandle(hFile);
3084 }
3085
3086#ifdef FEAT_MBYTE
3087 vim_free(wn);
3088#endif
3089 return res;
3090}
3091
3092/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003093 * get file attributes for `name'
3094 * -1 : error
3095 * else FILE_ATTRIBUTE_* defined in winnt.h
3096 */
3097 static
3098 int
3099win32_getattrs(char_u *name)
3100{
3101 int attr;
3102#ifdef FEAT_MBYTE
3103 WCHAR *p = NULL;
3104
3105 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3106 p = enc_to_utf16(name, NULL);
3107
3108 if (p != NULL)
3109 {
3110 attr = GetFileAttributesW(p);
3111 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3112 {
3113 /* Retry with non-wide function (for Windows 98). */
3114 vim_free(p);
3115 p = NULL;
3116 }
3117 }
3118 if (p == NULL)
3119#endif
3120 attr = GetFileAttributes((char *)name);
3121#ifdef FEAT_MBYTE
3122 vim_free(p);
3123#endif
3124 return attr;
3125}
3126
3127/*
3128 * set file attributes for `name' to `attrs'
3129 *
3130 * return -1 for failure, 0 otherwise
3131 */
3132 static
3133 int
3134win32_setattrs(char_u *name, int attrs)
3135{
3136 int res;
3137#ifdef FEAT_MBYTE
3138 WCHAR *p = NULL;
3139
3140 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3141 p = enc_to_utf16(name, NULL);
3142
3143 if (p != NULL)
3144 {
3145 res = SetFileAttributesW(p, attrs);
3146 if (res == FALSE
3147 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3148 {
3149 /* Retry with non-wide function (for Windows 98). */
3150 vim_free(p);
3151 p = NULL;
3152 }
3153 }
3154 if (p == NULL)
3155#endif
3156 res = SetFileAttributes((char *)name, attrs);
3157#ifdef FEAT_MBYTE
3158 vim_free(p);
3159#endif
3160 return res ? 0 : -1;
3161}
3162
3163/*
3164 * Set archive flag for "name".
3165 */
3166 static
3167 int
3168win32_set_archive(char_u *name)
3169{
3170 int attrs = win32_getattrs(name);
3171 if (attrs == -1)
3172 return -1;
3173
3174 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3175 return win32_setattrs(name, attrs);
3176}
3177
3178/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003179 * Return TRUE if file or directory "name" is writable (not readonly).
3180 * Strange semantics of Win32: a readonly directory is writable, but you can't
3181 * delete a file. Let's say this means it is writable.
3182 */
3183 int
3184mch_writable(char_u *name)
3185{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003186 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003187
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003188 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3189 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190}
3191
Bram Moolenaar071d4272004-06-13 20:20:40 +00003192/*
3193 * Return 1 if "name" can be executed, 0 if not.
3194 * Return -1 if unknown.
3195 */
3196 int
3197mch_can_exe(char_u *name)
3198{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003199 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003200 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003201 char_u *p;
3202
3203 if (len >= _MAX_PATH) /* safety check */
3204 return FALSE;
3205
3206 /* If there already is an extension try using the name directly. Also do
3207 * this with a Unix-shell like 'shell'. */
3208 if (vim_strchr(gettail(name), '.') != NULL
3209 || strstr((char *)gettail(p_sh), "sh") != NULL)
3210 if (executable_exists((char *)name))
3211 return TRUE;
3212
3213 /*
3214 * Loop over all extensions in $PATHEXT.
3215 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003216 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003217 p = mch_getenv("PATHEXT");
3218 if (p == NULL)
3219 p = (char_u *)".com;.exe;.bat;.cmd";
3220 while (*p)
3221 {
3222 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3223 {
3224 /* A single "." means no extension is added. */
3225 buf[len] = NUL;
3226 ++p;
3227 if (*p)
3228 ++p;
3229 }
3230 else
3231 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
3232 if (executable_exists((char *)buf))
3233 return TRUE;
3234 }
3235 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237
3238/*
3239 * Check what "name" is:
3240 * NODE_NORMAL: file or directory (or doesn't exist)
3241 * NODE_WRITABLE: writable device, socket, fifo, etc.
3242 * NODE_OTHER: non-writable things
3243 */
3244 int
3245mch_nodetype(char_u *name)
3246{
3247 HANDLE hFile;
3248 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003249#ifdef FEAT_MBYTE
3250 WCHAR *wn = NULL;
3251#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252
Bram Moolenaar043545e2006-10-10 16:44:07 +00003253 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3254 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3255 * here. */
3256 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3257 return NODE_WRITABLE;
3258
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003259#ifdef FEAT_MBYTE
3260 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3261 {
3262 wn = enc_to_utf16(name, NULL);
3263 if (wn != NULL)
3264 {
3265 hFile = CreateFileW(wn, /* file name */
3266 GENERIC_WRITE, /* access mode */
3267 0, /* share mode */
3268 NULL, /* security descriptor */
3269 OPEN_EXISTING, /* creation disposition */
3270 0, /* file attributes */
3271 NULL); /* handle to template file */
3272 if (hFile == INVALID_HANDLE_VALUE
3273 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3274 {
3275 /* Retry with non-wide function (for Windows 98). */
3276 vim_free(wn);
3277 wn = NULL;
3278 }
3279 }
3280 }
3281 if (wn == NULL)
3282#endif
3283 hFile = CreateFile(name, /* file name */
3284 GENERIC_WRITE, /* access mode */
3285 0, /* share mode */
3286 NULL, /* security descriptor */
3287 OPEN_EXISTING, /* creation disposition */
3288 0, /* file attributes */
3289 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003291#ifdef FEAT_MBYTE
3292 vim_free(wn);
3293#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294 if (hFile == INVALID_HANDLE_VALUE)
3295 return NODE_NORMAL;
3296
3297 type = GetFileType(hFile);
3298 CloseHandle(hFile);
3299 if (type == FILE_TYPE_CHAR)
3300 return NODE_WRITABLE;
3301 if (type == FILE_TYPE_DISK)
3302 return NODE_NORMAL;
3303 return NODE_OTHER;
3304}
3305
3306#ifdef HAVE_ACL
3307struct my_acl
3308{
3309 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3310 PSID pSidOwner;
3311 PSID pSidGroup;
3312 PACL pDacl;
3313 PACL pSacl;
3314};
3315#endif
3316
3317/*
3318 * Return a pointer to the ACL of file "fname" in allocated memory.
3319 * Return NULL if the ACL is not available for whatever reason.
3320 */
3321 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003322mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003323{
3324#ifndef HAVE_ACL
3325 return (vim_acl_T)NULL;
3326#else
3327 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003328 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003329
3330 /* This only works on Windows NT and 2000. */
3331 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3332 {
3333 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3334 if (p != NULL)
3335 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003336# ifdef FEAT_MBYTE
3337 WCHAR *wn = NULL;
3338
3339 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3340 wn = enc_to_utf16(fname, NULL);
3341 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003343 /* Try to retrieve the entire security descriptor. */
3344 err = pGetNamedSecurityInfoW(
3345 wn, // Abstract filename
3346 SE_FILE_OBJECT, // File Object
3347 OWNER_SECURITY_INFORMATION |
3348 GROUP_SECURITY_INFORMATION |
3349 DACL_SECURITY_INFORMATION |
3350 SACL_SECURITY_INFORMATION,
3351 &p->pSidOwner, // Ownership information.
3352 &p->pSidGroup, // Group membership.
3353 &p->pDacl, // Discretionary information.
3354 &p->pSacl, // For auditing purposes.
3355 &p->pSecurityDescriptor);
3356 if (err == ERROR_ACCESS_DENIED ||
3357 err == ERROR_PRIVILEGE_NOT_HELD)
3358 {
3359 /* Retrieve only DACL. */
3360 (void)pGetNamedSecurityInfoW(
3361 wn,
3362 SE_FILE_OBJECT,
3363 DACL_SECURITY_INFORMATION,
3364 NULL,
3365 NULL,
3366 &p->pDacl,
3367 NULL,
3368 &p->pSecurityDescriptor);
3369 }
3370 if (p->pSecurityDescriptor == NULL)
3371 {
3372 mch_free_acl((vim_acl_T)p);
3373 p = NULL;
3374 }
3375 vim_free(wn);
3376 }
3377 else
3378# endif
3379 {
3380 /* Try to retrieve the entire security descriptor. */
3381 err = pGetNamedSecurityInfo(
3382 (LPSTR)fname, // Abstract filename
3383 SE_FILE_OBJECT, // File Object
3384 OWNER_SECURITY_INFORMATION |
3385 GROUP_SECURITY_INFORMATION |
3386 DACL_SECURITY_INFORMATION |
3387 SACL_SECURITY_INFORMATION,
3388 &p->pSidOwner, // Ownership information.
3389 &p->pSidGroup, // Group membership.
3390 &p->pDacl, // Discretionary information.
3391 &p->pSacl, // For auditing purposes.
3392 &p->pSecurityDescriptor);
3393 if (err == ERROR_ACCESS_DENIED ||
3394 err == ERROR_PRIVILEGE_NOT_HELD)
3395 {
3396 /* Retrieve only DACL. */
3397 (void)pGetNamedSecurityInfo(
3398 (LPSTR)fname,
3399 SE_FILE_OBJECT,
3400 DACL_SECURITY_INFORMATION,
3401 NULL,
3402 NULL,
3403 &p->pDacl,
3404 NULL,
3405 &p->pSecurityDescriptor);
3406 }
3407 if (p->pSecurityDescriptor == NULL)
3408 {
3409 mch_free_acl((vim_acl_T)p);
3410 p = NULL;
3411 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003412 }
3413 }
3414 }
3415
3416 return (vim_acl_T)p;
3417#endif
3418}
3419
Bram Moolenaar27515922013-06-29 15:36:26 +02003420#ifdef HAVE_ACL
3421/*
3422 * Check if "acl" contains inherited ACE.
3423 */
3424 static BOOL
3425is_acl_inherited(PACL acl)
3426{
3427 DWORD i;
3428 ACL_SIZE_INFORMATION acl_info;
3429 PACCESS_ALLOWED_ACE ace;
3430
3431 acl_info.AceCount = 0;
3432 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3433 for (i = 0; i < acl_info.AceCount; i++)
3434 {
3435 GetAce(acl, i, (LPVOID *)&ace);
3436 if (ace->Header.AceFlags & INHERITED_ACE)
3437 return TRUE;
3438 }
3439 return FALSE;
3440}
3441#endif
3442
Bram Moolenaar071d4272004-06-13 20:20:40 +00003443/*
3444 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3445 * Errors are ignored.
3446 * This must only be called with "acl" equal to what mch_get_acl() returned.
3447 */
3448 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003449mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450{
3451#ifdef HAVE_ACL
3452 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003453 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454
3455 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003456 {
3457# ifdef FEAT_MBYTE
3458 WCHAR *wn = NULL;
3459# endif
3460
3461 /* Set security flags */
3462 if (p->pSidOwner)
3463 sec_info |= OWNER_SECURITY_INFORMATION;
3464 if (p->pSidGroup)
3465 sec_info |= GROUP_SECURITY_INFORMATION;
3466 if (p->pDacl)
3467 {
3468 sec_info |= DACL_SECURITY_INFORMATION;
3469 /* Do not inherit its parent's DACL.
3470 * If the DACL is inherited, Cygwin permissions would be changed.
3471 */
3472 if (!is_acl_inherited(p->pDacl))
3473 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3474 }
3475 if (p->pSacl)
3476 sec_info |= SACL_SECURITY_INFORMATION;
3477
3478# ifdef FEAT_MBYTE
3479 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3480 wn = enc_to_utf16(fname, NULL);
3481 if (wn != NULL)
3482 {
3483 (void)pSetNamedSecurityInfoW(
3484 wn, // Abstract filename
3485 SE_FILE_OBJECT, // File Object
3486 sec_info,
3487 p->pSidOwner, // Ownership information.
3488 p->pSidGroup, // Group membership.
3489 p->pDacl, // Discretionary information.
3490 p->pSacl // For auditing purposes.
3491 );
3492 vim_free(wn);
3493 }
3494 else
3495# endif
3496 {
3497 (void)pSetNamedSecurityInfo(
3498 (LPSTR)fname, // Abstract filename
3499 SE_FILE_OBJECT, // File Object
3500 sec_info,
3501 p->pSidOwner, // Ownership information.
3502 p->pSidGroup, // Group membership.
3503 p->pDacl, // Discretionary information.
3504 p->pSacl // For auditing purposes.
3505 );
3506 }
3507 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003508#endif
3509}
3510
3511 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003512mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003513{
3514#ifdef HAVE_ACL
3515 struct my_acl *p = (struct my_acl *)acl;
3516
3517 if (p != NULL)
3518 {
3519 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3520 vim_free(p);
3521 }
3522#endif
3523}
3524
3525#ifndef FEAT_GUI_W32
3526
3527/*
3528 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3529 */
3530 static BOOL WINAPI
3531handler_routine(
3532 DWORD dwCtrlType)
3533{
3534 switch (dwCtrlType)
3535 {
3536 case CTRL_C_EVENT:
3537 if (ctrl_c_interrupts)
3538 g_fCtrlCPressed = TRUE;
3539 return TRUE;
3540
3541 case CTRL_BREAK_EVENT:
3542 g_fCBrkPressed = TRUE;
3543 return TRUE;
3544
3545 /* fatal events: shut down gracefully */
3546 case CTRL_CLOSE_EVENT:
3547 case CTRL_LOGOFF_EVENT:
3548 case CTRL_SHUTDOWN_EVENT:
3549 windgoto((int)Rows - 1, 0);
3550 g_fForceExit = TRUE;
3551
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003552 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003553 (dwCtrlType == CTRL_CLOSE_EVENT
3554 ? _("close")
3555 : dwCtrlType == CTRL_LOGOFF_EVENT
3556 ? _("logoff")
3557 : _("shutdown")));
3558#ifdef DEBUG
3559 OutputDebugString(IObuff);
3560#endif
3561
3562 preserve_exit(); /* output IObuff, preserve files and exit */
3563
3564 return TRUE; /* not reached */
3565
3566 default:
3567 return FALSE;
3568 }
3569}
3570
3571
3572/*
3573 * set the tty in (raw) ? "raw" : "cooked" mode
3574 */
3575 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003576mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003577{
3578 DWORD cmodein;
3579 DWORD cmodeout;
3580 BOOL bEnableHandler;
3581
3582 GetConsoleMode(g_hConIn, &cmodein);
3583 GetConsoleMode(g_hConOut, &cmodeout);
3584 if (tmode == TMODE_RAW)
3585 {
3586 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3587 ENABLE_ECHO_INPUT);
3588#ifdef FEAT_MOUSE
3589 if (g_fMouseActive)
3590 cmodein |= ENABLE_MOUSE_INPUT;
3591#endif
3592 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3593 bEnableHandler = TRUE;
3594 }
3595 else /* cooked */
3596 {
3597 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3598 ENABLE_ECHO_INPUT);
3599 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3600 bEnableHandler = FALSE;
3601 }
3602 SetConsoleMode(g_hConIn, cmodein);
3603 SetConsoleMode(g_hConOut, cmodeout);
3604 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3605
3606#ifdef MCH_WRITE_DUMP
3607 if (fdDump)
3608 {
3609 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3610 tmode == TMODE_RAW ? "raw" :
3611 tmode == TMODE_COOK ? "cooked" : "normal",
3612 cmodein, cmodeout);
3613 fflush(fdDump);
3614 }
3615#endif
3616}
3617
3618
3619/*
3620 * Get the size of the current window in `Rows' and `Columns'
3621 * Return OK when size could be determined, FAIL otherwise.
3622 */
3623 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003624mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625{
3626 CONSOLE_SCREEN_BUFFER_INFO csbi;
3627
3628 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3629 {
3630 /*
3631 * For some reason, we are trying to get the screen dimensions
3632 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3633 * variables are really intended to mean the size of Vim screen
3634 * while in termcap mode.
3635 */
3636 Rows = g_cbTermcap.Info.dwSize.Y;
3637 Columns = g_cbTermcap.Info.dwSize.X;
3638 }
3639 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3640 {
3641 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3642 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3643 }
3644 else
3645 {
3646 Rows = 25;
3647 Columns = 80;
3648 }
3649 return OK;
3650}
3651
3652/*
3653 * Set a console window to `xSize' * `ySize'
3654 */
3655 static void
3656ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003657 HANDLE hConsole,
3658 int xSize,
3659 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003660{
3661 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3662 SMALL_RECT srWindowRect; /* hold the new console size */
3663 COORD coordScreen;
3664
3665#ifdef MCH_WRITE_DUMP
3666 if (fdDump)
3667 {
3668 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3669 fflush(fdDump);
3670 }
3671#endif
3672
3673 /* get the largest size we can size the console window to */
3674 coordScreen = GetLargestConsoleWindowSize(hConsole);
3675
3676 /* define the new console window size and scroll position */
3677 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3678 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3679 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3680
3681 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3682 {
3683 int sx, sy;
3684
3685 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3686 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3687 if (sy < ySize || sx < xSize)
3688 {
3689 /*
3690 * Increasing number of lines/columns, do buffer first.
3691 * Use the maximal size in x and y direction.
3692 */
3693 if (sy < ySize)
3694 coordScreen.Y = ySize;
3695 else
3696 coordScreen.Y = sy;
3697 if (sx < xSize)
3698 coordScreen.X = xSize;
3699 else
3700 coordScreen.X = sx;
3701 SetConsoleScreenBufferSize(hConsole, coordScreen);
3702 }
3703 }
3704
3705 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3706 {
3707#ifdef MCH_WRITE_DUMP
3708 if (fdDump)
3709 {
3710 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3711 GetLastError());
3712 fflush(fdDump);
3713 }
3714#endif
3715 }
3716
3717 /* define the new console buffer size */
3718 coordScreen.X = xSize;
3719 coordScreen.Y = ySize;
3720
3721 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3722 {
3723#ifdef MCH_WRITE_DUMP
3724 if (fdDump)
3725 {
3726 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3727 GetLastError());
3728 fflush(fdDump);
3729 }
3730#endif
3731 }
3732}
3733
3734
3735/*
3736 * Set the console window to `Rows' * `Columns'
3737 */
3738 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003739mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740{
3741 COORD coordScreen;
3742
3743 /* Don't change window size while still starting up */
3744 if (suppress_winsize != 0)
3745 {
3746 suppress_winsize = 2;
3747 return;
3748 }
3749
3750 if (term_console)
3751 {
3752 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3753
3754 /* Clamp Rows and Columns to reasonable values */
3755 if (Rows > coordScreen.Y)
3756 Rows = coordScreen.Y;
3757 if (Columns > coordScreen.X)
3758 Columns = coordScreen.X;
3759
3760 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3761 }
3762}
3763
3764/*
3765 * Rows and/or Columns has changed.
3766 */
3767 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003768mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003769{
3770 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3771}
3772
3773
3774/*
3775 * Called when started up, to set the winsize that was delayed.
3776 */
3777 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003778mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003779{
3780 if (suppress_winsize == 2)
3781 {
3782 suppress_winsize = 0;
3783 mch_set_shellsize();
3784 shell_resized();
3785 }
3786 suppress_winsize = 0;
3787}
3788#endif /* FEAT_GUI_W32 */
3789
3790
3791
3792#if defined(FEAT_GUI_W32) || defined(PROTO)
3793
3794/*
3795 * Specialised version of system() for Win32 GUI mode.
3796 * This version proceeds as follows:
3797 * 1. Create a console window for use by the subprocess
3798 * 2. Run the subprocess (it gets the allocated console by default)
3799 * 3. Wait for the subprocess to terminate and get its exit code
3800 * 4. Prompt the user to press a key to close the console window
3801 */
3802 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003803mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804{
3805 STARTUPINFO si;
3806 PROCESS_INFORMATION pi;
3807 DWORD ret = 0;
3808 HWND hwnd = GetFocus();
3809
3810 si.cb = sizeof(si);
3811 si.lpReserved = NULL;
3812 si.lpDesktop = NULL;
3813 si.lpTitle = NULL;
3814 si.dwFlags = STARTF_USESHOWWINDOW;
3815 /*
3816 * It's nicer to run a filter command in a minimized window, but in
3817 * Windows 95 this makes the command MUCH slower. We can't do it under
3818 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003819 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 */
3821 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003822 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003823 else
3824 si.wShowWindow = SW_SHOWNORMAL;
3825 si.cbReserved2 = 0;
3826 si.lpReserved2 = NULL;
3827
3828 /* There is a strange error on Windows 95 when using "c:\\command.com".
3829 * When the "c:\\" is left out it works OK...? */
3830 if (mch_windows95()
3831 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3832 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3833 cmd += 3;
3834
3835 /* Now, run the command */
3836 CreateProcess(NULL, /* Executable name */
3837 cmd, /* Command to execute */
3838 NULL, /* Process security attributes */
3839 NULL, /* Thread security attributes */
3840 FALSE, /* Inherit handles */
3841 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3842 CREATE_NEW_CONSOLE,
3843 NULL, /* Environment */
3844 NULL, /* Current directory */
3845 &si, /* Startup information */
3846 &pi); /* Process information */
3847
3848
3849 /* Wait for the command to terminate before continuing */
3850 if (g_PlatformId != VER_PLATFORM_WIN32s)
3851 {
3852#ifdef FEAT_GUI
3853 int delay = 1;
3854
3855 /* Keep updating the window while waiting for the shell to finish. */
3856 for (;;)
3857 {
3858 MSG msg;
3859
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003860 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003861 {
3862 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003863 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003864 delay = 1;
3865 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003866 }
3867 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3868 break;
3869
3870 /* We start waiting for a very short time and then increase it, so
3871 * that we respond quickly when the process is quick, and don't
3872 * consume too much overhead when it's slow. */
3873 if (delay < 50)
3874 delay += 10;
3875 }
3876#else
3877 WaitForSingleObject(pi.hProcess, INFINITE);
3878#endif
3879
3880 /* Get the command exit code */
3881 GetExitCodeProcess(pi.hProcess, &ret);
3882 }
3883 else
3884 {
3885 /*
3886 * This ugly code is the only quick way of performing
3887 * a synchronous spawn under Win32s. Yuk.
3888 */
3889 num_windows = 0;
3890 EnumWindows(win32ssynch_cb, 0);
3891 old_num_windows = num_windows;
3892 do
3893 {
3894 Sleep(1000);
3895 num_windows = 0;
3896 EnumWindows(win32ssynch_cb, 0);
3897 } while (num_windows == old_num_windows);
3898 ret = 0;
3899 }
3900
3901 /* Close the handles to the subprocess, so that it goes away */
3902 CloseHandle(pi.hThread);
3903 CloseHandle(pi.hProcess);
3904
3905 /* Try to get input focus back. Doesn't always work though. */
3906 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3907
3908 return ret;
3909}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003910
3911/*
3912 * Thread launched by the gui to send the current buffer data to the
3913 * process. This way avoid to hang up vim totally if the children
3914 * process take a long time to process the lines.
3915 */
3916 static DWORD WINAPI
3917sub_process_writer(LPVOID param)
3918{
3919 HANDLE g_hChildStd_IN_Wr = param;
3920 linenr_T lnum = curbuf->b_op_start.lnum;
3921 DWORD len = 0;
3922 DWORD l;
3923 char_u *lp = ml_get(lnum);
3924 char_u *s;
3925 int written = 0;
3926
3927 for (;;)
3928 {
3929 l = (DWORD)STRLEN(lp + written);
3930 if (l == 0)
3931 len = 0;
3932 else if (lp[written] == NL)
3933 {
3934 /* NL -> NUL translation */
3935 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3936 }
3937 else
3938 {
3939 s = vim_strchr(lp + written, NL);
3940 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3941 s == NULL ? l : (DWORD)(s - (lp + written)),
3942 &len, NULL);
3943 }
3944 if (len == (int)l)
3945 {
3946 /* Finished a line, add a NL, unless this line should not have
3947 * one. */
3948 if (lnum != curbuf->b_op_end.lnum
3949 || !curbuf->b_p_bin
3950 || (lnum != curbuf->b_no_eol_lnum
3951 && (lnum != curbuf->b_ml.ml_line_count
3952 || curbuf->b_p_eol)))
3953 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01003954 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003955 }
3956
3957 ++lnum;
3958 if (lnum > curbuf->b_op_end.lnum)
3959 break;
3960
3961 lp = ml_get(lnum);
3962 written = 0;
3963 }
3964 else if (len > 0)
3965 written += len;
3966 }
3967
3968 /* finished all the lines, close pipe */
3969 CloseHandle(g_hChildStd_IN_Wr);
3970 ExitThread(0);
3971}
3972
3973
3974# define BUFLEN 100 /* length for buffer, stolen from unix version */
3975
3976/*
3977 * This function read from the children's stdout and write the
3978 * data on screen or in the buffer accordingly.
3979 */
3980 static void
3981dump_pipe(int options,
3982 HANDLE g_hChildStd_OUT_Rd,
3983 garray_T *ga,
3984 char_u buffer[],
3985 DWORD *buffer_off)
3986{
3987 DWORD availableBytes = 0;
3988 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003989 int ret;
3990 DWORD len;
3991 DWORD toRead;
3992 int repeatCount;
3993
3994 /* we query the pipe to see if there is any data to read
3995 * to avoid to perform a blocking read */
3996 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3997 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003998 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003999 NULL, /* number of read bytes */
4000 &availableBytes, /* available bytes total */
4001 NULL); /* byteLeft */
4002
4003 repeatCount = 0;
4004 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004005 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004006 {
4007 repeatCount++;
4008 toRead =
4009# ifdef FEAT_MBYTE
4010 (DWORD)(BUFLEN - *buffer_off);
4011# else
4012 (DWORD)BUFLEN;
4013# endif
4014 toRead = availableBytes < toRead ? availableBytes : toRead;
4015 ReadFile(g_hChildStd_OUT_Rd, buffer
4016# ifdef FEAT_MBYTE
4017 + *buffer_off, toRead
4018# else
4019 , toRead
4020# endif
4021 , &len, NULL);
4022
4023 /* If we haven't read anything, there is a problem */
4024 if (len == 0)
4025 break;
4026
4027 availableBytes -= len;
4028
4029 if (options & SHELL_READ)
4030 {
4031 /* Do NUL -> NL translation, append NL separated
4032 * lines to the current buffer. */
4033 for (i = 0; i < len; ++i)
4034 {
4035 if (buffer[i] == NL)
4036 append_ga_line(ga);
4037 else if (buffer[i] == NUL)
4038 ga_append(ga, NL);
4039 else
4040 ga_append(ga, buffer[i]);
4041 }
4042 }
4043# ifdef FEAT_MBYTE
4044 else if (has_mbyte)
4045 {
4046 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004047 int c;
4048 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004049
4050 len += *buffer_off;
4051 buffer[len] = NUL;
4052
4053 /* Check if the last character in buffer[] is
4054 * incomplete, keep these bytes for the next
4055 * round. */
4056 for (p = buffer; p < buffer + len; p += l)
4057 {
4058 l = mb_cptr2len(p);
4059 if (l == 0)
4060 l = 1; /* NUL byte? */
4061 else if (MB_BYTE2LEN(*p) != l)
4062 break;
4063 }
4064 if (p == buffer) /* no complete character */
4065 {
4066 /* avoid getting stuck at an illegal byte */
4067 if (len >= 12)
4068 ++p;
4069 else
4070 {
4071 *buffer_off = len;
4072 return;
4073 }
4074 }
4075 c = *p;
4076 *p = NUL;
4077 msg_puts(buffer);
4078 if (p < buffer + len)
4079 {
4080 *p = c;
4081 *buffer_off = (DWORD)((buffer + len) - p);
4082 mch_memmove(buffer, p, *buffer_off);
4083 return;
4084 }
4085 *buffer_off = 0;
4086 }
4087# endif /* FEAT_MBYTE */
4088 else
4089 {
4090 buffer[len] = NUL;
4091 msg_puts(buffer);
4092 }
4093
4094 windgoto(msg_row, msg_col);
4095 cursor_on();
4096 out_flush();
4097 }
4098}
4099
4100/*
4101 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4102 * for communication and doesn't open any new window.
4103 */
4104 static int
4105mch_system_piped(char *cmd, int options)
4106{
4107 STARTUPINFO si;
4108 PROCESS_INFORMATION pi;
4109 DWORD ret = 0;
4110
4111 HANDLE g_hChildStd_IN_Rd = NULL;
4112 HANDLE g_hChildStd_IN_Wr = NULL;
4113 HANDLE g_hChildStd_OUT_Rd = NULL;
4114 HANDLE g_hChildStd_OUT_Wr = NULL;
4115
4116 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4117 DWORD len;
4118
4119 /* buffer used to receive keys */
4120 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4121 int ta_len = 0; /* valid bytes in ta_buf[] */
4122
4123 DWORD i;
4124 int c;
4125 int noread_cnt = 0;
4126 garray_T ga;
4127 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004128 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004129 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004130
4131 SECURITY_ATTRIBUTES saAttr;
4132
4133 /* Set the bInheritHandle flag so pipe handles are inherited. */
4134 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4135 saAttr.bInheritHandle = TRUE;
4136 saAttr.lpSecurityDescriptor = NULL;
4137
4138 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4139 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4140 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4141 /* Create a pipe for the child process's STDIN. */
4142 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4143 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4144 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4145 {
4146 CloseHandle(g_hChildStd_IN_Rd);
4147 CloseHandle(g_hChildStd_IN_Wr);
4148 CloseHandle(g_hChildStd_OUT_Rd);
4149 CloseHandle(g_hChildStd_OUT_Wr);
4150 MSG_PUTS(_("\nCannot create pipes\n"));
4151 }
4152
4153 si.cb = sizeof(si);
4154 si.lpReserved = NULL;
4155 si.lpDesktop = NULL;
4156 si.lpTitle = NULL;
4157 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4158
4159 /* set-up our file redirection */
4160 si.hStdError = g_hChildStd_OUT_Wr;
4161 si.hStdOutput = g_hChildStd_OUT_Wr;
4162 si.hStdInput = g_hChildStd_IN_Rd;
4163 si.wShowWindow = SW_HIDE;
4164 si.cbReserved2 = 0;
4165 si.lpReserved2 = NULL;
4166
4167 if (options & SHELL_READ)
4168 ga_init2(&ga, 1, BUFLEN);
4169
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004170 if (cmd != NULL)
4171 {
4172 p = (char *)vim_strsave((char_u *)cmd);
4173 if (p != NULL)
4174 unescape_shellxquote((char_u *)p, p_sxe);
4175 else
4176 p = cmd;
4177 }
4178
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004179 /* Now, run the command */
4180 CreateProcess(NULL, /* Executable name */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004181 p, /* Command to execute */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004182 NULL, /* Process security attributes */
4183 NULL, /* Thread security attributes */
4184
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004185 // this command can be litigious, handle inheritance was
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004186 // deactivated for pending temp file, but, if we deactivate
4187 // it, the pipes don't work for some reason.
4188 TRUE, /* Inherit handles, first deactivated,
4189 * but needed */
4190 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
4191 NULL, /* Environment */
4192 NULL, /* Current directory */
4193 &si, /* Startup information */
4194 &pi); /* Process information */
4195
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004196 if (p != cmd)
4197 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004198
4199 /* Close our unused side of the pipes */
4200 CloseHandle(g_hChildStd_IN_Rd);
4201 CloseHandle(g_hChildStd_OUT_Wr);
4202
4203 if (options & SHELL_WRITE)
4204 {
4205 HANDLE thread =
4206 CreateThread(NULL, /* security attributes */
4207 0, /* default stack size */
4208 sub_process_writer, /* function to be executed */
4209 g_hChildStd_IN_Wr, /* parameter */
4210 0, /* creation flag, start immediately */
4211 NULL); /* we don't care about thread id */
4212 CloseHandle(thread);
4213 g_hChildStd_IN_Wr = NULL;
4214 }
4215
4216 /* Keep updating the window while waiting for the shell to finish. */
4217 for (;;)
4218 {
4219 MSG msg;
4220
4221 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4222 {
4223 TranslateMessage(&msg);
4224 DispatchMessage(&msg);
4225 }
4226
4227 /* write pipe information in the window */
4228 if ((options & (SHELL_READ|SHELL_WRITE))
4229# ifdef FEAT_GUI
4230 || gui.in_use
4231# endif
4232 )
4233 {
4234 len = 0;
4235 if (!(options & SHELL_EXPAND)
4236 && ((options &
4237 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4238 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4239# ifdef FEAT_GUI
4240 || gui.in_use
4241# endif
4242 )
4243 && (ta_len > 0 || noread_cnt > 4))
4244 {
4245 if (ta_len == 0)
4246 {
4247 /* Get extra characters when we don't have any. Reset the
4248 * counter and timer. */
4249 noread_cnt = 0;
4250# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4251 gettimeofday(&start_tv, NULL);
4252# endif
4253 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4254 }
4255 if (ta_len > 0 || len > 0)
4256 {
4257 /*
4258 * For pipes: Check for CTRL-C: send interrupt signal to
4259 * child. Check for CTRL-D: EOF, close pipe to child.
4260 */
4261 if (len == 1 && cmd != NULL)
4262 {
4263 if (ta_buf[ta_len] == Ctrl_C)
4264 {
4265 /* Learn what exit code is expected, for
4266 * now put 9 as SIGKILL */
4267 TerminateProcess(pi.hProcess, 9);
4268 }
4269 if (ta_buf[ta_len] == Ctrl_D)
4270 {
4271 CloseHandle(g_hChildStd_IN_Wr);
4272 g_hChildStd_IN_Wr = NULL;
4273 }
4274 }
4275
4276 /* replace K_BS by <BS> and K_DEL by <DEL> */
4277 for (i = ta_len; i < ta_len + len; ++i)
4278 {
4279 if (ta_buf[i] == CSI && len - i > 2)
4280 {
4281 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4282 if (c == K_DEL || c == K_KDEL || c == K_BS)
4283 {
4284 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4285 (size_t)(len - i - 2));
4286 if (c == K_DEL || c == K_KDEL)
4287 ta_buf[i] = DEL;
4288 else
4289 ta_buf[i] = Ctrl_H;
4290 len -= 2;
4291 }
4292 }
4293 else if (ta_buf[i] == '\r')
4294 ta_buf[i] = '\n';
4295# ifdef FEAT_MBYTE
4296 if (has_mbyte)
4297 i += (*mb_ptr2len_len)(ta_buf + i,
4298 ta_len + len - i) - 1;
4299# endif
4300 }
4301
4302 /*
4303 * For pipes: echo the typed characters. For a pty this
4304 * does not seem to work.
4305 */
4306 for (i = ta_len; i < ta_len + len; ++i)
4307 {
4308 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4309 msg_putchar(ta_buf[i]);
4310# ifdef FEAT_MBYTE
4311 else if (has_mbyte)
4312 {
4313 int l = (*mb_ptr2len)(ta_buf + i);
4314
4315 msg_outtrans_len(ta_buf + i, l);
4316 i += l - 1;
4317 }
4318# endif
4319 else
4320 msg_outtrans_len(ta_buf + i, 1);
4321 }
4322 windgoto(msg_row, msg_col);
4323 out_flush();
4324
4325 ta_len += len;
4326
4327 /*
4328 * Write the characters to the child, unless EOF has been
4329 * typed for pipes. Write one character at a time, to
4330 * avoid losing too much typeahead. When writing buffer
4331 * lines, drop the typed characters (only check for
4332 * CTRL-C).
4333 */
4334 if (options & SHELL_WRITE)
4335 ta_len = 0;
4336 else if (g_hChildStd_IN_Wr != NULL)
4337 {
4338 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4339 1, &len, NULL);
4340 // if we are typing in, we want to keep things reactive
4341 delay = 1;
4342 if (len > 0)
4343 {
4344 ta_len -= len;
4345 mch_memmove(ta_buf, ta_buf + len, ta_len);
4346 }
4347 }
4348 }
4349 }
4350 }
4351
4352 if (ta_len)
4353 ui_inchar_undo(ta_buf, ta_len);
4354
4355 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4356 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004357 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004358 break;
4359 }
4360
4361 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004362 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004363
4364 /* We start waiting for a very short time and then increase it, so
4365 * that we respond quickly when the process is quick, and don't
4366 * consume too much overhead when it's slow. */
4367 if (delay < 50)
4368 delay += 10;
4369 }
4370
4371 /* Close the pipe */
4372 CloseHandle(g_hChildStd_OUT_Rd);
4373 if (g_hChildStd_IN_Wr != NULL)
4374 CloseHandle(g_hChildStd_IN_Wr);
4375
4376 WaitForSingleObject(pi.hProcess, INFINITE);
4377
4378 /* Get the command exit code */
4379 GetExitCodeProcess(pi.hProcess, &ret);
4380
4381 if (options & SHELL_READ)
4382 {
4383 if (ga.ga_len > 0)
4384 {
4385 append_ga_line(&ga);
4386 /* remember that the NL was missing */
4387 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4388 }
4389 else
4390 curbuf->b_no_eol_lnum = 0;
4391 ga_clear(&ga);
4392 }
4393
4394 /* Close the handles to the subprocess, so that it goes away */
4395 CloseHandle(pi.hThread);
4396 CloseHandle(pi.hProcess);
4397
4398 return ret;
4399}
4400
4401 static int
4402mch_system(char *cmd, int options)
4403{
4404 /* if we can pipe and the shelltemp option is off */
4405 if (allowPiping && !p_stmp)
4406 return mch_system_piped(cmd, options);
4407 else
4408 return mch_system_classic(cmd, options);
4409}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004410#else
4411
4412# define mch_system(c, o) system(c)
4413
4414#endif
4415
4416/*
4417 * Either execute a command by calling the shell or start a new shell
4418 */
4419 int
4420mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004421 char_u *cmd,
4422 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004423{
4424 int x = 0;
4425 int tmode = cur_tmode;
4426#ifdef FEAT_TITLE
4427 char szShellTitle[512];
4428
4429 /* Change the title to reflect that we are in a subshell. */
4430 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
4431 {
4432 if (cmd == NULL)
4433 strcat(szShellTitle, " :sh");
4434 else
4435 {
4436 strcat(szShellTitle, " - !");
4437 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4438 strcat(szShellTitle, cmd);
4439 }
4440 mch_settitle(szShellTitle, NULL);
4441 }
4442#endif
4443
4444 out_flush();
4445
4446#ifdef MCH_WRITE_DUMP
4447 if (fdDump)
4448 {
4449 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4450 fflush(fdDump);
4451 }
4452#endif
4453
4454 /*
4455 * Catch all deadly signals while running the external command, because a
4456 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4457 */
4458 signal(SIGINT, SIG_IGN);
4459#if defined(__GNUC__) && !defined(__MINGW32__)
4460 signal(SIGKILL, SIG_IGN);
4461#else
4462 signal(SIGBREAK, SIG_IGN);
4463#endif
4464 signal(SIGILL, SIG_IGN);
4465 signal(SIGFPE, SIG_IGN);
4466 signal(SIGSEGV, SIG_IGN);
4467 signal(SIGTERM, SIG_IGN);
4468 signal(SIGABRT, SIG_IGN);
4469
4470 if (options & SHELL_COOKED)
4471 settmode(TMODE_COOK); /* set to normal mode */
4472
4473 if (cmd == NULL)
4474 {
4475 x = mch_system(p_sh, options);
4476 }
4477 else
4478 {
4479 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004480 char_u *newcmd = NULL;
4481 char_u *cmdbase = cmd;
4482 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004483
4484 /* Skip a leading ", ( and "(. */
4485 if (*cmdbase == '"' )
4486 ++cmdbase;
4487 if (*cmdbase == '(')
4488 ++cmdbase;
4489
4490 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4491 {
4492 STARTUPINFO si;
4493 PROCESS_INFORMATION pi;
4494 DWORD flags = CREATE_NEW_CONSOLE;
4495 char_u *p;
4496
4497 si.cb = sizeof(si);
4498 si.lpReserved = NULL;
4499 si.lpDesktop = NULL;
4500 si.lpTitle = NULL;
4501 si.dwFlags = 0;
4502 si.cbReserved2 = 0;
4503 si.lpReserved2 = NULL;
4504
4505 cmdbase = skipwhite(cmdbase + 5);
4506 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4507 && vim_iswhite(cmdbase[4]))
4508 {
4509 cmdbase = skipwhite(cmdbase + 4);
4510 si.dwFlags = STARTF_USESHOWWINDOW;
4511 si.wShowWindow = SW_SHOWMINNOACTIVE;
4512 }
4513 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4514 && vim_iswhite(cmdbase[2]))
4515 {
4516 cmdbase = skipwhite(cmdbase + 2);
4517 flags = CREATE_NO_WINDOW;
4518 si.dwFlags = STARTF_USESTDHANDLES;
4519 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004520 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004521 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004522 NULL, // Security att.
4523 OPEN_EXISTING, // Open flags
4524 FILE_ATTRIBUTE_NORMAL, // File att.
4525 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004526 si.hStdOutput = si.hStdInput;
4527 si.hStdError = si.hStdInput;
4528 }
4529
4530 /* Remove a trailing ", ) and )" if they have a match
4531 * at the start of the command. */
4532 if (cmdbase > cmd)
4533 {
4534 p = cmdbase + STRLEN(cmdbase);
4535 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4536 *--p = NUL;
4537 if (p > cmdbase && p[-1] == ')'
4538 && (*cmd =='(' || cmd[1] == '('))
4539 *--p = NUL;
4540 }
4541
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004542 newcmd = cmdbase;
4543 unescape_shellxquote(cmdbase, p_sxe);
4544
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004545 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004546 * If creating new console, arguments are passed to the
4547 * 'cmd.exe' as-is. If it's not, arguments are not treated
4548 * correctly for current 'cmd.exe'. So unescape characters in
4549 * shellxescape except '|' for avoiding to be treated as
4550 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004551 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004552 if (flags != CREATE_NEW_CONSOLE)
4553 {
4554 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004555 char_u *cmd_shell = mch_getenv("COMSPEC");
4556
4557 if (cmd_shell == NULL || *cmd_shell == NUL)
4558 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004559
4560 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4561 if (subcmd != NULL)
4562 {
4563 /* make "cmd.exe /c arguments" */
4564 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004565 newcmd = lalloc(cmdlen, TRUE);
4566 if (newcmd != NULL)
4567 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004568 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004569 else
4570 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004571 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004572 }
4573 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004574
4575 /*
4576 * Now, start the command as a process, so that it doesn't
4577 * inherit our handles which causes unpleasant dangling swap
4578 * files if we exit before the spawned process
4579 */
4580 if (CreateProcess(NULL, // Executable name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004581 newcmd, // Command to execute
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004582 NULL, // Process security attributes
4583 NULL, // Thread security attributes
4584 FALSE, // Inherit handles
4585 flags, // Creation flags
4586 NULL, // Environment
4587 NULL, // Current directory
4588 &si, // Startup information
4589 &pi)) // Process information
4590 x = 0;
4591 else
4592 {
4593 x = -1;
4594#ifdef FEAT_GUI_W32
4595 EMSG(_("E371: Command not found"));
4596#endif
4597 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004598
4599 if (newcmd != cmdbase)
4600 vim_free(newcmd);
4601
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004602 if (si.hStdInput != NULL)
4603 {
4604 /* Close the handle to \\.\NUL */
4605 CloseHandle(si.hStdInput);
4606 }
4607 /* Close the handles to the subprocess, so that it goes away */
4608 CloseHandle(pi.hThread);
4609 CloseHandle(pi.hProcess);
4610 }
4611 else
4612 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004613 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004614#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004615 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004616#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004617 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4618
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004619 newcmd = lalloc(cmdlen, TRUE);
4620 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004621 {
4622#if defined(FEAT_GUI_W32)
4623 if (need_vimrun_warning)
4624 {
4625 MessageBox(NULL,
4626 _("VIMRUN.EXE not found in your $PATH.\n"
4627 "External commands will not pause after completion.\n"
4628 "See :help win32-vimrun for more information."),
4629 _("Vim Warning"),
4630 MB_ICONWARNING);
4631 need_vimrun_warning = FALSE;
4632 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004633 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004634 /* Use vimrun to execute the command. It opens a console
4635 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004636 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004637 vimrun_path,
4638 (msg_silent != 0 || (options & SHELL_DOOUT))
4639 ? "-s " : "",
4640 p_sh, p_shcf, cmd);
4641 else
4642#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004643 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004644 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004645 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004646 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004648 }
4649 }
4650
4651 if (tmode == TMODE_RAW)
4652 settmode(TMODE_RAW); /* set to raw mode */
4653
4654 /* Print the return value, unless "vimrun" was used. */
4655 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4656#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004657 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4658 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004659#endif
4660 )
4661 {
4662 smsg(_("shell returned %d"), x);
4663 msg_putchar('\n');
4664 }
4665#ifdef FEAT_TITLE
4666 resettitle();
4667#endif
4668
4669 signal(SIGINT, SIG_DFL);
4670#if defined(__GNUC__) && !defined(__MINGW32__)
4671 signal(SIGKILL, SIG_DFL);
4672#else
4673 signal(SIGBREAK, SIG_DFL);
4674#endif
4675 signal(SIGILL, SIG_DFL);
4676 signal(SIGFPE, SIG_DFL);
4677 signal(SIGSEGV, SIG_DFL);
4678 signal(SIGTERM, SIG_DFL);
4679 signal(SIGABRT, SIG_DFL);
4680
4681 return x;
4682}
4683
4684
4685#ifndef FEAT_GUI_W32
4686
4687/*
4688 * Start termcap mode
4689 */
4690 static void
4691termcap_mode_start(void)
4692{
4693 DWORD cmodein;
4694
4695 if (g_fTermcapMode)
4696 return;
4697
4698 SaveConsoleBuffer(&g_cbNonTermcap);
4699
4700 if (g_cbTermcap.IsValid)
4701 {
4702 /*
4703 * We've been in termcap mode before. Restore certain screen
4704 * characteristics, including the buffer size and the window
4705 * size. Since we will be redrawing the screen, we don't need
4706 * to restore the actual contents of the buffer.
4707 */
4708 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4709 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4710 Rows = g_cbTermcap.Info.dwSize.Y;
4711 Columns = g_cbTermcap.Info.dwSize.X;
4712 }
4713 else
4714 {
4715 /*
4716 * This is our first time entering termcap mode. Clear the console
4717 * screen buffer, and resize the buffer to match the current window
4718 * size. We will use this as the size of our editing environment.
4719 */
4720 ClearConsoleBuffer(g_attrCurrent);
4721 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4722 }
4723
4724#ifdef FEAT_TITLE
4725 resettitle();
4726#endif
4727
4728 GetConsoleMode(g_hConIn, &cmodein);
4729#ifdef FEAT_MOUSE
4730 if (g_fMouseActive)
4731 cmodein |= ENABLE_MOUSE_INPUT;
4732 else
4733 cmodein &= ~ENABLE_MOUSE_INPUT;
4734#endif
4735 cmodein |= ENABLE_WINDOW_INPUT;
4736 SetConsoleMode(g_hConIn, cmodein);
4737
4738 redraw_later_clear();
4739 g_fTermcapMode = TRUE;
4740}
4741
4742
4743/*
4744 * End termcap mode
4745 */
4746 static void
4747termcap_mode_end(void)
4748{
4749 DWORD cmodein;
4750 ConsoleBuffer *cb;
4751 COORD coord;
4752 DWORD dwDummy;
4753
4754 if (!g_fTermcapMode)
4755 return;
4756
4757 SaveConsoleBuffer(&g_cbTermcap);
4758
4759 GetConsoleMode(g_hConIn, &cmodein);
4760 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4761 SetConsoleMode(g_hConIn, cmodein);
4762
4763#ifdef FEAT_RESTORE_ORIG_SCREEN
4764 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4765#else
4766 cb = &g_cbNonTermcap;
4767#endif
4768 RestoreConsoleBuffer(cb, p_rs);
4769 SetConsoleCursorInfo(g_hConOut, &g_cci);
4770
4771 if (p_rs || exiting)
4772 {
4773 /*
4774 * Clear anything that happens to be on the current line.
4775 */
4776 coord.X = 0;
4777 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4778 FillConsoleOutputCharacter(g_hConOut, ' ',
4779 cb->Info.dwSize.X, coord, &dwDummy);
4780 /*
4781 * The following is just for aesthetics. If we are exiting without
4782 * restoring the screen, then we want to have a prompt string
4783 * appear at the bottom line. However, the command interpreter
4784 * seems to always advance the cursor one line before displaying
4785 * the prompt string, which causes the screen to scroll. To
4786 * counter this, move the cursor up one line before exiting.
4787 */
4788 if (exiting && !p_rs)
4789 coord.Y--;
4790 /*
4791 * Position the cursor at the leftmost column of the desired row.
4792 */
4793 SetConsoleCursorPosition(g_hConOut, coord);
4794 }
4795
4796 g_fTermcapMode = FALSE;
4797}
4798#endif /* FEAT_GUI_W32 */
4799
4800
4801#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004802/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004803 void
4804mch_write(
4805 char_u *s,
4806 int len)
4807{
4808 /* never used */
4809}
4810
4811#else
4812
4813/*
4814 * clear `n' chars, starting from `coord'
4815 */
4816 static void
4817clear_chars(
4818 COORD coord,
4819 DWORD n)
4820{
4821 DWORD dwDummy;
4822
4823 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4824 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4825}
4826
4827
4828/*
4829 * Clear the screen
4830 */
4831 static void
4832clear_screen(void)
4833{
4834 g_coord.X = g_coord.Y = 0;
4835 clear_chars(g_coord, Rows * Columns);
4836}
4837
4838
4839/*
4840 * Clear to end of display
4841 */
4842 static void
4843clear_to_end_of_display(void)
4844{
4845 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4846 * Columns + (Columns - g_coord.X));
4847}
4848
4849
4850/*
4851 * Clear to end of line
4852 */
4853 static void
4854clear_to_end_of_line(void)
4855{
4856 clear_chars(g_coord, Columns - g_coord.X);
4857}
4858
4859
4860/*
4861 * Scroll the scroll region up by `cLines' lines
4862 */
4863 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004864scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865{
4866 COORD oldcoord = g_coord;
4867
4868 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4869 delete_lines(cLines);
4870
4871 g_coord = oldcoord;
4872}
4873
4874
4875/*
4876 * Set the scroll region
4877 */
4878 static void
4879set_scroll_region(
4880 unsigned left,
4881 unsigned top,
4882 unsigned right,
4883 unsigned bottom)
4884{
4885 if (left >= right
4886 || top >= bottom
4887 || right > (unsigned) Columns - 1
4888 || bottom > (unsigned) Rows - 1)
4889 return;
4890
4891 g_srScrollRegion.Left = left;
4892 g_srScrollRegion.Top = top;
4893 g_srScrollRegion.Right = right;
4894 g_srScrollRegion.Bottom = bottom;
4895}
4896
4897
4898/*
4899 * Insert `cLines' lines at the current cursor position
4900 */
4901 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004902insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903{
4904 SMALL_RECT source;
4905 COORD dest;
4906 CHAR_INFO fill;
4907
4908 dest.X = 0;
4909 dest.Y = g_coord.Y + cLines;
4910
4911 source.Left = 0;
4912 source.Top = g_coord.Y;
4913 source.Right = g_srScrollRegion.Right;
4914 source.Bottom = g_srScrollRegion.Bottom - cLines;
4915
4916 fill.Char.AsciiChar = ' ';
4917 fill.Attributes = g_attrCurrent;
4918
4919 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4920
4921 /* Here we have to deal with a win32 console flake: If the scroll
4922 * region looks like abc and we scroll c to a and fill with d we get
4923 * cbd... if we scroll block c one line at a time to a, we get cdd...
4924 * vim expects cdd consistently... So we have to deal with that
4925 * here... (this also occurs scrolling the same way in the other
4926 * direction). */
4927
4928 if (source.Bottom < dest.Y)
4929 {
4930 COORD coord;
4931
4932 coord.X = 0;
4933 coord.Y = source.Bottom;
4934 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4935 }
4936}
4937
4938
4939/*
4940 * Delete `cLines' lines at the current cursor position
4941 */
4942 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004943delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004944{
4945 SMALL_RECT source;
4946 COORD dest;
4947 CHAR_INFO fill;
4948 int nb;
4949
4950 dest.X = 0;
4951 dest.Y = g_coord.Y;
4952
4953 source.Left = 0;
4954 source.Top = g_coord.Y + cLines;
4955 source.Right = g_srScrollRegion.Right;
4956 source.Bottom = g_srScrollRegion.Bottom;
4957
4958 fill.Char.AsciiChar = ' ';
4959 fill.Attributes = g_attrCurrent;
4960
4961 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4962
4963 /* Here we have to deal with a win32 console flake: If the scroll
4964 * region looks like abc and we scroll c to a and fill with d we get
4965 * cbd... if we scroll block c one line at a time to a, we get cdd...
4966 * vim expects cdd consistently... So we have to deal with that
4967 * here... (this also occurs scrolling the same way in the other
4968 * direction). */
4969
4970 nb = dest.Y + (source.Bottom - source.Top) + 1;
4971
4972 if (nb < source.Top)
4973 {
4974 COORD coord;
4975
4976 coord.X = 0;
4977 coord.Y = nb;
4978 clear_chars(coord, Columns * (source.Top - nb));
4979 }
4980}
4981
4982
4983/*
4984 * Set the cursor position
4985 */
4986 static void
4987gotoxy(
4988 unsigned x,
4989 unsigned y)
4990{
4991 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4992 return;
4993
4994 /* external cursor coords are 1-based; internal are 0-based */
4995 g_coord.X = x - 1;
4996 g_coord.Y = y - 1;
4997 SetConsoleCursorPosition(g_hConOut, g_coord);
4998}
4999
5000
5001/*
5002 * Set the current text attribute = (foreground | background)
5003 * See ../doc/os_win32.txt for the numbers.
5004 */
5005 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005006textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005007{
5008 g_attrCurrent = wAttr;
5009
5010 SetConsoleTextAttribute(g_hConOut, wAttr);
5011}
5012
5013
5014 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005015textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005016{
5017 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
5018
5019 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5020}
5021
5022
5023 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005024textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025{
5026 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
5027
5028 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5029}
5030
5031
5032/*
5033 * restore the default text attribute (whatever we started with)
5034 */
5035 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005036normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005037{
5038 textattr(g_attrDefault);
5039}
5040
5041
5042static WORD g_attrPreStandout = 0;
5043
5044/*
5045 * Make the text standout, by brightening it
5046 */
5047 static void
5048standout(void)
5049{
5050 g_attrPreStandout = g_attrCurrent;
5051 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5052}
5053
5054
5055/*
5056 * Turn off standout mode
5057 */
5058 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005059standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005060{
5061 if (g_attrPreStandout)
5062 {
5063 textattr(g_attrPreStandout);
5064 g_attrPreStandout = 0;
5065 }
5066}
5067
5068
5069/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005070 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005071 */
5072 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005073mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005074{
5075 char_u *p;
5076 int n;
5077
5078 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5079 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5080 if (T_ME[0] == ESC && T_ME[1] == '|')
5081 {
5082 p = T_ME + 2;
5083 n = getdigits(&p);
5084 if (*p == 'm' && n > 0)
5085 {
5086 cterm_normal_fg_color = (n & 0xf) + 1;
5087 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5088 }
5089 }
5090}
5091
5092
5093/*
5094 * visual bell: flash the screen
5095 */
5096 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005097visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005098{
5099 COORD coordOrigin = {0, 0};
5100 WORD attrFlash = ~g_attrCurrent & 0xff;
5101
5102 DWORD dwDummy;
5103 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5104
5105 if (oldattrs == NULL)
5106 return;
5107 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5108 coordOrigin, &dwDummy);
5109 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5110 coordOrigin, &dwDummy);
5111
5112 Sleep(15); /* wait for 15 msec */
5113 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5114 coordOrigin, &dwDummy);
5115 vim_free(oldattrs);
5116}
5117
5118
5119/*
5120 * Make the cursor visible or invisible
5121 */
5122 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005123cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005124{
5125 s_cursor_visible = fVisible;
5126#ifdef MCH_CURSOR_SHAPE
5127 mch_update_cursor();
5128#endif
5129}
5130
5131
5132/*
5133 * write `cchToWrite' characters in `pchBuf' to the screen
5134 * Returns the number of characters actually written (at least one).
5135 */
5136 static BOOL
5137write_chars(
5138 LPCSTR pchBuf,
5139 DWORD cchToWrite)
5140{
5141 COORD coord = g_coord;
5142 DWORD written;
5143
5144 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
5145 coord, &written);
5146 /* When writing fails or didn't write a single character, pretend one
5147 * character was written, otherwise we get stuck. */
5148 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
5149 coord, &written) == 0
5150 || written == 0)
5151 written = 1;
5152
5153 g_coord.X += (SHORT) written;
5154
5155 while (g_coord.X > g_srScrollRegion.Right)
5156 {
5157 g_coord.X -= (SHORT) Columns;
5158 if (g_coord.Y < g_srScrollRegion.Bottom)
5159 g_coord.Y++;
5160 }
5161
5162 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5163
5164 return written;
5165}
5166
5167
5168/*
5169 * mch_write(): write the output buffer to the screen, translating ESC
5170 * sequences into calls to console output routines.
5171 */
5172 void
5173mch_write(
5174 char_u *s,
5175 int len)
5176{
5177 s[len] = NUL;
5178
5179 if (!term_console)
5180 {
5181 write(1, s, (unsigned)len);
5182 return;
5183 }
5184
5185 /* translate ESC | sequences into faked bios calls */
5186 while (len--)
5187 {
5188 /* optimization: use one single write_chars for runs of text,
5189 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005190 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191
5192 if (p_wd)
5193 {
5194 WaitForChar(p_wd);
5195 if (prefix != 0)
5196 prefix = 1;
5197 }
5198
5199 if (prefix != 0)
5200 {
5201 DWORD nWritten;
5202
5203 nWritten = write_chars(s, prefix);
5204#ifdef MCH_WRITE_DUMP
5205 if (fdDump)
5206 {
5207 fputc('>', fdDump);
5208 fwrite(s, sizeof(char_u), nWritten, fdDump);
5209 fputs("<\n", fdDump);
5210 }
5211#endif
5212 len -= (nWritten - 1);
5213 s += nWritten;
5214 }
5215 else if (s[0] == '\n')
5216 {
5217 /* \n, newline: go to the beginning of the next line or scroll */
5218 if (g_coord.Y == g_srScrollRegion.Bottom)
5219 {
5220 scroll(1);
5221 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5222 }
5223 else
5224 {
5225 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5226 }
5227#ifdef MCH_WRITE_DUMP
5228 if (fdDump)
5229 fputs("\\n\n", fdDump);
5230#endif
5231 s++;
5232 }
5233 else if (s[0] == '\r')
5234 {
5235 /* \r, carriage return: go to beginning of line */
5236 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5237#ifdef MCH_WRITE_DUMP
5238 if (fdDump)
5239 fputs("\\r\n", fdDump);
5240#endif
5241 s++;
5242 }
5243 else if (s[0] == '\b')
5244 {
5245 /* \b, backspace: move cursor one position left */
5246 if (g_coord.X > g_srScrollRegion.Left)
5247 g_coord.X--;
5248 else if (g_coord.Y > g_srScrollRegion.Top)
5249 {
5250 g_coord.X = g_srScrollRegion.Right;
5251 g_coord.Y--;
5252 }
5253 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5254#ifdef MCH_WRITE_DUMP
5255 if (fdDump)
5256 fputs("\\b\n", fdDump);
5257#endif
5258 s++;
5259 }
5260 else if (s[0] == '\a')
5261 {
5262 /* \a, bell */
5263 MessageBeep(0xFFFFFFFF);
5264#ifdef MCH_WRITE_DUMP
5265 if (fdDump)
5266 fputs("\\a\n", fdDump);
5267#endif
5268 s++;
5269 }
5270 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5271 {
5272#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005273 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005274#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005275 char_u *p;
5276 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005277
5278 switch (s[2])
5279 {
5280 /* one or two numeric arguments, separated by ';' */
5281
5282 case '0': case '1': case '2': case '3': case '4':
5283 case '5': case '6': case '7': case '8': case '9':
5284 p = s + 2;
5285 arg1 = getdigits(&p); /* no check for length! */
5286 if (p > s + len)
5287 break;
5288
5289 if (*p == ';')
5290 {
5291 ++p;
5292 arg2 = getdigits(&p); /* no check for length! */
5293 if (p > s + len)
5294 break;
5295
5296 if (*p == 'H')
5297 gotoxy(arg2, arg1);
5298 else if (*p == 'r')
5299 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5300 }
5301 else if (*p == 'A')
5302 {
5303 /* move cursor up arg1 lines in same column */
5304 gotoxy(g_coord.X + 1,
5305 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5306 }
5307 else if (*p == 'C')
5308 {
5309 /* move cursor right arg1 columns in same line */
5310 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5311 g_coord.Y + 1);
5312 }
5313 else if (*p == 'H')
5314 {
5315 gotoxy(1, arg1);
5316 }
5317 else if (*p == 'L')
5318 {
5319 insert_lines(arg1);
5320 }
5321 else if (*p == 'm')
5322 {
5323 if (arg1 == 0)
5324 normvideo();
5325 else
5326 textattr((WORD) arg1);
5327 }
5328 else if (*p == 'f')
5329 {
5330 textcolor((WORD) arg1);
5331 }
5332 else if (*p == 'b')
5333 {
5334 textbackground((WORD) arg1);
5335 }
5336 else if (*p == 'M')
5337 {
5338 delete_lines(arg1);
5339 }
5340
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005341 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005342 s = p + 1;
5343 break;
5344
5345
5346 /* Three-character escape sequences */
5347
5348 case 'A':
5349 /* move cursor up one line in same column */
5350 gotoxy(g_coord.X + 1,
5351 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5352 goto got3;
5353
5354 case 'B':
5355 visual_bell();
5356 goto got3;
5357
5358 case 'C':
5359 /* move cursor right one column in same line */
5360 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5361 g_coord.Y + 1);
5362 goto got3;
5363
5364 case 'E':
5365 termcap_mode_end();
5366 goto got3;
5367
5368 case 'F':
5369 standout();
5370 goto got3;
5371
5372 case 'f':
5373 standend();
5374 goto got3;
5375
5376 case 'H':
5377 gotoxy(1, 1);
5378 goto got3;
5379
5380 case 'j':
5381 clear_to_end_of_display();
5382 goto got3;
5383
5384 case 'J':
5385 clear_screen();
5386 goto got3;
5387
5388 case 'K':
5389 clear_to_end_of_line();
5390 goto got3;
5391
5392 case 'L':
5393 insert_lines(1);
5394 goto got3;
5395
5396 case 'M':
5397 delete_lines(1);
5398 goto got3;
5399
5400 case 'S':
5401 termcap_mode_start();
5402 goto got3;
5403
5404 case 'V':
5405 cursor_visible(TRUE);
5406 goto got3;
5407
5408 case 'v':
5409 cursor_visible(FALSE);
5410 goto got3;
5411
5412 got3:
5413 s += 3;
5414 len -= 2;
5415 }
5416
5417#ifdef MCH_WRITE_DUMP
5418 if (fdDump)
5419 {
5420 fputs("ESC | ", fdDump);
5421 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5422 fputc('\n', fdDump);
5423 }
5424#endif
5425 }
5426 else
5427 {
5428 /* Write a single character */
5429 DWORD nWritten;
5430
5431 nWritten = write_chars(s, 1);
5432#ifdef MCH_WRITE_DUMP
5433 if (fdDump)
5434 {
5435 fputc('>', fdDump);
5436 fwrite(s, sizeof(char_u), nWritten, fdDump);
5437 fputs("<\n", fdDump);
5438 }
5439#endif
5440
5441 len -= (nWritten - 1);
5442 s += nWritten;
5443 }
5444 }
5445
5446#ifdef MCH_WRITE_DUMP
5447 if (fdDump)
5448 fflush(fdDump);
5449#endif
5450}
5451
5452#endif /* FEAT_GUI_W32 */
5453
5454
5455/*
5456 * Delay for half a second.
5457 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005458/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005459 void
5460mch_delay(
5461 long msec,
5462 int ignoreinput)
5463{
5464#ifdef FEAT_GUI_W32
5465 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005466#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005467 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005468# ifdef FEAT_MZSCHEME
5469 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5470 {
5471 int towait = p_mzq;
5472
5473 /* if msec is large enough, wait by portions in p_mzq */
5474 while (msec > 0)
5475 {
5476 mzvim_check_threads();
5477 if (msec < towait)
5478 towait = msec;
5479 Sleep(towait);
5480 msec -= towait;
5481 }
5482 }
5483 else
5484# endif
5485 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005486 else
5487 WaitForChar(msec);
5488#endif
5489}
5490
5491
5492/*
5493 * this version of remove is not scared by a readonly (backup) file
5494 * Return 0 for success, -1 for failure.
5495 */
5496 int
5497mch_remove(char_u *name)
5498{
5499#ifdef FEAT_MBYTE
5500 WCHAR *wn = NULL;
5501 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005502#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005503
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005504 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5505
5506#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005507 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5508 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005509 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005510 if (wn != NULL)
5511 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512 n = DeleteFileW(wn) ? 0 : -1;
5513 vim_free(wn);
5514 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5515 return n;
5516 /* Retry with non-wide function (for Windows 98). */
5517 }
5518 }
5519#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005520 return DeleteFile(name) ? 0 : -1;
5521}
5522
5523
5524/*
5525 * check for an "interrupt signal": CTRL-break or CTRL-C
5526 */
5527 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005528mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005529{
5530#ifndef FEAT_GUI_W32 /* never used */
5531 if (g_fCtrlCPressed || g_fCBrkPressed)
5532 {
5533 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5534 got_int = TRUE;
5535 }
5536#endif
5537}
5538
5539
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540#ifdef FEAT_MBYTE
5541/*
5542 * Same code as below, but with wide functions and no comments.
5543 * Return 0 for success, non-zero for failure.
5544 */
5545 int
5546mch_wrename(WCHAR *wold, WCHAR *wnew)
5547{
5548 WCHAR *p;
5549 int i;
5550 WCHAR szTempFile[_MAX_PATH + 1];
5551 WCHAR szNewPath[_MAX_PATH + 1];
5552 HANDLE hf;
5553
5554 if (!mch_windows95())
5555 {
5556 p = wold;
5557 for (i = 0; wold[i] != NUL; ++i)
5558 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5559 && wold[i + 1] != 0)
5560 p = wold + i + 1;
5561 if ((int)(wold + i - p) < 8 || p[6] != '~')
5562 return (MoveFileW(wold, wnew) == 0);
5563 }
5564
5565 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5566 return -1;
5567 *p = NUL;
5568
5569 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5570 return -2;
5571
5572 if (!DeleteFileW(szTempFile))
5573 return -3;
5574
5575 if (!MoveFileW(wold, szTempFile))
5576 return -4;
5577
5578 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5579 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5580 return -5;
5581 if (!CloseHandle(hf))
5582 return -6;
5583
5584 if (!MoveFileW(szTempFile, wnew))
5585 {
5586 (void)MoveFileW(szTempFile, wold);
5587 return -7;
5588 }
5589
5590 DeleteFileW(szTempFile);
5591
5592 if (!DeleteFileW(wold))
5593 return -8;
5594
5595 return 0;
5596}
5597#endif
5598
5599
5600/*
5601 * mch_rename() works around a bug in rename (aka MoveFile) in
5602 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5603 * file whose short file name is "FOO.BAR" (its long file name will
5604 * be correct: "foo.bar~"). Because a file can be accessed by
5605 * either its SFN or its LFN, "foo.bar" has effectively been
5606 * renamed to "foo.bar", which is not at all what was wanted. This
5607 * seems to happen only when renaming files with three-character
5608 * extensions by appending a suffix that does not include ".".
5609 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5610 *
5611 * There is another problem, which isn't really a bug but isn't right either:
5612 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5613 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5614 * service pack 6. Doesn't seem to happen on Windows 98.
5615 *
5616 * Like rename(), returns 0 upon success, non-zero upon failure.
5617 * Should probably set errno appropriately when errors occur.
5618 */
5619 int
5620mch_rename(
5621 const char *pszOldFile,
5622 const char *pszNewFile)
5623{
5624 char szTempFile[_MAX_PATH+1];
5625 char szNewPath[_MAX_PATH+1];
5626 char *pszFilePart;
5627 HANDLE hf;
5628#ifdef FEAT_MBYTE
5629 WCHAR *wold = NULL;
5630 WCHAR *wnew = NULL;
5631 int retval = -1;
5632
5633 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5634 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005635 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5636 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005637 if (wold != NULL && wnew != NULL)
5638 retval = mch_wrename(wold, wnew);
5639 vim_free(wold);
5640 vim_free(wnew);
5641 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5642 return retval;
5643 /* Retry with non-wide function (for Windows 98). */
5644 }
5645#endif
5646
5647 /*
5648 * No need to play tricks if not running Windows 95, unless the file name
5649 * contains a "~" as the seventh character.
5650 */
5651 if (!mch_windows95())
5652 {
5653 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5654 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5655 return rename(pszOldFile, pszNewFile);
5656 }
5657
5658 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5659 * a directory, no error is returned and pszFilePart will be NULL. */
5660 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5661 || pszFilePart == NULL)
5662 return -1;
5663 *pszFilePart = NUL;
5664
5665 /* Get (and create) a unique temporary file name in directory of new file */
5666 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5667 return -2;
5668
5669 /* blow the temp file away */
5670 if (!DeleteFile(szTempFile))
5671 return -3;
5672
5673 /* rename old file to the temp file */
5674 if (!MoveFile(pszOldFile, szTempFile))
5675 return -4;
5676
5677 /* now create an empty file called pszOldFile; this prevents the operating
5678 * system using pszOldFile as an alias (SFN) if we're renaming within the
5679 * same directory. For example, we're editing a file called
5680 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5681 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5682 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005683 * cause all sorts of problems later in buf_write(). So, we create an
5684 * empty file called filena~1.txt and the system will have to find some
5685 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005686 */
5687 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5688 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5689 return -5;
5690 if (!CloseHandle(hf))
5691 return -6;
5692
5693 /* rename the temp file to the new file */
5694 if (!MoveFile(szTempFile, pszNewFile))
5695 {
5696 /* Renaming failed. Rename the file back to its old name, so that it
5697 * looks like nothing happened. */
5698 (void)MoveFile(szTempFile, pszOldFile);
5699
5700 return -7;
5701 }
5702
5703 /* Seems to be left around on Novell filesystems */
5704 DeleteFile(szTempFile);
5705
5706 /* finally, remove the empty old file */
5707 if (!DeleteFile(pszOldFile))
5708 return -8;
5709
5710 return 0; /* success */
5711}
5712
5713/*
5714 * Get the default shell for the current hardware platform
5715 */
5716 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005717default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005718{
5719 char* psz = NULL;
5720
5721 PlatformId();
5722
5723 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5724 psz = "cmd.exe";
5725 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5726 psz = "command.com";
5727
5728 return psz;
5729}
5730
5731/*
5732 * mch_access() extends access() to do more detailed check on network drives.
5733 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5734 */
5735 int
5736mch_access(char *n, int p)
5737{
5738 HANDLE hFile;
5739 DWORD am;
5740 int retval = -1; /* default: fail */
5741#ifdef FEAT_MBYTE
5742 WCHAR *wn = NULL;
5743
5744 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005745 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005746#endif
5747
5748 if (mch_isdir(n))
5749 {
5750 char TempName[_MAX_PATH + 16] = "";
5751#ifdef FEAT_MBYTE
5752 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5753#endif
5754
5755 if (p & R_OK)
5756 {
5757 /* Read check is performed by seeing if we can do a find file on
5758 * the directory for any file. */
5759#ifdef FEAT_MBYTE
5760 if (wn != NULL)
5761 {
5762 int i;
5763 WIN32_FIND_DATAW d;
5764
5765 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5766 TempNameW[i] = wn[i];
5767 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5768 TempNameW[i++] = '\\';
5769 TempNameW[i++] = '*';
5770 TempNameW[i++] = 0;
5771
5772 hFile = FindFirstFileW(TempNameW, &d);
5773 if (hFile == INVALID_HANDLE_VALUE)
5774 {
5775 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5776 goto getout;
5777
5778 /* Retry with non-wide function (for Windows 98). */
5779 vim_free(wn);
5780 wn = NULL;
5781 }
5782 else
5783 (void)FindClose(hFile);
5784 }
5785 if (wn == NULL)
5786#endif
5787 {
5788 char *pch;
5789 WIN32_FIND_DATA d;
5790
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005791 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005792 pch = TempName + STRLEN(TempName) - 1;
5793 if (*pch != '\\' && *pch != '/')
5794 *++pch = '\\';
5795 *++pch = '*';
5796 *++pch = NUL;
5797
5798 hFile = FindFirstFile(TempName, &d);
5799 if (hFile == INVALID_HANDLE_VALUE)
5800 goto getout;
5801 (void)FindClose(hFile);
5802 }
5803 }
5804
5805 if (p & W_OK)
5806 {
5807 /* Trying to create a temporary file in the directory should catch
5808 * directories on read-only network shares. However, in
5809 * directories whose ACL allows writes but denies deletes will end
5810 * up keeping the temporary file :-(. */
5811#ifdef FEAT_MBYTE
5812 if (wn != NULL)
5813 {
5814 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5815 {
5816 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5817 goto getout;
5818
5819 /* Retry with non-wide function (for Windows 98). */
5820 vim_free(wn);
5821 wn = NULL;
5822 }
5823 else
5824 DeleteFileW(TempNameW);
5825 }
5826 if (wn == NULL)
5827#endif
5828 {
5829 if (!GetTempFileName(n, "VIM", 0, TempName))
5830 goto getout;
5831 mch_remove((char_u *)TempName);
5832 }
5833 }
5834 }
5835 else
5836 {
5837 /* Trying to open the file for the required access does ACL, read-only
5838 * network share, and file attribute checks. */
5839 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5840 | ((p & R_OK) ? GENERIC_READ : 0);
5841#ifdef FEAT_MBYTE
5842 if (wn != NULL)
5843 {
5844 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5845 if (hFile == INVALID_HANDLE_VALUE
5846 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5847 {
5848 /* Retry with non-wide function (for Windows 98). */
5849 vim_free(wn);
5850 wn = NULL;
5851 }
5852 }
5853 if (wn == NULL)
5854#endif
5855 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5856 if (hFile == INVALID_HANDLE_VALUE)
5857 goto getout;
5858 CloseHandle(hFile);
5859 }
5860
5861 retval = 0; /* success */
5862getout:
5863#ifdef FEAT_MBYTE
5864 vim_free(wn);
5865#endif
5866 return retval;
5867}
5868
5869#if defined(FEAT_MBYTE) || defined(PROTO)
5870/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005871 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005872 */
5873 int
5874mch_open(char *name, int flags, int mode)
5875{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005876 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5877# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005878 WCHAR *wn;
5879 int f;
5880
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005881 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005882 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005883 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005884 if (wn != NULL)
5885 {
5886 f = _wopen(wn, flags, mode);
5887 vim_free(wn);
5888 if (f >= 0)
5889 return f;
5890 /* Retry with non-wide function (for Windows 98). Can't use
5891 * GetLastError() here and it's unclear what errno gets set to if
5892 * the _wopen() fails for missing wide functions. */
5893 }
5894 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005895# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005896
5897 return open(name, flags, mode);
5898}
5899
5900/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005901 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902 */
5903 FILE *
5904mch_fopen(char *name, char *mode)
5905{
5906 WCHAR *wn, *wm;
5907 FILE *f = NULL;
5908
5909 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5910# ifdef __BORLANDC__
5911 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5912 && g_PlatformId == VER_PLATFORM_WIN32_NT
5913# endif
5914 )
5915 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005916# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005917 /* Work around an annoying assertion in the Microsoft debug CRT
5918 * when mode's text/binary setting doesn't match _get_fmode(). */
5919 char newMode = mode[strlen(mode) - 1];
5920 int oldMode = 0;
5921
5922 _get_fmode(&oldMode);
5923 if (newMode == 't')
5924 _set_fmode(_O_TEXT);
5925 else if (newMode == 'b')
5926 _set_fmode(_O_BINARY);
5927# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005928 wn = enc_to_utf16(name, NULL);
5929 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930 if (wn != NULL && wm != NULL)
5931 f = _wfopen(wn, wm);
5932 vim_free(wn);
5933 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005934
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005935# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005936 _set_fmode(oldMode);
5937# endif
5938
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939 if (f != NULL)
5940 return f;
5941 /* Retry with non-wide function (for Windows 98). Can't use
5942 * GetLastError() here and it's unclear what errno gets set to if
5943 * the _wfopen() fails for missing wide functions. */
5944 }
5945
5946 return fopen(name, mode);
5947}
5948#endif
5949
5950#ifdef FEAT_MBYTE
5951/*
5952 * SUB STREAM (aka info stream) handling:
5953 *
5954 * NTFS can have sub streams for each file. Normal contents of file is
5955 * stored in the main stream, and extra contents (author information and
5956 * title and so on) can be stored in sub stream. After Windows 2000, user
5957 * can access and store those informations in sub streams via explorer's
5958 * property menuitem in right click menu. Those informations in sub streams
5959 * were lost when copying only the main stream. So we have to copy sub
5960 * streams.
5961 *
5962 * Incomplete explanation:
5963 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5964 * More useful info and an example:
5965 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5966 */
5967
5968/*
5969 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5970 * and write to stream "substream" of file "to".
5971 * Errors are ignored.
5972 */
5973 static void
5974copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5975{
5976 HANDLE hTo;
5977 WCHAR *to_name;
5978
5979 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5980 wcscpy(to_name, to);
5981 wcscat(to_name, substream);
5982
5983 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5984 FILE_ATTRIBUTE_NORMAL, NULL);
5985 if (hTo != INVALID_HANDLE_VALUE)
5986 {
5987 long done;
5988 DWORD todo;
5989 DWORD readcnt, written;
5990 char buf[4096];
5991
5992 /* Copy block of bytes at a time. Abort when something goes wrong. */
5993 for (done = 0; done < len; done += written)
5994 {
5995 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005996 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5997 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5999 FALSE, FALSE, context)
6000 || readcnt != todo
6001 || !WriteFile(hTo, buf, todo, &written, NULL)
6002 || written != todo)
6003 break;
6004 }
6005 CloseHandle(hTo);
6006 }
6007
6008 free(to_name);
6009}
6010
6011/*
6012 * Copy info streams from file "from" to file "to".
6013 */
6014 static void
6015copy_infostreams(char_u *from, char_u *to)
6016{
6017 WCHAR *fromw;
6018 WCHAR *tow;
6019 HANDLE sh;
6020 WIN32_STREAM_ID sid;
6021 int headersize;
6022 WCHAR streamname[_MAX_PATH];
6023 DWORD readcount;
6024 void *context = NULL;
6025 DWORD lo, hi;
6026 int len;
6027
6028 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006029 fromw = enc_to_utf16(from, NULL);
6030 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031 if (fromw != NULL && tow != NULL)
6032 {
6033 /* Open the file for reading. */
6034 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6035 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6036 if (sh != INVALID_HANDLE_VALUE)
6037 {
6038 /* Use BackupRead() to find the info streams. Repeat until we
6039 * have done them all.*/
6040 for (;;)
6041 {
6042 /* Get the header to find the length of the stream name. If
6043 * the "readcount" is zero we have done all info streams. */
6044 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006045 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6047 &readcount, FALSE, FALSE, &context)
6048 || readcount == 0)
6049 break;
6050
6051 /* We only deal with streams that have a name. The normal
6052 * file data appears to be without a name, even though docs
6053 * suggest it is called "::$DATA". */
6054 if (sid.dwStreamNameSize > 0)
6055 {
6056 /* Read the stream name. */
6057 if (!BackupRead(sh, (LPBYTE)streamname,
6058 sid.dwStreamNameSize,
6059 &readcount, FALSE, FALSE, &context))
6060 break;
6061
6062 /* Copy an info stream with a name ":anything:$DATA".
6063 * Skip "::$DATA", it has no stream name (examples suggest
6064 * it might be used for the normal file contents).
6065 * Note that BackupRead() counts bytes, but the name is in
6066 * wide characters. */
6067 len = readcount / sizeof(WCHAR);
6068 streamname[len] = 0;
6069 if (len > 7 && wcsicmp(streamname + len - 6,
6070 L":$DATA") == 0)
6071 {
6072 streamname[len - 6] = 0;
6073 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006074 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006075 }
6076 }
6077
6078 /* Advance to the next stream. We might try seeking too far,
6079 * but BackupSeek() doesn't skip over stream borders, thus
6080 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006081 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006082 &lo, &hi, &context);
6083 }
6084
6085 /* Clear the context. */
6086 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6087
6088 CloseHandle(sh);
6089 }
6090 }
6091 vim_free(fromw);
6092 vim_free(tow);
6093}
6094#endif
6095
6096/*
6097 * Copy file attributes from file "from" to file "to".
6098 * For Windows NT and later we copy info streams.
6099 * Always returns zero, errors are ignored.
6100 */
6101 int
6102mch_copy_file_attribute(char_u *from, char_u *to)
6103{
6104#ifdef FEAT_MBYTE
6105 /* File streams only work on Windows NT and later. */
6106 PlatformId();
6107 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6108 copy_infostreams(from, to);
6109#endif
6110 return 0;
6111}
6112
6113#if defined(MYRESETSTKOFLW) || defined(PROTO)
6114/*
6115 * Recreate a destroyed stack guard page in win32.
6116 * Written by Benjamin Peterson.
6117 */
6118
6119/* These magic numbers are from the MS header files */
6120#define MIN_STACK_WIN9X 17
6121#define MIN_STACK_WINNT 2
6122
6123/*
6124 * This function does the same thing as _resetstkoflw(), which is only
6125 * available in DevStudio .net and later.
6126 * Returns 0 for failure, 1 for success.
6127 */
6128 int
6129myresetstkoflw(void)
6130{
6131 BYTE *pStackPtr;
6132 BYTE *pGuardPage;
6133 BYTE *pStackBase;
6134 BYTE *pLowestPossiblePage;
6135 MEMORY_BASIC_INFORMATION mbi;
6136 SYSTEM_INFO si;
6137 DWORD nPageSize;
6138 DWORD dummy;
6139
6140 /* This code will not work on win32s. */
6141 PlatformId();
6142 if (g_PlatformId == VER_PLATFORM_WIN32s)
6143 return 0;
6144
6145 /* We need to know the system page size. */
6146 GetSystemInfo(&si);
6147 nPageSize = si.dwPageSize;
6148
6149 /* ...and the current stack pointer */
6150 pStackPtr = (BYTE*)_alloca(1);
6151
6152 /* ...and the base of the stack. */
6153 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6154 return 0;
6155 pStackBase = (BYTE*)mbi.AllocationBase;
6156
6157 /* ...and the page thats min_stack_req pages away from stack base; this is
6158 * the lowest page we could use. */
6159 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6160 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6161
6162 /* On Win95, we want the next page down from the end of the stack. */
6163 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6164 {
6165 /* Find the page that's only 1 page down from the page that the stack
6166 * ptr is in. */
6167 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6168 / (DWORD)nPageSize) - 1));
6169 if (pGuardPage < pLowestPossiblePage)
6170 return 0;
6171
6172 /* Apply the noaccess attribute to the page -- there's no guard
6173 * attribute in win95-type OSes. */
6174 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6175 return 0;
6176 }
6177 else
6178 {
6179 /* On NT, however, we want the first committed page in the stack Start
6180 * at the stack base and move forward through memory until we find a
6181 * committed block. */
6182 BYTE *pBlock = pStackBase;
6183
Bram Moolenaara466c992005-07-09 21:03:22 +00006184 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006185 {
6186 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6187 return 0;
6188
6189 pBlock += mbi.RegionSize;
6190
6191 if (mbi.State & MEM_COMMIT)
6192 break;
6193 }
6194
6195 /* mbi now describes the first committed block in the stack. */
6196 if (mbi.Protect & PAGE_GUARD)
6197 return 1;
6198
6199 /* decide where the guard page should start */
6200 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6201 pGuardPage = pLowestPossiblePage;
6202 else
6203 pGuardPage = (BYTE*)mbi.BaseAddress;
6204
6205 /* allocate the guard page */
6206 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6207 return 0;
6208
6209 /* apply the guard attribute to the page */
6210 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6211 &dummy))
6212 return 0;
6213 }
6214
6215 return 1;
6216}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006217#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006219
6220#if defined(FEAT_MBYTE) || defined(PROTO)
6221/*
6222 * The command line arguments in UCS2
6223 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006224static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006225static LPWSTR *ArglistW = NULL;
6226static int global_argc = 0;
6227static char **global_argv;
6228
6229static int used_file_argc = 0; /* last argument in global_argv[] used
6230 for the argument list. */
6231static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6232 command line arguments added to
6233 the argument list */
6234static int used_file_count = 0; /* nr of entries in used_file_indexes */
6235static int used_file_literal = FALSE; /* take file names literally */
6236static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006237static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006238static int used_alist_count = 0;
6239
6240
6241/*
6242 * Get the command line arguments. Unicode version.
6243 * Returns argc. Zero when something fails.
6244 */
6245 int
6246get_cmd_argsW(char ***argvp)
6247{
6248 char **argv = NULL;
6249 int argc = 0;
6250 int i;
6251
6252 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6253 if (ArglistW != NULL)
6254 {
6255 argv = malloc((nArgsW + 1) * sizeof(char *));
6256 if (argv != NULL)
6257 {
6258 argc = nArgsW;
6259 argv[argc] = NULL;
6260 for (i = 0; i < argc; ++i)
6261 {
6262 int len;
6263
6264 /* Convert each Unicode argument to the current codepage. */
6265 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006266 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006267 (LPSTR *)&argv[i], &len, 0, 0);
6268 if (argv[i] == NULL)
6269 {
6270 /* Out of memory, clear everything. */
6271 while (i > 0)
6272 free(argv[--i]);
6273 free(argv);
6274 argc = 0;
6275 }
6276 }
6277 }
6278 }
6279
6280 global_argc = argc;
6281 global_argv = argv;
6282 if (argc > 0)
6283 used_file_indexes = malloc(argc * sizeof(int));
6284
6285 if (argvp != NULL)
6286 *argvp = argv;
6287 return argc;
6288}
6289
6290 void
6291free_cmd_argsW(void)
6292{
6293 if (ArglistW != NULL)
6294 {
6295 GlobalFree(ArglistW);
6296 ArglistW = NULL;
6297 }
6298}
6299
6300/*
6301 * Remember "name" is an argument that was added to the argument list.
6302 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6303 * is called.
6304 */
6305 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006306used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006307{
6308 int i;
6309
6310 if (used_file_indexes == NULL)
6311 return;
6312 for (i = used_file_argc + 1; i < global_argc; ++i)
6313 if (STRCMP(global_argv[i], name) == 0)
6314 {
6315 used_file_argc = i;
6316 used_file_indexes[used_file_count++] = i;
6317 break;
6318 }
6319 used_file_literal = literal;
6320 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006321 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006322}
6323
6324/*
6325 * Remember the length of the argument list as it was. If it changes then we
6326 * leave it alone when 'encoding' is set.
6327 */
6328 void
6329set_alist_count(void)
6330{
6331 used_alist_count = GARGCOUNT;
6332}
6333
6334/*
6335 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6336 * has been changed while starting up. Use the UCS-2 command line arguments
6337 * and convert them to 'encoding'.
6338 */
6339 void
6340fix_arg_enc(void)
6341{
6342 int i;
6343 int idx;
6344 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006345 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006346
6347 /* Safety checks:
6348 * - if argument count differs between the wide and non-wide argument
6349 * list, something must be wrong.
6350 * - the file name arguments must have been located.
6351 * - the length of the argument list wasn't changed by the user.
6352 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006353 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006354 || ArglistW == NULL
6355 || used_file_indexes == NULL
6356 || used_file_count == 0
6357 || used_alist_count != GARGCOUNT)
6358 return;
6359
Bram Moolenaar86b68352004-12-27 21:59:20 +00006360 /* Remember the buffer numbers for the arguments. */
6361 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6362 if (fnum_list == NULL)
6363 return; /* out of memory */
6364 for (i = 0; i < GARGCOUNT; ++i)
6365 fnum_list[i] = GARGLIST[i].ae_fnum;
6366
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006367 /* Clear the argument list. Make room for the new arguments. */
6368 alist_clear(&global_alist);
6369 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006370 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006371
6372 for (i = 0; i < used_file_count; ++i)
6373 {
6374 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006375 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006376 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006377 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006378#ifdef FEAT_DIFF
6379 /* When using diff mode may need to concatenate file name to
6380 * directory name. Just like it's done in main(). */
6381 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6382 && !mch_isdir(alist_name(&GARGLIST[0])))
6383 {
6384 char_u *r;
6385
6386 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6387 if (r != NULL)
6388 {
6389 vim_free(str);
6390 str = r;
6391 }
6392 }
6393#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006394 /* Re-use the old buffer by renaming it. When not using literal
6395 * names it's done by alist_expand() below. */
6396 if (used_file_literal)
6397 buf_set_name(fnum_list[i], str);
6398
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006399 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006400 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006401 }
6402
6403 if (!used_file_literal)
6404 {
6405 /* Now expand wildcards in the arguments. */
6406 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6407 * filename characters but are excluded from 'isfname' to make
6408 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6409 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006410 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006411 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6412 }
6413
6414 /* If wildcard expansion failed, we are editing the first file of the
6415 * arglist and there is no file name: Edit the first argument now. */
6416 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6417 {
6418 do_cmdline_cmd((char_u *)":rewind");
6419 if (GARGCOUNT == 1 && used_file_full_path)
6420 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6421 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006422
6423 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006424}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006425#endif