blob: b006a0db21ae00dba87423e794d50cf037a42e85 [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;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002512 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002513 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++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002531 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002532 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002533
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++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002676 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002677 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002678
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
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002771#ifdef FEAT_MBYTE
2772 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2773 {
2774 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2775 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2776
2777 if (GetUserNameW(wszUserName, &wcch))
2778 {
2779 char_u *p = utf16_to_enc(wszUserName, NULL);
2780
2781 if (p != NULL)
2782 {
2783 vim_strncpy(s, p, len - 1);
2784 vim_free(p);
2785 return OK;
2786 }
2787 }
2788 /* Retry with non-wide function (for Windows 98). */
2789 }
2790#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002791 if (GetUserName(szUserName, &cch))
2792 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002793 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002794 return OK;
2795 }
2796 s[0] = NUL;
2797 return FAIL;
2798}
2799
2800
2801/*
2802 * Insert host name in s[len].
2803 */
2804 void
2805mch_get_host_name(
2806 char_u *s,
2807 int len)
2808{
2809 DWORD cch = len;
2810
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002811#ifdef FEAT_MBYTE
2812 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2813 {
2814 WCHAR wszHostName[256 + 1];
2815 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2816
2817 if (GetComputerNameW(wszHostName, &wcch))
2818 {
2819 char_u *p = utf16_to_enc(wszHostName, NULL);
2820
2821 if (p != NULL)
2822 {
2823 vim_strncpy(s, p, len - 1);
2824 vim_free(p);
2825 return;
2826 }
2827 }
2828 /* Retry with non-wide function (for Windows 98). */
2829 }
2830#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002832 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833}
2834
2835
2836/*
2837 * return process ID
2838 */
2839 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002840mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002841{
2842 return (long)GetCurrentProcessId();
2843}
2844
2845
2846/*
2847 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2848 * Return OK for success, FAIL for failure.
2849 */
2850 int
2851mch_dirname(
2852 char_u *buf,
2853 int len)
2854{
2855 /*
2856 * Originally this was:
2857 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2858 * But the Win32s known bug list says that getcwd() doesn't work
2859 * so use the Win32 system call instead. <Negri>
2860 */
2861#ifdef FEAT_MBYTE
2862 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2863 {
2864 WCHAR wbuf[_MAX_PATH + 1];
2865
2866 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2867 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002868 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869
2870 if (p != NULL)
2871 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002872 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002873 vim_free(p);
2874 return OK;
2875 }
2876 }
2877 /* Retry with non-wide function (for Windows 98). */
2878 }
2879#endif
2880 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2881}
2882
2883/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002884 * Get file permissions for "name".
2885 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886 */
2887 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002888mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002889{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002890 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002891 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002892
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002893 n = mch_stat(name, &st);
Bram Moolenaarffa22202013-11-21 12:34:11 +01002894 return n == 0 ? (long)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895}
2896
2897
2898/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002899 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002900 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002901 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002902 */
2903 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002904mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002906 long n = -1;
2907
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908#ifdef FEAT_MBYTE
2909 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2910 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002911 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912
2913 if (p != NULL)
2914 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002915 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002916 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002917 if (n == -1 && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2918 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002919 /* Retry with non-wide function (for Windows 98). */
2920 }
2921 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002922 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002924 n = _chmod(name, perm);
2925 if (n == -1)
2926 return FAIL;
2927
2928 win32_set_archive(name);
2929
2930 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931}
2932
2933/*
2934 * Set hidden flag for "name".
2935 */
2936 void
2937mch_hide(char_u *name)
2938{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002939 int attrs = win32_getattrs(name);
2940 if (attrs == -1)
2941 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002943 attrs |= FILE_ATTRIBUTE_HIDDEN;
2944 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945}
2946
2947/*
2948 * return TRUE if "name" is a directory
2949 * return FALSE if "name" is not a directory or upon error
2950 */
2951 int
2952mch_isdir(char_u *name)
2953{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002954 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955
2956 if (f == -1)
2957 return FALSE; /* file does not exist at all */
2958
2959 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2960}
2961
2962/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002963 * Create directory "name".
2964 * Return 0 on success, -1 on error.
2965 */
2966 int
2967mch_mkdir(char_u *name)
2968{
2969#ifdef FEAT_MBYTE
2970 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2971 {
2972 WCHAR *p;
2973 int retval;
2974
2975 p = enc_to_utf16(name, NULL);
2976 if (p == NULL)
2977 return -1;
2978 retval = _wmkdir(p);
2979 vim_free(p);
2980 return retval;
2981 }
2982#endif
2983 return _mkdir(name);
2984}
2985
2986/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002987 * Return TRUE if file "fname" has more than one link.
2988 */
2989 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002990mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002991{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002992 BY_HANDLE_FILE_INFORMATION info;
2993
2994 return win32_fileinfo(fname, &info) == FILEINFO_OK
2995 && info.nNumberOfLinks > 1;
2996}
2997
2998/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002999 * Return TRUE if file "fname" is a symbolic link.
3000 */
3001 int
3002mch_is_symbolic_link(char_u *fname)
3003{
3004 HANDLE hFind;
3005 int res = FALSE;
3006 WIN32_FIND_DATAA findDataA;
3007 DWORD fileFlags = 0, reparseTag = 0;
3008#ifdef FEAT_MBYTE
3009 WCHAR *wn = NULL;
3010 WIN32_FIND_DATAW findDataW;
3011
3012 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3013 wn = enc_to_utf16(fname, NULL);
3014 if (wn != NULL)
3015 {
3016 hFind = FindFirstFileW(wn, &findDataW);
3017 vim_free(wn);
3018 if (hFind == INVALID_HANDLE_VALUE
3019 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3020 {
3021 /* Retry with non-wide function (for Windows 98). */
3022 hFind = FindFirstFile(fname, &findDataA);
3023 if (hFind != INVALID_HANDLE_VALUE)
3024 {
3025 fileFlags = findDataA.dwFileAttributes;
3026 reparseTag = findDataA.dwReserved0;
3027 }
3028 }
3029 else
3030 {
3031 fileFlags = findDataW.dwFileAttributes;
3032 reparseTag = findDataW.dwReserved0;
3033 }
3034 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003035 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003036#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003037 {
3038 hFind = FindFirstFile(fname, &findDataA);
3039 if (hFind != INVALID_HANDLE_VALUE)
3040 {
3041 fileFlags = findDataA.dwFileAttributes;
3042 reparseTag = findDataA.dwReserved0;
3043 }
3044 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003045
3046 if (hFind != INVALID_HANDLE_VALUE)
3047 FindClose(hFind);
3048
3049 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3050 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3051 res = TRUE;
3052
3053 return res;
3054}
3055
3056/*
3057 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3058 * link.
3059 */
3060 int
3061mch_is_linked(char_u *fname)
3062{
3063 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3064 return TRUE;
3065 return FALSE;
3066}
3067
3068/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003069 * Get the by-handle-file-information for "fname".
3070 * Returns FILEINFO_OK when OK.
3071 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3072 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3073 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3074 */
3075 int
3076win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3077{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003078 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003079 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003080#ifdef FEAT_MBYTE
3081 WCHAR *wn = NULL;
3082
3083 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003084 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003085 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003086 if (wn == NULL)
3087 res = FILEINFO_ENC_FAIL;
3088 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003089 if (wn != NULL)
3090 {
3091 hFile = CreateFileW(wn, /* file name */
3092 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003093 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003094 NULL, /* security descriptor */
3095 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003096 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003097 NULL); /* handle to template file */
3098 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003099 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003100 {
3101 /* Retry with non-wide function (for Windows 98). */
3102 vim_free(wn);
3103 wn = NULL;
3104 }
3105 }
3106 if (wn == NULL)
3107#endif
3108 hFile = CreateFile(fname, /* file name */
3109 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003110 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003111 NULL, /* security descriptor */
3112 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003113 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003114 NULL); /* handle to template file */
3115
3116 if (hFile != INVALID_HANDLE_VALUE)
3117 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003118 if (GetFileInformationByHandle(hFile, info) != 0)
3119 res = FILEINFO_OK;
3120 else
3121 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003122 CloseHandle(hFile);
3123 }
3124
3125#ifdef FEAT_MBYTE
3126 vim_free(wn);
3127#endif
3128 return res;
3129}
3130
3131/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003132 * get file attributes for `name'
3133 * -1 : error
3134 * else FILE_ATTRIBUTE_* defined in winnt.h
3135 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003136 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003137win32_getattrs(char_u *name)
3138{
3139 int attr;
3140#ifdef FEAT_MBYTE
3141 WCHAR *p = NULL;
3142
3143 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3144 p = enc_to_utf16(name, NULL);
3145
3146 if (p != NULL)
3147 {
3148 attr = GetFileAttributesW(p);
3149 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3150 {
3151 /* Retry with non-wide function (for Windows 98). */
3152 vim_free(p);
3153 p = NULL;
3154 }
3155 }
3156 if (p == NULL)
3157#endif
3158 attr = GetFileAttributes((char *)name);
3159#ifdef FEAT_MBYTE
3160 vim_free(p);
3161#endif
3162 return attr;
3163}
3164
3165/*
3166 * set file attributes for `name' to `attrs'
3167 *
3168 * return -1 for failure, 0 otherwise
3169 */
3170 static
3171 int
3172win32_setattrs(char_u *name, int attrs)
3173{
3174 int res;
3175#ifdef FEAT_MBYTE
3176 WCHAR *p = NULL;
3177
3178 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3179 p = enc_to_utf16(name, NULL);
3180
3181 if (p != NULL)
3182 {
3183 res = SetFileAttributesW(p, attrs);
3184 if (res == FALSE
3185 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3186 {
3187 /* Retry with non-wide function (for Windows 98). */
3188 vim_free(p);
3189 p = NULL;
3190 }
3191 }
3192 if (p == NULL)
3193#endif
3194 res = SetFileAttributes((char *)name, attrs);
3195#ifdef FEAT_MBYTE
3196 vim_free(p);
3197#endif
3198 return res ? 0 : -1;
3199}
3200
3201/*
3202 * Set archive flag for "name".
3203 */
3204 static
3205 int
3206win32_set_archive(char_u *name)
3207{
3208 int attrs = win32_getattrs(name);
3209 if (attrs == -1)
3210 return -1;
3211
3212 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3213 return win32_setattrs(name, attrs);
3214}
3215
3216/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217 * Return TRUE if file or directory "name" is writable (not readonly).
3218 * Strange semantics of Win32: a readonly directory is writable, but you can't
3219 * delete a file. Let's say this means it is writable.
3220 */
3221 int
3222mch_writable(char_u *name)
3223{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003224 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003225
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003226 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3227 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003228}
3229
Bram Moolenaar071d4272004-06-13 20:20:40 +00003230/*
3231 * Return 1 if "name" can be executed, 0 if not.
3232 * Return -1 if unknown.
3233 */
3234 int
3235mch_can_exe(char_u *name)
3236{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003237 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003238 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003239 char_u *p;
3240
3241 if (len >= _MAX_PATH) /* safety check */
3242 return FALSE;
3243
3244 /* If there already is an extension try using the name directly. Also do
3245 * this with a Unix-shell like 'shell'. */
3246 if (vim_strchr(gettail(name), '.') != NULL
3247 || strstr((char *)gettail(p_sh), "sh") != NULL)
3248 if (executable_exists((char *)name))
3249 return TRUE;
3250
3251 /*
3252 * Loop over all extensions in $PATHEXT.
3253 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003254 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003255 p = mch_getenv("PATHEXT");
3256 if (p == NULL)
3257 p = (char_u *)".com;.exe;.bat;.cmd";
3258 while (*p)
3259 {
3260 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3261 {
3262 /* A single "." means no extension is added. */
3263 buf[len] = NUL;
3264 ++p;
3265 if (*p)
3266 ++p;
3267 }
3268 else
3269 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
3270 if (executable_exists((char *)buf))
3271 return TRUE;
3272 }
3273 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003274}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003275
3276/*
3277 * Check what "name" is:
3278 * NODE_NORMAL: file or directory (or doesn't exist)
3279 * NODE_WRITABLE: writable device, socket, fifo, etc.
3280 * NODE_OTHER: non-writable things
3281 */
3282 int
3283mch_nodetype(char_u *name)
3284{
3285 HANDLE hFile;
3286 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003287#ifdef FEAT_MBYTE
3288 WCHAR *wn = NULL;
3289#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003290
Bram Moolenaar043545e2006-10-10 16:44:07 +00003291 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3292 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3293 * here. */
3294 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3295 return NODE_WRITABLE;
3296
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003297#ifdef FEAT_MBYTE
3298 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3299 {
3300 wn = enc_to_utf16(name, NULL);
3301 if (wn != NULL)
3302 {
3303 hFile = CreateFileW(wn, /* file name */
3304 GENERIC_WRITE, /* access mode */
3305 0, /* share mode */
3306 NULL, /* security descriptor */
3307 OPEN_EXISTING, /* creation disposition */
3308 0, /* file attributes */
3309 NULL); /* handle to template file */
3310 if (hFile == INVALID_HANDLE_VALUE
3311 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3312 {
3313 /* Retry with non-wide function (for Windows 98). */
3314 vim_free(wn);
3315 wn = NULL;
3316 }
3317 }
3318 }
3319 if (wn == NULL)
3320#endif
3321 hFile = CreateFile(name, /* file name */
3322 GENERIC_WRITE, /* access mode */
3323 0, /* share mode */
3324 NULL, /* security descriptor */
3325 OPEN_EXISTING, /* creation disposition */
3326 0, /* file attributes */
3327 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003329#ifdef FEAT_MBYTE
3330 vim_free(wn);
3331#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003332 if (hFile == INVALID_HANDLE_VALUE)
3333 return NODE_NORMAL;
3334
3335 type = GetFileType(hFile);
3336 CloseHandle(hFile);
3337 if (type == FILE_TYPE_CHAR)
3338 return NODE_WRITABLE;
3339 if (type == FILE_TYPE_DISK)
3340 return NODE_NORMAL;
3341 return NODE_OTHER;
3342}
3343
3344#ifdef HAVE_ACL
3345struct my_acl
3346{
3347 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3348 PSID pSidOwner;
3349 PSID pSidGroup;
3350 PACL pDacl;
3351 PACL pSacl;
3352};
3353#endif
3354
3355/*
3356 * Return a pointer to the ACL of file "fname" in allocated memory.
3357 * Return NULL if the ACL is not available for whatever reason.
3358 */
3359 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003360mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003361{
3362#ifndef HAVE_ACL
3363 return (vim_acl_T)NULL;
3364#else
3365 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003366 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003367
3368 /* This only works on Windows NT and 2000. */
3369 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3370 {
3371 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3372 if (p != NULL)
3373 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003374# ifdef FEAT_MBYTE
3375 WCHAR *wn = NULL;
3376
3377 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3378 wn = enc_to_utf16(fname, NULL);
3379 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003380 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003381 /* Try to retrieve the entire security descriptor. */
3382 err = pGetNamedSecurityInfoW(
3383 wn, // Abstract filename
3384 SE_FILE_OBJECT, // File Object
3385 OWNER_SECURITY_INFORMATION |
3386 GROUP_SECURITY_INFORMATION |
3387 DACL_SECURITY_INFORMATION |
3388 SACL_SECURITY_INFORMATION,
3389 &p->pSidOwner, // Ownership information.
3390 &p->pSidGroup, // Group membership.
3391 &p->pDacl, // Discretionary information.
3392 &p->pSacl, // For auditing purposes.
3393 &p->pSecurityDescriptor);
3394 if (err == ERROR_ACCESS_DENIED ||
3395 err == ERROR_PRIVILEGE_NOT_HELD)
3396 {
3397 /* Retrieve only DACL. */
3398 (void)pGetNamedSecurityInfoW(
3399 wn,
3400 SE_FILE_OBJECT,
3401 DACL_SECURITY_INFORMATION,
3402 NULL,
3403 NULL,
3404 &p->pDacl,
3405 NULL,
3406 &p->pSecurityDescriptor);
3407 }
3408 if (p->pSecurityDescriptor == NULL)
3409 {
3410 mch_free_acl((vim_acl_T)p);
3411 p = NULL;
3412 }
3413 vim_free(wn);
3414 }
3415 else
3416# endif
3417 {
3418 /* Try to retrieve the entire security descriptor. */
3419 err = pGetNamedSecurityInfo(
3420 (LPSTR)fname, // Abstract filename
3421 SE_FILE_OBJECT, // File Object
3422 OWNER_SECURITY_INFORMATION |
3423 GROUP_SECURITY_INFORMATION |
3424 DACL_SECURITY_INFORMATION |
3425 SACL_SECURITY_INFORMATION,
3426 &p->pSidOwner, // Ownership information.
3427 &p->pSidGroup, // Group membership.
3428 &p->pDacl, // Discretionary information.
3429 &p->pSacl, // For auditing purposes.
3430 &p->pSecurityDescriptor);
3431 if (err == ERROR_ACCESS_DENIED ||
3432 err == ERROR_PRIVILEGE_NOT_HELD)
3433 {
3434 /* Retrieve only DACL. */
3435 (void)pGetNamedSecurityInfo(
3436 (LPSTR)fname,
3437 SE_FILE_OBJECT,
3438 DACL_SECURITY_INFORMATION,
3439 NULL,
3440 NULL,
3441 &p->pDacl,
3442 NULL,
3443 &p->pSecurityDescriptor);
3444 }
3445 if (p->pSecurityDescriptor == NULL)
3446 {
3447 mch_free_acl((vim_acl_T)p);
3448 p = NULL;
3449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003450 }
3451 }
3452 }
3453
3454 return (vim_acl_T)p;
3455#endif
3456}
3457
Bram Moolenaar27515922013-06-29 15:36:26 +02003458#ifdef HAVE_ACL
3459/*
3460 * Check if "acl" contains inherited ACE.
3461 */
3462 static BOOL
3463is_acl_inherited(PACL acl)
3464{
3465 DWORD i;
3466 ACL_SIZE_INFORMATION acl_info;
3467 PACCESS_ALLOWED_ACE ace;
3468
3469 acl_info.AceCount = 0;
3470 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3471 for (i = 0; i < acl_info.AceCount; i++)
3472 {
3473 GetAce(acl, i, (LPVOID *)&ace);
3474 if (ace->Header.AceFlags & INHERITED_ACE)
3475 return TRUE;
3476 }
3477 return FALSE;
3478}
3479#endif
3480
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481/*
3482 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3483 * Errors are ignored.
3484 * This must only be called with "acl" equal to what mch_get_acl() returned.
3485 */
3486 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003487mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488{
3489#ifdef HAVE_ACL
3490 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003491 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003492
3493 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003494 {
3495# ifdef FEAT_MBYTE
3496 WCHAR *wn = NULL;
3497# endif
3498
3499 /* Set security flags */
3500 if (p->pSidOwner)
3501 sec_info |= OWNER_SECURITY_INFORMATION;
3502 if (p->pSidGroup)
3503 sec_info |= GROUP_SECURITY_INFORMATION;
3504 if (p->pDacl)
3505 {
3506 sec_info |= DACL_SECURITY_INFORMATION;
3507 /* Do not inherit its parent's DACL.
3508 * If the DACL is inherited, Cygwin permissions would be changed.
3509 */
3510 if (!is_acl_inherited(p->pDacl))
3511 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3512 }
3513 if (p->pSacl)
3514 sec_info |= SACL_SECURITY_INFORMATION;
3515
3516# ifdef FEAT_MBYTE
3517 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3518 wn = enc_to_utf16(fname, NULL);
3519 if (wn != NULL)
3520 {
3521 (void)pSetNamedSecurityInfoW(
3522 wn, // Abstract filename
3523 SE_FILE_OBJECT, // File Object
3524 sec_info,
3525 p->pSidOwner, // Ownership information.
3526 p->pSidGroup, // Group membership.
3527 p->pDacl, // Discretionary information.
3528 p->pSacl // For auditing purposes.
3529 );
3530 vim_free(wn);
3531 }
3532 else
3533# endif
3534 {
3535 (void)pSetNamedSecurityInfo(
3536 (LPSTR)fname, // Abstract filename
3537 SE_FILE_OBJECT, // File Object
3538 sec_info,
3539 p->pSidOwner, // Ownership information.
3540 p->pSidGroup, // Group membership.
3541 p->pDacl, // Discretionary information.
3542 p->pSacl // For auditing purposes.
3543 );
3544 }
3545 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003546#endif
3547}
3548
3549 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003550mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551{
3552#ifdef HAVE_ACL
3553 struct my_acl *p = (struct my_acl *)acl;
3554
3555 if (p != NULL)
3556 {
3557 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3558 vim_free(p);
3559 }
3560#endif
3561}
3562
3563#ifndef FEAT_GUI_W32
3564
3565/*
3566 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3567 */
3568 static BOOL WINAPI
3569handler_routine(
3570 DWORD dwCtrlType)
3571{
3572 switch (dwCtrlType)
3573 {
3574 case CTRL_C_EVENT:
3575 if (ctrl_c_interrupts)
3576 g_fCtrlCPressed = TRUE;
3577 return TRUE;
3578
3579 case CTRL_BREAK_EVENT:
3580 g_fCBrkPressed = TRUE;
3581 return TRUE;
3582
3583 /* fatal events: shut down gracefully */
3584 case CTRL_CLOSE_EVENT:
3585 case CTRL_LOGOFF_EVENT:
3586 case CTRL_SHUTDOWN_EVENT:
3587 windgoto((int)Rows - 1, 0);
3588 g_fForceExit = TRUE;
3589
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003590 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003591 (dwCtrlType == CTRL_CLOSE_EVENT
3592 ? _("close")
3593 : dwCtrlType == CTRL_LOGOFF_EVENT
3594 ? _("logoff")
3595 : _("shutdown")));
3596#ifdef DEBUG
3597 OutputDebugString(IObuff);
3598#endif
3599
3600 preserve_exit(); /* output IObuff, preserve files and exit */
3601
3602 return TRUE; /* not reached */
3603
3604 default:
3605 return FALSE;
3606 }
3607}
3608
3609
3610/*
3611 * set the tty in (raw) ? "raw" : "cooked" mode
3612 */
3613 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003614mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003615{
3616 DWORD cmodein;
3617 DWORD cmodeout;
3618 BOOL bEnableHandler;
3619
3620 GetConsoleMode(g_hConIn, &cmodein);
3621 GetConsoleMode(g_hConOut, &cmodeout);
3622 if (tmode == TMODE_RAW)
3623 {
3624 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3625 ENABLE_ECHO_INPUT);
3626#ifdef FEAT_MOUSE
3627 if (g_fMouseActive)
3628 cmodein |= ENABLE_MOUSE_INPUT;
3629#endif
3630 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3631 bEnableHandler = TRUE;
3632 }
3633 else /* cooked */
3634 {
3635 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3636 ENABLE_ECHO_INPUT);
3637 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3638 bEnableHandler = FALSE;
3639 }
3640 SetConsoleMode(g_hConIn, cmodein);
3641 SetConsoleMode(g_hConOut, cmodeout);
3642 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3643
3644#ifdef MCH_WRITE_DUMP
3645 if (fdDump)
3646 {
3647 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3648 tmode == TMODE_RAW ? "raw" :
3649 tmode == TMODE_COOK ? "cooked" : "normal",
3650 cmodein, cmodeout);
3651 fflush(fdDump);
3652 }
3653#endif
3654}
3655
3656
3657/*
3658 * Get the size of the current window in `Rows' and `Columns'
3659 * Return OK when size could be determined, FAIL otherwise.
3660 */
3661 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003662mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003663{
3664 CONSOLE_SCREEN_BUFFER_INFO csbi;
3665
3666 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3667 {
3668 /*
3669 * For some reason, we are trying to get the screen dimensions
3670 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3671 * variables are really intended to mean the size of Vim screen
3672 * while in termcap mode.
3673 */
3674 Rows = g_cbTermcap.Info.dwSize.Y;
3675 Columns = g_cbTermcap.Info.dwSize.X;
3676 }
3677 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3678 {
3679 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3680 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3681 }
3682 else
3683 {
3684 Rows = 25;
3685 Columns = 80;
3686 }
3687 return OK;
3688}
3689
3690/*
3691 * Set a console window to `xSize' * `ySize'
3692 */
3693 static void
3694ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003695 HANDLE hConsole,
3696 int xSize,
3697 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698{
3699 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3700 SMALL_RECT srWindowRect; /* hold the new console size */
3701 COORD coordScreen;
3702
3703#ifdef MCH_WRITE_DUMP
3704 if (fdDump)
3705 {
3706 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3707 fflush(fdDump);
3708 }
3709#endif
3710
3711 /* get the largest size we can size the console window to */
3712 coordScreen = GetLargestConsoleWindowSize(hConsole);
3713
3714 /* define the new console window size and scroll position */
3715 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3716 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3717 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3718
3719 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3720 {
3721 int sx, sy;
3722
3723 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3724 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3725 if (sy < ySize || sx < xSize)
3726 {
3727 /*
3728 * Increasing number of lines/columns, do buffer first.
3729 * Use the maximal size in x and y direction.
3730 */
3731 if (sy < ySize)
3732 coordScreen.Y = ySize;
3733 else
3734 coordScreen.Y = sy;
3735 if (sx < xSize)
3736 coordScreen.X = xSize;
3737 else
3738 coordScreen.X = sx;
3739 SetConsoleScreenBufferSize(hConsole, coordScreen);
3740 }
3741 }
3742
3743 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3744 {
3745#ifdef MCH_WRITE_DUMP
3746 if (fdDump)
3747 {
3748 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3749 GetLastError());
3750 fflush(fdDump);
3751 }
3752#endif
3753 }
3754
3755 /* define the new console buffer size */
3756 coordScreen.X = xSize;
3757 coordScreen.Y = ySize;
3758
3759 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3760 {
3761#ifdef MCH_WRITE_DUMP
3762 if (fdDump)
3763 {
3764 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3765 GetLastError());
3766 fflush(fdDump);
3767 }
3768#endif
3769 }
3770}
3771
3772
3773/*
3774 * Set the console window to `Rows' * `Columns'
3775 */
3776 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003777mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003778{
3779 COORD coordScreen;
3780
3781 /* Don't change window size while still starting up */
3782 if (suppress_winsize != 0)
3783 {
3784 suppress_winsize = 2;
3785 return;
3786 }
3787
3788 if (term_console)
3789 {
3790 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3791
3792 /* Clamp Rows and Columns to reasonable values */
3793 if (Rows > coordScreen.Y)
3794 Rows = coordScreen.Y;
3795 if (Columns > coordScreen.X)
3796 Columns = coordScreen.X;
3797
3798 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3799 }
3800}
3801
3802/*
3803 * Rows and/or Columns has changed.
3804 */
3805 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003806mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003807{
3808 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3809}
3810
3811
3812/*
3813 * Called when started up, to set the winsize that was delayed.
3814 */
3815 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003816mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817{
3818 if (suppress_winsize == 2)
3819 {
3820 suppress_winsize = 0;
3821 mch_set_shellsize();
3822 shell_resized();
3823 }
3824 suppress_winsize = 0;
3825}
3826#endif /* FEAT_GUI_W32 */
3827
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003828 static BOOL
3829vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003830 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003831 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01003832 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003833 STARTUPINFO *si,
3834 PROCESS_INFORMATION *pi)
3835{
3836# ifdef FEAT_MBYTE
3837 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3838 {
3839 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
3840
3841 if (wcmd != NULL)
3842 {
3843 BOOL ret;
3844 ret = CreateProcessW(
3845 NULL, /* Executable name */
3846 wcmd, /* Command to execute */
3847 NULL, /* Process security attributes */
3848 NULL, /* Thread security attributes */
3849 inherit_handles, /* Inherit handles */
3850 flags, /* Creation flags */
3851 NULL, /* Environment */
3852 NULL, /* Current directory */
Bram Moolenaar36c85b22013-12-12 20:25:44 +01003853 (LPSTARTUPINFOW)si, /* Startup information */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003854 pi); /* Process information */
3855 vim_free(wcmd);
3856 return ret;
3857 }
3858 }
3859#endif
3860 return CreateProcess(
3861 NULL, /* Executable name */
3862 cmd, /* Command to execute */
3863 NULL, /* Process security attributes */
3864 NULL, /* Thread security attributes */
3865 inherit_handles, /* Inherit handles */
3866 flags, /* Creation flags */
3867 NULL, /* Environment */
3868 NULL, /* Current directory */
3869 si, /* Startup information */
3870 pi); /* Process information */
3871}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003872
3873
3874#if defined(FEAT_GUI_W32) || defined(PROTO)
3875
3876/*
3877 * Specialised version of system() for Win32 GUI mode.
3878 * This version proceeds as follows:
3879 * 1. Create a console window for use by the subprocess
3880 * 2. Run the subprocess (it gets the allocated console by default)
3881 * 3. Wait for the subprocess to terminate and get its exit code
3882 * 4. Prompt the user to press a key to close the console window
3883 */
3884 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003885mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886{
3887 STARTUPINFO si;
3888 PROCESS_INFORMATION pi;
3889 DWORD ret = 0;
3890 HWND hwnd = GetFocus();
3891
3892 si.cb = sizeof(si);
3893 si.lpReserved = NULL;
3894 si.lpDesktop = NULL;
3895 si.lpTitle = NULL;
3896 si.dwFlags = STARTF_USESHOWWINDOW;
3897 /*
3898 * It's nicer to run a filter command in a minimized window, but in
3899 * Windows 95 this makes the command MUCH slower. We can't do it under
3900 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003901 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003902 */
3903 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003904 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905 else
3906 si.wShowWindow = SW_SHOWNORMAL;
3907 si.cbReserved2 = 0;
3908 si.lpReserved2 = NULL;
3909
3910 /* There is a strange error on Windows 95 when using "c:\\command.com".
3911 * When the "c:\\" is left out it works OK...? */
3912 if (mch_windows95()
3913 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3914 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3915 cmd += 3;
3916
3917 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003918 vim_create_process(cmd, FALSE,
3919 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003920
3921 /* Wait for the command to terminate before continuing */
3922 if (g_PlatformId != VER_PLATFORM_WIN32s)
3923 {
3924#ifdef FEAT_GUI
3925 int delay = 1;
3926
3927 /* Keep updating the window while waiting for the shell to finish. */
3928 for (;;)
3929 {
3930 MSG msg;
3931
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003932 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933 {
3934 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003935 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003936 delay = 1;
3937 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 }
3939 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3940 break;
3941
3942 /* We start waiting for a very short time and then increase it, so
3943 * that we respond quickly when the process is quick, and don't
3944 * consume too much overhead when it's slow. */
3945 if (delay < 50)
3946 delay += 10;
3947 }
3948#else
3949 WaitForSingleObject(pi.hProcess, INFINITE);
3950#endif
3951
3952 /* Get the command exit code */
3953 GetExitCodeProcess(pi.hProcess, &ret);
3954 }
3955 else
3956 {
3957 /*
3958 * This ugly code is the only quick way of performing
3959 * a synchronous spawn under Win32s. Yuk.
3960 */
3961 num_windows = 0;
3962 EnumWindows(win32ssynch_cb, 0);
3963 old_num_windows = num_windows;
3964 do
3965 {
3966 Sleep(1000);
3967 num_windows = 0;
3968 EnumWindows(win32ssynch_cb, 0);
3969 } while (num_windows == old_num_windows);
3970 ret = 0;
3971 }
3972
3973 /* Close the handles to the subprocess, so that it goes away */
3974 CloseHandle(pi.hThread);
3975 CloseHandle(pi.hProcess);
3976
3977 /* Try to get input focus back. Doesn't always work though. */
3978 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3979
3980 return ret;
3981}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003982
3983/*
3984 * Thread launched by the gui to send the current buffer data to the
3985 * process. This way avoid to hang up vim totally if the children
3986 * process take a long time to process the lines.
3987 */
3988 static DWORD WINAPI
3989sub_process_writer(LPVOID param)
3990{
3991 HANDLE g_hChildStd_IN_Wr = param;
3992 linenr_T lnum = curbuf->b_op_start.lnum;
3993 DWORD len = 0;
3994 DWORD l;
3995 char_u *lp = ml_get(lnum);
3996 char_u *s;
3997 int written = 0;
3998
3999 for (;;)
4000 {
4001 l = (DWORD)STRLEN(lp + written);
4002 if (l == 0)
4003 len = 0;
4004 else if (lp[written] == NL)
4005 {
4006 /* NL -> NUL translation */
4007 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4008 }
4009 else
4010 {
4011 s = vim_strchr(lp + written, NL);
4012 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4013 s == NULL ? l : (DWORD)(s - (lp + written)),
4014 &len, NULL);
4015 }
4016 if (len == (int)l)
4017 {
4018 /* Finished a line, add a NL, unless this line should not have
4019 * one. */
4020 if (lnum != curbuf->b_op_end.lnum
4021 || !curbuf->b_p_bin
4022 || (lnum != curbuf->b_no_eol_lnum
4023 && (lnum != curbuf->b_ml.ml_line_count
4024 || curbuf->b_p_eol)))
4025 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004026 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004027 }
4028
4029 ++lnum;
4030 if (lnum > curbuf->b_op_end.lnum)
4031 break;
4032
4033 lp = ml_get(lnum);
4034 written = 0;
4035 }
4036 else if (len > 0)
4037 written += len;
4038 }
4039
4040 /* finished all the lines, close pipe */
4041 CloseHandle(g_hChildStd_IN_Wr);
4042 ExitThread(0);
4043}
4044
4045
4046# define BUFLEN 100 /* length for buffer, stolen from unix version */
4047
4048/*
4049 * This function read from the children's stdout and write the
4050 * data on screen or in the buffer accordingly.
4051 */
4052 static void
4053dump_pipe(int options,
4054 HANDLE g_hChildStd_OUT_Rd,
4055 garray_T *ga,
4056 char_u buffer[],
4057 DWORD *buffer_off)
4058{
4059 DWORD availableBytes = 0;
4060 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004061 int ret;
4062 DWORD len;
4063 DWORD toRead;
4064 int repeatCount;
4065
4066 /* we query the pipe to see if there is any data to read
4067 * to avoid to perform a blocking read */
4068 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4069 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004070 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004071 NULL, /* number of read bytes */
4072 &availableBytes, /* available bytes total */
4073 NULL); /* byteLeft */
4074
4075 repeatCount = 0;
4076 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004077 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004078 {
4079 repeatCount++;
4080 toRead =
4081# ifdef FEAT_MBYTE
4082 (DWORD)(BUFLEN - *buffer_off);
4083# else
4084 (DWORD)BUFLEN;
4085# endif
4086 toRead = availableBytes < toRead ? availableBytes : toRead;
4087 ReadFile(g_hChildStd_OUT_Rd, buffer
4088# ifdef FEAT_MBYTE
4089 + *buffer_off, toRead
4090# else
4091 , toRead
4092# endif
4093 , &len, NULL);
4094
4095 /* If we haven't read anything, there is a problem */
4096 if (len == 0)
4097 break;
4098
4099 availableBytes -= len;
4100
4101 if (options & SHELL_READ)
4102 {
4103 /* Do NUL -> NL translation, append NL separated
4104 * lines to the current buffer. */
4105 for (i = 0; i < len; ++i)
4106 {
4107 if (buffer[i] == NL)
4108 append_ga_line(ga);
4109 else if (buffer[i] == NUL)
4110 ga_append(ga, NL);
4111 else
4112 ga_append(ga, buffer[i]);
4113 }
4114 }
4115# ifdef FEAT_MBYTE
4116 else if (has_mbyte)
4117 {
4118 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004119 int c;
4120 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004121
4122 len += *buffer_off;
4123 buffer[len] = NUL;
4124
4125 /* Check if the last character in buffer[] is
4126 * incomplete, keep these bytes for the next
4127 * round. */
4128 for (p = buffer; p < buffer + len; p += l)
4129 {
4130 l = mb_cptr2len(p);
4131 if (l == 0)
4132 l = 1; /* NUL byte? */
4133 else if (MB_BYTE2LEN(*p) != l)
4134 break;
4135 }
4136 if (p == buffer) /* no complete character */
4137 {
4138 /* avoid getting stuck at an illegal byte */
4139 if (len >= 12)
4140 ++p;
4141 else
4142 {
4143 *buffer_off = len;
4144 return;
4145 }
4146 }
4147 c = *p;
4148 *p = NUL;
4149 msg_puts(buffer);
4150 if (p < buffer + len)
4151 {
4152 *p = c;
4153 *buffer_off = (DWORD)((buffer + len) - p);
4154 mch_memmove(buffer, p, *buffer_off);
4155 return;
4156 }
4157 *buffer_off = 0;
4158 }
4159# endif /* FEAT_MBYTE */
4160 else
4161 {
4162 buffer[len] = NUL;
4163 msg_puts(buffer);
4164 }
4165
4166 windgoto(msg_row, msg_col);
4167 cursor_on();
4168 out_flush();
4169 }
4170}
4171
4172/*
4173 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4174 * for communication and doesn't open any new window.
4175 */
4176 static int
4177mch_system_piped(char *cmd, int options)
4178{
4179 STARTUPINFO si;
4180 PROCESS_INFORMATION pi;
4181 DWORD ret = 0;
4182
4183 HANDLE g_hChildStd_IN_Rd = NULL;
4184 HANDLE g_hChildStd_IN_Wr = NULL;
4185 HANDLE g_hChildStd_OUT_Rd = NULL;
4186 HANDLE g_hChildStd_OUT_Wr = NULL;
4187
4188 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4189 DWORD len;
4190
4191 /* buffer used to receive keys */
4192 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4193 int ta_len = 0; /* valid bytes in ta_buf[] */
4194
4195 DWORD i;
4196 int c;
4197 int noread_cnt = 0;
4198 garray_T ga;
4199 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004200 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004201 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004202
4203 SECURITY_ATTRIBUTES saAttr;
4204
4205 /* Set the bInheritHandle flag so pipe handles are inherited. */
4206 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4207 saAttr.bInheritHandle = TRUE;
4208 saAttr.lpSecurityDescriptor = NULL;
4209
4210 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4211 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4212 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4213 /* Create a pipe for the child process's STDIN. */
4214 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4215 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4216 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4217 {
4218 CloseHandle(g_hChildStd_IN_Rd);
4219 CloseHandle(g_hChildStd_IN_Wr);
4220 CloseHandle(g_hChildStd_OUT_Rd);
4221 CloseHandle(g_hChildStd_OUT_Wr);
4222 MSG_PUTS(_("\nCannot create pipes\n"));
4223 }
4224
4225 si.cb = sizeof(si);
4226 si.lpReserved = NULL;
4227 si.lpDesktop = NULL;
4228 si.lpTitle = NULL;
4229 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4230
4231 /* set-up our file redirection */
4232 si.hStdError = g_hChildStd_OUT_Wr;
4233 si.hStdOutput = g_hChildStd_OUT_Wr;
4234 si.hStdInput = g_hChildStd_IN_Rd;
4235 si.wShowWindow = SW_HIDE;
4236 si.cbReserved2 = 0;
4237 si.lpReserved2 = NULL;
4238
4239 if (options & SHELL_READ)
4240 ga_init2(&ga, 1, BUFLEN);
4241
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004242 if (cmd != NULL)
4243 {
4244 p = (char *)vim_strsave((char_u *)cmd);
4245 if (p != NULL)
4246 unescape_shellxquote((char_u *)p, p_sxe);
4247 else
4248 p = cmd;
4249 }
4250
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004251 /* Now, run the command.
4252 * About "Inherit handles" being TRUE: this command can be litigious,
4253 * handle inheritance was deactivated for pending temp file, but, if we
4254 * deactivate it, the pipes don't work for some reason. */
4255 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004256
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004257 if (p != cmd)
4258 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004259
4260 /* Close our unused side of the pipes */
4261 CloseHandle(g_hChildStd_IN_Rd);
4262 CloseHandle(g_hChildStd_OUT_Wr);
4263
4264 if (options & SHELL_WRITE)
4265 {
4266 HANDLE thread =
4267 CreateThread(NULL, /* security attributes */
4268 0, /* default stack size */
4269 sub_process_writer, /* function to be executed */
4270 g_hChildStd_IN_Wr, /* parameter */
4271 0, /* creation flag, start immediately */
4272 NULL); /* we don't care about thread id */
4273 CloseHandle(thread);
4274 g_hChildStd_IN_Wr = NULL;
4275 }
4276
4277 /* Keep updating the window while waiting for the shell to finish. */
4278 for (;;)
4279 {
4280 MSG msg;
4281
Bram Moolenaar175d0702013-12-11 18:36:33 +01004282 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004283 {
4284 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004285 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004286 }
4287
4288 /* write pipe information in the window */
4289 if ((options & (SHELL_READ|SHELL_WRITE))
4290# ifdef FEAT_GUI
4291 || gui.in_use
4292# endif
4293 )
4294 {
4295 len = 0;
4296 if (!(options & SHELL_EXPAND)
4297 && ((options &
4298 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4299 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4300# ifdef FEAT_GUI
4301 || gui.in_use
4302# endif
4303 )
4304 && (ta_len > 0 || noread_cnt > 4))
4305 {
4306 if (ta_len == 0)
4307 {
4308 /* Get extra characters when we don't have any. Reset the
4309 * counter and timer. */
4310 noread_cnt = 0;
4311# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4312 gettimeofday(&start_tv, NULL);
4313# endif
4314 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4315 }
4316 if (ta_len > 0 || len > 0)
4317 {
4318 /*
4319 * For pipes: Check for CTRL-C: send interrupt signal to
4320 * child. Check for CTRL-D: EOF, close pipe to child.
4321 */
4322 if (len == 1 && cmd != NULL)
4323 {
4324 if (ta_buf[ta_len] == Ctrl_C)
4325 {
4326 /* Learn what exit code is expected, for
4327 * now put 9 as SIGKILL */
4328 TerminateProcess(pi.hProcess, 9);
4329 }
4330 if (ta_buf[ta_len] == Ctrl_D)
4331 {
4332 CloseHandle(g_hChildStd_IN_Wr);
4333 g_hChildStd_IN_Wr = NULL;
4334 }
4335 }
4336
4337 /* replace K_BS by <BS> and K_DEL by <DEL> */
4338 for (i = ta_len; i < ta_len + len; ++i)
4339 {
4340 if (ta_buf[i] == CSI && len - i > 2)
4341 {
4342 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4343 if (c == K_DEL || c == K_KDEL || c == K_BS)
4344 {
4345 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4346 (size_t)(len - i - 2));
4347 if (c == K_DEL || c == K_KDEL)
4348 ta_buf[i] = DEL;
4349 else
4350 ta_buf[i] = Ctrl_H;
4351 len -= 2;
4352 }
4353 }
4354 else if (ta_buf[i] == '\r')
4355 ta_buf[i] = '\n';
4356# ifdef FEAT_MBYTE
4357 if (has_mbyte)
4358 i += (*mb_ptr2len_len)(ta_buf + i,
4359 ta_len + len - i) - 1;
4360# endif
4361 }
4362
4363 /*
4364 * For pipes: echo the typed characters. For a pty this
4365 * does not seem to work.
4366 */
4367 for (i = ta_len; i < ta_len + len; ++i)
4368 {
4369 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4370 msg_putchar(ta_buf[i]);
4371# ifdef FEAT_MBYTE
4372 else if (has_mbyte)
4373 {
4374 int l = (*mb_ptr2len)(ta_buf + i);
4375
4376 msg_outtrans_len(ta_buf + i, l);
4377 i += l - 1;
4378 }
4379# endif
4380 else
4381 msg_outtrans_len(ta_buf + i, 1);
4382 }
4383 windgoto(msg_row, msg_col);
4384 out_flush();
4385
4386 ta_len += len;
4387
4388 /*
4389 * Write the characters to the child, unless EOF has been
4390 * typed for pipes. Write one character at a time, to
4391 * avoid losing too much typeahead. When writing buffer
4392 * lines, drop the typed characters (only check for
4393 * CTRL-C).
4394 */
4395 if (options & SHELL_WRITE)
4396 ta_len = 0;
4397 else if (g_hChildStd_IN_Wr != NULL)
4398 {
4399 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4400 1, &len, NULL);
4401 // if we are typing in, we want to keep things reactive
4402 delay = 1;
4403 if (len > 0)
4404 {
4405 ta_len -= len;
4406 mch_memmove(ta_buf, ta_buf + len, ta_len);
4407 }
4408 }
4409 }
4410 }
4411 }
4412
4413 if (ta_len)
4414 ui_inchar_undo(ta_buf, ta_len);
4415
4416 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4417 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004418 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004419 break;
4420 }
4421
4422 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004423 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004424
4425 /* We start waiting for a very short time and then increase it, so
4426 * that we respond quickly when the process is quick, and don't
4427 * consume too much overhead when it's slow. */
4428 if (delay < 50)
4429 delay += 10;
4430 }
4431
4432 /* Close the pipe */
4433 CloseHandle(g_hChildStd_OUT_Rd);
4434 if (g_hChildStd_IN_Wr != NULL)
4435 CloseHandle(g_hChildStd_IN_Wr);
4436
4437 WaitForSingleObject(pi.hProcess, INFINITE);
4438
4439 /* Get the command exit code */
4440 GetExitCodeProcess(pi.hProcess, &ret);
4441
4442 if (options & SHELL_READ)
4443 {
4444 if (ga.ga_len > 0)
4445 {
4446 append_ga_line(&ga);
4447 /* remember that the NL was missing */
4448 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4449 }
4450 else
4451 curbuf->b_no_eol_lnum = 0;
4452 ga_clear(&ga);
4453 }
4454
4455 /* Close the handles to the subprocess, so that it goes away */
4456 CloseHandle(pi.hThread);
4457 CloseHandle(pi.hProcess);
4458
4459 return ret;
4460}
4461
4462 static int
4463mch_system(char *cmd, int options)
4464{
4465 /* if we can pipe and the shelltemp option is off */
4466 if (allowPiping && !p_stmp)
4467 return mch_system_piped(cmd, options);
4468 else
4469 return mch_system_classic(cmd, options);
4470}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471#else
4472
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004473# ifdef FEAT_MBYTE
4474 static int
4475mch_system(char *cmd, int options)
4476{
4477 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4478 {
4479 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4480 if (wcmd != NULL)
4481 {
4482 int ret = _wsystem(wcmd);
4483 vim_free(wcmd);
4484 return ret;
4485 }
4486 }
4487 return system(cmd);
4488}
4489# else
4490# define mch_system(c, o) system(c)
4491# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004492
4493#endif
4494
4495/*
4496 * Either execute a command by calling the shell or start a new shell
4497 */
4498 int
4499mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004500 char_u *cmd,
4501 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004502{
4503 int x = 0;
4504 int tmode = cur_tmode;
4505#ifdef FEAT_TITLE
4506 char szShellTitle[512];
4507
4508 /* Change the title to reflect that we are in a subshell. */
4509 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
4510 {
4511 if (cmd == NULL)
4512 strcat(szShellTitle, " :sh");
4513 else
4514 {
4515 strcat(szShellTitle, " - !");
4516 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4517 strcat(szShellTitle, cmd);
4518 }
4519 mch_settitle(szShellTitle, NULL);
4520 }
4521#endif
4522
4523 out_flush();
4524
4525#ifdef MCH_WRITE_DUMP
4526 if (fdDump)
4527 {
4528 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4529 fflush(fdDump);
4530 }
4531#endif
4532
4533 /*
4534 * Catch all deadly signals while running the external command, because a
4535 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4536 */
4537 signal(SIGINT, SIG_IGN);
4538#if defined(__GNUC__) && !defined(__MINGW32__)
4539 signal(SIGKILL, SIG_IGN);
4540#else
4541 signal(SIGBREAK, SIG_IGN);
4542#endif
4543 signal(SIGILL, SIG_IGN);
4544 signal(SIGFPE, SIG_IGN);
4545 signal(SIGSEGV, SIG_IGN);
4546 signal(SIGTERM, SIG_IGN);
4547 signal(SIGABRT, SIG_IGN);
4548
4549 if (options & SHELL_COOKED)
4550 settmode(TMODE_COOK); /* set to normal mode */
4551
4552 if (cmd == NULL)
4553 {
4554 x = mch_system(p_sh, options);
4555 }
4556 else
4557 {
4558 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004559 char_u *newcmd = NULL;
4560 char_u *cmdbase = cmd;
4561 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004562
4563 /* Skip a leading ", ( and "(. */
4564 if (*cmdbase == '"' )
4565 ++cmdbase;
4566 if (*cmdbase == '(')
4567 ++cmdbase;
4568
4569 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4570 {
4571 STARTUPINFO si;
4572 PROCESS_INFORMATION pi;
4573 DWORD flags = CREATE_NEW_CONSOLE;
4574 char_u *p;
4575
4576 si.cb = sizeof(si);
4577 si.lpReserved = NULL;
4578 si.lpDesktop = NULL;
4579 si.lpTitle = NULL;
4580 si.dwFlags = 0;
4581 si.cbReserved2 = 0;
4582 si.lpReserved2 = NULL;
4583
4584 cmdbase = skipwhite(cmdbase + 5);
4585 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4586 && vim_iswhite(cmdbase[4]))
4587 {
4588 cmdbase = skipwhite(cmdbase + 4);
4589 si.dwFlags = STARTF_USESHOWWINDOW;
4590 si.wShowWindow = SW_SHOWMINNOACTIVE;
4591 }
4592 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4593 && vim_iswhite(cmdbase[2]))
4594 {
4595 cmdbase = skipwhite(cmdbase + 2);
4596 flags = CREATE_NO_WINDOW;
4597 si.dwFlags = STARTF_USESTDHANDLES;
4598 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004599 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004600 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004601 NULL, // Security att.
4602 OPEN_EXISTING, // Open flags
4603 FILE_ATTRIBUTE_NORMAL, // File att.
4604 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004605 si.hStdOutput = si.hStdInput;
4606 si.hStdError = si.hStdInput;
4607 }
4608
4609 /* Remove a trailing ", ) and )" if they have a match
4610 * at the start of the command. */
4611 if (cmdbase > cmd)
4612 {
4613 p = cmdbase + STRLEN(cmdbase);
4614 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4615 *--p = NUL;
4616 if (p > cmdbase && p[-1] == ')'
4617 && (*cmd =='(' || cmd[1] == '('))
4618 *--p = NUL;
4619 }
4620
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004621 newcmd = cmdbase;
4622 unescape_shellxquote(cmdbase, p_sxe);
4623
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004624 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004625 * If creating new console, arguments are passed to the
4626 * 'cmd.exe' as-is. If it's not, arguments are not treated
4627 * correctly for current 'cmd.exe'. So unescape characters in
4628 * shellxescape except '|' for avoiding to be treated as
4629 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004630 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004631 if (flags != CREATE_NEW_CONSOLE)
4632 {
4633 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004634 char_u *cmd_shell = mch_getenv("COMSPEC");
4635
4636 if (cmd_shell == NULL || *cmd_shell == NUL)
4637 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004638
4639 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4640 if (subcmd != NULL)
4641 {
4642 /* make "cmd.exe /c arguments" */
4643 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004644 newcmd = lalloc(cmdlen, TRUE);
4645 if (newcmd != NULL)
4646 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004647 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004648 else
4649 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004650 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004651 }
4652 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004653
4654 /*
4655 * Now, start the command as a process, so that it doesn't
4656 * inherit our handles which causes unpleasant dangling swap
4657 * files if we exit before the spawned process
4658 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004659 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004660 x = 0;
4661 else
4662 {
4663 x = -1;
4664#ifdef FEAT_GUI_W32
4665 EMSG(_("E371: Command not found"));
4666#endif
4667 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004668
4669 if (newcmd != cmdbase)
4670 vim_free(newcmd);
4671
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004672 if (si.hStdInput != NULL)
4673 {
4674 /* Close the handle to \\.\NUL */
4675 CloseHandle(si.hStdInput);
4676 }
4677 /* Close the handles to the subprocess, so that it goes away */
4678 CloseHandle(pi.hThread);
4679 CloseHandle(pi.hProcess);
4680 }
4681 else
4682 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004683 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004684#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004685 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004686#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004687 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4688
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004689 newcmd = lalloc(cmdlen, TRUE);
4690 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004691 {
4692#if defined(FEAT_GUI_W32)
4693 if (need_vimrun_warning)
4694 {
4695 MessageBox(NULL,
4696 _("VIMRUN.EXE not found in your $PATH.\n"
4697 "External commands will not pause after completion.\n"
4698 "See :help win32-vimrun for more information."),
4699 _("Vim Warning"),
4700 MB_ICONWARNING);
4701 need_vimrun_warning = FALSE;
4702 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004703 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004704 /* Use vimrun to execute the command. It opens a console
4705 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004706 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004707 vimrun_path,
4708 (msg_silent != 0 || (options & SHELL_DOOUT))
4709 ? "-s " : "",
4710 p_sh, p_shcf, cmd);
4711 else
4712#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004713 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004714 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004715 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004716 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004717 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004718 }
4719 }
4720
4721 if (tmode == TMODE_RAW)
4722 settmode(TMODE_RAW); /* set to raw mode */
4723
4724 /* Print the return value, unless "vimrun" was used. */
4725 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4726#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004727 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4728 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729#endif
4730 )
4731 {
4732 smsg(_("shell returned %d"), x);
4733 msg_putchar('\n');
4734 }
4735#ifdef FEAT_TITLE
4736 resettitle();
4737#endif
4738
4739 signal(SIGINT, SIG_DFL);
4740#if defined(__GNUC__) && !defined(__MINGW32__)
4741 signal(SIGKILL, SIG_DFL);
4742#else
4743 signal(SIGBREAK, SIG_DFL);
4744#endif
4745 signal(SIGILL, SIG_DFL);
4746 signal(SIGFPE, SIG_DFL);
4747 signal(SIGSEGV, SIG_DFL);
4748 signal(SIGTERM, SIG_DFL);
4749 signal(SIGABRT, SIG_DFL);
4750
4751 return x;
4752}
4753
4754
4755#ifndef FEAT_GUI_W32
4756
4757/*
4758 * Start termcap mode
4759 */
4760 static void
4761termcap_mode_start(void)
4762{
4763 DWORD cmodein;
4764
4765 if (g_fTermcapMode)
4766 return;
4767
4768 SaveConsoleBuffer(&g_cbNonTermcap);
4769
4770 if (g_cbTermcap.IsValid)
4771 {
4772 /*
4773 * We've been in termcap mode before. Restore certain screen
4774 * characteristics, including the buffer size and the window
4775 * size. Since we will be redrawing the screen, we don't need
4776 * to restore the actual contents of the buffer.
4777 */
4778 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4779 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4780 Rows = g_cbTermcap.Info.dwSize.Y;
4781 Columns = g_cbTermcap.Info.dwSize.X;
4782 }
4783 else
4784 {
4785 /*
4786 * This is our first time entering termcap mode. Clear the console
4787 * screen buffer, and resize the buffer to match the current window
4788 * size. We will use this as the size of our editing environment.
4789 */
4790 ClearConsoleBuffer(g_attrCurrent);
4791 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4792 }
4793
4794#ifdef FEAT_TITLE
4795 resettitle();
4796#endif
4797
4798 GetConsoleMode(g_hConIn, &cmodein);
4799#ifdef FEAT_MOUSE
4800 if (g_fMouseActive)
4801 cmodein |= ENABLE_MOUSE_INPUT;
4802 else
4803 cmodein &= ~ENABLE_MOUSE_INPUT;
4804#endif
4805 cmodein |= ENABLE_WINDOW_INPUT;
4806 SetConsoleMode(g_hConIn, cmodein);
4807
4808 redraw_later_clear();
4809 g_fTermcapMode = TRUE;
4810}
4811
4812
4813/*
4814 * End termcap mode
4815 */
4816 static void
4817termcap_mode_end(void)
4818{
4819 DWORD cmodein;
4820 ConsoleBuffer *cb;
4821 COORD coord;
4822 DWORD dwDummy;
4823
4824 if (!g_fTermcapMode)
4825 return;
4826
4827 SaveConsoleBuffer(&g_cbTermcap);
4828
4829 GetConsoleMode(g_hConIn, &cmodein);
4830 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4831 SetConsoleMode(g_hConIn, cmodein);
4832
4833#ifdef FEAT_RESTORE_ORIG_SCREEN
4834 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4835#else
4836 cb = &g_cbNonTermcap;
4837#endif
4838 RestoreConsoleBuffer(cb, p_rs);
4839 SetConsoleCursorInfo(g_hConOut, &g_cci);
4840
4841 if (p_rs || exiting)
4842 {
4843 /*
4844 * Clear anything that happens to be on the current line.
4845 */
4846 coord.X = 0;
4847 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4848 FillConsoleOutputCharacter(g_hConOut, ' ',
4849 cb->Info.dwSize.X, coord, &dwDummy);
4850 /*
4851 * The following is just for aesthetics. If we are exiting without
4852 * restoring the screen, then we want to have a prompt string
4853 * appear at the bottom line. However, the command interpreter
4854 * seems to always advance the cursor one line before displaying
4855 * the prompt string, which causes the screen to scroll. To
4856 * counter this, move the cursor up one line before exiting.
4857 */
4858 if (exiting && !p_rs)
4859 coord.Y--;
4860 /*
4861 * Position the cursor at the leftmost column of the desired row.
4862 */
4863 SetConsoleCursorPosition(g_hConOut, coord);
4864 }
4865
4866 g_fTermcapMode = FALSE;
4867}
4868#endif /* FEAT_GUI_W32 */
4869
4870
4871#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004872/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 void
4874mch_write(
4875 char_u *s,
4876 int len)
4877{
4878 /* never used */
4879}
4880
4881#else
4882
4883/*
4884 * clear `n' chars, starting from `coord'
4885 */
4886 static void
4887clear_chars(
4888 COORD coord,
4889 DWORD n)
4890{
4891 DWORD dwDummy;
4892
4893 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4894 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4895}
4896
4897
4898/*
4899 * Clear the screen
4900 */
4901 static void
4902clear_screen(void)
4903{
4904 g_coord.X = g_coord.Y = 0;
4905 clear_chars(g_coord, Rows * Columns);
4906}
4907
4908
4909/*
4910 * Clear to end of display
4911 */
4912 static void
4913clear_to_end_of_display(void)
4914{
4915 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4916 * Columns + (Columns - g_coord.X));
4917}
4918
4919
4920/*
4921 * Clear to end of line
4922 */
4923 static void
4924clear_to_end_of_line(void)
4925{
4926 clear_chars(g_coord, Columns - g_coord.X);
4927}
4928
4929
4930/*
4931 * Scroll the scroll region up by `cLines' lines
4932 */
4933 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004934scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004935{
4936 COORD oldcoord = g_coord;
4937
4938 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4939 delete_lines(cLines);
4940
4941 g_coord = oldcoord;
4942}
4943
4944
4945/*
4946 * Set the scroll region
4947 */
4948 static void
4949set_scroll_region(
4950 unsigned left,
4951 unsigned top,
4952 unsigned right,
4953 unsigned bottom)
4954{
4955 if (left >= right
4956 || top >= bottom
4957 || right > (unsigned) Columns - 1
4958 || bottom > (unsigned) Rows - 1)
4959 return;
4960
4961 g_srScrollRegion.Left = left;
4962 g_srScrollRegion.Top = top;
4963 g_srScrollRegion.Right = right;
4964 g_srScrollRegion.Bottom = bottom;
4965}
4966
4967
4968/*
4969 * Insert `cLines' lines at the current cursor position
4970 */
4971 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004972insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973{
4974 SMALL_RECT source;
4975 COORD dest;
4976 CHAR_INFO fill;
4977
4978 dest.X = 0;
4979 dest.Y = g_coord.Y + cLines;
4980
4981 source.Left = 0;
4982 source.Top = g_coord.Y;
4983 source.Right = g_srScrollRegion.Right;
4984 source.Bottom = g_srScrollRegion.Bottom - cLines;
4985
4986 fill.Char.AsciiChar = ' ';
4987 fill.Attributes = g_attrCurrent;
4988
4989 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4990
4991 /* Here we have to deal with a win32 console flake: If the scroll
4992 * region looks like abc and we scroll c to a and fill with d we get
4993 * cbd... if we scroll block c one line at a time to a, we get cdd...
4994 * vim expects cdd consistently... So we have to deal with that
4995 * here... (this also occurs scrolling the same way in the other
4996 * direction). */
4997
4998 if (source.Bottom < dest.Y)
4999 {
5000 COORD coord;
5001
5002 coord.X = 0;
5003 coord.Y = source.Bottom;
5004 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5005 }
5006}
5007
5008
5009/*
5010 * Delete `cLines' lines at the current cursor position
5011 */
5012 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005013delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005014{
5015 SMALL_RECT source;
5016 COORD dest;
5017 CHAR_INFO fill;
5018 int nb;
5019
5020 dest.X = 0;
5021 dest.Y = g_coord.Y;
5022
5023 source.Left = 0;
5024 source.Top = g_coord.Y + cLines;
5025 source.Right = g_srScrollRegion.Right;
5026 source.Bottom = g_srScrollRegion.Bottom;
5027
5028 fill.Char.AsciiChar = ' ';
5029 fill.Attributes = g_attrCurrent;
5030
5031 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5032
5033 /* Here we have to deal with a win32 console flake: If the scroll
5034 * region looks like abc and we scroll c to a and fill with d we get
5035 * cbd... if we scroll block c one line at a time to a, we get cdd...
5036 * vim expects cdd consistently... So we have to deal with that
5037 * here... (this also occurs scrolling the same way in the other
5038 * direction). */
5039
5040 nb = dest.Y + (source.Bottom - source.Top) + 1;
5041
5042 if (nb < source.Top)
5043 {
5044 COORD coord;
5045
5046 coord.X = 0;
5047 coord.Y = nb;
5048 clear_chars(coord, Columns * (source.Top - nb));
5049 }
5050}
5051
5052
5053/*
5054 * Set the cursor position
5055 */
5056 static void
5057gotoxy(
5058 unsigned x,
5059 unsigned y)
5060{
5061 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5062 return;
5063
5064 /* external cursor coords are 1-based; internal are 0-based */
5065 g_coord.X = x - 1;
5066 g_coord.Y = y - 1;
5067 SetConsoleCursorPosition(g_hConOut, g_coord);
5068}
5069
5070
5071/*
5072 * Set the current text attribute = (foreground | background)
5073 * See ../doc/os_win32.txt for the numbers.
5074 */
5075 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005076textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005077{
5078 g_attrCurrent = wAttr;
5079
5080 SetConsoleTextAttribute(g_hConOut, wAttr);
5081}
5082
5083
5084 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005085textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005086{
5087 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
5088
5089 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5090}
5091
5092
5093 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005094textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005095{
5096 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
5097
5098 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5099}
5100
5101
5102/*
5103 * restore the default text attribute (whatever we started with)
5104 */
5105 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005106normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005107{
5108 textattr(g_attrDefault);
5109}
5110
5111
5112static WORD g_attrPreStandout = 0;
5113
5114/*
5115 * Make the text standout, by brightening it
5116 */
5117 static void
5118standout(void)
5119{
5120 g_attrPreStandout = g_attrCurrent;
5121 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5122}
5123
5124
5125/*
5126 * Turn off standout mode
5127 */
5128 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005129standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005130{
5131 if (g_attrPreStandout)
5132 {
5133 textattr(g_attrPreStandout);
5134 g_attrPreStandout = 0;
5135 }
5136}
5137
5138
5139/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005140 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005141 */
5142 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005143mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005144{
5145 char_u *p;
5146 int n;
5147
5148 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5149 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5150 if (T_ME[0] == ESC && T_ME[1] == '|')
5151 {
5152 p = T_ME + 2;
5153 n = getdigits(&p);
5154 if (*p == 'm' && n > 0)
5155 {
5156 cterm_normal_fg_color = (n & 0xf) + 1;
5157 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5158 }
5159 }
5160}
5161
5162
5163/*
5164 * visual bell: flash the screen
5165 */
5166 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005167visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005168{
5169 COORD coordOrigin = {0, 0};
5170 WORD attrFlash = ~g_attrCurrent & 0xff;
5171
5172 DWORD dwDummy;
5173 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5174
5175 if (oldattrs == NULL)
5176 return;
5177 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5178 coordOrigin, &dwDummy);
5179 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5180 coordOrigin, &dwDummy);
5181
5182 Sleep(15); /* wait for 15 msec */
5183 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5184 coordOrigin, &dwDummy);
5185 vim_free(oldattrs);
5186}
5187
5188
5189/*
5190 * Make the cursor visible or invisible
5191 */
5192 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005193cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194{
5195 s_cursor_visible = fVisible;
5196#ifdef MCH_CURSOR_SHAPE
5197 mch_update_cursor();
5198#endif
5199}
5200
5201
5202/*
5203 * write `cchToWrite' characters in `pchBuf' to the screen
5204 * Returns the number of characters actually written (at least one).
5205 */
5206 static BOOL
5207write_chars(
5208 LPCSTR pchBuf,
5209 DWORD cchToWrite)
5210{
5211 COORD coord = g_coord;
5212 DWORD written;
5213
5214 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
5215 coord, &written);
5216 /* When writing fails or didn't write a single character, pretend one
5217 * character was written, otherwise we get stuck. */
5218 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
5219 coord, &written) == 0
5220 || written == 0)
5221 written = 1;
5222
5223 g_coord.X += (SHORT) written;
5224
5225 while (g_coord.X > g_srScrollRegion.Right)
5226 {
5227 g_coord.X -= (SHORT) Columns;
5228 if (g_coord.Y < g_srScrollRegion.Bottom)
5229 g_coord.Y++;
5230 }
5231
5232 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5233
5234 return written;
5235}
5236
5237
5238/*
5239 * mch_write(): write the output buffer to the screen, translating ESC
5240 * sequences into calls to console output routines.
5241 */
5242 void
5243mch_write(
5244 char_u *s,
5245 int len)
5246{
5247 s[len] = NUL;
5248
5249 if (!term_console)
5250 {
5251 write(1, s, (unsigned)len);
5252 return;
5253 }
5254
5255 /* translate ESC | sequences into faked bios calls */
5256 while (len--)
5257 {
5258 /* optimization: use one single write_chars for runs of text,
5259 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005260 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261
5262 if (p_wd)
5263 {
5264 WaitForChar(p_wd);
5265 if (prefix != 0)
5266 prefix = 1;
5267 }
5268
5269 if (prefix != 0)
5270 {
5271 DWORD nWritten;
5272
5273 nWritten = write_chars(s, prefix);
5274#ifdef MCH_WRITE_DUMP
5275 if (fdDump)
5276 {
5277 fputc('>', fdDump);
5278 fwrite(s, sizeof(char_u), nWritten, fdDump);
5279 fputs("<\n", fdDump);
5280 }
5281#endif
5282 len -= (nWritten - 1);
5283 s += nWritten;
5284 }
5285 else if (s[0] == '\n')
5286 {
5287 /* \n, newline: go to the beginning of the next line or scroll */
5288 if (g_coord.Y == g_srScrollRegion.Bottom)
5289 {
5290 scroll(1);
5291 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5292 }
5293 else
5294 {
5295 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5296 }
5297#ifdef MCH_WRITE_DUMP
5298 if (fdDump)
5299 fputs("\\n\n", fdDump);
5300#endif
5301 s++;
5302 }
5303 else if (s[0] == '\r')
5304 {
5305 /* \r, carriage return: go to beginning of line */
5306 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5307#ifdef MCH_WRITE_DUMP
5308 if (fdDump)
5309 fputs("\\r\n", fdDump);
5310#endif
5311 s++;
5312 }
5313 else if (s[0] == '\b')
5314 {
5315 /* \b, backspace: move cursor one position left */
5316 if (g_coord.X > g_srScrollRegion.Left)
5317 g_coord.X--;
5318 else if (g_coord.Y > g_srScrollRegion.Top)
5319 {
5320 g_coord.X = g_srScrollRegion.Right;
5321 g_coord.Y--;
5322 }
5323 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5324#ifdef MCH_WRITE_DUMP
5325 if (fdDump)
5326 fputs("\\b\n", fdDump);
5327#endif
5328 s++;
5329 }
5330 else if (s[0] == '\a')
5331 {
5332 /* \a, bell */
5333 MessageBeep(0xFFFFFFFF);
5334#ifdef MCH_WRITE_DUMP
5335 if (fdDump)
5336 fputs("\\a\n", fdDump);
5337#endif
5338 s++;
5339 }
5340 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5341 {
5342#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005343 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005344#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005345 char_u *p;
5346 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005347
5348 switch (s[2])
5349 {
5350 /* one or two numeric arguments, separated by ';' */
5351
5352 case '0': case '1': case '2': case '3': case '4':
5353 case '5': case '6': case '7': case '8': case '9':
5354 p = s + 2;
5355 arg1 = getdigits(&p); /* no check for length! */
5356 if (p > s + len)
5357 break;
5358
5359 if (*p == ';')
5360 {
5361 ++p;
5362 arg2 = getdigits(&p); /* no check for length! */
5363 if (p > s + len)
5364 break;
5365
5366 if (*p == 'H')
5367 gotoxy(arg2, arg1);
5368 else if (*p == 'r')
5369 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5370 }
5371 else if (*p == 'A')
5372 {
5373 /* move cursor up arg1 lines in same column */
5374 gotoxy(g_coord.X + 1,
5375 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5376 }
5377 else if (*p == 'C')
5378 {
5379 /* move cursor right arg1 columns in same line */
5380 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5381 g_coord.Y + 1);
5382 }
5383 else if (*p == 'H')
5384 {
5385 gotoxy(1, arg1);
5386 }
5387 else if (*p == 'L')
5388 {
5389 insert_lines(arg1);
5390 }
5391 else if (*p == 'm')
5392 {
5393 if (arg1 == 0)
5394 normvideo();
5395 else
5396 textattr((WORD) arg1);
5397 }
5398 else if (*p == 'f')
5399 {
5400 textcolor((WORD) arg1);
5401 }
5402 else if (*p == 'b')
5403 {
5404 textbackground((WORD) arg1);
5405 }
5406 else if (*p == 'M')
5407 {
5408 delete_lines(arg1);
5409 }
5410
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005411 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005412 s = p + 1;
5413 break;
5414
5415
5416 /* Three-character escape sequences */
5417
5418 case 'A':
5419 /* move cursor up one line in same column */
5420 gotoxy(g_coord.X + 1,
5421 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5422 goto got3;
5423
5424 case 'B':
5425 visual_bell();
5426 goto got3;
5427
5428 case 'C':
5429 /* move cursor right one column in same line */
5430 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5431 g_coord.Y + 1);
5432 goto got3;
5433
5434 case 'E':
5435 termcap_mode_end();
5436 goto got3;
5437
5438 case 'F':
5439 standout();
5440 goto got3;
5441
5442 case 'f':
5443 standend();
5444 goto got3;
5445
5446 case 'H':
5447 gotoxy(1, 1);
5448 goto got3;
5449
5450 case 'j':
5451 clear_to_end_of_display();
5452 goto got3;
5453
5454 case 'J':
5455 clear_screen();
5456 goto got3;
5457
5458 case 'K':
5459 clear_to_end_of_line();
5460 goto got3;
5461
5462 case 'L':
5463 insert_lines(1);
5464 goto got3;
5465
5466 case 'M':
5467 delete_lines(1);
5468 goto got3;
5469
5470 case 'S':
5471 termcap_mode_start();
5472 goto got3;
5473
5474 case 'V':
5475 cursor_visible(TRUE);
5476 goto got3;
5477
5478 case 'v':
5479 cursor_visible(FALSE);
5480 goto got3;
5481
5482 got3:
5483 s += 3;
5484 len -= 2;
5485 }
5486
5487#ifdef MCH_WRITE_DUMP
5488 if (fdDump)
5489 {
5490 fputs("ESC | ", fdDump);
5491 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5492 fputc('\n', fdDump);
5493 }
5494#endif
5495 }
5496 else
5497 {
5498 /* Write a single character */
5499 DWORD nWritten;
5500
5501 nWritten = write_chars(s, 1);
5502#ifdef MCH_WRITE_DUMP
5503 if (fdDump)
5504 {
5505 fputc('>', fdDump);
5506 fwrite(s, sizeof(char_u), nWritten, fdDump);
5507 fputs("<\n", fdDump);
5508 }
5509#endif
5510
5511 len -= (nWritten - 1);
5512 s += nWritten;
5513 }
5514 }
5515
5516#ifdef MCH_WRITE_DUMP
5517 if (fdDump)
5518 fflush(fdDump);
5519#endif
5520}
5521
5522#endif /* FEAT_GUI_W32 */
5523
5524
5525/*
5526 * Delay for half a second.
5527 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005528/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005529 void
5530mch_delay(
5531 long msec,
5532 int ignoreinput)
5533{
5534#ifdef FEAT_GUI_W32
5535 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005536#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005537 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005538# ifdef FEAT_MZSCHEME
5539 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5540 {
5541 int towait = p_mzq;
5542
5543 /* if msec is large enough, wait by portions in p_mzq */
5544 while (msec > 0)
5545 {
5546 mzvim_check_threads();
5547 if (msec < towait)
5548 towait = msec;
5549 Sleep(towait);
5550 msec -= towait;
5551 }
5552 }
5553 else
5554# endif
5555 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556 else
5557 WaitForChar(msec);
5558#endif
5559}
5560
5561
5562/*
5563 * this version of remove is not scared by a readonly (backup) file
5564 * Return 0 for success, -1 for failure.
5565 */
5566 int
5567mch_remove(char_u *name)
5568{
5569#ifdef FEAT_MBYTE
5570 WCHAR *wn = NULL;
5571 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005572#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005574 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5575
5576#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5578 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005579 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005580 if (wn != NULL)
5581 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005582 n = DeleteFileW(wn) ? 0 : -1;
5583 vim_free(wn);
5584 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5585 return n;
5586 /* Retry with non-wide function (for Windows 98). */
5587 }
5588 }
5589#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 return DeleteFile(name) ? 0 : -1;
5591}
5592
5593
5594/*
5595 * check for an "interrupt signal": CTRL-break or CTRL-C
5596 */
5597 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005598mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005599{
5600#ifndef FEAT_GUI_W32 /* never used */
5601 if (g_fCtrlCPressed || g_fCBrkPressed)
5602 {
5603 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5604 got_int = TRUE;
5605 }
5606#endif
5607}
5608
5609
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610#ifdef FEAT_MBYTE
5611/*
5612 * Same code as below, but with wide functions and no comments.
5613 * Return 0 for success, non-zero for failure.
5614 */
5615 int
5616mch_wrename(WCHAR *wold, WCHAR *wnew)
5617{
5618 WCHAR *p;
5619 int i;
5620 WCHAR szTempFile[_MAX_PATH + 1];
5621 WCHAR szNewPath[_MAX_PATH + 1];
5622 HANDLE hf;
5623
5624 if (!mch_windows95())
5625 {
5626 p = wold;
5627 for (i = 0; wold[i] != NUL; ++i)
5628 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5629 && wold[i + 1] != 0)
5630 p = wold + i + 1;
5631 if ((int)(wold + i - p) < 8 || p[6] != '~')
5632 return (MoveFileW(wold, wnew) == 0);
5633 }
5634
5635 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5636 return -1;
5637 *p = NUL;
5638
5639 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5640 return -2;
5641
5642 if (!DeleteFileW(szTempFile))
5643 return -3;
5644
5645 if (!MoveFileW(wold, szTempFile))
5646 return -4;
5647
5648 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5649 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5650 return -5;
5651 if (!CloseHandle(hf))
5652 return -6;
5653
5654 if (!MoveFileW(szTempFile, wnew))
5655 {
5656 (void)MoveFileW(szTempFile, wold);
5657 return -7;
5658 }
5659
5660 DeleteFileW(szTempFile);
5661
5662 if (!DeleteFileW(wold))
5663 return -8;
5664
5665 return 0;
5666}
5667#endif
5668
5669
5670/*
5671 * mch_rename() works around a bug in rename (aka MoveFile) in
5672 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5673 * file whose short file name is "FOO.BAR" (its long file name will
5674 * be correct: "foo.bar~"). Because a file can be accessed by
5675 * either its SFN or its LFN, "foo.bar" has effectively been
5676 * renamed to "foo.bar", which is not at all what was wanted. This
5677 * seems to happen only when renaming files with three-character
5678 * extensions by appending a suffix that does not include ".".
5679 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5680 *
5681 * There is another problem, which isn't really a bug but isn't right either:
5682 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5683 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5684 * service pack 6. Doesn't seem to happen on Windows 98.
5685 *
5686 * Like rename(), returns 0 upon success, non-zero upon failure.
5687 * Should probably set errno appropriately when errors occur.
5688 */
5689 int
5690mch_rename(
5691 const char *pszOldFile,
5692 const char *pszNewFile)
5693{
5694 char szTempFile[_MAX_PATH+1];
5695 char szNewPath[_MAX_PATH+1];
5696 char *pszFilePart;
5697 HANDLE hf;
5698#ifdef FEAT_MBYTE
5699 WCHAR *wold = NULL;
5700 WCHAR *wnew = NULL;
5701 int retval = -1;
5702
5703 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5704 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005705 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5706 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 if (wold != NULL && wnew != NULL)
5708 retval = mch_wrename(wold, wnew);
5709 vim_free(wold);
5710 vim_free(wnew);
5711 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5712 return retval;
5713 /* Retry with non-wide function (for Windows 98). */
5714 }
5715#endif
5716
5717 /*
5718 * No need to play tricks if not running Windows 95, unless the file name
5719 * contains a "~" as the seventh character.
5720 */
5721 if (!mch_windows95())
5722 {
5723 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5724 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5725 return rename(pszOldFile, pszNewFile);
5726 }
5727
5728 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5729 * a directory, no error is returned and pszFilePart will be NULL. */
5730 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5731 || pszFilePart == NULL)
5732 return -1;
5733 *pszFilePart = NUL;
5734
5735 /* Get (and create) a unique temporary file name in directory of new file */
5736 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5737 return -2;
5738
5739 /* blow the temp file away */
5740 if (!DeleteFile(szTempFile))
5741 return -3;
5742
5743 /* rename old file to the temp file */
5744 if (!MoveFile(pszOldFile, szTempFile))
5745 return -4;
5746
5747 /* now create an empty file called pszOldFile; this prevents the operating
5748 * system using pszOldFile as an alias (SFN) if we're renaming within the
5749 * same directory. For example, we're editing a file called
5750 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5751 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5752 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005753 * cause all sorts of problems later in buf_write(). So, we create an
5754 * empty file called filena~1.txt and the system will have to find some
5755 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005756 */
5757 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5758 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5759 return -5;
5760 if (!CloseHandle(hf))
5761 return -6;
5762
5763 /* rename the temp file to the new file */
5764 if (!MoveFile(szTempFile, pszNewFile))
5765 {
5766 /* Renaming failed. Rename the file back to its old name, so that it
5767 * looks like nothing happened. */
5768 (void)MoveFile(szTempFile, pszOldFile);
5769
5770 return -7;
5771 }
5772
5773 /* Seems to be left around on Novell filesystems */
5774 DeleteFile(szTempFile);
5775
5776 /* finally, remove the empty old file */
5777 if (!DeleteFile(pszOldFile))
5778 return -8;
5779
5780 return 0; /* success */
5781}
5782
5783/*
5784 * Get the default shell for the current hardware platform
5785 */
5786 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005787default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005788{
5789 char* psz = NULL;
5790
5791 PlatformId();
5792
5793 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5794 psz = "cmd.exe";
5795 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5796 psz = "command.com";
5797
5798 return psz;
5799}
5800
5801/*
5802 * mch_access() extends access() to do more detailed check on network drives.
5803 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5804 */
5805 int
5806mch_access(char *n, int p)
5807{
5808 HANDLE hFile;
5809 DWORD am;
5810 int retval = -1; /* default: fail */
5811#ifdef FEAT_MBYTE
5812 WCHAR *wn = NULL;
5813
5814 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005815 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005816#endif
5817
5818 if (mch_isdir(n))
5819 {
5820 char TempName[_MAX_PATH + 16] = "";
5821#ifdef FEAT_MBYTE
5822 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5823#endif
5824
5825 if (p & R_OK)
5826 {
5827 /* Read check is performed by seeing if we can do a find file on
5828 * the directory for any file. */
5829#ifdef FEAT_MBYTE
5830 if (wn != NULL)
5831 {
5832 int i;
5833 WIN32_FIND_DATAW d;
5834
5835 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5836 TempNameW[i] = wn[i];
5837 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5838 TempNameW[i++] = '\\';
5839 TempNameW[i++] = '*';
5840 TempNameW[i++] = 0;
5841
5842 hFile = FindFirstFileW(TempNameW, &d);
5843 if (hFile == INVALID_HANDLE_VALUE)
5844 {
5845 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5846 goto getout;
5847
5848 /* Retry with non-wide function (for Windows 98). */
5849 vim_free(wn);
5850 wn = NULL;
5851 }
5852 else
5853 (void)FindClose(hFile);
5854 }
5855 if (wn == NULL)
5856#endif
5857 {
5858 char *pch;
5859 WIN32_FIND_DATA d;
5860
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005861 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005862 pch = TempName + STRLEN(TempName) - 1;
5863 if (*pch != '\\' && *pch != '/')
5864 *++pch = '\\';
5865 *++pch = '*';
5866 *++pch = NUL;
5867
5868 hFile = FindFirstFile(TempName, &d);
5869 if (hFile == INVALID_HANDLE_VALUE)
5870 goto getout;
5871 (void)FindClose(hFile);
5872 }
5873 }
5874
5875 if (p & W_OK)
5876 {
5877 /* Trying to create a temporary file in the directory should catch
5878 * directories on read-only network shares. However, in
5879 * directories whose ACL allows writes but denies deletes will end
5880 * up keeping the temporary file :-(. */
5881#ifdef FEAT_MBYTE
5882 if (wn != NULL)
5883 {
5884 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5885 {
5886 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5887 goto getout;
5888
5889 /* Retry with non-wide function (for Windows 98). */
5890 vim_free(wn);
5891 wn = NULL;
5892 }
5893 else
5894 DeleteFileW(TempNameW);
5895 }
5896 if (wn == NULL)
5897#endif
5898 {
5899 if (!GetTempFileName(n, "VIM", 0, TempName))
5900 goto getout;
5901 mch_remove((char_u *)TempName);
5902 }
5903 }
5904 }
5905 else
5906 {
5907 /* Trying to open the file for the required access does ACL, read-only
5908 * network share, and file attribute checks. */
5909 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5910 | ((p & R_OK) ? GENERIC_READ : 0);
5911#ifdef FEAT_MBYTE
5912 if (wn != NULL)
5913 {
5914 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5915 if (hFile == INVALID_HANDLE_VALUE
5916 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5917 {
5918 /* Retry with non-wide function (for Windows 98). */
5919 vim_free(wn);
5920 wn = NULL;
5921 }
5922 }
5923 if (wn == NULL)
5924#endif
5925 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5926 if (hFile == INVALID_HANDLE_VALUE)
5927 goto getout;
5928 CloseHandle(hFile);
5929 }
5930
5931 retval = 0; /* success */
5932getout:
5933#ifdef FEAT_MBYTE
5934 vim_free(wn);
5935#endif
5936 return retval;
5937}
5938
5939#if defined(FEAT_MBYTE) || defined(PROTO)
5940/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005941 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005942 */
5943 int
5944mch_open(char *name, int flags, int mode)
5945{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005946 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5947# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005948 WCHAR *wn;
5949 int f;
5950
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005951 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005953 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005954 if (wn != NULL)
5955 {
5956 f = _wopen(wn, flags, mode);
5957 vim_free(wn);
5958 if (f >= 0)
5959 return f;
5960 /* Retry with non-wide function (for Windows 98). Can't use
5961 * GetLastError() here and it's unclear what errno gets set to if
5962 * the _wopen() fails for missing wide functions. */
5963 }
5964 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005965# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005966
5967 return open(name, flags, mode);
5968}
5969
5970/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005971 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972 */
5973 FILE *
5974mch_fopen(char *name, char *mode)
5975{
5976 WCHAR *wn, *wm;
5977 FILE *f = NULL;
5978
5979 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5980# ifdef __BORLANDC__
5981 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5982 && g_PlatformId == VER_PLATFORM_WIN32_NT
5983# endif
5984 )
5985 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005986# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005987 /* Work around an annoying assertion in the Microsoft debug CRT
5988 * when mode's text/binary setting doesn't match _get_fmode(). */
5989 char newMode = mode[strlen(mode) - 1];
5990 int oldMode = 0;
5991
5992 _get_fmode(&oldMode);
5993 if (newMode == 't')
5994 _set_fmode(_O_TEXT);
5995 else if (newMode == 'b')
5996 _set_fmode(_O_BINARY);
5997# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005998 wn = enc_to_utf16(name, NULL);
5999 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006000 if (wn != NULL && wm != NULL)
6001 f = _wfopen(wn, wm);
6002 vim_free(wn);
6003 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006004
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006005# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006006 _set_fmode(oldMode);
6007# endif
6008
Bram Moolenaar071d4272004-06-13 20:20:40 +00006009 if (f != NULL)
6010 return f;
6011 /* Retry with non-wide function (for Windows 98). Can't use
6012 * GetLastError() here and it's unclear what errno gets set to if
6013 * the _wfopen() fails for missing wide functions. */
6014 }
6015
6016 return fopen(name, mode);
6017}
6018#endif
6019
6020#ifdef FEAT_MBYTE
6021/*
6022 * SUB STREAM (aka info stream) handling:
6023 *
6024 * NTFS can have sub streams for each file. Normal contents of file is
6025 * stored in the main stream, and extra contents (author information and
6026 * title and so on) can be stored in sub stream. After Windows 2000, user
6027 * can access and store those informations in sub streams via explorer's
6028 * property menuitem in right click menu. Those informations in sub streams
6029 * were lost when copying only the main stream. So we have to copy sub
6030 * streams.
6031 *
6032 * Incomplete explanation:
6033 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6034 * More useful info and an example:
6035 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6036 */
6037
6038/*
6039 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6040 * and write to stream "substream" of file "to".
6041 * Errors are ignored.
6042 */
6043 static void
6044copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6045{
6046 HANDLE hTo;
6047 WCHAR *to_name;
6048
6049 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6050 wcscpy(to_name, to);
6051 wcscat(to_name, substream);
6052
6053 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6054 FILE_ATTRIBUTE_NORMAL, NULL);
6055 if (hTo != INVALID_HANDLE_VALUE)
6056 {
6057 long done;
6058 DWORD todo;
6059 DWORD readcnt, written;
6060 char buf[4096];
6061
6062 /* Copy block of bytes at a time. Abort when something goes wrong. */
6063 for (done = 0; done < len; done += written)
6064 {
6065 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006066 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6067 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006068 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6069 FALSE, FALSE, context)
6070 || readcnt != todo
6071 || !WriteFile(hTo, buf, todo, &written, NULL)
6072 || written != todo)
6073 break;
6074 }
6075 CloseHandle(hTo);
6076 }
6077
6078 free(to_name);
6079}
6080
6081/*
6082 * Copy info streams from file "from" to file "to".
6083 */
6084 static void
6085copy_infostreams(char_u *from, char_u *to)
6086{
6087 WCHAR *fromw;
6088 WCHAR *tow;
6089 HANDLE sh;
6090 WIN32_STREAM_ID sid;
6091 int headersize;
6092 WCHAR streamname[_MAX_PATH];
6093 DWORD readcount;
6094 void *context = NULL;
6095 DWORD lo, hi;
6096 int len;
6097
6098 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006099 fromw = enc_to_utf16(from, NULL);
6100 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006101 if (fromw != NULL && tow != NULL)
6102 {
6103 /* Open the file for reading. */
6104 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6105 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6106 if (sh != INVALID_HANDLE_VALUE)
6107 {
6108 /* Use BackupRead() to find the info streams. Repeat until we
6109 * have done them all.*/
6110 for (;;)
6111 {
6112 /* Get the header to find the length of the stream name. If
6113 * the "readcount" is zero we have done all info streams. */
6114 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006115 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006116 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6117 &readcount, FALSE, FALSE, &context)
6118 || readcount == 0)
6119 break;
6120
6121 /* We only deal with streams that have a name. The normal
6122 * file data appears to be without a name, even though docs
6123 * suggest it is called "::$DATA". */
6124 if (sid.dwStreamNameSize > 0)
6125 {
6126 /* Read the stream name. */
6127 if (!BackupRead(sh, (LPBYTE)streamname,
6128 sid.dwStreamNameSize,
6129 &readcount, FALSE, FALSE, &context))
6130 break;
6131
6132 /* Copy an info stream with a name ":anything:$DATA".
6133 * Skip "::$DATA", it has no stream name (examples suggest
6134 * it might be used for the normal file contents).
6135 * Note that BackupRead() counts bytes, but the name is in
6136 * wide characters. */
6137 len = readcount / sizeof(WCHAR);
6138 streamname[len] = 0;
6139 if (len > 7 && wcsicmp(streamname + len - 6,
6140 L":$DATA") == 0)
6141 {
6142 streamname[len - 6] = 0;
6143 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006144 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006145 }
6146 }
6147
6148 /* Advance to the next stream. We might try seeking too far,
6149 * but BackupSeek() doesn't skip over stream borders, thus
6150 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006151 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006152 &lo, &hi, &context);
6153 }
6154
6155 /* Clear the context. */
6156 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6157
6158 CloseHandle(sh);
6159 }
6160 }
6161 vim_free(fromw);
6162 vim_free(tow);
6163}
6164#endif
6165
6166/*
6167 * Copy file attributes from file "from" to file "to".
6168 * For Windows NT and later we copy info streams.
6169 * Always returns zero, errors are ignored.
6170 */
6171 int
6172mch_copy_file_attribute(char_u *from, char_u *to)
6173{
6174#ifdef FEAT_MBYTE
6175 /* File streams only work on Windows NT and later. */
6176 PlatformId();
6177 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6178 copy_infostreams(from, to);
6179#endif
6180 return 0;
6181}
6182
6183#if defined(MYRESETSTKOFLW) || defined(PROTO)
6184/*
6185 * Recreate a destroyed stack guard page in win32.
6186 * Written by Benjamin Peterson.
6187 */
6188
6189/* These magic numbers are from the MS header files */
6190#define MIN_STACK_WIN9X 17
6191#define MIN_STACK_WINNT 2
6192
6193/*
6194 * This function does the same thing as _resetstkoflw(), which is only
6195 * available in DevStudio .net and later.
6196 * Returns 0 for failure, 1 for success.
6197 */
6198 int
6199myresetstkoflw(void)
6200{
6201 BYTE *pStackPtr;
6202 BYTE *pGuardPage;
6203 BYTE *pStackBase;
6204 BYTE *pLowestPossiblePage;
6205 MEMORY_BASIC_INFORMATION mbi;
6206 SYSTEM_INFO si;
6207 DWORD nPageSize;
6208 DWORD dummy;
6209
6210 /* This code will not work on win32s. */
6211 PlatformId();
6212 if (g_PlatformId == VER_PLATFORM_WIN32s)
6213 return 0;
6214
6215 /* We need to know the system page size. */
6216 GetSystemInfo(&si);
6217 nPageSize = si.dwPageSize;
6218
6219 /* ...and the current stack pointer */
6220 pStackPtr = (BYTE*)_alloca(1);
6221
6222 /* ...and the base of the stack. */
6223 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6224 return 0;
6225 pStackBase = (BYTE*)mbi.AllocationBase;
6226
6227 /* ...and the page thats min_stack_req pages away from stack base; this is
6228 * the lowest page we could use. */
6229 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6230 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6231
6232 /* On Win95, we want the next page down from the end of the stack. */
6233 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6234 {
6235 /* Find the page that's only 1 page down from the page that the stack
6236 * ptr is in. */
6237 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6238 / (DWORD)nPageSize) - 1));
6239 if (pGuardPage < pLowestPossiblePage)
6240 return 0;
6241
6242 /* Apply the noaccess attribute to the page -- there's no guard
6243 * attribute in win95-type OSes. */
6244 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6245 return 0;
6246 }
6247 else
6248 {
6249 /* On NT, however, we want the first committed page in the stack Start
6250 * at the stack base and move forward through memory until we find a
6251 * committed block. */
6252 BYTE *pBlock = pStackBase;
6253
Bram Moolenaara466c992005-07-09 21:03:22 +00006254 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 {
6256 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6257 return 0;
6258
6259 pBlock += mbi.RegionSize;
6260
6261 if (mbi.State & MEM_COMMIT)
6262 break;
6263 }
6264
6265 /* mbi now describes the first committed block in the stack. */
6266 if (mbi.Protect & PAGE_GUARD)
6267 return 1;
6268
6269 /* decide where the guard page should start */
6270 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6271 pGuardPage = pLowestPossiblePage;
6272 else
6273 pGuardPage = (BYTE*)mbi.BaseAddress;
6274
6275 /* allocate the guard page */
6276 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6277 return 0;
6278
6279 /* apply the guard attribute to the page */
6280 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6281 &dummy))
6282 return 0;
6283 }
6284
6285 return 1;
6286}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006287#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006289
6290#if defined(FEAT_MBYTE) || defined(PROTO)
6291/*
6292 * The command line arguments in UCS2
6293 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006294static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006295static LPWSTR *ArglistW = NULL;
6296static int global_argc = 0;
6297static char **global_argv;
6298
6299static int used_file_argc = 0; /* last argument in global_argv[] used
6300 for the argument list. */
6301static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6302 command line arguments added to
6303 the argument list */
6304static int used_file_count = 0; /* nr of entries in used_file_indexes */
6305static int used_file_literal = FALSE; /* take file names literally */
6306static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006307static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006308static int used_alist_count = 0;
6309
6310
6311/*
6312 * Get the command line arguments. Unicode version.
6313 * Returns argc. Zero when something fails.
6314 */
6315 int
6316get_cmd_argsW(char ***argvp)
6317{
6318 char **argv = NULL;
6319 int argc = 0;
6320 int i;
6321
6322 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6323 if (ArglistW != NULL)
6324 {
6325 argv = malloc((nArgsW + 1) * sizeof(char *));
6326 if (argv != NULL)
6327 {
6328 argc = nArgsW;
6329 argv[argc] = NULL;
6330 for (i = 0; i < argc; ++i)
6331 {
6332 int len;
6333
6334 /* Convert each Unicode argument to the current codepage. */
6335 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006336 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006337 (LPSTR *)&argv[i], &len, 0, 0);
6338 if (argv[i] == NULL)
6339 {
6340 /* Out of memory, clear everything. */
6341 while (i > 0)
6342 free(argv[--i]);
6343 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006344 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006345 argc = 0;
6346 }
6347 }
6348 }
6349 }
6350
6351 global_argc = argc;
6352 global_argv = argv;
6353 if (argc > 0)
6354 used_file_indexes = malloc(argc * sizeof(int));
6355
6356 if (argvp != NULL)
6357 *argvp = argv;
6358 return argc;
6359}
6360
6361 void
6362free_cmd_argsW(void)
6363{
6364 if (ArglistW != NULL)
6365 {
6366 GlobalFree(ArglistW);
6367 ArglistW = NULL;
6368 }
6369}
6370
6371/*
6372 * Remember "name" is an argument that was added to the argument list.
6373 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6374 * is called.
6375 */
6376 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006377used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006378{
6379 int i;
6380
6381 if (used_file_indexes == NULL)
6382 return;
6383 for (i = used_file_argc + 1; i < global_argc; ++i)
6384 if (STRCMP(global_argv[i], name) == 0)
6385 {
6386 used_file_argc = i;
6387 used_file_indexes[used_file_count++] = i;
6388 break;
6389 }
6390 used_file_literal = literal;
6391 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006392 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006393}
6394
6395/*
6396 * Remember the length of the argument list as it was. If it changes then we
6397 * leave it alone when 'encoding' is set.
6398 */
6399 void
6400set_alist_count(void)
6401{
6402 used_alist_count = GARGCOUNT;
6403}
6404
6405/*
6406 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6407 * has been changed while starting up. Use the UCS-2 command line arguments
6408 * and convert them to 'encoding'.
6409 */
6410 void
6411fix_arg_enc(void)
6412{
6413 int i;
6414 int idx;
6415 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006416 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006417
6418 /* Safety checks:
6419 * - if argument count differs between the wide and non-wide argument
6420 * list, something must be wrong.
6421 * - the file name arguments must have been located.
6422 * - the length of the argument list wasn't changed by the user.
6423 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006424 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006425 || ArglistW == NULL
6426 || used_file_indexes == NULL
6427 || used_file_count == 0
6428 || used_alist_count != GARGCOUNT)
6429 return;
6430
Bram Moolenaar86b68352004-12-27 21:59:20 +00006431 /* Remember the buffer numbers for the arguments. */
6432 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6433 if (fnum_list == NULL)
6434 return; /* out of memory */
6435 for (i = 0; i < GARGCOUNT; ++i)
6436 fnum_list[i] = GARGLIST[i].ae_fnum;
6437
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006438 /* Clear the argument list. Make room for the new arguments. */
6439 alist_clear(&global_alist);
6440 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006441 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006442
6443 for (i = 0; i < used_file_count; ++i)
6444 {
6445 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006446 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006447 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006448 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006449#ifdef FEAT_DIFF
6450 /* When using diff mode may need to concatenate file name to
6451 * directory name. Just like it's done in main(). */
6452 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6453 && !mch_isdir(alist_name(&GARGLIST[0])))
6454 {
6455 char_u *r;
6456
6457 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6458 if (r != NULL)
6459 {
6460 vim_free(str);
6461 str = r;
6462 }
6463 }
6464#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006465 /* Re-use the old buffer by renaming it. When not using literal
6466 * names it's done by alist_expand() below. */
6467 if (used_file_literal)
6468 buf_set_name(fnum_list[i], str);
6469
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006470 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006471 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006472 }
6473
6474 if (!used_file_literal)
6475 {
6476 /* Now expand wildcards in the arguments. */
6477 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6478 * filename characters but are excluded from 'isfname' to make
6479 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6480 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006481 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006482 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6483 }
6484
6485 /* If wildcard expansion failed, we are editing the first file of the
6486 * arglist and there is no file name: Edit the first argument now. */
6487 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6488 {
6489 do_cmdline_cmd((char_u *)":rewind");
6490 if (GARGCOUNT == 1 && used_file_full_path)
6491 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6492 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006493
6494 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006495}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006496#endif