blob: 33a72565aac712784ebf443dc1f8b09cd4f2dd89 [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
Bram Moolenaar12b559e2013-06-12 22:41:37 +020081/*
82 * Reparse Point
83 */
84#ifndef FILE_ATTRIBUTE_REPARSE_POINT
85# define FILE_ATTRIBUTE_REPARSE_POINT 0x00000400
86#endif
87#ifndef IO_REPARSE_TAG_SYMLINK
88# define IO_REPARSE_TAG_SYMLINK 0xA000000C
89#endif
90
Bram Moolenaar071d4272004-06-13 20:20:40 +000091/* Record all output and all keyboard & mouse input */
92/* #define MCH_WRITE_DUMP */
93
94#ifdef MCH_WRITE_DUMP
95FILE* fdDump = NULL;
96#endif
97
98/*
99 * When generating prototypes for Win32 on Unix, these lines make the syntax
100 * errors disappear. They do not need to be correct.
101 */
102#ifdef PROTO
103#define WINAPI
104#define WINBASEAPI
105typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000106typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000107typedef int ACCESS_MASK;
108typedef int BOOL;
109typedef int COLORREF;
110typedef int CONSOLE_CURSOR_INFO;
111typedef int COORD;
112typedef int DWORD;
113typedef int HANDLE;
114typedef int HDC;
115typedef int HFONT;
116typedef int HICON;
117typedef int HINSTANCE;
118typedef int HWND;
119typedef int INPUT_RECORD;
120typedef int KEY_EVENT_RECORD;
121typedef int LOGFONT;
122typedef int LPBOOL;
123typedef int LPCTSTR;
124typedef int LPDWORD;
125typedef int LPSTR;
126typedef int LPTSTR;
127typedef int LPVOID;
128typedef int MOUSE_EVENT_RECORD;
129typedef int PACL;
130typedef int PDWORD;
131typedef int PHANDLE;
132typedef int PRINTDLG;
133typedef int PSECURITY_DESCRIPTOR;
134typedef int PSID;
135typedef int SECURITY_INFORMATION;
136typedef int SHORT;
137typedef int SMALL_RECT;
138typedef int TEXTMETRIC;
139typedef int TOKEN_INFORMATION_CLASS;
140typedef int TRUSTEE;
141typedef int WORD;
142typedef int WCHAR;
143typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100144typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200145typedef int SE_OBJECT_TYPE;
146typedef int PSNSECINFO;
147typedef int PSNSECINFOW;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148#endif
149
150#ifndef FEAT_GUI_W32
151/* Undocumented API in kernel32.dll needed to work around dead key bug in
152 * console-mode applications in NT 4.0. If you switch keyboard layouts
153 * in a console app to a layout that includes dead keys and then hit a
154 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
155 * and Michael Dietrich for helping me figure out this workaround.
156 */
157
158/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
159#ifndef WINBASEAPI
160# define WINBASEAPI __stdcall
161#endif
162#if defined(__BORLANDC__)
163typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
164#else
165typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
166#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000167static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000168#endif
169
170#if defined(__BORLANDC__)
171/* Strangely Borland uses a non-standard name. */
172# define wcsicmp(a, b) wcscmpi((a), (b))
173#endif
174
Bram Moolenaar82881492012-11-20 16:53:39 +0100175#ifndef PROTO
176
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200177/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200178#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100179LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200180BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
181BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
182BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
183#endif
184
Bram Moolenaar82881492012-11-20 16:53:39 +0100185#endif /* PROTO */
186
Bram Moolenaar071d4272004-06-13 20:20:40 +0000187#ifndef FEAT_GUI_W32
188/* Win32 Console handles for input and output */
189static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
190static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
191
192/* Win32 Screen buffer,coordinate,console I/O information */
193static SMALL_RECT g_srScrollRegion;
194static COORD g_coord; /* 0-based, but external coords are 1-based */
195
196/* The attribute of the screen when the editor was started */
197static WORD g_attrDefault = 7; /* lightgray text on black background */
198static WORD g_attrCurrent;
199
200static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
201static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
202static int g_fForceExit = FALSE; /* set when forcefully exiting */
203
204static void termcap_mode_start(void);
205static void termcap_mode_end(void);
206static void clear_chars(COORD coord, DWORD n);
207static void clear_screen(void);
208static void clear_to_end_of_display(void);
209static void clear_to_end_of_line(void);
210static void scroll(unsigned cLines);
211static void set_scroll_region(unsigned left, unsigned top,
212 unsigned right, unsigned bottom);
213static void insert_lines(unsigned cLines);
214static void delete_lines(unsigned cLines);
215static void gotoxy(unsigned x, unsigned y);
216static void normvideo(void);
217static void textattr(WORD wAttr);
218static void textcolor(WORD wAttr);
219static void textbackground(WORD wAttr);
220static void standout(void);
221static void standend(void);
222static void visual_bell(void);
223static void cursor_visible(BOOL fVisible);
224static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
225static char_u tgetch(int *pmodifiers, char_u *pch2);
226static void create_conin(void);
227static int s_cursor_visible = TRUE;
228static int did_create_conin = FALSE;
229#else
230static int s_dont_use_vimrun = TRUE;
231static int need_vimrun_warning = FALSE;
232static char *vimrun_path = "vimrun ";
233#endif
234
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200235static int win32_getattrs(char_u *name);
236static int win32_setattrs(char_u *name, int attrs);
237static int win32_set_archive(char_u *name);
238
Bram Moolenaar071d4272004-06-13 20:20:40 +0000239#ifndef FEAT_GUI_W32
240static int suppress_winsize = 1; /* don't fiddle with console */
241#endif
242
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200243static char_u *exe_path = NULL;
244
Bram Moolenaar071d4272004-06-13 20:20:40 +0000245 static void
246get_exe_name(void)
247{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100248 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
249 * as the maximum length that works (plus a NUL byte). */
250#define MAX_ENV_PATH_LEN 8192
251 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200252 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000253
254 if (exe_name == NULL)
255 {
256 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100257 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000258 if (*temp != NUL)
259 exe_name = FullName_save((char_u *)temp, FALSE);
260 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000261
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200262 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000263 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200264 exe_path = vim_strnsave(exe_name,
265 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200266 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000267 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200268 /* Append our starting directory to $PATH, so that when doing
269 * "!xxd" it's found in our starting directory. Needed because
270 * SearchPath() also looks there. */
271 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100272 if (p == NULL
273 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200274 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100275 if (p == NULL || *p == NUL)
276 temp[0] = NUL;
277 else
278 {
279 STRCPY(temp, p);
280 STRCAT(temp, ";");
281 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200282 STRCAT(temp, exe_path);
283 vim_setenv((char_u *)"PATH", temp);
284 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000285 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287}
288
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200289/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100290 * Unescape characters in "p" that appear in "escaped".
291 */
292 static void
293unescape_shellxquote(char_u *p, char_u *escaped)
294{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100295 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100296 int n;
297
298 while (*p != NUL)
299 {
300 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
301 mch_memmove(p, p + 1, l--);
302#ifdef FEAT_MBYTE
303 n = (*mb_ptr2len)(p);
304#else
305 n = 1;
306#endif
307 p += n;
308 l -= n;
309 }
310}
311
312/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200313 * Load library "name".
314 */
315 HINSTANCE
316vimLoadLib(char *name)
317{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200318 HINSTANCE dll = NULL;
319 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200320
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200321 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
322 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200323 if (exe_path == NULL)
324 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200325 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200326 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200327#ifdef FEAT_MBYTE
328 WCHAR old_dirw[MAXPATHL];
329
330 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
331 {
332 /* Change directory to where the executable is, both to make
333 * sure we find a .dll there and to avoid looking for a .dll
334 * in the current directory. */
335 SetCurrentDirectory(exe_path);
336 dll = LoadLibrary(name);
337 SetCurrentDirectoryW(old_dirw);
338 return dll;
339 }
340 /* Retry with non-wide function (for Windows 98). */
341 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
342#endif
343 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
344 {
345 /* Change directory to where the executable is, both to make
346 * sure we find a .dll there and to avoid looking for a .dll
347 * in the current directory. */
348 SetCurrentDirectory(exe_path);
349 dll = LoadLibrary(name);
350 SetCurrentDirectory(old_dir);
351 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200352 }
353 return dll;
354}
355
Bram Moolenaar071d4272004-06-13 20:20:40 +0000356#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
357# ifndef GETTEXT_DLL
358# define GETTEXT_DLL "libintl.dll"
359# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200360/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000361static char *null_libintl_gettext(const char *);
362static char *null_libintl_textdomain(const char *);
363static char *null_libintl_bindtextdomain(const char *, const char *);
364static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200366static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000367char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
368char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
369char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000370 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000371char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
372 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373
374 int
375dyn_libintl_init(char *libname)
376{
377 int i;
378 static struct
379 {
380 char *name;
381 FARPROC *ptr;
382 } libintl_entry[] =
383 {
384 {"gettext", (FARPROC*)&dyn_libintl_gettext},
385 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
386 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
387 {NULL, NULL}
388 };
389
390 /* No need to initialize twice. */
391 if (hLibintlDLL)
392 return 1;
393 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200394 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000395 if (!hLibintlDLL)
396 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200397 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000398 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200399 verbose_enter();
400 EMSG2(_(e_loadlib), GETTEXT_DLL);
401 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000402 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200403 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 }
405 for (i = 0; libintl_entry[i].name != NULL
406 && libintl_entry[i].ptr != NULL; ++i)
407 {
408 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
409 libintl_entry[i].name)) == NULL)
410 {
411 dyn_libintl_end();
412 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000413 {
414 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000415 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000416 verbose_leave();
417 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 return 0;
419 }
420 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000421
422 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000423 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000424 "bind_textdomain_codeset");
425 if (dyn_libintl_bind_textdomain_codeset == NULL)
426 dyn_libintl_bind_textdomain_codeset =
427 null_libintl_bind_textdomain_codeset;
428
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429 return 1;
430}
431
432 void
433dyn_libintl_end()
434{
435 if (hLibintlDLL)
436 FreeLibrary(hLibintlDLL);
437 hLibintlDLL = NULL;
438 dyn_libintl_gettext = null_libintl_gettext;
439 dyn_libintl_textdomain = null_libintl_textdomain;
440 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000441 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442}
443
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000444/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000446null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447{
448 return (char*)msgid;
449}
450
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000451/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000453null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000454{
455 return NULL;
456}
457
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000458/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000460null_libintl_bind_textdomain_codeset(const char *domainname,
461 const char *codeset)
462{
463 return NULL;
464}
465
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000466/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000467 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000468null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000469{
470 return NULL;
471}
472
473#endif /* DYNAMIC_GETTEXT */
474
475/* This symbol is not defined in older versions of the SDK or Visual C++ */
476
477#ifndef VER_PLATFORM_WIN32_WINDOWS
478# define VER_PLATFORM_WIN32_WINDOWS 1
479#endif
480
481DWORD g_PlatformId;
482
483#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100484# ifndef PROTO
485# include <aclapi.h>
486# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200487# ifndef PROTECTED_DACL_SECURITY_INFORMATION
488# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
489# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100490
Bram Moolenaar071d4272004-06-13 20:20:40 +0000491/*
492 * These are needed to dynamically load the ADVAPI DLL, which is not
493 * implemented under Windows 95 (and causes VIM to crash)
494 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200495typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000496 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200497typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
499 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200500# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200501typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200502 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200503typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200504 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
505 PSECURITY_DESCRIPTOR *);
506# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507
508static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
509static PSNSECINFO pSetNamedSecurityInfo;
510static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200511# ifdef FEAT_MBYTE
512static PSNSECINFOW pSetNamedSecurityInfoW;
513static PGNSECINFOW pGetNamedSecurityInfoW;
514# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515#endif
516
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200517typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
518
519static BOOL allowPiping = FALSE;
520static PSETHANDLEINFORMATION pSetHandleInformation;
521
Bram Moolenaar27515922013-06-29 15:36:26 +0200522#ifdef HAVE_ACL
523/*
524 * Enables or disables the specified privilege.
525 */
526 static BOOL
527win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
528{
529 BOOL bResult;
530 LUID luid;
531 HANDLE hToken;
532 TOKEN_PRIVILEGES tokenPrivileges;
533
534 if (!OpenProcessToken(GetCurrentProcess(),
535 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
536 return FALSE;
537
538 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
539 {
540 CloseHandle(hToken);
541 return FALSE;
542 }
543
544 tokenPrivileges.PrivilegeCount = 1;
545 tokenPrivileges.Privileges[0].Luid = luid;
546 tokenPrivileges.Privileges[0].Attributes = bEnable ?
547 SE_PRIVILEGE_ENABLED : 0;
548
549 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
550 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
551
552 CloseHandle(hToken);
553
554 return bResult && GetLastError() == ERROR_SUCCESS;
555}
556#endif
557
Bram Moolenaar071d4272004-06-13 20:20:40 +0000558/*
559 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
560 * VER_PLATFORM_WIN32_WINDOWS (Win95).
561 */
562 void
563PlatformId(void)
564{
565 static int done = FALSE;
566
567 if (!done)
568 {
569 OSVERSIONINFO ovi;
570
571 ovi.dwOSVersionInfoSize = sizeof(ovi);
572 GetVersionEx(&ovi);
573
574 g_PlatformId = ovi.dwPlatformId;
575
576#ifdef HAVE_ACL
577 /*
578 * Load the ADVAPI runtime if we are on anything
579 * other than Windows 95
580 */
581 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
582 {
583 /*
584 * do this load. Problems: Doesn't unload at end of run (this is
585 * theoretically okay, since Windows should unload it when VIM
586 * terminates). Should we be using the 'mch_libcall' routines?
587 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
588 * time we verify security...
589 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200590 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591 if (advapi_lib != NULL)
592 {
593 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
594 "SetNamedSecurityInfoA");
595 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
596 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200597# ifdef FEAT_MBYTE
598 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
599 "SetNamedSecurityInfoW");
600 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
601 "GetNamedSecurityInfoW");
602# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000603 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200604 || pGetNamedSecurityInfo == NULL
605# ifdef FEAT_MBYTE
606 || pSetNamedSecurityInfoW == NULL
607 || pGetNamedSecurityInfoW == NULL
608# endif
609 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 {
611 /* If we can't get the function addresses, set advapi_lib
612 * to NULL so that we don't use them. */
613 FreeLibrary(advapi_lib);
614 advapi_lib = NULL;
615 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200616 /* Enable privilege for getting or setting SACLs. */
617 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618 }
619 }
620#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200621 /*
622 * If we are on windows NT, try to load the pipe functions, only
623 * available from Win2K.
624 */
625 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
626 {
627 HANDLE kernel32 = GetModuleHandle("kernel32");
628 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
629 kernel32, "SetHandleInformation");
630
631 allowPiping = pSetHandleInformation != NULL;
632 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633 done = TRUE;
634 }
635}
636
637/*
638 * Return TRUE when running on Windows 95 (or 98 or ME).
639 * Only to be used after mch_init().
640 */
641 int
642mch_windows95(void)
643{
644 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
645}
646
647#ifdef FEAT_GUI_W32
648/*
649 * Used to work around the "can't do synchronous spawn"
650 * problem on Win32s, without resorting to Universal Thunk.
651 */
652static int old_num_windows;
653static int num_windows;
654
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000655/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000656 static BOOL CALLBACK
657win32ssynch_cb(HWND hwnd, LPARAM lparam)
658{
659 num_windows++;
660 return TRUE;
661}
662#endif
663
664#ifndef FEAT_GUI_W32
665
666#define SHIFT (SHIFT_PRESSED)
667#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
668#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
669#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
670
671
672/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
673 * We map function keys to their ANSI terminal equivalents, as produced
674 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
675 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
676 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
677 * combinations of function/arrow/etc keys.
678 */
679
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000680static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000681{
682 WORD wVirtKey;
683 BOOL fAnsiKey;
684 int chAlone;
685 int chShift;
686 int chCtrl;
687 int chAlt;
688} VirtKeyMap[] =
689{
690
691/* Key ANSI alone shift ctrl alt */
692 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
693
694 { VK_F1, TRUE, ';', 'T', '^', 'h', },
695 { VK_F2, TRUE, '<', 'U', '_', 'i', },
696 { VK_F3, TRUE, '=', 'V', '`', 'j', },
697 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
698 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
699 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
700 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
701 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
702 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
703 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
704 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
705 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
706
707 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
708 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
709 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
710 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
711 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
712 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
713 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
714 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
715 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
716 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
717
718 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
719
720#if 0
721 /* Most people don't have F13-F20, but what the hell... */
722 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
723 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
724 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
725 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
726 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
727 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
728 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
729 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
730#endif
731 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
732 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
733 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
734 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
735
736 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
737 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
738 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
739 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
740 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
741 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
742 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
743 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
744 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
745 /* Sorry, out of number space! <negri>*/
746 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
747
748};
749
750
751#ifdef _MSC_VER
752// The ToAscii bug destroys several registers. Need to turn off optimization
753// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000754# pragma warning(push)
755# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000756# pragma optimize("", off)
757#endif
758
759#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
760# define AChar AsciiChar
761#else
762# define AChar uChar.AsciiChar
763#endif
764
765/* The return code indicates key code size. */
766 static int
767#ifdef __BORLANDC__
768 __stdcall
769#endif
770win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000771 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772{
773 UINT uMods = pker->dwControlKeyState;
774 static int s_iIsDead = 0;
775 static WORD awAnsiCode[2];
776 static BYTE abKeystate[256];
777
778
779 if (s_iIsDead == 2)
780 {
781 pker->AChar = (CHAR) awAnsiCode[1];
782 s_iIsDead = 0;
783 return 1;
784 }
785
786 if (pker->AChar != 0)
787 return 1;
788
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200789 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000790
791 // Should only be non-NULL on NT 4.0
792 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
793 {
794 CHAR szKLID[KL_NAMELENGTH];
795
796 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
797 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
798 }
799
800 /* Clear any pending dead keys */
801 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
802
803 if (uMods & SHIFT_PRESSED)
804 abKeystate[VK_SHIFT] = 0x80;
805 if (uMods & CAPSLOCK_ON)
806 abKeystate[VK_CAPITAL] = 1;
807
808 if ((uMods & ALT_GR) == ALT_GR)
809 {
810 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
811 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
812 }
813
814 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
815 abKeystate, awAnsiCode, 0);
816
817 if (s_iIsDead > 0)
818 pker->AChar = (CHAR) awAnsiCode[0];
819
820 return s_iIsDead;
821}
822
823#ifdef _MSC_VER
824/* MUST switch optimization on again here, otherwise a call to
825 * decode_key_event() may crash (e.g. when hitting caps-lock) */
826# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000827# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000828
829# if (_MSC_VER < 1100)
830/* MUST turn off global optimisation for this next function, or
831 * pressing ctrl-minus in insert mode crashes Vim when built with
832 * VC4.1. -- negri. */
833# pragma optimize("g", off)
834# endif
835#endif
836
837static BOOL g_fJustGotFocus = FALSE;
838
839/*
840 * Decode a KEY_EVENT into one or two keystrokes
841 */
842 static BOOL
843decode_key_event(
844 KEY_EVENT_RECORD *pker,
845 char_u *pch,
846 char_u *pch2,
847 int *pmodifiers,
848 BOOL fDoPost)
849{
850 int i;
851 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
852
853 *pch = *pch2 = NUL;
854 g_fJustGotFocus = FALSE;
855
856 /* ignore key up events */
857 if (!pker->bKeyDown)
858 return FALSE;
859
860 /* ignore some keystrokes */
861 switch (pker->wVirtualKeyCode)
862 {
863 /* modifiers */
864 case VK_SHIFT:
865 case VK_CONTROL:
866 case VK_MENU: /* Alt key */
867 return FALSE;
868
869 default:
870 break;
871 }
872
873 /* special cases */
874 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
875 {
876 /* Ctrl-6 is Ctrl-^ */
877 if (pker->wVirtualKeyCode == '6')
878 {
879 *pch = Ctrl_HAT;
880 return TRUE;
881 }
882 /* Ctrl-2 is Ctrl-@ */
883 else if (pker->wVirtualKeyCode == '2')
884 {
885 *pch = NUL;
886 return TRUE;
887 }
888 /* Ctrl-- is Ctrl-_ */
889 else if (pker->wVirtualKeyCode == 0xBD)
890 {
891 *pch = Ctrl__;
892 return TRUE;
893 }
894 }
895
896 /* Shift-TAB */
897 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
898 {
899 *pch = K_NUL;
900 *pch2 = '\017';
901 return TRUE;
902 }
903
904 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
905 {
906 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
907 {
908 if (nModifs == 0)
909 *pch = VirtKeyMap[i].chAlone;
910 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
911 *pch = VirtKeyMap[i].chShift;
912 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
913 *pch = VirtKeyMap[i].chCtrl;
914 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
915 *pch = VirtKeyMap[i].chAlt;
916
917 if (*pch != 0)
918 {
919 if (VirtKeyMap[i].fAnsiKey)
920 {
921 *pch2 = *pch;
922 *pch = K_NUL;
923 }
924
925 return TRUE;
926 }
927 }
928 }
929
930 i = win32_kbd_patch_key(pker);
931
932 if (i < 0)
933 *pch = NUL;
934 else
935 {
936 *pch = (i > 0) ? pker->AChar : NUL;
937
938 if (pmodifiers != NULL)
939 {
940 /* Pass on the ALT key as a modifier, but only when not combined
941 * with CTRL (which is ALTGR). */
942 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
943 *pmodifiers |= MOD_MASK_ALT;
944
945 /* Pass on SHIFT only for special keys, because we don't know when
946 * it's already included with the character. */
947 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
948 *pmodifiers |= MOD_MASK_SHIFT;
949
950 /* Pass on CTRL only for non-special keys, because we don't know
951 * when it's already included with the character. And not when
952 * combined with ALT (which is ALTGR). */
953 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
954 && *pch >= 0x20 && *pch < 0x80)
955 *pmodifiers |= MOD_MASK_CTRL;
956 }
957 }
958
959 return (*pch != NUL);
960}
961
962#ifdef _MSC_VER
963# pragma optimize("", on)
964#endif
965
966#endif /* FEAT_GUI_W32 */
967
968
969#ifdef FEAT_MOUSE
970
971/*
972 * For the GUI the mouse handling is in gui_w32.c.
973 */
974# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000975/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000977mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000978{
979}
980# else
981static int g_fMouseAvail = FALSE; /* mouse present */
982static int g_fMouseActive = FALSE; /* mouse enabled */
983static int g_nMouseClick = -1; /* mouse status */
984static int g_xMouse; /* mouse x coordinate */
985static int g_yMouse; /* mouse y coordinate */
986
987/*
988 * Enable or disable mouse input
989 */
990 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000991mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000992{
993 DWORD cmodein;
994
995 if (!g_fMouseAvail)
996 return;
997
998 g_fMouseActive = on;
999 GetConsoleMode(g_hConIn, &cmodein);
1000
1001 if (g_fMouseActive)
1002 cmodein |= ENABLE_MOUSE_INPUT;
1003 else
1004 cmodein &= ~ENABLE_MOUSE_INPUT;
1005
1006 SetConsoleMode(g_hConIn, cmodein);
1007}
1008
1009
1010/*
1011 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1012 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1013 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1014 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1015 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1016 * and we return the mouse position in g_xMouse and g_yMouse.
1017 *
1018 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1019 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1020 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1021 *
1022 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1023 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1024 *
1025 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1026 * moves, even if it stays within the same character cell. We ignore
1027 * all MOUSE_MOVED messages if the position hasn't really changed, and
1028 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1029 * we're only interested in MOUSE_DRAG).
1030 *
1031 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1032 * 2-button mouses by pressing the left & right buttons simultaneously.
1033 * In practice, it's almost impossible to click both at the same time,
1034 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1035 * in such cases, if the user is clicking quickly.
1036 */
1037 static BOOL
1038decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001039 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040{
1041 static int s_nOldButton = -1;
1042 static int s_nOldMouseClick = -1;
1043 static int s_xOldMouse = -1;
1044 static int s_yOldMouse = -1;
1045 static linenr_T s_old_topline = 0;
1046#ifdef FEAT_DIFF
1047 static int s_old_topfill = 0;
1048#endif
1049 static int s_cClicks = 1;
1050 static BOOL s_fReleased = TRUE;
1051 static DWORD s_dwLastClickTime = 0;
1052 static BOOL s_fNextIsMiddle = FALSE;
1053
1054 static DWORD cButtons = 0; /* number of buttons supported */
1055
1056 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1057 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1058 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1059 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1060
1061 int nButton;
1062
1063 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1064 cButtons = 2;
1065
1066 if (!g_fMouseAvail || !g_fMouseActive)
1067 {
1068 g_nMouseClick = -1;
1069 return FALSE;
1070 }
1071
1072 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1073 if (g_fJustGotFocus)
1074 {
1075 g_fJustGotFocus = FALSE;
1076 return FALSE;
1077 }
1078
1079 /* unprocessed mouse click? */
1080 if (g_nMouseClick != -1)
1081 return TRUE;
1082
1083 nButton = -1;
1084 g_xMouse = pmer->dwMousePosition.X;
1085 g_yMouse = pmer->dwMousePosition.Y;
1086
1087 if (pmer->dwEventFlags == MOUSE_MOVED)
1088 {
1089 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1090 * events even when the mouse moves only within a char cell.) */
1091 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1092 return FALSE;
1093 }
1094
1095 /* If no buttons are pressed... */
1096 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1097 {
1098 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1099 if (s_fReleased)
1100 return FALSE;
1101
1102 nButton = MOUSE_RELEASE;
1103 s_fReleased = TRUE;
1104 }
1105 else /* one or more buttons pressed */
1106 {
1107 /* on a 2-button mouse, hold down left and right buttons
1108 * simultaneously to get MIDDLE. */
1109
1110 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1111 {
1112 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1113
1114 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001115 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116 if (dwLR == LEFT || dwLR == RIGHT)
1117 {
1118 for (;;)
1119 {
1120 /* wait a short time for next input event */
1121 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1122 != WAIT_OBJECT_0)
1123 break;
1124 else
1125 {
1126 DWORD cRecords = 0;
1127 INPUT_RECORD ir;
1128 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1129
1130 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1131
1132 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1133 || !(pmer2->dwButtonState & LEFT_RIGHT))
1134 break;
1135 else
1136 {
1137 if (pmer2->dwEventFlags != MOUSE_MOVED)
1138 {
1139 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1140
1141 return decode_mouse_event(pmer2);
1142 }
1143 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1144 s_yOldMouse == pmer2->dwMousePosition.Y)
1145 {
1146 /* throw away spurious mouse move */
1147 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1148
1149 /* are there any more mouse events in queue? */
1150 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1151
1152 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1153 break;
1154 }
1155 else
1156 break;
1157 }
1158 }
1159 }
1160 }
1161 }
1162
1163 if (s_fNextIsMiddle)
1164 {
1165 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1166 ? MOUSE_DRAG : MOUSE_MIDDLE;
1167 s_fNextIsMiddle = FALSE;
1168 }
1169 else if (cButtons == 2 &&
1170 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1171 {
1172 nButton = MOUSE_MIDDLE;
1173
1174 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1175 {
1176 s_fNextIsMiddle = TRUE;
1177 nButton = MOUSE_RELEASE;
1178 }
1179 }
1180 else if ((pmer->dwButtonState & LEFT) == LEFT)
1181 nButton = MOUSE_LEFT;
1182 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1183 nButton = MOUSE_MIDDLE;
1184 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1185 nButton = MOUSE_RIGHT;
1186
1187 if (! s_fReleased && ! s_fNextIsMiddle
1188 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1189 return FALSE;
1190
1191 s_fReleased = s_fNextIsMiddle;
1192 }
1193
1194 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1195 {
1196 /* button pressed or released, without mouse moving */
1197 if (nButton != -1 && nButton != MOUSE_RELEASE)
1198 {
1199 DWORD dwCurrentTime = GetTickCount();
1200
1201 if (s_xOldMouse != g_xMouse
1202 || s_yOldMouse != g_yMouse
1203 || s_nOldButton != nButton
1204 || s_old_topline != curwin->w_topline
1205#ifdef FEAT_DIFF
1206 || s_old_topfill != curwin->w_topfill
1207#endif
1208 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1209 {
1210 s_cClicks = 1;
1211 }
1212 else if (++s_cClicks > 4)
1213 {
1214 s_cClicks = 1;
1215 }
1216
1217 s_dwLastClickTime = dwCurrentTime;
1218 }
1219 }
1220 else if (pmer->dwEventFlags == MOUSE_MOVED)
1221 {
1222 if (nButton != -1 && nButton != MOUSE_RELEASE)
1223 nButton = MOUSE_DRAG;
1224
1225 s_cClicks = 1;
1226 }
1227
1228 if (nButton == -1)
1229 return FALSE;
1230
1231 if (nButton != MOUSE_RELEASE)
1232 s_nOldButton = nButton;
1233
1234 g_nMouseClick = nButton;
1235
1236 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1237 g_nMouseClick |= MOUSE_SHIFT;
1238 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1239 g_nMouseClick |= MOUSE_CTRL;
1240 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1241 g_nMouseClick |= MOUSE_ALT;
1242
1243 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1244 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1245
1246 /* only pass on interesting (i.e., different) mouse events */
1247 if (s_xOldMouse == g_xMouse
1248 && s_yOldMouse == g_yMouse
1249 && s_nOldMouseClick == g_nMouseClick)
1250 {
1251 g_nMouseClick = -1;
1252 return FALSE;
1253 }
1254
1255 s_xOldMouse = g_xMouse;
1256 s_yOldMouse = g_yMouse;
1257 s_old_topline = curwin->w_topline;
1258#ifdef FEAT_DIFF
1259 s_old_topfill = curwin->w_topfill;
1260#endif
1261 s_nOldMouseClick = g_nMouseClick;
1262
1263 return TRUE;
1264}
1265
1266# endif /* FEAT_GUI_W32 */
1267#endif /* FEAT_MOUSE */
1268
1269
1270#ifdef MCH_CURSOR_SHAPE
1271/*
1272 * Set the shape of the cursor.
1273 * 'thickness' can be from 1 (thin) to 99 (block)
1274 */
1275 static void
1276mch_set_cursor_shape(int thickness)
1277{
1278 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1279 ConsoleCursorInfo.dwSize = thickness;
1280 ConsoleCursorInfo.bVisible = s_cursor_visible;
1281
1282 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1283 if (s_cursor_visible)
1284 SetConsoleCursorPosition(g_hConOut, g_coord);
1285}
1286
1287 void
1288mch_update_cursor(void)
1289{
1290 int idx;
1291 int thickness;
1292
1293 /*
1294 * How the cursor is drawn depends on the current mode.
1295 */
1296 idx = get_shape_idx(FALSE);
1297
1298 if (shape_table[idx].shape == SHAPE_BLOCK)
1299 thickness = 99; /* 100 doesn't work on W95 */
1300 else
1301 thickness = shape_table[idx].percentage;
1302 mch_set_cursor_shape(thickness);
1303}
1304#endif
1305
1306#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1307/*
1308 * Handle FOCUS_EVENT.
1309 */
1310 static void
1311handle_focus_event(INPUT_RECORD ir)
1312{
1313 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1314 ui_focus_change((int)g_fJustGotFocus);
1315}
1316
1317/*
1318 * Wait until console input from keyboard or mouse is available,
1319 * or the time is up.
1320 * Return TRUE if something is available FALSE if not.
1321 */
1322 static int
1323WaitForChar(long msec)
1324{
1325 DWORD dwNow = 0, dwEndTime = 0;
1326 INPUT_RECORD ir;
1327 DWORD cRecords;
1328 char_u ch, ch2;
1329
1330 if (msec > 0)
1331 /* Wait until the specified time has elapsed. */
1332 dwEndTime = GetTickCount() + msec;
1333 else if (msec < 0)
1334 /* Wait forever. */
1335 dwEndTime = INFINITE;
1336
1337 /* We need to loop until the end of the time period, because
1338 * we might get multiple unusable mouse events in that time.
1339 */
1340 for (;;)
1341 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001342#ifdef FEAT_MZSCHEME
1343 mzvim_check_threads();
1344#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001345#ifdef FEAT_CLIENTSERVER
1346 serverProcessPendingMessages();
1347#endif
1348 if (0
1349#ifdef FEAT_MOUSE
1350 || g_nMouseClick != -1
1351#endif
1352#ifdef FEAT_CLIENTSERVER
1353 || input_available()
1354#endif
1355 )
1356 return TRUE;
1357
1358 if (msec > 0)
1359 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001360 /* If the specified wait time has passed, return. Beware that
1361 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001362 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001363 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001364 break;
1365 }
1366 if (msec != 0)
1367 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001368 DWORD dwWaitTime = dwEndTime - dwNow;
1369
1370#ifdef FEAT_MZSCHEME
1371 if (mzthreads_allowed() && p_mzq > 0
1372 && (msec < 0 || (long)dwWaitTime > p_mzq))
1373 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1374#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001375#ifdef FEAT_CLIENTSERVER
1376 /* Wait for either an event on the console input or a message in
1377 * the client-server window. */
1378 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001379 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001380#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001381 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001382#endif
1383 continue;
1384 }
1385
1386 cRecords = 0;
1387 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1388
1389#ifdef FEAT_MBYTE_IME
1390 if (State & CMDLINE && msg_row == Rows - 1)
1391 {
1392 CONSOLE_SCREEN_BUFFER_INFO csbi;
1393
1394 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1395 {
1396 if (csbi.dwCursorPosition.Y != msg_row)
1397 {
1398 /* The screen is now messed up, must redraw the
1399 * command line and later all the windows. */
1400 redraw_all_later(CLEAR);
1401 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1402 redrawcmd();
1403 }
1404 }
1405 }
1406#endif
1407
1408 if (cRecords > 0)
1409 {
1410 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1411 {
1412#ifdef FEAT_MBYTE_IME
1413 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1414 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1415 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1416 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1417 {
1418 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1419 continue;
1420 }
1421#endif
1422 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1423 NULL, FALSE))
1424 return TRUE;
1425 }
1426
1427 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1428
1429 if (ir.EventType == FOCUS_EVENT)
1430 handle_focus_event(ir);
1431 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1432 shell_resized();
1433#ifdef FEAT_MOUSE
1434 else if (ir.EventType == MOUSE_EVENT
1435 && decode_mouse_event(&ir.Event.MouseEvent))
1436 return TRUE;
1437#endif
1438 }
1439 else if (msec == 0)
1440 break;
1441 }
1442
1443#ifdef FEAT_CLIENTSERVER
1444 /* Something might have been received while we were waiting. */
1445 if (input_available())
1446 return TRUE;
1447#endif
1448 return FALSE;
1449}
1450
1451#ifndef FEAT_GUI_MSWIN
1452/*
1453 * return non-zero if a character is available
1454 */
1455 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001456mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457{
1458 return WaitForChar(0L);
1459}
1460#endif
1461
1462/*
1463 * Create the console input. Used when reading stdin doesn't work.
1464 */
1465 static void
1466create_conin(void)
1467{
1468 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1469 FILE_SHARE_READ|FILE_SHARE_WRITE,
1470 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001471 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472 did_create_conin = TRUE;
1473}
1474
1475/*
1476 * Get a keystroke or a mouse event
1477 */
1478 static char_u
1479tgetch(int *pmodifiers, char_u *pch2)
1480{
1481 char_u ch;
1482
1483 for (;;)
1484 {
1485 INPUT_RECORD ir;
1486 DWORD cRecords = 0;
1487
1488#ifdef FEAT_CLIENTSERVER
1489 (void)WaitForChar(-1L);
1490 if (input_available())
1491 return 0;
1492# ifdef FEAT_MOUSE
1493 if (g_nMouseClick != -1)
1494 return 0;
1495# endif
1496#endif
1497 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1498 {
1499 if (did_create_conin)
1500 read_error_exit();
1501 create_conin();
1502 continue;
1503 }
1504
1505 if (ir.EventType == KEY_EVENT)
1506 {
1507 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1508 pmodifiers, TRUE))
1509 return ch;
1510 }
1511 else if (ir.EventType == FOCUS_EVENT)
1512 handle_focus_event(ir);
1513 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1514 shell_resized();
1515#ifdef FEAT_MOUSE
1516 else if (ir.EventType == MOUSE_EVENT)
1517 {
1518 if (decode_mouse_event(&ir.Event.MouseEvent))
1519 return 0;
1520 }
1521#endif
1522 }
1523}
1524#endif /* !FEAT_GUI_W32 */
1525
1526
1527/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001528 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529 * Get one or more characters from the keyboard or the mouse.
1530 * If time == 0, do not wait for characters.
1531 * If time == n, wait a short time for characters.
1532 * If time == -1, wait forever for characters.
1533 * Returns the number of characters read into buf.
1534 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001535/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001536 int
1537mch_inchar(
1538 char_u *buf,
1539 int maxlen,
1540 long time,
1541 int tb_change_cnt)
1542{
1543#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1544
1545 int len;
1546 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547#define TYPEAHEADLEN 20
1548 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1549 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001550#ifdef FEAT_MBYTE
1551 static char_u *rest = NULL; /* unconverted rest of previous read */
1552 static int restlen = 0;
1553 int unconverted;
1554#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555
1556 /* First use any typeahead that was kept because "buf" was too small. */
1557 if (typeaheadlen > 0)
1558 goto theend;
1559
1560#ifdef FEAT_SNIFF
1561 if (want_sniff_request)
1562 {
1563 if (sniff_request_waiting)
1564 {
1565 /* return K_SNIFF */
1566 typeahead[typeaheadlen++] = CSI;
1567 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1568 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1569 sniff_request_waiting = 0;
1570 want_sniff_request = 0;
1571 goto theend;
1572 }
1573 else if (time < 0 || time > 250)
1574 {
1575 /* don't wait too long, a request might be pending */
1576 time = 250;
1577 }
1578 }
1579#endif
1580
1581 if (time >= 0)
1582 {
1583 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001584 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001585 }
1586 else /* time == -1, wait forever */
1587 {
1588 mch_set_winsize_now(); /* Allow winsize changes from now on */
1589
Bram Moolenaar3918c952005-03-15 22:34:55 +00001590 /*
1591 * If there is no character available within 2 seconds (default)
1592 * write the autoscript file to disk. Or cause the CursorHold event
1593 * to be triggered.
1594 */
1595 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596 {
1597#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001598 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001599 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001600 buf[0] = K_SPECIAL;
1601 buf[1] = KS_EXTRA;
1602 buf[2] = (int)KE_CURSORHOLD;
1603 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001604 }
1605#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001606 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 }
1608 }
1609
1610 /*
1611 * Try to read as many characters as there are, until the buffer is full.
1612 */
1613
1614 /* we will get at least one key. Get more if they are available. */
1615 g_fCBrkPressed = FALSE;
1616
1617#ifdef MCH_WRITE_DUMP
1618 if (fdDump)
1619 fputc('[', fdDump);
1620#endif
1621
1622 /* Keep looping until there is something in the typeahead buffer and more
1623 * to get and still room in the buffer (up to two bytes for a char and
1624 * three bytes for a modifier). */
1625 while ((typeaheadlen == 0 || WaitForChar(0L))
1626 && typeaheadlen + 5 <= TYPEAHEADLEN)
1627 {
1628 if (typebuf_changed(tb_change_cnt))
1629 {
1630 /* "buf" may be invalid now if a client put something in the
1631 * typeahead buffer and "buf" is in the typeahead buffer. */
1632 typeaheadlen = 0;
1633 break;
1634 }
1635#ifdef FEAT_MOUSE
1636 if (g_nMouseClick != -1)
1637 {
1638# ifdef MCH_WRITE_DUMP
1639 if (fdDump)
1640 fprintf(fdDump, "{%02x @ %d, %d}",
1641 g_nMouseClick, g_xMouse, g_yMouse);
1642# endif
1643 typeahead[typeaheadlen++] = ESC + 128;
1644 typeahead[typeaheadlen++] = 'M';
1645 typeahead[typeaheadlen++] = g_nMouseClick;
1646 typeahead[typeaheadlen++] = g_xMouse + '!';
1647 typeahead[typeaheadlen++] = g_yMouse + '!';
1648 g_nMouseClick = -1;
1649 }
1650 else
1651#endif
1652 {
1653 char_u ch2 = NUL;
1654 int modifiers = 0;
1655
1656 c = tgetch(&modifiers, &ch2);
1657
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001658#ifdef FEAT_MBYTE
1659 /* stolen from fill_input_buf() in ui.c */
1660 if (rest != NULL)
1661 {
1662 /* Use remainder of previous call, starts with an invalid
1663 * character that may become valid when reading more. */
1664 if (restlen > TYPEAHEADLEN - typeaheadlen)
1665 unconverted = TYPEAHEADLEN - typeaheadlen;
1666 else
1667 unconverted = restlen;
1668 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1669 if (unconverted == restlen)
1670 {
1671 vim_free(rest);
1672 rest = NULL;
1673 }
1674 else
1675 {
1676 restlen -= unconverted;
1677 mch_memmove(rest, rest + unconverted, restlen);
1678 }
1679 typeaheadlen += unconverted;
1680 }
1681 else
1682 unconverted = 0;
1683#endif
1684
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685 if (typebuf_changed(tb_change_cnt))
1686 {
1687 /* "buf" may be invalid now if a client put something in the
1688 * typeahead buffer and "buf" is in the typeahead buffer. */
1689 typeaheadlen = 0;
1690 break;
1691 }
1692
1693 if (c == Ctrl_C && ctrl_c_interrupts)
1694 {
1695#if defined(FEAT_CLIENTSERVER)
1696 trash_input_buf();
1697#endif
1698 got_int = TRUE;
1699 }
1700
1701#ifdef FEAT_MOUSE
1702 if (g_nMouseClick == -1)
1703#endif
1704 {
1705 int n = 1;
1706
1707 /* A key may have one or two bytes. */
1708 typeahead[typeaheadlen] = c;
1709 if (ch2 != NUL)
1710 {
1711 typeahead[typeaheadlen + 1] = ch2;
1712 ++n;
1713 }
1714#ifdef FEAT_MBYTE
1715 /* Only convert normal characters, not special keys. Need to
1716 * convert before applying ALT, otherwise mapping <M-x> breaks
1717 * when 'tenc' is set. */
1718 if (input_conv.vc_type != CONV_NONE
1719 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001720 {
1721 typeaheadlen -= unconverted;
1722 n = convert_input_safe(typeahead + typeaheadlen,
1723 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1724 rest == NULL ? &rest : NULL, &restlen);
1725 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001726#endif
1727
1728 /* Use the ALT key to set the 8th bit of the character
1729 * when it's one byte, the 8th bit isn't set yet and not
1730 * using a double-byte encoding (would become a lead
1731 * byte). */
1732 if ((modifiers & MOD_MASK_ALT)
1733 && n == 1
1734 && (typeahead[typeaheadlen] & 0x80) == 0
1735#ifdef FEAT_MBYTE
1736 && !enc_dbcs
1737#endif
1738 )
1739 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001740#ifdef FEAT_MBYTE
1741 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1742 typeahead + typeaheadlen);
1743#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001745#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746 modifiers &= ~MOD_MASK_ALT;
1747 }
1748
1749 if (modifiers != 0)
1750 {
1751 /* Prepend modifiers to the character. */
1752 mch_memmove(typeahead + typeaheadlen + 3,
1753 typeahead + typeaheadlen, n);
1754 typeahead[typeaheadlen++] = K_SPECIAL;
1755 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1756 typeahead[typeaheadlen++] = modifiers;
1757 }
1758
1759 typeaheadlen += n;
1760
1761#ifdef MCH_WRITE_DUMP
1762 if (fdDump)
1763 fputc(c, fdDump);
1764#endif
1765 }
1766 }
1767 }
1768
1769#ifdef MCH_WRITE_DUMP
1770 if (fdDump)
1771 {
1772 fputs("]\n", fdDump);
1773 fflush(fdDump);
1774 }
1775#endif
1776
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777theend:
1778 /* Move typeahead to "buf", as much as fits. */
1779 len = 0;
1780 while (len < maxlen && typeaheadlen > 0)
1781 {
1782 buf[len++] = typeahead[0];
1783 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1784 }
1785 return len;
1786
1787#else /* FEAT_GUI_W32 */
1788 return 0;
1789#endif /* FEAT_GUI_W32 */
1790}
1791
Bram Moolenaar82881492012-11-20 16:53:39 +01001792#ifndef PROTO
1793# ifndef __MINGW32__
1794# include <shellapi.h> /* required for FindExecutable() */
1795# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001796#endif
1797
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001798/*
1799 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001800 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001801 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001802 static int
1803executable_exists(char *name)
1804{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001805 char *dum;
1806 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001807
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001808#ifdef FEAT_MBYTE
1809 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001810 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001811 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001812 WCHAR fnamew[_MAX_PATH];
1813 WCHAR *dumw;
1814 long n;
1815
1816 if (p != NULL)
1817 {
1818 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1819 vim_free(p);
1820 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1821 {
1822 if (n == 0)
1823 return FALSE;
1824 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1825 return FALSE;
1826 return TRUE;
1827 }
1828 /* Retry with non-wide function (for Windows 98). */
1829 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001830 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001831#endif
1832 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1833 return FALSE;
1834 if (mch_isdir(fname))
1835 return FALSE;
1836 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001837}
1838
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001839#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001840 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001841/*
1842 * Bad parameter handler.
1843 *
1844 * Certain MS CRT functions will intentionally crash when passed invalid
1845 * parameters to highlight possible security holes. Setting this function as
1846 * the bad parameter handler will prevent the crash.
1847 *
1848 * In debug builds the parameters contain CRT information that might help track
1849 * down the source of a problem, but in non-debug builds the arguments are all
1850 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1851 * worth allowing these to make debugging of issues easier.
1852 */
1853 static void
1854bad_param_handler(const wchar_t *expression,
1855 const wchar_t *function,
1856 const wchar_t *file,
1857 unsigned int line,
1858 uintptr_t pReserved)
1859{
1860}
1861
1862# define SET_INVALID_PARAM_HANDLER \
1863 ((void)_set_invalid_parameter_handler(bad_param_handler))
1864#else
1865# define SET_INVALID_PARAM_HANDLER
1866#endif
1867
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868#ifdef FEAT_GUI_W32
1869
1870/*
1871 * GUI version of mch_init().
1872 */
1873 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001874mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001875{
1876#ifndef __MINGW32__
1877 extern int _fmode;
1878#endif
1879
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001880 /* Silently handle invalid parameters to CRT functions */
1881 SET_INVALID_PARAM_HANDLER;
1882
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 /* Let critical errors result in a failure, not in a dialog box. Required
1884 * for the timestamp test to work on removed floppies. */
1885 SetErrorMode(SEM_FAILCRITICALERRORS);
1886
1887 _fmode = O_BINARY; /* we do our own CR-LF translation */
1888
1889 /* Specify window size. Is there a place to get the default from? */
1890 Rows = 25;
1891 Columns = 80;
1892
1893 /* Look for 'vimrun' */
1894 if (!gui_is_win32s())
1895 {
1896 char_u vimrun_location[_MAX_PATH + 4];
1897
1898 /* First try in same directory as gvim.exe */
1899 STRCPY(vimrun_location, exe_name);
1900 STRCPY(gettail(vimrun_location), "vimrun.exe");
1901 if (mch_getperm(vimrun_location) >= 0)
1902 {
1903 if (*skiptowhite(vimrun_location) != NUL)
1904 {
1905 /* Enclose path with white space in double quotes. */
1906 mch_memmove(vimrun_location + 1, vimrun_location,
1907 STRLEN(vimrun_location) + 1);
1908 *vimrun_location = '"';
1909 STRCPY(gettail(vimrun_location), "vimrun\" ");
1910 }
1911 else
1912 STRCPY(gettail(vimrun_location), "vimrun ");
1913
1914 vimrun_path = (char *)vim_strsave(vimrun_location);
1915 s_dont_use_vimrun = FALSE;
1916 }
1917 else if (executable_exists("vimrun.exe"))
1918 s_dont_use_vimrun = FALSE;
1919
1920 /* Don't give the warning for a missing vimrun.exe right now, but only
1921 * when vimrun was supposed to be used. Don't bother people that do
1922 * not need vimrun.exe. */
1923 if (s_dont_use_vimrun)
1924 need_vimrun_warning = TRUE;
1925 }
1926
1927 /*
1928 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1929 * Otherwise the default "findstr /n" is used.
1930 */
1931 if (!executable_exists("findstr.exe"))
1932 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1933
1934#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001935 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001936#endif
1937}
1938
1939
1940#else /* FEAT_GUI_W32 */
1941
1942#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1943#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1944
1945/*
1946 * ClearConsoleBuffer()
1947 * Description:
1948 * Clears the entire contents of the console screen buffer, using the
1949 * specified attribute.
1950 * Returns:
1951 * TRUE on success
1952 */
1953 static BOOL
1954ClearConsoleBuffer(WORD wAttribute)
1955{
1956 CONSOLE_SCREEN_BUFFER_INFO csbi;
1957 COORD coord;
1958 DWORD NumCells, dummy;
1959
1960 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1961 return FALSE;
1962
1963 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1964 coord.X = 0;
1965 coord.Y = 0;
1966 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1967 coord, &dummy))
1968 {
1969 return FALSE;
1970 }
1971 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1972 coord, &dummy))
1973 {
1974 return FALSE;
1975 }
1976
1977 return TRUE;
1978}
1979
1980/*
1981 * FitConsoleWindow()
1982 * Description:
1983 * Checks if the console window will fit within given buffer dimensions.
1984 * Also, if requested, will shrink the window to fit.
1985 * Returns:
1986 * TRUE on success
1987 */
1988 static BOOL
1989FitConsoleWindow(
1990 COORD dwBufferSize,
1991 BOOL WantAdjust)
1992{
1993 CONSOLE_SCREEN_BUFFER_INFO csbi;
1994 COORD dwWindowSize;
1995 BOOL NeedAdjust = FALSE;
1996
1997 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1998 {
1999 /*
2000 * A buffer resize will fail if the current console window does
2001 * not lie completely within that buffer. To avoid this, we might
2002 * have to move and possibly shrink the window.
2003 */
2004 if (csbi.srWindow.Right >= dwBufferSize.X)
2005 {
2006 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2007 if (dwWindowSize.X > dwBufferSize.X)
2008 dwWindowSize.X = dwBufferSize.X;
2009 csbi.srWindow.Right = dwBufferSize.X - 1;
2010 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2011 NeedAdjust = TRUE;
2012 }
2013 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2014 {
2015 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2016 if (dwWindowSize.Y > dwBufferSize.Y)
2017 dwWindowSize.Y = dwBufferSize.Y;
2018 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2019 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2020 NeedAdjust = TRUE;
2021 }
2022 if (NeedAdjust && WantAdjust)
2023 {
2024 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2025 return FALSE;
2026 }
2027 return TRUE;
2028 }
2029
2030 return FALSE;
2031}
2032
2033typedef struct ConsoleBufferStruct
2034{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002035 BOOL IsValid;
2036 CONSOLE_SCREEN_BUFFER_INFO Info;
2037 PCHAR_INFO Buffer;
2038 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002039} ConsoleBuffer;
2040
2041/*
2042 * SaveConsoleBuffer()
2043 * Description:
2044 * Saves important information about the console buffer, including the
2045 * actual buffer contents. The saved information is suitable for later
2046 * restoration by RestoreConsoleBuffer().
2047 * Returns:
2048 * TRUE if all information was saved; FALSE otherwise
2049 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2050 */
2051 static BOOL
2052SaveConsoleBuffer(
2053 ConsoleBuffer *cb)
2054{
2055 DWORD NumCells;
2056 COORD BufferCoord;
2057 SMALL_RECT ReadRegion;
2058 WORD Y, Y_incr;
2059
2060 if (cb == NULL)
2061 return FALSE;
2062
2063 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2064 {
2065 cb->IsValid = FALSE;
2066 return FALSE;
2067 }
2068 cb->IsValid = TRUE;
2069
2070 /*
2071 * Allocate a buffer large enough to hold the entire console screen
2072 * buffer. If this ConsoleBuffer structure has already been initialized
2073 * with a buffer of the correct size, then just use that one.
2074 */
2075 if (!cb->IsValid || cb->Buffer == NULL ||
2076 cb->BufferSize.X != cb->Info.dwSize.X ||
2077 cb->BufferSize.Y != cb->Info.dwSize.Y)
2078 {
2079 cb->BufferSize.X = cb->Info.dwSize.X;
2080 cb->BufferSize.Y = cb->Info.dwSize.Y;
2081 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002082 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2084 if (cb->Buffer == NULL)
2085 return FALSE;
2086 }
2087
2088 /*
2089 * We will now copy the console screen buffer into our buffer.
2090 * ReadConsoleOutput() seems to be limited as far as how much you
2091 * can read at a time. Empirically, this number seems to be about
2092 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2093 * in chunks until it is all copied. The chunks will all have the
2094 * same horizontal characteristics, so initialize them now. The
2095 * height of each chunk will be (12000 / width).
2096 */
2097 BufferCoord.X = 0;
2098 ReadRegion.Left = 0;
2099 ReadRegion.Right = cb->Info.dwSize.X - 1;
2100 Y_incr = 12000 / cb->Info.dwSize.X;
2101 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2102 {
2103 /*
2104 * Read into position (0, Y) in our buffer.
2105 */
2106 BufferCoord.Y = Y;
2107 /*
2108 * Read the region whose top left corner is (0, Y) and whose bottom
2109 * right corner is (width - 1, Y + Y_incr - 1). This should define
2110 * a region of size width by Y_incr. Don't worry if this region is
2111 * too large for the remaining buffer; it will be cropped.
2112 */
2113 ReadRegion.Top = Y;
2114 ReadRegion.Bottom = Y + Y_incr - 1;
2115 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2116 cb->Buffer, /* our buffer */
2117 cb->BufferSize, /* dimensions of our buffer */
2118 BufferCoord, /* offset in our buffer */
2119 &ReadRegion)) /* region to save */
2120 {
2121 vim_free(cb->Buffer);
2122 cb->Buffer = NULL;
2123 return FALSE;
2124 }
2125 }
2126
2127 return TRUE;
2128}
2129
2130/*
2131 * RestoreConsoleBuffer()
2132 * Description:
2133 * Restores important information about the console buffer, including the
2134 * actual buffer contents, if desired. The information to restore is in
2135 * the same format used by SaveConsoleBuffer().
2136 * Returns:
2137 * TRUE on success
2138 */
2139 static BOOL
2140RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002141 ConsoleBuffer *cb,
2142 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002143{
2144 COORD BufferCoord;
2145 SMALL_RECT WriteRegion;
2146
2147 if (cb == NULL || !cb->IsValid)
2148 return FALSE;
2149
2150 /*
2151 * Before restoring the buffer contents, clear the current buffer, and
2152 * restore the cursor position and window information. Doing this now
2153 * prevents old buffer contents from "flashing" onto the screen.
2154 */
2155 if (RestoreScreen)
2156 ClearConsoleBuffer(cb->Info.wAttributes);
2157
2158 FitConsoleWindow(cb->Info.dwSize, TRUE);
2159 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2160 return FALSE;
2161 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2162 return FALSE;
2163
2164 if (!RestoreScreen)
2165 {
2166 /*
2167 * No need to restore the screen buffer contents, so we're done.
2168 */
2169 return TRUE;
2170 }
2171
2172 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2173 return FALSE;
2174 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2175 return FALSE;
2176
2177 /*
2178 * Restore the screen buffer contents.
2179 */
2180 if (cb->Buffer != NULL)
2181 {
2182 BufferCoord.X = 0;
2183 BufferCoord.Y = 0;
2184 WriteRegion.Left = 0;
2185 WriteRegion.Top = 0;
2186 WriteRegion.Right = cb->Info.dwSize.X - 1;
2187 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2188 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2189 cb->Buffer, /* our buffer */
2190 cb->BufferSize, /* dimensions of our buffer */
2191 BufferCoord, /* offset in our buffer */
2192 &WriteRegion)) /* region to restore */
2193 {
2194 return FALSE;
2195 }
2196 }
2197
2198 return TRUE;
2199}
2200
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002201#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002202#ifdef FEAT_RESTORE_ORIG_SCREEN
2203static ConsoleBuffer g_cbOrig = { 0 };
2204#endif
2205static ConsoleBuffer g_cbNonTermcap = { 0 };
2206static ConsoleBuffer g_cbTermcap = { 0 };
2207
2208#ifdef FEAT_TITLE
2209#ifdef __BORLANDC__
2210typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2211#else
2212typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2213#endif
2214char g_szOrigTitle[256] = { 0 };
2215HWND g_hWnd = NULL; /* also used in os_mswin.c */
2216static HICON g_hOrigIconSmall = NULL;
2217static HICON g_hOrigIcon = NULL;
2218static HICON g_hVimIcon = NULL;
2219static BOOL g_fCanChangeIcon = FALSE;
2220
2221/* ICON* are not defined in VC++ 4.0 */
2222#ifndef ICON_SMALL
2223#define ICON_SMALL 0
2224#endif
2225#ifndef ICON_BIG
2226#define ICON_BIG 1
2227#endif
2228/*
2229 * GetConsoleIcon()
2230 * Description:
2231 * Attempts to retrieve the small icon and/or the big icon currently in
2232 * use by a given window.
2233 * Returns:
2234 * TRUE on success
2235 */
2236 static BOOL
2237GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002238 HWND hWnd,
2239 HICON *phIconSmall,
2240 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002241{
2242 if (hWnd == NULL)
2243 return FALSE;
2244
2245 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002246 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2247 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002248 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002249 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2250 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 return TRUE;
2252}
2253
2254/*
2255 * SetConsoleIcon()
2256 * Description:
2257 * Attempts to change the small icon and/or the big icon currently in
2258 * use by a given window.
2259 * Returns:
2260 * TRUE on success
2261 */
2262 static BOOL
2263SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002264 HWND hWnd,
2265 HICON hIconSmall,
2266 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002267{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002268 HICON hPrevIconSmall;
2269 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002270
2271 if (hWnd == NULL)
2272 return FALSE;
2273
2274 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002275 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2276 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002278 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2279 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002280 return TRUE;
2281}
2282
2283/*
2284 * SaveConsoleTitleAndIcon()
2285 * Description:
2286 * Saves the current console window title in g_szOrigTitle, for later
2287 * restoration. Also, attempts to obtain a handle to the console window,
2288 * and use it to save the small and big icons currently in use by the
2289 * console window. This is not always possible on some versions of Windows;
2290 * nor is it possible when running Vim remotely using Telnet (since the
2291 * console window the user sees is owned by a remote process).
2292 */
2293 static void
2294SaveConsoleTitleAndIcon(void)
2295{
2296 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2297
2298 /* Save the original title. */
2299 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2300 return;
2301
2302 /*
2303 * Obtain a handle to the console window using GetConsoleWindow() from
2304 * KERNEL32.DLL; we need to handle in order to change the window icon.
2305 * This function only exists on NT-based Windows, starting with Windows
2306 * 2000. On older operating systems, we can't change the window icon
2307 * anyway.
2308 */
2309 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2310 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2311 "GetConsoleWindow")) != NULL)
2312 {
2313 g_hWnd = (*GetConsoleWindowProc)();
2314 }
2315 if (g_hWnd == NULL)
2316 return;
2317
2318 /* Save the original console window icon. */
2319 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2320 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2321 return;
2322
2323 /* Extract the first icon contained in the Vim executable. */
2324 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2325 if (g_hVimIcon != NULL)
2326 g_fCanChangeIcon = TRUE;
2327}
2328#endif
2329
2330static int g_fWindInitCalled = FALSE;
2331static int g_fTermcapMode = FALSE;
2332static CONSOLE_CURSOR_INFO g_cci;
2333static DWORD g_cmodein = 0;
2334static DWORD g_cmodeout = 0;
2335
2336/*
2337 * non-GUI version of mch_init().
2338 */
2339 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002340mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341{
2342#ifndef FEAT_RESTORE_ORIG_SCREEN
2343 CONSOLE_SCREEN_BUFFER_INFO csbi;
2344#endif
2345#ifndef __MINGW32__
2346 extern int _fmode;
2347#endif
2348
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002349 /* Silently handle invalid parameters to CRT functions */
2350 SET_INVALID_PARAM_HANDLER;
2351
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352 /* Let critical errors result in a failure, not in a dialog box. Required
2353 * for the timestamp test to work on removed floppies. */
2354 SetErrorMode(SEM_FAILCRITICALERRORS);
2355
2356 _fmode = O_BINARY; /* we do our own CR-LF translation */
2357 out_flush();
2358
2359 /* Obtain handles for the standard Console I/O devices */
2360 if (read_cmd_fd == 0)
2361 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2362 else
2363 create_conin();
2364 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2365
2366#ifdef FEAT_RESTORE_ORIG_SCREEN
2367 /* Save the initial console buffer for later restoration */
2368 SaveConsoleBuffer(&g_cbOrig);
2369 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2370#else
2371 /* Get current text attributes */
2372 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2373 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2374#endif
2375 if (cterm_normal_fg_color == 0)
2376 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2377 if (cterm_normal_bg_color == 0)
2378 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2379
2380 /* set termcap codes to current text attributes */
2381 update_tcap(g_attrCurrent);
2382
2383 GetConsoleCursorInfo(g_hConOut, &g_cci);
2384 GetConsoleMode(g_hConIn, &g_cmodein);
2385 GetConsoleMode(g_hConOut, &g_cmodeout);
2386
2387#ifdef FEAT_TITLE
2388 SaveConsoleTitleAndIcon();
2389 /*
2390 * Set both the small and big icons of the console window to Vim's icon.
2391 * Note that Vim presently only has one size of icon (32x32), but it
2392 * automatically gets scaled down to 16x16 when setting the small icon.
2393 */
2394 if (g_fCanChangeIcon)
2395 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2396#endif
2397
2398 ui_get_shellsize();
2399
2400#ifdef MCH_WRITE_DUMP
2401 fdDump = fopen("dump", "wt");
2402
2403 if (fdDump)
2404 {
2405 time_t t;
2406
2407 time(&t);
2408 fputs(ctime(&t), fdDump);
2409 fflush(fdDump);
2410 }
2411#endif
2412
2413 g_fWindInitCalled = TRUE;
2414
2415#ifdef FEAT_MOUSE
2416 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2417#endif
2418
2419#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002420 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002421#endif
2422
2423 /* This will be NULL on anything but NT 4.0 */
2424 s_pfnGetConsoleKeyboardLayoutName =
2425 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2426 "GetConsoleKeyboardLayoutNameA");
2427}
2428
2429/*
2430 * non-GUI version of mch_exit().
2431 * Shut down and exit with status `r'
2432 * Careful: mch_exit() may be called before mch_init()!
2433 */
2434 void
2435mch_exit(int r)
2436{
2437 stoptermcap();
2438
2439 if (g_fWindInitCalled)
2440 settmode(TMODE_COOK);
2441
2442 ml_close_all(TRUE); /* remove all memfiles */
2443
2444 if (g_fWindInitCalled)
2445 {
2446#ifdef FEAT_TITLE
2447 mch_restore_title(3);
2448 /*
2449 * Restore both the small and big icons of the console window to
2450 * what they were at startup. Don't do this when the window is
2451 * closed, Vim would hang here.
2452 */
2453 if (g_fCanChangeIcon && !g_fForceExit)
2454 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2455#endif
2456
2457#ifdef MCH_WRITE_DUMP
2458 if (fdDump)
2459 {
2460 time_t t;
2461
2462 time(&t);
2463 fputs(ctime(&t), fdDump);
2464 fclose(fdDump);
2465 }
2466 fdDump = NULL;
2467#endif
2468 }
2469
2470 SetConsoleCursorInfo(g_hConOut, &g_cci);
2471 SetConsoleMode(g_hConIn, g_cmodein);
2472 SetConsoleMode(g_hConOut, g_cmodeout);
2473
2474#ifdef DYNAMIC_GETTEXT
2475 dyn_libintl_end();
2476#endif
2477
2478 exit(r);
2479}
2480#endif /* !FEAT_GUI_W32 */
2481
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482/*
2483 * Do we have an interactive window?
2484 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002485/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002486 int
2487mch_check_win(
2488 int argc,
2489 char **argv)
2490{
2491 get_exe_name();
2492
2493#ifdef FEAT_GUI_W32
2494 return OK; /* GUI always has a tty */
2495#else
2496 if (isatty(1))
2497 return OK;
2498 return FAIL;
2499#endif
2500}
2501
2502
2503/*
2504 * fname_case(): Set the case of the file name, if it already exists.
2505 * When "len" is > 0, also expand short to long filenames.
2506 */
2507 void
2508fname_case(
2509 char_u *name,
2510 int len)
2511{
2512 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002513 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514 char *ptrue, *ptruePrev;
2515 char *porig, *porigPrev;
2516 int flen;
2517 WIN32_FIND_DATA fb;
2518 HANDLE hFind;
2519 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002520 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002522 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 if (flen == 0 || flen > _MAX_PATH)
2524 return;
2525
2526 slash_adjust(name);
2527
2528 /* Build the new name in szTrueName[] one component at a time. */
2529 porig = name;
2530 ptrue = szTrueName;
2531
2532 if (isalpha(porig[0]) && porig[1] == ':')
2533 {
2534 /* copy leading drive letter */
2535 *ptrue++ = *porig++;
2536 *ptrue++ = *porig++;
2537 *ptrue = NUL; /* in case nothing follows */
2538 }
2539
2540 while (*porig != NUL)
2541 {
2542 /* copy \ characters */
2543 while (*porig == psepc)
2544 *ptrue++ = *porig++;
2545
2546 ptruePrev = ptrue;
2547 porigPrev = porig;
2548 while (*porig != NUL && *porig != psepc)
2549 {
2550#ifdef FEAT_MBYTE
2551 int l;
2552
2553 if (enc_dbcs)
2554 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002555 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002556 while (--l >= 0)
2557 *ptrue++ = *porig++;
2558 }
2559 else
2560#endif
2561 *ptrue++ = *porig++;
2562 }
2563 *ptrue = NUL;
2564
Bram Moolenaar464c9252010-10-13 20:37:41 +02002565 /* To avoid a slow failure append "\*" when searching a directory,
2566 * server or network share. */
2567 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002568 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002569 if (*porig == psepc && slen + 2 < _MAX_PATH)
2570 STRCPY(szTrueNameTemp + slen, "\\*");
2571
Bram Moolenaar071d4272004-06-13 20:20:40 +00002572 /* Skip "", "." and "..". */
2573 if (ptrue > ptruePrev
2574 && (ptruePrev[0] != '.'
2575 || (ptruePrev[1] != NUL
2576 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002577 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 != INVALID_HANDLE_VALUE)
2579 {
2580 c = *porig;
2581 *porig = NUL;
2582
2583 /* Only use the match when it's the same name (ignoring case) or
2584 * expansion is allowed and there is a match with the short name
2585 * and there is enough room. */
2586 if (_stricoll(porigPrev, fb.cFileName) == 0
2587 || (len > 0
2588 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2589 && (int)(ptruePrev - szTrueName)
2590 + (int)strlen(fb.cFileName) < len)))
2591 {
2592 STRCPY(ptruePrev, fb.cFileName);
2593
2594 /* Look for exact match and prefer it if found. Must be a
2595 * long name, otherwise there would be only one match. */
2596 while (FindNextFile(hFind, &fb))
2597 {
2598 if (*fb.cAlternateFileName != NUL
2599 && (strcoll(porigPrev, fb.cFileName) == 0
2600 || (len > 0
2601 && (_stricoll(porigPrev,
2602 fb.cAlternateFileName) == 0
2603 && (int)(ptruePrev - szTrueName)
2604 + (int)strlen(fb.cFileName) < len))))
2605 {
2606 STRCPY(ptruePrev, fb.cFileName);
2607 break;
2608 }
2609 }
2610 }
2611 FindClose(hFind);
2612 *porig = c;
2613 ptrue = ptruePrev + strlen(ptruePrev);
2614 }
2615 }
2616
2617 STRCPY(name, szTrueName);
2618}
2619
2620
2621/*
2622 * Insert user name in s[len].
2623 */
2624 int
2625mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002626 char_u *s,
2627 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002628{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002629 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630 DWORD cch = sizeof szUserName;
2631
2632 if (GetUserName(szUserName, &cch))
2633 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002634 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635 return OK;
2636 }
2637 s[0] = NUL;
2638 return FAIL;
2639}
2640
2641
2642/*
2643 * Insert host name in s[len].
2644 */
2645 void
2646mch_get_host_name(
2647 char_u *s,
2648 int len)
2649{
2650 DWORD cch = len;
2651
2652 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002653 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002654}
2655
2656
2657/*
2658 * return process ID
2659 */
2660 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002661mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662{
2663 return (long)GetCurrentProcessId();
2664}
2665
2666
2667/*
2668 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2669 * Return OK for success, FAIL for failure.
2670 */
2671 int
2672mch_dirname(
2673 char_u *buf,
2674 int len)
2675{
2676 /*
2677 * Originally this was:
2678 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2679 * But the Win32s known bug list says that getcwd() doesn't work
2680 * so use the Win32 system call instead. <Negri>
2681 */
2682#ifdef FEAT_MBYTE
2683 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2684 {
2685 WCHAR wbuf[_MAX_PATH + 1];
2686
2687 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2688 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002689 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690
2691 if (p != NULL)
2692 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002693 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694 vim_free(p);
2695 return OK;
2696 }
2697 }
2698 /* Retry with non-wide function (for Windows 98). */
2699 }
2700#endif
2701 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2702}
2703
2704/*
2705 * get file permissions for `name'
2706 * -1 : error
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002707 * else mode_t
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708 */
2709 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002710mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002712 struct stat st;
2713 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002715 n = mch_stat(name, &st);
2716 return n == 0 ? (int)st.st_mode : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717}
2718
2719
2720/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002721 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002722 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002723 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724 */
2725 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002726mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002728 long n = -1;
2729
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730#ifdef FEAT_MBYTE
2731 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2732 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002733 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002734
2735 if (p != NULL)
2736 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002737 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002739 if (n == -1 && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2740 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002741 /* Retry with non-wide function (for Windows 98). */
2742 }
2743 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02002744 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002745#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002746 n = _chmod(name, perm);
2747 if (n == -1)
2748 return FAIL;
2749
2750 win32_set_archive(name);
2751
2752 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002753}
2754
2755/*
2756 * Set hidden flag for "name".
2757 */
2758 void
2759mch_hide(char_u *name)
2760{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002761 int attrs = win32_getattrs(name);
2762 if (attrs == -1)
2763 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002765 attrs |= FILE_ATTRIBUTE_HIDDEN;
2766 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002767}
2768
2769/*
2770 * return TRUE if "name" is a directory
2771 * return FALSE if "name" is not a directory or upon error
2772 */
2773 int
2774mch_isdir(char_u *name)
2775{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002776 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002777
2778 if (f == -1)
2779 return FALSE; /* file does not exist at all */
2780
2781 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2782}
2783
2784/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002785 * Create directory "name".
2786 * Return 0 on success, -1 on error.
2787 */
2788 int
2789mch_mkdir(char_u *name)
2790{
2791#ifdef FEAT_MBYTE
2792 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2793 {
2794 WCHAR *p;
2795 int retval;
2796
2797 p = enc_to_utf16(name, NULL);
2798 if (p == NULL)
2799 return -1;
2800 retval = _wmkdir(p);
2801 vim_free(p);
2802 return retval;
2803 }
2804#endif
2805 return _mkdir(name);
2806}
2807
2808/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002809 * Return TRUE if file "fname" has more than one link.
2810 */
2811 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002812mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002813{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002814 BY_HANDLE_FILE_INFORMATION info;
2815
2816 return win32_fileinfo(fname, &info) == FILEINFO_OK
2817 && info.nNumberOfLinks > 1;
2818}
2819
2820/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002821 * Return TRUE if file "fname" is a symbolic link.
2822 */
2823 int
2824mch_is_symbolic_link(char_u *fname)
2825{
2826 HANDLE hFind;
2827 int res = FALSE;
2828 WIN32_FIND_DATAA findDataA;
2829 DWORD fileFlags = 0, reparseTag = 0;
2830#ifdef FEAT_MBYTE
2831 WCHAR *wn = NULL;
2832 WIN32_FIND_DATAW findDataW;
2833
2834 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2835 wn = enc_to_utf16(fname, NULL);
2836 if (wn != NULL)
2837 {
2838 hFind = FindFirstFileW(wn, &findDataW);
2839 vim_free(wn);
2840 if (hFind == INVALID_HANDLE_VALUE
2841 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2842 {
2843 /* Retry with non-wide function (for Windows 98). */
2844 hFind = FindFirstFile(fname, &findDataA);
2845 if (hFind != INVALID_HANDLE_VALUE)
2846 {
2847 fileFlags = findDataA.dwFileAttributes;
2848 reparseTag = findDataA.dwReserved0;
2849 }
2850 }
2851 else
2852 {
2853 fileFlags = findDataW.dwFileAttributes;
2854 reparseTag = findDataW.dwReserved0;
2855 }
2856 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002857 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002858#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002859 {
2860 hFind = FindFirstFile(fname, &findDataA);
2861 if (hFind != INVALID_HANDLE_VALUE)
2862 {
2863 fileFlags = findDataA.dwFileAttributes;
2864 reparseTag = findDataA.dwReserved0;
2865 }
2866 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002867
2868 if (hFind != INVALID_HANDLE_VALUE)
2869 FindClose(hFind);
2870
2871 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
2872 && reparseTag == IO_REPARSE_TAG_SYMLINK)
2873 res = TRUE;
2874
2875 return res;
2876}
2877
2878/*
2879 * Return TRUE if file "fname" has more than one link or if it is a symbolic
2880 * link.
2881 */
2882 int
2883mch_is_linked(char_u *fname)
2884{
2885 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
2886 return TRUE;
2887 return FALSE;
2888}
2889
2890/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002891 * Get the by-handle-file-information for "fname".
2892 * Returns FILEINFO_OK when OK.
2893 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
2894 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
2895 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
2896 */
2897 int
2898win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
2899{
Bram Moolenaar03f48552006-02-28 23:52:23 +00002900 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002901 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002902#ifdef FEAT_MBYTE
2903 WCHAR *wn = NULL;
2904
2905 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002906 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002907 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002908 if (wn == NULL)
2909 res = FILEINFO_ENC_FAIL;
2910 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00002911 if (wn != NULL)
2912 {
2913 hFile = CreateFileW(wn, /* file name */
2914 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002915 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002916 NULL, /* security descriptor */
2917 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002918 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002919 NULL); /* handle to template file */
2920 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002921 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002922 {
2923 /* Retry with non-wide function (for Windows 98). */
2924 vim_free(wn);
2925 wn = NULL;
2926 }
2927 }
2928 if (wn == NULL)
2929#endif
2930 hFile = CreateFile(fname, /* file name */
2931 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002932 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002933 NULL, /* security descriptor */
2934 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002935 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002936 NULL); /* handle to template file */
2937
2938 if (hFile != INVALID_HANDLE_VALUE)
2939 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002940 if (GetFileInformationByHandle(hFile, info) != 0)
2941 res = FILEINFO_OK;
2942 else
2943 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002944 CloseHandle(hFile);
2945 }
2946
2947#ifdef FEAT_MBYTE
2948 vim_free(wn);
2949#endif
2950 return res;
2951}
2952
2953/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002954 * get file attributes for `name'
2955 * -1 : error
2956 * else FILE_ATTRIBUTE_* defined in winnt.h
2957 */
2958 static
2959 int
2960win32_getattrs(char_u *name)
2961{
2962 int attr;
2963#ifdef FEAT_MBYTE
2964 WCHAR *p = NULL;
2965
2966 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2967 p = enc_to_utf16(name, NULL);
2968
2969 if (p != NULL)
2970 {
2971 attr = GetFileAttributesW(p);
2972 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2973 {
2974 /* Retry with non-wide function (for Windows 98). */
2975 vim_free(p);
2976 p = NULL;
2977 }
2978 }
2979 if (p == NULL)
2980#endif
2981 attr = GetFileAttributes((char *)name);
2982#ifdef FEAT_MBYTE
2983 vim_free(p);
2984#endif
2985 return attr;
2986}
2987
2988/*
2989 * set file attributes for `name' to `attrs'
2990 *
2991 * return -1 for failure, 0 otherwise
2992 */
2993 static
2994 int
2995win32_setattrs(char_u *name, int attrs)
2996{
2997 int res;
2998#ifdef FEAT_MBYTE
2999 WCHAR *p = NULL;
3000
3001 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3002 p = enc_to_utf16(name, NULL);
3003
3004 if (p != NULL)
3005 {
3006 res = SetFileAttributesW(p, attrs);
3007 if (res == FALSE
3008 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3009 {
3010 /* Retry with non-wide function (for Windows 98). */
3011 vim_free(p);
3012 p = NULL;
3013 }
3014 }
3015 if (p == NULL)
3016#endif
3017 res = SetFileAttributes((char *)name, attrs);
3018#ifdef FEAT_MBYTE
3019 vim_free(p);
3020#endif
3021 return res ? 0 : -1;
3022}
3023
3024/*
3025 * Set archive flag for "name".
3026 */
3027 static
3028 int
3029win32_set_archive(char_u *name)
3030{
3031 int attrs = win32_getattrs(name);
3032 if (attrs == -1)
3033 return -1;
3034
3035 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3036 return win32_setattrs(name, attrs);
3037}
3038
3039/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040 * Return TRUE if file or directory "name" is writable (not readonly).
3041 * Strange semantics of Win32: a readonly directory is writable, but you can't
3042 * delete a file. Let's say this means it is writable.
3043 */
3044 int
3045mch_writable(char_u *name)
3046{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003047 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003049 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3050 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051}
3052
Bram Moolenaar071d4272004-06-13 20:20:40 +00003053/*
3054 * Return 1 if "name" can be executed, 0 if not.
3055 * Return -1 if unknown.
3056 */
3057 int
3058mch_can_exe(char_u *name)
3059{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003060 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003061 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003062 char_u *p;
3063
3064 if (len >= _MAX_PATH) /* safety check */
3065 return FALSE;
3066
3067 /* If there already is an extension try using the name directly. Also do
3068 * this with a Unix-shell like 'shell'. */
3069 if (vim_strchr(gettail(name), '.') != NULL
3070 || strstr((char *)gettail(p_sh), "sh") != NULL)
3071 if (executable_exists((char *)name))
3072 return TRUE;
3073
3074 /*
3075 * Loop over all extensions in $PATHEXT.
3076 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003077 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003078 p = mch_getenv("PATHEXT");
3079 if (p == NULL)
3080 p = (char_u *)".com;.exe;.bat;.cmd";
3081 while (*p)
3082 {
3083 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3084 {
3085 /* A single "." means no extension is added. */
3086 buf[len] = NUL;
3087 ++p;
3088 if (*p)
3089 ++p;
3090 }
3091 else
3092 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
3093 if (executable_exists((char *)buf))
3094 return TRUE;
3095 }
3096 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003097}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098
3099/*
3100 * Check what "name" is:
3101 * NODE_NORMAL: file or directory (or doesn't exist)
3102 * NODE_WRITABLE: writable device, socket, fifo, etc.
3103 * NODE_OTHER: non-writable things
3104 */
3105 int
3106mch_nodetype(char_u *name)
3107{
3108 HANDLE hFile;
3109 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003110#ifdef FEAT_MBYTE
3111 WCHAR *wn = NULL;
3112#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003113
Bram Moolenaar043545e2006-10-10 16:44:07 +00003114 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3115 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3116 * here. */
3117 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3118 return NODE_WRITABLE;
3119
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003120#ifdef FEAT_MBYTE
3121 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3122 {
3123 wn = enc_to_utf16(name, NULL);
3124 if (wn != NULL)
3125 {
3126 hFile = CreateFileW(wn, /* file name */
3127 GENERIC_WRITE, /* access mode */
3128 0, /* share mode */
3129 NULL, /* security descriptor */
3130 OPEN_EXISTING, /* creation disposition */
3131 0, /* file attributes */
3132 NULL); /* handle to template file */
3133 if (hFile == INVALID_HANDLE_VALUE
3134 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3135 {
3136 /* Retry with non-wide function (for Windows 98). */
3137 vim_free(wn);
3138 wn = NULL;
3139 }
3140 }
3141 }
3142 if (wn == NULL)
3143#endif
3144 hFile = CreateFile(name, /* file name */
3145 GENERIC_WRITE, /* access mode */
3146 0, /* share mode */
3147 NULL, /* security descriptor */
3148 OPEN_EXISTING, /* creation disposition */
3149 0, /* file attributes */
3150 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003152#ifdef FEAT_MBYTE
3153 vim_free(wn);
3154#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003155 if (hFile == INVALID_HANDLE_VALUE)
3156 return NODE_NORMAL;
3157
3158 type = GetFileType(hFile);
3159 CloseHandle(hFile);
3160 if (type == FILE_TYPE_CHAR)
3161 return NODE_WRITABLE;
3162 if (type == FILE_TYPE_DISK)
3163 return NODE_NORMAL;
3164 return NODE_OTHER;
3165}
3166
3167#ifdef HAVE_ACL
3168struct my_acl
3169{
3170 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3171 PSID pSidOwner;
3172 PSID pSidGroup;
3173 PACL pDacl;
3174 PACL pSacl;
3175};
3176#endif
3177
3178/*
3179 * Return a pointer to the ACL of file "fname" in allocated memory.
3180 * Return NULL if the ACL is not available for whatever reason.
3181 */
3182 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003183mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003184{
3185#ifndef HAVE_ACL
3186 return (vim_acl_T)NULL;
3187#else
3188 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003189 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003190
3191 /* This only works on Windows NT and 2000. */
3192 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3193 {
3194 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3195 if (p != NULL)
3196 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003197# ifdef FEAT_MBYTE
3198 WCHAR *wn = NULL;
3199
3200 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3201 wn = enc_to_utf16(fname, NULL);
3202 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003203 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003204 /* Try to retrieve the entire security descriptor. */
3205 err = pGetNamedSecurityInfoW(
3206 wn, // Abstract filename
3207 SE_FILE_OBJECT, // File Object
3208 OWNER_SECURITY_INFORMATION |
3209 GROUP_SECURITY_INFORMATION |
3210 DACL_SECURITY_INFORMATION |
3211 SACL_SECURITY_INFORMATION,
3212 &p->pSidOwner, // Ownership information.
3213 &p->pSidGroup, // Group membership.
3214 &p->pDacl, // Discretionary information.
3215 &p->pSacl, // For auditing purposes.
3216 &p->pSecurityDescriptor);
3217 if (err == ERROR_ACCESS_DENIED ||
3218 err == ERROR_PRIVILEGE_NOT_HELD)
3219 {
3220 /* Retrieve only DACL. */
3221 (void)pGetNamedSecurityInfoW(
3222 wn,
3223 SE_FILE_OBJECT,
3224 DACL_SECURITY_INFORMATION,
3225 NULL,
3226 NULL,
3227 &p->pDacl,
3228 NULL,
3229 &p->pSecurityDescriptor);
3230 }
3231 if (p->pSecurityDescriptor == NULL)
3232 {
3233 mch_free_acl((vim_acl_T)p);
3234 p = NULL;
3235 }
3236 vim_free(wn);
3237 }
3238 else
3239# endif
3240 {
3241 /* Try to retrieve the entire security descriptor. */
3242 err = pGetNamedSecurityInfo(
3243 (LPSTR)fname, // Abstract filename
3244 SE_FILE_OBJECT, // File Object
3245 OWNER_SECURITY_INFORMATION |
3246 GROUP_SECURITY_INFORMATION |
3247 DACL_SECURITY_INFORMATION |
3248 SACL_SECURITY_INFORMATION,
3249 &p->pSidOwner, // Ownership information.
3250 &p->pSidGroup, // Group membership.
3251 &p->pDacl, // Discretionary information.
3252 &p->pSacl, // For auditing purposes.
3253 &p->pSecurityDescriptor);
3254 if (err == ERROR_ACCESS_DENIED ||
3255 err == ERROR_PRIVILEGE_NOT_HELD)
3256 {
3257 /* Retrieve only DACL. */
3258 (void)pGetNamedSecurityInfo(
3259 (LPSTR)fname,
3260 SE_FILE_OBJECT,
3261 DACL_SECURITY_INFORMATION,
3262 NULL,
3263 NULL,
3264 &p->pDacl,
3265 NULL,
3266 &p->pSecurityDescriptor);
3267 }
3268 if (p->pSecurityDescriptor == NULL)
3269 {
3270 mch_free_acl((vim_acl_T)p);
3271 p = NULL;
3272 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273 }
3274 }
3275 }
3276
3277 return (vim_acl_T)p;
3278#endif
3279}
3280
Bram Moolenaar27515922013-06-29 15:36:26 +02003281#ifdef HAVE_ACL
3282/*
3283 * Check if "acl" contains inherited ACE.
3284 */
3285 static BOOL
3286is_acl_inherited(PACL acl)
3287{
3288 DWORD i;
3289 ACL_SIZE_INFORMATION acl_info;
3290 PACCESS_ALLOWED_ACE ace;
3291
3292 acl_info.AceCount = 0;
3293 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3294 for (i = 0; i < acl_info.AceCount; i++)
3295 {
3296 GetAce(acl, i, (LPVOID *)&ace);
3297 if (ace->Header.AceFlags & INHERITED_ACE)
3298 return TRUE;
3299 }
3300 return FALSE;
3301}
3302#endif
3303
Bram Moolenaar071d4272004-06-13 20:20:40 +00003304/*
3305 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3306 * Errors are ignored.
3307 * This must only be called with "acl" equal to what mch_get_acl() returned.
3308 */
3309 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003310mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003311{
3312#ifdef HAVE_ACL
3313 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003314 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003315
3316 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003317 {
3318# ifdef FEAT_MBYTE
3319 WCHAR *wn = NULL;
3320# endif
3321
3322 /* Set security flags */
3323 if (p->pSidOwner)
3324 sec_info |= OWNER_SECURITY_INFORMATION;
3325 if (p->pSidGroup)
3326 sec_info |= GROUP_SECURITY_INFORMATION;
3327 if (p->pDacl)
3328 {
3329 sec_info |= DACL_SECURITY_INFORMATION;
3330 /* Do not inherit its parent's DACL.
3331 * If the DACL is inherited, Cygwin permissions would be changed.
3332 */
3333 if (!is_acl_inherited(p->pDacl))
3334 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3335 }
3336 if (p->pSacl)
3337 sec_info |= SACL_SECURITY_INFORMATION;
3338
3339# ifdef FEAT_MBYTE
3340 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3341 wn = enc_to_utf16(fname, NULL);
3342 if (wn != NULL)
3343 {
3344 (void)pSetNamedSecurityInfoW(
3345 wn, // Abstract filename
3346 SE_FILE_OBJECT, // File Object
3347 sec_info,
3348 p->pSidOwner, // Ownership information.
3349 p->pSidGroup, // Group membership.
3350 p->pDacl, // Discretionary information.
3351 p->pSacl // For auditing purposes.
3352 );
3353 vim_free(wn);
3354 }
3355 else
3356# endif
3357 {
3358 (void)pSetNamedSecurityInfo(
3359 (LPSTR)fname, // Abstract filename
3360 SE_FILE_OBJECT, // File Object
3361 sec_info,
3362 p->pSidOwner, // Ownership information.
3363 p->pSidGroup, // Group membership.
3364 p->pDacl, // Discretionary information.
3365 p->pSacl // For auditing purposes.
3366 );
3367 }
3368 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003369#endif
3370}
3371
3372 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003373mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003374{
3375#ifdef HAVE_ACL
3376 struct my_acl *p = (struct my_acl *)acl;
3377
3378 if (p != NULL)
3379 {
3380 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3381 vim_free(p);
3382 }
3383#endif
3384}
3385
3386#ifndef FEAT_GUI_W32
3387
3388/*
3389 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3390 */
3391 static BOOL WINAPI
3392handler_routine(
3393 DWORD dwCtrlType)
3394{
3395 switch (dwCtrlType)
3396 {
3397 case CTRL_C_EVENT:
3398 if (ctrl_c_interrupts)
3399 g_fCtrlCPressed = TRUE;
3400 return TRUE;
3401
3402 case CTRL_BREAK_EVENT:
3403 g_fCBrkPressed = TRUE;
3404 return TRUE;
3405
3406 /* fatal events: shut down gracefully */
3407 case CTRL_CLOSE_EVENT:
3408 case CTRL_LOGOFF_EVENT:
3409 case CTRL_SHUTDOWN_EVENT:
3410 windgoto((int)Rows - 1, 0);
3411 g_fForceExit = TRUE;
3412
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003413 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003414 (dwCtrlType == CTRL_CLOSE_EVENT
3415 ? _("close")
3416 : dwCtrlType == CTRL_LOGOFF_EVENT
3417 ? _("logoff")
3418 : _("shutdown")));
3419#ifdef DEBUG
3420 OutputDebugString(IObuff);
3421#endif
3422
3423 preserve_exit(); /* output IObuff, preserve files and exit */
3424
3425 return TRUE; /* not reached */
3426
3427 default:
3428 return FALSE;
3429 }
3430}
3431
3432
3433/*
3434 * set the tty in (raw) ? "raw" : "cooked" mode
3435 */
3436 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003437mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003438{
3439 DWORD cmodein;
3440 DWORD cmodeout;
3441 BOOL bEnableHandler;
3442
3443 GetConsoleMode(g_hConIn, &cmodein);
3444 GetConsoleMode(g_hConOut, &cmodeout);
3445 if (tmode == TMODE_RAW)
3446 {
3447 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3448 ENABLE_ECHO_INPUT);
3449#ifdef FEAT_MOUSE
3450 if (g_fMouseActive)
3451 cmodein |= ENABLE_MOUSE_INPUT;
3452#endif
3453 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3454 bEnableHandler = TRUE;
3455 }
3456 else /* cooked */
3457 {
3458 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3459 ENABLE_ECHO_INPUT);
3460 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3461 bEnableHandler = FALSE;
3462 }
3463 SetConsoleMode(g_hConIn, cmodein);
3464 SetConsoleMode(g_hConOut, cmodeout);
3465 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3466
3467#ifdef MCH_WRITE_DUMP
3468 if (fdDump)
3469 {
3470 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3471 tmode == TMODE_RAW ? "raw" :
3472 tmode == TMODE_COOK ? "cooked" : "normal",
3473 cmodein, cmodeout);
3474 fflush(fdDump);
3475 }
3476#endif
3477}
3478
3479
3480/*
3481 * Get the size of the current window in `Rows' and `Columns'
3482 * Return OK when size could be determined, FAIL otherwise.
3483 */
3484 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003485mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486{
3487 CONSOLE_SCREEN_BUFFER_INFO csbi;
3488
3489 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3490 {
3491 /*
3492 * For some reason, we are trying to get the screen dimensions
3493 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3494 * variables are really intended to mean the size of Vim screen
3495 * while in termcap mode.
3496 */
3497 Rows = g_cbTermcap.Info.dwSize.Y;
3498 Columns = g_cbTermcap.Info.dwSize.X;
3499 }
3500 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3501 {
3502 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3503 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3504 }
3505 else
3506 {
3507 Rows = 25;
3508 Columns = 80;
3509 }
3510 return OK;
3511}
3512
3513/*
3514 * Set a console window to `xSize' * `ySize'
3515 */
3516 static void
3517ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003518 HANDLE hConsole,
3519 int xSize,
3520 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003521{
3522 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3523 SMALL_RECT srWindowRect; /* hold the new console size */
3524 COORD coordScreen;
3525
3526#ifdef MCH_WRITE_DUMP
3527 if (fdDump)
3528 {
3529 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3530 fflush(fdDump);
3531 }
3532#endif
3533
3534 /* get the largest size we can size the console window to */
3535 coordScreen = GetLargestConsoleWindowSize(hConsole);
3536
3537 /* define the new console window size and scroll position */
3538 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3539 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3540 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3541
3542 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3543 {
3544 int sx, sy;
3545
3546 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3547 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3548 if (sy < ySize || sx < xSize)
3549 {
3550 /*
3551 * Increasing number of lines/columns, do buffer first.
3552 * Use the maximal size in x and y direction.
3553 */
3554 if (sy < ySize)
3555 coordScreen.Y = ySize;
3556 else
3557 coordScreen.Y = sy;
3558 if (sx < xSize)
3559 coordScreen.X = xSize;
3560 else
3561 coordScreen.X = sx;
3562 SetConsoleScreenBufferSize(hConsole, coordScreen);
3563 }
3564 }
3565
3566 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3567 {
3568#ifdef MCH_WRITE_DUMP
3569 if (fdDump)
3570 {
3571 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3572 GetLastError());
3573 fflush(fdDump);
3574 }
3575#endif
3576 }
3577
3578 /* define the new console buffer size */
3579 coordScreen.X = xSize;
3580 coordScreen.Y = ySize;
3581
3582 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3583 {
3584#ifdef MCH_WRITE_DUMP
3585 if (fdDump)
3586 {
3587 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3588 GetLastError());
3589 fflush(fdDump);
3590 }
3591#endif
3592 }
3593}
3594
3595
3596/*
3597 * Set the console window to `Rows' * `Columns'
3598 */
3599 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003600mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601{
3602 COORD coordScreen;
3603
3604 /* Don't change window size while still starting up */
3605 if (suppress_winsize != 0)
3606 {
3607 suppress_winsize = 2;
3608 return;
3609 }
3610
3611 if (term_console)
3612 {
3613 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3614
3615 /* Clamp Rows and Columns to reasonable values */
3616 if (Rows > coordScreen.Y)
3617 Rows = coordScreen.Y;
3618 if (Columns > coordScreen.X)
3619 Columns = coordScreen.X;
3620
3621 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3622 }
3623}
3624
3625/*
3626 * Rows and/or Columns has changed.
3627 */
3628 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003629mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630{
3631 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3632}
3633
3634
3635/*
3636 * Called when started up, to set the winsize that was delayed.
3637 */
3638 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003639mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003640{
3641 if (suppress_winsize == 2)
3642 {
3643 suppress_winsize = 0;
3644 mch_set_shellsize();
3645 shell_resized();
3646 }
3647 suppress_winsize = 0;
3648}
3649#endif /* FEAT_GUI_W32 */
3650
3651
3652
3653#if defined(FEAT_GUI_W32) || defined(PROTO)
3654
3655/*
3656 * Specialised version of system() for Win32 GUI mode.
3657 * This version proceeds as follows:
3658 * 1. Create a console window for use by the subprocess
3659 * 2. Run the subprocess (it gets the allocated console by default)
3660 * 3. Wait for the subprocess to terminate and get its exit code
3661 * 4. Prompt the user to press a key to close the console window
3662 */
3663 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003664mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003665{
3666 STARTUPINFO si;
3667 PROCESS_INFORMATION pi;
3668 DWORD ret = 0;
3669 HWND hwnd = GetFocus();
3670
3671 si.cb = sizeof(si);
3672 si.lpReserved = NULL;
3673 si.lpDesktop = NULL;
3674 si.lpTitle = NULL;
3675 si.dwFlags = STARTF_USESHOWWINDOW;
3676 /*
3677 * It's nicer to run a filter command in a minimized window, but in
3678 * Windows 95 this makes the command MUCH slower. We can't do it under
3679 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003680 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003681 */
3682 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003683 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684 else
3685 si.wShowWindow = SW_SHOWNORMAL;
3686 si.cbReserved2 = 0;
3687 si.lpReserved2 = NULL;
3688
3689 /* There is a strange error on Windows 95 when using "c:\\command.com".
3690 * When the "c:\\" is left out it works OK...? */
3691 if (mch_windows95()
3692 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3693 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3694 cmd += 3;
3695
3696 /* Now, run the command */
3697 CreateProcess(NULL, /* Executable name */
3698 cmd, /* Command to execute */
3699 NULL, /* Process security attributes */
3700 NULL, /* Thread security attributes */
3701 FALSE, /* Inherit handles */
3702 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3703 CREATE_NEW_CONSOLE,
3704 NULL, /* Environment */
3705 NULL, /* Current directory */
3706 &si, /* Startup information */
3707 &pi); /* Process information */
3708
3709
3710 /* Wait for the command to terminate before continuing */
3711 if (g_PlatformId != VER_PLATFORM_WIN32s)
3712 {
3713#ifdef FEAT_GUI
3714 int delay = 1;
3715
3716 /* Keep updating the window while waiting for the shell to finish. */
3717 for (;;)
3718 {
3719 MSG msg;
3720
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003721 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003722 {
3723 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003724 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003725 delay = 1;
3726 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727 }
3728 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3729 break;
3730
3731 /* We start waiting for a very short time and then increase it, so
3732 * that we respond quickly when the process is quick, and don't
3733 * consume too much overhead when it's slow. */
3734 if (delay < 50)
3735 delay += 10;
3736 }
3737#else
3738 WaitForSingleObject(pi.hProcess, INFINITE);
3739#endif
3740
3741 /* Get the command exit code */
3742 GetExitCodeProcess(pi.hProcess, &ret);
3743 }
3744 else
3745 {
3746 /*
3747 * This ugly code is the only quick way of performing
3748 * a synchronous spawn under Win32s. Yuk.
3749 */
3750 num_windows = 0;
3751 EnumWindows(win32ssynch_cb, 0);
3752 old_num_windows = num_windows;
3753 do
3754 {
3755 Sleep(1000);
3756 num_windows = 0;
3757 EnumWindows(win32ssynch_cb, 0);
3758 } while (num_windows == old_num_windows);
3759 ret = 0;
3760 }
3761
3762 /* Close the handles to the subprocess, so that it goes away */
3763 CloseHandle(pi.hThread);
3764 CloseHandle(pi.hProcess);
3765
3766 /* Try to get input focus back. Doesn't always work though. */
3767 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3768
3769 return ret;
3770}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003771
3772/*
3773 * Thread launched by the gui to send the current buffer data to the
3774 * process. This way avoid to hang up vim totally if the children
3775 * process take a long time to process the lines.
3776 */
3777 static DWORD WINAPI
3778sub_process_writer(LPVOID param)
3779{
3780 HANDLE g_hChildStd_IN_Wr = param;
3781 linenr_T lnum = curbuf->b_op_start.lnum;
3782 DWORD len = 0;
3783 DWORD l;
3784 char_u *lp = ml_get(lnum);
3785 char_u *s;
3786 int written = 0;
3787
3788 for (;;)
3789 {
3790 l = (DWORD)STRLEN(lp + written);
3791 if (l == 0)
3792 len = 0;
3793 else if (lp[written] == NL)
3794 {
3795 /* NL -> NUL translation */
3796 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3797 }
3798 else
3799 {
3800 s = vim_strchr(lp + written, NL);
3801 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3802 s == NULL ? l : (DWORD)(s - (lp + written)),
3803 &len, NULL);
3804 }
3805 if (len == (int)l)
3806 {
3807 /* Finished a line, add a NL, unless this line should not have
3808 * one. */
3809 if (lnum != curbuf->b_op_end.lnum
3810 || !curbuf->b_p_bin
3811 || (lnum != curbuf->b_no_eol_lnum
3812 && (lnum != curbuf->b_ml.ml_line_count
3813 || curbuf->b_p_eol)))
3814 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01003815 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003816 }
3817
3818 ++lnum;
3819 if (lnum > curbuf->b_op_end.lnum)
3820 break;
3821
3822 lp = ml_get(lnum);
3823 written = 0;
3824 }
3825 else if (len > 0)
3826 written += len;
3827 }
3828
3829 /* finished all the lines, close pipe */
3830 CloseHandle(g_hChildStd_IN_Wr);
3831 ExitThread(0);
3832}
3833
3834
3835# define BUFLEN 100 /* length for buffer, stolen from unix version */
3836
3837/*
3838 * This function read from the children's stdout and write the
3839 * data on screen or in the buffer accordingly.
3840 */
3841 static void
3842dump_pipe(int options,
3843 HANDLE g_hChildStd_OUT_Rd,
3844 garray_T *ga,
3845 char_u buffer[],
3846 DWORD *buffer_off)
3847{
3848 DWORD availableBytes = 0;
3849 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003850 int ret;
3851 DWORD len;
3852 DWORD toRead;
3853 int repeatCount;
3854
3855 /* we query the pipe to see if there is any data to read
3856 * to avoid to perform a blocking read */
3857 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3858 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003859 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003860 NULL, /* number of read bytes */
3861 &availableBytes, /* available bytes total */
3862 NULL); /* byteLeft */
3863
3864 repeatCount = 0;
3865 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003866 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003867 {
3868 repeatCount++;
3869 toRead =
3870# ifdef FEAT_MBYTE
3871 (DWORD)(BUFLEN - *buffer_off);
3872# else
3873 (DWORD)BUFLEN;
3874# endif
3875 toRead = availableBytes < toRead ? availableBytes : toRead;
3876 ReadFile(g_hChildStd_OUT_Rd, buffer
3877# ifdef FEAT_MBYTE
3878 + *buffer_off, toRead
3879# else
3880 , toRead
3881# endif
3882 , &len, NULL);
3883
3884 /* If we haven't read anything, there is a problem */
3885 if (len == 0)
3886 break;
3887
3888 availableBytes -= len;
3889
3890 if (options & SHELL_READ)
3891 {
3892 /* Do NUL -> NL translation, append NL separated
3893 * lines to the current buffer. */
3894 for (i = 0; i < len; ++i)
3895 {
3896 if (buffer[i] == NL)
3897 append_ga_line(ga);
3898 else if (buffer[i] == NUL)
3899 ga_append(ga, NL);
3900 else
3901 ga_append(ga, buffer[i]);
3902 }
3903 }
3904# ifdef FEAT_MBYTE
3905 else if (has_mbyte)
3906 {
3907 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003908 int c;
3909 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003910
3911 len += *buffer_off;
3912 buffer[len] = NUL;
3913
3914 /* Check if the last character in buffer[] is
3915 * incomplete, keep these bytes for the next
3916 * round. */
3917 for (p = buffer; p < buffer + len; p += l)
3918 {
3919 l = mb_cptr2len(p);
3920 if (l == 0)
3921 l = 1; /* NUL byte? */
3922 else if (MB_BYTE2LEN(*p) != l)
3923 break;
3924 }
3925 if (p == buffer) /* no complete character */
3926 {
3927 /* avoid getting stuck at an illegal byte */
3928 if (len >= 12)
3929 ++p;
3930 else
3931 {
3932 *buffer_off = len;
3933 return;
3934 }
3935 }
3936 c = *p;
3937 *p = NUL;
3938 msg_puts(buffer);
3939 if (p < buffer + len)
3940 {
3941 *p = c;
3942 *buffer_off = (DWORD)((buffer + len) - p);
3943 mch_memmove(buffer, p, *buffer_off);
3944 return;
3945 }
3946 *buffer_off = 0;
3947 }
3948# endif /* FEAT_MBYTE */
3949 else
3950 {
3951 buffer[len] = NUL;
3952 msg_puts(buffer);
3953 }
3954
3955 windgoto(msg_row, msg_col);
3956 cursor_on();
3957 out_flush();
3958 }
3959}
3960
3961/*
3962 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
3963 * for communication and doesn't open any new window.
3964 */
3965 static int
3966mch_system_piped(char *cmd, int options)
3967{
3968 STARTUPINFO si;
3969 PROCESS_INFORMATION pi;
3970 DWORD ret = 0;
3971
3972 HANDLE g_hChildStd_IN_Rd = NULL;
3973 HANDLE g_hChildStd_IN_Wr = NULL;
3974 HANDLE g_hChildStd_OUT_Rd = NULL;
3975 HANDLE g_hChildStd_OUT_Wr = NULL;
3976
3977 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
3978 DWORD len;
3979
3980 /* buffer used to receive keys */
3981 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3982 int ta_len = 0; /* valid bytes in ta_buf[] */
3983
3984 DWORD i;
3985 int c;
3986 int noread_cnt = 0;
3987 garray_T ga;
3988 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003989 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003990 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003991
3992 SECURITY_ATTRIBUTES saAttr;
3993
3994 /* Set the bInheritHandle flag so pipe handles are inherited. */
3995 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
3996 saAttr.bInheritHandle = TRUE;
3997 saAttr.lpSecurityDescriptor = NULL;
3998
3999 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4000 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
4001 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
4002 /* Create a pipe for the child process's STDIN. */
4003 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4004 /* Ensure the write handle to the pipe for STDIN is not inherited. */
4005 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
4006 {
4007 CloseHandle(g_hChildStd_IN_Rd);
4008 CloseHandle(g_hChildStd_IN_Wr);
4009 CloseHandle(g_hChildStd_OUT_Rd);
4010 CloseHandle(g_hChildStd_OUT_Wr);
4011 MSG_PUTS(_("\nCannot create pipes\n"));
4012 }
4013
4014 si.cb = sizeof(si);
4015 si.lpReserved = NULL;
4016 si.lpDesktop = NULL;
4017 si.lpTitle = NULL;
4018 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4019
4020 /* set-up our file redirection */
4021 si.hStdError = g_hChildStd_OUT_Wr;
4022 si.hStdOutput = g_hChildStd_OUT_Wr;
4023 si.hStdInput = g_hChildStd_IN_Rd;
4024 si.wShowWindow = SW_HIDE;
4025 si.cbReserved2 = 0;
4026 si.lpReserved2 = NULL;
4027
4028 if (options & SHELL_READ)
4029 ga_init2(&ga, 1, BUFLEN);
4030
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004031 if (cmd != NULL)
4032 {
4033 p = (char *)vim_strsave((char_u *)cmd);
4034 if (p != NULL)
4035 unescape_shellxquote((char_u *)p, p_sxe);
4036 else
4037 p = cmd;
4038 }
4039
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004040 /* Now, run the command */
4041 CreateProcess(NULL, /* Executable name */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004042 p, /* Command to execute */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004043 NULL, /* Process security attributes */
4044 NULL, /* Thread security attributes */
4045
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004046 // this command can be litigious, handle inheritance was
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004047 // deactivated for pending temp file, but, if we deactivate
4048 // it, the pipes don't work for some reason.
4049 TRUE, /* Inherit handles, first deactivated,
4050 * but needed */
4051 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
4052 NULL, /* Environment */
4053 NULL, /* Current directory */
4054 &si, /* Startup information */
4055 &pi); /* Process information */
4056
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004057 if (p != cmd)
4058 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004059
4060 /* Close our unused side of the pipes */
4061 CloseHandle(g_hChildStd_IN_Rd);
4062 CloseHandle(g_hChildStd_OUT_Wr);
4063
4064 if (options & SHELL_WRITE)
4065 {
4066 HANDLE thread =
4067 CreateThread(NULL, /* security attributes */
4068 0, /* default stack size */
4069 sub_process_writer, /* function to be executed */
4070 g_hChildStd_IN_Wr, /* parameter */
4071 0, /* creation flag, start immediately */
4072 NULL); /* we don't care about thread id */
4073 CloseHandle(thread);
4074 g_hChildStd_IN_Wr = NULL;
4075 }
4076
4077 /* Keep updating the window while waiting for the shell to finish. */
4078 for (;;)
4079 {
4080 MSG msg;
4081
4082 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4083 {
4084 TranslateMessage(&msg);
4085 DispatchMessage(&msg);
4086 }
4087
4088 /* write pipe information in the window */
4089 if ((options & (SHELL_READ|SHELL_WRITE))
4090# ifdef FEAT_GUI
4091 || gui.in_use
4092# endif
4093 )
4094 {
4095 len = 0;
4096 if (!(options & SHELL_EXPAND)
4097 && ((options &
4098 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4099 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4100# ifdef FEAT_GUI
4101 || gui.in_use
4102# endif
4103 )
4104 && (ta_len > 0 || noread_cnt > 4))
4105 {
4106 if (ta_len == 0)
4107 {
4108 /* Get extra characters when we don't have any. Reset the
4109 * counter and timer. */
4110 noread_cnt = 0;
4111# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4112 gettimeofday(&start_tv, NULL);
4113# endif
4114 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4115 }
4116 if (ta_len > 0 || len > 0)
4117 {
4118 /*
4119 * For pipes: Check for CTRL-C: send interrupt signal to
4120 * child. Check for CTRL-D: EOF, close pipe to child.
4121 */
4122 if (len == 1 && cmd != NULL)
4123 {
4124 if (ta_buf[ta_len] == Ctrl_C)
4125 {
4126 /* Learn what exit code is expected, for
4127 * now put 9 as SIGKILL */
4128 TerminateProcess(pi.hProcess, 9);
4129 }
4130 if (ta_buf[ta_len] == Ctrl_D)
4131 {
4132 CloseHandle(g_hChildStd_IN_Wr);
4133 g_hChildStd_IN_Wr = NULL;
4134 }
4135 }
4136
4137 /* replace K_BS by <BS> and K_DEL by <DEL> */
4138 for (i = ta_len; i < ta_len + len; ++i)
4139 {
4140 if (ta_buf[i] == CSI && len - i > 2)
4141 {
4142 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4143 if (c == K_DEL || c == K_KDEL || c == K_BS)
4144 {
4145 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4146 (size_t)(len - i - 2));
4147 if (c == K_DEL || c == K_KDEL)
4148 ta_buf[i] = DEL;
4149 else
4150 ta_buf[i] = Ctrl_H;
4151 len -= 2;
4152 }
4153 }
4154 else if (ta_buf[i] == '\r')
4155 ta_buf[i] = '\n';
4156# ifdef FEAT_MBYTE
4157 if (has_mbyte)
4158 i += (*mb_ptr2len_len)(ta_buf + i,
4159 ta_len + len - i) - 1;
4160# endif
4161 }
4162
4163 /*
4164 * For pipes: echo the typed characters. For a pty this
4165 * does not seem to work.
4166 */
4167 for (i = ta_len; i < ta_len + len; ++i)
4168 {
4169 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4170 msg_putchar(ta_buf[i]);
4171# ifdef FEAT_MBYTE
4172 else if (has_mbyte)
4173 {
4174 int l = (*mb_ptr2len)(ta_buf + i);
4175
4176 msg_outtrans_len(ta_buf + i, l);
4177 i += l - 1;
4178 }
4179# endif
4180 else
4181 msg_outtrans_len(ta_buf + i, 1);
4182 }
4183 windgoto(msg_row, msg_col);
4184 out_flush();
4185
4186 ta_len += len;
4187
4188 /*
4189 * Write the characters to the child, unless EOF has been
4190 * typed for pipes. Write one character at a time, to
4191 * avoid losing too much typeahead. When writing buffer
4192 * lines, drop the typed characters (only check for
4193 * CTRL-C).
4194 */
4195 if (options & SHELL_WRITE)
4196 ta_len = 0;
4197 else if (g_hChildStd_IN_Wr != NULL)
4198 {
4199 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4200 1, &len, NULL);
4201 // if we are typing in, we want to keep things reactive
4202 delay = 1;
4203 if (len > 0)
4204 {
4205 ta_len -= len;
4206 mch_memmove(ta_buf, ta_buf + len, ta_len);
4207 }
4208 }
4209 }
4210 }
4211 }
4212
4213 if (ta_len)
4214 ui_inchar_undo(ta_buf, ta_len);
4215
4216 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4217 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004218 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004219 break;
4220 }
4221
4222 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004223 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004224
4225 /* We start waiting for a very short time and then increase it, so
4226 * that we respond quickly when the process is quick, and don't
4227 * consume too much overhead when it's slow. */
4228 if (delay < 50)
4229 delay += 10;
4230 }
4231
4232 /* Close the pipe */
4233 CloseHandle(g_hChildStd_OUT_Rd);
4234 if (g_hChildStd_IN_Wr != NULL)
4235 CloseHandle(g_hChildStd_IN_Wr);
4236
4237 WaitForSingleObject(pi.hProcess, INFINITE);
4238
4239 /* Get the command exit code */
4240 GetExitCodeProcess(pi.hProcess, &ret);
4241
4242 if (options & SHELL_READ)
4243 {
4244 if (ga.ga_len > 0)
4245 {
4246 append_ga_line(&ga);
4247 /* remember that the NL was missing */
4248 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4249 }
4250 else
4251 curbuf->b_no_eol_lnum = 0;
4252 ga_clear(&ga);
4253 }
4254
4255 /* Close the handles to the subprocess, so that it goes away */
4256 CloseHandle(pi.hThread);
4257 CloseHandle(pi.hProcess);
4258
4259 return ret;
4260}
4261
4262 static int
4263mch_system(char *cmd, int options)
4264{
4265 /* if we can pipe and the shelltemp option is off */
4266 if (allowPiping && !p_stmp)
4267 return mch_system_piped(cmd, options);
4268 else
4269 return mch_system_classic(cmd, options);
4270}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004271#else
4272
4273# define mch_system(c, o) system(c)
4274
4275#endif
4276
4277/*
4278 * Either execute a command by calling the shell or start a new shell
4279 */
4280 int
4281mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004282 char_u *cmd,
4283 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004284{
4285 int x = 0;
4286 int tmode = cur_tmode;
4287#ifdef FEAT_TITLE
4288 char szShellTitle[512];
4289
4290 /* Change the title to reflect that we are in a subshell. */
4291 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
4292 {
4293 if (cmd == NULL)
4294 strcat(szShellTitle, " :sh");
4295 else
4296 {
4297 strcat(szShellTitle, " - !");
4298 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4299 strcat(szShellTitle, cmd);
4300 }
4301 mch_settitle(szShellTitle, NULL);
4302 }
4303#endif
4304
4305 out_flush();
4306
4307#ifdef MCH_WRITE_DUMP
4308 if (fdDump)
4309 {
4310 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4311 fflush(fdDump);
4312 }
4313#endif
4314
4315 /*
4316 * Catch all deadly signals while running the external command, because a
4317 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4318 */
4319 signal(SIGINT, SIG_IGN);
4320#if defined(__GNUC__) && !defined(__MINGW32__)
4321 signal(SIGKILL, SIG_IGN);
4322#else
4323 signal(SIGBREAK, SIG_IGN);
4324#endif
4325 signal(SIGILL, SIG_IGN);
4326 signal(SIGFPE, SIG_IGN);
4327 signal(SIGSEGV, SIG_IGN);
4328 signal(SIGTERM, SIG_IGN);
4329 signal(SIGABRT, SIG_IGN);
4330
4331 if (options & SHELL_COOKED)
4332 settmode(TMODE_COOK); /* set to normal mode */
4333
4334 if (cmd == NULL)
4335 {
4336 x = mch_system(p_sh, options);
4337 }
4338 else
4339 {
4340 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004341 char_u *newcmd = NULL;
4342 char_u *cmdbase = cmd;
4343 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004344
4345 /* Skip a leading ", ( and "(. */
4346 if (*cmdbase == '"' )
4347 ++cmdbase;
4348 if (*cmdbase == '(')
4349 ++cmdbase;
4350
4351 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4352 {
4353 STARTUPINFO si;
4354 PROCESS_INFORMATION pi;
4355 DWORD flags = CREATE_NEW_CONSOLE;
4356 char_u *p;
4357
4358 si.cb = sizeof(si);
4359 si.lpReserved = NULL;
4360 si.lpDesktop = NULL;
4361 si.lpTitle = NULL;
4362 si.dwFlags = 0;
4363 si.cbReserved2 = 0;
4364 si.lpReserved2 = NULL;
4365
4366 cmdbase = skipwhite(cmdbase + 5);
4367 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4368 && vim_iswhite(cmdbase[4]))
4369 {
4370 cmdbase = skipwhite(cmdbase + 4);
4371 si.dwFlags = STARTF_USESHOWWINDOW;
4372 si.wShowWindow = SW_SHOWMINNOACTIVE;
4373 }
4374 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4375 && vim_iswhite(cmdbase[2]))
4376 {
4377 cmdbase = skipwhite(cmdbase + 2);
4378 flags = CREATE_NO_WINDOW;
4379 si.dwFlags = STARTF_USESTDHANDLES;
4380 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004381 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004382 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004383 NULL, // Security att.
4384 OPEN_EXISTING, // Open flags
4385 FILE_ATTRIBUTE_NORMAL, // File att.
4386 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004387 si.hStdOutput = si.hStdInput;
4388 si.hStdError = si.hStdInput;
4389 }
4390
4391 /* Remove a trailing ", ) and )" if they have a match
4392 * at the start of the command. */
4393 if (cmdbase > cmd)
4394 {
4395 p = cmdbase + STRLEN(cmdbase);
4396 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4397 *--p = NUL;
4398 if (p > cmdbase && p[-1] == ')'
4399 && (*cmd =='(' || cmd[1] == '('))
4400 *--p = NUL;
4401 }
4402
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004403 newcmd = cmdbase;
4404 unescape_shellxquote(cmdbase, p_sxe);
4405
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004406 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004407 * If creating new console, arguments are passed to the
4408 * 'cmd.exe' as-is. If it's not, arguments are not treated
4409 * correctly for current 'cmd.exe'. So unescape characters in
4410 * shellxescape except '|' for avoiding to be treated as
4411 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004412 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004413 if (flags != CREATE_NEW_CONSOLE)
4414 {
4415 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004416 char_u *cmd_shell = mch_getenv("COMSPEC");
4417
4418 if (cmd_shell == NULL || *cmd_shell == NUL)
4419 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004420
4421 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4422 if (subcmd != NULL)
4423 {
4424 /* make "cmd.exe /c arguments" */
4425 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004426 newcmd = lalloc(cmdlen, TRUE);
4427 if (newcmd != NULL)
4428 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004429 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004430 else
4431 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004432 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004433 }
4434 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004435
4436 /*
4437 * Now, start the command as a process, so that it doesn't
4438 * inherit our handles which causes unpleasant dangling swap
4439 * files if we exit before the spawned process
4440 */
4441 if (CreateProcess(NULL, // Executable name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004442 newcmd, // Command to execute
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004443 NULL, // Process security attributes
4444 NULL, // Thread security attributes
4445 FALSE, // Inherit handles
4446 flags, // Creation flags
4447 NULL, // Environment
4448 NULL, // Current directory
4449 &si, // Startup information
4450 &pi)) // Process information
4451 x = 0;
4452 else
4453 {
4454 x = -1;
4455#ifdef FEAT_GUI_W32
4456 EMSG(_("E371: Command not found"));
4457#endif
4458 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004459
4460 if (newcmd != cmdbase)
4461 vim_free(newcmd);
4462
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004463 if (si.hStdInput != NULL)
4464 {
4465 /* Close the handle to \\.\NUL */
4466 CloseHandle(si.hStdInput);
4467 }
4468 /* Close the handles to the subprocess, so that it goes away */
4469 CloseHandle(pi.hThread);
4470 CloseHandle(pi.hProcess);
4471 }
4472 else
4473 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004474 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004475#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004476 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004478 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4479
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004480 newcmd = lalloc(cmdlen, TRUE);
4481 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004482 {
4483#if defined(FEAT_GUI_W32)
4484 if (need_vimrun_warning)
4485 {
4486 MessageBox(NULL,
4487 _("VIMRUN.EXE not found in your $PATH.\n"
4488 "External commands will not pause after completion.\n"
4489 "See :help win32-vimrun for more information."),
4490 _("Vim Warning"),
4491 MB_ICONWARNING);
4492 need_vimrun_warning = FALSE;
4493 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004494 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495 /* Use vimrun to execute the command. It opens a console
4496 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004497 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004498 vimrun_path,
4499 (msg_silent != 0 || (options & SHELL_DOOUT))
4500 ? "-s " : "",
4501 p_sh, p_shcf, cmd);
4502 else
4503#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004504 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004505 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004506 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004507 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004508 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004509 }
4510 }
4511
4512 if (tmode == TMODE_RAW)
4513 settmode(TMODE_RAW); /* set to raw mode */
4514
4515 /* Print the return value, unless "vimrun" was used. */
4516 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4517#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004518 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4519 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004520#endif
4521 )
4522 {
4523 smsg(_("shell returned %d"), x);
4524 msg_putchar('\n');
4525 }
4526#ifdef FEAT_TITLE
4527 resettitle();
4528#endif
4529
4530 signal(SIGINT, SIG_DFL);
4531#if defined(__GNUC__) && !defined(__MINGW32__)
4532 signal(SIGKILL, SIG_DFL);
4533#else
4534 signal(SIGBREAK, SIG_DFL);
4535#endif
4536 signal(SIGILL, SIG_DFL);
4537 signal(SIGFPE, SIG_DFL);
4538 signal(SIGSEGV, SIG_DFL);
4539 signal(SIGTERM, SIG_DFL);
4540 signal(SIGABRT, SIG_DFL);
4541
4542 return x;
4543}
4544
4545
4546#ifndef FEAT_GUI_W32
4547
4548/*
4549 * Start termcap mode
4550 */
4551 static void
4552termcap_mode_start(void)
4553{
4554 DWORD cmodein;
4555
4556 if (g_fTermcapMode)
4557 return;
4558
4559 SaveConsoleBuffer(&g_cbNonTermcap);
4560
4561 if (g_cbTermcap.IsValid)
4562 {
4563 /*
4564 * We've been in termcap mode before. Restore certain screen
4565 * characteristics, including the buffer size and the window
4566 * size. Since we will be redrawing the screen, we don't need
4567 * to restore the actual contents of the buffer.
4568 */
4569 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4570 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4571 Rows = g_cbTermcap.Info.dwSize.Y;
4572 Columns = g_cbTermcap.Info.dwSize.X;
4573 }
4574 else
4575 {
4576 /*
4577 * This is our first time entering termcap mode. Clear the console
4578 * screen buffer, and resize the buffer to match the current window
4579 * size. We will use this as the size of our editing environment.
4580 */
4581 ClearConsoleBuffer(g_attrCurrent);
4582 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4583 }
4584
4585#ifdef FEAT_TITLE
4586 resettitle();
4587#endif
4588
4589 GetConsoleMode(g_hConIn, &cmodein);
4590#ifdef FEAT_MOUSE
4591 if (g_fMouseActive)
4592 cmodein |= ENABLE_MOUSE_INPUT;
4593 else
4594 cmodein &= ~ENABLE_MOUSE_INPUT;
4595#endif
4596 cmodein |= ENABLE_WINDOW_INPUT;
4597 SetConsoleMode(g_hConIn, cmodein);
4598
4599 redraw_later_clear();
4600 g_fTermcapMode = TRUE;
4601}
4602
4603
4604/*
4605 * End termcap mode
4606 */
4607 static void
4608termcap_mode_end(void)
4609{
4610 DWORD cmodein;
4611 ConsoleBuffer *cb;
4612 COORD coord;
4613 DWORD dwDummy;
4614
4615 if (!g_fTermcapMode)
4616 return;
4617
4618 SaveConsoleBuffer(&g_cbTermcap);
4619
4620 GetConsoleMode(g_hConIn, &cmodein);
4621 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4622 SetConsoleMode(g_hConIn, cmodein);
4623
4624#ifdef FEAT_RESTORE_ORIG_SCREEN
4625 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4626#else
4627 cb = &g_cbNonTermcap;
4628#endif
4629 RestoreConsoleBuffer(cb, p_rs);
4630 SetConsoleCursorInfo(g_hConOut, &g_cci);
4631
4632 if (p_rs || exiting)
4633 {
4634 /*
4635 * Clear anything that happens to be on the current line.
4636 */
4637 coord.X = 0;
4638 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4639 FillConsoleOutputCharacter(g_hConOut, ' ',
4640 cb->Info.dwSize.X, coord, &dwDummy);
4641 /*
4642 * The following is just for aesthetics. If we are exiting without
4643 * restoring the screen, then we want to have a prompt string
4644 * appear at the bottom line. However, the command interpreter
4645 * seems to always advance the cursor one line before displaying
4646 * the prompt string, which causes the screen to scroll. To
4647 * counter this, move the cursor up one line before exiting.
4648 */
4649 if (exiting && !p_rs)
4650 coord.Y--;
4651 /*
4652 * Position the cursor at the leftmost column of the desired row.
4653 */
4654 SetConsoleCursorPosition(g_hConOut, coord);
4655 }
4656
4657 g_fTermcapMode = FALSE;
4658}
4659#endif /* FEAT_GUI_W32 */
4660
4661
4662#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004663/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664 void
4665mch_write(
4666 char_u *s,
4667 int len)
4668{
4669 /* never used */
4670}
4671
4672#else
4673
4674/*
4675 * clear `n' chars, starting from `coord'
4676 */
4677 static void
4678clear_chars(
4679 COORD coord,
4680 DWORD n)
4681{
4682 DWORD dwDummy;
4683
4684 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4685 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4686}
4687
4688
4689/*
4690 * Clear the screen
4691 */
4692 static void
4693clear_screen(void)
4694{
4695 g_coord.X = g_coord.Y = 0;
4696 clear_chars(g_coord, Rows * Columns);
4697}
4698
4699
4700/*
4701 * Clear to end of display
4702 */
4703 static void
4704clear_to_end_of_display(void)
4705{
4706 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4707 * Columns + (Columns - g_coord.X));
4708}
4709
4710
4711/*
4712 * Clear to end of line
4713 */
4714 static void
4715clear_to_end_of_line(void)
4716{
4717 clear_chars(g_coord, Columns - g_coord.X);
4718}
4719
4720
4721/*
4722 * Scroll the scroll region up by `cLines' lines
4723 */
4724 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004725scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004726{
4727 COORD oldcoord = g_coord;
4728
4729 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4730 delete_lines(cLines);
4731
4732 g_coord = oldcoord;
4733}
4734
4735
4736/*
4737 * Set the scroll region
4738 */
4739 static void
4740set_scroll_region(
4741 unsigned left,
4742 unsigned top,
4743 unsigned right,
4744 unsigned bottom)
4745{
4746 if (left >= right
4747 || top >= bottom
4748 || right > (unsigned) Columns - 1
4749 || bottom > (unsigned) Rows - 1)
4750 return;
4751
4752 g_srScrollRegion.Left = left;
4753 g_srScrollRegion.Top = top;
4754 g_srScrollRegion.Right = right;
4755 g_srScrollRegion.Bottom = bottom;
4756}
4757
4758
4759/*
4760 * Insert `cLines' lines at the current cursor position
4761 */
4762 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004763insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004764{
4765 SMALL_RECT source;
4766 COORD dest;
4767 CHAR_INFO fill;
4768
4769 dest.X = 0;
4770 dest.Y = g_coord.Y + cLines;
4771
4772 source.Left = 0;
4773 source.Top = g_coord.Y;
4774 source.Right = g_srScrollRegion.Right;
4775 source.Bottom = g_srScrollRegion.Bottom - cLines;
4776
4777 fill.Char.AsciiChar = ' ';
4778 fill.Attributes = g_attrCurrent;
4779
4780 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4781
4782 /* Here we have to deal with a win32 console flake: If the scroll
4783 * region looks like abc and we scroll c to a and fill with d we get
4784 * cbd... if we scroll block c one line at a time to a, we get cdd...
4785 * vim expects cdd consistently... So we have to deal with that
4786 * here... (this also occurs scrolling the same way in the other
4787 * direction). */
4788
4789 if (source.Bottom < dest.Y)
4790 {
4791 COORD coord;
4792
4793 coord.X = 0;
4794 coord.Y = source.Bottom;
4795 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4796 }
4797}
4798
4799
4800/*
4801 * Delete `cLines' lines at the current cursor position
4802 */
4803 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004804delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004805{
4806 SMALL_RECT source;
4807 COORD dest;
4808 CHAR_INFO fill;
4809 int nb;
4810
4811 dest.X = 0;
4812 dest.Y = g_coord.Y;
4813
4814 source.Left = 0;
4815 source.Top = g_coord.Y + cLines;
4816 source.Right = g_srScrollRegion.Right;
4817 source.Bottom = g_srScrollRegion.Bottom;
4818
4819 fill.Char.AsciiChar = ' ';
4820 fill.Attributes = g_attrCurrent;
4821
4822 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4823
4824 /* Here we have to deal with a win32 console flake: If the scroll
4825 * region looks like abc and we scroll c to a and fill with d we get
4826 * cbd... if we scroll block c one line at a time to a, we get cdd...
4827 * vim expects cdd consistently... So we have to deal with that
4828 * here... (this also occurs scrolling the same way in the other
4829 * direction). */
4830
4831 nb = dest.Y + (source.Bottom - source.Top) + 1;
4832
4833 if (nb < source.Top)
4834 {
4835 COORD coord;
4836
4837 coord.X = 0;
4838 coord.Y = nb;
4839 clear_chars(coord, Columns * (source.Top - nb));
4840 }
4841}
4842
4843
4844/*
4845 * Set the cursor position
4846 */
4847 static void
4848gotoxy(
4849 unsigned x,
4850 unsigned y)
4851{
4852 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4853 return;
4854
4855 /* external cursor coords are 1-based; internal are 0-based */
4856 g_coord.X = x - 1;
4857 g_coord.Y = y - 1;
4858 SetConsoleCursorPosition(g_hConOut, g_coord);
4859}
4860
4861
4862/*
4863 * Set the current text attribute = (foreground | background)
4864 * See ../doc/os_win32.txt for the numbers.
4865 */
4866 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004867textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868{
4869 g_attrCurrent = wAttr;
4870
4871 SetConsoleTextAttribute(g_hConOut, wAttr);
4872}
4873
4874
4875 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004876textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004877{
4878 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
4879
4880 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4881}
4882
4883
4884 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004885textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886{
4887 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
4888
4889 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4890}
4891
4892
4893/*
4894 * restore the default text attribute (whatever we started with)
4895 */
4896 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004897normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004898{
4899 textattr(g_attrDefault);
4900}
4901
4902
4903static WORD g_attrPreStandout = 0;
4904
4905/*
4906 * Make the text standout, by brightening it
4907 */
4908 static void
4909standout(void)
4910{
4911 g_attrPreStandout = g_attrCurrent;
4912 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
4913}
4914
4915
4916/*
4917 * Turn off standout mode
4918 */
4919 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004920standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921{
4922 if (g_attrPreStandout)
4923 {
4924 textattr(g_attrPreStandout);
4925 g_attrPreStandout = 0;
4926 }
4927}
4928
4929
4930/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00004931 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004932 */
4933 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004934mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004935{
4936 char_u *p;
4937 int n;
4938
4939 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
4940 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
4941 if (T_ME[0] == ESC && T_ME[1] == '|')
4942 {
4943 p = T_ME + 2;
4944 n = getdigits(&p);
4945 if (*p == 'm' && n > 0)
4946 {
4947 cterm_normal_fg_color = (n & 0xf) + 1;
4948 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
4949 }
4950 }
4951}
4952
4953
4954/*
4955 * visual bell: flash the screen
4956 */
4957 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004958visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004959{
4960 COORD coordOrigin = {0, 0};
4961 WORD attrFlash = ~g_attrCurrent & 0xff;
4962
4963 DWORD dwDummy;
4964 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
4965
4966 if (oldattrs == NULL)
4967 return;
4968 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4969 coordOrigin, &dwDummy);
4970 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
4971 coordOrigin, &dwDummy);
4972
4973 Sleep(15); /* wait for 15 msec */
4974 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4975 coordOrigin, &dwDummy);
4976 vim_free(oldattrs);
4977}
4978
4979
4980/*
4981 * Make the cursor visible or invisible
4982 */
4983 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004984cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004985{
4986 s_cursor_visible = fVisible;
4987#ifdef MCH_CURSOR_SHAPE
4988 mch_update_cursor();
4989#endif
4990}
4991
4992
4993/*
4994 * write `cchToWrite' characters in `pchBuf' to the screen
4995 * Returns the number of characters actually written (at least one).
4996 */
4997 static BOOL
4998write_chars(
4999 LPCSTR pchBuf,
5000 DWORD cchToWrite)
5001{
5002 COORD coord = g_coord;
5003 DWORD written;
5004
5005 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
5006 coord, &written);
5007 /* When writing fails or didn't write a single character, pretend one
5008 * character was written, otherwise we get stuck. */
5009 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
5010 coord, &written) == 0
5011 || written == 0)
5012 written = 1;
5013
5014 g_coord.X += (SHORT) written;
5015
5016 while (g_coord.X > g_srScrollRegion.Right)
5017 {
5018 g_coord.X -= (SHORT) Columns;
5019 if (g_coord.Y < g_srScrollRegion.Bottom)
5020 g_coord.Y++;
5021 }
5022
5023 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5024
5025 return written;
5026}
5027
5028
5029/*
5030 * mch_write(): write the output buffer to the screen, translating ESC
5031 * sequences into calls to console output routines.
5032 */
5033 void
5034mch_write(
5035 char_u *s,
5036 int len)
5037{
5038 s[len] = NUL;
5039
5040 if (!term_console)
5041 {
5042 write(1, s, (unsigned)len);
5043 return;
5044 }
5045
5046 /* translate ESC | sequences into faked bios calls */
5047 while (len--)
5048 {
5049 /* optimization: use one single write_chars for runs of text,
5050 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005051 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005052
5053 if (p_wd)
5054 {
5055 WaitForChar(p_wd);
5056 if (prefix != 0)
5057 prefix = 1;
5058 }
5059
5060 if (prefix != 0)
5061 {
5062 DWORD nWritten;
5063
5064 nWritten = write_chars(s, prefix);
5065#ifdef MCH_WRITE_DUMP
5066 if (fdDump)
5067 {
5068 fputc('>', fdDump);
5069 fwrite(s, sizeof(char_u), nWritten, fdDump);
5070 fputs("<\n", fdDump);
5071 }
5072#endif
5073 len -= (nWritten - 1);
5074 s += nWritten;
5075 }
5076 else if (s[0] == '\n')
5077 {
5078 /* \n, newline: go to the beginning of the next line or scroll */
5079 if (g_coord.Y == g_srScrollRegion.Bottom)
5080 {
5081 scroll(1);
5082 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5083 }
5084 else
5085 {
5086 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5087 }
5088#ifdef MCH_WRITE_DUMP
5089 if (fdDump)
5090 fputs("\\n\n", fdDump);
5091#endif
5092 s++;
5093 }
5094 else if (s[0] == '\r')
5095 {
5096 /* \r, carriage return: go to beginning of line */
5097 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5098#ifdef MCH_WRITE_DUMP
5099 if (fdDump)
5100 fputs("\\r\n", fdDump);
5101#endif
5102 s++;
5103 }
5104 else if (s[0] == '\b')
5105 {
5106 /* \b, backspace: move cursor one position left */
5107 if (g_coord.X > g_srScrollRegion.Left)
5108 g_coord.X--;
5109 else if (g_coord.Y > g_srScrollRegion.Top)
5110 {
5111 g_coord.X = g_srScrollRegion.Right;
5112 g_coord.Y--;
5113 }
5114 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5115#ifdef MCH_WRITE_DUMP
5116 if (fdDump)
5117 fputs("\\b\n", fdDump);
5118#endif
5119 s++;
5120 }
5121 else if (s[0] == '\a')
5122 {
5123 /* \a, bell */
5124 MessageBeep(0xFFFFFFFF);
5125#ifdef MCH_WRITE_DUMP
5126 if (fdDump)
5127 fputs("\\a\n", fdDump);
5128#endif
5129 s++;
5130 }
5131 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5132 {
5133#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005134 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005135#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005136 char_u *p;
5137 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005138
5139 switch (s[2])
5140 {
5141 /* one or two numeric arguments, separated by ';' */
5142
5143 case '0': case '1': case '2': case '3': case '4':
5144 case '5': case '6': case '7': case '8': case '9':
5145 p = s + 2;
5146 arg1 = getdigits(&p); /* no check for length! */
5147 if (p > s + len)
5148 break;
5149
5150 if (*p == ';')
5151 {
5152 ++p;
5153 arg2 = getdigits(&p); /* no check for length! */
5154 if (p > s + len)
5155 break;
5156
5157 if (*p == 'H')
5158 gotoxy(arg2, arg1);
5159 else if (*p == 'r')
5160 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5161 }
5162 else if (*p == 'A')
5163 {
5164 /* move cursor up arg1 lines in same column */
5165 gotoxy(g_coord.X + 1,
5166 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5167 }
5168 else if (*p == 'C')
5169 {
5170 /* move cursor right arg1 columns in same line */
5171 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5172 g_coord.Y + 1);
5173 }
5174 else if (*p == 'H')
5175 {
5176 gotoxy(1, arg1);
5177 }
5178 else if (*p == 'L')
5179 {
5180 insert_lines(arg1);
5181 }
5182 else if (*p == 'm')
5183 {
5184 if (arg1 == 0)
5185 normvideo();
5186 else
5187 textattr((WORD) arg1);
5188 }
5189 else if (*p == 'f')
5190 {
5191 textcolor((WORD) arg1);
5192 }
5193 else if (*p == 'b')
5194 {
5195 textbackground((WORD) arg1);
5196 }
5197 else if (*p == 'M')
5198 {
5199 delete_lines(arg1);
5200 }
5201
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005202 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005203 s = p + 1;
5204 break;
5205
5206
5207 /* Three-character escape sequences */
5208
5209 case 'A':
5210 /* move cursor up one line in same column */
5211 gotoxy(g_coord.X + 1,
5212 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5213 goto got3;
5214
5215 case 'B':
5216 visual_bell();
5217 goto got3;
5218
5219 case 'C':
5220 /* move cursor right one column in same line */
5221 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5222 g_coord.Y + 1);
5223 goto got3;
5224
5225 case 'E':
5226 termcap_mode_end();
5227 goto got3;
5228
5229 case 'F':
5230 standout();
5231 goto got3;
5232
5233 case 'f':
5234 standend();
5235 goto got3;
5236
5237 case 'H':
5238 gotoxy(1, 1);
5239 goto got3;
5240
5241 case 'j':
5242 clear_to_end_of_display();
5243 goto got3;
5244
5245 case 'J':
5246 clear_screen();
5247 goto got3;
5248
5249 case 'K':
5250 clear_to_end_of_line();
5251 goto got3;
5252
5253 case 'L':
5254 insert_lines(1);
5255 goto got3;
5256
5257 case 'M':
5258 delete_lines(1);
5259 goto got3;
5260
5261 case 'S':
5262 termcap_mode_start();
5263 goto got3;
5264
5265 case 'V':
5266 cursor_visible(TRUE);
5267 goto got3;
5268
5269 case 'v':
5270 cursor_visible(FALSE);
5271 goto got3;
5272
5273 got3:
5274 s += 3;
5275 len -= 2;
5276 }
5277
5278#ifdef MCH_WRITE_DUMP
5279 if (fdDump)
5280 {
5281 fputs("ESC | ", fdDump);
5282 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5283 fputc('\n', fdDump);
5284 }
5285#endif
5286 }
5287 else
5288 {
5289 /* Write a single character */
5290 DWORD nWritten;
5291
5292 nWritten = write_chars(s, 1);
5293#ifdef MCH_WRITE_DUMP
5294 if (fdDump)
5295 {
5296 fputc('>', fdDump);
5297 fwrite(s, sizeof(char_u), nWritten, fdDump);
5298 fputs("<\n", fdDump);
5299 }
5300#endif
5301
5302 len -= (nWritten - 1);
5303 s += nWritten;
5304 }
5305 }
5306
5307#ifdef MCH_WRITE_DUMP
5308 if (fdDump)
5309 fflush(fdDump);
5310#endif
5311}
5312
5313#endif /* FEAT_GUI_W32 */
5314
5315
5316/*
5317 * Delay for half a second.
5318 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005319/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005320 void
5321mch_delay(
5322 long msec,
5323 int ignoreinput)
5324{
5325#ifdef FEAT_GUI_W32
5326 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005327#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005328 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005329# ifdef FEAT_MZSCHEME
5330 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5331 {
5332 int towait = p_mzq;
5333
5334 /* if msec is large enough, wait by portions in p_mzq */
5335 while (msec > 0)
5336 {
5337 mzvim_check_threads();
5338 if (msec < towait)
5339 towait = msec;
5340 Sleep(towait);
5341 msec -= towait;
5342 }
5343 }
5344 else
5345# endif
5346 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005347 else
5348 WaitForChar(msec);
5349#endif
5350}
5351
5352
5353/*
5354 * this version of remove is not scared by a readonly (backup) file
5355 * Return 0 for success, -1 for failure.
5356 */
5357 int
5358mch_remove(char_u *name)
5359{
5360#ifdef FEAT_MBYTE
5361 WCHAR *wn = NULL;
5362 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005363#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005364
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005365 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5366
5367#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005368 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5369 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005370 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005371 if (wn != NULL)
5372 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005373 n = DeleteFileW(wn) ? 0 : -1;
5374 vim_free(wn);
5375 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5376 return n;
5377 /* Retry with non-wide function (for Windows 98). */
5378 }
5379 }
5380#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005381 return DeleteFile(name) ? 0 : -1;
5382}
5383
5384
5385/*
5386 * check for an "interrupt signal": CTRL-break or CTRL-C
5387 */
5388 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005389mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005390{
5391#ifndef FEAT_GUI_W32 /* never used */
5392 if (g_fCtrlCPressed || g_fCBrkPressed)
5393 {
5394 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5395 got_int = TRUE;
5396 }
5397#endif
5398}
5399
5400
Bram Moolenaar071d4272004-06-13 20:20:40 +00005401#ifdef FEAT_MBYTE
5402/*
5403 * Same code as below, but with wide functions and no comments.
5404 * Return 0 for success, non-zero for failure.
5405 */
5406 int
5407mch_wrename(WCHAR *wold, WCHAR *wnew)
5408{
5409 WCHAR *p;
5410 int i;
5411 WCHAR szTempFile[_MAX_PATH + 1];
5412 WCHAR szNewPath[_MAX_PATH + 1];
5413 HANDLE hf;
5414
5415 if (!mch_windows95())
5416 {
5417 p = wold;
5418 for (i = 0; wold[i] != NUL; ++i)
5419 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5420 && wold[i + 1] != 0)
5421 p = wold + i + 1;
5422 if ((int)(wold + i - p) < 8 || p[6] != '~')
5423 return (MoveFileW(wold, wnew) == 0);
5424 }
5425
5426 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5427 return -1;
5428 *p = NUL;
5429
5430 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5431 return -2;
5432
5433 if (!DeleteFileW(szTempFile))
5434 return -3;
5435
5436 if (!MoveFileW(wold, szTempFile))
5437 return -4;
5438
5439 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5440 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5441 return -5;
5442 if (!CloseHandle(hf))
5443 return -6;
5444
5445 if (!MoveFileW(szTempFile, wnew))
5446 {
5447 (void)MoveFileW(szTempFile, wold);
5448 return -7;
5449 }
5450
5451 DeleteFileW(szTempFile);
5452
5453 if (!DeleteFileW(wold))
5454 return -8;
5455
5456 return 0;
5457}
5458#endif
5459
5460
5461/*
5462 * mch_rename() works around a bug in rename (aka MoveFile) in
5463 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5464 * file whose short file name is "FOO.BAR" (its long file name will
5465 * be correct: "foo.bar~"). Because a file can be accessed by
5466 * either its SFN or its LFN, "foo.bar" has effectively been
5467 * renamed to "foo.bar", which is not at all what was wanted. This
5468 * seems to happen only when renaming files with three-character
5469 * extensions by appending a suffix that does not include ".".
5470 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5471 *
5472 * There is another problem, which isn't really a bug but isn't right either:
5473 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5474 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5475 * service pack 6. Doesn't seem to happen on Windows 98.
5476 *
5477 * Like rename(), returns 0 upon success, non-zero upon failure.
5478 * Should probably set errno appropriately when errors occur.
5479 */
5480 int
5481mch_rename(
5482 const char *pszOldFile,
5483 const char *pszNewFile)
5484{
5485 char szTempFile[_MAX_PATH+1];
5486 char szNewPath[_MAX_PATH+1];
5487 char *pszFilePart;
5488 HANDLE hf;
5489#ifdef FEAT_MBYTE
5490 WCHAR *wold = NULL;
5491 WCHAR *wnew = NULL;
5492 int retval = -1;
5493
5494 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5495 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005496 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5497 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498 if (wold != NULL && wnew != NULL)
5499 retval = mch_wrename(wold, wnew);
5500 vim_free(wold);
5501 vim_free(wnew);
5502 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5503 return retval;
5504 /* Retry with non-wide function (for Windows 98). */
5505 }
5506#endif
5507
5508 /*
5509 * No need to play tricks if not running Windows 95, unless the file name
5510 * contains a "~" as the seventh character.
5511 */
5512 if (!mch_windows95())
5513 {
5514 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5515 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5516 return rename(pszOldFile, pszNewFile);
5517 }
5518
5519 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5520 * a directory, no error is returned and pszFilePart will be NULL. */
5521 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5522 || pszFilePart == NULL)
5523 return -1;
5524 *pszFilePart = NUL;
5525
5526 /* Get (and create) a unique temporary file name in directory of new file */
5527 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5528 return -2;
5529
5530 /* blow the temp file away */
5531 if (!DeleteFile(szTempFile))
5532 return -3;
5533
5534 /* rename old file to the temp file */
5535 if (!MoveFile(pszOldFile, szTempFile))
5536 return -4;
5537
5538 /* now create an empty file called pszOldFile; this prevents the operating
5539 * system using pszOldFile as an alias (SFN) if we're renaming within the
5540 * same directory. For example, we're editing a file called
5541 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5542 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5543 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005544 * cause all sorts of problems later in buf_write(). So, we create an
5545 * empty file called filena~1.txt and the system will have to find some
5546 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547 */
5548 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5549 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5550 return -5;
5551 if (!CloseHandle(hf))
5552 return -6;
5553
5554 /* rename the temp file to the new file */
5555 if (!MoveFile(szTempFile, pszNewFile))
5556 {
5557 /* Renaming failed. Rename the file back to its old name, so that it
5558 * looks like nothing happened. */
5559 (void)MoveFile(szTempFile, pszOldFile);
5560
5561 return -7;
5562 }
5563
5564 /* Seems to be left around on Novell filesystems */
5565 DeleteFile(szTempFile);
5566
5567 /* finally, remove the empty old file */
5568 if (!DeleteFile(pszOldFile))
5569 return -8;
5570
5571 return 0; /* success */
5572}
5573
5574/*
5575 * Get the default shell for the current hardware platform
5576 */
5577 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005578default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005579{
5580 char* psz = NULL;
5581
5582 PlatformId();
5583
5584 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5585 psz = "cmd.exe";
5586 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5587 psz = "command.com";
5588
5589 return psz;
5590}
5591
5592/*
5593 * mch_access() extends access() to do more detailed check on network drives.
5594 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5595 */
5596 int
5597mch_access(char *n, int p)
5598{
5599 HANDLE hFile;
5600 DWORD am;
5601 int retval = -1; /* default: fail */
5602#ifdef FEAT_MBYTE
5603 WCHAR *wn = NULL;
5604
5605 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005606 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005607#endif
5608
5609 if (mch_isdir(n))
5610 {
5611 char TempName[_MAX_PATH + 16] = "";
5612#ifdef FEAT_MBYTE
5613 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5614#endif
5615
5616 if (p & R_OK)
5617 {
5618 /* Read check is performed by seeing if we can do a find file on
5619 * the directory for any file. */
5620#ifdef FEAT_MBYTE
5621 if (wn != NULL)
5622 {
5623 int i;
5624 WIN32_FIND_DATAW d;
5625
5626 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5627 TempNameW[i] = wn[i];
5628 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5629 TempNameW[i++] = '\\';
5630 TempNameW[i++] = '*';
5631 TempNameW[i++] = 0;
5632
5633 hFile = FindFirstFileW(TempNameW, &d);
5634 if (hFile == INVALID_HANDLE_VALUE)
5635 {
5636 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5637 goto getout;
5638
5639 /* Retry with non-wide function (for Windows 98). */
5640 vim_free(wn);
5641 wn = NULL;
5642 }
5643 else
5644 (void)FindClose(hFile);
5645 }
5646 if (wn == NULL)
5647#endif
5648 {
5649 char *pch;
5650 WIN32_FIND_DATA d;
5651
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005652 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005653 pch = TempName + STRLEN(TempName) - 1;
5654 if (*pch != '\\' && *pch != '/')
5655 *++pch = '\\';
5656 *++pch = '*';
5657 *++pch = NUL;
5658
5659 hFile = FindFirstFile(TempName, &d);
5660 if (hFile == INVALID_HANDLE_VALUE)
5661 goto getout;
5662 (void)FindClose(hFile);
5663 }
5664 }
5665
5666 if (p & W_OK)
5667 {
5668 /* Trying to create a temporary file in the directory should catch
5669 * directories on read-only network shares. However, in
5670 * directories whose ACL allows writes but denies deletes will end
5671 * up keeping the temporary file :-(. */
5672#ifdef FEAT_MBYTE
5673 if (wn != NULL)
5674 {
5675 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5676 {
5677 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5678 goto getout;
5679
5680 /* Retry with non-wide function (for Windows 98). */
5681 vim_free(wn);
5682 wn = NULL;
5683 }
5684 else
5685 DeleteFileW(TempNameW);
5686 }
5687 if (wn == NULL)
5688#endif
5689 {
5690 if (!GetTempFileName(n, "VIM", 0, TempName))
5691 goto getout;
5692 mch_remove((char_u *)TempName);
5693 }
5694 }
5695 }
5696 else
5697 {
5698 /* Trying to open the file for the required access does ACL, read-only
5699 * network share, and file attribute checks. */
5700 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5701 | ((p & R_OK) ? GENERIC_READ : 0);
5702#ifdef FEAT_MBYTE
5703 if (wn != NULL)
5704 {
5705 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5706 if (hFile == INVALID_HANDLE_VALUE
5707 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5708 {
5709 /* Retry with non-wide function (for Windows 98). */
5710 vim_free(wn);
5711 wn = NULL;
5712 }
5713 }
5714 if (wn == NULL)
5715#endif
5716 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5717 if (hFile == INVALID_HANDLE_VALUE)
5718 goto getout;
5719 CloseHandle(hFile);
5720 }
5721
5722 retval = 0; /* success */
5723getout:
5724#ifdef FEAT_MBYTE
5725 vim_free(wn);
5726#endif
5727 return retval;
5728}
5729
5730#if defined(FEAT_MBYTE) || defined(PROTO)
5731/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005732 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005733 */
5734 int
5735mch_open(char *name, int flags, int mode)
5736{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005737 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5738# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005739 WCHAR *wn;
5740 int f;
5741
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005742 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005743 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005744 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005745 if (wn != NULL)
5746 {
5747 f = _wopen(wn, flags, mode);
5748 vim_free(wn);
5749 if (f >= 0)
5750 return f;
5751 /* Retry with non-wide function (for Windows 98). Can't use
5752 * GetLastError() here and it's unclear what errno gets set to if
5753 * the _wopen() fails for missing wide functions. */
5754 }
5755 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005756# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005757
5758 return open(name, flags, mode);
5759}
5760
5761/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005762 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005763 */
5764 FILE *
5765mch_fopen(char *name, char *mode)
5766{
5767 WCHAR *wn, *wm;
5768 FILE *f = NULL;
5769
5770 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5771# ifdef __BORLANDC__
5772 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5773 && g_PlatformId == VER_PLATFORM_WIN32_NT
5774# endif
5775 )
5776 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005777# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005778 /* Work around an annoying assertion in the Microsoft debug CRT
5779 * when mode's text/binary setting doesn't match _get_fmode(). */
5780 char newMode = mode[strlen(mode) - 1];
5781 int oldMode = 0;
5782
5783 _get_fmode(&oldMode);
5784 if (newMode == 't')
5785 _set_fmode(_O_TEXT);
5786 else if (newMode == 'b')
5787 _set_fmode(_O_BINARY);
5788# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005789 wn = enc_to_utf16(name, NULL);
5790 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 if (wn != NULL && wm != NULL)
5792 f = _wfopen(wn, wm);
5793 vim_free(wn);
5794 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005795
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005796# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005797 _set_fmode(oldMode);
5798# endif
5799
Bram Moolenaar071d4272004-06-13 20:20:40 +00005800 if (f != NULL)
5801 return f;
5802 /* Retry with non-wide function (for Windows 98). Can't use
5803 * GetLastError() here and it's unclear what errno gets set to if
5804 * the _wfopen() fails for missing wide functions. */
5805 }
5806
5807 return fopen(name, mode);
5808}
5809#endif
5810
5811#ifdef FEAT_MBYTE
5812/*
5813 * SUB STREAM (aka info stream) handling:
5814 *
5815 * NTFS can have sub streams for each file. Normal contents of file is
5816 * stored in the main stream, and extra contents (author information and
5817 * title and so on) can be stored in sub stream. After Windows 2000, user
5818 * can access and store those informations in sub streams via explorer's
5819 * property menuitem in right click menu. Those informations in sub streams
5820 * were lost when copying only the main stream. So we have to copy sub
5821 * streams.
5822 *
5823 * Incomplete explanation:
5824 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5825 * More useful info and an example:
5826 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5827 */
5828
5829/*
5830 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5831 * and write to stream "substream" of file "to".
5832 * Errors are ignored.
5833 */
5834 static void
5835copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5836{
5837 HANDLE hTo;
5838 WCHAR *to_name;
5839
5840 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5841 wcscpy(to_name, to);
5842 wcscat(to_name, substream);
5843
5844 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5845 FILE_ATTRIBUTE_NORMAL, NULL);
5846 if (hTo != INVALID_HANDLE_VALUE)
5847 {
5848 long done;
5849 DWORD todo;
5850 DWORD readcnt, written;
5851 char buf[4096];
5852
5853 /* Copy block of bytes at a time. Abort when something goes wrong. */
5854 for (done = 0; done < len; done += written)
5855 {
5856 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005857 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5858 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005859 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5860 FALSE, FALSE, context)
5861 || readcnt != todo
5862 || !WriteFile(hTo, buf, todo, &written, NULL)
5863 || written != todo)
5864 break;
5865 }
5866 CloseHandle(hTo);
5867 }
5868
5869 free(to_name);
5870}
5871
5872/*
5873 * Copy info streams from file "from" to file "to".
5874 */
5875 static void
5876copy_infostreams(char_u *from, char_u *to)
5877{
5878 WCHAR *fromw;
5879 WCHAR *tow;
5880 HANDLE sh;
5881 WIN32_STREAM_ID sid;
5882 int headersize;
5883 WCHAR streamname[_MAX_PATH];
5884 DWORD readcount;
5885 void *context = NULL;
5886 DWORD lo, hi;
5887 int len;
5888
5889 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005890 fromw = enc_to_utf16(from, NULL);
5891 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005892 if (fromw != NULL && tow != NULL)
5893 {
5894 /* Open the file for reading. */
5895 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
5896 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5897 if (sh != INVALID_HANDLE_VALUE)
5898 {
5899 /* Use BackupRead() to find the info streams. Repeat until we
5900 * have done them all.*/
5901 for (;;)
5902 {
5903 /* Get the header to find the length of the stream name. If
5904 * the "readcount" is zero we have done all info streams. */
5905 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005906 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005907 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
5908 &readcount, FALSE, FALSE, &context)
5909 || readcount == 0)
5910 break;
5911
5912 /* We only deal with streams that have a name. The normal
5913 * file data appears to be without a name, even though docs
5914 * suggest it is called "::$DATA". */
5915 if (sid.dwStreamNameSize > 0)
5916 {
5917 /* Read the stream name. */
5918 if (!BackupRead(sh, (LPBYTE)streamname,
5919 sid.dwStreamNameSize,
5920 &readcount, FALSE, FALSE, &context))
5921 break;
5922
5923 /* Copy an info stream with a name ":anything:$DATA".
5924 * Skip "::$DATA", it has no stream name (examples suggest
5925 * it might be used for the normal file contents).
5926 * Note that BackupRead() counts bytes, but the name is in
5927 * wide characters. */
5928 len = readcount / sizeof(WCHAR);
5929 streamname[len] = 0;
5930 if (len > 7 && wcsicmp(streamname + len - 6,
5931 L":$DATA") == 0)
5932 {
5933 streamname[len - 6] = 0;
5934 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00005935 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005936 }
5937 }
5938
5939 /* Advance to the next stream. We might try seeking too far,
5940 * but BackupSeek() doesn't skip over stream borders, thus
5941 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005942 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943 &lo, &hi, &context);
5944 }
5945
5946 /* Clear the context. */
5947 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
5948
5949 CloseHandle(sh);
5950 }
5951 }
5952 vim_free(fromw);
5953 vim_free(tow);
5954}
5955#endif
5956
5957/*
5958 * Copy file attributes from file "from" to file "to".
5959 * For Windows NT and later we copy info streams.
5960 * Always returns zero, errors are ignored.
5961 */
5962 int
5963mch_copy_file_attribute(char_u *from, char_u *to)
5964{
5965#ifdef FEAT_MBYTE
5966 /* File streams only work on Windows NT and later. */
5967 PlatformId();
5968 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5969 copy_infostreams(from, to);
5970#endif
5971 return 0;
5972}
5973
5974#if defined(MYRESETSTKOFLW) || defined(PROTO)
5975/*
5976 * Recreate a destroyed stack guard page in win32.
5977 * Written by Benjamin Peterson.
5978 */
5979
5980/* These magic numbers are from the MS header files */
5981#define MIN_STACK_WIN9X 17
5982#define MIN_STACK_WINNT 2
5983
5984/*
5985 * This function does the same thing as _resetstkoflw(), which is only
5986 * available in DevStudio .net and later.
5987 * Returns 0 for failure, 1 for success.
5988 */
5989 int
5990myresetstkoflw(void)
5991{
5992 BYTE *pStackPtr;
5993 BYTE *pGuardPage;
5994 BYTE *pStackBase;
5995 BYTE *pLowestPossiblePage;
5996 MEMORY_BASIC_INFORMATION mbi;
5997 SYSTEM_INFO si;
5998 DWORD nPageSize;
5999 DWORD dummy;
6000
6001 /* This code will not work on win32s. */
6002 PlatformId();
6003 if (g_PlatformId == VER_PLATFORM_WIN32s)
6004 return 0;
6005
6006 /* We need to know the system page size. */
6007 GetSystemInfo(&si);
6008 nPageSize = si.dwPageSize;
6009
6010 /* ...and the current stack pointer */
6011 pStackPtr = (BYTE*)_alloca(1);
6012
6013 /* ...and the base of the stack. */
6014 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6015 return 0;
6016 pStackBase = (BYTE*)mbi.AllocationBase;
6017
6018 /* ...and the page thats min_stack_req pages away from stack base; this is
6019 * the lowest page we could use. */
6020 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
6021 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
6022
6023 /* On Win95, we want the next page down from the end of the stack. */
6024 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
6025 {
6026 /* Find the page that's only 1 page down from the page that the stack
6027 * ptr is in. */
6028 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
6029 / (DWORD)nPageSize) - 1));
6030 if (pGuardPage < pLowestPossiblePage)
6031 return 0;
6032
6033 /* Apply the noaccess attribute to the page -- there's no guard
6034 * attribute in win95-type OSes. */
6035 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6036 return 0;
6037 }
6038 else
6039 {
6040 /* On NT, however, we want the first committed page in the stack Start
6041 * at the stack base and move forward through memory until we find a
6042 * committed block. */
6043 BYTE *pBlock = pStackBase;
6044
Bram Moolenaara466c992005-07-09 21:03:22 +00006045 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006046 {
6047 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6048 return 0;
6049
6050 pBlock += mbi.RegionSize;
6051
6052 if (mbi.State & MEM_COMMIT)
6053 break;
6054 }
6055
6056 /* mbi now describes the first committed block in the stack. */
6057 if (mbi.Protect & PAGE_GUARD)
6058 return 1;
6059
6060 /* decide where the guard page should start */
6061 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6062 pGuardPage = pLowestPossiblePage;
6063 else
6064 pGuardPage = (BYTE*)mbi.BaseAddress;
6065
6066 /* allocate the guard page */
6067 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6068 return 0;
6069
6070 /* apply the guard attribute to the page */
6071 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6072 &dummy))
6073 return 0;
6074 }
6075
6076 return 1;
6077}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006078#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006079
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006080
6081#if defined(FEAT_MBYTE) || defined(PROTO)
6082/*
6083 * The command line arguments in UCS2
6084 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006085static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006086static LPWSTR *ArglistW = NULL;
6087static int global_argc = 0;
6088static char **global_argv;
6089
6090static int used_file_argc = 0; /* last argument in global_argv[] used
6091 for the argument list. */
6092static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6093 command line arguments added to
6094 the argument list */
6095static int used_file_count = 0; /* nr of entries in used_file_indexes */
6096static int used_file_literal = FALSE; /* take file names literally */
6097static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006098static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006099static int used_alist_count = 0;
6100
6101
6102/*
6103 * Get the command line arguments. Unicode version.
6104 * Returns argc. Zero when something fails.
6105 */
6106 int
6107get_cmd_argsW(char ***argvp)
6108{
6109 char **argv = NULL;
6110 int argc = 0;
6111 int i;
6112
6113 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6114 if (ArglistW != NULL)
6115 {
6116 argv = malloc((nArgsW + 1) * sizeof(char *));
6117 if (argv != NULL)
6118 {
6119 argc = nArgsW;
6120 argv[argc] = NULL;
6121 for (i = 0; i < argc; ++i)
6122 {
6123 int len;
6124
6125 /* Convert each Unicode argument to the current codepage. */
6126 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006127 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006128 (LPSTR *)&argv[i], &len, 0, 0);
6129 if (argv[i] == NULL)
6130 {
6131 /* Out of memory, clear everything. */
6132 while (i > 0)
6133 free(argv[--i]);
6134 free(argv);
6135 argc = 0;
6136 }
6137 }
6138 }
6139 }
6140
6141 global_argc = argc;
6142 global_argv = argv;
6143 if (argc > 0)
6144 used_file_indexes = malloc(argc * sizeof(int));
6145
6146 if (argvp != NULL)
6147 *argvp = argv;
6148 return argc;
6149}
6150
6151 void
6152free_cmd_argsW(void)
6153{
6154 if (ArglistW != NULL)
6155 {
6156 GlobalFree(ArglistW);
6157 ArglistW = NULL;
6158 }
6159}
6160
6161/*
6162 * Remember "name" is an argument that was added to the argument list.
6163 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6164 * is called.
6165 */
6166 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006167used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006168{
6169 int i;
6170
6171 if (used_file_indexes == NULL)
6172 return;
6173 for (i = used_file_argc + 1; i < global_argc; ++i)
6174 if (STRCMP(global_argv[i], name) == 0)
6175 {
6176 used_file_argc = i;
6177 used_file_indexes[used_file_count++] = i;
6178 break;
6179 }
6180 used_file_literal = literal;
6181 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006182 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006183}
6184
6185/*
6186 * Remember the length of the argument list as it was. If it changes then we
6187 * leave it alone when 'encoding' is set.
6188 */
6189 void
6190set_alist_count(void)
6191{
6192 used_alist_count = GARGCOUNT;
6193}
6194
6195/*
6196 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6197 * has been changed while starting up. Use the UCS-2 command line arguments
6198 * and convert them to 'encoding'.
6199 */
6200 void
6201fix_arg_enc(void)
6202{
6203 int i;
6204 int idx;
6205 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006206 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006207
6208 /* Safety checks:
6209 * - if argument count differs between the wide and non-wide argument
6210 * list, something must be wrong.
6211 * - the file name arguments must have been located.
6212 * - the length of the argument list wasn't changed by the user.
6213 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006214 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006215 || ArglistW == NULL
6216 || used_file_indexes == NULL
6217 || used_file_count == 0
6218 || used_alist_count != GARGCOUNT)
6219 return;
6220
Bram Moolenaar86b68352004-12-27 21:59:20 +00006221 /* Remember the buffer numbers for the arguments. */
6222 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6223 if (fnum_list == NULL)
6224 return; /* out of memory */
6225 for (i = 0; i < GARGCOUNT; ++i)
6226 fnum_list[i] = GARGLIST[i].ae_fnum;
6227
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006228 /* Clear the argument list. Make room for the new arguments. */
6229 alist_clear(&global_alist);
6230 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006231 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006232
6233 for (i = 0; i < used_file_count; ++i)
6234 {
6235 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006236 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006237 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006238 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006239#ifdef FEAT_DIFF
6240 /* When using diff mode may need to concatenate file name to
6241 * directory name. Just like it's done in main(). */
6242 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6243 && !mch_isdir(alist_name(&GARGLIST[0])))
6244 {
6245 char_u *r;
6246
6247 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6248 if (r != NULL)
6249 {
6250 vim_free(str);
6251 str = r;
6252 }
6253 }
6254#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006255 /* Re-use the old buffer by renaming it. When not using literal
6256 * names it's done by alist_expand() below. */
6257 if (used_file_literal)
6258 buf_set_name(fnum_list[i], str);
6259
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006260 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006261 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006262 }
6263
6264 if (!used_file_literal)
6265 {
6266 /* Now expand wildcards in the arguments. */
6267 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6268 * filename characters but are excluded from 'isfname' to make
6269 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6270 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006271 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006272 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6273 }
6274
6275 /* If wildcard expansion failed, we are editing the first file of the
6276 * arglist and there is no file name: Edit the first argument now. */
6277 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6278 {
6279 do_cmdline_cmd((char_u *)":rewind");
6280 if (GARGCOUNT == 1 && used_file_full_path)
6281 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6282 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006283
6284 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006285}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286#endif