blob: 2d5544b44291214592f4dc62f6068bd40e317c20 [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
2771 if (GetUserName(szUserName, &cch))
2772 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002773 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 return OK;
2775 }
2776 s[0] = NUL;
2777 return FAIL;
2778}
2779
2780
2781/*
2782 * Insert host name in s[len].
2783 */
2784 void
2785mch_get_host_name(
2786 char_u *s,
2787 int len)
2788{
2789 DWORD cch = len;
2790
2791 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002792 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002793}
2794
2795
2796/*
2797 * return process ID
2798 */
2799 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002800mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801{
2802 return (long)GetCurrentProcessId();
2803}
2804
2805
2806/*
2807 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2808 * Return OK for success, FAIL for failure.
2809 */
2810 int
2811mch_dirname(
2812 char_u *buf,
2813 int len)
2814{
2815 /*
2816 * Originally this was:
2817 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2818 * But the Win32s known bug list says that getcwd() doesn't work
2819 * so use the Win32 system call instead. <Negri>
2820 */
2821#ifdef FEAT_MBYTE
2822 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2823 {
2824 WCHAR wbuf[_MAX_PATH + 1];
2825
2826 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2827 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002828 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829
2830 if (p != NULL)
2831 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002832 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833 vim_free(p);
2834 return OK;
2835 }
2836 }
2837 /* Retry with non-wide function (for Windows 98). */
2838 }
2839#endif
2840 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2841}
2842
2843/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01002844 * Get file permissions for "name".
2845 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846 */
2847 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002848mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002850 struct stat st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01002851 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002852
Bram Moolenaarffa22202013-11-21 12:34:11 +01002853 if (name[0] == '\\' && name[1] == '\\')
2854 /* UNC path */
2855 return (long)win32_getattrs(name);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002856 n = mch_stat(name, &st);
Bram Moolenaarffa22202013-11-21 12:34:11 +01002857 return n == 0 ? (long)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858}
2859
2860
2861/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002862 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002863 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002864 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002865 */
2866 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002867mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002868{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002869 long n = -1;
2870
Bram Moolenaar071d4272004-06-13 20:20:40 +00002871#ifdef FEAT_MBYTE
2872 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2873 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002874 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002875
2876 if (p != NULL)
2877 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002878 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002879 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002880 if (n == -1 && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2881 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002882 /* Retry with non-wide function (for Windows 98). */
2883 }
2884 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002885 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002886#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002887 n = _chmod(name, perm);
2888 if (n == -1)
2889 return FAIL;
2890
2891 win32_set_archive(name);
2892
2893 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894}
2895
2896/*
2897 * Set hidden flag for "name".
2898 */
2899 void
2900mch_hide(char_u *name)
2901{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002902 int attrs = win32_getattrs(name);
2903 if (attrs == -1)
2904 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002905
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002906 attrs |= FILE_ATTRIBUTE_HIDDEN;
2907 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908}
2909
2910/*
2911 * return TRUE if "name" is a directory
2912 * return FALSE if "name" is not a directory or upon error
2913 */
2914 int
2915mch_isdir(char_u *name)
2916{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002917 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918
2919 if (f == -1)
2920 return FALSE; /* file does not exist at all */
2921
2922 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2923}
2924
2925/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002926 * Create directory "name".
2927 * Return 0 on success, -1 on error.
2928 */
2929 int
2930mch_mkdir(char_u *name)
2931{
2932#ifdef FEAT_MBYTE
2933 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2934 {
2935 WCHAR *p;
2936 int retval;
2937
2938 p = enc_to_utf16(name, NULL);
2939 if (p == NULL)
2940 return -1;
2941 retval = _wmkdir(p);
2942 vim_free(p);
2943 return retval;
2944 }
2945#endif
2946 return _mkdir(name);
2947}
2948
2949/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002950 * Return TRUE if file "fname" has more than one link.
2951 */
2952 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002953mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002954{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002955 BY_HANDLE_FILE_INFORMATION info;
2956
2957 return win32_fileinfo(fname, &info) == FILEINFO_OK
2958 && info.nNumberOfLinks > 1;
2959}
2960
2961/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002962 * Return TRUE if file "fname" is a symbolic link.
2963 */
2964 int
2965mch_is_symbolic_link(char_u *fname)
2966{
2967 HANDLE hFind;
2968 int res = FALSE;
2969 WIN32_FIND_DATAA findDataA;
2970 DWORD fileFlags = 0, reparseTag = 0;
2971#ifdef FEAT_MBYTE
2972 WCHAR *wn = NULL;
2973 WIN32_FIND_DATAW findDataW;
2974
2975 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2976 wn = enc_to_utf16(fname, NULL);
2977 if (wn != NULL)
2978 {
2979 hFind = FindFirstFileW(wn, &findDataW);
2980 vim_free(wn);
2981 if (hFind == INVALID_HANDLE_VALUE
2982 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2983 {
2984 /* Retry with non-wide function (for Windows 98). */
2985 hFind = FindFirstFile(fname, &findDataA);
2986 if (hFind != INVALID_HANDLE_VALUE)
2987 {
2988 fileFlags = findDataA.dwFileAttributes;
2989 reparseTag = findDataA.dwReserved0;
2990 }
2991 }
2992 else
2993 {
2994 fileFlags = findDataW.dwFileAttributes;
2995 reparseTag = findDataW.dwReserved0;
2996 }
2997 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002998 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002999#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003000 {
3001 hFind = FindFirstFile(fname, &findDataA);
3002 if (hFind != INVALID_HANDLE_VALUE)
3003 {
3004 fileFlags = findDataA.dwFileAttributes;
3005 reparseTag = findDataA.dwReserved0;
3006 }
3007 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003008
3009 if (hFind != INVALID_HANDLE_VALUE)
3010 FindClose(hFind);
3011
3012 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
3013 && reparseTag == IO_REPARSE_TAG_SYMLINK)
3014 res = TRUE;
3015
3016 return res;
3017}
3018
3019/*
3020 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3021 * link.
3022 */
3023 int
3024mch_is_linked(char_u *fname)
3025{
3026 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3027 return TRUE;
3028 return FALSE;
3029}
3030
3031/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003032 * Get the by-handle-file-information for "fname".
3033 * Returns FILEINFO_OK when OK.
3034 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3035 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3036 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3037 */
3038 int
3039win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3040{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003041 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003042 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003043#ifdef FEAT_MBYTE
3044 WCHAR *wn = NULL;
3045
3046 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003047 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003048 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003049 if (wn == NULL)
3050 res = FILEINFO_ENC_FAIL;
3051 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003052 if (wn != NULL)
3053 {
3054 hFile = CreateFileW(wn, /* file name */
3055 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003056 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003057 NULL, /* security descriptor */
3058 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003059 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003060 NULL); /* handle to template file */
3061 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003062 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003063 {
3064 /* Retry with non-wide function (for Windows 98). */
3065 vim_free(wn);
3066 wn = NULL;
3067 }
3068 }
3069 if (wn == NULL)
3070#endif
3071 hFile = CreateFile(fname, /* file name */
3072 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003073 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003074 NULL, /* security descriptor */
3075 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003076 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003077 NULL); /* handle to template file */
3078
3079 if (hFile != INVALID_HANDLE_VALUE)
3080 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003081 if (GetFileInformationByHandle(hFile, info) != 0)
3082 res = FILEINFO_OK;
3083 else
3084 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003085 CloseHandle(hFile);
3086 }
3087
3088#ifdef FEAT_MBYTE
3089 vim_free(wn);
3090#endif
3091 return res;
3092}
3093
3094/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003095 * get file attributes for `name'
3096 * -1 : error
3097 * else FILE_ATTRIBUTE_* defined in winnt.h
3098 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003099 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003100win32_getattrs(char_u *name)
3101{
3102 int attr;
3103#ifdef FEAT_MBYTE
3104 WCHAR *p = NULL;
3105
3106 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3107 p = enc_to_utf16(name, NULL);
3108
3109 if (p != NULL)
3110 {
3111 attr = GetFileAttributesW(p);
3112 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3113 {
3114 /* Retry with non-wide function (for Windows 98). */
3115 vim_free(p);
3116 p = NULL;
3117 }
3118 }
3119 if (p == NULL)
3120#endif
3121 attr = GetFileAttributes((char *)name);
3122#ifdef FEAT_MBYTE
3123 vim_free(p);
3124#endif
3125 return attr;
3126}
3127
3128/*
3129 * set file attributes for `name' to `attrs'
3130 *
3131 * return -1 for failure, 0 otherwise
3132 */
3133 static
3134 int
3135win32_setattrs(char_u *name, int attrs)
3136{
3137 int res;
3138#ifdef FEAT_MBYTE
3139 WCHAR *p = NULL;
3140
3141 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3142 p = enc_to_utf16(name, NULL);
3143
3144 if (p != NULL)
3145 {
3146 res = SetFileAttributesW(p, attrs);
3147 if (res == FALSE
3148 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3149 {
3150 /* Retry with non-wide function (for Windows 98). */
3151 vim_free(p);
3152 p = NULL;
3153 }
3154 }
3155 if (p == NULL)
3156#endif
3157 res = SetFileAttributes((char *)name, attrs);
3158#ifdef FEAT_MBYTE
3159 vim_free(p);
3160#endif
3161 return res ? 0 : -1;
3162}
3163
3164/*
3165 * Set archive flag for "name".
3166 */
3167 static
3168 int
3169win32_set_archive(char_u *name)
3170{
3171 int attrs = win32_getattrs(name);
3172 if (attrs == -1)
3173 return -1;
3174
3175 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3176 return win32_setattrs(name, attrs);
3177}
3178
3179/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003180 * Return TRUE if file or directory "name" is writable (not readonly).
3181 * Strange semantics of Win32: a readonly directory is writable, but you can't
3182 * delete a file. Let's say this means it is writable.
3183 */
3184 int
3185mch_writable(char_u *name)
3186{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003187 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003188
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003189 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3190 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191}
3192
Bram Moolenaar071d4272004-06-13 20:20:40 +00003193/*
3194 * Return 1 if "name" can be executed, 0 if not.
3195 * Return -1 if unknown.
3196 */
3197 int
3198mch_can_exe(char_u *name)
3199{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003200 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003201 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003202 char_u *p;
3203
3204 if (len >= _MAX_PATH) /* safety check */
3205 return FALSE;
3206
3207 /* If there already is an extension try using the name directly. Also do
3208 * this with a Unix-shell like 'shell'. */
3209 if (vim_strchr(gettail(name), '.') != NULL
3210 || strstr((char *)gettail(p_sh), "sh") != NULL)
3211 if (executable_exists((char *)name))
3212 return TRUE;
3213
3214 /*
3215 * Loop over all extensions in $PATHEXT.
3216 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003217 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003218 p = mch_getenv("PATHEXT");
3219 if (p == NULL)
3220 p = (char_u *)".com;.exe;.bat;.cmd";
3221 while (*p)
3222 {
3223 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3224 {
3225 /* A single "." means no extension is added. */
3226 buf[len] = NUL;
3227 ++p;
3228 if (*p)
3229 ++p;
3230 }
3231 else
3232 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
3233 if (executable_exists((char *)buf))
3234 return TRUE;
3235 }
3236 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238
3239/*
3240 * Check what "name" is:
3241 * NODE_NORMAL: file or directory (or doesn't exist)
3242 * NODE_WRITABLE: writable device, socket, fifo, etc.
3243 * NODE_OTHER: non-writable things
3244 */
3245 int
3246mch_nodetype(char_u *name)
3247{
3248 HANDLE hFile;
3249 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003250#ifdef FEAT_MBYTE
3251 WCHAR *wn = NULL;
3252#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003253
Bram Moolenaar043545e2006-10-10 16:44:07 +00003254 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3255 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3256 * here. */
3257 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3258 return NODE_WRITABLE;
3259
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003260#ifdef FEAT_MBYTE
3261 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3262 {
3263 wn = enc_to_utf16(name, NULL);
3264 if (wn != NULL)
3265 {
3266 hFile = CreateFileW(wn, /* file name */
3267 GENERIC_WRITE, /* access mode */
3268 0, /* share mode */
3269 NULL, /* security descriptor */
3270 OPEN_EXISTING, /* creation disposition */
3271 0, /* file attributes */
3272 NULL); /* handle to template file */
3273 if (hFile == INVALID_HANDLE_VALUE
3274 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3275 {
3276 /* Retry with non-wide function (for Windows 98). */
3277 vim_free(wn);
3278 wn = NULL;
3279 }
3280 }
3281 }
3282 if (wn == NULL)
3283#endif
3284 hFile = CreateFile(name, /* file name */
3285 GENERIC_WRITE, /* access mode */
3286 0, /* share mode */
3287 NULL, /* security descriptor */
3288 OPEN_EXISTING, /* creation disposition */
3289 0, /* file attributes */
3290 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003292#ifdef FEAT_MBYTE
3293 vim_free(wn);
3294#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003295 if (hFile == INVALID_HANDLE_VALUE)
3296 return NODE_NORMAL;
3297
3298 type = GetFileType(hFile);
3299 CloseHandle(hFile);
3300 if (type == FILE_TYPE_CHAR)
3301 return NODE_WRITABLE;
3302 if (type == FILE_TYPE_DISK)
3303 return NODE_NORMAL;
3304 return NODE_OTHER;
3305}
3306
3307#ifdef HAVE_ACL
3308struct my_acl
3309{
3310 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3311 PSID pSidOwner;
3312 PSID pSidGroup;
3313 PACL pDacl;
3314 PACL pSacl;
3315};
3316#endif
3317
3318/*
3319 * Return a pointer to the ACL of file "fname" in allocated memory.
3320 * Return NULL if the ACL is not available for whatever reason.
3321 */
3322 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003323mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324{
3325#ifndef HAVE_ACL
3326 return (vim_acl_T)NULL;
3327#else
3328 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003329 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330
3331 /* This only works on Windows NT and 2000. */
3332 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3333 {
3334 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3335 if (p != NULL)
3336 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003337# ifdef FEAT_MBYTE
3338 WCHAR *wn = NULL;
3339
3340 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3341 wn = enc_to_utf16(fname, NULL);
3342 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003343 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003344 /* Try to retrieve the entire security descriptor. */
3345 err = pGetNamedSecurityInfoW(
3346 wn, // Abstract filename
3347 SE_FILE_OBJECT, // File Object
3348 OWNER_SECURITY_INFORMATION |
3349 GROUP_SECURITY_INFORMATION |
3350 DACL_SECURITY_INFORMATION |
3351 SACL_SECURITY_INFORMATION,
3352 &p->pSidOwner, // Ownership information.
3353 &p->pSidGroup, // Group membership.
3354 &p->pDacl, // Discretionary information.
3355 &p->pSacl, // For auditing purposes.
3356 &p->pSecurityDescriptor);
3357 if (err == ERROR_ACCESS_DENIED ||
3358 err == ERROR_PRIVILEGE_NOT_HELD)
3359 {
3360 /* Retrieve only DACL. */
3361 (void)pGetNamedSecurityInfoW(
3362 wn,
3363 SE_FILE_OBJECT,
3364 DACL_SECURITY_INFORMATION,
3365 NULL,
3366 NULL,
3367 &p->pDacl,
3368 NULL,
3369 &p->pSecurityDescriptor);
3370 }
3371 if (p->pSecurityDescriptor == NULL)
3372 {
3373 mch_free_acl((vim_acl_T)p);
3374 p = NULL;
3375 }
3376 vim_free(wn);
3377 }
3378 else
3379# endif
3380 {
3381 /* Try to retrieve the entire security descriptor. */
3382 err = pGetNamedSecurityInfo(
3383 (LPSTR)fname, // Abstract filename
3384 SE_FILE_OBJECT, // File Object
3385 OWNER_SECURITY_INFORMATION |
3386 GROUP_SECURITY_INFORMATION |
3387 DACL_SECURITY_INFORMATION |
3388 SACL_SECURITY_INFORMATION,
3389 &p->pSidOwner, // Ownership information.
3390 &p->pSidGroup, // Group membership.
3391 &p->pDacl, // Discretionary information.
3392 &p->pSacl, // For auditing purposes.
3393 &p->pSecurityDescriptor);
3394 if (err == ERROR_ACCESS_DENIED ||
3395 err == ERROR_PRIVILEGE_NOT_HELD)
3396 {
3397 /* Retrieve only DACL. */
3398 (void)pGetNamedSecurityInfo(
3399 (LPSTR)fname,
3400 SE_FILE_OBJECT,
3401 DACL_SECURITY_INFORMATION,
3402 NULL,
3403 NULL,
3404 &p->pDacl,
3405 NULL,
3406 &p->pSecurityDescriptor);
3407 }
3408 if (p->pSecurityDescriptor == NULL)
3409 {
3410 mch_free_acl((vim_acl_T)p);
3411 p = NULL;
3412 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413 }
3414 }
3415 }
3416
3417 return (vim_acl_T)p;
3418#endif
3419}
3420
Bram Moolenaar27515922013-06-29 15:36:26 +02003421#ifdef HAVE_ACL
3422/*
3423 * Check if "acl" contains inherited ACE.
3424 */
3425 static BOOL
3426is_acl_inherited(PACL acl)
3427{
3428 DWORD i;
3429 ACL_SIZE_INFORMATION acl_info;
3430 PACCESS_ALLOWED_ACE ace;
3431
3432 acl_info.AceCount = 0;
3433 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3434 for (i = 0; i < acl_info.AceCount; i++)
3435 {
3436 GetAce(acl, i, (LPVOID *)&ace);
3437 if (ace->Header.AceFlags & INHERITED_ACE)
3438 return TRUE;
3439 }
3440 return FALSE;
3441}
3442#endif
3443
Bram Moolenaar071d4272004-06-13 20:20:40 +00003444/*
3445 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3446 * Errors are ignored.
3447 * This must only be called with "acl" equal to what mch_get_acl() returned.
3448 */
3449 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003450mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003451{
3452#ifdef HAVE_ACL
3453 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003454 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003455
3456 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003457 {
3458# ifdef FEAT_MBYTE
3459 WCHAR *wn = NULL;
3460# endif
3461
3462 /* Set security flags */
3463 if (p->pSidOwner)
3464 sec_info |= OWNER_SECURITY_INFORMATION;
3465 if (p->pSidGroup)
3466 sec_info |= GROUP_SECURITY_INFORMATION;
3467 if (p->pDacl)
3468 {
3469 sec_info |= DACL_SECURITY_INFORMATION;
3470 /* Do not inherit its parent's DACL.
3471 * If the DACL is inherited, Cygwin permissions would be changed.
3472 */
3473 if (!is_acl_inherited(p->pDacl))
3474 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3475 }
3476 if (p->pSacl)
3477 sec_info |= SACL_SECURITY_INFORMATION;
3478
3479# ifdef FEAT_MBYTE
3480 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3481 wn = enc_to_utf16(fname, NULL);
3482 if (wn != NULL)
3483 {
3484 (void)pSetNamedSecurityInfoW(
3485 wn, // Abstract filename
3486 SE_FILE_OBJECT, // File Object
3487 sec_info,
3488 p->pSidOwner, // Ownership information.
3489 p->pSidGroup, // Group membership.
3490 p->pDacl, // Discretionary information.
3491 p->pSacl // For auditing purposes.
3492 );
3493 vim_free(wn);
3494 }
3495 else
3496# endif
3497 {
3498 (void)pSetNamedSecurityInfo(
3499 (LPSTR)fname, // Abstract filename
3500 SE_FILE_OBJECT, // File Object
3501 sec_info,
3502 p->pSidOwner, // Ownership information.
3503 p->pSidGroup, // Group membership.
3504 p->pDacl, // Discretionary information.
3505 p->pSacl // For auditing purposes.
3506 );
3507 }
3508 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003509#endif
3510}
3511
3512 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003513mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003514{
3515#ifdef HAVE_ACL
3516 struct my_acl *p = (struct my_acl *)acl;
3517
3518 if (p != NULL)
3519 {
3520 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3521 vim_free(p);
3522 }
3523#endif
3524}
3525
3526#ifndef FEAT_GUI_W32
3527
3528/*
3529 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3530 */
3531 static BOOL WINAPI
3532handler_routine(
3533 DWORD dwCtrlType)
3534{
3535 switch (dwCtrlType)
3536 {
3537 case CTRL_C_EVENT:
3538 if (ctrl_c_interrupts)
3539 g_fCtrlCPressed = TRUE;
3540 return TRUE;
3541
3542 case CTRL_BREAK_EVENT:
3543 g_fCBrkPressed = TRUE;
3544 return TRUE;
3545
3546 /* fatal events: shut down gracefully */
3547 case CTRL_CLOSE_EVENT:
3548 case CTRL_LOGOFF_EVENT:
3549 case CTRL_SHUTDOWN_EVENT:
3550 windgoto((int)Rows - 1, 0);
3551 g_fForceExit = TRUE;
3552
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003553 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554 (dwCtrlType == CTRL_CLOSE_EVENT
3555 ? _("close")
3556 : dwCtrlType == CTRL_LOGOFF_EVENT
3557 ? _("logoff")
3558 : _("shutdown")));
3559#ifdef DEBUG
3560 OutputDebugString(IObuff);
3561#endif
3562
3563 preserve_exit(); /* output IObuff, preserve files and exit */
3564
3565 return TRUE; /* not reached */
3566
3567 default:
3568 return FALSE;
3569 }
3570}
3571
3572
3573/*
3574 * set the tty in (raw) ? "raw" : "cooked" mode
3575 */
3576 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003577mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578{
3579 DWORD cmodein;
3580 DWORD cmodeout;
3581 BOOL bEnableHandler;
3582
3583 GetConsoleMode(g_hConIn, &cmodein);
3584 GetConsoleMode(g_hConOut, &cmodeout);
3585 if (tmode == TMODE_RAW)
3586 {
3587 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3588 ENABLE_ECHO_INPUT);
3589#ifdef FEAT_MOUSE
3590 if (g_fMouseActive)
3591 cmodein |= ENABLE_MOUSE_INPUT;
3592#endif
3593 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3594 bEnableHandler = TRUE;
3595 }
3596 else /* cooked */
3597 {
3598 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3599 ENABLE_ECHO_INPUT);
3600 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3601 bEnableHandler = FALSE;
3602 }
3603 SetConsoleMode(g_hConIn, cmodein);
3604 SetConsoleMode(g_hConOut, cmodeout);
3605 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3606
3607#ifdef MCH_WRITE_DUMP
3608 if (fdDump)
3609 {
3610 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3611 tmode == TMODE_RAW ? "raw" :
3612 tmode == TMODE_COOK ? "cooked" : "normal",
3613 cmodein, cmodeout);
3614 fflush(fdDump);
3615 }
3616#endif
3617}
3618
3619
3620/*
3621 * Get the size of the current window in `Rows' and `Columns'
3622 * Return OK when size could be determined, FAIL otherwise.
3623 */
3624 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003625mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003626{
3627 CONSOLE_SCREEN_BUFFER_INFO csbi;
3628
3629 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3630 {
3631 /*
3632 * For some reason, we are trying to get the screen dimensions
3633 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3634 * variables are really intended to mean the size of Vim screen
3635 * while in termcap mode.
3636 */
3637 Rows = g_cbTermcap.Info.dwSize.Y;
3638 Columns = g_cbTermcap.Info.dwSize.X;
3639 }
3640 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3641 {
3642 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3643 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3644 }
3645 else
3646 {
3647 Rows = 25;
3648 Columns = 80;
3649 }
3650 return OK;
3651}
3652
3653/*
3654 * Set a console window to `xSize' * `ySize'
3655 */
3656 static void
3657ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003658 HANDLE hConsole,
3659 int xSize,
3660 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003661{
3662 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3663 SMALL_RECT srWindowRect; /* hold the new console size */
3664 COORD coordScreen;
3665
3666#ifdef MCH_WRITE_DUMP
3667 if (fdDump)
3668 {
3669 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3670 fflush(fdDump);
3671 }
3672#endif
3673
3674 /* get the largest size we can size the console window to */
3675 coordScreen = GetLargestConsoleWindowSize(hConsole);
3676
3677 /* define the new console window size and scroll position */
3678 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3679 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3680 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3681
3682 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3683 {
3684 int sx, sy;
3685
3686 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3687 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3688 if (sy < ySize || sx < xSize)
3689 {
3690 /*
3691 * Increasing number of lines/columns, do buffer first.
3692 * Use the maximal size in x and y direction.
3693 */
3694 if (sy < ySize)
3695 coordScreen.Y = ySize;
3696 else
3697 coordScreen.Y = sy;
3698 if (sx < xSize)
3699 coordScreen.X = xSize;
3700 else
3701 coordScreen.X = sx;
3702 SetConsoleScreenBufferSize(hConsole, coordScreen);
3703 }
3704 }
3705
3706 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3707 {
3708#ifdef MCH_WRITE_DUMP
3709 if (fdDump)
3710 {
3711 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3712 GetLastError());
3713 fflush(fdDump);
3714 }
3715#endif
3716 }
3717
3718 /* define the new console buffer size */
3719 coordScreen.X = xSize;
3720 coordScreen.Y = ySize;
3721
3722 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3723 {
3724#ifdef MCH_WRITE_DUMP
3725 if (fdDump)
3726 {
3727 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3728 GetLastError());
3729 fflush(fdDump);
3730 }
3731#endif
3732 }
3733}
3734
3735
3736/*
3737 * Set the console window to `Rows' * `Columns'
3738 */
3739 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003740mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003741{
3742 COORD coordScreen;
3743
3744 /* Don't change window size while still starting up */
3745 if (suppress_winsize != 0)
3746 {
3747 suppress_winsize = 2;
3748 return;
3749 }
3750
3751 if (term_console)
3752 {
3753 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3754
3755 /* Clamp Rows and Columns to reasonable values */
3756 if (Rows > coordScreen.Y)
3757 Rows = coordScreen.Y;
3758 if (Columns > coordScreen.X)
3759 Columns = coordScreen.X;
3760
3761 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3762 }
3763}
3764
3765/*
3766 * Rows and/or Columns has changed.
3767 */
3768 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003769mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770{
3771 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3772}
3773
3774
3775/*
3776 * Called when started up, to set the winsize that was delayed.
3777 */
3778 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003779mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003780{
3781 if (suppress_winsize == 2)
3782 {
3783 suppress_winsize = 0;
3784 mch_set_shellsize();
3785 shell_resized();
3786 }
3787 suppress_winsize = 0;
3788}
3789#endif /* FEAT_GUI_W32 */
3790
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003791 static BOOL
3792vim_create_process(
3793 const char *cmd,
3794 DWORD flags,
3795 BOOL inherit_handles,
3796 STARTUPINFO *si,
3797 PROCESS_INFORMATION *pi)
3798{
3799# ifdef FEAT_MBYTE
3800 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3801 {
3802 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
3803
3804 if (wcmd != NULL)
3805 {
3806 BOOL ret;
3807 ret = CreateProcessW(
3808 NULL, /* Executable name */
3809 wcmd, /* Command to execute */
3810 NULL, /* Process security attributes */
3811 NULL, /* Thread security attributes */
3812 inherit_handles, /* Inherit handles */
3813 flags, /* Creation flags */
3814 NULL, /* Environment */
3815 NULL, /* Current directory */
3816 si, /* Startup information */
3817 pi); /* Process information */
3818 vim_free(wcmd);
3819 return ret;
3820 }
3821 }
3822#endif
3823 return CreateProcess(
3824 NULL, /* Executable name */
3825 cmd, /* Command to execute */
3826 NULL, /* Process security attributes */
3827 NULL, /* Thread security attributes */
3828 inherit_handles, /* Inherit handles */
3829 flags, /* Creation flags */
3830 NULL, /* Environment */
3831 NULL, /* Current directory */
3832 si, /* Startup information */
3833 pi); /* Process information */
3834}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003835
3836
3837#if defined(FEAT_GUI_W32) || defined(PROTO)
3838
3839/*
3840 * Specialised version of system() for Win32 GUI mode.
3841 * This version proceeds as follows:
3842 * 1. Create a console window for use by the subprocess
3843 * 2. Run the subprocess (it gets the allocated console by default)
3844 * 3. Wait for the subprocess to terminate and get its exit code
3845 * 4. Prompt the user to press a key to close the console window
3846 */
3847 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003848mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849{
3850 STARTUPINFO si;
3851 PROCESS_INFORMATION pi;
3852 DWORD ret = 0;
3853 HWND hwnd = GetFocus();
3854
3855 si.cb = sizeof(si);
3856 si.lpReserved = NULL;
3857 si.lpDesktop = NULL;
3858 si.lpTitle = NULL;
3859 si.dwFlags = STARTF_USESHOWWINDOW;
3860 /*
3861 * It's nicer to run a filter command in a minimized window, but in
3862 * Windows 95 this makes the command MUCH slower. We can't do it under
3863 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003864 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865 */
3866 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003867 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003868 else
3869 si.wShowWindow = SW_SHOWNORMAL;
3870 si.cbReserved2 = 0;
3871 si.lpReserved2 = NULL;
3872
3873 /* There is a strange error on Windows 95 when using "c:\\command.com".
3874 * When the "c:\\" is left out it works OK...? */
3875 if (mch_windows95()
3876 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3877 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3878 cmd += 3;
3879
3880 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01003881 vim_create_process(cmd, FALSE,
3882 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE, &si, &pi);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883
3884 /* Wait for the command to terminate before continuing */
3885 if (g_PlatformId != VER_PLATFORM_WIN32s)
3886 {
3887#ifdef FEAT_GUI
3888 int delay = 1;
3889
3890 /* Keep updating the window while waiting for the shell to finish. */
3891 for (;;)
3892 {
3893 MSG msg;
3894
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003895 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003896 {
3897 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003898 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003899 delay = 1;
3900 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901 }
3902 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3903 break;
3904
3905 /* We start waiting for a very short time and then increase it, so
3906 * that we respond quickly when the process is quick, and don't
3907 * consume too much overhead when it's slow. */
3908 if (delay < 50)
3909 delay += 10;
3910 }
3911#else
3912 WaitForSingleObject(pi.hProcess, INFINITE);
3913#endif
3914
3915 /* Get the command exit code */
3916 GetExitCodeProcess(pi.hProcess, &ret);
3917 }
3918 else
3919 {
3920 /*
3921 * This ugly code is the only quick way of performing
3922 * a synchronous spawn under Win32s. Yuk.
3923 */
3924 num_windows = 0;
3925 EnumWindows(win32ssynch_cb, 0);
3926 old_num_windows = num_windows;
3927 do
3928 {
3929 Sleep(1000);
3930 num_windows = 0;
3931 EnumWindows(win32ssynch_cb, 0);
3932 } while (num_windows == old_num_windows);
3933 ret = 0;
3934 }
3935
3936 /* Close the handles to the subprocess, so that it goes away */
3937 CloseHandle(pi.hThread);
3938 CloseHandle(pi.hProcess);
3939
3940 /* Try to get input focus back. Doesn't always work though. */
3941 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3942
3943 return ret;
3944}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003945
3946/*
3947 * Thread launched by the gui to send the current buffer data to the
3948 * process. This way avoid to hang up vim totally if the children
3949 * process take a long time to process the lines.
3950 */
3951 static DWORD WINAPI
3952sub_process_writer(LPVOID param)
3953{
3954 HANDLE g_hChildStd_IN_Wr = param;
3955 linenr_T lnum = curbuf->b_op_start.lnum;
3956 DWORD len = 0;
3957 DWORD l;
3958 char_u *lp = ml_get(lnum);
3959 char_u *s;
3960 int written = 0;
3961
3962 for (;;)
3963 {
3964 l = (DWORD)STRLEN(lp + written);
3965 if (l == 0)
3966 len = 0;
3967 else if (lp[written] == NL)
3968 {
3969 /* NL -> NUL translation */
3970 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3971 }
3972 else
3973 {
3974 s = vim_strchr(lp + written, NL);
3975 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3976 s == NULL ? l : (DWORD)(s - (lp + written)),
3977 &len, NULL);
3978 }
3979 if (len == (int)l)
3980 {
3981 /* Finished a line, add a NL, unless this line should not have
3982 * one. */
3983 if (lnum != curbuf->b_op_end.lnum
3984 || !curbuf->b_p_bin
3985 || (lnum != curbuf->b_no_eol_lnum
3986 && (lnum != curbuf->b_ml.ml_line_count
3987 || curbuf->b_p_eol)))
3988 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01003989 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003990 }
3991
3992 ++lnum;
3993 if (lnum > curbuf->b_op_end.lnum)
3994 break;
3995
3996 lp = ml_get(lnum);
3997 written = 0;
3998 }
3999 else if (len > 0)
4000 written += len;
4001 }
4002
4003 /* finished all the lines, close pipe */
4004 CloseHandle(g_hChildStd_IN_Wr);
4005 ExitThread(0);
4006}
4007
4008
4009# define BUFLEN 100 /* length for buffer, stolen from unix version */
4010
4011/*
4012 * This function read from the children's stdout and write the
4013 * data on screen or in the buffer accordingly.
4014 */
4015 static void
4016dump_pipe(int options,
4017 HANDLE g_hChildStd_OUT_Rd,
4018 garray_T *ga,
4019 char_u buffer[],
4020 DWORD *buffer_off)
4021{
4022 DWORD availableBytes = 0;
4023 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004024 int ret;
4025 DWORD len;
4026 DWORD toRead;
4027 int repeatCount;
4028
4029 /* we query the pipe to see if there is any data to read
4030 * to avoid to perform a blocking read */
4031 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4032 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004033 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004034 NULL, /* number of read bytes */
4035 &availableBytes, /* available bytes total */
4036 NULL); /* byteLeft */
4037
4038 repeatCount = 0;
4039 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004040 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004041 {
4042 repeatCount++;
4043 toRead =
4044# ifdef FEAT_MBYTE
4045 (DWORD)(BUFLEN - *buffer_off);
4046# else
4047 (DWORD)BUFLEN;
4048# endif
4049 toRead = availableBytes < toRead ? availableBytes : toRead;
4050 ReadFile(g_hChildStd_OUT_Rd, buffer
4051# ifdef FEAT_MBYTE
4052 + *buffer_off, toRead
4053# else
4054 , toRead
4055# endif
4056 , &len, NULL);
4057
4058 /* If we haven't read anything, there is a problem */
4059 if (len == 0)
4060 break;
4061
4062 availableBytes -= len;
4063
4064 if (options & SHELL_READ)
4065 {
4066 /* Do NUL -> NL translation, append NL separated
4067 * lines to the current buffer. */
4068 for (i = 0; i < len; ++i)
4069 {
4070 if (buffer[i] == NL)
4071 append_ga_line(ga);
4072 else if (buffer[i] == NUL)
4073 ga_append(ga, NL);
4074 else
4075 ga_append(ga, buffer[i]);
4076 }
4077 }
4078# ifdef FEAT_MBYTE
4079 else if (has_mbyte)
4080 {
4081 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004082 int c;
4083 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004084
4085 len += *buffer_off;
4086 buffer[len] = NUL;
4087
4088 /* Check if the last character in buffer[] is
4089 * incomplete, keep these bytes for the next
4090 * round. */
4091 for (p = buffer; p < buffer + len; p += l)
4092 {
4093 l = mb_cptr2len(p);
4094 if (l == 0)
4095 l = 1; /* NUL byte? */
4096 else if (MB_BYTE2LEN(*p) != l)
4097 break;
4098 }
4099 if (p == buffer) /* no complete character */
4100 {
4101 /* avoid getting stuck at an illegal byte */
4102 if (len >= 12)
4103 ++p;
4104 else
4105 {
4106 *buffer_off = len;
4107 return;
4108 }
4109 }
4110 c = *p;
4111 *p = NUL;
4112 msg_puts(buffer);
4113 if (p < buffer + len)
4114 {
4115 *p = c;
4116 *buffer_off = (DWORD)((buffer + len) - p);
4117 mch_memmove(buffer, p, *buffer_off);
4118 return;
4119 }
4120 *buffer_off = 0;
4121 }
4122# endif /* FEAT_MBYTE */
4123 else
4124 {
4125 buffer[len] = NUL;
4126 msg_puts(buffer);
4127 }
4128
4129 windgoto(msg_row, msg_col);
4130 cursor_on();
4131 out_flush();
4132 }
4133}
4134
4135/*
4136 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4137 * for communication and doesn't open any new window.
4138 */
4139 static int
4140mch_system_piped(char *cmd, int options)
4141{
4142 STARTUPINFO si;
4143 PROCESS_INFORMATION pi;
4144 DWORD ret = 0;
4145
4146 HANDLE g_hChildStd_IN_Rd = NULL;
4147 HANDLE g_hChildStd_IN_Wr = NULL;
4148 HANDLE g_hChildStd_OUT_Rd = NULL;
4149 HANDLE g_hChildStd_OUT_Wr = NULL;
4150
4151 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4152 DWORD len;
4153
4154 /* buffer used to receive keys */
4155 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4156 int ta_len = 0; /* valid bytes in ta_buf[] */
4157
4158 DWORD i;
4159 int c;
4160 int noread_cnt = 0;
4161 garray_T ga;
4162 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004163 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004164 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004165
4166 SECURITY_ATTRIBUTES saAttr;
4167
4168 /* Set the bInheritHandle flag so pipe handles are inherited. */
4169 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4170 saAttr.bInheritHandle = TRUE;
4171 saAttr.lpSecurityDescriptor = NULL;
4172
4173 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4174 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4175 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4176 /* Create a pipe for the child process's STDIN. */
4177 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4178 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4179 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4180 {
4181 CloseHandle(g_hChildStd_IN_Rd);
4182 CloseHandle(g_hChildStd_IN_Wr);
4183 CloseHandle(g_hChildStd_OUT_Rd);
4184 CloseHandle(g_hChildStd_OUT_Wr);
4185 MSG_PUTS(_("\nCannot create pipes\n"));
4186 }
4187
4188 si.cb = sizeof(si);
4189 si.lpReserved = NULL;
4190 si.lpDesktop = NULL;
4191 si.lpTitle = NULL;
4192 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4193
4194 /* set-up our file redirection */
4195 si.hStdError = g_hChildStd_OUT_Wr;
4196 si.hStdOutput = g_hChildStd_OUT_Wr;
4197 si.hStdInput = g_hChildStd_IN_Rd;
4198 si.wShowWindow = SW_HIDE;
4199 si.cbReserved2 = 0;
4200 si.lpReserved2 = NULL;
4201
4202 if (options & SHELL_READ)
4203 ga_init2(&ga, 1, BUFLEN);
4204
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004205 if (cmd != NULL)
4206 {
4207 p = (char *)vim_strsave((char_u *)cmd);
4208 if (p != NULL)
4209 unescape_shellxquote((char_u *)p, p_sxe);
4210 else
4211 p = cmd;
4212 }
4213
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004214 /* Now, run the command.
4215 * About "Inherit handles" being TRUE: this command can be litigious,
4216 * handle inheritance was deactivated for pending temp file, but, if we
4217 * deactivate it, the pipes don't work for some reason. */
4218 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE, &si, &pi);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004219
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004220 if (p != cmd)
4221 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004222
4223 /* Close our unused side of the pipes */
4224 CloseHandle(g_hChildStd_IN_Rd);
4225 CloseHandle(g_hChildStd_OUT_Wr);
4226
4227 if (options & SHELL_WRITE)
4228 {
4229 HANDLE thread =
4230 CreateThread(NULL, /* security attributes */
4231 0, /* default stack size */
4232 sub_process_writer, /* function to be executed */
4233 g_hChildStd_IN_Wr, /* parameter */
4234 0, /* creation flag, start immediately */
4235 NULL); /* we don't care about thread id */
4236 CloseHandle(thread);
4237 g_hChildStd_IN_Wr = NULL;
4238 }
4239
4240 /* Keep updating the window while waiting for the shell to finish. */
4241 for (;;)
4242 {
4243 MSG msg;
4244
4245 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4246 {
4247 TranslateMessage(&msg);
4248 DispatchMessage(&msg);
4249 }
4250
4251 /* write pipe information in the window */
4252 if ((options & (SHELL_READ|SHELL_WRITE))
4253# ifdef FEAT_GUI
4254 || gui.in_use
4255# endif
4256 )
4257 {
4258 len = 0;
4259 if (!(options & SHELL_EXPAND)
4260 && ((options &
4261 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4262 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4263# ifdef FEAT_GUI
4264 || gui.in_use
4265# endif
4266 )
4267 && (ta_len > 0 || noread_cnt > 4))
4268 {
4269 if (ta_len == 0)
4270 {
4271 /* Get extra characters when we don't have any. Reset the
4272 * counter and timer. */
4273 noread_cnt = 0;
4274# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4275 gettimeofday(&start_tv, NULL);
4276# endif
4277 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4278 }
4279 if (ta_len > 0 || len > 0)
4280 {
4281 /*
4282 * For pipes: Check for CTRL-C: send interrupt signal to
4283 * child. Check for CTRL-D: EOF, close pipe to child.
4284 */
4285 if (len == 1 && cmd != NULL)
4286 {
4287 if (ta_buf[ta_len] == Ctrl_C)
4288 {
4289 /* Learn what exit code is expected, for
4290 * now put 9 as SIGKILL */
4291 TerminateProcess(pi.hProcess, 9);
4292 }
4293 if (ta_buf[ta_len] == Ctrl_D)
4294 {
4295 CloseHandle(g_hChildStd_IN_Wr);
4296 g_hChildStd_IN_Wr = NULL;
4297 }
4298 }
4299
4300 /* replace K_BS by <BS> and K_DEL by <DEL> */
4301 for (i = ta_len; i < ta_len + len; ++i)
4302 {
4303 if (ta_buf[i] == CSI && len - i > 2)
4304 {
4305 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4306 if (c == K_DEL || c == K_KDEL || c == K_BS)
4307 {
4308 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4309 (size_t)(len - i - 2));
4310 if (c == K_DEL || c == K_KDEL)
4311 ta_buf[i] = DEL;
4312 else
4313 ta_buf[i] = Ctrl_H;
4314 len -= 2;
4315 }
4316 }
4317 else if (ta_buf[i] == '\r')
4318 ta_buf[i] = '\n';
4319# ifdef FEAT_MBYTE
4320 if (has_mbyte)
4321 i += (*mb_ptr2len_len)(ta_buf + i,
4322 ta_len + len - i) - 1;
4323# endif
4324 }
4325
4326 /*
4327 * For pipes: echo the typed characters. For a pty this
4328 * does not seem to work.
4329 */
4330 for (i = ta_len; i < ta_len + len; ++i)
4331 {
4332 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4333 msg_putchar(ta_buf[i]);
4334# ifdef FEAT_MBYTE
4335 else if (has_mbyte)
4336 {
4337 int l = (*mb_ptr2len)(ta_buf + i);
4338
4339 msg_outtrans_len(ta_buf + i, l);
4340 i += l - 1;
4341 }
4342# endif
4343 else
4344 msg_outtrans_len(ta_buf + i, 1);
4345 }
4346 windgoto(msg_row, msg_col);
4347 out_flush();
4348
4349 ta_len += len;
4350
4351 /*
4352 * Write the characters to the child, unless EOF has been
4353 * typed for pipes. Write one character at a time, to
4354 * avoid losing too much typeahead. When writing buffer
4355 * lines, drop the typed characters (only check for
4356 * CTRL-C).
4357 */
4358 if (options & SHELL_WRITE)
4359 ta_len = 0;
4360 else if (g_hChildStd_IN_Wr != NULL)
4361 {
4362 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4363 1, &len, NULL);
4364 // if we are typing in, we want to keep things reactive
4365 delay = 1;
4366 if (len > 0)
4367 {
4368 ta_len -= len;
4369 mch_memmove(ta_buf, ta_buf + len, ta_len);
4370 }
4371 }
4372 }
4373 }
4374 }
4375
4376 if (ta_len)
4377 ui_inchar_undo(ta_buf, ta_len);
4378
4379 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4380 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004381 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004382 break;
4383 }
4384
4385 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004386 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004387
4388 /* We start waiting for a very short time and then increase it, so
4389 * that we respond quickly when the process is quick, and don't
4390 * consume too much overhead when it's slow. */
4391 if (delay < 50)
4392 delay += 10;
4393 }
4394
4395 /* Close the pipe */
4396 CloseHandle(g_hChildStd_OUT_Rd);
4397 if (g_hChildStd_IN_Wr != NULL)
4398 CloseHandle(g_hChildStd_IN_Wr);
4399
4400 WaitForSingleObject(pi.hProcess, INFINITE);
4401
4402 /* Get the command exit code */
4403 GetExitCodeProcess(pi.hProcess, &ret);
4404
4405 if (options & SHELL_READ)
4406 {
4407 if (ga.ga_len > 0)
4408 {
4409 append_ga_line(&ga);
4410 /* remember that the NL was missing */
4411 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4412 }
4413 else
4414 curbuf->b_no_eol_lnum = 0;
4415 ga_clear(&ga);
4416 }
4417
4418 /* Close the handles to the subprocess, so that it goes away */
4419 CloseHandle(pi.hThread);
4420 CloseHandle(pi.hProcess);
4421
4422 return ret;
4423}
4424
4425 static int
4426mch_system(char *cmd, int options)
4427{
4428 /* if we can pipe and the shelltemp option is off */
4429 if (allowPiping && !p_stmp)
4430 return mch_system_piped(cmd, options);
4431 else
4432 return mch_system_classic(cmd, options);
4433}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004434#else
4435
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004436# ifdef FEAT_MBYTE
4437 static int
4438mch_system(char *cmd, int options)
4439{
4440 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4441 {
4442 WCHAR *wcmd = enc_to_utf16(cmd, NULL);
4443 if (wcmd != NULL)
4444 {
4445 int ret = _wsystem(wcmd);
4446 vim_free(wcmd);
4447 return ret;
4448 }
4449 }
4450 return system(cmd);
4451}
4452# else
4453# define mch_system(c, o) system(c)
4454# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455
4456#endif
4457
4458/*
4459 * Either execute a command by calling the shell or start a new shell
4460 */
4461 int
4462mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004463 char_u *cmd,
4464 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004465{
4466 int x = 0;
4467 int tmode = cur_tmode;
4468#ifdef FEAT_TITLE
4469 char szShellTitle[512];
4470
4471 /* Change the title to reflect that we are in a subshell. */
4472 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
4473 {
4474 if (cmd == NULL)
4475 strcat(szShellTitle, " :sh");
4476 else
4477 {
4478 strcat(szShellTitle, " - !");
4479 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4480 strcat(szShellTitle, cmd);
4481 }
4482 mch_settitle(szShellTitle, NULL);
4483 }
4484#endif
4485
4486 out_flush();
4487
4488#ifdef MCH_WRITE_DUMP
4489 if (fdDump)
4490 {
4491 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4492 fflush(fdDump);
4493 }
4494#endif
4495
4496 /*
4497 * Catch all deadly signals while running the external command, because a
4498 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4499 */
4500 signal(SIGINT, SIG_IGN);
4501#if defined(__GNUC__) && !defined(__MINGW32__)
4502 signal(SIGKILL, SIG_IGN);
4503#else
4504 signal(SIGBREAK, SIG_IGN);
4505#endif
4506 signal(SIGILL, SIG_IGN);
4507 signal(SIGFPE, SIG_IGN);
4508 signal(SIGSEGV, SIG_IGN);
4509 signal(SIGTERM, SIG_IGN);
4510 signal(SIGABRT, SIG_IGN);
4511
4512 if (options & SHELL_COOKED)
4513 settmode(TMODE_COOK); /* set to normal mode */
4514
4515 if (cmd == NULL)
4516 {
4517 x = mch_system(p_sh, options);
4518 }
4519 else
4520 {
4521 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004522 char_u *newcmd = NULL;
4523 char_u *cmdbase = cmd;
4524 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004525
4526 /* Skip a leading ", ( and "(. */
4527 if (*cmdbase == '"' )
4528 ++cmdbase;
4529 if (*cmdbase == '(')
4530 ++cmdbase;
4531
4532 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4533 {
4534 STARTUPINFO si;
4535 PROCESS_INFORMATION pi;
4536 DWORD flags = CREATE_NEW_CONSOLE;
4537 char_u *p;
4538
4539 si.cb = sizeof(si);
4540 si.lpReserved = NULL;
4541 si.lpDesktop = NULL;
4542 si.lpTitle = NULL;
4543 si.dwFlags = 0;
4544 si.cbReserved2 = 0;
4545 si.lpReserved2 = NULL;
4546
4547 cmdbase = skipwhite(cmdbase + 5);
4548 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4549 && vim_iswhite(cmdbase[4]))
4550 {
4551 cmdbase = skipwhite(cmdbase + 4);
4552 si.dwFlags = STARTF_USESHOWWINDOW;
4553 si.wShowWindow = SW_SHOWMINNOACTIVE;
4554 }
4555 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4556 && vim_iswhite(cmdbase[2]))
4557 {
4558 cmdbase = skipwhite(cmdbase + 2);
4559 flags = CREATE_NO_WINDOW;
4560 si.dwFlags = STARTF_USESTDHANDLES;
4561 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004562 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004563 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004564 NULL, // Security att.
4565 OPEN_EXISTING, // Open flags
4566 FILE_ATTRIBUTE_NORMAL, // File att.
4567 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004568 si.hStdOutput = si.hStdInput;
4569 si.hStdError = si.hStdInput;
4570 }
4571
4572 /* Remove a trailing ", ) and )" if they have a match
4573 * at the start of the command. */
4574 if (cmdbase > cmd)
4575 {
4576 p = cmdbase + STRLEN(cmdbase);
4577 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4578 *--p = NUL;
4579 if (p > cmdbase && p[-1] == ')'
4580 && (*cmd =='(' || cmd[1] == '('))
4581 *--p = NUL;
4582 }
4583
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004584 newcmd = cmdbase;
4585 unescape_shellxquote(cmdbase, p_sxe);
4586
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004587 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004588 * If creating new console, arguments are passed to the
4589 * 'cmd.exe' as-is. If it's not, arguments are not treated
4590 * correctly for current 'cmd.exe'. So unescape characters in
4591 * shellxescape except '|' for avoiding to be treated as
4592 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004593 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004594 if (flags != CREATE_NEW_CONSOLE)
4595 {
4596 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004597 char_u *cmd_shell = mch_getenv("COMSPEC");
4598
4599 if (cmd_shell == NULL || *cmd_shell == NUL)
4600 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004601
4602 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4603 if (subcmd != NULL)
4604 {
4605 /* make "cmd.exe /c arguments" */
4606 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004607 newcmd = lalloc(cmdlen, TRUE);
4608 if (newcmd != NULL)
4609 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004610 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004611 else
4612 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004613 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004614 }
4615 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004616
4617 /*
4618 * Now, start the command as a process, so that it doesn't
4619 * inherit our handles which causes unpleasant dangling swap
4620 * files if we exit before the spawned process
4621 */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004622 if (vim_create_process(newcmd, FALSE, flags, &si, &pi))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004623 x = 0;
4624 else
4625 {
4626 x = -1;
4627#ifdef FEAT_GUI_W32
4628 EMSG(_("E371: Command not found"));
4629#endif
4630 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004631
4632 if (newcmd != cmdbase)
4633 vim_free(newcmd);
4634
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004635 if (si.hStdInput != NULL)
4636 {
4637 /* Close the handle to \\.\NUL */
4638 CloseHandle(si.hStdInput);
4639 }
4640 /* Close the handles to the subprocess, so that it goes away */
4641 CloseHandle(pi.hThread);
4642 CloseHandle(pi.hProcess);
4643 }
4644 else
4645 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004646 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004647#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004648 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004649#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004650 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4651
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004652 newcmd = lalloc(cmdlen, TRUE);
4653 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004654 {
4655#if defined(FEAT_GUI_W32)
4656 if (need_vimrun_warning)
4657 {
4658 MessageBox(NULL,
4659 _("VIMRUN.EXE not found in your $PATH.\n"
4660 "External commands will not pause after completion.\n"
4661 "See :help win32-vimrun for more information."),
4662 _("Vim Warning"),
4663 MB_ICONWARNING);
4664 need_vimrun_warning = FALSE;
4665 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004666 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004667 /* Use vimrun to execute the command. It opens a console
4668 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004669 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004670 vimrun_path,
4671 (msg_silent != 0 || (options & SHELL_DOOUT))
4672 ? "-s " : "",
4673 p_sh, p_shcf, cmd);
4674 else
4675#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004676 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004677 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004679 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004680 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004681 }
4682 }
4683
4684 if (tmode == TMODE_RAW)
4685 settmode(TMODE_RAW); /* set to raw mode */
4686
4687 /* Print the return value, unless "vimrun" was used. */
4688 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4689#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004690 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4691 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004692#endif
4693 )
4694 {
4695 smsg(_("shell returned %d"), x);
4696 msg_putchar('\n');
4697 }
4698#ifdef FEAT_TITLE
4699 resettitle();
4700#endif
4701
4702 signal(SIGINT, SIG_DFL);
4703#if defined(__GNUC__) && !defined(__MINGW32__)
4704 signal(SIGKILL, SIG_DFL);
4705#else
4706 signal(SIGBREAK, SIG_DFL);
4707#endif
4708 signal(SIGILL, SIG_DFL);
4709 signal(SIGFPE, SIG_DFL);
4710 signal(SIGSEGV, SIG_DFL);
4711 signal(SIGTERM, SIG_DFL);
4712 signal(SIGABRT, SIG_DFL);
4713
4714 return x;
4715}
4716
4717
4718#ifndef FEAT_GUI_W32
4719
4720/*
4721 * Start termcap mode
4722 */
4723 static void
4724termcap_mode_start(void)
4725{
4726 DWORD cmodein;
4727
4728 if (g_fTermcapMode)
4729 return;
4730
4731 SaveConsoleBuffer(&g_cbNonTermcap);
4732
4733 if (g_cbTermcap.IsValid)
4734 {
4735 /*
4736 * We've been in termcap mode before. Restore certain screen
4737 * characteristics, including the buffer size and the window
4738 * size. Since we will be redrawing the screen, we don't need
4739 * to restore the actual contents of the buffer.
4740 */
4741 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4742 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4743 Rows = g_cbTermcap.Info.dwSize.Y;
4744 Columns = g_cbTermcap.Info.dwSize.X;
4745 }
4746 else
4747 {
4748 /*
4749 * This is our first time entering termcap mode. Clear the console
4750 * screen buffer, and resize the buffer to match the current window
4751 * size. We will use this as the size of our editing environment.
4752 */
4753 ClearConsoleBuffer(g_attrCurrent);
4754 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4755 }
4756
4757#ifdef FEAT_TITLE
4758 resettitle();
4759#endif
4760
4761 GetConsoleMode(g_hConIn, &cmodein);
4762#ifdef FEAT_MOUSE
4763 if (g_fMouseActive)
4764 cmodein |= ENABLE_MOUSE_INPUT;
4765 else
4766 cmodein &= ~ENABLE_MOUSE_INPUT;
4767#endif
4768 cmodein |= ENABLE_WINDOW_INPUT;
4769 SetConsoleMode(g_hConIn, cmodein);
4770
4771 redraw_later_clear();
4772 g_fTermcapMode = TRUE;
4773}
4774
4775
4776/*
4777 * End termcap mode
4778 */
4779 static void
4780termcap_mode_end(void)
4781{
4782 DWORD cmodein;
4783 ConsoleBuffer *cb;
4784 COORD coord;
4785 DWORD dwDummy;
4786
4787 if (!g_fTermcapMode)
4788 return;
4789
4790 SaveConsoleBuffer(&g_cbTermcap);
4791
4792 GetConsoleMode(g_hConIn, &cmodein);
4793 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4794 SetConsoleMode(g_hConIn, cmodein);
4795
4796#ifdef FEAT_RESTORE_ORIG_SCREEN
4797 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4798#else
4799 cb = &g_cbNonTermcap;
4800#endif
4801 RestoreConsoleBuffer(cb, p_rs);
4802 SetConsoleCursorInfo(g_hConOut, &g_cci);
4803
4804 if (p_rs || exiting)
4805 {
4806 /*
4807 * Clear anything that happens to be on the current line.
4808 */
4809 coord.X = 0;
4810 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4811 FillConsoleOutputCharacter(g_hConOut, ' ',
4812 cb->Info.dwSize.X, coord, &dwDummy);
4813 /*
4814 * The following is just for aesthetics. If we are exiting without
4815 * restoring the screen, then we want to have a prompt string
4816 * appear at the bottom line. However, the command interpreter
4817 * seems to always advance the cursor one line before displaying
4818 * the prompt string, which causes the screen to scroll. To
4819 * counter this, move the cursor up one line before exiting.
4820 */
4821 if (exiting && !p_rs)
4822 coord.Y--;
4823 /*
4824 * Position the cursor at the leftmost column of the desired row.
4825 */
4826 SetConsoleCursorPosition(g_hConOut, coord);
4827 }
4828
4829 g_fTermcapMode = FALSE;
4830}
4831#endif /* FEAT_GUI_W32 */
4832
4833
4834#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004835/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836 void
4837mch_write(
4838 char_u *s,
4839 int len)
4840{
4841 /* never used */
4842}
4843
4844#else
4845
4846/*
4847 * clear `n' chars, starting from `coord'
4848 */
4849 static void
4850clear_chars(
4851 COORD coord,
4852 DWORD n)
4853{
4854 DWORD dwDummy;
4855
4856 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4857 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4858}
4859
4860
4861/*
4862 * Clear the screen
4863 */
4864 static void
4865clear_screen(void)
4866{
4867 g_coord.X = g_coord.Y = 0;
4868 clear_chars(g_coord, Rows * Columns);
4869}
4870
4871
4872/*
4873 * Clear to end of display
4874 */
4875 static void
4876clear_to_end_of_display(void)
4877{
4878 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4879 * Columns + (Columns - g_coord.X));
4880}
4881
4882
4883/*
4884 * Clear to end of line
4885 */
4886 static void
4887clear_to_end_of_line(void)
4888{
4889 clear_chars(g_coord, Columns - g_coord.X);
4890}
4891
4892
4893/*
4894 * Scroll the scroll region up by `cLines' lines
4895 */
4896 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004897scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898{
4899 COORD oldcoord = g_coord;
4900
4901 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4902 delete_lines(cLines);
4903
4904 g_coord = oldcoord;
4905}
4906
4907
4908/*
4909 * Set the scroll region
4910 */
4911 static void
4912set_scroll_region(
4913 unsigned left,
4914 unsigned top,
4915 unsigned right,
4916 unsigned bottom)
4917{
4918 if (left >= right
4919 || top >= bottom
4920 || right > (unsigned) Columns - 1
4921 || bottom > (unsigned) Rows - 1)
4922 return;
4923
4924 g_srScrollRegion.Left = left;
4925 g_srScrollRegion.Top = top;
4926 g_srScrollRegion.Right = right;
4927 g_srScrollRegion.Bottom = bottom;
4928}
4929
4930
4931/*
4932 * Insert `cLines' lines at the current cursor position
4933 */
4934 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004935insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936{
4937 SMALL_RECT source;
4938 COORD dest;
4939 CHAR_INFO fill;
4940
4941 dest.X = 0;
4942 dest.Y = g_coord.Y + cLines;
4943
4944 source.Left = 0;
4945 source.Top = g_coord.Y;
4946 source.Right = g_srScrollRegion.Right;
4947 source.Bottom = g_srScrollRegion.Bottom - cLines;
4948
4949 fill.Char.AsciiChar = ' ';
4950 fill.Attributes = g_attrCurrent;
4951
4952 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4953
4954 /* Here we have to deal with a win32 console flake: If the scroll
4955 * region looks like abc and we scroll c to a and fill with d we get
4956 * cbd... if we scroll block c one line at a time to a, we get cdd...
4957 * vim expects cdd consistently... So we have to deal with that
4958 * here... (this also occurs scrolling the same way in the other
4959 * direction). */
4960
4961 if (source.Bottom < dest.Y)
4962 {
4963 COORD coord;
4964
4965 coord.X = 0;
4966 coord.Y = source.Bottom;
4967 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4968 }
4969}
4970
4971
4972/*
4973 * Delete `cLines' lines at the current cursor position
4974 */
4975 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004976delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977{
4978 SMALL_RECT source;
4979 COORD dest;
4980 CHAR_INFO fill;
4981 int nb;
4982
4983 dest.X = 0;
4984 dest.Y = g_coord.Y;
4985
4986 source.Left = 0;
4987 source.Top = g_coord.Y + cLines;
4988 source.Right = g_srScrollRegion.Right;
4989 source.Bottom = g_srScrollRegion.Bottom;
4990
4991 fill.Char.AsciiChar = ' ';
4992 fill.Attributes = g_attrCurrent;
4993
4994 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4995
4996 /* Here we have to deal with a win32 console flake: If the scroll
4997 * region looks like abc and we scroll c to a and fill with d we get
4998 * cbd... if we scroll block c one line at a time to a, we get cdd...
4999 * vim expects cdd consistently... So we have to deal with that
5000 * here... (this also occurs scrolling the same way in the other
5001 * direction). */
5002
5003 nb = dest.Y + (source.Bottom - source.Top) + 1;
5004
5005 if (nb < source.Top)
5006 {
5007 COORD coord;
5008
5009 coord.X = 0;
5010 coord.Y = nb;
5011 clear_chars(coord, Columns * (source.Top - nb));
5012 }
5013}
5014
5015
5016/*
5017 * Set the cursor position
5018 */
5019 static void
5020gotoxy(
5021 unsigned x,
5022 unsigned y)
5023{
5024 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5025 return;
5026
5027 /* external cursor coords are 1-based; internal are 0-based */
5028 g_coord.X = x - 1;
5029 g_coord.Y = y - 1;
5030 SetConsoleCursorPosition(g_hConOut, g_coord);
5031}
5032
5033
5034/*
5035 * Set the current text attribute = (foreground | background)
5036 * See ../doc/os_win32.txt for the numbers.
5037 */
5038 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005039textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040{
5041 g_attrCurrent = wAttr;
5042
5043 SetConsoleTextAttribute(g_hConOut, wAttr);
5044}
5045
5046
5047 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005048textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005049{
5050 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
5051
5052 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5053}
5054
5055
5056 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005057textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005058{
5059 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
5060
5061 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5062}
5063
5064
5065/*
5066 * restore the default text attribute (whatever we started with)
5067 */
5068 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005069normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005070{
5071 textattr(g_attrDefault);
5072}
5073
5074
5075static WORD g_attrPreStandout = 0;
5076
5077/*
5078 * Make the text standout, by brightening it
5079 */
5080 static void
5081standout(void)
5082{
5083 g_attrPreStandout = g_attrCurrent;
5084 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5085}
5086
5087
5088/*
5089 * Turn off standout mode
5090 */
5091 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005092standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005093{
5094 if (g_attrPreStandout)
5095 {
5096 textattr(g_attrPreStandout);
5097 g_attrPreStandout = 0;
5098 }
5099}
5100
5101
5102/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005103 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005104 */
5105 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005106mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005107{
5108 char_u *p;
5109 int n;
5110
5111 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5112 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5113 if (T_ME[0] == ESC && T_ME[1] == '|')
5114 {
5115 p = T_ME + 2;
5116 n = getdigits(&p);
5117 if (*p == 'm' && n > 0)
5118 {
5119 cterm_normal_fg_color = (n & 0xf) + 1;
5120 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5121 }
5122 }
5123}
5124
5125
5126/*
5127 * visual bell: flash the screen
5128 */
5129 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005130visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005131{
5132 COORD coordOrigin = {0, 0};
5133 WORD attrFlash = ~g_attrCurrent & 0xff;
5134
5135 DWORD dwDummy;
5136 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5137
5138 if (oldattrs == NULL)
5139 return;
5140 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5141 coordOrigin, &dwDummy);
5142 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5143 coordOrigin, &dwDummy);
5144
5145 Sleep(15); /* wait for 15 msec */
5146 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5147 coordOrigin, &dwDummy);
5148 vim_free(oldattrs);
5149}
5150
5151
5152/*
5153 * Make the cursor visible or invisible
5154 */
5155 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005156cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157{
5158 s_cursor_visible = fVisible;
5159#ifdef MCH_CURSOR_SHAPE
5160 mch_update_cursor();
5161#endif
5162}
5163
5164
5165/*
5166 * write `cchToWrite' characters in `pchBuf' to the screen
5167 * Returns the number of characters actually written (at least one).
5168 */
5169 static BOOL
5170write_chars(
5171 LPCSTR pchBuf,
5172 DWORD cchToWrite)
5173{
5174 COORD coord = g_coord;
5175 DWORD written;
5176
5177 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
5178 coord, &written);
5179 /* When writing fails or didn't write a single character, pretend one
5180 * character was written, otherwise we get stuck. */
5181 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
5182 coord, &written) == 0
5183 || written == 0)
5184 written = 1;
5185
5186 g_coord.X += (SHORT) written;
5187
5188 while (g_coord.X > g_srScrollRegion.Right)
5189 {
5190 g_coord.X -= (SHORT) Columns;
5191 if (g_coord.Y < g_srScrollRegion.Bottom)
5192 g_coord.Y++;
5193 }
5194
5195 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5196
5197 return written;
5198}
5199
5200
5201/*
5202 * mch_write(): write the output buffer to the screen, translating ESC
5203 * sequences into calls to console output routines.
5204 */
5205 void
5206mch_write(
5207 char_u *s,
5208 int len)
5209{
5210 s[len] = NUL;
5211
5212 if (!term_console)
5213 {
5214 write(1, s, (unsigned)len);
5215 return;
5216 }
5217
5218 /* translate ESC | sequences into faked bios calls */
5219 while (len--)
5220 {
5221 /* optimization: use one single write_chars for runs of text,
5222 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005223 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005224
5225 if (p_wd)
5226 {
5227 WaitForChar(p_wd);
5228 if (prefix != 0)
5229 prefix = 1;
5230 }
5231
5232 if (prefix != 0)
5233 {
5234 DWORD nWritten;
5235
5236 nWritten = write_chars(s, prefix);
5237#ifdef MCH_WRITE_DUMP
5238 if (fdDump)
5239 {
5240 fputc('>', fdDump);
5241 fwrite(s, sizeof(char_u), nWritten, fdDump);
5242 fputs("<\n", fdDump);
5243 }
5244#endif
5245 len -= (nWritten - 1);
5246 s += nWritten;
5247 }
5248 else if (s[0] == '\n')
5249 {
5250 /* \n, newline: go to the beginning of the next line or scroll */
5251 if (g_coord.Y == g_srScrollRegion.Bottom)
5252 {
5253 scroll(1);
5254 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5255 }
5256 else
5257 {
5258 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5259 }
5260#ifdef MCH_WRITE_DUMP
5261 if (fdDump)
5262 fputs("\\n\n", fdDump);
5263#endif
5264 s++;
5265 }
5266 else if (s[0] == '\r')
5267 {
5268 /* \r, carriage return: go to beginning of line */
5269 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5270#ifdef MCH_WRITE_DUMP
5271 if (fdDump)
5272 fputs("\\r\n", fdDump);
5273#endif
5274 s++;
5275 }
5276 else if (s[0] == '\b')
5277 {
5278 /* \b, backspace: move cursor one position left */
5279 if (g_coord.X > g_srScrollRegion.Left)
5280 g_coord.X--;
5281 else if (g_coord.Y > g_srScrollRegion.Top)
5282 {
5283 g_coord.X = g_srScrollRegion.Right;
5284 g_coord.Y--;
5285 }
5286 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5287#ifdef MCH_WRITE_DUMP
5288 if (fdDump)
5289 fputs("\\b\n", fdDump);
5290#endif
5291 s++;
5292 }
5293 else if (s[0] == '\a')
5294 {
5295 /* \a, bell */
5296 MessageBeep(0xFFFFFFFF);
5297#ifdef MCH_WRITE_DUMP
5298 if (fdDump)
5299 fputs("\\a\n", fdDump);
5300#endif
5301 s++;
5302 }
5303 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5304 {
5305#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005306 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005307#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005308 char_u *p;
5309 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310
5311 switch (s[2])
5312 {
5313 /* one or two numeric arguments, separated by ';' */
5314
5315 case '0': case '1': case '2': case '3': case '4':
5316 case '5': case '6': case '7': case '8': case '9':
5317 p = s + 2;
5318 arg1 = getdigits(&p); /* no check for length! */
5319 if (p > s + len)
5320 break;
5321
5322 if (*p == ';')
5323 {
5324 ++p;
5325 arg2 = getdigits(&p); /* no check for length! */
5326 if (p > s + len)
5327 break;
5328
5329 if (*p == 'H')
5330 gotoxy(arg2, arg1);
5331 else if (*p == 'r')
5332 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5333 }
5334 else if (*p == 'A')
5335 {
5336 /* move cursor up arg1 lines in same column */
5337 gotoxy(g_coord.X + 1,
5338 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5339 }
5340 else if (*p == 'C')
5341 {
5342 /* move cursor right arg1 columns in same line */
5343 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5344 g_coord.Y + 1);
5345 }
5346 else if (*p == 'H')
5347 {
5348 gotoxy(1, arg1);
5349 }
5350 else if (*p == 'L')
5351 {
5352 insert_lines(arg1);
5353 }
5354 else if (*p == 'm')
5355 {
5356 if (arg1 == 0)
5357 normvideo();
5358 else
5359 textattr((WORD) arg1);
5360 }
5361 else if (*p == 'f')
5362 {
5363 textcolor((WORD) arg1);
5364 }
5365 else if (*p == 'b')
5366 {
5367 textbackground((WORD) arg1);
5368 }
5369 else if (*p == 'M')
5370 {
5371 delete_lines(arg1);
5372 }
5373
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005374 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005375 s = p + 1;
5376 break;
5377
5378
5379 /* Three-character escape sequences */
5380
5381 case 'A':
5382 /* move cursor up one line in same column */
5383 gotoxy(g_coord.X + 1,
5384 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5385 goto got3;
5386
5387 case 'B':
5388 visual_bell();
5389 goto got3;
5390
5391 case 'C':
5392 /* move cursor right one column in same line */
5393 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5394 g_coord.Y + 1);
5395 goto got3;
5396
5397 case 'E':
5398 termcap_mode_end();
5399 goto got3;
5400
5401 case 'F':
5402 standout();
5403 goto got3;
5404
5405 case 'f':
5406 standend();
5407 goto got3;
5408
5409 case 'H':
5410 gotoxy(1, 1);
5411 goto got3;
5412
5413 case 'j':
5414 clear_to_end_of_display();
5415 goto got3;
5416
5417 case 'J':
5418 clear_screen();
5419 goto got3;
5420
5421 case 'K':
5422 clear_to_end_of_line();
5423 goto got3;
5424
5425 case 'L':
5426 insert_lines(1);
5427 goto got3;
5428
5429 case 'M':
5430 delete_lines(1);
5431 goto got3;
5432
5433 case 'S':
5434 termcap_mode_start();
5435 goto got3;
5436
5437 case 'V':
5438 cursor_visible(TRUE);
5439 goto got3;
5440
5441 case 'v':
5442 cursor_visible(FALSE);
5443 goto got3;
5444
5445 got3:
5446 s += 3;
5447 len -= 2;
5448 }
5449
5450#ifdef MCH_WRITE_DUMP
5451 if (fdDump)
5452 {
5453 fputs("ESC | ", fdDump);
5454 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5455 fputc('\n', fdDump);
5456 }
5457#endif
5458 }
5459 else
5460 {
5461 /* Write a single character */
5462 DWORD nWritten;
5463
5464 nWritten = write_chars(s, 1);
5465#ifdef MCH_WRITE_DUMP
5466 if (fdDump)
5467 {
5468 fputc('>', fdDump);
5469 fwrite(s, sizeof(char_u), nWritten, fdDump);
5470 fputs("<\n", fdDump);
5471 }
5472#endif
5473
5474 len -= (nWritten - 1);
5475 s += nWritten;
5476 }
5477 }
5478
5479#ifdef MCH_WRITE_DUMP
5480 if (fdDump)
5481 fflush(fdDump);
5482#endif
5483}
5484
5485#endif /* FEAT_GUI_W32 */
5486
5487
5488/*
5489 * Delay for half a second.
5490 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005491/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005492 void
5493mch_delay(
5494 long msec,
5495 int ignoreinput)
5496{
5497#ifdef FEAT_GUI_W32
5498 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005499#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005500 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005501# ifdef FEAT_MZSCHEME
5502 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5503 {
5504 int towait = p_mzq;
5505
5506 /* if msec is large enough, wait by portions in p_mzq */
5507 while (msec > 0)
5508 {
5509 mzvim_check_threads();
5510 if (msec < towait)
5511 towait = msec;
5512 Sleep(towait);
5513 msec -= towait;
5514 }
5515 }
5516 else
5517# endif
5518 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005519 else
5520 WaitForChar(msec);
5521#endif
5522}
5523
5524
5525/*
5526 * this version of remove is not scared by a readonly (backup) file
5527 * Return 0 for success, -1 for failure.
5528 */
5529 int
5530mch_remove(char_u *name)
5531{
5532#ifdef FEAT_MBYTE
5533 WCHAR *wn = NULL;
5534 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005535#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005536
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005537 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5538
5539#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5541 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005542 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005543 if (wn != NULL)
5544 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005545 n = DeleteFileW(wn) ? 0 : -1;
5546 vim_free(wn);
5547 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5548 return n;
5549 /* Retry with non-wide function (for Windows 98). */
5550 }
5551 }
5552#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005553 return DeleteFile(name) ? 0 : -1;
5554}
5555
5556
5557/*
5558 * check for an "interrupt signal": CTRL-break or CTRL-C
5559 */
5560 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005561mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562{
5563#ifndef FEAT_GUI_W32 /* never used */
5564 if (g_fCtrlCPressed || g_fCBrkPressed)
5565 {
5566 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5567 got_int = TRUE;
5568 }
5569#endif
5570}
5571
5572
Bram Moolenaar071d4272004-06-13 20:20:40 +00005573#ifdef FEAT_MBYTE
5574/*
5575 * Same code as below, but with wide functions and no comments.
5576 * Return 0 for success, non-zero for failure.
5577 */
5578 int
5579mch_wrename(WCHAR *wold, WCHAR *wnew)
5580{
5581 WCHAR *p;
5582 int i;
5583 WCHAR szTempFile[_MAX_PATH + 1];
5584 WCHAR szNewPath[_MAX_PATH + 1];
5585 HANDLE hf;
5586
5587 if (!mch_windows95())
5588 {
5589 p = wold;
5590 for (i = 0; wold[i] != NUL; ++i)
5591 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5592 && wold[i + 1] != 0)
5593 p = wold + i + 1;
5594 if ((int)(wold + i - p) < 8 || p[6] != '~')
5595 return (MoveFileW(wold, wnew) == 0);
5596 }
5597
5598 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5599 return -1;
5600 *p = NUL;
5601
5602 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5603 return -2;
5604
5605 if (!DeleteFileW(szTempFile))
5606 return -3;
5607
5608 if (!MoveFileW(wold, szTempFile))
5609 return -4;
5610
5611 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5612 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5613 return -5;
5614 if (!CloseHandle(hf))
5615 return -6;
5616
5617 if (!MoveFileW(szTempFile, wnew))
5618 {
5619 (void)MoveFileW(szTempFile, wold);
5620 return -7;
5621 }
5622
5623 DeleteFileW(szTempFile);
5624
5625 if (!DeleteFileW(wold))
5626 return -8;
5627
5628 return 0;
5629}
5630#endif
5631
5632
5633/*
5634 * mch_rename() works around a bug in rename (aka MoveFile) in
5635 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5636 * file whose short file name is "FOO.BAR" (its long file name will
5637 * be correct: "foo.bar~"). Because a file can be accessed by
5638 * either its SFN or its LFN, "foo.bar" has effectively been
5639 * renamed to "foo.bar", which is not at all what was wanted. This
5640 * seems to happen only when renaming files with three-character
5641 * extensions by appending a suffix that does not include ".".
5642 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5643 *
5644 * There is another problem, which isn't really a bug but isn't right either:
5645 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5646 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5647 * service pack 6. Doesn't seem to happen on Windows 98.
5648 *
5649 * Like rename(), returns 0 upon success, non-zero upon failure.
5650 * Should probably set errno appropriately when errors occur.
5651 */
5652 int
5653mch_rename(
5654 const char *pszOldFile,
5655 const char *pszNewFile)
5656{
5657 char szTempFile[_MAX_PATH+1];
5658 char szNewPath[_MAX_PATH+1];
5659 char *pszFilePart;
5660 HANDLE hf;
5661#ifdef FEAT_MBYTE
5662 WCHAR *wold = NULL;
5663 WCHAR *wnew = NULL;
5664 int retval = -1;
5665
5666 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5667 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005668 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5669 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005670 if (wold != NULL && wnew != NULL)
5671 retval = mch_wrename(wold, wnew);
5672 vim_free(wold);
5673 vim_free(wnew);
5674 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5675 return retval;
5676 /* Retry with non-wide function (for Windows 98). */
5677 }
5678#endif
5679
5680 /*
5681 * No need to play tricks if not running Windows 95, unless the file name
5682 * contains a "~" as the seventh character.
5683 */
5684 if (!mch_windows95())
5685 {
5686 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5687 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5688 return rename(pszOldFile, pszNewFile);
5689 }
5690
5691 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5692 * a directory, no error is returned and pszFilePart will be NULL. */
5693 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5694 || pszFilePart == NULL)
5695 return -1;
5696 *pszFilePart = NUL;
5697
5698 /* Get (and create) a unique temporary file name in directory of new file */
5699 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5700 return -2;
5701
5702 /* blow the temp file away */
5703 if (!DeleteFile(szTempFile))
5704 return -3;
5705
5706 /* rename old file to the temp file */
5707 if (!MoveFile(pszOldFile, szTempFile))
5708 return -4;
5709
5710 /* now create an empty file called pszOldFile; this prevents the operating
5711 * system using pszOldFile as an alias (SFN) if we're renaming within the
5712 * same directory. For example, we're editing a file called
5713 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5714 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5715 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005716 * cause all sorts of problems later in buf_write(). So, we create an
5717 * empty file called filena~1.txt and the system will have to find some
5718 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005719 */
5720 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5721 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5722 return -5;
5723 if (!CloseHandle(hf))
5724 return -6;
5725
5726 /* rename the temp file to the new file */
5727 if (!MoveFile(szTempFile, pszNewFile))
5728 {
5729 /* Renaming failed. Rename the file back to its old name, so that it
5730 * looks like nothing happened. */
5731 (void)MoveFile(szTempFile, pszOldFile);
5732
5733 return -7;
5734 }
5735
5736 /* Seems to be left around on Novell filesystems */
5737 DeleteFile(szTempFile);
5738
5739 /* finally, remove the empty old file */
5740 if (!DeleteFile(pszOldFile))
5741 return -8;
5742
5743 return 0; /* success */
5744}
5745
5746/*
5747 * Get the default shell for the current hardware platform
5748 */
5749 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005750default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005751{
5752 char* psz = NULL;
5753
5754 PlatformId();
5755
5756 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5757 psz = "cmd.exe";
5758 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5759 psz = "command.com";
5760
5761 return psz;
5762}
5763
5764/*
5765 * mch_access() extends access() to do more detailed check on network drives.
5766 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5767 */
5768 int
5769mch_access(char *n, int p)
5770{
5771 HANDLE hFile;
5772 DWORD am;
5773 int retval = -1; /* default: fail */
5774#ifdef FEAT_MBYTE
5775 WCHAR *wn = NULL;
5776
5777 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005778 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779#endif
5780
5781 if (mch_isdir(n))
5782 {
5783 char TempName[_MAX_PATH + 16] = "";
5784#ifdef FEAT_MBYTE
5785 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5786#endif
5787
5788 if (p & R_OK)
5789 {
5790 /* Read check is performed by seeing if we can do a find file on
5791 * the directory for any file. */
5792#ifdef FEAT_MBYTE
5793 if (wn != NULL)
5794 {
5795 int i;
5796 WIN32_FIND_DATAW d;
5797
5798 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5799 TempNameW[i] = wn[i];
5800 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5801 TempNameW[i++] = '\\';
5802 TempNameW[i++] = '*';
5803 TempNameW[i++] = 0;
5804
5805 hFile = FindFirstFileW(TempNameW, &d);
5806 if (hFile == INVALID_HANDLE_VALUE)
5807 {
5808 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5809 goto getout;
5810
5811 /* Retry with non-wide function (for Windows 98). */
5812 vim_free(wn);
5813 wn = NULL;
5814 }
5815 else
5816 (void)FindClose(hFile);
5817 }
5818 if (wn == NULL)
5819#endif
5820 {
5821 char *pch;
5822 WIN32_FIND_DATA d;
5823
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005824 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005825 pch = TempName + STRLEN(TempName) - 1;
5826 if (*pch != '\\' && *pch != '/')
5827 *++pch = '\\';
5828 *++pch = '*';
5829 *++pch = NUL;
5830
5831 hFile = FindFirstFile(TempName, &d);
5832 if (hFile == INVALID_HANDLE_VALUE)
5833 goto getout;
5834 (void)FindClose(hFile);
5835 }
5836 }
5837
5838 if (p & W_OK)
5839 {
5840 /* Trying to create a temporary file in the directory should catch
5841 * directories on read-only network shares. However, in
5842 * directories whose ACL allows writes but denies deletes will end
5843 * up keeping the temporary file :-(. */
5844#ifdef FEAT_MBYTE
5845 if (wn != NULL)
5846 {
5847 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5848 {
5849 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5850 goto getout;
5851
5852 /* Retry with non-wide function (for Windows 98). */
5853 vim_free(wn);
5854 wn = NULL;
5855 }
5856 else
5857 DeleteFileW(TempNameW);
5858 }
5859 if (wn == NULL)
5860#endif
5861 {
5862 if (!GetTempFileName(n, "VIM", 0, TempName))
5863 goto getout;
5864 mch_remove((char_u *)TempName);
5865 }
5866 }
5867 }
5868 else
5869 {
5870 /* Trying to open the file for the required access does ACL, read-only
5871 * network share, and file attribute checks. */
5872 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5873 | ((p & R_OK) ? GENERIC_READ : 0);
5874#ifdef FEAT_MBYTE
5875 if (wn != NULL)
5876 {
5877 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5878 if (hFile == INVALID_HANDLE_VALUE
5879 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5880 {
5881 /* Retry with non-wide function (for Windows 98). */
5882 vim_free(wn);
5883 wn = NULL;
5884 }
5885 }
5886 if (wn == NULL)
5887#endif
5888 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5889 if (hFile == INVALID_HANDLE_VALUE)
5890 goto getout;
5891 CloseHandle(hFile);
5892 }
5893
5894 retval = 0; /* success */
5895getout:
5896#ifdef FEAT_MBYTE
5897 vim_free(wn);
5898#endif
5899 return retval;
5900}
5901
5902#if defined(FEAT_MBYTE) || defined(PROTO)
5903/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005904 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005905 */
5906 int
5907mch_open(char *name, int flags, int mode)
5908{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005909 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5910# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005911 WCHAR *wn;
5912 int f;
5913
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005914 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005915 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005916 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005917 if (wn != NULL)
5918 {
5919 f = _wopen(wn, flags, mode);
5920 vim_free(wn);
5921 if (f >= 0)
5922 return f;
5923 /* Retry with non-wide function (for Windows 98). Can't use
5924 * GetLastError() here and it's unclear what errno gets set to if
5925 * the _wopen() fails for missing wide functions. */
5926 }
5927 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005928# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005929
5930 return open(name, flags, mode);
5931}
5932
5933/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005934 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005935 */
5936 FILE *
5937mch_fopen(char *name, char *mode)
5938{
5939 WCHAR *wn, *wm;
5940 FILE *f = NULL;
5941
5942 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5943# ifdef __BORLANDC__
5944 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5945 && g_PlatformId == VER_PLATFORM_WIN32_NT
5946# endif
5947 )
5948 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005949# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005950 /* Work around an annoying assertion in the Microsoft debug CRT
5951 * when mode's text/binary setting doesn't match _get_fmode(). */
5952 char newMode = mode[strlen(mode) - 1];
5953 int oldMode = 0;
5954
5955 _get_fmode(&oldMode);
5956 if (newMode == 't')
5957 _set_fmode(_O_TEXT);
5958 else if (newMode == 'b')
5959 _set_fmode(_O_BINARY);
5960# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005961 wn = enc_to_utf16(name, NULL);
5962 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005963 if (wn != NULL && wm != NULL)
5964 f = _wfopen(wn, wm);
5965 vim_free(wn);
5966 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005967
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005968# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005969 _set_fmode(oldMode);
5970# endif
5971
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972 if (f != NULL)
5973 return f;
5974 /* Retry with non-wide function (for Windows 98). Can't use
5975 * GetLastError() here and it's unclear what errno gets set to if
5976 * the _wfopen() fails for missing wide functions. */
5977 }
5978
5979 return fopen(name, mode);
5980}
5981#endif
5982
5983#ifdef FEAT_MBYTE
5984/*
5985 * SUB STREAM (aka info stream) handling:
5986 *
5987 * NTFS can have sub streams for each file. Normal contents of file is
5988 * stored in the main stream, and extra contents (author information and
5989 * title and so on) can be stored in sub stream. After Windows 2000, user
5990 * can access and store those informations in sub streams via explorer's
5991 * property menuitem in right click menu. Those informations in sub streams
5992 * were lost when copying only the main stream. So we have to copy sub
5993 * streams.
5994 *
5995 * Incomplete explanation:
5996 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5997 * More useful info and an example:
5998 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5999 */
6000
6001/*
6002 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6003 * and write to stream "substream" of file "to".
6004 * Errors are ignored.
6005 */
6006 static void
6007copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6008{
6009 HANDLE hTo;
6010 WCHAR *to_name;
6011
6012 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6013 wcscpy(to_name, to);
6014 wcscat(to_name, substream);
6015
6016 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6017 FILE_ATTRIBUTE_NORMAL, NULL);
6018 if (hTo != INVALID_HANDLE_VALUE)
6019 {
6020 long done;
6021 DWORD todo;
6022 DWORD readcnt, written;
6023 char buf[4096];
6024
6025 /* Copy block of bytes at a time. Abort when something goes wrong. */
6026 for (done = 0; done < len; done += written)
6027 {
6028 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006029 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6030 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006031 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6032 FALSE, FALSE, context)
6033 || readcnt != todo
6034 || !WriteFile(hTo, buf, todo, &written, NULL)
6035 || written != todo)
6036 break;
6037 }
6038 CloseHandle(hTo);
6039 }
6040
6041 free(to_name);
6042}
6043
6044/*
6045 * Copy info streams from file "from" to file "to".
6046 */
6047 static void
6048copy_infostreams(char_u *from, char_u *to)
6049{
6050 WCHAR *fromw;
6051 WCHAR *tow;
6052 HANDLE sh;
6053 WIN32_STREAM_ID sid;
6054 int headersize;
6055 WCHAR streamname[_MAX_PATH];
6056 DWORD readcount;
6057 void *context = NULL;
6058 DWORD lo, hi;
6059 int len;
6060
6061 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006062 fromw = enc_to_utf16(from, NULL);
6063 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006064 if (fromw != NULL && tow != NULL)
6065 {
6066 /* Open the file for reading. */
6067 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6068 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6069 if (sh != INVALID_HANDLE_VALUE)
6070 {
6071 /* Use BackupRead() to find the info streams. Repeat until we
6072 * have done them all.*/
6073 for (;;)
6074 {
6075 /* Get the header to find the length of the stream name. If
6076 * the "readcount" is zero we have done all info streams. */
6077 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006078 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006079 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6080 &readcount, FALSE, FALSE, &context)
6081 || readcount == 0)
6082 break;
6083
6084 /* We only deal with streams that have a name. The normal
6085 * file data appears to be without a name, even though docs
6086 * suggest it is called "::$DATA". */
6087 if (sid.dwStreamNameSize > 0)
6088 {
6089 /* Read the stream name. */
6090 if (!BackupRead(sh, (LPBYTE)streamname,
6091 sid.dwStreamNameSize,
6092 &readcount, FALSE, FALSE, &context))
6093 break;
6094
6095 /* Copy an info stream with a name ":anything:$DATA".
6096 * Skip "::$DATA", it has no stream name (examples suggest
6097 * it might be used for the normal file contents).
6098 * Note that BackupRead() counts bytes, but the name is in
6099 * wide characters. */
6100 len = readcount / sizeof(WCHAR);
6101 streamname[len] = 0;
6102 if (len > 7 && wcsicmp(streamname + len - 6,
6103 L":$DATA") == 0)
6104 {
6105 streamname[len - 6] = 0;
6106 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006107 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006108 }
6109 }
6110
6111 /* Advance to the next stream. We might try seeking too far,
6112 * but BackupSeek() doesn't skip over stream borders, thus
6113 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006114 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006115 &lo, &hi, &context);
6116 }
6117
6118 /* Clear the context. */
6119 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6120
6121 CloseHandle(sh);
6122 }
6123 }
6124 vim_free(fromw);
6125 vim_free(tow);
6126}
6127#endif
6128
6129/*
6130 * Copy file attributes from file "from" to file "to".
6131 * For Windows NT and later we copy info streams.
6132 * Always returns zero, errors are ignored.
6133 */
6134 int
6135mch_copy_file_attribute(char_u *from, char_u *to)
6136{
6137#ifdef FEAT_MBYTE
6138 /* File streams only work on Windows NT and later. */
6139 PlatformId();
6140 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
6141 copy_infostreams(from, to);
6142#endif
6143 return 0;
6144}
6145
6146#if defined(MYRESETSTKOFLW) || defined(PROTO)
6147/*
6148 * Recreate a destroyed stack guard page in win32.
6149 * Written by Benjamin Peterson.
6150 */
6151
6152/* These magic numbers are from the MS header files */
6153#define MIN_STACK_WIN9X 17
6154#define MIN_STACK_WINNT 2
6155
6156/*
6157 * This function does the same thing as _resetstkoflw(), which is only
6158 * available in DevStudio .net and later.
6159 * Returns 0 for failure, 1 for success.
6160 */
6161 int
6162myresetstkoflw(void)
6163{
6164 BYTE *pStackPtr;
6165 BYTE *pGuardPage;
6166 BYTE *pStackBase;
6167 BYTE *pLowestPossiblePage;
6168 MEMORY_BASIC_INFORMATION mbi;
6169 SYSTEM_INFO si;
6170 DWORD nPageSize;
6171 DWORD dummy;
6172
6173 /* This code will not work on win32s. */
6174 PlatformId();
6175 if (g_PlatformId == VER_PLATFORM_WIN32s)
6176 return 0;
6177
6178 /* We need to know the system page size. */
6179 GetSystemInfo(&si);
6180 nPageSize = si.dwPageSize;
6181
6182 /* ...and the current stack pointer */
6183 pStackPtr = (BYTE*)_alloca(1);
6184
6185 /* ...and the base of the stack. */
6186 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6187 return 0;
6188 pStackBase = (BYTE*)mbi.AllocationBase;
6189
6190 /* ...and the page thats min_stack_req pages away from stack base; this is
6191 * the lowest page we could use. */
6192 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6193 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6194
6195 /* On Win95, we want the next page down from the end of the stack. */
6196 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6197 {
6198 /* Find the page that's only 1 page down from the page that the stack
6199 * ptr is in. */
6200 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6201 / (DWORD)nPageSize) - 1));
6202 if (pGuardPage < pLowestPossiblePage)
6203 return 0;
6204
6205 /* Apply the noaccess attribute to the page -- there's no guard
6206 * attribute in win95-type OSes. */
6207 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6208 return 0;
6209 }
6210 else
6211 {
6212 /* On NT, however, we want the first committed page in the stack Start
6213 * at the stack base and move forward through memory until we find a
6214 * committed block. */
6215 BYTE *pBlock = pStackBase;
6216
Bram Moolenaara466c992005-07-09 21:03:22 +00006217 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218 {
6219 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6220 return 0;
6221
6222 pBlock += mbi.RegionSize;
6223
6224 if (mbi.State & MEM_COMMIT)
6225 break;
6226 }
6227
6228 /* mbi now describes the first committed block in the stack. */
6229 if (mbi.Protect & PAGE_GUARD)
6230 return 1;
6231
6232 /* decide where the guard page should start */
6233 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6234 pGuardPage = pLowestPossiblePage;
6235 else
6236 pGuardPage = (BYTE*)mbi.BaseAddress;
6237
6238 /* allocate the guard page */
6239 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6240 return 0;
6241
6242 /* apply the guard attribute to the page */
6243 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6244 &dummy))
6245 return 0;
6246 }
6247
6248 return 1;
6249}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006250#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006252
6253#if defined(FEAT_MBYTE) || defined(PROTO)
6254/*
6255 * The command line arguments in UCS2
6256 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006257static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006258static LPWSTR *ArglistW = NULL;
6259static int global_argc = 0;
6260static char **global_argv;
6261
6262static int used_file_argc = 0; /* last argument in global_argv[] used
6263 for the argument list. */
6264static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6265 command line arguments added to
6266 the argument list */
6267static int used_file_count = 0; /* nr of entries in used_file_indexes */
6268static int used_file_literal = FALSE; /* take file names literally */
6269static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006270static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006271static int used_alist_count = 0;
6272
6273
6274/*
6275 * Get the command line arguments. Unicode version.
6276 * Returns argc. Zero when something fails.
6277 */
6278 int
6279get_cmd_argsW(char ***argvp)
6280{
6281 char **argv = NULL;
6282 int argc = 0;
6283 int i;
6284
6285 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6286 if (ArglistW != NULL)
6287 {
6288 argv = malloc((nArgsW + 1) * sizeof(char *));
6289 if (argv != NULL)
6290 {
6291 argc = nArgsW;
6292 argv[argc] = NULL;
6293 for (i = 0; i < argc; ++i)
6294 {
6295 int len;
6296
6297 /* Convert each Unicode argument to the current codepage. */
6298 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006299 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006300 (LPSTR *)&argv[i], &len, 0, 0);
6301 if (argv[i] == NULL)
6302 {
6303 /* Out of memory, clear everything. */
6304 while (i > 0)
6305 free(argv[--i]);
6306 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01006307 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006308 argc = 0;
6309 }
6310 }
6311 }
6312 }
6313
6314 global_argc = argc;
6315 global_argv = argv;
6316 if (argc > 0)
6317 used_file_indexes = malloc(argc * sizeof(int));
6318
6319 if (argvp != NULL)
6320 *argvp = argv;
6321 return argc;
6322}
6323
6324 void
6325free_cmd_argsW(void)
6326{
6327 if (ArglistW != NULL)
6328 {
6329 GlobalFree(ArglistW);
6330 ArglistW = NULL;
6331 }
6332}
6333
6334/*
6335 * Remember "name" is an argument that was added to the argument list.
6336 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6337 * is called.
6338 */
6339 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006340used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006341{
6342 int i;
6343
6344 if (used_file_indexes == NULL)
6345 return;
6346 for (i = used_file_argc + 1; i < global_argc; ++i)
6347 if (STRCMP(global_argv[i], name) == 0)
6348 {
6349 used_file_argc = i;
6350 used_file_indexes[used_file_count++] = i;
6351 break;
6352 }
6353 used_file_literal = literal;
6354 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006355 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006356}
6357
6358/*
6359 * Remember the length of the argument list as it was. If it changes then we
6360 * leave it alone when 'encoding' is set.
6361 */
6362 void
6363set_alist_count(void)
6364{
6365 used_alist_count = GARGCOUNT;
6366}
6367
6368/*
6369 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6370 * has been changed while starting up. Use the UCS-2 command line arguments
6371 * and convert them to 'encoding'.
6372 */
6373 void
6374fix_arg_enc(void)
6375{
6376 int i;
6377 int idx;
6378 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006379 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006380
6381 /* Safety checks:
6382 * - if argument count differs between the wide and non-wide argument
6383 * list, something must be wrong.
6384 * - the file name arguments must have been located.
6385 * - the length of the argument list wasn't changed by the user.
6386 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006387 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006388 || ArglistW == NULL
6389 || used_file_indexes == NULL
6390 || used_file_count == 0
6391 || used_alist_count != GARGCOUNT)
6392 return;
6393
Bram Moolenaar86b68352004-12-27 21:59:20 +00006394 /* Remember the buffer numbers for the arguments. */
6395 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6396 if (fnum_list == NULL)
6397 return; /* out of memory */
6398 for (i = 0; i < GARGCOUNT; ++i)
6399 fnum_list[i] = GARGLIST[i].ae_fnum;
6400
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006401 /* Clear the argument list. Make room for the new arguments. */
6402 alist_clear(&global_alist);
6403 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006404 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006405
6406 for (i = 0; i < used_file_count; ++i)
6407 {
6408 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006409 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006410 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006411 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006412#ifdef FEAT_DIFF
6413 /* When using diff mode may need to concatenate file name to
6414 * directory name. Just like it's done in main(). */
6415 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6416 && !mch_isdir(alist_name(&GARGLIST[0])))
6417 {
6418 char_u *r;
6419
6420 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6421 if (r != NULL)
6422 {
6423 vim_free(str);
6424 str = r;
6425 }
6426 }
6427#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006428 /* Re-use the old buffer by renaming it. When not using literal
6429 * names it's done by alist_expand() below. */
6430 if (used_file_literal)
6431 buf_set_name(fnum_list[i], str);
6432
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006433 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006434 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006435 }
6436
6437 if (!used_file_literal)
6438 {
6439 /* Now expand wildcards in the arguments. */
6440 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6441 * filename characters but are excluded from 'isfname' to make
6442 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6443 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006444 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006445 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6446 }
6447
6448 /* If wildcard expansion failed, we are editing the first file of the
6449 * arglist and there is no file name: Edit the first argument now. */
6450 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6451 {
6452 do_cmdline_cmd((char_u *)":rewind");
6453 if (GARGCOUNT == 1 && used_file_full_path)
6454 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6455 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006456
6457 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006458}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006459#endif