blob: 06cc315e5537b0c73b72d50c4cc1459d8554f634 [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
2811 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002812 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002813}
2814
2815
2816/*
2817 * return process ID
2818 */
2819 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002820mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002821{
2822 return (long)GetCurrentProcessId();
2823}
2824
2825
2826/*
2827 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2828 * Return OK for success, FAIL for failure.
2829 */
2830 int
2831mch_dirname(
2832 char_u *buf,
2833 int len)
2834{
2835 /*
2836 * Originally this was:
2837 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2838 * But the Win32s known bug list says that getcwd() doesn't work
2839 * so use the Win32 system call instead. <Negri>
2840 */
2841#ifdef FEAT_MBYTE
2842 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2843 {
2844 WCHAR wbuf[_MAX_PATH + 1];
2845
2846 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2847 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002848 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849
2850 if (p != NULL)
2851 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002852 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853 vim_free(p);
2854 return OK;
2855 }
2856 }
2857 /* Retry with non-wide function (for Windows 98). */
2858 }
2859#endif
2860 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2861}
2862
2863/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002864 * Get file permissions for "name".
2865 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866 */
2867 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002868mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002870 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002871 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872
Bram Moolenaarffa22202013-11-21 12:34:11 +01002873 if (name[0] == '\\' && name[1] == '\\')
2874 /* UNC path */
2875 return (long)win32_getattrs(name);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002876 n = mch_stat(name, &st);
Bram Moolenaarffa22202013-11-21 12:34:11 +01002877 return n == 0 ? (long)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878}
2879
2880
2881/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002882 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002883 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002884 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 */
2886 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002887mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002888{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002889 long n = -1;
2890
Bram Moolenaar071d4272004-06-13 20:20:40 +00002891#ifdef FEAT_MBYTE
2892 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2893 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002894 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002895
2896 if (p != NULL)
2897 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002898 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002900 if (n == -1 && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2901 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002902 /* Retry with non-wide function (for Windows 98). */
2903 }
2904 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002905 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002907 n = _chmod(name, perm);
2908 if (n == -1)
2909 return FAIL;
2910
2911 win32_set_archive(name);
2912
2913 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914}
2915
2916/*
2917 * Set hidden flag for "name".
2918 */
2919 void
2920mch_hide(char_u *name)
2921{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002922 int attrs = win32_getattrs(name);
2923 if (attrs == -1)
2924 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002926 attrs |= FILE_ATTRIBUTE_HIDDEN;
2927 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002928}
2929
2930/*
2931 * return TRUE if "name" is a directory
2932 * return FALSE if "name" is not a directory or upon error
2933 */
2934 int
2935mch_isdir(char_u *name)
2936{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002937 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002938
2939 if (f == -1)
2940 return FALSE; /* file does not exist at all */
2941
2942 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2943}
2944
2945/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002946 * Create directory "name".
2947 * Return 0 on success, -1 on error.
2948 */
2949 int
2950mch_mkdir(char_u *name)
2951{
2952#ifdef FEAT_MBYTE
2953 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2954 {
2955 WCHAR *p;
2956 int retval;
2957
2958 p = enc_to_utf16(name, NULL);
2959 if (p == NULL)
2960 return -1;
2961 retval = _wmkdir(p);
2962 vim_free(p);
2963 return retval;
2964 }
2965#endif
2966 return _mkdir(name);
2967}
2968
2969/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002970 * Return TRUE if file "fname" has more than one link.
2971 */
2972 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002973mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002974{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002975 BY_HANDLE_FILE_INFORMATION info;
2976
2977 return win32_fileinfo(fname, &info) == FILEINFO_OK
2978 && info.nNumberOfLinks > 1;
2979}
2980
2981/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002982 * Return TRUE if file "fname" is a symbolic link.
2983 */
2984 int
2985mch_is_symbolic_link(char_u *fname)
2986{
2987 HANDLE hFind;
2988 int res = FALSE;
2989 WIN32_FIND_DATAA findDataA;
2990 DWORD fileFlags = 0, reparseTag = 0;
2991#ifdef FEAT_MBYTE
2992 WCHAR *wn = NULL;
2993 WIN32_FIND_DATAW findDataW;
2994
2995 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2996 wn = enc_to_utf16(fname, NULL);
2997 if (wn != NULL)
2998 {
2999 hFind = FindFirstFileW(wn, &findDataW);
3000 vim_free(wn);
3001 if (hFind == INVALID_HANDLE_VALUE
3002 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3003 {
3004 /* Retry with non-wide function (for Windows 98). */
3005 hFind = FindFirstFile(fname, &findDataA);
3006 if (hFind != INVALID_HANDLE_VALUE)
3007 {
3008 fileFlags = findDataA.dwFileAttributes;
3009 reparseTag = findDataA.dwReserved0;
3010 }
3011 }
3012 else
3013 {
3014 fileFlags = findDataW.dwFileAttributes;
3015 reparseTag = findDataW.dwReserved0;
3016 }
3017 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003018 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003019#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003020 {
3021 hFind = FindFirstFile(fname, &findDataA);
3022 if (hFind != INVALID_HANDLE_VALUE)
3023 {
3024 fileFlags = findDataA.dwFileAttributes;
3025 reparseTag = findDataA.dwReserved0;
3026 }
3027 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003028
3029 if (hFind != INVALID_HANDLE_VALUE)
3030 FindClose(hFind);
3031
3032 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3033 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3034 res = TRUE;
3035
3036 return res;
3037}
3038
3039/*
3040 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3041 * link.
3042 */
3043 int
3044mch_is_linked(char_u *fname)
3045{
3046 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3047 return TRUE;
3048 return FALSE;
3049}
3050
3051/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003052 * Get the by-handle-file-information for "fname".
3053 * Returns FILEINFO_OK when OK.
3054 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3055 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3056 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3057 */
3058 int
3059win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3060{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003061 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003062 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003063#ifdef FEAT_MBYTE
3064 WCHAR *wn = NULL;
3065
3066 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003067 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003068 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003069 if (wn == NULL)
3070 res = FILEINFO_ENC_FAIL;
3071 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003072 if (wn != NULL)
3073 {
3074 hFile = CreateFileW(wn, /* file name */
3075 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003076 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003077 NULL, /* security descriptor */
3078 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003079 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003080 NULL); /* handle to template file */
3081 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003082 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003083 {
3084 /* Retry with non-wide function (for Windows 98). */
3085 vim_free(wn);
3086 wn = NULL;
3087 }
3088 }
3089 if (wn == NULL)
3090#endif
3091 hFile = CreateFile(fname, /* 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
3099 if (hFile != INVALID_HANDLE_VALUE)
3100 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003101 if (GetFileInformationByHandle(hFile, info) != 0)
3102 res = FILEINFO_OK;
3103 else
3104 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003105 CloseHandle(hFile);
3106 }
3107
3108#ifdef FEAT_MBYTE
3109 vim_free(wn);
3110#endif
3111 return res;
3112}
3113
3114/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003115 * get file attributes for `name'
3116 * -1 : error
3117 * else FILE_ATTRIBUTE_* defined in winnt.h
3118 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003119 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003120win32_getattrs(char_u *name)
3121{
3122 int attr;
3123#ifdef FEAT_MBYTE
3124 WCHAR *p = NULL;
3125
3126 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3127 p = enc_to_utf16(name, NULL);
3128
3129 if (p != NULL)
3130 {
3131 attr = GetFileAttributesW(p);
3132 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3133 {
3134 /* Retry with non-wide function (for Windows 98). */
3135 vim_free(p);
3136 p = NULL;
3137 }
3138 }
3139 if (p == NULL)
3140#endif
3141 attr = GetFileAttributes((char *)name);
3142#ifdef FEAT_MBYTE
3143 vim_free(p);
3144#endif
3145 return attr;
3146}
3147
3148/*
3149 * set file attributes for `name' to `attrs'
3150 *
3151 * return -1 for failure, 0 otherwise
3152 */
3153 static
3154 int
3155win32_setattrs(char_u *name, int attrs)
3156{
3157 int res;
3158#ifdef FEAT_MBYTE
3159 WCHAR *p = NULL;
3160
3161 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3162 p = enc_to_utf16(name, NULL);
3163
3164 if (p != NULL)
3165 {
3166 res = SetFileAttributesW(p, attrs);
3167 if (res == FALSE
3168 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3169 {
3170 /* Retry with non-wide function (for Windows 98). */
3171 vim_free(p);
3172 p = NULL;
3173 }
3174 }
3175 if (p == NULL)
3176#endif
3177 res = SetFileAttributes((char *)name, attrs);
3178#ifdef FEAT_MBYTE
3179 vim_free(p);
3180#endif
3181 return res ? 0 : -1;
3182}
3183
3184/*
3185 * Set archive flag for "name".
3186 */
3187 static
3188 int
3189win32_set_archive(char_u *name)
3190{
3191 int attrs = win32_getattrs(name);
3192 if (attrs == -1)
3193 return -1;
3194
3195 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3196 return win32_setattrs(name, attrs);
3197}
3198
3199/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003200 * Return TRUE if file or directory "name" is writable (not readonly).
3201 * Strange semantics of Win32: a readonly directory is writable, but you can't
3202 * delete a file. Let's say this means it is writable.
3203 */
3204 int
3205mch_writable(char_u *name)
3206{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003207 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003208
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003209 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3210 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003211}
3212
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213/*
3214 * Return 1 if "name" can be executed, 0 if not.
3215 * Return -1 if unknown.
3216 */
3217 int
3218mch_can_exe(char_u *name)
3219{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003220 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003221 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003222 char_u *p;
3223
3224 if (len >= _MAX_PATH) /* safety check */
3225 return FALSE;
3226
3227 /* If there already is an extension try using the name directly. Also do
3228 * this with a Unix-shell like 'shell'. */
3229 if (vim_strchr(gettail(name), '.') != NULL
3230 || strstr((char *)gettail(p_sh), "sh") != NULL)
3231 if (executable_exists((char *)name))
3232 return TRUE;
3233
3234 /*
3235 * Loop over all extensions in $PATHEXT.
3236 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003237 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003238 p = mch_getenv("PATHEXT");
3239 if (p == NULL)
3240 p = (char_u *)".com;.exe;.bat;.cmd";
3241 while (*p)
3242 {
3243 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3244 {
3245 /* A single "." means no extension is added. */
3246 buf[len] = NUL;
3247 ++p;
3248 if (*p)
3249 ++p;
3250 }
3251 else
3252 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
3253 if (executable_exists((char *)buf))
3254 return TRUE;
3255 }
3256 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258
3259/*
3260 * Check what "name" is:
3261 * NODE_NORMAL: file or directory (or doesn't exist)
3262 * NODE_WRITABLE: writable device, socket, fifo, etc.
3263 * NODE_OTHER: non-writable things
3264 */
3265 int
3266mch_nodetype(char_u *name)
3267{
3268 HANDLE hFile;
3269 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003270#ifdef FEAT_MBYTE
3271 WCHAR *wn = NULL;
3272#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273
Bram Moolenaar043545e2006-10-10 16:44:07 +00003274 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3275 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3276 * here. */
3277 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3278 return NODE_WRITABLE;
3279
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003280#ifdef FEAT_MBYTE
3281 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3282 {
3283 wn = enc_to_utf16(name, NULL);
3284 if (wn != NULL)
3285 {
3286 hFile = CreateFileW(wn, /* file name */
3287 GENERIC_WRITE, /* access mode */
3288 0, /* share mode */
3289 NULL, /* security descriptor */
3290 OPEN_EXISTING, /* creation disposition */
3291 0, /* file attributes */
3292 NULL); /* handle to template file */
3293 if (hFile == INVALID_HANDLE_VALUE
3294 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3295 {
3296 /* Retry with non-wide function (for Windows 98). */
3297 vim_free(wn);
3298 wn = NULL;
3299 }
3300 }
3301 }
3302 if (wn == NULL)
3303#endif
3304 hFile = CreateFile(name, /* file name */
3305 GENERIC_WRITE, /* access mode */
3306 0, /* share mode */
3307 NULL, /* security descriptor */
3308 OPEN_EXISTING, /* creation disposition */
3309 0, /* file attributes */
3310 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003311
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003312#ifdef FEAT_MBYTE
3313 vim_free(wn);
3314#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003315 if (hFile == INVALID_HANDLE_VALUE)
3316 return NODE_NORMAL;
3317
3318 type = GetFileType(hFile);
3319 CloseHandle(hFile);
3320 if (type == FILE_TYPE_CHAR)
3321 return NODE_WRITABLE;
3322 if (type == FILE_TYPE_DISK)
3323 return NODE_NORMAL;
3324 return NODE_OTHER;
3325}
3326
3327#ifdef HAVE_ACL
3328struct my_acl
3329{
3330 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3331 PSID pSidOwner;
3332 PSID pSidGroup;
3333 PACL pDacl;
3334 PACL pSacl;
3335};
3336#endif
3337
3338/*
3339 * Return a pointer to the ACL of file "fname" in allocated memory.
3340 * Return NULL if the ACL is not available for whatever reason.
3341 */
3342 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003343mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344{
3345#ifndef HAVE_ACL
3346 return (vim_acl_T)NULL;
3347#else
3348 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003349 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003350
3351 /* This only works on Windows NT and 2000. */
3352 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3353 {
3354 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3355 if (p != NULL)
3356 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003357# ifdef FEAT_MBYTE
3358 WCHAR *wn = NULL;
3359
3360 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3361 wn = enc_to_utf16(fname, NULL);
3362 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003364 /* Try to retrieve the entire security descriptor. */
3365 err = pGetNamedSecurityInfoW(
3366 wn, // Abstract filename
3367 SE_FILE_OBJECT, // File Object
3368 OWNER_SECURITY_INFORMATION |
3369 GROUP_SECURITY_INFORMATION |
3370 DACL_SECURITY_INFORMATION |
3371 SACL_SECURITY_INFORMATION,
3372 &p->pSidOwner, // Ownership information.
3373 &p->pSidGroup, // Group membership.
3374 &p->pDacl, // Discretionary information.
3375 &p->pSacl, // For auditing purposes.
3376 &p->pSecurityDescriptor);
3377 if (err == ERROR_ACCESS_DENIED ||
3378 err == ERROR_PRIVILEGE_NOT_HELD)
3379 {
3380 /* Retrieve only DACL. */
3381 (void)pGetNamedSecurityInfoW(
3382 wn,
3383 SE_FILE_OBJECT,
3384 DACL_SECURITY_INFORMATION,
3385 NULL,
3386 NULL,
3387 &p->pDacl,
3388 NULL,
3389 &p->pSecurityDescriptor);
3390 }
3391 if (p->pSecurityDescriptor == NULL)
3392 {
3393 mch_free_acl((vim_acl_T)p);
3394 p = NULL;
3395 }
3396 vim_free(wn);
3397 }
3398 else
3399# endif
3400 {
3401 /* Try to retrieve the entire security descriptor. */
3402 err = pGetNamedSecurityInfo(
3403 (LPSTR)fname, // Abstract filename
3404 SE_FILE_OBJECT, // File Object
3405 OWNER_SECURITY_INFORMATION |
3406 GROUP_SECURITY_INFORMATION |
3407 DACL_SECURITY_INFORMATION |
3408 SACL_SECURITY_INFORMATION,
3409 &p->pSidOwner, // Ownership information.
3410 &p->pSidGroup, // Group membership.
3411 &p->pDacl, // Discretionary information.
3412 &p->pSacl, // For auditing purposes.
3413 &p->pSecurityDescriptor);
3414 if (err == ERROR_ACCESS_DENIED ||
3415 err == ERROR_PRIVILEGE_NOT_HELD)
3416 {
3417 /* Retrieve only DACL. */
3418 (void)pGetNamedSecurityInfo(
3419 (LPSTR)fname,
3420 SE_FILE_OBJECT,
3421 DACL_SECURITY_INFORMATION,
3422 NULL,
3423 NULL,
3424 &p->pDacl,
3425 NULL,
3426 &p->pSecurityDescriptor);
3427 }
3428 if (p->pSecurityDescriptor == NULL)
3429 {
3430 mch_free_acl((vim_acl_T)p);
3431 p = NULL;
3432 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003433 }
3434 }
3435 }
3436
3437 return (vim_acl_T)p;
3438#endif
3439}
3440
Bram Moolenaar27515922013-06-29 15:36:26 +02003441#ifdef HAVE_ACL
3442/*
3443 * Check if "acl" contains inherited ACE.
3444 */
3445 static BOOL
3446is_acl_inherited(PACL acl)
3447{
3448 DWORD i;
3449 ACL_SIZE_INFORMATION acl_info;
3450 PACCESS_ALLOWED_ACE ace;
3451
3452 acl_info.AceCount = 0;
3453 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3454 for (i = 0; i < acl_info.AceCount; i++)
3455 {
3456 GetAce(acl, i, (LPVOID *)&ace);
3457 if (ace->Header.AceFlags & INHERITED_ACE)
3458 return TRUE;
3459 }
3460 return FALSE;
3461}
3462#endif
3463
Bram Moolenaar071d4272004-06-13 20:20:40 +00003464/*
3465 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3466 * Errors are ignored.
3467 * This must only be called with "acl" equal to what mch_get_acl() returned.
3468 */
3469 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003470mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471{
3472#ifdef HAVE_ACL
3473 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003474 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003475
3476 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003477 {
3478# ifdef FEAT_MBYTE
3479 WCHAR *wn = NULL;
3480# endif
3481
3482 /* Set security flags */
3483 if (p->pSidOwner)
3484 sec_info |= OWNER_SECURITY_INFORMATION;
3485 if (p->pSidGroup)
3486 sec_info |= GROUP_SECURITY_INFORMATION;
3487 if (p->pDacl)
3488 {
3489 sec_info |= DACL_SECURITY_INFORMATION;
3490 /* Do not inherit its parent's DACL.
3491 * If the DACL is inherited, Cygwin permissions would be changed.
3492 */
3493 if (!is_acl_inherited(p->pDacl))
3494 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3495 }
3496 if (p->pSacl)
3497 sec_info |= SACL_SECURITY_INFORMATION;
3498
3499# ifdef FEAT_MBYTE
3500 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3501 wn = enc_to_utf16(fname, NULL);
3502 if (wn != NULL)
3503 {
3504 (void)pSetNamedSecurityInfoW(
3505 wn, // Abstract filename
3506 SE_FILE_OBJECT, // File Object
3507 sec_info,
3508 p->pSidOwner, // Ownership information.
3509 p->pSidGroup, // Group membership.
3510 p->pDacl, // Discretionary information.
3511 p->pSacl // For auditing purposes.
3512 );
3513 vim_free(wn);
3514 }
3515 else
3516# endif
3517 {
3518 (void)pSetNamedSecurityInfo(
3519 (LPSTR)fname, // Abstract filename
3520 SE_FILE_OBJECT, // File Object
3521 sec_info,
3522 p->pSidOwner, // Ownership information.
3523 p->pSidGroup, // Group membership.
3524 p->pDacl, // Discretionary information.
3525 p->pSacl // For auditing purposes.
3526 );
3527 }
3528 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003529#endif
3530}
3531
3532 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003533mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003534{
3535#ifdef HAVE_ACL
3536 struct my_acl *p = (struct my_acl *)acl;
3537
3538 if (p != NULL)
3539 {
3540 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3541 vim_free(p);
3542 }
3543#endif
3544}
3545
3546#ifndef FEAT_GUI_W32
3547
3548/*
3549 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3550 */
3551 static BOOL WINAPI
3552handler_routine(
3553 DWORD dwCtrlType)
3554{
3555 switch (dwCtrlType)
3556 {
3557 case CTRL_C_EVENT:
3558 if (ctrl_c_interrupts)
3559 g_fCtrlCPressed = TRUE;
3560 return TRUE;
3561
3562 case CTRL_BREAK_EVENT:
3563 g_fCBrkPressed = TRUE;
3564 return TRUE;
3565
3566 /* fatal events: shut down gracefully */
3567 case CTRL_CLOSE_EVENT:
3568 case CTRL_LOGOFF_EVENT:
3569 case CTRL_SHUTDOWN_EVENT:
3570 windgoto((int)Rows - 1, 0);
3571 g_fForceExit = TRUE;
3572
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003573 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003574 (dwCtrlType == CTRL_CLOSE_EVENT
3575 ? _("close")
3576 : dwCtrlType == CTRL_LOGOFF_EVENT
3577 ? _("logoff")
3578 : _("shutdown")));
3579#ifdef DEBUG
3580 OutputDebugString(IObuff);
3581#endif
3582
3583 preserve_exit(); /* output IObuff, preserve files and exit */
3584
3585 return TRUE; /* not reached */
3586
3587 default:
3588 return FALSE;
3589 }
3590}
3591
3592
3593/*
3594 * set the tty in (raw) ? "raw" : "cooked" mode
3595 */
3596 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003597mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598{
3599 DWORD cmodein;
3600 DWORD cmodeout;
3601 BOOL bEnableHandler;
3602
3603 GetConsoleMode(g_hConIn, &cmodein);
3604 GetConsoleMode(g_hConOut, &cmodeout);
3605 if (tmode == TMODE_RAW)
3606 {
3607 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3608 ENABLE_ECHO_INPUT);
3609#ifdef FEAT_MOUSE
3610 if (g_fMouseActive)
3611 cmodein |= ENABLE_MOUSE_INPUT;
3612#endif
3613 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3614 bEnableHandler = TRUE;
3615 }
3616 else /* cooked */
3617 {
3618 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3619 ENABLE_ECHO_INPUT);
3620 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3621 bEnableHandler = FALSE;
3622 }
3623 SetConsoleMode(g_hConIn, cmodein);
3624 SetConsoleMode(g_hConOut, cmodeout);
3625 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3626
3627#ifdef MCH_WRITE_DUMP
3628 if (fdDump)
3629 {
3630 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3631 tmode == TMODE_RAW ? "raw" :
3632 tmode == TMODE_COOK ? "cooked" : "normal",
3633 cmodein, cmodeout);
3634 fflush(fdDump);
3635 }
3636#endif
3637}
3638
3639
3640/*
3641 * Get the size of the current window in `Rows' and `Columns'
3642 * Return OK when size could be determined, FAIL otherwise.
3643 */
3644 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003645mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003646{
3647 CONSOLE_SCREEN_BUFFER_INFO csbi;
3648
3649 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3650 {
3651 /*
3652 * For some reason, we are trying to get the screen dimensions
3653 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3654 * variables are really intended to mean the size of Vim screen
3655 * while in termcap mode.
3656 */
3657 Rows = g_cbTermcap.Info.dwSize.Y;
3658 Columns = g_cbTermcap.Info.dwSize.X;
3659 }
3660 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3661 {
3662 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3663 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3664 }
3665 else
3666 {
3667 Rows = 25;
3668 Columns = 80;
3669 }
3670 return OK;
3671}
3672
3673/*
3674 * Set a console window to `xSize' * `ySize'
3675 */
3676 static void
3677ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003678 HANDLE hConsole,
3679 int xSize,
3680 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003681{
3682 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3683 SMALL_RECT srWindowRect; /* hold the new console size */
3684 COORD coordScreen;
3685
3686#ifdef MCH_WRITE_DUMP
3687 if (fdDump)
3688 {
3689 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3690 fflush(fdDump);
3691 }
3692#endif
3693
3694 /* get the largest size we can size the console window to */
3695 coordScreen = GetLargestConsoleWindowSize(hConsole);
3696
3697 /* define the new console window size and scroll position */
3698 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3699 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3700 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3701
3702 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3703 {
3704 int sx, sy;
3705
3706 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3707 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3708 if (sy < ySize || sx < xSize)
3709 {
3710 /*
3711 * Increasing number of lines/columns, do buffer first.
3712 * Use the maximal size in x and y direction.
3713 */
3714 if (sy < ySize)
3715 coordScreen.Y = ySize;
3716 else
3717 coordScreen.Y = sy;
3718 if (sx < xSize)
3719 coordScreen.X = xSize;
3720 else
3721 coordScreen.X = sx;
3722 SetConsoleScreenBufferSize(hConsole, coordScreen);
3723 }
3724 }
3725
3726 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3727 {
3728#ifdef MCH_WRITE_DUMP
3729 if (fdDump)
3730 {
3731 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3732 GetLastError());
3733 fflush(fdDump);
3734 }
3735#endif
3736 }
3737
3738 /* define the new console buffer size */
3739 coordScreen.X = xSize;
3740 coordScreen.Y = ySize;
3741
3742 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3743 {
3744#ifdef MCH_WRITE_DUMP
3745 if (fdDump)
3746 {
3747 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3748 GetLastError());
3749 fflush(fdDump);
3750 }
3751#endif
3752 }
3753}
3754
3755
3756/*
3757 * Set the console window to `Rows' * `Columns'
3758 */
3759 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003760mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003761{
3762 COORD coordScreen;
3763
3764 /* Don't change window size while still starting up */
3765 if (suppress_winsize != 0)
3766 {
3767 suppress_winsize = 2;
3768 return;
3769 }
3770
3771 if (term_console)
3772 {
3773 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3774
3775 /* Clamp Rows and Columns to reasonable values */
3776 if (Rows > coordScreen.Y)
3777 Rows = coordScreen.Y;
3778 if (Columns > coordScreen.X)
3779 Columns = coordScreen.X;
3780
3781 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3782 }
3783}
3784
3785/*
3786 * Rows and/or Columns has changed.
3787 */
3788 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003789mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003790{
3791 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3792}
3793
3794
3795/*
3796 * Called when started up, to set the winsize that was delayed.
3797 */
3798 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003799mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003800{
3801 if (suppress_winsize == 2)
3802 {
3803 suppress_winsize = 0;
3804 mch_set_shellsize();
3805 shell_resized();
3806 }
3807 suppress_winsize = 0;
3808}
3809#endif /* FEAT_GUI_W32 */
3810
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003811 static BOOL
3812vim_create_process(
3813 const char *cmd,
3814 DWORD flags,
3815 BOOL inherit_handles,
3816 STARTUPINFO *si,
3817 PROCESS_INFORMATION *pi)
3818{
3819# ifdef FEAT_MBYTE
3820 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3821 {
3822 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
3823
3824 if (wcmd != NULL)
3825 {
3826 BOOL ret;
3827 ret = CreateProcessW(
3828 NULL, /* Executable name */
3829 wcmd, /* Command to execute */
3830 NULL, /* Process security attributes */
3831 NULL, /* Thread security attributes */
3832 inherit_handles, /* Inherit handles */
3833 flags, /* Creation flags */
3834 NULL, /* Environment */
3835 NULL, /* Current directory */
3836 si, /* Startup information */
3837 pi); /* Process information */
3838 vim_free(wcmd);
3839 return ret;
3840 }
3841 }
3842#endif
3843 return CreateProcess(
3844 NULL, /* Executable name */
3845 cmd, /* Command to execute */
3846 NULL, /* Process security attributes */
3847 NULL, /* Thread security attributes */
3848 inherit_handles, /* Inherit handles */
3849 flags, /* Creation flags */
3850 NULL, /* Environment */
3851 NULL, /* Current directory */
3852 si, /* Startup information */
3853 pi); /* Process information */
3854}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003855
3856
3857#if defined(FEAT_GUI_W32) || defined(PROTO)
3858
3859/*
3860 * Specialised version of system() for Win32 GUI mode.
3861 * This version proceeds as follows:
3862 * 1. Create a console window for use by the subprocess
3863 * 2. Run the subprocess (it gets the allocated console by default)
3864 * 3. Wait for the subprocess to terminate and get its exit code
3865 * 4. Prompt the user to press a key to close the console window
3866 */
3867 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003868mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003869{
3870 STARTUPINFO si;
3871 PROCESS_INFORMATION pi;
3872 DWORD ret = 0;
3873 HWND hwnd = GetFocus();
3874
3875 si.cb = sizeof(si);
3876 si.lpReserved = NULL;
3877 si.lpDesktop = NULL;
3878 si.lpTitle = NULL;
3879 si.dwFlags = STARTF_USESHOWWINDOW;
3880 /*
3881 * It's nicer to run a filter command in a minimized window, but in
3882 * Windows 95 this makes the command MUCH slower. We can't do it under
3883 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003884 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885 */
3886 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003887 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003888 else
3889 si.wShowWindow = SW_SHOWNORMAL;
3890 si.cbReserved2 = 0;
3891 si.lpReserved2 = NULL;
3892
3893 /* There is a strange error on Windows 95 when using "c:\\command.com".
3894 * When the "c:\\" is left out it works OK...? */
3895 if (mch_windows95()
3896 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3897 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3898 cmd += 3;
3899
3900 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003901 vim_create_process(cmd, FALSE,
3902 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903
3904 /* Wait for the command to terminate before continuing */
3905 if (g_PlatformId != VER_PLATFORM_WIN32s)
3906 {
3907#ifdef FEAT_GUI
3908 int delay = 1;
3909
3910 /* Keep updating the window while waiting for the shell to finish. */
3911 for (;;)
3912 {
3913 MSG msg;
3914
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003915 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003916 {
3917 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003918 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003919 delay = 1;
3920 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003921 }
3922 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3923 break;
3924
3925 /* We start waiting for a very short time and then increase it, so
3926 * that we respond quickly when the process is quick, and don't
3927 * consume too much overhead when it's slow. */
3928 if (delay < 50)
3929 delay += 10;
3930 }
3931#else
3932 WaitForSingleObject(pi.hProcess, INFINITE);
3933#endif
3934
3935 /* Get the command exit code */
3936 GetExitCodeProcess(pi.hProcess, &ret);
3937 }
3938 else
3939 {
3940 /*
3941 * This ugly code is the only quick way of performing
3942 * a synchronous spawn under Win32s. Yuk.
3943 */
3944 num_windows = 0;
3945 EnumWindows(win32ssynch_cb, 0);
3946 old_num_windows = num_windows;
3947 do
3948 {
3949 Sleep(1000);
3950 num_windows = 0;
3951 EnumWindows(win32ssynch_cb, 0);
3952 } while (num_windows == old_num_windows);
3953 ret = 0;
3954 }
3955
3956 /* Close the handles to the subprocess, so that it goes away */
3957 CloseHandle(pi.hThread);
3958 CloseHandle(pi.hProcess);
3959
3960 /* Try to get input focus back. Doesn't always work though. */
3961 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3962
3963 return ret;
3964}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003965
3966/*
3967 * Thread launched by the gui to send the current buffer data to the
3968 * process. This way avoid to hang up vim totally if the children
3969 * process take a long time to process the lines.
3970 */
3971 static DWORD WINAPI
3972sub_process_writer(LPVOID param)
3973{
3974 HANDLE g_hChildStd_IN_Wr = param;
3975 linenr_T lnum = curbuf->b_op_start.lnum;
3976 DWORD len = 0;
3977 DWORD l;
3978 char_u *lp = ml_get(lnum);
3979 char_u *s;
3980 int written = 0;
3981
3982 for (;;)
3983 {
3984 l = (DWORD)STRLEN(lp + written);
3985 if (l == 0)
3986 len = 0;
3987 else if (lp[written] == NL)
3988 {
3989 /* NL -> NUL translation */
3990 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3991 }
3992 else
3993 {
3994 s = vim_strchr(lp + written, NL);
3995 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3996 s == NULL ? l : (DWORD)(s - (lp + written)),
3997 &len, NULL);
3998 }
3999 if (len == (int)l)
4000 {
4001 /* Finished a line, add a NL, unless this line should not have
4002 * one. */
4003 if (lnum != curbuf->b_op_end.lnum
4004 || !curbuf->b_p_bin
4005 || (lnum != curbuf->b_no_eol_lnum
4006 && (lnum != curbuf->b_ml.ml_line_count
4007 || curbuf->b_p_eol)))
4008 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004009 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004010 }
4011
4012 ++lnum;
4013 if (lnum > curbuf->b_op_end.lnum)
4014 break;
4015
4016 lp = ml_get(lnum);
4017 written = 0;
4018 }
4019 else if (len > 0)
4020 written += len;
4021 }
4022
4023 /* finished all the lines, close pipe */
4024 CloseHandle(g_hChildStd_IN_Wr);
4025 ExitThread(0);
4026}
4027
4028
4029# define BUFLEN 100 /* length for buffer, stolen from unix version */
4030
4031/*
4032 * This function read from the children's stdout and write the
4033 * data on screen or in the buffer accordingly.
4034 */
4035 static void
4036dump_pipe(int options,
4037 HANDLE g_hChildStd_OUT_Rd,
4038 garray_T *ga,
4039 char_u buffer[],
4040 DWORD *buffer_off)
4041{
4042 DWORD availableBytes = 0;
4043 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004044 int ret;
4045 DWORD len;
4046 DWORD toRead;
4047 int repeatCount;
4048
4049 /* we query the pipe to see if there is any data to read
4050 * to avoid to perform a blocking read */
4051 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4052 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004053 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004054 NULL, /* number of read bytes */
4055 &availableBytes, /* available bytes total */
4056 NULL); /* byteLeft */
4057
4058 repeatCount = 0;
4059 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004060 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004061 {
4062 repeatCount++;
4063 toRead =
4064# ifdef FEAT_MBYTE
4065 (DWORD)(BUFLEN - *buffer_off);
4066# else
4067 (DWORD)BUFLEN;
4068# endif
4069 toRead = availableBytes < toRead ? availableBytes : toRead;
4070 ReadFile(g_hChildStd_OUT_Rd, buffer
4071# ifdef FEAT_MBYTE
4072 + *buffer_off, toRead
4073# else
4074 , toRead
4075# endif
4076 , &len, NULL);
4077
4078 /* If we haven't read anything, there is a problem */
4079 if (len == 0)
4080 break;
4081
4082 availableBytes -= len;
4083
4084 if (options & SHELL_READ)
4085 {
4086 /* Do NUL -> NL translation, append NL separated
4087 * lines to the current buffer. */
4088 for (i = 0; i < len; ++i)
4089 {
4090 if (buffer[i] == NL)
4091 append_ga_line(ga);
4092 else if (buffer[i] == NUL)
4093 ga_append(ga, NL);
4094 else
4095 ga_append(ga, buffer[i]);
4096 }
4097 }
4098# ifdef FEAT_MBYTE
4099 else if (has_mbyte)
4100 {
4101 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004102 int c;
4103 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004104
4105 len += *buffer_off;
4106 buffer[len] = NUL;
4107
4108 /* Check if the last character in buffer[] is
4109 * incomplete, keep these bytes for the next
4110 * round. */
4111 for (p = buffer; p < buffer + len; p += l)
4112 {
4113 l = mb_cptr2len(p);
4114 if (l == 0)
4115 l = 1; /* NUL byte? */
4116 else if (MB_BYTE2LEN(*p) != l)
4117 break;
4118 }
4119 if (p == buffer) /* no complete character */
4120 {
4121 /* avoid getting stuck at an illegal byte */
4122 if (len >= 12)
4123 ++p;
4124 else
4125 {
4126 *buffer_off = len;
4127 return;
4128 }
4129 }
4130 c = *p;
4131 *p = NUL;
4132 msg_puts(buffer);
4133 if (p < buffer + len)
4134 {
4135 *p = c;
4136 *buffer_off = (DWORD)((buffer + len) - p);
4137 mch_memmove(buffer, p, *buffer_off);
4138 return;
4139 }
4140 *buffer_off = 0;
4141 }
4142# endif /* FEAT_MBYTE */
4143 else
4144 {
4145 buffer[len] = NUL;
4146 msg_puts(buffer);
4147 }
4148
4149 windgoto(msg_row, msg_col);
4150 cursor_on();
4151 out_flush();
4152 }
4153}
4154
4155/*
4156 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4157 * for communication and doesn't open any new window.
4158 */
4159 static int
4160mch_system_piped(char *cmd, int options)
4161{
4162 STARTUPINFO si;
4163 PROCESS_INFORMATION pi;
4164 DWORD ret = 0;
4165
4166 HANDLE g_hChildStd_IN_Rd = NULL;
4167 HANDLE g_hChildStd_IN_Wr = NULL;
4168 HANDLE g_hChildStd_OUT_Rd = NULL;
4169 HANDLE g_hChildStd_OUT_Wr = NULL;
4170
4171 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4172 DWORD len;
4173
4174 /* buffer used to receive keys */
4175 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4176 int ta_len = 0; /* valid bytes in ta_buf[] */
4177
4178 DWORD i;
4179 int c;
4180 int noread_cnt = 0;
4181 garray_T ga;
4182 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004183 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004184 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004185
4186 SECURITY_ATTRIBUTES saAttr;
4187
4188 /* Set the bInheritHandle flag so pipe handles are inherited. */
4189 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4190 saAttr.bInheritHandle = TRUE;
4191 saAttr.lpSecurityDescriptor = NULL;
4192
4193 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4194 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4195 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4196 /* Create a pipe for the child process's STDIN. */
4197 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4198 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4199 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4200 {
4201 CloseHandle(g_hChildStd_IN_Rd);
4202 CloseHandle(g_hChildStd_IN_Wr);
4203 CloseHandle(g_hChildStd_OUT_Rd);
4204 CloseHandle(g_hChildStd_OUT_Wr);
4205 MSG_PUTS(_("\nCannot create pipes\n"));
4206 }
4207
4208 si.cb = sizeof(si);
4209 si.lpReserved = NULL;
4210 si.lpDesktop = NULL;
4211 si.lpTitle = NULL;
4212 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4213
4214 /* set-up our file redirection */
4215 si.hStdError = g_hChildStd_OUT_Wr;
4216 si.hStdOutput = g_hChildStd_OUT_Wr;
4217 si.hStdInput = g_hChildStd_IN_Rd;
4218 si.wShowWindow = SW_HIDE;
4219 si.cbReserved2 = 0;
4220 si.lpReserved2 = NULL;
4221
4222 if (options & SHELL_READ)
4223 ga_init2(&ga, 1, BUFLEN);
4224
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004225 if (cmd != NULL)
4226 {
4227 p = (char *)vim_strsave((char_u *)cmd);
4228 if (p != NULL)
4229 unescape_shellxquote((char_u *)p, p_sxe);
4230 else
4231 p = cmd;
4232 }
4233
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004234 /* Now, run the command.
4235 * About "Inherit handles" being TRUE: this command can be litigious,
4236 * handle inheritance was deactivated for pending temp file, but, if we
4237 * deactivate it, the pipes don't work for some reason. */
4238 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004239
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004240 if (p != cmd)
4241 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004242
4243 /* Close our unused side of the pipes */
4244 CloseHandle(g_hChildStd_IN_Rd);
4245 CloseHandle(g_hChildStd_OUT_Wr);
4246
4247 if (options & SHELL_WRITE)
4248 {
4249 HANDLE thread =
4250 CreateThread(NULL, /* security attributes */
4251 0, /* default stack size */
4252 sub_process_writer, /* function to be executed */
4253 g_hChildStd_IN_Wr, /* parameter */
4254 0, /* creation flag, start immediately */
4255 NULL); /* we don't care about thread id */
4256 CloseHandle(thread);
4257 g_hChildStd_IN_Wr = NULL;
4258 }
4259
4260 /* Keep updating the window while waiting for the shell to finish. */
4261 for (;;)
4262 {
4263 MSG msg;
4264
4265 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4266 {
4267 TranslateMessage(&msg);
4268 DispatchMessage(&msg);
4269 }
4270
4271 /* write pipe information in the window */
4272 if ((options & (SHELL_READ|SHELL_WRITE))
4273# ifdef FEAT_GUI
4274 || gui.in_use
4275# endif
4276 )
4277 {
4278 len = 0;
4279 if (!(options & SHELL_EXPAND)
4280 && ((options &
4281 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4282 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4283# ifdef FEAT_GUI
4284 || gui.in_use
4285# endif
4286 )
4287 && (ta_len > 0 || noread_cnt > 4))
4288 {
4289 if (ta_len == 0)
4290 {
4291 /* Get extra characters when we don't have any. Reset the
4292 * counter and timer. */
4293 noread_cnt = 0;
4294# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4295 gettimeofday(&start_tv, NULL);
4296# endif
4297 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4298 }
4299 if (ta_len > 0 || len > 0)
4300 {
4301 /*
4302 * For pipes: Check for CTRL-C: send interrupt signal to
4303 * child. Check for CTRL-D: EOF, close pipe to child.
4304 */
4305 if (len == 1 && cmd != NULL)
4306 {
4307 if (ta_buf[ta_len] == Ctrl_C)
4308 {
4309 /* Learn what exit code is expected, for
4310 * now put 9 as SIGKILL */
4311 TerminateProcess(pi.hProcess, 9);
4312 }
4313 if (ta_buf[ta_len] == Ctrl_D)
4314 {
4315 CloseHandle(g_hChildStd_IN_Wr);
4316 g_hChildStd_IN_Wr = NULL;
4317 }
4318 }
4319
4320 /* replace K_BS by <BS> and K_DEL by <DEL> */
4321 for (i = ta_len; i < ta_len + len; ++i)
4322 {
4323 if (ta_buf[i] == CSI && len - i > 2)
4324 {
4325 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4326 if (c == K_DEL || c == K_KDEL || c == K_BS)
4327 {
4328 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4329 (size_t)(len - i - 2));
4330 if (c == K_DEL || c == K_KDEL)
4331 ta_buf[i] = DEL;
4332 else
4333 ta_buf[i] = Ctrl_H;
4334 len -= 2;
4335 }
4336 }
4337 else if (ta_buf[i] == '\r')
4338 ta_buf[i] = '\n';
4339# ifdef FEAT_MBYTE
4340 if (has_mbyte)
4341 i += (*mb_ptr2len_len)(ta_buf + i,
4342 ta_len + len - i) - 1;
4343# endif
4344 }
4345
4346 /*
4347 * For pipes: echo the typed characters. For a pty this
4348 * does not seem to work.
4349 */
4350 for (i = ta_len; i < ta_len + len; ++i)
4351 {
4352 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4353 msg_putchar(ta_buf[i]);
4354# ifdef FEAT_MBYTE
4355 else if (has_mbyte)
4356 {
4357 int l = (*mb_ptr2len)(ta_buf + i);
4358
4359 msg_outtrans_len(ta_buf + i, l);
4360 i += l - 1;
4361 }
4362# endif
4363 else
4364 msg_outtrans_len(ta_buf + i, 1);
4365 }
4366 windgoto(msg_row, msg_col);
4367 out_flush();
4368
4369 ta_len += len;
4370
4371 /*
4372 * Write the characters to the child, unless EOF has been
4373 * typed for pipes. Write one character at a time, to
4374 * avoid losing too much typeahead. When writing buffer
4375 * lines, drop the typed characters (only check for
4376 * CTRL-C).
4377 */
4378 if (options & SHELL_WRITE)
4379 ta_len = 0;
4380 else if (g_hChildStd_IN_Wr != NULL)
4381 {
4382 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4383 1, &len, NULL);
4384 // if we are typing in, we want to keep things reactive
4385 delay = 1;
4386 if (len > 0)
4387 {
4388 ta_len -= len;
4389 mch_memmove(ta_buf, ta_buf + len, ta_len);
4390 }
4391 }
4392 }
4393 }
4394 }
4395
4396 if (ta_len)
4397 ui_inchar_undo(ta_buf, ta_len);
4398
4399 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4400 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004401 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004402 break;
4403 }
4404
4405 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004406 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004407
4408 /* We start waiting for a very short time and then increase it, so
4409 * that we respond quickly when the process is quick, and don't
4410 * consume too much overhead when it's slow. */
4411 if (delay < 50)
4412 delay += 10;
4413 }
4414
4415 /* Close the pipe */
4416 CloseHandle(g_hChildStd_OUT_Rd);
4417 if (g_hChildStd_IN_Wr != NULL)
4418 CloseHandle(g_hChildStd_IN_Wr);
4419
4420 WaitForSingleObject(pi.hProcess, INFINITE);
4421
4422 /* Get the command exit code */
4423 GetExitCodeProcess(pi.hProcess, &ret);
4424
4425 if (options & SHELL_READ)
4426 {
4427 if (ga.ga_len > 0)
4428 {
4429 append_ga_line(&ga);
4430 /* remember that the NL was missing */
4431 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4432 }
4433 else
4434 curbuf->b_no_eol_lnum = 0;
4435 ga_clear(&ga);
4436 }
4437
4438 /* Close the handles to the subprocess, so that it goes away */
4439 CloseHandle(pi.hThread);
4440 CloseHandle(pi.hProcess);
4441
4442 return ret;
4443}
4444
4445 static int
4446mch_system(char *cmd, int options)
4447{
4448 /* if we can pipe and the shelltemp option is off */
4449 if (allowPiping && !p_stmp)
4450 return mch_system_piped(cmd, options);
4451 else
4452 return mch_system_classic(cmd, options);
4453}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004454#else
4455
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004456# ifdef FEAT_MBYTE
4457 static int
4458mch_system(char *cmd, int options)
4459{
4460 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4461 {
4462 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4463 if (wcmd != NULL)
4464 {
4465 int ret = _wsystem(wcmd);
4466 vim_free(wcmd);
4467 return ret;
4468 }
4469 }
4470 return system(cmd);
4471}
4472# else
4473# define mch_system(c, o) system(c)
4474# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475
4476#endif
4477
4478/*
4479 * Either execute a command by calling the shell or start a new shell
4480 */
4481 int
4482mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004483 char_u *cmd,
4484 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004485{
4486 int x = 0;
4487 int tmode = cur_tmode;
4488#ifdef FEAT_TITLE
4489 char szShellTitle[512];
4490
4491 /* Change the title to reflect that we are in a subshell. */
4492 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
4493 {
4494 if (cmd == NULL)
4495 strcat(szShellTitle, " :sh");
4496 else
4497 {
4498 strcat(szShellTitle, " - !");
4499 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4500 strcat(szShellTitle, cmd);
4501 }
4502 mch_settitle(szShellTitle, NULL);
4503 }
4504#endif
4505
4506 out_flush();
4507
4508#ifdef MCH_WRITE_DUMP
4509 if (fdDump)
4510 {
4511 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4512 fflush(fdDump);
4513 }
4514#endif
4515
4516 /*
4517 * Catch all deadly signals while running the external command, because a
4518 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4519 */
4520 signal(SIGINT, SIG_IGN);
4521#if defined(__GNUC__) && !defined(__MINGW32__)
4522 signal(SIGKILL, SIG_IGN);
4523#else
4524 signal(SIGBREAK, SIG_IGN);
4525#endif
4526 signal(SIGILL, SIG_IGN);
4527 signal(SIGFPE, SIG_IGN);
4528 signal(SIGSEGV, SIG_IGN);
4529 signal(SIGTERM, SIG_IGN);
4530 signal(SIGABRT, SIG_IGN);
4531
4532 if (options & SHELL_COOKED)
4533 settmode(TMODE_COOK); /* set to normal mode */
4534
4535 if (cmd == NULL)
4536 {
4537 x = mch_system(p_sh, options);
4538 }
4539 else
4540 {
4541 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004542 char_u *newcmd = NULL;
4543 char_u *cmdbase = cmd;
4544 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004545
4546 /* Skip a leading ", ( and "(. */
4547 if (*cmdbase == '"' )
4548 ++cmdbase;
4549 if (*cmdbase == '(')
4550 ++cmdbase;
4551
4552 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4553 {
4554 STARTUPINFO si;
4555 PROCESS_INFORMATION pi;
4556 DWORD flags = CREATE_NEW_CONSOLE;
4557 char_u *p;
4558
4559 si.cb = sizeof(si);
4560 si.lpReserved = NULL;
4561 si.lpDesktop = NULL;
4562 si.lpTitle = NULL;
4563 si.dwFlags = 0;
4564 si.cbReserved2 = 0;
4565 si.lpReserved2 = NULL;
4566
4567 cmdbase = skipwhite(cmdbase + 5);
4568 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4569 && vim_iswhite(cmdbase[4]))
4570 {
4571 cmdbase = skipwhite(cmdbase + 4);
4572 si.dwFlags = STARTF_USESHOWWINDOW;
4573 si.wShowWindow = SW_SHOWMINNOACTIVE;
4574 }
4575 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4576 && vim_iswhite(cmdbase[2]))
4577 {
4578 cmdbase = skipwhite(cmdbase + 2);
4579 flags = CREATE_NO_WINDOW;
4580 si.dwFlags = STARTF_USESTDHANDLES;
4581 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004582 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004583 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004584 NULL, // Security att.
4585 OPEN_EXISTING, // Open flags
4586 FILE_ATTRIBUTE_NORMAL, // File att.
4587 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004588 si.hStdOutput = si.hStdInput;
4589 si.hStdError = si.hStdInput;
4590 }
4591
4592 /* Remove a trailing ", ) and )" if they have a match
4593 * at the start of the command. */
4594 if (cmdbase > cmd)
4595 {
4596 p = cmdbase + STRLEN(cmdbase);
4597 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4598 *--p = NUL;
4599 if (p > cmdbase && p[-1] == ')'
4600 && (*cmd =='(' || cmd[1] == '('))
4601 *--p = NUL;
4602 }
4603
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004604 newcmd = cmdbase;
4605 unescape_shellxquote(cmdbase, p_sxe);
4606
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004607 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004608 * If creating new console, arguments are passed to the
4609 * 'cmd.exe' as-is. If it's not, arguments are not treated
4610 * correctly for current 'cmd.exe'. So unescape characters in
4611 * shellxescape except '|' for avoiding to be treated as
4612 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004613 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004614 if (flags != CREATE_NEW_CONSOLE)
4615 {
4616 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004617 char_u *cmd_shell = mch_getenv("COMSPEC");
4618
4619 if (cmd_shell == NULL || *cmd_shell == NUL)
4620 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004621
4622 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4623 if (subcmd != NULL)
4624 {
4625 /* make "cmd.exe /c arguments" */
4626 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004627 newcmd = lalloc(cmdlen, TRUE);
4628 if (newcmd != NULL)
4629 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004630 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004631 else
4632 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004633 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004634 }
4635 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004636
4637 /*
4638 * Now, start the command as a process, so that it doesn't
4639 * inherit our handles which causes unpleasant dangling swap
4640 * files if we exit before the spawned process
4641 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004642 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004643 x = 0;
4644 else
4645 {
4646 x = -1;
4647#ifdef FEAT_GUI_W32
4648 EMSG(_("E371: Command not found"));
4649#endif
4650 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004651
4652 if (newcmd != cmdbase)
4653 vim_free(newcmd);
4654
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004655 if (si.hStdInput != NULL)
4656 {
4657 /* Close the handle to \\.\NUL */
4658 CloseHandle(si.hStdInput);
4659 }
4660 /* Close the handles to the subprocess, so that it goes away */
4661 CloseHandle(pi.hThread);
4662 CloseHandle(pi.hProcess);
4663 }
4664 else
4665 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004666 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004667#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004668 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004669#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004670 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4671
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004672 newcmd = lalloc(cmdlen, TRUE);
4673 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004674 {
4675#if defined(FEAT_GUI_W32)
4676 if (need_vimrun_warning)
4677 {
4678 MessageBox(NULL,
4679 _("VIMRUN.EXE not found in your $PATH.\n"
4680 "External commands will not pause after completion.\n"
4681 "See :help win32-vimrun for more information."),
4682 _("Vim Warning"),
4683 MB_ICONWARNING);
4684 need_vimrun_warning = FALSE;
4685 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004686 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004687 /* Use vimrun to execute the command. It opens a console
4688 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004689 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004690 vimrun_path,
4691 (msg_silent != 0 || (options & SHELL_DOOUT))
4692 ? "-s " : "",
4693 p_sh, p_shcf, cmd);
4694 else
4695#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004696 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004697 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004698 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004699 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004700 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004701 }
4702 }
4703
4704 if (tmode == TMODE_RAW)
4705 settmode(TMODE_RAW); /* set to raw mode */
4706
4707 /* Print the return value, unless "vimrun" was used. */
4708 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4709#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004710 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4711 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004712#endif
4713 )
4714 {
4715 smsg(_("shell returned %d"), x);
4716 msg_putchar('\n');
4717 }
4718#ifdef FEAT_TITLE
4719 resettitle();
4720#endif
4721
4722 signal(SIGINT, SIG_DFL);
4723#if defined(__GNUC__) && !defined(__MINGW32__)
4724 signal(SIGKILL, SIG_DFL);
4725#else
4726 signal(SIGBREAK, SIG_DFL);
4727#endif
4728 signal(SIGILL, SIG_DFL);
4729 signal(SIGFPE, SIG_DFL);
4730 signal(SIGSEGV, SIG_DFL);
4731 signal(SIGTERM, SIG_DFL);
4732 signal(SIGABRT, SIG_DFL);
4733
4734 return x;
4735}
4736
4737
4738#ifndef FEAT_GUI_W32
4739
4740/*
4741 * Start termcap mode
4742 */
4743 static void
4744termcap_mode_start(void)
4745{
4746 DWORD cmodein;
4747
4748 if (g_fTermcapMode)
4749 return;
4750
4751 SaveConsoleBuffer(&g_cbNonTermcap);
4752
4753 if (g_cbTermcap.IsValid)
4754 {
4755 /*
4756 * We've been in termcap mode before. Restore certain screen
4757 * characteristics, including the buffer size and the window
4758 * size. Since we will be redrawing the screen, we don't need
4759 * to restore the actual contents of the buffer.
4760 */
4761 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4762 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4763 Rows = g_cbTermcap.Info.dwSize.Y;
4764 Columns = g_cbTermcap.Info.dwSize.X;
4765 }
4766 else
4767 {
4768 /*
4769 * This is our first time entering termcap mode. Clear the console
4770 * screen buffer, and resize the buffer to match the current window
4771 * size. We will use this as the size of our editing environment.
4772 */
4773 ClearConsoleBuffer(g_attrCurrent);
4774 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4775 }
4776
4777#ifdef FEAT_TITLE
4778 resettitle();
4779#endif
4780
4781 GetConsoleMode(g_hConIn, &cmodein);
4782#ifdef FEAT_MOUSE
4783 if (g_fMouseActive)
4784 cmodein |= ENABLE_MOUSE_INPUT;
4785 else
4786 cmodein &= ~ENABLE_MOUSE_INPUT;
4787#endif
4788 cmodein |= ENABLE_WINDOW_INPUT;
4789 SetConsoleMode(g_hConIn, cmodein);
4790
4791 redraw_later_clear();
4792 g_fTermcapMode = TRUE;
4793}
4794
4795
4796/*
4797 * End termcap mode
4798 */
4799 static void
4800termcap_mode_end(void)
4801{
4802 DWORD cmodein;
4803 ConsoleBuffer *cb;
4804 COORD coord;
4805 DWORD dwDummy;
4806
4807 if (!g_fTermcapMode)
4808 return;
4809
4810 SaveConsoleBuffer(&g_cbTermcap);
4811
4812 GetConsoleMode(g_hConIn, &cmodein);
4813 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4814 SetConsoleMode(g_hConIn, cmodein);
4815
4816#ifdef FEAT_RESTORE_ORIG_SCREEN
4817 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4818#else
4819 cb = &g_cbNonTermcap;
4820#endif
4821 RestoreConsoleBuffer(cb, p_rs);
4822 SetConsoleCursorInfo(g_hConOut, &g_cci);
4823
4824 if (p_rs || exiting)
4825 {
4826 /*
4827 * Clear anything that happens to be on the current line.
4828 */
4829 coord.X = 0;
4830 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4831 FillConsoleOutputCharacter(g_hConOut, ' ',
4832 cb->Info.dwSize.X, coord, &dwDummy);
4833 /*
4834 * The following is just for aesthetics. If we are exiting without
4835 * restoring the screen, then we want to have a prompt string
4836 * appear at the bottom line. However, the command interpreter
4837 * seems to always advance the cursor one line before displaying
4838 * the prompt string, which causes the screen to scroll. To
4839 * counter this, move the cursor up one line before exiting.
4840 */
4841 if (exiting && !p_rs)
4842 coord.Y--;
4843 /*
4844 * Position the cursor at the leftmost column of the desired row.
4845 */
4846 SetConsoleCursorPosition(g_hConOut, coord);
4847 }
4848
4849 g_fTermcapMode = FALSE;
4850}
4851#endif /* FEAT_GUI_W32 */
4852
4853
4854#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004855/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004856 void
4857mch_write(
4858 char_u *s,
4859 int len)
4860{
4861 /* never used */
4862}
4863
4864#else
4865
4866/*
4867 * clear `n' chars, starting from `coord'
4868 */
4869 static void
4870clear_chars(
4871 COORD coord,
4872 DWORD n)
4873{
4874 DWORD dwDummy;
4875
4876 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4877 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4878}
4879
4880
4881/*
4882 * Clear the screen
4883 */
4884 static void
4885clear_screen(void)
4886{
4887 g_coord.X = g_coord.Y = 0;
4888 clear_chars(g_coord, Rows * Columns);
4889}
4890
4891
4892/*
4893 * Clear to end of display
4894 */
4895 static void
4896clear_to_end_of_display(void)
4897{
4898 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4899 * Columns + (Columns - g_coord.X));
4900}
4901
4902
4903/*
4904 * Clear to end of line
4905 */
4906 static void
4907clear_to_end_of_line(void)
4908{
4909 clear_chars(g_coord, Columns - g_coord.X);
4910}
4911
4912
4913/*
4914 * Scroll the scroll region up by `cLines' lines
4915 */
4916 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004917scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918{
4919 COORD oldcoord = g_coord;
4920
4921 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4922 delete_lines(cLines);
4923
4924 g_coord = oldcoord;
4925}
4926
4927
4928/*
4929 * Set the scroll region
4930 */
4931 static void
4932set_scroll_region(
4933 unsigned left,
4934 unsigned top,
4935 unsigned right,
4936 unsigned bottom)
4937{
4938 if (left >= right
4939 || top >= bottom
4940 || right > (unsigned) Columns - 1
4941 || bottom > (unsigned) Rows - 1)
4942 return;
4943
4944 g_srScrollRegion.Left = left;
4945 g_srScrollRegion.Top = top;
4946 g_srScrollRegion.Right = right;
4947 g_srScrollRegion.Bottom = bottom;
4948}
4949
4950
4951/*
4952 * Insert `cLines' lines at the current cursor position
4953 */
4954 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004955insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004956{
4957 SMALL_RECT source;
4958 COORD dest;
4959 CHAR_INFO fill;
4960
4961 dest.X = 0;
4962 dest.Y = g_coord.Y + cLines;
4963
4964 source.Left = 0;
4965 source.Top = g_coord.Y;
4966 source.Right = g_srScrollRegion.Right;
4967 source.Bottom = g_srScrollRegion.Bottom - cLines;
4968
4969 fill.Char.AsciiChar = ' ';
4970 fill.Attributes = g_attrCurrent;
4971
4972 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4973
4974 /* Here we have to deal with a win32 console flake: If the scroll
4975 * region looks like abc and we scroll c to a and fill with d we get
4976 * cbd... if we scroll block c one line at a time to a, we get cdd...
4977 * vim expects cdd consistently... So we have to deal with that
4978 * here... (this also occurs scrolling the same way in the other
4979 * direction). */
4980
4981 if (source.Bottom < dest.Y)
4982 {
4983 COORD coord;
4984
4985 coord.X = 0;
4986 coord.Y = source.Bottom;
4987 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4988 }
4989}
4990
4991
4992/*
4993 * Delete `cLines' lines at the current cursor position
4994 */
4995 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004996delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004997{
4998 SMALL_RECT source;
4999 COORD dest;
5000 CHAR_INFO fill;
5001 int nb;
5002
5003 dest.X = 0;
5004 dest.Y = g_coord.Y;
5005
5006 source.Left = 0;
5007 source.Top = g_coord.Y + cLines;
5008 source.Right = g_srScrollRegion.Right;
5009 source.Bottom = g_srScrollRegion.Bottom;
5010
5011 fill.Char.AsciiChar = ' ';
5012 fill.Attributes = g_attrCurrent;
5013
5014 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5015
5016 /* Here we have to deal with a win32 console flake: If the scroll
5017 * region looks like abc and we scroll c to a and fill with d we get
5018 * cbd... if we scroll block c one line at a time to a, we get cdd...
5019 * vim expects cdd consistently... So we have to deal with that
5020 * here... (this also occurs scrolling the same way in the other
5021 * direction). */
5022
5023 nb = dest.Y + (source.Bottom - source.Top) + 1;
5024
5025 if (nb < source.Top)
5026 {
5027 COORD coord;
5028
5029 coord.X = 0;
5030 coord.Y = nb;
5031 clear_chars(coord, Columns * (source.Top - nb));
5032 }
5033}
5034
5035
5036/*
5037 * Set the cursor position
5038 */
5039 static void
5040gotoxy(
5041 unsigned x,
5042 unsigned y)
5043{
5044 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5045 return;
5046
5047 /* external cursor coords are 1-based; internal are 0-based */
5048 g_coord.X = x - 1;
5049 g_coord.Y = y - 1;
5050 SetConsoleCursorPosition(g_hConOut, g_coord);
5051}
5052
5053
5054/*
5055 * Set the current text attribute = (foreground | background)
5056 * See ../doc/os_win32.txt for the numbers.
5057 */
5058 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005059textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005060{
5061 g_attrCurrent = wAttr;
5062
5063 SetConsoleTextAttribute(g_hConOut, wAttr);
5064}
5065
5066
5067 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005068textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005069{
5070 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
5071
5072 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5073}
5074
5075
5076 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005077textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005078{
5079 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
5080
5081 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5082}
5083
5084
5085/*
5086 * restore the default text attribute (whatever we started with)
5087 */
5088 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005089normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005090{
5091 textattr(g_attrDefault);
5092}
5093
5094
5095static WORD g_attrPreStandout = 0;
5096
5097/*
5098 * Make the text standout, by brightening it
5099 */
5100 static void
5101standout(void)
5102{
5103 g_attrPreStandout = g_attrCurrent;
5104 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5105}
5106
5107
5108/*
5109 * Turn off standout mode
5110 */
5111 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005112standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005113{
5114 if (g_attrPreStandout)
5115 {
5116 textattr(g_attrPreStandout);
5117 g_attrPreStandout = 0;
5118 }
5119}
5120
5121
5122/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005123 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005124 */
5125 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005126mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005127{
5128 char_u *p;
5129 int n;
5130
5131 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5132 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5133 if (T_ME[0] == ESC && T_ME[1] == '|')
5134 {
5135 p = T_ME + 2;
5136 n = getdigits(&p);
5137 if (*p == 'm' && n > 0)
5138 {
5139 cterm_normal_fg_color = (n & 0xf) + 1;
5140 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5141 }
5142 }
5143}
5144
5145
5146/*
5147 * visual bell: flash the screen
5148 */
5149 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005150visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005151{
5152 COORD coordOrigin = {0, 0};
5153 WORD attrFlash = ~g_attrCurrent & 0xff;
5154
5155 DWORD dwDummy;
5156 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5157
5158 if (oldattrs == NULL)
5159 return;
5160 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5161 coordOrigin, &dwDummy);
5162 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5163 coordOrigin, &dwDummy);
5164
5165 Sleep(15); /* wait for 15 msec */
5166 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5167 coordOrigin, &dwDummy);
5168 vim_free(oldattrs);
5169}
5170
5171
5172/*
5173 * Make the cursor visible or invisible
5174 */
5175 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005176cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005177{
5178 s_cursor_visible = fVisible;
5179#ifdef MCH_CURSOR_SHAPE
5180 mch_update_cursor();
5181#endif
5182}
5183
5184
5185/*
5186 * write `cchToWrite' characters in `pchBuf' to the screen
5187 * Returns the number of characters actually written (at least one).
5188 */
5189 static BOOL
5190write_chars(
5191 LPCSTR pchBuf,
5192 DWORD cchToWrite)
5193{
5194 COORD coord = g_coord;
5195 DWORD written;
5196
5197 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
5198 coord, &written);
5199 /* When writing fails or didn't write a single character, pretend one
5200 * character was written, otherwise we get stuck. */
5201 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
5202 coord, &written) == 0
5203 || written == 0)
5204 written = 1;
5205
5206 g_coord.X += (SHORT) written;
5207
5208 while (g_coord.X > g_srScrollRegion.Right)
5209 {
5210 g_coord.X -= (SHORT) Columns;
5211 if (g_coord.Y < g_srScrollRegion.Bottom)
5212 g_coord.Y++;
5213 }
5214
5215 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5216
5217 return written;
5218}
5219
5220
5221/*
5222 * mch_write(): write the output buffer to the screen, translating ESC
5223 * sequences into calls to console output routines.
5224 */
5225 void
5226mch_write(
5227 char_u *s,
5228 int len)
5229{
5230 s[len] = NUL;
5231
5232 if (!term_console)
5233 {
5234 write(1, s, (unsigned)len);
5235 return;
5236 }
5237
5238 /* translate ESC | sequences into faked bios calls */
5239 while (len--)
5240 {
5241 /* optimization: use one single write_chars for runs of text,
5242 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005243 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005244
5245 if (p_wd)
5246 {
5247 WaitForChar(p_wd);
5248 if (prefix != 0)
5249 prefix = 1;
5250 }
5251
5252 if (prefix != 0)
5253 {
5254 DWORD nWritten;
5255
5256 nWritten = write_chars(s, prefix);
5257#ifdef MCH_WRITE_DUMP
5258 if (fdDump)
5259 {
5260 fputc('>', fdDump);
5261 fwrite(s, sizeof(char_u), nWritten, fdDump);
5262 fputs("<\n", fdDump);
5263 }
5264#endif
5265 len -= (nWritten - 1);
5266 s += nWritten;
5267 }
5268 else if (s[0] == '\n')
5269 {
5270 /* \n, newline: go to the beginning of the next line or scroll */
5271 if (g_coord.Y == g_srScrollRegion.Bottom)
5272 {
5273 scroll(1);
5274 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5275 }
5276 else
5277 {
5278 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5279 }
5280#ifdef MCH_WRITE_DUMP
5281 if (fdDump)
5282 fputs("\\n\n", fdDump);
5283#endif
5284 s++;
5285 }
5286 else if (s[0] == '\r')
5287 {
5288 /* \r, carriage return: go to beginning of line */
5289 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5290#ifdef MCH_WRITE_DUMP
5291 if (fdDump)
5292 fputs("\\r\n", fdDump);
5293#endif
5294 s++;
5295 }
5296 else if (s[0] == '\b')
5297 {
5298 /* \b, backspace: move cursor one position left */
5299 if (g_coord.X > g_srScrollRegion.Left)
5300 g_coord.X--;
5301 else if (g_coord.Y > g_srScrollRegion.Top)
5302 {
5303 g_coord.X = g_srScrollRegion.Right;
5304 g_coord.Y--;
5305 }
5306 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5307#ifdef MCH_WRITE_DUMP
5308 if (fdDump)
5309 fputs("\\b\n", fdDump);
5310#endif
5311 s++;
5312 }
5313 else if (s[0] == '\a')
5314 {
5315 /* \a, bell */
5316 MessageBeep(0xFFFFFFFF);
5317#ifdef MCH_WRITE_DUMP
5318 if (fdDump)
5319 fputs("\\a\n", fdDump);
5320#endif
5321 s++;
5322 }
5323 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5324 {
5325#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005326 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005327#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005328 char_u *p;
5329 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005330
5331 switch (s[2])
5332 {
5333 /* one or two numeric arguments, separated by ';' */
5334
5335 case '0': case '1': case '2': case '3': case '4':
5336 case '5': case '6': case '7': case '8': case '9':
5337 p = s + 2;
5338 arg1 = getdigits(&p); /* no check for length! */
5339 if (p > s + len)
5340 break;
5341
5342 if (*p == ';')
5343 {
5344 ++p;
5345 arg2 = getdigits(&p); /* no check for length! */
5346 if (p > s + len)
5347 break;
5348
5349 if (*p == 'H')
5350 gotoxy(arg2, arg1);
5351 else if (*p == 'r')
5352 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5353 }
5354 else if (*p == 'A')
5355 {
5356 /* move cursor up arg1 lines in same column */
5357 gotoxy(g_coord.X + 1,
5358 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5359 }
5360 else if (*p == 'C')
5361 {
5362 /* move cursor right arg1 columns in same line */
5363 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5364 g_coord.Y + 1);
5365 }
5366 else if (*p == 'H')
5367 {
5368 gotoxy(1, arg1);
5369 }
5370 else if (*p == 'L')
5371 {
5372 insert_lines(arg1);
5373 }
5374 else if (*p == 'm')
5375 {
5376 if (arg1 == 0)
5377 normvideo();
5378 else
5379 textattr((WORD) arg1);
5380 }
5381 else if (*p == 'f')
5382 {
5383 textcolor((WORD) arg1);
5384 }
5385 else if (*p == 'b')
5386 {
5387 textbackground((WORD) arg1);
5388 }
5389 else if (*p == 'M')
5390 {
5391 delete_lines(arg1);
5392 }
5393
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005394 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005395 s = p + 1;
5396 break;
5397
5398
5399 /* Three-character escape sequences */
5400
5401 case 'A':
5402 /* move cursor up one line in same column */
5403 gotoxy(g_coord.X + 1,
5404 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5405 goto got3;
5406
5407 case 'B':
5408 visual_bell();
5409 goto got3;
5410
5411 case 'C':
5412 /* move cursor right one column in same line */
5413 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5414 g_coord.Y + 1);
5415 goto got3;
5416
5417 case 'E':
5418 termcap_mode_end();
5419 goto got3;
5420
5421 case 'F':
5422 standout();
5423 goto got3;
5424
5425 case 'f':
5426 standend();
5427 goto got3;
5428
5429 case 'H':
5430 gotoxy(1, 1);
5431 goto got3;
5432
5433 case 'j':
5434 clear_to_end_of_display();
5435 goto got3;
5436
5437 case 'J':
5438 clear_screen();
5439 goto got3;
5440
5441 case 'K':
5442 clear_to_end_of_line();
5443 goto got3;
5444
5445 case 'L':
5446 insert_lines(1);
5447 goto got3;
5448
5449 case 'M':
5450 delete_lines(1);
5451 goto got3;
5452
5453 case 'S':
5454 termcap_mode_start();
5455 goto got3;
5456
5457 case 'V':
5458 cursor_visible(TRUE);
5459 goto got3;
5460
5461 case 'v':
5462 cursor_visible(FALSE);
5463 goto got3;
5464
5465 got3:
5466 s += 3;
5467 len -= 2;
5468 }
5469
5470#ifdef MCH_WRITE_DUMP
5471 if (fdDump)
5472 {
5473 fputs("ESC | ", fdDump);
5474 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5475 fputc('\n', fdDump);
5476 }
5477#endif
5478 }
5479 else
5480 {
5481 /* Write a single character */
5482 DWORD nWritten;
5483
5484 nWritten = write_chars(s, 1);
5485#ifdef MCH_WRITE_DUMP
5486 if (fdDump)
5487 {
5488 fputc('>', fdDump);
5489 fwrite(s, sizeof(char_u), nWritten, fdDump);
5490 fputs("<\n", fdDump);
5491 }
5492#endif
5493
5494 len -= (nWritten - 1);
5495 s += nWritten;
5496 }
5497 }
5498
5499#ifdef MCH_WRITE_DUMP
5500 if (fdDump)
5501 fflush(fdDump);
5502#endif
5503}
5504
5505#endif /* FEAT_GUI_W32 */
5506
5507
5508/*
5509 * Delay for half a second.
5510 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005511/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005512 void
5513mch_delay(
5514 long msec,
5515 int ignoreinput)
5516{
5517#ifdef FEAT_GUI_W32
5518 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005519#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005520 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005521# ifdef FEAT_MZSCHEME
5522 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5523 {
5524 int towait = p_mzq;
5525
5526 /* if msec is large enough, wait by portions in p_mzq */
5527 while (msec > 0)
5528 {
5529 mzvim_check_threads();
5530 if (msec < towait)
5531 towait = msec;
5532 Sleep(towait);
5533 msec -= towait;
5534 }
5535 }
5536 else
5537# endif
5538 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005539 else
5540 WaitForChar(msec);
5541#endif
5542}
5543
5544
5545/*
5546 * this version of remove is not scared by a readonly (backup) file
5547 * Return 0 for success, -1 for failure.
5548 */
5549 int
5550mch_remove(char_u *name)
5551{
5552#ifdef FEAT_MBYTE
5553 WCHAR *wn = NULL;
5554 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005555#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005557 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5558
5559#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5561 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005562 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563 if (wn != NULL)
5564 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005565 n = DeleteFileW(wn) ? 0 : -1;
5566 vim_free(wn);
5567 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5568 return n;
5569 /* Retry with non-wide function (for Windows 98). */
5570 }
5571 }
5572#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573 return DeleteFile(name) ? 0 : -1;
5574}
5575
5576
5577/*
5578 * check for an "interrupt signal": CTRL-break or CTRL-C
5579 */
5580 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005581mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005582{
5583#ifndef FEAT_GUI_W32 /* never used */
5584 if (g_fCtrlCPressed || g_fCBrkPressed)
5585 {
5586 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5587 got_int = TRUE;
5588 }
5589#endif
5590}
5591
5592
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593#ifdef FEAT_MBYTE
5594/*
5595 * Same code as below, but with wide functions and no comments.
5596 * Return 0 for success, non-zero for failure.
5597 */
5598 int
5599mch_wrename(WCHAR *wold, WCHAR *wnew)
5600{
5601 WCHAR *p;
5602 int i;
5603 WCHAR szTempFile[_MAX_PATH + 1];
5604 WCHAR szNewPath[_MAX_PATH + 1];
5605 HANDLE hf;
5606
5607 if (!mch_windows95())
5608 {
5609 p = wold;
5610 for (i = 0; wold[i] != NUL; ++i)
5611 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5612 && wold[i + 1] != 0)
5613 p = wold + i + 1;
5614 if ((int)(wold + i - p) < 8 || p[6] != '~')
5615 return (MoveFileW(wold, wnew) == 0);
5616 }
5617
5618 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5619 return -1;
5620 *p = NUL;
5621
5622 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5623 return -2;
5624
5625 if (!DeleteFileW(szTempFile))
5626 return -3;
5627
5628 if (!MoveFileW(wold, szTempFile))
5629 return -4;
5630
5631 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5632 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5633 return -5;
5634 if (!CloseHandle(hf))
5635 return -6;
5636
5637 if (!MoveFileW(szTempFile, wnew))
5638 {
5639 (void)MoveFileW(szTempFile, wold);
5640 return -7;
5641 }
5642
5643 DeleteFileW(szTempFile);
5644
5645 if (!DeleteFileW(wold))
5646 return -8;
5647
5648 return 0;
5649}
5650#endif
5651
5652
5653/*
5654 * mch_rename() works around a bug in rename (aka MoveFile) in
5655 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5656 * file whose short file name is "FOO.BAR" (its long file name will
5657 * be correct: "foo.bar~"). Because a file can be accessed by
5658 * either its SFN or its LFN, "foo.bar" has effectively been
5659 * renamed to "foo.bar", which is not at all what was wanted. This
5660 * seems to happen only when renaming files with three-character
5661 * extensions by appending a suffix that does not include ".".
5662 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5663 *
5664 * There is another problem, which isn't really a bug but isn't right either:
5665 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5666 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5667 * service pack 6. Doesn't seem to happen on Windows 98.
5668 *
5669 * Like rename(), returns 0 upon success, non-zero upon failure.
5670 * Should probably set errno appropriately when errors occur.
5671 */
5672 int
5673mch_rename(
5674 const char *pszOldFile,
5675 const char *pszNewFile)
5676{
5677 char szTempFile[_MAX_PATH+1];
5678 char szNewPath[_MAX_PATH+1];
5679 char *pszFilePart;
5680 HANDLE hf;
5681#ifdef FEAT_MBYTE
5682 WCHAR *wold = NULL;
5683 WCHAR *wnew = NULL;
5684 int retval = -1;
5685
5686 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5687 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005688 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5689 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005690 if (wold != NULL && wnew != NULL)
5691 retval = mch_wrename(wold, wnew);
5692 vim_free(wold);
5693 vim_free(wnew);
5694 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5695 return retval;
5696 /* Retry with non-wide function (for Windows 98). */
5697 }
5698#endif
5699
5700 /*
5701 * No need to play tricks if not running Windows 95, unless the file name
5702 * contains a "~" as the seventh character.
5703 */
5704 if (!mch_windows95())
5705 {
5706 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5707 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5708 return rename(pszOldFile, pszNewFile);
5709 }
5710
5711 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5712 * a directory, no error is returned and pszFilePart will be NULL. */
5713 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5714 || pszFilePart == NULL)
5715 return -1;
5716 *pszFilePart = NUL;
5717
5718 /* Get (and create) a unique temporary file name in directory of new file */
5719 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5720 return -2;
5721
5722 /* blow the temp file away */
5723 if (!DeleteFile(szTempFile))
5724 return -3;
5725
5726 /* rename old file to the temp file */
5727 if (!MoveFile(pszOldFile, szTempFile))
5728 return -4;
5729
5730 /* now create an empty file called pszOldFile; this prevents the operating
5731 * system using pszOldFile as an alias (SFN) if we're renaming within the
5732 * same directory. For example, we're editing a file called
5733 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5734 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5735 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005736 * cause all sorts of problems later in buf_write(). So, we create an
5737 * empty file called filena~1.txt and the system will have to find some
5738 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005739 */
5740 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5741 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5742 return -5;
5743 if (!CloseHandle(hf))
5744 return -6;
5745
5746 /* rename the temp file to the new file */
5747 if (!MoveFile(szTempFile, pszNewFile))
5748 {
5749 /* Renaming failed. Rename the file back to its old name, so that it
5750 * looks like nothing happened. */
5751 (void)MoveFile(szTempFile, pszOldFile);
5752
5753 return -7;
5754 }
5755
5756 /* Seems to be left around on Novell filesystems */
5757 DeleteFile(szTempFile);
5758
5759 /* finally, remove the empty old file */
5760 if (!DeleteFile(pszOldFile))
5761 return -8;
5762
5763 return 0; /* success */
5764}
5765
5766/*
5767 * Get the default shell for the current hardware platform
5768 */
5769 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005770default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005771{
5772 char* psz = NULL;
5773
5774 PlatformId();
5775
5776 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5777 psz = "cmd.exe";
5778 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5779 psz = "command.com";
5780
5781 return psz;
5782}
5783
5784/*
5785 * mch_access() extends access() to do more detailed check on network drives.
5786 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5787 */
5788 int
5789mch_access(char *n, int p)
5790{
5791 HANDLE hFile;
5792 DWORD am;
5793 int retval = -1; /* default: fail */
5794#ifdef FEAT_MBYTE
5795 WCHAR *wn = NULL;
5796
5797 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005798 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005799#endif
5800
5801 if (mch_isdir(n))
5802 {
5803 char TempName[_MAX_PATH + 16] = "";
5804#ifdef FEAT_MBYTE
5805 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5806#endif
5807
5808 if (p & R_OK)
5809 {
5810 /* Read check is performed by seeing if we can do a find file on
5811 * the directory for any file. */
5812#ifdef FEAT_MBYTE
5813 if (wn != NULL)
5814 {
5815 int i;
5816 WIN32_FIND_DATAW d;
5817
5818 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5819 TempNameW[i] = wn[i];
5820 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5821 TempNameW[i++] = '\\';
5822 TempNameW[i++] = '*';
5823 TempNameW[i++] = 0;
5824
5825 hFile = FindFirstFileW(TempNameW, &d);
5826 if (hFile == INVALID_HANDLE_VALUE)
5827 {
5828 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5829 goto getout;
5830
5831 /* Retry with non-wide function (for Windows 98). */
5832 vim_free(wn);
5833 wn = NULL;
5834 }
5835 else
5836 (void)FindClose(hFile);
5837 }
5838 if (wn == NULL)
5839#endif
5840 {
5841 char *pch;
5842 WIN32_FIND_DATA d;
5843
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005844 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005845 pch = TempName + STRLEN(TempName) - 1;
5846 if (*pch != '\\' && *pch != '/')
5847 *++pch = '\\';
5848 *++pch = '*';
5849 *++pch = NUL;
5850
5851 hFile = FindFirstFile(TempName, &d);
5852 if (hFile == INVALID_HANDLE_VALUE)
5853 goto getout;
5854 (void)FindClose(hFile);
5855 }
5856 }
5857
5858 if (p & W_OK)
5859 {
5860 /* Trying to create a temporary file in the directory should catch
5861 * directories on read-only network shares. However, in
5862 * directories whose ACL allows writes but denies deletes will end
5863 * up keeping the temporary file :-(. */
5864#ifdef FEAT_MBYTE
5865 if (wn != NULL)
5866 {
5867 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5868 {
5869 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5870 goto getout;
5871
5872 /* Retry with non-wide function (for Windows 98). */
5873 vim_free(wn);
5874 wn = NULL;
5875 }
5876 else
5877 DeleteFileW(TempNameW);
5878 }
5879 if (wn == NULL)
5880#endif
5881 {
5882 if (!GetTempFileName(n, "VIM", 0, TempName))
5883 goto getout;
5884 mch_remove((char_u *)TempName);
5885 }
5886 }
5887 }
5888 else
5889 {
5890 /* Trying to open the file for the required access does ACL, read-only
5891 * network share, and file attribute checks. */
5892 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5893 | ((p & R_OK) ? GENERIC_READ : 0);
5894#ifdef FEAT_MBYTE
5895 if (wn != NULL)
5896 {
5897 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5898 if (hFile == INVALID_HANDLE_VALUE
5899 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5900 {
5901 /* Retry with non-wide function (for Windows 98). */
5902 vim_free(wn);
5903 wn = NULL;
5904 }
5905 }
5906 if (wn == NULL)
5907#endif
5908 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5909 if (hFile == INVALID_HANDLE_VALUE)
5910 goto getout;
5911 CloseHandle(hFile);
5912 }
5913
5914 retval = 0; /* success */
5915getout:
5916#ifdef FEAT_MBYTE
5917 vim_free(wn);
5918#endif
5919 return retval;
5920}
5921
5922#if defined(FEAT_MBYTE) || defined(PROTO)
5923/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005924 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005925 */
5926 int
5927mch_open(char *name, int flags, int mode)
5928{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005929 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5930# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931 WCHAR *wn;
5932 int f;
5933
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005934 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005936 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005937 if (wn != NULL)
5938 {
5939 f = _wopen(wn, flags, mode);
5940 vim_free(wn);
5941 if (f >= 0)
5942 return f;
5943 /* Retry with non-wide function (for Windows 98). Can't use
5944 * GetLastError() here and it's unclear what errno gets set to if
5945 * the _wopen() fails for missing wide functions. */
5946 }
5947 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005948# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005949
5950 return open(name, flags, mode);
5951}
5952
5953/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005954 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955 */
5956 FILE *
5957mch_fopen(char *name, char *mode)
5958{
5959 WCHAR *wn, *wm;
5960 FILE *f = NULL;
5961
5962 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5963# ifdef __BORLANDC__
5964 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5965 && g_PlatformId == VER_PLATFORM_WIN32_NT
5966# endif
5967 )
5968 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005969# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005970 /* Work around an annoying assertion in the Microsoft debug CRT
5971 * when mode's text/binary setting doesn't match _get_fmode(). */
5972 char newMode = mode[strlen(mode) - 1];
5973 int oldMode = 0;
5974
5975 _get_fmode(&oldMode);
5976 if (newMode == 't')
5977 _set_fmode(_O_TEXT);
5978 else if (newMode == 'b')
5979 _set_fmode(_O_BINARY);
5980# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005981 wn = enc_to_utf16(name, NULL);
5982 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005983 if (wn != NULL && wm != NULL)
5984 f = _wfopen(wn, wm);
5985 vim_free(wn);
5986 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005987
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005988# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005989 _set_fmode(oldMode);
5990# endif
5991
Bram Moolenaar071d4272004-06-13 20:20:40 +00005992 if (f != NULL)
5993 return f;
5994 /* Retry with non-wide function (for Windows 98). Can't use
5995 * GetLastError() here and it's unclear what errno gets set to if
5996 * the _wfopen() fails for missing wide functions. */
5997 }
5998
5999 return fopen(name, mode);
6000}
6001#endif
6002
6003#ifdef FEAT_MBYTE
6004/*
6005 * SUB STREAM (aka info stream) handling:
6006 *
6007 * NTFS can have sub streams for each file. Normal contents of file is
6008 * stored in the main stream, and extra contents (author information and
6009 * title and so on) can be stored in sub stream. After Windows 2000, user
6010 * can access and store those informations in sub streams via explorer's
6011 * property menuitem in right click menu. Those informations in sub streams
6012 * were lost when copying only the main stream. So we have to copy sub
6013 * streams.
6014 *
6015 * Incomplete explanation:
6016 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6017 * More useful info and an example:
6018 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6019 */
6020
6021/*
6022 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6023 * and write to stream "substream" of file "to".
6024 * Errors are ignored.
6025 */
6026 static void
6027copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6028{
6029 HANDLE hTo;
6030 WCHAR *to_name;
6031
6032 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6033 wcscpy(to_name, to);
6034 wcscat(to_name, substream);
6035
6036 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6037 FILE_ATTRIBUTE_NORMAL, NULL);
6038 if (hTo != INVALID_HANDLE_VALUE)
6039 {
6040 long done;
6041 DWORD todo;
6042 DWORD readcnt, written;
6043 char buf[4096];
6044
6045 /* Copy block of bytes at a time. Abort when something goes wrong. */
6046 for (done = 0; done < len; done += written)
6047 {
6048 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006049 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6050 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006051 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6052 FALSE, FALSE, context)
6053 || readcnt != todo
6054 || !WriteFile(hTo, buf, todo, &written, NULL)
6055 || written != todo)
6056 break;
6057 }
6058 CloseHandle(hTo);
6059 }
6060
6061 free(to_name);
6062}
6063
6064/*
6065 * Copy info streams from file "from" to file "to".
6066 */
6067 static void
6068copy_infostreams(char_u *from, char_u *to)
6069{
6070 WCHAR *fromw;
6071 WCHAR *tow;
6072 HANDLE sh;
6073 WIN32_STREAM_ID sid;
6074 int headersize;
6075 WCHAR streamname[_MAX_PATH];
6076 DWORD readcount;
6077 void *context = NULL;
6078 DWORD lo, hi;
6079 int len;
6080
6081 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006082 fromw = enc_to_utf16(from, NULL);
6083 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084 if (fromw != NULL && tow != NULL)
6085 {
6086 /* Open the file for reading. */
6087 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6088 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6089 if (sh != INVALID_HANDLE_VALUE)
6090 {
6091 /* Use BackupRead() to find the info streams. Repeat until we
6092 * have done them all.*/
6093 for (;;)
6094 {
6095 /* Get the header to find the length of the stream name. If
6096 * the "readcount" is zero we have done all info streams. */
6097 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006098 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006099 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6100 &readcount, FALSE, FALSE, &context)
6101 || readcount == 0)
6102 break;
6103
6104 /* We only deal with streams that have a name. The normal
6105 * file data appears to be without a name, even though docs
6106 * suggest it is called "::$DATA". */
6107 if (sid.dwStreamNameSize > 0)
6108 {
6109 /* Read the stream name. */
6110 if (!BackupRead(sh, (LPBYTE)streamname,
6111 sid.dwStreamNameSize,
6112 &readcount, FALSE, FALSE, &context))
6113 break;
6114
6115 /* Copy an info stream with a name ":anything:$DATA".
6116 * Skip "::$DATA", it has no stream name (examples suggest
6117 * it might be used for the normal file contents).
6118 * Note that BackupRead() counts bytes, but the name is in
6119 * wide characters. */
6120 len = readcount / sizeof(WCHAR);
6121 streamname[len] = 0;
6122 if (len > 7 && wcsicmp(streamname + len - 6,
6123 L":$DATA") == 0)
6124 {
6125 streamname[len - 6] = 0;
6126 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006127 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006128 }
6129 }
6130
6131 /* Advance to the next stream. We might try seeking too far,
6132 * but BackupSeek() doesn't skip over stream borders, thus
6133 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006134 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006135 &lo, &hi, &context);
6136 }
6137
6138 /* Clear the context. */
6139 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6140
6141 CloseHandle(sh);
6142 }
6143 }
6144 vim_free(fromw);
6145 vim_free(tow);
6146}
6147#endif
6148
6149/*
6150 * Copy file attributes from file "from" to file "to".
6151 * For Windows NT and later we copy info streams.
6152 * Always returns zero, errors are ignored.
6153 */
6154 int
6155mch_copy_file_attribute(char_u *from, char_u *to)
6156{
6157#ifdef FEAT_MBYTE
6158 /* File streams only work on Windows NT and later. */
6159 PlatformId();
6160 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6161 copy_infostreams(from, to);
6162#endif
6163 return 0;
6164}
6165
6166#if defined(MYRESETSTKOFLW) || defined(PROTO)
6167/*
6168 * Recreate a destroyed stack guard page in win32.
6169 * Written by Benjamin Peterson.
6170 */
6171
6172/* These magic numbers are from the MS header files */
6173#define MIN_STACK_WIN9X 17
6174#define MIN_STACK_WINNT 2
6175
6176/*
6177 * This function does the same thing as _resetstkoflw(), which is only
6178 * available in DevStudio .net and later.
6179 * Returns 0 for failure, 1 for success.
6180 */
6181 int
6182myresetstkoflw(void)
6183{
6184 BYTE *pStackPtr;
6185 BYTE *pGuardPage;
6186 BYTE *pStackBase;
6187 BYTE *pLowestPossiblePage;
6188 MEMORY_BASIC_INFORMATION mbi;
6189 SYSTEM_INFO si;
6190 DWORD nPageSize;
6191 DWORD dummy;
6192
6193 /* This code will not work on win32s. */
6194 PlatformId();
6195 if (g_PlatformId == VER_PLATFORM_WIN32s)
6196 return 0;
6197
6198 /* We need to know the system page size. */
6199 GetSystemInfo(&si);
6200 nPageSize = si.dwPageSize;
6201
6202 /* ...and the current stack pointer */
6203 pStackPtr = (BYTE*)_alloca(1);
6204
6205 /* ...and the base of the stack. */
6206 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6207 return 0;
6208 pStackBase = (BYTE*)mbi.AllocationBase;
6209
6210 /* ...and the page thats min_stack_req pages away from stack base; this is
6211 * the lowest page we could use. */
6212 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6213 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6214
6215 /* On Win95, we want the next page down from the end of the stack. */
6216 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6217 {
6218 /* Find the page that's only 1 page down from the page that the stack
6219 * ptr is in. */
6220 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6221 / (DWORD)nPageSize) - 1));
6222 if (pGuardPage < pLowestPossiblePage)
6223 return 0;
6224
6225 /* Apply the noaccess attribute to the page -- there's no guard
6226 * attribute in win95-type OSes. */
6227 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6228 return 0;
6229 }
6230 else
6231 {
6232 /* On NT, however, we want the first committed page in the stack Start
6233 * at the stack base and move forward through memory until we find a
6234 * committed block. */
6235 BYTE *pBlock = pStackBase;
6236
Bram Moolenaara466c992005-07-09 21:03:22 +00006237 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006238 {
6239 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6240 return 0;
6241
6242 pBlock += mbi.RegionSize;
6243
6244 if (mbi.State & MEM_COMMIT)
6245 break;
6246 }
6247
6248 /* mbi now describes the first committed block in the stack. */
6249 if (mbi.Protect & PAGE_GUARD)
6250 return 1;
6251
6252 /* decide where the guard page should start */
6253 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6254 pGuardPage = pLowestPossiblePage;
6255 else
6256 pGuardPage = (BYTE*)mbi.BaseAddress;
6257
6258 /* allocate the guard page */
6259 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6260 return 0;
6261
6262 /* apply the guard attribute to the page */
6263 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6264 &dummy))
6265 return 0;
6266 }
6267
6268 return 1;
6269}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006270#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006271
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006272
6273#if defined(FEAT_MBYTE) || defined(PROTO)
6274/*
6275 * The command line arguments in UCS2
6276 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006277static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006278static LPWSTR *ArglistW = NULL;
6279static int global_argc = 0;
6280static char **global_argv;
6281
6282static int used_file_argc = 0; /* last argument in global_argv[] used
6283 for the argument list. */
6284static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6285 command line arguments added to
6286 the argument list */
6287static int used_file_count = 0; /* nr of entries in used_file_indexes */
6288static int used_file_literal = FALSE; /* take file names literally */
6289static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006290static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006291static int used_alist_count = 0;
6292
6293
6294/*
6295 * Get the command line arguments. Unicode version.
6296 * Returns argc. Zero when something fails.
6297 */
6298 int
6299get_cmd_argsW(char ***argvp)
6300{
6301 char **argv = NULL;
6302 int argc = 0;
6303 int i;
6304
6305 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6306 if (ArglistW != NULL)
6307 {
6308 argv = malloc((nArgsW + 1) * sizeof(char *));
6309 if (argv != NULL)
6310 {
6311 argc = nArgsW;
6312 argv[argc] = NULL;
6313 for (i = 0; i < argc; ++i)
6314 {
6315 int len;
6316
6317 /* Convert each Unicode argument to the current codepage. */
6318 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006319 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006320 (LPSTR *)&argv[i], &len, 0, 0);
6321 if (argv[i] == NULL)
6322 {
6323 /* Out of memory, clear everything. */
6324 while (i > 0)
6325 free(argv[--i]);
6326 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006327 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006328 argc = 0;
6329 }
6330 }
6331 }
6332 }
6333
6334 global_argc = argc;
6335 global_argv = argv;
6336 if (argc > 0)
6337 used_file_indexes = malloc(argc * sizeof(int));
6338
6339 if (argvp != NULL)
6340 *argvp = argv;
6341 return argc;
6342}
6343
6344 void
6345free_cmd_argsW(void)
6346{
6347 if (ArglistW != NULL)
6348 {
6349 GlobalFree(ArglistW);
6350 ArglistW = NULL;
6351 }
6352}
6353
6354/*
6355 * Remember "name" is an argument that was added to the argument list.
6356 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6357 * is called.
6358 */
6359 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006360used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006361{
6362 int i;
6363
6364 if (used_file_indexes == NULL)
6365 return;
6366 for (i = used_file_argc + 1; i < global_argc; ++i)
6367 if (STRCMP(global_argv[i], name) == 0)
6368 {
6369 used_file_argc = i;
6370 used_file_indexes[used_file_count++] = i;
6371 break;
6372 }
6373 used_file_literal = literal;
6374 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006375 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006376}
6377
6378/*
6379 * Remember the length of the argument list as it was. If it changes then we
6380 * leave it alone when 'encoding' is set.
6381 */
6382 void
6383set_alist_count(void)
6384{
6385 used_alist_count = GARGCOUNT;
6386}
6387
6388/*
6389 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6390 * has been changed while starting up. Use the UCS-2 command line arguments
6391 * and convert them to 'encoding'.
6392 */
6393 void
6394fix_arg_enc(void)
6395{
6396 int i;
6397 int idx;
6398 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006399 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006400
6401 /* Safety checks:
6402 * - if argument count differs between the wide and non-wide argument
6403 * list, something must be wrong.
6404 * - the file name arguments must have been located.
6405 * - the length of the argument list wasn't changed by the user.
6406 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006407 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006408 || ArglistW == NULL
6409 || used_file_indexes == NULL
6410 || used_file_count == 0
6411 || used_alist_count != GARGCOUNT)
6412 return;
6413
Bram Moolenaar86b68352004-12-27 21:59:20 +00006414 /* Remember the buffer numbers for the arguments. */
6415 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6416 if (fnum_list == NULL)
6417 return; /* out of memory */
6418 for (i = 0; i < GARGCOUNT; ++i)
6419 fnum_list[i] = GARGLIST[i].ae_fnum;
6420
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006421 /* Clear the argument list. Make room for the new arguments. */
6422 alist_clear(&global_alist);
6423 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006424 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006425
6426 for (i = 0; i < used_file_count; ++i)
6427 {
6428 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006429 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006430 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006431 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006432#ifdef FEAT_DIFF
6433 /* When using diff mode may need to concatenate file name to
6434 * directory name. Just like it's done in main(). */
6435 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6436 && !mch_isdir(alist_name(&GARGLIST[0])))
6437 {
6438 char_u *r;
6439
6440 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6441 if (r != NULL)
6442 {
6443 vim_free(str);
6444 str = r;
6445 }
6446 }
6447#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006448 /* Re-use the old buffer by renaming it. When not using literal
6449 * names it's done by alist_expand() below. */
6450 if (used_file_literal)
6451 buf_set_name(fnum_list[i], str);
6452
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006453 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006454 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006455 }
6456
6457 if (!used_file_literal)
6458 {
6459 /* Now expand wildcards in the arguments. */
6460 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6461 * filename characters but are excluded from 'isfname' to make
6462 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6463 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006464 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006465 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6466 }
6467
6468 /* If wildcard expansion failed, we are editing the first file of the
6469 * arglist and there is no file name: Edit the first argument now. */
6470 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6471 {
6472 do_cmdline_cmd((char_u *)":rewind");
6473 if (GARGCOUNT == 1 && used_file_full_path)
6474 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6475 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006476
6477 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006478}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006479#endif