blob: 421a164c50ca912460622d8531154a3b946125b5 [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 Moolenaar071d4272004-06-13 20:20:40 +0000145#endif
146
147#ifndef FEAT_GUI_W32
148/* Undocumented API in kernel32.dll needed to work around dead key bug in
149 * console-mode applications in NT 4.0. If you switch keyboard layouts
150 * in a console app to a layout that includes dead keys and then hit a
151 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
152 * and Michael Dietrich for helping me figure out this workaround.
153 */
154
155/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
156#ifndef WINBASEAPI
157# define WINBASEAPI __stdcall
158#endif
159#if defined(__BORLANDC__)
160typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
161#else
162typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
163#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000164static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000165#endif
166
167#if defined(__BORLANDC__)
168/* Strangely Borland uses a non-standard name. */
169# define wcsicmp(a, b) wcscmpi((a), (b))
170#endif
171
Bram Moolenaar82881492012-11-20 16:53:39 +0100172#ifndef PROTO
173
Bram Moolenaar84a05ac2013-05-06 04:24:17 +0200174/* Enable common dialogs input unicode from IME if possible. */
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200175#ifdef FEAT_MBYTE
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100176LRESULT (WINAPI *pDispatchMessage)(CONST MSG *) = DispatchMessage;
Bram Moolenaar8c85fa32011-08-10 17:08:03 +0200177BOOL (WINAPI *pGetMessage)(LPMSG, HWND, UINT, UINT) = GetMessage;
178BOOL (WINAPI *pIsDialogMessage)(HWND, LPMSG) = IsDialogMessage;
179BOOL (WINAPI *pPeekMessage)(LPMSG, HWND, UINT, UINT, UINT) = PeekMessage;
180#endif
181
Bram Moolenaar82881492012-11-20 16:53:39 +0100182#endif /* PROTO */
183
Bram Moolenaar071d4272004-06-13 20:20:40 +0000184#ifndef FEAT_GUI_W32
185/* Win32 Console handles for input and output */
186static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
187static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
188
189/* Win32 Screen buffer,coordinate,console I/O information */
190static SMALL_RECT g_srScrollRegion;
191static COORD g_coord; /* 0-based, but external coords are 1-based */
192
193/* The attribute of the screen when the editor was started */
194static WORD g_attrDefault = 7; /* lightgray text on black background */
195static WORD g_attrCurrent;
196
197static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
198static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
199static int g_fForceExit = FALSE; /* set when forcefully exiting */
200
201static void termcap_mode_start(void);
202static void termcap_mode_end(void);
203static void clear_chars(COORD coord, DWORD n);
204static void clear_screen(void);
205static void clear_to_end_of_display(void);
206static void clear_to_end_of_line(void);
207static void scroll(unsigned cLines);
208static void set_scroll_region(unsigned left, unsigned top,
209 unsigned right, unsigned bottom);
210static void insert_lines(unsigned cLines);
211static void delete_lines(unsigned cLines);
212static void gotoxy(unsigned x, unsigned y);
213static void normvideo(void);
214static void textattr(WORD wAttr);
215static void textcolor(WORD wAttr);
216static void textbackground(WORD wAttr);
217static void standout(void);
218static void standend(void);
219static void visual_bell(void);
220static void cursor_visible(BOOL fVisible);
221static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
222static char_u tgetch(int *pmodifiers, char_u *pch2);
223static void create_conin(void);
224static int s_cursor_visible = TRUE;
225static int did_create_conin = FALSE;
226#else
227static int s_dont_use_vimrun = TRUE;
228static int need_vimrun_warning = FALSE;
229static char *vimrun_path = "vimrun ";
230#endif
231
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200232static int win32_getattrs(char_u *name);
233static int win32_setattrs(char_u *name, int attrs);
234static int win32_set_archive(char_u *name);
235
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236#ifndef FEAT_GUI_W32
237static int suppress_winsize = 1; /* don't fiddle with console */
238#endif
239
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200240static char_u *exe_path = NULL;
241
Bram Moolenaar071d4272004-06-13 20:20:40 +0000242 static void
243get_exe_name(void)
244{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100245 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
246 * as the maximum length that works (plus a NUL byte). */
247#define MAX_ENV_PATH_LEN 8192
248 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200249 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000250
251 if (exe_name == NULL)
252 {
253 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100254 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000255 if (*temp != NUL)
256 exe_name = FullName_save((char_u *)temp, FALSE);
257 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000258
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200259 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000260 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200261 exe_path = vim_strnsave(exe_name,
262 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200263 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000264 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200265 /* Append our starting directory to $PATH, so that when doing
266 * "!xxd" it's found in our starting directory. Needed because
267 * SearchPath() also looks there. */
268 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100269 if (p == NULL
270 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200271 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100272 if (p == NULL || *p == NUL)
273 temp[0] = NUL;
274 else
275 {
276 STRCPY(temp, p);
277 STRCAT(temp, ";");
278 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200279 STRCAT(temp, exe_path);
280 vim_setenv((char_u *)"PATH", temp);
281 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000282 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000283 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000284}
285
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200286/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100287 * Unescape characters in "p" that appear in "escaped".
288 */
289 static void
290unescape_shellxquote(char_u *p, char_u *escaped)
291{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100292 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100293 int n;
294
295 while (*p != NUL)
296 {
297 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
298 mch_memmove(p, p + 1, l--);
299#ifdef FEAT_MBYTE
300 n = (*mb_ptr2len)(p);
301#else
302 n = 1;
303#endif
304 p += n;
305 l -= n;
306 }
307}
308
309/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200310 * Load library "name".
311 */
312 HINSTANCE
313vimLoadLib(char *name)
314{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200315 HINSTANCE dll = NULL;
316 char old_dir[MAXPATHL];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200317
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200318 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
319 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200320 if (exe_path == NULL)
321 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200322 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200323 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200324#ifdef FEAT_MBYTE
325 WCHAR old_dirw[MAXPATHL];
326
327 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
328 {
329 /* Change directory to where the executable is, both to make
330 * sure we find a .dll there and to avoid looking for a .dll
331 * in the current directory. */
332 SetCurrentDirectory(exe_path);
333 dll = LoadLibrary(name);
334 SetCurrentDirectoryW(old_dirw);
335 return dll;
336 }
337 /* Retry with non-wide function (for Windows 98). */
338 if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
339#endif
340 if (GetCurrentDirectory(MAXPATHL, old_dir) != 0)
341 {
342 /* Change directory to where the executable is, both to make
343 * sure we find a .dll there and to avoid looking for a .dll
344 * in the current directory. */
345 SetCurrentDirectory(exe_path);
346 dll = LoadLibrary(name);
347 SetCurrentDirectory(old_dir);
348 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200349 }
350 return dll;
351}
352
Bram Moolenaar071d4272004-06-13 20:20:40 +0000353#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
354# ifndef GETTEXT_DLL
355# define GETTEXT_DLL "libintl.dll"
356# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200357/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000358static char *null_libintl_gettext(const char *);
359static char *null_libintl_textdomain(const char *);
360static char *null_libintl_bindtextdomain(const char *, const char *);
361static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000362
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200363static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000364char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
365char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
366char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000368char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
369 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000370
371 int
372dyn_libintl_init(char *libname)
373{
374 int i;
375 static struct
376 {
377 char *name;
378 FARPROC *ptr;
379 } libintl_entry[] =
380 {
381 {"gettext", (FARPROC*)&dyn_libintl_gettext},
382 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
383 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
384 {NULL, NULL}
385 };
386
387 /* No need to initialize twice. */
388 if (hLibintlDLL)
389 return 1;
390 /* Load gettext library (libintl.dll) */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200391 hLibintlDLL = vimLoadLib(libname != NULL ? libname : GETTEXT_DLL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392 if (!hLibintlDLL)
393 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200394 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000395 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200396 verbose_enter();
397 EMSG2(_(e_loadlib), GETTEXT_DLL);
398 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000399 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200400 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000401 }
402 for (i = 0; libintl_entry[i].name != NULL
403 && libintl_entry[i].ptr != NULL; ++i)
404 {
405 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
406 libintl_entry[i].name)) == NULL)
407 {
408 dyn_libintl_end();
409 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000410 {
411 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000412 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000413 verbose_leave();
414 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000415 return 0;
416 }
417 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000418
419 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000420 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000421 "bind_textdomain_codeset");
422 if (dyn_libintl_bind_textdomain_codeset == NULL)
423 dyn_libintl_bind_textdomain_codeset =
424 null_libintl_bind_textdomain_codeset;
425
Bram Moolenaar071d4272004-06-13 20:20:40 +0000426 return 1;
427}
428
429 void
430dyn_libintl_end()
431{
432 if (hLibintlDLL)
433 FreeLibrary(hLibintlDLL);
434 hLibintlDLL = NULL;
435 dyn_libintl_gettext = null_libintl_gettext;
436 dyn_libintl_textdomain = null_libintl_textdomain;
437 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000438 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439}
440
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000441/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000443null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000444{
445 return (char*)msgid;
446}
447
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000448/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000450null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000451{
452 return NULL;
453}
454
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000455/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000456 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000457null_libintl_bind_textdomain_codeset(const char *domainname,
458 const char *codeset)
459{
460 return NULL;
461}
462
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000463/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000464 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000465null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000466{
467 return NULL;
468}
469
470#endif /* DYNAMIC_GETTEXT */
471
472/* This symbol is not defined in older versions of the SDK or Visual C++ */
473
474#ifndef VER_PLATFORM_WIN32_WINDOWS
475# define VER_PLATFORM_WIN32_WINDOWS 1
476#endif
477
478DWORD g_PlatformId;
479
480#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100481# ifndef PROTO
482# include <aclapi.h>
483# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200484# ifndef PROTECTED_DACL_SECURITY_INFORMATION
485# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
486# endif
Bram Moolenaar82881492012-11-20 16:53:39 +0100487
Bram Moolenaar071d4272004-06-13 20:20:40 +0000488/*
489 * These are needed to dynamically load the ADVAPI DLL, which is not
490 * implemented under Windows 95 (and causes VIM to crash)
491 */
Bram Moolenaar39efa892013-06-29 15:40:04 +0200492typedef DWORD (WINAPI *PSNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200494typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, SE_OBJECT_TYPE,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
496 PSECURITY_DESCRIPTOR *);
Bram Moolenaar27515922013-06-29 15:36:26 +0200497# ifdef FEAT_MBYTE
Bram Moolenaar39efa892013-06-29 15:40:04 +0200498typedef DWORD (WINAPI *PSNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200499 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
Bram Moolenaar39efa892013-06-29 15:40:04 +0200500typedef DWORD (WINAPI *PGNSECINFOW) (LPWSTR, SE_OBJECT_TYPE,
Bram Moolenaar27515922013-06-29 15:36:26 +0200501 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
502 PSECURITY_DESCRIPTOR *);
503# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000504
505static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
506static PSNSECINFO pSetNamedSecurityInfo;
507static PGNSECINFO pGetNamedSecurityInfo;
Bram Moolenaar27515922013-06-29 15:36:26 +0200508# ifdef FEAT_MBYTE
509static PSNSECINFOW pSetNamedSecurityInfoW;
510static PGNSECINFOW pGetNamedSecurityInfoW;
511# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000512#endif
513
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200514typedef BOOL (WINAPI *PSETHANDLEINFORMATION)(HANDLE, DWORD, DWORD);
515
516static BOOL allowPiping = FALSE;
517static PSETHANDLEINFORMATION pSetHandleInformation;
518
Bram Moolenaar27515922013-06-29 15:36:26 +0200519#ifdef HAVE_ACL
520/*
521 * Enables or disables the specified privilege.
522 */
523 static BOOL
524win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
525{
526 BOOL bResult;
527 LUID luid;
528 HANDLE hToken;
529 TOKEN_PRIVILEGES tokenPrivileges;
530
531 if (!OpenProcessToken(GetCurrentProcess(),
532 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
533 return FALSE;
534
535 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
536 {
537 CloseHandle(hToken);
538 return FALSE;
539 }
540
541 tokenPrivileges.PrivilegeCount = 1;
542 tokenPrivileges.Privileges[0].Luid = luid;
543 tokenPrivileges.Privileges[0].Attributes = bEnable ?
544 SE_PRIVILEGE_ENABLED : 0;
545
546 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
547 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
548
549 CloseHandle(hToken);
550
551 return bResult && GetLastError() == ERROR_SUCCESS;
552}
553#endif
554
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555/*
556 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
557 * VER_PLATFORM_WIN32_WINDOWS (Win95).
558 */
559 void
560PlatformId(void)
561{
562 static int done = FALSE;
563
564 if (!done)
565 {
566 OSVERSIONINFO ovi;
567
568 ovi.dwOSVersionInfoSize = sizeof(ovi);
569 GetVersionEx(&ovi);
570
571 g_PlatformId = ovi.dwPlatformId;
572
573#ifdef HAVE_ACL
574 /*
575 * Load the ADVAPI runtime if we are on anything
576 * other than Windows 95
577 */
578 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
579 {
580 /*
581 * do this load. Problems: Doesn't unload at end of run (this is
582 * theoretically okay, since Windows should unload it when VIM
583 * terminates). Should we be using the 'mch_libcall' routines?
584 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
585 * time we verify security...
586 */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200587 advapi_lib = vimLoadLib("ADVAPI32.DLL");
Bram Moolenaar071d4272004-06-13 20:20:40 +0000588 if (advapi_lib != NULL)
589 {
590 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
591 "SetNamedSecurityInfoA");
592 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
593 "GetNamedSecurityInfoA");
Bram Moolenaar27515922013-06-29 15:36:26 +0200594# ifdef FEAT_MBYTE
595 pSetNamedSecurityInfoW = (PSNSECINFOW)GetProcAddress(advapi_lib,
596 "SetNamedSecurityInfoW");
597 pGetNamedSecurityInfoW = (PGNSECINFOW)GetProcAddress(advapi_lib,
598 "GetNamedSecurityInfoW");
599# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000600 if (pSetNamedSecurityInfo == NULL
Bram Moolenaar27515922013-06-29 15:36:26 +0200601 || pGetNamedSecurityInfo == NULL
602# ifdef FEAT_MBYTE
603 || pSetNamedSecurityInfoW == NULL
604 || pGetNamedSecurityInfoW == NULL
605# endif
606 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000607 {
608 /* If we can't get the function addresses, set advapi_lib
609 * to NULL so that we don't use them. */
610 FreeLibrary(advapi_lib);
611 advapi_lib = NULL;
612 }
Bram Moolenaar27515922013-06-29 15:36:26 +0200613 /* Enable privilege for getting or setting SACLs. */
614 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615 }
616 }
617#endif
Bram Moolenaar4b9669f2011-07-07 16:20:52 +0200618 /*
619 * If we are on windows NT, try to load the pipe functions, only
620 * available from Win2K.
621 */
622 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
623 {
624 HANDLE kernel32 = GetModuleHandle("kernel32");
625 pSetHandleInformation = (PSETHANDLEINFORMATION)GetProcAddress(
626 kernel32, "SetHandleInformation");
627
628 allowPiping = pSetHandleInformation != NULL;
629 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 done = TRUE;
631 }
632}
633
634/*
635 * Return TRUE when running on Windows 95 (or 98 or ME).
636 * Only to be used after mch_init().
637 */
638 int
639mch_windows95(void)
640{
641 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
642}
643
644#ifdef FEAT_GUI_W32
645/*
646 * Used to work around the "can't do synchronous spawn"
647 * problem on Win32s, without resorting to Universal Thunk.
648 */
649static int old_num_windows;
650static int num_windows;
651
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000652/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000653 static BOOL CALLBACK
654win32ssynch_cb(HWND hwnd, LPARAM lparam)
655{
656 num_windows++;
657 return TRUE;
658}
659#endif
660
661#ifndef FEAT_GUI_W32
662
663#define SHIFT (SHIFT_PRESSED)
664#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
665#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
666#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
667
668
669/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
670 * We map function keys to their ANSI terminal equivalents, as produced
671 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
672 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
673 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
674 * combinations of function/arrow/etc keys.
675 */
676
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000677static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000678{
679 WORD wVirtKey;
680 BOOL fAnsiKey;
681 int chAlone;
682 int chShift;
683 int chCtrl;
684 int chAlt;
685} VirtKeyMap[] =
686{
687
688/* Key ANSI alone shift ctrl alt */
689 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
690
691 { VK_F1, TRUE, ';', 'T', '^', 'h', },
692 { VK_F2, TRUE, '<', 'U', '_', 'i', },
693 { VK_F3, TRUE, '=', 'V', '`', 'j', },
694 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
695 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
696 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
697 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
698 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
699 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
700 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
701 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
702 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
703
704 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
705 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
706 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
707 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
708 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
709 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
710 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
711 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
712 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
713 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
714
715 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
716
717#if 0
718 /* Most people don't have F13-F20, but what the hell... */
719 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
720 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
721 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
722 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
723 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
724 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
725 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
726 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
727#endif
728 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
729 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
730 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
731 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
732
733 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
734 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
735 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
736 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
737 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
738 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
739 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
740 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
741 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
742 /* Sorry, out of number space! <negri>*/
743 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
744
745};
746
747
748#ifdef _MSC_VER
749// The ToAscii bug destroys several registers. Need to turn off optimization
750// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000751# pragma warning(push)
752# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000753# pragma optimize("", off)
754#endif
755
756#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
757# define AChar AsciiChar
758#else
759# define AChar uChar.AsciiChar
760#endif
761
762/* The return code indicates key code size. */
763 static int
764#ifdef __BORLANDC__
765 __stdcall
766#endif
767win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000768 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769{
770 UINT uMods = pker->dwControlKeyState;
771 static int s_iIsDead = 0;
772 static WORD awAnsiCode[2];
773 static BYTE abKeystate[256];
774
775
776 if (s_iIsDead == 2)
777 {
778 pker->AChar = (CHAR) awAnsiCode[1];
779 s_iIsDead = 0;
780 return 1;
781 }
782
783 if (pker->AChar != 0)
784 return 1;
785
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200786 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000787
788 // Should only be non-NULL on NT 4.0
789 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
790 {
791 CHAR szKLID[KL_NAMELENGTH];
792
793 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
794 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
795 }
796
797 /* Clear any pending dead keys */
798 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
799
800 if (uMods & SHIFT_PRESSED)
801 abKeystate[VK_SHIFT] = 0x80;
802 if (uMods & CAPSLOCK_ON)
803 abKeystate[VK_CAPITAL] = 1;
804
805 if ((uMods & ALT_GR) == ALT_GR)
806 {
807 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
808 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
809 }
810
811 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
812 abKeystate, awAnsiCode, 0);
813
814 if (s_iIsDead > 0)
815 pker->AChar = (CHAR) awAnsiCode[0];
816
817 return s_iIsDead;
818}
819
820#ifdef _MSC_VER
821/* MUST switch optimization on again here, otherwise a call to
822 * decode_key_event() may crash (e.g. when hitting caps-lock) */
823# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000824# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825
826# if (_MSC_VER < 1100)
827/* MUST turn off global optimisation for this next function, or
828 * pressing ctrl-minus in insert mode crashes Vim when built with
829 * VC4.1. -- negri. */
830# pragma optimize("g", off)
831# endif
832#endif
833
834static BOOL g_fJustGotFocus = FALSE;
835
836/*
837 * Decode a KEY_EVENT into one or two keystrokes
838 */
839 static BOOL
840decode_key_event(
841 KEY_EVENT_RECORD *pker,
842 char_u *pch,
843 char_u *pch2,
844 int *pmodifiers,
845 BOOL fDoPost)
846{
847 int i;
848 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
849
850 *pch = *pch2 = NUL;
851 g_fJustGotFocus = FALSE;
852
853 /* ignore key up events */
854 if (!pker->bKeyDown)
855 return FALSE;
856
857 /* ignore some keystrokes */
858 switch (pker->wVirtualKeyCode)
859 {
860 /* modifiers */
861 case VK_SHIFT:
862 case VK_CONTROL:
863 case VK_MENU: /* Alt key */
864 return FALSE;
865
866 default:
867 break;
868 }
869
870 /* special cases */
871 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
872 {
873 /* Ctrl-6 is Ctrl-^ */
874 if (pker->wVirtualKeyCode == '6')
875 {
876 *pch = Ctrl_HAT;
877 return TRUE;
878 }
879 /* Ctrl-2 is Ctrl-@ */
880 else if (pker->wVirtualKeyCode == '2')
881 {
882 *pch = NUL;
883 return TRUE;
884 }
885 /* Ctrl-- is Ctrl-_ */
886 else if (pker->wVirtualKeyCode == 0xBD)
887 {
888 *pch = Ctrl__;
889 return TRUE;
890 }
891 }
892
893 /* Shift-TAB */
894 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
895 {
896 *pch = K_NUL;
897 *pch2 = '\017';
898 return TRUE;
899 }
900
901 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
902 {
903 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
904 {
905 if (nModifs == 0)
906 *pch = VirtKeyMap[i].chAlone;
907 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
908 *pch = VirtKeyMap[i].chShift;
909 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
910 *pch = VirtKeyMap[i].chCtrl;
911 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
912 *pch = VirtKeyMap[i].chAlt;
913
914 if (*pch != 0)
915 {
916 if (VirtKeyMap[i].fAnsiKey)
917 {
918 *pch2 = *pch;
919 *pch = K_NUL;
920 }
921
922 return TRUE;
923 }
924 }
925 }
926
927 i = win32_kbd_patch_key(pker);
928
929 if (i < 0)
930 *pch = NUL;
931 else
932 {
933 *pch = (i > 0) ? pker->AChar : NUL;
934
935 if (pmodifiers != NULL)
936 {
937 /* Pass on the ALT key as a modifier, but only when not combined
938 * with CTRL (which is ALTGR). */
939 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
940 *pmodifiers |= MOD_MASK_ALT;
941
942 /* Pass on SHIFT only for special keys, because we don't know when
943 * it's already included with the character. */
944 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
945 *pmodifiers |= MOD_MASK_SHIFT;
946
947 /* Pass on CTRL only for non-special keys, because we don't know
948 * when it's already included with the character. And not when
949 * combined with ALT (which is ALTGR). */
950 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
951 && *pch >= 0x20 && *pch < 0x80)
952 *pmodifiers |= MOD_MASK_CTRL;
953 }
954 }
955
956 return (*pch != NUL);
957}
958
959#ifdef _MSC_VER
960# pragma optimize("", on)
961#endif
962
963#endif /* FEAT_GUI_W32 */
964
965
966#ifdef FEAT_MOUSE
967
968/*
969 * For the GUI the mouse handling is in gui_w32.c.
970 */
971# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000972/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000974mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000975{
976}
977# else
978static int g_fMouseAvail = FALSE; /* mouse present */
979static int g_fMouseActive = FALSE; /* mouse enabled */
980static int g_nMouseClick = -1; /* mouse status */
981static int g_xMouse; /* mouse x coordinate */
982static int g_yMouse; /* mouse y coordinate */
983
984/*
985 * Enable or disable mouse input
986 */
987 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000988mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989{
990 DWORD cmodein;
991
992 if (!g_fMouseAvail)
993 return;
994
995 g_fMouseActive = on;
996 GetConsoleMode(g_hConIn, &cmodein);
997
998 if (g_fMouseActive)
999 cmodein |= ENABLE_MOUSE_INPUT;
1000 else
1001 cmodein &= ~ENABLE_MOUSE_INPUT;
1002
1003 SetConsoleMode(g_hConIn, cmodein);
1004}
1005
1006
1007/*
1008 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1009 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1010 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1011 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1012 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1013 * and we return the mouse position in g_xMouse and g_yMouse.
1014 *
1015 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1016 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1017 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1018 *
1019 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1020 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1021 *
1022 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1023 * moves, even if it stays within the same character cell. We ignore
1024 * all MOUSE_MOVED messages if the position hasn't really changed, and
1025 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1026 * we're only interested in MOUSE_DRAG).
1027 *
1028 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1029 * 2-button mouses by pressing the left & right buttons simultaneously.
1030 * In practice, it's almost impossible to click both at the same time,
1031 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1032 * in such cases, if the user is clicking quickly.
1033 */
1034 static BOOL
1035decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001036 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001037{
1038 static int s_nOldButton = -1;
1039 static int s_nOldMouseClick = -1;
1040 static int s_xOldMouse = -1;
1041 static int s_yOldMouse = -1;
1042 static linenr_T s_old_topline = 0;
1043#ifdef FEAT_DIFF
1044 static int s_old_topfill = 0;
1045#endif
1046 static int s_cClicks = 1;
1047 static BOOL s_fReleased = TRUE;
1048 static DWORD s_dwLastClickTime = 0;
1049 static BOOL s_fNextIsMiddle = FALSE;
1050
1051 static DWORD cButtons = 0; /* number of buttons supported */
1052
1053 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1054 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1055 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1056 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1057
1058 int nButton;
1059
1060 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1061 cButtons = 2;
1062
1063 if (!g_fMouseAvail || !g_fMouseActive)
1064 {
1065 g_nMouseClick = -1;
1066 return FALSE;
1067 }
1068
1069 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1070 if (g_fJustGotFocus)
1071 {
1072 g_fJustGotFocus = FALSE;
1073 return FALSE;
1074 }
1075
1076 /* unprocessed mouse click? */
1077 if (g_nMouseClick != -1)
1078 return TRUE;
1079
1080 nButton = -1;
1081 g_xMouse = pmer->dwMousePosition.X;
1082 g_yMouse = pmer->dwMousePosition.Y;
1083
1084 if (pmer->dwEventFlags == MOUSE_MOVED)
1085 {
1086 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1087 * events even when the mouse moves only within a char cell.) */
1088 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1089 return FALSE;
1090 }
1091
1092 /* If no buttons are pressed... */
1093 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1094 {
1095 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1096 if (s_fReleased)
1097 return FALSE;
1098
1099 nButton = MOUSE_RELEASE;
1100 s_fReleased = TRUE;
1101 }
1102 else /* one or more buttons pressed */
1103 {
1104 /* on a 2-button mouse, hold down left and right buttons
1105 * simultaneously to get MIDDLE. */
1106
1107 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1108 {
1109 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1110
1111 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001112 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001113 if (dwLR == LEFT || dwLR == RIGHT)
1114 {
1115 for (;;)
1116 {
1117 /* wait a short time for next input event */
1118 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1119 != WAIT_OBJECT_0)
1120 break;
1121 else
1122 {
1123 DWORD cRecords = 0;
1124 INPUT_RECORD ir;
1125 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1126
1127 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1128
1129 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1130 || !(pmer2->dwButtonState & LEFT_RIGHT))
1131 break;
1132 else
1133 {
1134 if (pmer2->dwEventFlags != MOUSE_MOVED)
1135 {
1136 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1137
1138 return decode_mouse_event(pmer2);
1139 }
1140 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1141 s_yOldMouse == pmer2->dwMousePosition.Y)
1142 {
1143 /* throw away spurious mouse move */
1144 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1145
1146 /* are there any more mouse events in queue? */
1147 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1148
1149 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1150 break;
1151 }
1152 else
1153 break;
1154 }
1155 }
1156 }
1157 }
1158 }
1159
1160 if (s_fNextIsMiddle)
1161 {
1162 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1163 ? MOUSE_DRAG : MOUSE_MIDDLE;
1164 s_fNextIsMiddle = FALSE;
1165 }
1166 else if (cButtons == 2 &&
1167 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1168 {
1169 nButton = MOUSE_MIDDLE;
1170
1171 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1172 {
1173 s_fNextIsMiddle = TRUE;
1174 nButton = MOUSE_RELEASE;
1175 }
1176 }
1177 else if ((pmer->dwButtonState & LEFT) == LEFT)
1178 nButton = MOUSE_LEFT;
1179 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1180 nButton = MOUSE_MIDDLE;
1181 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1182 nButton = MOUSE_RIGHT;
1183
1184 if (! s_fReleased && ! s_fNextIsMiddle
1185 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1186 return FALSE;
1187
1188 s_fReleased = s_fNextIsMiddle;
1189 }
1190
1191 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1192 {
1193 /* button pressed or released, without mouse moving */
1194 if (nButton != -1 && nButton != MOUSE_RELEASE)
1195 {
1196 DWORD dwCurrentTime = GetTickCount();
1197
1198 if (s_xOldMouse != g_xMouse
1199 || s_yOldMouse != g_yMouse
1200 || s_nOldButton != nButton
1201 || s_old_topline != curwin->w_topline
1202#ifdef FEAT_DIFF
1203 || s_old_topfill != curwin->w_topfill
1204#endif
1205 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1206 {
1207 s_cClicks = 1;
1208 }
1209 else if (++s_cClicks > 4)
1210 {
1211 s_cClicks = 1;
1212 }
1213
1214 s_dwLastClickTime = dwCurrentTime;
1215 }
1216 }
1217 else if (pmer->dwEventFlags == MOUSE_MOVED)
1218 {
1219 if (nButton != -1 && nButton != MOUSE_RELEASE)
1220 nButton = MOUSE_DRAG;
1221
1222 s_cClicks = 1;
1223 }
1224
1225 if (nButton == -1)
1226 return FALSE;
1227
1228 if (nButton != MOUSE_RELEASE)
1229 s_nOldButton = nButton;
1230
1231 g_nMouseClick = nButton;
1232
1233 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1234 g_nMouseClick |= MOUSE_SHIFT;
1235 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1236 g_nMouseClick |= MOUSE_CTRL;
1237 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1238 g_nMouseClick |= MOUSE_ALT;
1239
1240 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1241 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1242
1243 /* only pass on interesting (i.e., different) mouse events */
1244 if (s_xOldMouse == g_xMouse
1245 && s_yOldMouse == g_yMouse
1246 && s_nOldMouseClick == g_nMouseClick)
1247 {
1248 g_nMouseClick = -1;
1249 return FALSE;
1250 }
1251
1252 s_xOldMouse = g_xMouse;
1253 s_yOldMouse = g_yMouse;
1254 s_old_topline = curwin->w_topline;
1255#ifdef FEAT_DIFF
1256 s_old_topfill = curwin->w_topfill;
1257#endif
1258 s_nOldMouseClick = g_nMouseClick;
1259
1260 return TRUE;
1261}
1262
1263# endif /* FEAT_GUI_W32 */
1264#endif /* FEAT_MOUSE */
1265
1266
1267#ifdef MCH_CURSOR_SHAPE
1268/*
1269 * Set the shape of the cursor.
1270 * 'thickness' can be from 1 (thin) to 99 (block)
1271 */
1272 static void
1273mch_set_cursor_shape(int thickness)
1274{
1275 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1276 ConsoleCursorInfo.dwSize = thickness;
1277 ConsoleCursorInfo.bVisible = s_cursor_visible;
1278
1279 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1280 if (s_cursor_visible)
1281 SetConsoleCursorPosition(g_hConOut, g_coord);
1282}
1283
1284 void
1285mch_update_cursor(void)
1286{
1287 int idx;
1288 int thickness;
1289
1290 /*
1291 * How the cursor is drawn depends on the current mode.
1292 */
1293 idx = get_shape_idx(FALSE);
1294
1295 if (shape_table[idx].shape == SHAPE_BLOCK)
1296 thickness = 99; /* 100 doesn't work on W95 */
1297 else
1298 thickness = shape_table[idx].percentage;
1299 mch_set_cursor_shape(thickness);
1300}
1301#endif
1302
1303#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1304/*
1305 * Handle FOCUS_EVENT.
1306 */
1307 static void
1308handle_focus_event(INPUT_RECORD ir)
1309{
1310 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1311 ui_focus_change((int)g_fJustGotFocus);
1312}
1313
1314/*
1315 * Wait until console input from keyboard or mouse is available,
1316 * or the time is up.
1317 * Return TRUE if something is available FALSE if not.
1318 */
1319 static int
1320WaitForChar(long msec)
1321{
1322 DWORD dwNow = 0, dwEndTime = 0;
1323 INPUT_RECORD ir;
1324 DWORD cRecords;
1325 char_u ch, ch2;
1326
1327 if (msec > 0)
1328 /* Wait until the specified time has elapsed. */
1329 dwEndTime = GetTickCount() + msec;
1330 else if (msec < 0)
1331 /* Wait forever. */
1332 dwEndTime = INFINITE;
1333
1334 /* We need to loop until the end of the time period, because
1335 * we might get multiple unusable mouse events in that time.
1336 */
1337 for (;;)
1338 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001339#ifdef FEAT_MZSCHEME
1340 mzvim_check_threads();
1341#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001342#ifdef FEAT_CLIENTSERVER
1343 serverProcessPendingMessages();
1344#endif
1345 if (0
1346#ifdef FEAT_MOUSE
1347 || g_nMouseClick != -1
1348#endif
1349#ifdef FEAT_CLIENTSERVER
1350 || input_available()
1351#endif
1352 )
1353 return TRUE;
1354
1355 if (msec > 0)
1356 {
1357 /* If the specified wait time has passed, return. */
1358 dwNow = GetTickCount();
1359 if (dwNow >= dwEndTime)
1360 break;
1361 }
1362 if (msec != 0)
1363 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001364 DWORD dwWaitTime = dwEndTime - dwNow;
1365
1366#ifdef FEAT_MZSCHEME
1367 if (mzthreads_allowed() && p_mzq > 0
1368 && (msec < 0 || (long)dwWaitTime > p_mzq))
1369 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1370#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001371#ifdef FEAT_CLIENTSERVER
1372 /* Wait for either an event on the console input or a message in
1373 * the client-server window. */
1374 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001375 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001376#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001377 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001378#endif
1379 continue;
1380 }
1381
1382 cRecords = 0;
1383 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1384
1385#ifdef FEAT_MBYTE_IME
1386 if (State & CMDLINE && msg_row == Rows - 1)
1387 {
1388 CONSOLE_SCREEN_BUFFER_INFO csbi;
1389
1390 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1391 {
1392 if (csbi.dwCursorPosition.Y != msg_row)
1393 {
1394 /* The screen is now messed up, must redraw the
1395 * command line and later all the windows. */
1396 redraw_all_later(CLEAR);
1397 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1398 redrawcmd();
1399 }
1400 }
1401 }
1402#endif
1403
1404 if (cRecords > 0)
1405 {
1406 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1407 {
1408#ifdef FEAT_MBYTE_IME
1409 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1410 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1411 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1412 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1413 {
1414 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1415 continue;
1416 }
1417#endif
1418 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1419 NULL, FALSE))
1420 return TRUE;
1421 }
1422
1423 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1424
1425 if (ir.EventType == FOCUS_EVENT)
1426 handle_focus_event(ir);
1427 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1428 shell_resized();
1429#ifdef FEAT_MOUSE
1430 else if (ir.EventType == MOUSE_EVENT
1431 && decode_mouse_event(&ir.Event.MouseEvent))
1432 return TRUE;
1433#endif
1434 }
1435 else if (msec == 0)
1436 break;
1437 }
1438
1439#ifdef FEAT_CLIENTSERVER
1440 /* Something might have been received while we were waiting. */
1441 if (input_available())
1442 return TRUE;
1443#endif
1444 return FALSE;
1445}
1446
1447#ifndef FEAT_GUI_MSWIN
1448/*
1449 * return non-zero if a character is available
1450 */
1451 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001452mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001453{
1454 return WaitForChar(0L);
1455}
1456#endif
1457
1458/*
1459 * Create the console input. Used when reading stdin doesn't work.
1460 */
1461 static void
1462create_conin(void)
1463{
1464 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1465 FILE_SHARE_READ|FILE_SHARE_WRITE,
1466 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001467 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001468 did_create_conin = TRUE;
1469}
1470
1471/*
1472 * Get a keystroke or a mouse event
1473 */
1474 static char_u
1475tgetch(int *pmodifiers, char_u *pch2)
1476{
1477 char_u ch;
1478
1479 for (;;)
1480 {
1481 INPUT_RECORD ir;
1482 DWORD cRecords = 0;
1483
1484#ifdef FEAT_CLIENTSERVER
1485 (void)WaitForChar(-1L);
1486 if (input_available())
1487 return 0;
1488# ifdef FEAT_MOUSE
1489 if (g_nMouseClick != -1)
1490 return 0;
1491# endif
1492#endif
1493 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1494 {
1495 if (did_create_conin)
1496 read_error_exit();
1497 create_conin();
1498 continue;
1499 }
1500
1501 if (ir.EventType == KEY_EVENT)
1502 {
1503 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1504 pmodifiers, TRUE))
1505 return ch;
1506 }
1507 else if (ir.EventType == FOCUS_EVENT)
1508 handle_focus_event(ir);
1509 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1510 shell_resized();
1511#ifdef FEAT_MOUSE
1512 else if (ir.EventType == MOUSE_EVENT)
1513 {
1514 if (decode_mouse_event(&ir.Event.MouseEvent))
1515 return 0;
1516 }
1517#endif
1518 }
1519}
1520#endif /* !FEAT_GUI_W32 */
1521
1522
1523/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001524 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001525 * Get one or more characters from the keyboard or the mouse.
1526 * If time == 0, do not wait for characters.
1527 * If time == n, wait a short time for characters.
1528 * If time == -1, wait forever for characters.
1529 * Returns the number of characters read into buf.
1530 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001531/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001532 int
1533mch_inchar(
1534 char_u *buf,
1535 int maxlen,
1536 long time,
1537 int tb_change_cnt)
1538{
1539#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1540
1541 int len;
1542 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543#define TYPEAHEADLEN 20
1544 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1545 static int typeaheadlen = 0;
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001546#ifdef FEAT_MBYTE
1547 static char_u *rest = NULL; /* unconverted rest of previous read */
1548 static int restlen = 0;
1549 int unconverted;
1550#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001551
1552 /* First use any typeahead that was kept because "buf" was too small. */
1553 if (typeaheadlen > 0)
1554 goto theend;
1555
1556#ifdef FEAT_SNIFF
1557 if (want_sniff_request)
1558 {
1559 if (sniff_request_waiting)
1560 {
1561 /* return K_SNIFF */
1562 typeahead[typeaheadlen++] = CSI;
1563 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1564 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1565 sniff_request_waiting = 0;
1566 want_sniff_request = 0;
1567 goto theend;
1568 }
1569 else if (time < 0 || time > 250)
1570 {
1571 /* don't wait too long, a request might be pending */
1572 time = 250;
1573 }
1574 }
1575#endif
1576
1577 if (time >= 0)
1578 {
1579 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001581 }
1582 else /* time == -1, wait forever */
1583 {
1584 mch_set_winsize_now(); /* Allow winsize changes from now on */
1585
Bram Moolenaar3918c952005-03-15 22:34:55 +00001586 /*
1587 * If there is no character available within 2 seconds (default)
1588 * write the autoscript file to disk. Or cause the CursorHold event
1589 * to be triggered.
1590 */
1591 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 {
1593#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001594 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001596 buf[0] = K_SPECIAL;
1597 buf[1] = KS_EXTRA;
1598 buf[2] = (int)KE_CURSORHOLD;
1599 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600 }
1601#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001602 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603 }
1604 }
1605
1606 /*
1607 * Try to read as many characters as there are, until the buffer is full.
1608 */
1609
1610 /* we will get at least one key. Get more if they are available. */
1611 g_fCBrkPressed = FALSE;
1612
1613#ifdef MCH_WRITE_DUMP
1614 if (fdDump)
1615 fputc('[', fdDump);
1616#endif
1617
1618 /* Keep looping until there is something in the typeahead buffer and more
1619 * to get and still room in the buffer (up to two bytes for a char and
1620 * three bytes for a modifier). */
1621 while ((typeaheadlen == 0 || WaitForChar(0L))
1622 && typeaheadlen + 5 <= TYPEAHEADLEN)
1623 {
1624 if (typebuf_changed(tb_change_cnt))
1625 {
1626 /* "buf" may be invalid now if a client put something in the
1627 * typeahead buffer and "buf" is in the typeahead buffer. */
1628 typeaheadlen = 0;
1629 break;
1630 }
1631#ifdef FEAT_MOUSE
1632 if (g_nMouseClick != -1)
1633 {
1634# ifdef MCH_WRITE_DUMP
1635 if (fdDump)
1636 fprintf(fdDump, "{%02x @ %d, %d}",
1637 g_nMouseClick, g_xMouse, g_yMouse);
1638# endif
1639 typeahead[typeaheadlen++] = ESC + 128;
1640 typeahead[typeaheadlen++] = 'M';
1641 typeahead[typeaheadlen++] = g_nMouseClick;
1642 typeahead[typeaheadlen++] = g_xMouse + '!';
1643 typeahead[typeaheadlen++] = g_yMouse + '!';
1644 g_nMouseClick = -1;
1645 }
1646 else
1647#endif
1648 {
1649 char_u ch2 = NUL;
1650 int modifiers = 0;
1651
1652 c = tgetch(&modifiers, &ch2);
1653
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001654#ifdef FEAT_MBYTE
1655 /* stolen from fill_input_buf() in ui.c */
1656 if (rest != NULL)
1657 {
1658 /* Use remainder of previous call, starts with an invalid
1659 * character that may become valid when reading more. */
1660 if (restlen > TYPEAHEADLEN - typeaheadlen)
1661 unconverted = TYPEAHEADLEN - typeaheadlen;
1662 else
1663 unconverted = restlen;
1664 mch_memmove(typeahead + typeaheadlen, rest, unconverted);
1665 if (unconverted == restlen)
1666 {
1667 vim_free(rest);
1668 rest = NULL;
1669 }
1670 else
1671 {
1672 restlen -= unconverted;
1673 mch_memmove(rest, rest + unconverted, restlen);
1674 }
1675 typeaheadlen += unconverted;
1676 }
1677 else
1678 unconverted = 0;
1679#endif
1680
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681 if (typebuf_changed(tb_change_cnt))
1682 {
1683 /* "buf" may be invalid now if a client put something in the
1684 * typeahead buffer and "buf" is in the typeahead buffer. */
1685 typeaheadlen = 0;
1686 break;
1687 }
1688
1689 if (c == Ctrl_C && ctrl_c_interrupts)
1690 {
1691#if defined(FEAT_CLIENTSERVER)
1692 trash_input_buf();
1693#endif
1694 got_int = TRUE;
1695 }
1696
1697#ifdef FEAT_MOUSE
1698 if (g_nMouseClick == -1)
1699#endif
1700 {
1701 int n = 1;
1702
1703 /* A key may have one or two bytes. */
1704 typeahead[typeaheadlen] = c;
1705 if (ch2 != NUL)
1706 {
1707 typeahead[typeaheadlen + 1] = ch2;
1708 ++n;
1709 }
1710#ifdef FEAT_MBYTE
1711 /* Only convert normal characters, not special keys. Need to
1712 * convert before applying ALT, otherwise mapping <M-x> breaks
1713 * when 'tenc' is set. */
1714 if (input_conv.vc_type != CONV_NONE
1715 && (ch2 == NUL || c != K_NUL))
Bram Moolenaarffeedec2013-02-13 16:49:58 +01001716 {
1717 typeaheadlen -= unconverted;
1718 n = convert_input_safe(typeahead + typeaheadlen,
1719 n + unconverted, TYPEAHEADLEN - typeaheadlen,
1720 rest == NULL ? &rest : NULL, &restlen);
1721 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722#endif
1723
1724 /* Use the ALT key to set the 8th bit of the character
1725 * when it's one byte, the 8th bit isn't set yet and not
1726 * using a double-byte encoding (would become a lead
1727 * byte). */
1728 if ((modifiers & MOD_MASK_ALT)
1729 && n == 1
1730 && (typeahead[typeaheadlen] & 0x80) == 0
1731#ifdef FEAT_MBYTE
1732 && !enc_dbcs
1733#endif
1734 )
1735 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001736#ifdef FEAT_MBYTE
1737 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1738 typeahead + typeaheadlen);
1739#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001740 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001741#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001742 modifiers &= ~MOD_MASK_ALT;
1743 }
1744
1745 if (modifiers != 0)
1746 {
1747 /* Prepend modifiers to the character. */
1748 mch_memmove(typeahead + typeaheadlen + 3,
1749 typeahead + typeaheadlen, n);
1750 typeahead[typeaheadlen++] = K_SPECIAL;
1751 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1752 typeahead[typeaheadlen++] = modifiers;
1753 }
1754
1755 typeaheadlen += n;
1756
1757#ifdef MCH_WRITE_DUMP
1758 if (fdDump)
1759 fputc(c, fdDump);
1760#endif
1761 }
1762 }
1763 }
1764
1765#ifdef MCH_WRITE_DUMP
1766 if (fdDump)
1767 {
1768 fputs("]\n", fdDump);
1769 fflush(fdDump);
1770 }
1771#endif
1772
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773theend:
1774 /* Move typeahead to "buf", as much as fits. */
1775 len = 0;
1776 while (len < maxlen && typeaheadlen > 0)
1777 {
1778 buf[len++] = typeahead[0];
1779 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1780 }
1781 return len;
1782
1783#else /* FEAT_GUI_W32 */
1784 return 0;
1785#endif /* FEAT_GUI_W32 */
1786}
1787
Bram Moolenaar82881492012-11-20 16:53:39 +01001788#ifndef PROTO
1789# ifndef __MINGW32__
1790# include <shellapi.h> /* required for FindExecutable() */
1791# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001792#endif
1793
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001794/*
1795 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001796 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001797 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001798 static int
1799executable_exists(char *name)
1800{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001801 char *dum;
1802 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001803
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001804#ifdef FEAT_MBYTE
1805 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001806 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001807 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001808 WCHAR fnamew[_MAX_PATH];
1809 WCHAR *dumw;
1810 long n;
1811
1812 if (p != NULL)
1813 {
1814 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1815 vim_free(p);
1816 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1817 {
1818 if (n == 0)
1819 return FALSE;
1820 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1821 return FALSE;
1822 return TRUE;
1823 }
1824 /* Retry with non-wide function (for Windows 98). */
1825 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001826 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001827#endif
1828 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1829 return FALSE;
1830 if (mch_isdir(fname))
1831 return FALSE;
1832 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833}
1834
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001835#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02001836 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001837/*
1838 * Bad parameter handler.
1839 *
1840 * Certain MS CRT functions will intentionally crash when passed invalid
1841 * parameters to highlight possible security holes. Setting this function as
1842 * the bad parameter handler will prevent the crash.
1843 *
1844 * In debug builds the parameters contain CRT information that might help track
1845 * down the source of a problem, but in non-debug builds the arguments are all
1846 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
1847 * worth allowing these to make debugging of issues easier.
1848 */
1849 static void
1850bad_param_handler(const wchar_t *expression,
1851 const wchar_t *function,
1852 const wchar_t *file,
1853 unsigned int line,
1854 uintptr_t pReserved)
1855{
1856}
1857
1858# define SET_INVALID_PARAM_HANDLER \
1859 ((void)_set_invalid_parameter_handler(bad_param_handler))
1860#else
1861# define SET_INVALID_PARAM_HANDLER
1862#endif
1863
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864#ifdef FEAT_GUI_W32
1865
1866/*
1867 * GUI version of mch_init().
1868 */
1869 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001870mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871{
1872#ifndef __MINGW32__
1873 extern int _fmode;
1874#endif
1875
Bram Moolenaard32a99a2010-09-21 17:29:23 +02001876 /* Silently handle invalid parameters to CRT functions */
1877 SET_INVALID_PARAM_HANDLER;
1878
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 /* Let critical errors result in a failure, not in a dialog box. Required
1880 * for the timestamp test to work on removed floppies. */
1881 SetErrorMode(SEM_FAILCRITICALERRORS);
1882
1883 _fmode = O_BINARY; /* we do our own CR-LF translation */
1884
1885 /* Specify window size. Is there a place to get the default from? */
1886 Rows = 25;
1887 Columns = 80;
1888
1889 /* Look for 'vimrun' */
1890 if (!gui_is_win32s())
1891 {
1892 char_u vimrun_location[_MAX_PATH + 4];
1893
1894 /* First try in same directory as gvim.exe */
1895 STRCPY(vimrun_location, exe_name);
1896 STRCPY(gettail(vimrun_location), "vimrun.exe");
1897 if (mch_getperm(vimrun_location) >= 0)
1898 {
1899 if (*skiptowhite(vimrun_location) != NUL)
1900 {
1901 /* Enclose path with white space in double quotes. */
1902 mch_memmove(vimrun_location + 1, vimrun_location,
1903 STRLEN(vimrun_location) + 1);
1904 *vimrun_location = '"';
1905 STRCPY(gettail(vimrun_location), "vimrun\" ");
1906 }
1907 else
1908 STRCPY(gettail(vimrun_location), "vimrun ");
1909
1910 vimrun_path = (char *)vim_strsave(vimrun_location);
1911 s_dont_use_vimrun = FALSE;
1912 }
1913 else if (executable_exists("vimrun.exe"))
1914 s_dont_use_vimrun = FALSE;
1915
1916 /* Don't give the warning for a missing vimrun.exe right now, but only
1917 * when vimrun was supposed to be used. Don't bother people that do
1918 * not need vimrun.exe. */
1919 if (s_dont_use_vimrun)
1920 need_vimrun_warning = TRUE;
1921 }
1922
1923 /*
1924 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1925 * Otherwise the default "findstr /n" is used.
1926 */
1927 if (!executable_exists("findstr.exe"))
1928 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1929
1930#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01001931 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932#endif
1933}
1934
1935
1936#else /* FEAT_GUI_W32 */
1937
1938#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1939#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1940
1941/*
1942 * ClearConsoleBuffer()
1943 * Description:
1944 * Clears the entire contents of the console screen buffer, using the
1945 * specified attribute.
1946 * Returns:
1947 * TRUE on success
1948 */
1949 static BOOL
1950ClearConsoleBuffer(WORD wAttribute)
1951{
1952 CONSOLE_SCREEN_BUFFER_INFO csbi;
1953 COORD coord;
1954 DWORD NumCells, dummy;
1955
1956 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1957 return FALSE;
1958
1959 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1960 coord.X = 0;
1961 coord.Y = 0;
1962 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1963 coord, &dummy))
1964 {
1965 return FALSE;
1966 }
1967 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1968 coord, &dummy))
1969 {
1970 return FALSE;
1971 }
1972
1973 return TRUE;
1974}
1975
1976/*
1977 * FitConsoleWindow()
1978 * Description:
1979 * Checks if the console window will fit within given buffer dimensions.
1980 * Also, if requested, will shrink the window to fit.
1981 * Returns:
1982 * TRUE on success
1983 */
1984 static BOOL
1985FitConsoleWindow(
1986 COORD dwBufferSize,
1987 BOOL WantAdjust)
1988{
1989 CONSOLE_SCREEN_BUFFER_INFO csbi;
1990 COORD dwWindowSize;
1991 BOOL NeedAdjust = FALSE;
1992
1993 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1994 {
1995 /*
1996 * A buffer resize will fail if the current console window does
1997 * not lie completely within that buffer. To avoid this, we might
1998 * have to move and possibly shrink the window.
1999 */
2000 if (csbi.srWindow.Right >= dwBufferSize.X)
2001 {
2002 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2003 if (dwWindowSize.X > dwBufferSize.X)
2004 dwWindowSize.X = dwBufferSize.X;
2005 csbi.srWindow.Right = dwBufferSize.X - 1;
2006 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2007 NeedAdjust = TRUE;
2008 }
2009 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2010 {
2011 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2012 if (dwWindowSize.Y > dwBufferSize.Y)
2013 dwWindowSize.Y = dwBufferSize.Y;
2014 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2015 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2016 NeedAdjust = TRUE;
2017 }
2018 if (NeedAdjust && WantAdjust)
2019 {
2020 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2021 return FALSE;
2022 }
2023 return TRUE;
2024 }
2025
2026 return FALSE;
2027}
2028
2029typedef struct ConsoleBufferStruct
2030{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002031 BOOL IsValid;
2032 CONSOLE_SCREEN_BUFFER_INFO Info;
2033 PCHAR_INFO Buffer;
2034 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002035} ConsoleBuffer;
2036
2037/*
2038 * SaveConsoleBuffer()
2039 * Description:
2040 * Saves important information about the console buffer, including the
2041 * actual buffer contents. The saved information is suitable for later
2042 * restoration by RestoreConsoleBuffer().
2043 * Returns:
2044 * TRUE if all information was saved; FALSE otherwise
2045 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2046 */
2047 static BOOL
2048SaveConsoleBuffer(
2049 ConsoleBuffer *cb)
2050{
2051 DWORD NumCells;
2052 COORD BufferCoord;
2053 SMALL_RECT ReadRegion;
2054 WORD Y, Y_incr;
2055
2056 if (cb == NULL)
2057 return FALSE;
2058
2059 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
2060 {
2061 cb->IsValid = FALSE;
2062 return FALSE;
2063 }
2064 cb->IsValid = TRUE;
2065
2066 /*
2067 * Allocate a buffer large enough to hold the entire console screen
2068 * buffer. If this ConsoleBuffer structure has already been initialized
2069 * with a buffer of the correct size, then just use that one.
2070 */
2071 if (!cb->IsValid || cb->Buffer == NULL ||
2072 cb->BufferSize.X != cb->Info.dwSize.X ||
2073 cb->BufferSize.Y != cb->Info.dwSize.Y)
2074 {
2075 cb->BufferSize.X = cb->Info.dwSize.X;
2076 cb->BufferSize.Y = cb->Info.dwSize.Y;
2077 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
Bram Moolenaar3c2d6532011-02-01 13:48:53 +01002078 vim_free(cb->Buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2080 if (cb->Buffer == NULL)
2081 return FALSE;
2082 }
2083
2084 /*
2085 * We will now copy the console screen buffer into our buffer.
2086 * ReadConsoleOutput() seems to be limited as far as how much you
2087 * can read at a time. Empirically, this number seems to be about
2088 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2089 * in chunks until it is all copied. The chunks will all have the
2090 * same horizontal characteristics, so initialize them now. The
2091 * height of each chunk will be (12000 / width).
2092 */
2093 BufferCoord.X = 0;
2094 ReadRegion.Left = 0;
2095 ReadRegion.Right = cb->Info.dwSize.X - 1;
2096 Y_incr = 12000 / cb->Info.dwSize.X;
2097 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
2098 {
2099 /*
2100 * Read into position (0, Y) in our buffer.
2101 */
2102 BufferCoord.Y = Y;
2103 /*
2104 * Read the region whose top left corner is (0, Y) and whose bottom
2105 * right corner is (width - 1, Y + Y_incr - 1). This should define
2106 * a region of size width by Y_incr. Don't worry if this region is
2107 * too large for the remaining buffer; it will be cropped.
2108 */
2109 ReadRegion.Top = Y;
2110 ReadRegion.Bottom = Y + Y_incr - 1;
2111 if (!ReadConsoleOutput(g_hConOut, /* output handle */
2112 cb->Buffer, /* our buffer */
2113 cb->BufferSize, /* dimensions of our buffer */
2114 BufferCoord, /* offset in our buffer */
2115 &ReadRegion)) /* region to save */
2116 {
2117 vim_free(cb->Buffer);
2118 cb->Buffer = NULL;
2119 return FALSE;
2120 }
2121 }
2122
2123 return TRUE;
2124}
2125
2126/*
2127 * RestoreConsoleBuffer()
2128 * Description:
2129 * Restores important information about the console buffer, including the
2130 * actual buffer contents, if desired. The information to restore is in
2131 * the same format used by SaveConsoleBuffer().
2132 * Returns:
2133 * TRUE on success
2134 */
2135 static BOOL
2136RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002137 ConsoleBuffer *cb,
2138 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002139{
2140 COORD BufferCoord;
2141 SMALL_RECT WriteRegion;
2142
2143 if (cb == NULL || !cb->IsValid)
2144 return FALSE;
2145
2146 /*
2147 * Before restoring the buffer contents, clear the current buffer, and
2148 * restore the cursor position and window information. Doing this now
2149 * prevents old buffer contents from "flashing" onto the screen.
2150 */
2151 if (RestoreScreen)
2152 ClearConsoleBuffer(cb->Info.wAttributes);
2153
2154 FitConsoleWindow(cb->Info.dwSize, TRUE);
2155 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2156 return FALSE;
2157 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2158 return FALSE;
2159
2160 if (!RestoreScreen)
2161 {
2162 /*
2163 * No need to restore the screen buffer contents, so we're done.
2164 */
2165 return TRUE;
2166 }
2167
2168 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2169 return FALSE;
2170 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2171 return FALSE;
2172
2173 /*
2174 * Restore the screen buffer contents.
2175 */
2176 if (cb->Buffer != NULL)
2177 {
2178 BufferCoord.X = 0;
2179 BufferCoord.Y = 0;
2180 WriteRegion.Left = 0;
2181 WriteRegion.Top = 0;
2182 WriteRegion.Right = cb->Info.dwSize.X - 1;
2183 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
2184 if (!WriteConsoleOutput(g_hConOut, /* output handle */
2185 cb->Buffer, /* our buffer */
2186 cb->BufferSize, /* dimensions of our buffer */
2187 BufferCoord, /* offset in our buffer */
2188 &WriteRegion)) /* region to restore */
2189 {
2190 return FALSE;
2191 }
2192 }
2193
2194 return TRUE;
2195}
2196
Bram Moolenaar362e1a32006-03-06 23:29:24 +00002197#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198#ifdef FEAT_RESTORE_ORIG_SCREEN
2199static ConsoleBuffer g_cbOrig = { 0 };
2200#endif
2201static ConsoleBuffer g_cbNonTermcap = { 0 };
2202static ConsoleBuffer g_cbTermcap = { 0 };
2203
2204#ifdef FEAT_TITLE
2205#ifdef __BORLANDC__
2206typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2207#else
2208typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
2209#endif
2210char g_szOrigTitle[256] = { 0 };
2211HWND g_hWnd = NULL; /* also used in os_mswin.c */
2212static HICON g_hOrigIconSmall = NULL;
2213static HICON g_hOrigIcon = NULL;
2214static HICON g_hVimIcon = NULL;
2215static BOOL g_fCanChangeIcon = FALSE;
2216
2217/* ICON* are not defined in VC++ 4.0 */
2218#ifndef ICON_SMALL
2219#define ICON_SMALL 0
2220#endif
2221#ifndef ICON_BIG
2222#define ICON_BIG 1
2223#endif
2224/*
2225 * GetConsoleIcon()
2226 * Description:
2227 * Attempts to retrieve the small icon and/or the big icon currently in
2228 * use by a given window.
2229 * Returns:
2230 * TRUE on success
2231 */
2232 static BOOL
2233GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002234 HWND hWnd,
2235 HICON *phIconSmall,
2236 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002237{
2238 if (hWnd == NULL)
2239 return FALSE;
2240
2241 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002242 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2243 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002245 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2246 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002247 return TRUE;
2248}
2249
2250/*
2251 * SetConsoleIcon()
2252 * Description:
2253 * Attempts to change the small icon and/or the big icon currently in
2254 * use by a given window.
2255 * Returns:
2256 * TRUE on success
2257 */
2258 static BOOL
2259SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002260 HWND hWnd,
2261 HICON hIconSmall,
2262 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002263{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002264 HICON hPrevIconSmall;
2265 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002266
2267 if (hWnd == NULL)
2268 return FALSE;
2269
2270 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002271 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2272 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002274 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2275 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002276 return TRUE;
2277}
2278
2279/*
2280 * SaveConsoleTitleAndIcon()
2281 * Description:
2282 * Saves the current console window title in g_szOrigTitle, for later
2283 * restoration. Also, attempts to obtain a handle to the console window,
2284 * and use it to save the small and big icons currently in use by the
2285 * console window. This is not always possible on some versions of Windows;
2286 * nor is it possible when running Vim remotely using Telnet (since the
2287 * console window the user sees is owned by a remote process).
2288 */
2289 static void
2290SaveConsoleTitleAndIcon(void)
2291{
2292 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2293
2294 /* Save the original title. */
2295 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2296 return;
2297
2298 /*
2299 * Obtain a handle to the console window using GetConsoleWindow() from
2300 * KERNEL32.DLL; we need to handle in order to change the window icon.
2301 * This function only exists on NT-based Windows, starting with Windows
2302 * 2000. On older operating systems, we can't change the window icon
2303 * anyway.
2304 */
2305 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2306 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2307 "GetConsoleWindow")) != NULL)
2308 {
2309 g_hWnd = (*GetConsoleWindowProc)();
2310 }
2311 if (g_hWnd == NULL)
2312 return;
2313
2314 /* Save the original console window icon. */
2315 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2316 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2317 return;
2318
2319 /* Extract the first icon contained in the Vim executable. */
2320 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2321 if (g_hVimIcon != NULL)
2322 g_fCanChangeIcon = TRUE;
2323}
2324#endif
2325
2326static int g_fWindInitCalled = FALSE;
2327static int g_fTermcapMode = FALSE;
2328static CONSOLE_CURSOR_INFO g_cci;
2329static DWORD g_cmodein = 0;
2330static DWORD g_cmodeout = 0;
2331
2332/*
2333 * non-GUI version of mch_init().
2334 */
2335 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002336mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337{
2338#ifndef FEAT_RESTORE_ORIG_SCREEN
2339 CONSOLE_SCREEN_BUFFER_INFO csbi;
2340#endif
2341#ifndef __MINGW32__
2342 extern int _fmode;
2343#endif
2344
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002345 /* Silently handle invalid parameters to CRT functions */
2346 SET_INVALID_PARAM_HANDLER;
2347
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 /* Let critical errors result in a failure, not in a dialog box. Required
2349 * for the timestamp test to work on removed floppies. */
2350 SetErrorMode(SEM_FAILCRITICALERRORS);
2351
2352 _fmode = O_BINARY; /* we do our own CR-LF translation */
2353 out_flush();
2354
2355 /* Obtain handles for the standard Console I/O devices */
2356 if (read_cmd_fd == 0)
2357 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2358 else
2359 create_conin();
2360 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2361
2362#ifdef FEAT_RESTORE_ORIG_SCREEN
2363 /* Save the initial console buffer for later restoration */
2364 SaveConsoleBuffer(&g_cbOrig);
2365 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2366#else
2367 /* Get current text attributes */
2368 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2369 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2370#endif
2371 if (cterm_normal_fg_color == 0)
2372 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2373 if (cterm_normal_bg_color == 0)
2374 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2375
2376 /* set termcap codes to current text attributes */
2377 update_tcap(g_attrCurrent);
2378
2379 GetConsoleCursorInfo(g_hConOut, &g_cci);
2380 GetConsoleMode(g_hConIn, &g_cmodein);
2381 GetConsoleMode(g_hConOut, &g_cmodeout);
2382
2383#ifdef FEAT_TITLE
2384 SaveConsoleTitleAndIcon();
2385 /*
2386 * Set both the small and big icons of the console window to Vim's icon.
2387 * Note that Vim presently only has one size of icon (32x32), but it
2388 * automatically gets scaled down to 16x16 when setting the small icon.
2389 */
2390 if (g_fCanChangeIcon)
2391 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2392#endif
2393
2394 ui_get_shellsize();
2395
2396#ifdef MCH_WRITE_DUMP
2397 fdDump = fopen("dump", "wt");
2398
2399 if (fdDump)
2400 {
2401 time_t t;
2402
2403 time(&t);
2404 fputs(ctime(&t), fdDump);
2405 fflush(fdDump);
2406 }
2407#endif
2408
2409 g_fWindInitCalled = TRUE;
2410
2411#ifdef FEAT_MOUSE
2412 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2413#endif
2414
2415#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002416 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002417#endif
2418
2419 /* This will be NULL on anything but NT 4.0 */
2420 s_pfnGetConsoleKeyboardLayoutName =
2421 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2422 "GetConsoleKeyboardLayoutNameA");
2423}
2424
2425/*
2426 * non-GUI version of mch_exit().
2427 * Shut down and exit with status `r'
2428 * Careful: mch_exit() may be called before mch_init()!
2429 */
2430 void
2431mch_exit(int r)
2432{
2433 stoptermcap();
2434
2435 if (g_fWindInitCalled)
2436 settmode(TMODE_COOK);
2437
2438 ml_close_all(TRUE); /* remove all memfiles */
2439
2440 if (g_fWindInitCalled)
2441 {
2442#ifdef FEAT_TITLE
2443 mch_restore_title(3);
2444 /*
2445 * Restore both the small and big icons of the console window to
2446 * what they were at startup. Don't do this when the window is
2447 * closed, Vim would hang here.
2448 */
2449 if (g_fCanChangeIcon && !g_fForceExit)
2450 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2451#endif
2452
2453#ifdef MCH_WRITE_DUMP
2454 if (fdDump)
2455 {
2456 time_t t;
2457
2458 time(&t);
2459 fputs(ctime(&t), fdDump);
2460 fclose(fdDump);
2461 }
2462 fdDump = NULL;
2463#endif
2464 }
2465
2466 SetConsoleCursorInfo(g_hConOut, &g_cci);
2467 SetConsoleMode(g_hConIn, g_cmodein);
2468 SetConsoleMode(g_hConOut, g_cmodeout);
2469
2470#ifdef DYNAMIC_GETTEXT
2471 dyn_libintl_end();
2472#endif
2473
2474 exit(r);
2475}
2476#endif /* !FEAT_GUI_W32 */
2477
Bram Moolenaar071d4272004-06-13 20:20:40 +00002478/*
2479 * Do we have an interactive window?
2480 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002481/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002482 int
2483mch_check_win(
2484 int argc,
2485 char **argv)
2486{
2487 get_exe_name();
2488
2489#ifdef FEAT_GUI_W32
2490 return OK; /* GUI always has a tty */
2491#else
2492 if (isatty(1))
2493 return OK;
2494 return FAIL;
2495#endif
2496}
2497
2498
2499/*
2500 * fname_case(): Set the case of the file name, if it already exists.
2501 * When "len" is > 0, also expand short to long filenames.
2502 */
2503 void
2504fname_case(
2505 char_u *name,
2506 int len)
2507{
2508 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002509 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002510 char *ptrue, *ptruePrev;
2511 char *porig, *porigPrev;
2512 int flen;
2513 WIN32_FIND_DATA fb;
2514 HANDLE hFind;
2515 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002516 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002517
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002518 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519 if (flen == 0 || flen > _MAX_PATH)
2520 return;
2521
2522 slash_adjust(name);
2523
2524 /* Build the new name in szTrueName[] one component at a time. */
2525 porig = name;
2526 ptrue = szTrueName;
2527
2528 if (isalpha(porig[0]) && porig[1] == ':')
2529 {
2530 /* copy leading drive letter */
2531 *ptrue++ = *porig++;
2532 *ptrue++ = *porig++;
2533 *ptrue = NUL; /* in case nothing follows */
2534 }
2535
2536 while (*porig != NUL)
2537 {
2538 /* copy \ characters */
2539 while (*porig == psepc)
2540 *ptrue++ = *porig++;
2541
2542 ptruePrev = ptrue;
2543 porigPrev = porig;
2544 while (*porig != NUL && *porig != psepc)
2545 {
2546#ifdef FEAT_MBYTE
2547 int l;
2548
2549 if (enc_dbcs)
2550 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002551 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002552 while (--l >= 0)
2553 *ptrue++ = *porig++;
2554 }
2555 else
2556#endif
2557 *ptrue++ = *porig++;
2558 }
2559 *ptrue = NUL;
2560
Bram Moolenaar464c9252010-10-13 20:37:41 +02002561 /* To avoid a slow failure append "\*" when searching a directory,
2562 * server or network share. */
2563 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002564 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002565 if (*porig == psepc && slen + 2 < _MAX_PATH)
2566 STRCPY(szTrueNameTemp + slen, "\\*");
2567
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568 /* Skip "", "." and "..". */
2569 if (ptrue > ptruePrev
2570 && (ptruePrev[0] != '.'
2571 || (ptruePrev[1] != NUL
2572 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002573 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574 != INVALID_HANDLE_VALUE)
2575 {
2576 c = *porig;
2577 *porig = NUL;
2578
2579 /* Only use the match when it's the same name (ignoring case) or
2580 * expansion is allowed and there is a match with the short name
2581 * and there is enough room. */
2582 if (_stricoll(porigPrev, fb.cFileName) == 0
2583 || (len > 0
2584 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2585 && (int)(ptruePrev - szTrueName)
2586 + (int)strlen(fb.cFileName) < len)))
2587 {
2588 STRCPY(ptruePrev, fb.cFileName);
2589
2590 /* Look for exact match and prefer it if found. Must be a
2591 * long name, otherwise there would be only one match. */
2592 while (FindNextFile(hFind, &fb))
2593 {
2594 if (*fb.cAlternateFileName != NUL
2595 && (strcoll(porigPrev, fb.cFileName) == 0
2596 || (len > 0
2597 && (_stricoll(porigPrev,
2598 fb.cAlternateFileName) == 0
2599 && (int)(ptruePrev - szTrueName)
2600 + (int)strlen(fb.cFileName) < len))))
2601 {
2602 STRCPY(ptruePrev, fb.cFileName);
2603 break;
2604 }
2605 }
2606 }
2607 FindClose(hFind);
2608 *porig = c;
2609 ptrue = ptruePrev + strlen(ptruePrev);
2610 }
2611 }
2612
2613 STRCPY(name, szTrueName);
2614}
2615
2616
2617/*
2618 * Insert user name in s[len].
2619 */
2620 int
2621mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002622 char_u *s,
2623 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002625 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 DWORD cch = sizeof szUserName;
2627
2628 if (GetUserName(szUserName, &cch))
2629 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002630 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002631 return OK;
2632 }
2633 s[0] = NUL;
2634 return FAIL;
2635}
2636
2637
2638/*
2639 * Insert host name in s[len].
2640 */
2641 void
2642mch_get_host_name(
2643 char_u *s,
2644 int len)
2645{
2646 DWORD cch = len;
2647
2648 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002649 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002650}
2651
2652
2653/*
2654 * return process ID
2655 */
2656 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002657mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002658{
2659 return (long)GetCurrentProcessId();
2660}
2661
2662
2663/*
2664 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2665 * Return OK for success, FAIL for failure.
2666 */
2667 int
2668mch_dirname(
2669 char_u *buf,
2670 int len)
2671{
2672 /*
2673 * Originally this was:
2674 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2675 * But the Win32s known bug list says that getcwd() doesn't work
2676 * so use the Win32 system call instead. <Negri>
2677 */
2678#ifdef FEAT_MBYTE
2679 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2680 {
2681 WCHAR wbuf[_MAX_PATH + 1];
2682
2683 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2684 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002685 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002686
2687 if (p != NULL)
2688 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002689 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690 vim_free(p);
2691 return OK;
2692 }
2693 }
2694 /* Retry with non-wide function (for Windows 98). */
2695 }
2696#endif
2697 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2698}
2699
2700/*
2701 * get file permissions for `name'
2702 * -1 : error
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002703 * else mode_t
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704 */
2705 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002706mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002707{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002708 struct stat st;
2709 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002711 n = mch_stat(name, &st);
2712 return n == 0 ? (int)st.st_mode : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002713}
2714
2715
2716/*
2717 * set file permission for `name' to `perm'
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002718 *
2719 * return FAIL for failure, OK otherwise
Bram Moolenaar071d4272004-06-13 20:20:40 +00002720 */
2721 int
2722mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002723 char_u *name,
2724 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002725{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002726 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727#ifdef FEAT_MBYTE
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002728 WCHAR *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002729 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2730 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002731 p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002732
2733 if (p != NULL)
2734 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002735 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002737 if (n == -1 && GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2738 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002739 /* Retry with non-wide function (for Windows 98). */
2740 }
2741 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002742 if (p == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002743#endif
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002744 n = _chmod(name, perm);
2745 if (n == -1)
2746 return FAIL;
2747
2748 win32_set_archive(name);
2749
2750 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002751}
2752
2753/*
2754 * Set hidden flag for "name".
2755 */
2756 void
2757mch_hide(char_u *name)
2758{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002759 int attrs = win32_getattrs(name);
2760 if (attrs == -1)
2761 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002762
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002763 attrs |= FILE_ATTRIBUTE_HIDDEN;
2764 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765}
2766
2767/*
2768 * return TRUE if "name" is a directory
2769 * return FALSE if "name" is not a directory or upon error
2770 */
2771 int
2772mch_isdir(char_u *name)
2773{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002774 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002775
2776 if (f == -1)
2777 return FALSE; /* file does not exist at all */
2778
2779 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2780}
2781
2782/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02002783 * Create directory "name".
2784 * Return 0 on success, -1 on error.
2785 */
2786 int
2787mch_mkdir(char_u *name)
2788{
2789#ifdef FEAT_MBYTE
2790 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2791 {
2792 WCHAR *p;
2793 int retval;
2794
2795 p = enc_to_utf16(name, NULL);
2796 if (p == NULL)
2797 return -1;
2798 retval = _wmkdir(p);
2799 vim_free(p);
2800 return retval;
2801 }
2802#endif
2803 return _mkdir(name);
2804}
2805
2806/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002807 * Return TRUE if file "fname" has more than one link.
2808 */
2809 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002810mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002811{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002812 BY_HANDLE_FILE_INFORMATION info;
2813
2814 return win32_fileinfo(fname, &info) == FILEINFO_OK
2815 && info.nNumberOfLinks > 1;
2816}
2817
2818/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002819 * Return TRUE if file "fname" is a symbolic link.
2820 */
2821 int
2822mch_is_symbolic_link(char_u *fname)
2823{
2824 HANDLE hFind;
2825 int res = FALSE;
2826 WIN32_FIND_DATAA findDataA;
2827 DWORD fileFlags = 0, reparseTag = 0;
2828#ifdef FEAT_MBYTE
2829 WCHAR *wn = NULL;
2830 WIN32_FIND_DATAW findDataW;
2831
2832 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2833 wn = enc_to_utf16(fname, NULL);
2834 if (wn != NULL)
2835 {
2836 hFind = FindFirstFileW(wn, &findDataW);
2837 vim_free(wn);
2838 if (hFind == INVALID_HANDLE_VALUE
2839 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2840 {
2841 /* Retry with non-wide function (for Windows 98). */
2842 hFind = FindFirstFile(fname, &findDataA);
2843 if (hFind != INVALID_HANDLE_VALUE)
2844 {
2845 fileFlags = findDataA.dwFileAttributes;
2846 reparseTag = findDataA.dwReserved0;
2847 }
2848 }
2849 else
2850 {
2851 fileFlags = findDataW.dwFileAttributes;
2852 reparseTag = findDataW.dwReserved0;
2853 }
2854 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002855 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002856#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02002857 {
2858 hFind = FindFirstFile(fname, &findDataA);
2859 if (hFind != INVALID_HANDLE_VALUE)
2860 {
2861 fileFlags = findDataA.dwFileAttributes;
2862 reparseTag = findDataA.dwReserved0;
2863 }
2864 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002865
2866 if (hFind != INVALID_HANDLE_VALUE)
2867 FindClose(hFind);
2868
2869 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
2870 && reparseTag == IO_REPARSE_TAG_SYMLINK)
2871 res = TRUE;
2872
2873 return res;
2874}
2875
2876/*
2877 * Return TRUE if file "fname" has more than one link or if it is a symbolic
2878 * link.
2879 */
2880 int
2881mch_is_linked(char_u *fname)
2882{
2883 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
2884 return TRUE;
2885 return FALSE;
2886}
2887
2888/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002889 * Get the by-handle-file-information for "fname".
2890 * Returns FILEINFO_OK when OK.
2891 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
2892 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
2893 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
2894 */
2895 int
2896win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
2897{
Bram Moolenaar03f48552006-02-28 23:52:23 +00002898 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002899 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002900#ifdef FEAT_MBYTE
2901 WCHAR *wn = NULL;
2902
2903 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002904 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00002905 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002906 if (wn == NULL)
2907 res = FILEINFO_ENC_FAIL;
2908 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00002909 if (wn != NULL)
2910 {
2911 hFile = CreateFileW(wn, /* file name */
2912 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002913 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002914 NULL, /* security descriptor */
2915 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002916 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002917 NULL); /* handle to template file */
2918 if (hFile == INVALID_HANDLE_VALUE
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002919 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
Bram Moolenaar03f48552006-02-28 23:52:23 +00002920 {
2921 /* Retry with non-wide function (for Windows 98). */
2922 vim_free(wn);
2923 wn = NULL;
2924 }
2925 }
2926 if (wn == NULL)
2927#endif
2928 hFile = CreateFile(fname, /* file name */
2929 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002930 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002931 NULL, /* security descriptor */
2932 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002933 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00002934 NULL); /* handle to template file */
2935
2936 if (hFile != INVALID_HANDLE_VALUE)
2937 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02002938 if (GetFileInformationByHandle(hFile, info) != 0)
2939 res = FILEINFO_OK;
2940 else
2941 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002942 CloseHandle(hFile);
2943 }
2944
2945#ifdef FEAT_MBYTE
2946 vim_free(wn);
2947#endif
2948 return res;
2949}
2950
2951/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02002952 * get file attributes for `name'
2953 * -1 : error
2954 * else FILE_ATTRIBUTE_* defined in winnt.h
2955 */
2956 static
2957 int
2958win32_getattrs(char_u *name)
2959{
2960 int attr;
2961#ifdef FEAT_MBYTE
2962 WCHAR *p = NULL;
2963
2964 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2965 p = enc_to_utf16(name, NULL);
2966
2967 if (p != NULL)
2968 {
2969 attr = GetFileAttributesW(p);
2970 if (attr < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2971 {
2972 /* Retry with non-wide function (for Windows 98). */
2973 vim_free(p);
2974 p = NULL;
2975 }
2976 }
2977 if (p == NULL)
2978#endif
2979 attr = GetFileAttributes((char *)name);
2980#ifdef FEAT_MBYTE
2981 vim_free(p);
2982#endif
2983 return attr;
2984}
2985
2986/*
2987 * set file attributes for `name' to `attrs'
2988 *
2989 * return -1 for failure, 0 otherwise
2990 */
2991 static
2992 int
2993win32_setattrs(char_u *name, int attrs)
2994{
2995 int res;
2996#ifdef FEAT_MBYTE
2997 WCHAR *p = NULL;
2998
2999 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3000 p = enc_to_utf16(name, NULL);
3001
3002 if (p != NULL)
3003 {
3004 res = SetFileAttributesW(p, attrs);
3005 if (res == FALSE
3006 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
3007 {
3008 /* Retry with non-wide function (for Windows 98). */
3009 vim_free(p);
3010 p = NULL;
3011 }
3012 }
3013 if (p == NULL)
3014#endif
3015 res = SetFileAttributes((char *)name, attrs);
3016#ifdef FEAT_MBYTE
3017 vim_free(p);
3018#endif
3019 return res ? 0 : -1;
3020}
3021
3022/*
3023 * Set archive flag for "name".
3024 */
3025 static
3026 int
3027win32_set_archive(char_u *name)
3028{
3029 int attrs = win32_getattrs(name);
3030 if (attrs == -1)
3031 return -1;
3032
3033 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3034 return win32_setattrs(name, attrs);
3035}
3036
3037/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038 * Return TRUE if file or directory "name" is writable (not readonly).
3039 * Strange semantics of Win32: a readonly directory is writable, but you can't
3040 * delete a file. Let's say this means it is writable.
3041 */
3042 int
3043mch_writable(char_u *name)
3044{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003045 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003047 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3048 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003049}
3050
Bram Moolenaar071d4272004-06-13 20:20:40 +00003051/*
3052 * Return 1 if "name" can be executed, 0 if not.
3053 * Return -1 if unknown.
3054 */
3055 int
3056mch_can_exe(char_u *name)
3057{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003058 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003059 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003060 char_u *p;
3061
3062 if (len >= _MAX_PATH) /* safety check */
3063 return FALSE;
3064
3065 /* If there already is an extension try using the name directly. Also do
3066 * this with a Unix-shell like 'shell'. */
3067 if (vim_strchr(gettail(name), '.') != NULL
3068 || strstr((char *)gettail(p_sh), "sh") != NULL)
3069 if (executable_exists((char *)name))
3070 return TRUE;
3071
3072 /*
3073 * Loop over all extensions in $PATHEXT.
3074 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003075 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003076 p = mch_getenv("PATHEXT");
3077 if (p == NULL)
3078 p = (char_u *)".com;.exe;.bat;.cmd";
3079 while (*p)
3080 {
3081 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3082 {
3083 /* A single "." means no extension is added. */
3084 buf[len] = NUL;
3085 ++p;
3086 if (*p)
3087 ++p;
3088 }
3089 else
3090 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
3091 if (executable_exists((char *)buf))
3092 return TRUE;
3093 }
3094 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003096
3097/*
3098 * Check what "name" is:
3099 * NODE_NORMAL: file or directory (or doesn't exist)
3100 * NODE_WRITABLE: writable device, socket, fifo, etc.
3101 * NODE_OTHER: non-writable things
3102 */
3103 int
3104mch_nodetype(char_u *name)
3105{
3106 HANDLE hFile;
3107 int type;
3108
Bram Moolenaar043545e2006-10-10 16:44:07 +00003109 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3110 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3111 * here. */
3112 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3113 return NODE_WRITABLE;
3114
Bram Moolenaar071d4272004-06-13 20:20:40 +00003115 hFile = CreateFile(name, /* file name */
3116 GENERIC_WRITE, /* access mode */
3117 0, /* share mode */
3118 NULL, /* security descriptor */
3119 OPEN_EXISTING, /* creation disposition */
3120 0, /* file attributes */
3121 NULL); /* handle to template file */
3122
3123 if (hFile == INVALID_HANDLE_VALUE)
3124 return NODE_NORMAL;
3125
3126 type = GetFileType(hFile);
3127 CloseHandle(hFile);
3128 if (type == FILE_TYPE_CHAR)
3129 return NODE_WRITABLE;
3130 if (type == FILE_TYPE_DISK)
3131 return NODE_NORMAL;
3132 return NODE_OTHER;
3133}
3134
3135#ifdef HAVE_ACL
3136struct my_acl
3137{
3138 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3139 PSID pSidOwner;
3140 PSID pSidGroup;
3141 PACL pDacl;
3142 PACL pSacl;
3143};
3144#endif
3145
3146/*
3147 * Return a pointer to the ACL of file "fname" in allocated memory.
3148 * Return NULL if the ACL is not available for whatever reason.
3149 */
3150 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003151mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152{
3153#ifndef HAVE_ACL
3154 return (vim_acl_T)NULL;
3155#else
3156 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003157 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003158
3159 /* This only works on Windows NT and 2000. */
3160 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
3161 {
3162 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3163 if (p != NULL)
3164 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003165# ifdef FEAT_MBYTE
3166 WCHAR *wn = NULL;
3167
3168 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3169 wn = enc_to_utf16(fname, NULL);
3170 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003172 /* Try to retrieve the entire security descriptor. */
3173 err = pGetNamedSecurityInfoW(
3174 wn, // Abstract filename
3175 SE_FILE_OBJECT, // File Object
3176 OWNER_SECURITY_INFORMATION |
3177 GROUP_SECURITY_INFORMATION |
3178 DACL_SECURITY_INFORMATION |
3179 SACL_SECURITY_INFORMATION,
3180 &p->pSidOwner, // Ownership information.
3181 &p->pSidGroup, // Group membership.
3182 &p->pDacl, // Discretionary information.
3183 &p->pSacl, // For auditing purposes.
3184 &p->pSecurityDescriptor);
3185 if (err == ERROR_ACCESS_DENIED ||
3186 err == ERROR_PRIVILEGE_NOT_HELD)
3187 {
3188 /* Retrieve only DACL. */
3189 (void)pGetNamedSecurityInfoW(
3190 wn,
3191 SE_FILE_OBJECT,
3192 DACL_SECURITY_INFORMATION,
3193 NULL,
3194 NULL,
3195 &p->pDacl,
3196 NULL,
3197 &p->pSecurityDescriptor);
3198 }
3199 if (p->pSecurityDescriptor == NULL)
3200 {
3201 mch_free_acl((vim_acl_T)p);
3202 p = NULL;
3203 }
3204 vim_free(wn);
3205 }
3206 else
3207# endif
3208 {
3209 /* Try to retrieve the entire security descriptor. */
3210 err = pGetNamedSecurityInfo(
3211 (LPSTR)fname, // Abstract filename
3212 SE_FILE_OBJECT, // File Object
3213 OWNER_SECURITY_INFORMATION |
3214 GROUP_SECURITY_INFORMATION |
3215 DACL_SECURITY_INFORMATION |
3216 SACL_SECURITY_INFORMATION,
3217 &p->pSidOwner, // Ownership information.
3218 &p->pSidGroup, // Group membership.
3219 &p->pDacl, // Discretionary information.
3220 &p->pSacl, // For auditing purposes.
3221 &p->pSecurityDescriptor);
3222 if (err == ERROR_ACCESS_DENIED ||
3223 err == ERROR_PRIVILEGE_NOT_HELD)
3224 {
3225 /* Retrieve only DACL. */
3226 (void)pGetNamedSecurityInfo(
3227 (LPSTR)fname,
3228 SE_FILE_OBJECT,
3229 DACL_SECURITY_INFORMATION,
3230 NULL,
3231 NULL,
3232 &p->pDacl,
3233 NULL,
3234 &p->pSecurityDescriptor);
3235 }
3236 if (p->pSecurityDescriptor == NULL)
3237 {
3238 mch_free_acl((vim_acl_T)p);
3239 p = NULL;
3240 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003241 }
3242 }
3243 }
3244
3245 return (vim_acl_T)p;
3246#endif
3247}
3248
Bram Moolenaar27515922013-06-29 15:36:26 +02003249#ifdef HAVE_ACL
3250/*
3251 * Check if "acl" contains inherited ACE.
3252 */
3253 static BOOL
3254is_acl_inherited(PACL acl)
3255{
3256 DWORD i;
3257 ACL_SIZE_INFORMATION acl_info;
3258 PACCESS_ALLOWED_ACE ace;
3259
3260 acl_info.AceCount = 0;
3261 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3262 for (i = 0; i < acl_info.AceCount; i++)
3263 {
3264 GetAce(acl, i, (LPVOID *)&ace);
3265 if (ace->Header.AceFlags & INHERITED_ACE)
3266 return TRUE;
3267 }
3268 return FALSE;
3269}
3270#endif
3271
Bram Moolenaar071d4272004-06-13 20:20:40 +00003272/*
3273 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3274 * Errors are ignored.
3275 * This must only be called with "acl" equal to what mch_get_acl() returned.
3276 */
3277 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003278mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279{
3280#ifdef HAVE_ACL
3281 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003282 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003283
3284 if (p != NULL && advapi_lib != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003285 {
3286# ifdef FEAT_MBYTE
3287 WCHAR *wn = NULL;
3288# endif
3289
3290 /* Set security flags */
3291 if (p->pSidOwner)
3292 sec_info |= OWNER_SECURITY_INFORMATION;
3293 if (p->pSidGroup)
3294 sec_info |= GROUP_SECURITY_INFORMATION;
3295 if (p->pDacl)
3296 {
3297 sec_info |= DACL_SECURITY_INFORMATION;
3298 /* Do not inherit its parent's DACL.
3299 * If the DACL is inherited, Cygwin permissions would be changed.
3300 */
3301 if (!is_acl_inherited(p->pDacl))
3302 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3303 }
3304 if (p->pSacl)
3305 sec_info |= SACL_SECURITY_INFORMATION;
3306
3307# ifdef FEAT_MBYTE
3308 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3309 wn = enc_to_utf16(fname, NULL);
3310 if (wn != NULL)
3311 {
3312 (void)pSetNamedSecurityInfoW(
3313 wn, // Abstract filename
3314 SE_FILE_OBJECT, // File Object
3315 sec_info,
3316 p->pSidOwner, // Ownership information.
3317 p->pSidGroup, // Group membership.
3318 p->pDacl, // Discretionary information.
3319 p->pSacl // For auditing purposes.
3320 );
3321 vim_free(wn);
3322 }
3323 else
3324# endif
3325 {
3326 (void)pSetNamedSecurityInfo(
3327 (LPSTR)fname, // Abstract filename
3328 SE_FILE_OBJECT, // File Object
3329 sec_info,
3330 p->pSidOwner, // Ownership information.
3331 p->pSidGroup, // Group membership.
3332 p->pDacl, // Discretionary information.
3333 p->pSacl // For auditing purposes.
3334 );
3335 }
3336 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003337#endif
3338}
3339
3340 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003341mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003342{
3343#ifdef HAVE_ACL
3344 struct my_acl *p = (struct my_acl *)acl;
3345
3346 if (p != NULL)
3347 {
3348 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3349 vim_free(p);
3350 }
3351#endif
3352}
3353
3354#ifndef FEAT_GUI_W32
3355
3356/*
3357 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3358 */
3359 static BOOL WINAPI
3360handler_routine(
3361 DWORD dwCtrlType)
3362{
3363 switch (dwCtrlType)
3364 {
3365 case CTRL_C_EVENT:
3366 if (ctrl_c_interrupts)
3367 g_fCtrlCPressed = TRUE;
3368 return TRUE;
3369
3370 case CTRL_BREAK_EVENT:
3371 g_fCBrkPressed = TRUE;
3372 return TRUE;
3373
3374 /* fatal events: shut down gracefully */
3375 case CTRL_CLOSE_EVENT:
3376 case CTRL_LOGOFF_EVENT:
3377 case CTRL_SHUTDOWN_EVENT:
3378 windgoto((int)Rows - 1, 0);
3379 g_fForceExit = TRUE;
3380
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003381 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003382 (dwCtrlType == CTRL_CLOSE_EVENT
3383 ? _("close")
3384 : dwCtrlType == CTRL_LOGOFF_EVENT
3385 ? _("logoff")
3386 : _("shutdown")));
3387#ifdef DEBUG
3388 OutputDebugString(IObuff);
3389#endif
3390
3391 preserve_exit(); /* output IObuff, preserve files and exit */
3392
3393 return TRUE; /* not reached */
3394
3395 default:
3396 return FALSE;
3397 }
3398}
3399
3400
3401/*
3402 * set the tty in (raw) ? "raw" : "cooked" mode
3403 */
3404 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003405mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003406{
3407 DWORD cmodein;
3408 DWORD cmodeout;
3409 BOOL bEnableHandler;
3410
3411 GetConsoleMode(g_hConIn, &cmodein);
3412 GetConsoleMode(g_hConOut, &cmodeout);
3413 if (tmode == TMODE_RAW)
3414 {
3415 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3416 ENABLE_ECHO_INPUT);
3417#ifdef FEAT_MOUSE
3418 if (g_fMouseActive)
3419 cmodein |= ENABLE_MOUSE_INPUT;
3420#endif
3421 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3422 bEnableHandler = TRUE;
3423 }
3424 else /* cooked */
3425 {
3426 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3427 ENABLE_ECHO_INPUT);
3428 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3429 bEnableHandler = FALSE;
3430 }
3431 SetConsoleMode(g_hConIn, cmodein);
3432 SetConsoleMode(g_hConOut, cmodeout);
3433 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3434
3435#ifdef MCH_WRITE_DUMP
3436 if (fdDump)
3437 {
3438 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3439 tmode == TMODE_RAW ? "raw" :
3440 tmode == TMODE_COOK ? "cooked" : "normal",
3441 cmodein, cmodeout);
3442 fflush(fdDump);
3443 }
3444#endif
3445}
3446
3447
3448/*
3449 * Get the size of the current window in `Rows' and `Columns'
3450 * Return OK when size could be determined, FAIL otherwise.
3451 */
3452 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003453mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454{
3455 CONSOLE_SCREEN_BUFFER_INFO csbi;
3456
3457 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3458 {
3459 /*
3460 * For some reason, we are trying to get the screen dimensions
3461 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3462 * variables are really intended to mean the size of Vim screen
3463 * while in termcap mode.
3464 */
3465 Rows = g_cbTermcap.Info.dwSize.Y;
3466 Columns = g_cbTermcap.Info.dwSize.X;
3467 }
3468 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3469 {
3470 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3471 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3472 }
3473 else
3474 {
3475 Rows = 25;
3476 Columns = 80;
3477 }
3478 return OK;
3479}
3480
3481/*
3482 * Set a console window to `xSize' * `ySize'
3483 */
3484 static void
3485ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003486 HANDLE hConsole,
3487 int xSize,
3488 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489{
3490 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3491 SMALL_RECT srWindowRect; /* hold the new console size */
3492 COORD coordScreen;
3493
3494#ifdef MCH_WRITE_DUMP
3495 if (fdDump)
3496 {
3497 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3498 fflush(fdDump);
3499 }
3500#endif
3501
3502 /* get the largest size we can size the console window to */
3503 coordScreen = GetLargestConsoleWindowSize(hConsole);
3504
3505 /* define the new console window size and scroll position */
3506 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3507 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3508 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3509
3510 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3511 {
3512 int sx, sy;
3513
3514 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3515 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3516 if (sy < ySize || sx < xSize)
3517 {
3518 /*
3519 * Increasing number of lines/columns, do buffer first.
3520 * Use the maximal size in x and y direction.
3521 */
3522 if (sy < ySize)
3523 coordScreen.Y = ySize;
3524 else
3525 coordScreen.Y = sy;
3526 if (sx < xSize)
3527 coordScreen.X = xSize;
3528 else
3529 coordScreen.X = sx;
3530 SetConsoleScreenBufferSize(hConsole, coordScreen);
3531 }
3532 }
3533
3534 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3535 {
3536#ifdef MCH_WRITE_DUMP
3537 if (fdDump)
3538 {
3539 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3540 GetLastError());
3541 fflush(fdDump);
3542 }
3543#endif
3544 }
3545
3546 /* define the new console buffer size */
3547 coordScreen.X = xSize;
3548 coordScreen.Y = ySize;
3549
3550 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3551 {
3552#ifdef MCH_WRITE_DUMP
3553 if (fdDump)
3554 {
3555 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3556 GetLastError());
3557 fflush(fdDump);
3558 }
3559#endif
3560 }
3561}
3562
3563
3564/*
3565 * Set the console window to `Rows' * `Columns'
3566 */
3567 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003568mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003569{
3570 COORD coordScreen;
3571
3572 /* Don't change window size while still starting up */
3573 if (suppress_winsize != 0)
3574 {
3575 suppress_winsize = 2;
3576 return;
3577 }
3578
3579 if (term_console)
3580 {
3581 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3582
3583 /* Clamp Rows and Columns to reasonable values */
3584 if (Rows > coordScreen.Y)
3585 Rows = coordScreen.Y;
3586 if (Columns > coordScreen.X)
3587 Columns = coordScreen.X;
3588
3589 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3590 }
3591}
3592
3593/*
3594 * Rows and/or Columns has changed.
3595 */
3596 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003597mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598{
3599 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3600}
3601
3602
3603/*
3604 * Called when started up, to set the winsize that was delayed.
3605 */
3606 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003607mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608{
3609 if (suppress_winsize == 2)
3610 {
3611 suppress_winsize = 0;
3612 mch_set_shellsize();
3613 shell_resized();
3614 }
3615 suppress_winsize = 0;
3616}
3617#endif /* FEAT_GUI_W32 */
3618
3619
3620
3621#if defined(FEAT_GUI_W32) || defined(PROTO)
3622
3623/*
3624 * Specialised version of system() for Win32 GUI mode.
3625 * This version proceeds as follows:
3626 * 1. Create a console window for use by the subprocess
3627 * 2. Run the subprocess (it gets the allocated console by default)
3628 * 3. Wait for the subprocess to terminate and get its exit code
3629 * 4. Prompt the user to press a key to close the console window
3630 */
3631 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003632mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003633{
3634 STARTUPINFO si;
3635 PROCESS_INFORMATION pi;
3636 DWORD ret = 0;
3637 HWND hwnd = GetFocus();
3638
3639 si.cb = sizeof(si);
3640 si.lpReserved = NULL;
3641 si.lpDesktop = NULL;
3642 si.lpTitle = NULL;
3643 si.dwFlags = STARTF_USESHOWWINDOW;
3644 /*
3645 * It's nicer to run a filter command in a minimized window, but in
3646 * Windows 95 this makes the command MUCH slower. We can't do it under
3647 * Win32s either as it stops the synchronous spawn workaround working.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003648 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003649 */
3650 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01003651 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652 else
3653 si.wShowWindow = SW_SHOWNORMAL;
3654 si.cbReserved2 = 0;
3655 si.lpReserved2 = NULL;
3656
3657 /* There is a strange error on Windows 95 when using "c:\\command.com".
3658 * When the "c:\\" is left out it works OK...? */
3659 if (mch_windows95()
3660 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3661 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3662 cmd += 3;
3663
3664 /* Now, run the command */
3665 CreateProcess(NULL, /* Executable name */
3666 cmd, /* Command to execute */
3667 NULL, /* Process security attributes */
3668 NULL, /* Thread security attributes */
3669 FALSE, /* Inherit handles */
3670 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3671 CREATE_NEW_CONSOLE,
3672 NULL, /* Environment */
3673 NULL, /* Current directory */
3674 &si, /* Startup information */
3675 &pi); /* Process information */
3676
3677
3678 /* Wait for the command to terminate before continuing */
3679 if (g_PlatformId != VER_PLATFORM_WIN32s)
3680 {
3681#ifdef FEAT_GUI
3682 int delay = 1;
3683
3684 /* Keep updating the window while waiting for the shell to finish. */
3685 for (;;)
3686 {
3687 MSG msg;
3688
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003689 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690 {
3691 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003692 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02003693 delay = 1;
3694 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003695 }
3696 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3697 break;
3698
3699 /* We start waiting for a very short time and then increase it, so
3700 * that we respond quickly when the process is quick, and don't
3701 * consume too much overhead when it's slow. */
3702 if (delay < 50)
3703 delay += 10;
3704 }
3705#else
3706 WaitForSingleObject(pi.hProcess, INFINITE);
3707#endif
3708
3709 /* Get the command exit code */
3710 GetExitCodeProcess(pi.hProcess, &ret);
3711 }
3712 else
3713 {
3714 /*
3715 * This ugly code is the only quick way of performing
3716 * a synchronous spawn under Win32s. Yuk.
3717 */
3718 num_windows = 0;
3719 EnumWindows(win32ssynch_cb, 0);
3720 old_num_windows = num_windows;
3721 do
3722 {
3723 Sleep(1000);
3724 num_windows = 0;
3725 EnumWindows(win32ssynch_cb, 0);
3726 } while (num_windows == old_num_windows);
3727 ret = 0;
3728 }
3729
3730 /* Close the handles to the subprocess, so that it goes away */
3731 CloseHandle(pi.hThread);
3732 CloseHandle(pi.hProcess);
3733
3734 /* Try to get input focus back. Doesn't always work though. */
3735 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3736
3737 return ret;
3738}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003739
3740/*
3741 * Thread launched by the gui to send the current buffer data to the
3742 * process. This way avoid to hang up vim totally if the children
3743 * process take a long time to process the lines.
3744 */
3745 static DWORD WINAPI
3746sub_process_writer(LPVOID param)
3747{
3748 HANDLE g_hChildStd_IN_Wr = param;
3749 linenr_T lnum = curbuf->b_op_start.lnum;
3750 DWORD len = 0;
3751 DWORD l;
3752 char_u *lp = ml_get(lnum);
3753 char_u *s;
3754 int written = 0;
3755
3756 for (;;)
3757 {
3758 l = (DWORD)STRLEN(lp + written);
3759 if (l == 0)
3760 len = 0;
3761 else if (lp[written] == NL)
3762 {
3763 /* NL -> NUL translation */
3764 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
3765 }
3766 else
3767 {
3768 s = vim_strchr(lp + written, NL);
3769 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
3770 s == NULL ? l : (DWORD)(s - (lp + written)),
3771 &len, NULL);
3772 }
3773 if (len == (int)l)
3774 {
3775 /* Finished a line, add a NL, unless this line should not have
3776 * one. */
3777 if (lnum != curbuf->b_op_end.lnum
3778 || !curbuf->b_p_bin
3779 || (lnum != curbuf->b_no_eol_lnum
3780 && (lnum != curbuf->b_ml.ml_line_count
3781 || curbuf->b_p_eol)))
3782 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01003783 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003784 }
3785
3786 ++lnum;
3787 if (lnum > curbuf->b_op_end.lnum)
3788 break;
3789
3790 lp = ml_get(lnum);
3791 written = 0;
3792 }
3793 else if (len > 0)
3794 written += len;
3795 }
3796
3797 /* finished all the lines, close pipe */
3798 CloseHandle(g_hChildStd_IN_Wr);
3799 ExitThread(0);
3800}
3801
3802
3803# define BUFLEN 100 /* length for buffer, stolen from unix version */
3804
3805/*
3806 * This function read from the children's stdout and write the
3807 * data on screen or in the buffer accordingly.
3808 */
3809 static void
3810dump_pipe(int options,
3811 HANDLE g_hChildStd_OUT_Rd,
3812 garray_T *ga,
3813 char_u buffer[],
3814 DWORD *buffer_off)
3815{
3816 DWORD availableBytes = 0;
3817 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003818 int ret;
3819 DWORD len;
3820 DWORD toRead;
3821 int repeatCount;
3822
3823 /* we query the pipe to see if there is any data to read
3824 * to avoid to perform a blocking read */
3825 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
3826 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003827 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003828 NULL, /* number of read bytes */
3829 &availableBytes, /* available bytes total */
3830 NULL); /* byteLeft */
3831
3832 repeatCount = 0;
3833 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02003834 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003835 {
3836 repeatCount++;
3837 toRead =
3838# ifdef FEAT_MBYTE
3839 (DWORD)(BUFLEN - *buffer_off);
3840# else
3841 (DWORD)BUFLEN;
3842# endif
3843 toRead = availableBytes < toRead ? availableBytes : toRead;
3844 ReadFile(g_hChildStd_OUT_Rd, buffer
3845# ifdef FEAT_MBYTE
3846 + *buffer_off, toRead
3847# else
3848 , toRead
3849# endif
3850 , &len, NULL);
3851
3852 /* If we haven't read anything, there is a problem */
3853 if (len == 0)
3854 break;
3855
3856 availableBytes -= len;
3857
3858 if (options & SHELL_READ)
3859 {
3860 /* Do NUL -> NL translation, append NL separated
3861 * lines to the current buffer. */
3862 for (i = 0; i < len; ++i)
3863 {
3864 if (buffer[i] == NL)
3865 append_ga_line(ga);
3866 else if (buffer[i] == NUL)
3867 ga_append(ga, NL);
3868 else
3869 ga_append(ga, buffer[i]);
3870 }
3871 }
3872# ifdef FEAT_MBYTE
3873 else if (has_mbyte)
3874 {
3875 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02003876 int c;
3877 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003878
3879 len += *buffer_off;
3880 buffer[len] = NUL;
3881
3882 /* Check if the last character in buffer[] is
3883 * incomplete, keep these bytes for the next
3884 * round. */
3885 for (p = buffer; p < buffer + len; p += l)
3886 {
3887 l = mb_cptr2len(p);
3888 if (l == 0)
3889 l = 1; /* NUL byte? */
3890 else if (MB_BYTE2LEN(*p) != l)
3891 break;
3892 }
3893 if (p == buffer) /* no complete character */
3894 {
3895 /* avoid getting stuck at an illegal byte */
3896 if (len >= 12)
3897 ++p;
3898 else
3899 {
3900 *buffer_off = len;
3901 return;
3902 }
3903 }
3904 c = *p;
3905 *p = NUL;
3906 msg_puts(buffer);
3907 if (p < buffer + len)
3908 {
3909 *p = c;
3910 *buffer_off = (DWORD)((buffer + len) - p);
3911 mch_memmove(buffer, p, *buffer_off);
3912 return;
3913 }
3914 *buffer_off = 0;
3915 }
3916# endif /* FEAT_MBYTE */
3917 else
3918 {
3919 buffer[len] = NUL;
3920 msg_puts(buffer);
3921 }
3922
3923 windgoto(msg_row, msg_col);
3924 cursor_on();
3925 out_flush();
3926 }
3927}
3928
3929/*
3930 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
3931 * for communication and doesn't open any new window.
3932 */
3933 static int
3934mch_system_piped(char *cmd, int options)
3935{
3936 STARTUPINFO si;
3937 PROCESS_INFORMATION pi;
3938 DWORD ret = 0;
3939
3940 HANDLE g_hChildStd_IN_Rd = NULL;
3941 HANDLE g_hChildStd_IN_Wr = NULL;
3942 HANDLE g_hChildStd_OUT_Rd = NULL;
3943 HANDLE g_hChildStd_OUT_Wr = NULL;
3944
3945 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
3946 DWORD len;
3947
3948 /* buffer used to receive keys */
3949 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
3950 int ta_len = 0; /* valid bytes in ta_buf[] */
3951
3952 DWORD i;
3953 int c;
3954 int noread_cnt = 0;
3955 garray_T ga;
3956 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003957 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003958 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02003959
3960 SECURITY_ATTRIBUTES saAttr;
3961
3962 /* Set the bInheritHandle flag so pipe handles are inherited. */
3963 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
3964 saAttr.bInheritHandle = TRUE;
3965 saAttr.lpSecurityDescriptor = NULL;
3966
3967 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
3968 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
3969 || ! pSetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
3970 /* Create a pipe for the child process's STDIN. */
3971 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
3972 /* Ensure the write handle to the pipe for STDIN is not inherited. */
3973 || ! pSetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
3974 {
3975 CloseHandle(g_hChildStd_IN_Rd);
3976 CloseHandle(g_hChildStd_IN_Wr);
3977 CloseHandle(g_hChildStd_OUT_Rd);
3978 CloseHandle(g_hChildStd_OUT_Wr);
3979 MSG_PUTS(_("\nCannot create pipes\n"));
3980 }
3981
3982 si.cb = sizeof(si);
3983 si.lpReserved = NULL;
3984 si.lpDesktop = NULL;
3985 si.lpTitle = NULL;
3986 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
3987
3988 /* set-up our file redirection */
3989 si.hStdError = g_hChildStd_OUT_Wr;
3990 si.hStdOutput = g_hChildStd_OUT_Wr;
3991 si.hStdInput = g_hChildStd_IN_Rd;
3992 si.wShowWindow = SW_HIDE;
3993 si.cbReserved2 = 0;
3994 si.lpReserved2 = NULL;
3995
3996 if (options & SHELL_READ)
3997 ga_init2(&ga, 1, BUFLEN);
3998
Bram Moolenaar6b707b42012-02-21 21:22:44 +01003999 if (cmd != NULL)
4000 {
4001 p = (char *)vim_strsave((char_u *)cmd);
4002 if (p != NULL)
4003 unescape_shellxquote((char_u *)p, p_sxe);
4004 else
4005 p = cmd;
4006 }
4007
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004008 /* Now, run the command */
4009 CreateProcess(NULL, /* Executable name */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004010 p, /* Command to execute */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004011 NULL, /* Process security attributes */
4012 NULL, /* Thread security attributes */
4013
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004014 // this command can be litigious, handle inheritance was
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004015 // deactivated for pending temp file, but, if we deactivate
4016 // it, the pipes don't work for some reason.
4017 TRUE, /* Inherit handles, first deactivated,
4018 * but needed */
4019 CREATE_DEFAULT_ERROR_MODE, /* Creation flags */
4020 NULL, /* Environment */
4021 NULL, /* Current directory */
4022 &si, /* Startup information */
4023 &pi); /* Process information */
4024
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004025 if (p != cmd)
4026 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004027
4028 /* Close our unused side of the pipes */
4029 CloseHandle(g_hChildStd_IN_Rd);
4030 CloseHandle(g_hChildStd_OUT_Wr);
4031
4032 if (options & SHELL_WRITE)
4033 {
4034 HANDLE thread =
4035 CreateThread(NULL, /* security attributes */
4036 0, /* default stack size */
4037 sub_process_writer, /* function to be executed */
4038 g_hChildStd_IN_Wr, /* parameter */
4039 0, /* creation flag, start immediately */
4040 NULL); /* we don't care about thread id */
4041 CloseHandle(thread);
4042 g_hChildStd_IN_Wr = NULL;
4043 }
4044
4045 /* Keep updating the window while waiting for the shell to finish. */
4046 for (;;)
4047 {
4048 MSG msg;
4049
4050 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
4051 {
4052 TranslateMessage(&msg);
4053 DispatchMessage(&msg);
4054 }
4055
4056 /* write pipe information in the window */
4057 if ((options & (SHELL_READ|SHELL_WRITE))
4058# ifdef FEAT_GUI
4059 || gui.in_use
4060# endif
4061 )
4062 {
4063 len = 0;
4064 if (!(options & SHELL_EXPAND)
4065 && ((options &
4066 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4067 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4068# ifdef FEAT_GUI
4069 || gui.in_use
4070# endif
4071 )
4072 && (ta_len > 0 || noread_cnt > 4))
4073 {
4074 if (ta_len == 0)
4075 {
4076 /* Get extra characters when we don't have any. Reset the
4077 * counter and timer. */
4078 noread_cnt = 0;
4079# if defined(HAVE_GETTIMEOFDAY) && defined(HAVE_SYS_TIME_H)
4080 gettimeofday(&start_tv, NULL);
4081# endif
4082 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4083 }
4084 if (ta_len > 0 || len > 0)
4085 {
4086 /*
4087 * For pipes: Check for CTRL-C: send interrupt signal to
4088 * child. Check for CTRL-D: EOF, close pipe to child.
4089 */
4090 if (len == 1 && cmd != NULL)
4091 {
4092 if (ta_buf[ta_len] == Ctrl_C)
4093 {
4094 /* Learn what exit code is expected, for
4095 * now put 9 as SIGKILL */
4096 TerminateProcess(pi.hProcess, 9);
4097 }
4098 if (ta_buf[ta_len] == Ctrl_D)
4099 {
4100 CloseHandle(g_hChildStd_IN_Wr);
4101 g_hChildStd_IN_Wr = NULL;
4102 }
4103 }
4104
4105 /* replace K_BS by <BS> and K_DEL by <DEL> */
4106 for (i = ta_len; i < ta_len + len; ++i)
4107 {
4108 if (ta_buf[i] == CSI && len - i > 2)
4109 {
4110 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4111 if (c == K_DEL || c == K_KDEL || c == K_BS)
4112 {
4113 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4114 (size_t)(len - i - 2));
4115 if (c == K_DEL || c == K_KDEL)
4116 ta_buf[i] = DEL;
4117 else
4118 ta_buf[i] = Ctrl_H;
4119 len -= 2;
4120 }
4121 }
4122 else if (ta_buf[i] == '\r')
4123 ta_buf[i] = '\n';
4124# ifdef FEAT_MBYTE
4125 if (has_mbyte)
4126 i += (*mb_ptr2len_len)(ta_buf + i,
4127 ta_len + len - i) - 1;
4128# endif
4129 }
4130
4131 /*
4132 * For pipes: echo the typed characters. For a pty this
4133 * does not seem to work.
4134 */
4135 for (i = ta_len; i < ta_len + len; ++i)
4136 {
4137 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4138 msg_putchar(ta_buf[i]);
4139# ifdef FEAT_MBYTE
4140 else if (has_mbyte)
4141 {
4142 int l = (*mb_ptr2len)(ta_buf + i);
4143
4144 msg_outtrans_len(ta_buf + i, l);
4145 i += l - 1;
4146 }
4147# endif
4148 else
4149 msg_outtrans_len(ta_buf + i, 1);
4150 }
4151 windgoto(msg_row, msg_col);
4152 out_flush();
4153
4154 ta_len += len;
4155
4156 /*
4157 * Write the characters to the child, unless EOF has been
4158 * typed for pipes. Write one character at a time, to
4159 * avoid losing too much typeahead. When writing buffer
4160 * lines, drop the typed characters (only check for
4161 * CTRL-C).
4162 */
4163 if (options & SHELL_WRITE)
4164 ta_len = 0;
4165 else if (g_hChildStd_IN_Wr != NULL)
4166 {
4167 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4168 1, &len, NULL);
4169 // if we are typing in, we want to keep things reactive
4170 delay = 1;
4171 if (len > 0)
4172 {
4173 ta_len -= len;
4174 mch_memmove(ta_buf, ta_buf + len, ta_len);
4175 }
4176 }
4177 }
4178 }
4179 }
4180
4181 if (ta_len)
4182 ui_inchar_undo(ta_buf, ta_len);
4183
4184 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4185 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004186 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004187 break;
4188 }
4189
4190 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004191 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004192
4193 /* We start waiting for a very short time and then increase it, so
4194 * that we respond quickly when the process is quick, and don't
4195 * consume too much overhead when it's slow. */
4196 if (delay < 50)
4197 delay += 10;
4198 }
4199
4200 /* Close the pipe */
4201 CloseHandle(g_hChildStd_OUT_Rd);
4202 if (g_hChildStd_IN_Wr != NULL)
4203 CloseHandle(g_hChildStd_IN_Wr);
4204
4205 WaitForSingleObject(pi.hProcess, INFINITE);
4206
4207 /* Get the command exit code */
4208 GetExitCodeProcess(pi.hProcess, &ret);
4209
4210 if (options & SHELL_READ)
4211 {
4212 if (ga.ga_len > 0)
4213 {
4214 append_ga_line(&ga);
4215 /* remember that the NL was missing */
4216 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4217 }
4218 else
4219 curbuf->b_no_eol_lnum = 0;
4220 ga_clear(&ga);
4221 }
4222
4223 /* Close the handles to the subprocess, so that it goes away */
4224 CloseHandle(pi.hThread);
4225 CloseHandle(pi.hProcess);
4226
4227 return ret;
4228}
4229
4230 static int
4231mch_system(char *cmd, int options)
4232{
4233 /* if we can pipe and the shelltemp option is off */
4234 if (allowPiping && !p_stmp)
4235 return mch_system_piped(cmd, options);
4236 else
4237 return mch_system_classic(cmd, options);
4238}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239#else
4240
4241# define mch_system(c, o) system(c)
4242
4243#endif
4244
4245/*
4246 * Either execute a command by calling the shell or start a new shell
4247 */
4248 int
4249mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004250 char_u *cmd,
4251 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004252{
4253 int x = 0;
4254 int tmode = cur_tmode;
4255#ifdef FEAT_TITLE
4256 char szShellTitle[512];
4257
4258 /* Change the title to reflect that we are in a subshell. */
4259 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
4260 {
4261 if (cmd == NULL)
4262 strcat(szShellTitle, " :sh");
4263 else
4264 {
4265 strcat(szShellTitle, " - !");
4266 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
4267 strcat(szShellTitle, cmd);
4268 }
4269 mch_settitle(szShellTitle, NULL);
4270 }
4271#endif
4272
4273 out_flush();
4274
4275#ifdef MCH_WRITE_DUMP
4276 if (fdDump)
4277 {
4278 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4279 fflush(fdDump);
4280 }
4281#endif
4282
4283 /*
4284 * Catch all deadly signals while running the external command, because a
4285 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4286 */
4287 signal(SIGINT, SIG_IGN);
4288#if defined(__GNUC__) && !defined(__MINGW32__)
4289 signal(SIGKILL, SIG_IGN);
4290#else
4291 signal(SIGBREAK, SIG_IGN);
4292#endif
4293 signal(SIGILL, SIG_IGN);
4294 signal(SIGFPE, SIG_IGN);
4295 signal(SIGSEGV, SIG_IGN);
4296 signal(SIGTERM, SIG_IGN);
4297 signal(SIGABRT, SIG_IGN);
4298
4299 if (options & SHELL_COOKED)
4300 settmode(TMODE_COOK); /* set to normal mode */
4301
4302 if (cmd == NULL)
4303 {
4304 x = mch_system(p_sh, options);
4305 }
4306 else
4307 {
4308 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004309 char_u *newcmd = NULL;
4310 char_u *cmdbase = cmd;
4311 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004312
4313 /* Skip a leading ", ( and "(. */
4314 if (*cmdbase == '"' )
4315 ++cmdbase;
4316 if (*cmdbase == '(')
4317 ++cmdbase;
4318
4319 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
4320 {
4321 STARTUPINFO si;
4322 PROCESS_INFORMATION pi;
4323 DWORD flags = CREATE_NEW_CONSOLE;
4324 char_u *p;
4325
4326 si.cb = sizeof(si);
4327 si.lpReserved = NULL;
4328 si.lpDesktop = NULL;
4329 si.lpTitle = NULL;
4330 si.dwFlags = 0;
4331 si.cbReserved2 = 0;
4332 si.lpReserved2 = NULL;
4333
4334 cmdbase = skipwhite(cmdbase + 5);
4335 if ((STRNICMP(cmdbase, "/min", 4) == 0)
4336 && vim_iswhite(cmdbase[4]))
4337 {
4338 cmdbase = skipwhite(cmdbase + 4);
4339 si.dwFlags = STARTF_USESHOWWINDOW;
4340 si.wShowWindow = SW_SHOWMINNOACTIVE;
4341 }
4342 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
4343 && vim_iswhite(cmdbase[2]))
4344 {
4345 cmdbase = skipwhite(cmdbase + 2);
4346 flags = CREATE_NO_WINDOW;
4347 si.dwFlags = STARTF_USESTDHANDLES;
4348 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004349 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004350 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004351 NULL, // Security att.
4352 OPEN_EXISTING, // Open flags
4353 FILE_ATTRIBUTE_NORMAL, // File att.
4354 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004355 si.hStdOutput = si.hStdInput;
4356 si.hStdError = si.hStdInput;
4357 }
4358
4359 /* Remove a trailing ", ) and )" if they have a match
4360 * at the start of the command. */
4361 if (cmdbase > cmd)
4362 {
4363 p = cmdbase + STRLEN(cmdbase);
4364 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4365 *--p = NUL;
4366 if (p > cmdbase && p[-1] == ')'
4367 && (*cmd =='(' || cmd[1] == '('))
4368 *--p = NUL;
4369 }
4370
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004371 newcmd = cmdbase;
4372 unescape_shellxquote(cmdbase, p_sxe);
4373
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004374 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004375 * If creating new console, arguments are passed to the
4376 * 'cmd.exe' as-is. If it's not, arguments are not treated
4377 * correctly for current 'cmd.exe'. So unescape characters in
4378 * shellxescape except '|' for avoiding to be treated as
4379 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004380 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004381 if (flags != CREATE_NEW_CONSOLE)
4382 {
4383 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004384 char_u *cmd_shell = mch_getenv("COMSPEC");
4385
4386 if (cmd_shell == NULL || *cmd_shell == NUL)
4387 cmd_shell = default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004388
4389 subcmd = vim_strsave_escaped_ext(cmdbase, "|", '^', FALSE);
4390 if (subcmd != NULL)
4391 {
4392 /* make "cmd.exe /c arguments" */
4393 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004394 newcmd = lalloc(cmdlen, TRUE);
4395 if (newcmd != NULL)
4396 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004397 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004398 else
4399 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004400 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004401 }
4402 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004403
4404 /*
4405 * Now, start the command as a process, so that it doesn't
4406 * inherit our handles which causes unpleasant dangling swap
4407 * files if we exit before the spawned process
4408 */
4409 if (CreateProcess(NULL, // Executable name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004410 newcmd, // Command to execute
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004411 NULL, // Process security attributes
4412 NULL, // Thread security attributes
4413 FALSE, // Inherit handles
4414 flags, // Creation flags
4415 NULL, // Environment
4416 NULL, // Current directory
4417 &si, // Startup information
4418 &pi)) // Process information
4419 x = 0;
4420 else
4421 {
4422 x = -1;
4423#ifdef FEAT_GUI_W32
4424 EMSG(_("E371: Command not found"));
4425#endif
4426 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004427
4428 if (newcmd != cmdbase)
4429 vim_free(newcmd);
4430
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004431 if (si.hStdInput != NULL)
4432 {
4433 /* Close the handle to \\.\NUL */
4434 CloseHandle(si.hStdInput);
4435 }
4436 /* Close the handles to the subprocess, so that it goes away */
4437 CloseHandle(pi.hThread);
4438 CloseHandle(pi.hProcess);
4439 }
4440 else
4441 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004442 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443#ifdef FEAT_GUI_W32
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004444 (allowPiping && !p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004445#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004446 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4447
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004448 newcmd = lalloc(cmdlen, TRUE);
4449 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004450 {
4451#if defined(FEAT_GUI_W32)
4452 if (need_vimrun_warning)
4453 {
4454 MessageBox(NULL,
4455 _("VIMRUN.EXE not found in your $PATH.\n"
4456 "External commands will not pause after completion.\n"
4457 "See :help win32-vimrun for more information."),
4458 _("Vim Warning"),
4459 MB_ICONWARNING);
4460 need_vimrun_warning = FALSE;
4461 }
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004462 if (!s_dont_use_vimrun && (!allowPiping || p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004463 /* Use vimrun to execute the command. It opens a console
4464 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004465 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004466 vimrun_path,
4467 (msg_silent != 0 || (options & SHELL_DOOUT))
4468 ? "-s " : "",
4469 p_sh, p_shcf, cmd);
4470 else
4471#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004472 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004473 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004474 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004475 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004477 }
4478 }
4479
4480 if (tmode == TMODE_RAW)
4481 settmode(TMODE_RAW); /* set to raw mode */
4482
4483 /* Print the return value, unless "vimrun" was used. */
4484 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4485#if defined(FEAT_GUI_W32)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004486 && ((options & SHELL_DOOUT) || s_dont_use_vimrun
4487 || (allowPiping && !p_stmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004488#endif
4489 )
4490 {
4491 smsg(_("shell returned %d"), x);
4492 msg_putchar('\n');
4493 }
4494#ifdef FEAT_TITLE
4495 resettitle();
4496#endif
4497
4498 signal(SIGINT, SIG_DFL);
4499#if defined(__GNUC__) && !defined(__MINGW32__)
4500 signal(SIGKILL, SIG_DFL);
4501#else
4502 signal(SIGBREAK, SIG_DFL);
4503#endif
4504 signal(SIGILL, SIG_DFL);
4505 signal(SIGFPE, SIG_DFL);
4506 signal(SIGSEGV, SIG_DFL);
4507 signal(SIGTERM, SIG_DFL);
4508 signal(SIGABRT, SIG_DFL);
4509
4510 return x;
4511}
4512
4513
4514#ifndef FEAT_GUI_W32
4515
4516/*
4517 * Start termcap mode
4518 */
4519 static void
4520termcap_mode_start(void)
4521{
4522 DWORD cmodein;
4523
4524 if (g_fTermcapMode)
4525 return;
4526
4527 SaveConsoleBuffer(&g_cbNonTermcap);
4528
4529 if (g_cbTermcap.IsValid)
4530 {
4531 /*
4532 * We've been in termcap mode before. Restore certain screen
4533 * characteristics, including the buffer size and the window
4534 * size. Since we will be redrawing the screen, we don't need
4535 * to restore the actual contents of the buffer.
4536 */
4537 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
4538 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
4539 Rows = g_cbTermcap.Info.dwSize.Y;
4540 Columns = g_cbTermcap.Info.dwSize.X;
4541 }
4542 else
4543 {
4544 /*
4545 * This is our first time entering termcap mode. Clear the console
4546 * screen buffer, and resize the buffer to match the current window
4547 * size. We will use this as the size of our editing environment.
4548 */
4549 ClearConsoleBuffer(g_attrCurrent);
4550 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
4551 }
4552
4553#ifdef FEAT_TITLE
4554 resettitle();
4555#endif
4556
4557 GetConsoleMode(g_hConIn, &cmodein);
4558#ifdef FEAT_MOUSE
4559 if (g_fMouseActive)
4560 cmodein |= ENABLE_MOUSE_INPUT;
4561 else
4562 cmodein &= ~ENABLE_MOUSE_INPUT;
4563#endif
4564 cmodein |= ENABLE_WINDOW_INPUT;
4565 SetConsoleMode(g_hConIn, cmodein);
4566
4567 redraw_later_clear();
4568 g_fTermcapMode = TRUE;
4569}
4570
4571
4572/*
4573 * End termcap mode
4574 */
4575 static void
4576termcap_mode_end(void)
4577{
4578 DWORD cmodein;
4579 ConsoleBuffer *cb;
4580 COORD coord;
4581 DWORD dwDummy;
4582
4583 if (!g_fTermcapMode)
4584 return;
4585
4586 SaveConsoleBuffer(&g_cbTermcap);
4587
4588 GetConsoleMode(g_hConIn, &cmodein);
4589 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
4590 SetConsoleMode(g_hConIn, cmodein);
4591
4592#ifdef FEAT_RESTORE_ORIG_SCREEN
4593 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
4594#else
4595 cb = &g_cbNonTermcap;
4596#endif
4597 RestoreConsoleBuffer(cb, p_rs);
4598 SetConsoleCursorInfo(g_hConOut, &g_cci);
4599
4600 if (p_rs || exiting)
4601 {
4602 /*
4603 * Clear anything that happens to be on the current line.
4604 */
4605 coord.X = 0;
4606 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
4607 FillConsoleOutputCharacter(g_hConOut, ' ',
4608 cb->Info.dwSize.X, coord, &dwDummy);
4609 /*
4610 * The following is just for aesthetics. If we are exiting without
4611 * restoring the screen, then we want to have a prompt string
4612 * appear at the bottom line. However, the command interpreter
4613 * seems to always advance the cursor one line before displaying
4614 * the prompt string, which causes the screen to scroll. To
4615 * counter this, move the cursor up one line before exiting.
4616 */
4617 if (exiting && !p_rs)
4618 coord.Y--;
4619 /*
4620 * Position the cursor at the leftmost column of the desired row.
4621 */
4622 SetConsoleCursorPosition(g_hConOut, coord);
4623 }
4624
4625 g_fTermcapMode = FALSE;
4626}
4627#endif /* FEAT_GUI_W32 */
4628
4629
4630#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004631/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004632 void
4633mch_write(
4634 char_u *s,
4635 int len)
4636{
4637 /* never used */
4638}
4639
4640#else
4641
4642/*
4643 * clear `n' chars, starting from `coord'
4644 */
4645 static void
4646clear_chars(
4647 COORD coord,
4648 DWORD n)
4649{
4650 DWORD dwDummy;
4651
4652 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
4653 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
4654}
4655
4656
4657/*
4658 * Clear the screen
4659 */
4660 static void
4661clear_screen(void)
4662{
4663 g_coord.X = g_coord.Y = 0;
4664 clear_chars(g_coord, Rows * Columns);
4665}
4666
4667
4668/*
4669 * Clear to end of display
4670 */
4671 static void
4672clear_to_end_of_display(void)
4673{
4674 clear_chars(g_coord, (Rows - g_coord.Y - 1)
4675 * Columns + (Columns - g_coord.X));
4676}
4677
4678
4679/*
4680 * Clear to end of line
4681 */
4682 static void
4683clear_to_end_of_line(void)
4684{
4685 clear_chars(g_coord, Columns - g_coord.X);
4686}
4687
4688
4689/*
4690 * Scroll the scroll region up by `cLines' lines
4691 */
4692 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004693scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004694{
4695 COORD oldcoord = g_coord;
4696
4697 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
4698 delete_lines(cLines);
4699
4700 g_coord = oldcoord;
4701}
4702
4703
4704/*
4705 * Set the scroll region
4706 */
4707 static void
4708set_scroll_region(
4709 unsigned left,
4710 unsigned top,
4711 unsigned right,
4712 unsigned bottom)
4713{
4714 if (left >= right
4715 || top >= bottom
4716 || right > (unsigned) Columns - 1
4717 || bottom > (unsigned) Rows - 1)
4718 return;
4719
4720 g_srScrollRegion.Left = left;
4721 g_srScrollRegion.Top = top;
4722 g_srScrollRegion.Right = right;
4723 g_srScrollRegion.Bottom = bottom;
4724}
4725
4726
4727/*
4728 * Insert `cLines' lines at the current cursor position
4729 */
4730 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004731insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004732{
4733 SMALL_RECT source;
4734 COORD dest;
4735 CHAR_INFO fill;
4736
4737 dest.X = 0;
4738 dest.Y = g_coord.Y + cLines;
4739
4740 source.Left = 0;
4741 source.Top = g_coord.Y;
4742 source.Right = g_srScrollRegion.Right;
4743 source.Bottom = g_srScrollRegion.Bottom - cLines;
4744
4745 fill.Char.AsciiChar = ' ';
4746 fill.Attributes = g_attrCurrent;
4747
4748 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4749
4750 /* Here we have to deal with a win32 console flake: If the scroll
4751 * region looks like abc and we scroll c to a and fill with d we get
4752 * cbd... if we scroll block c one line at a time to a, we get cdd...
4753 * vim expects cdd consistently... So we have to deal with that
4754 * here... (this also occurs scrolling the same way in the other
4755 * direction). */
4756
4757 if (source.Bottom < dest.Y)
4758 {
4759 COORD coord;
4760
4761 coord.X = 0;
4762 coord.Y = source.Bottom;
4763 clear_chars(coord, Columns * (dest.Y - source.Bottom));
4764 }
4765}
4766
4767
4768/*
4769 * Delete `cLines' lines at the current cursor position
4770 */
4771 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004772delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004773{
4774 SMALL_RECT source;
4775 COORD dest;
4776 CHAR_INFO fill;
4777 int nb;
4778
4779 dest.X = 0;
4780 dest.Y = g_coord.Y;
4781
4782 source.Left = 0;
4783 source.Top = g_coord.Y + cLines;
4784 source.Right = g_srScrollRegion.Right;
4785 source.Bottom = g_srScrollRegion.Bottom;
4786
4787 fill.Char.AsciiChar = ' ';
4788 fill.Attributes = g_attrCurrent;
4789
4790 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
4791
4792 /* Here we have to deal with a win32 console flake: If the scroll
4793 * region looks like abc and we scroll c to a and fill with d we get
4794 * cbd... if we scroll block c one line at a time to a, we get cdd...
4795 * vim expects cdd consistently... So we have to deal with that
4796 * here... (this also occurs scrolling the same way in the other
4797 * direction). */
4798
4799 nb = dest.Y + (source.Bottom - source.Top) + 1;
4800
4801 if (nb < source.Top)
4802 {
4803 COORD coord;
4804
4805 coord.X = 0;
4806 coord.Y = nb;
4807 clear_chars(coord, Columns * (source.Top - nb));
4808 }
4809}
4810
4811
4812/*
4813 * Set the cursor position
4814 */
4815 static void
4816gotoxy(
4817 unsigned x,
4818 unsigned y)
4819{
4820 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
4821 return;
4822
4823 /* external cursor coords are 1-based; internal are 0-based */
4824 g_coord.X = x - 1;
4825 g_coord.Y = y - 1;
4826 SetConsoleCursorPosition(g_hConOut, g_coord);
4827}
4828
4829
4830/*
4831 * Set the current text attribute = (foreground | background)
4832 * See ../doc/os_win32.txt for the numbers.
4833 */
4834 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004835textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004836{
4837 g_attrCurrent = wAttr;
4838
4839 SetConsoleTextAttribute(g_hConOut, wAttr);
4840}
4841
4842
4843 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004844textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004845{
4846 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
4847
4848 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4849}
4850
4851
4852 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004853textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004854{
4855 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
4856
4857 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
4858}
4859
4860
4861/*
4862 * restore the default text attribute (whatever we started with)
4863 */
4864 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004865normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004866{
4867 textattr(g_attrDefault);
4868}
4869
4870
4871static WORD g_attrPreStandout = 0;
4872
4873/*
4874 * Make the text standout, by brightening it
4875 */
4876 static void
4877standout(void)
4878{
4879 g_attrPreStandout = g_attrCurrent;
4880 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
4881}
4882
4883
4884/*
4885 * Turn off standout mode
4886 */
4887 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004888standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889{
4890 if (g_attrPreStandout)
4891 {
4892 textattr(g_attrPreStandout);
4893 g_attrPreStandout = 0;
4894 }
4895}
4896
4897
4898/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00004899 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900 */
4901 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004902mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903{
4904 char_u *p;
4905 int n;
4906
4907 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
4908 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
4909 if (T_ME[0] == ESC && T_ME[1] == '|')
4910 {
4911 p = T_ME + 2;
4912 n = getdigits(&p);
4913 if (*p == 'm' && n > 0)
4914 {
4915 cterm_normal_fg_color = (n & 0xf) + 1;
4916 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
4917 }
4918 }
4919}
4920
4921
4922/*
4923 * visual bell: flash the screen
4924 */
4925 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004926visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004927{
4928 COORD coordOrigin = {0, 0};
4929 WORD attrFlash = ~g_attrCurrent & 0xff;
4930
4931 DWORD dwDummy;
4932 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
4933
4934 if (oldattrs == NULL)
4935 return;
4936 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4937 coordOrigin, &dwDummy);
4938 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
4939 coordOrigin, &dwDummy);
4940
4941 Sleep(15); /* wait for 15 msec */
4942 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
4943 coordOrigin, &dwDummy);
4944 vim_free(oldattrs);
4945}
4946
4947
4948/*
4949 * Make the cursor visible or invisible
4950 */
4951 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004952cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004953{
4954 s_cursor_visible = fVisible;
4955#ifdef MCH_CURSOR_SHAPE
4956 mch_update_cursor();
4957#endif
4958}
4959
4960
4961/*
4962 * write `cchToWrite' characters in `pchBuf' to the screen
4963 * Returns the number of characters actually written (at least one).
4964 */
4965 static BOOL
4966write_chars(
4967 LPCSTR pchBuf,
4968 DWORD cchToWrite)
4969{
4970 COORD coord = g_coord;
4971 DWORD written;
4972
4973 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
4974 coord, &written);
4975 /* When writing fails or didn't write a single character, pretend one
4976 * character was written, otherwise we get stuck. */
4977 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
4978 coord, &written) == 0
4979 || written == 0)
4980 written = 1;
4981
4982 g_coord.X += (SHORT) written;
4983
4984 while (g_coord.X > g_srScrollRegion.Right)
4985 {
4986 g_coord.X -= (SHORT) Columns;
4987 if (g_coord.Y < g_srScrollRegion.Bottom)
4988 g_coord.Y++;
4989 }
4990
4991 gotoxy(g_coord.X + 1, g_coord.Y + 1);
4992
4993 return written;
4994}
4995
4996
4997/*
4998 * mch_write(): write the output buffer to the screen, translating ESC
4999 * sequences into calls to console output routines.
5000 */
5001 void
5002mch_write(
5003 char_u *s,
5004 int len)
5005{
5006 s[len] = NUL;
5007
5008 if (!term_console)
5009 {
5010 write(1, s, (unsigned)len);
5011 return;
5012 }
5013
5014 /* translate ESC | sequences into faked bios calls */
5015 while (len--)
5016 {
5017 /* optimization: use one single write_chars for runs of text,
5018 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005019 DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005020
5021 if (p_wd)
5022 {
5023 WaitForChar(p_wd);
5024 if (prefix != 0)
5025 prefix = 1;
5026 }
5027
5028 if (prefix != 0)
5029 {
5030 DWORD nWritten;
5031
5032 nWritten = write_chars(s, prefix);
5033#ifdef MCH_WRITE_DUMP
5034 if (fdDump)
5035 {
5036 fputc('>', fdDump);
5037 fwrite(s, sizeof(char_u), nWritten, fdDump);
5038 fputs("<\n", fdDump);
5039 }
5040#endif
5041 len -= (nWritten - 1);
5042 s += nWritten;
5043 }
5044 else if (s[0] == '\n')
5045 {
5046 /* \n, newline: go to the beginning of the next line or scroll */
5047 if (g_coord.Y == g_srScrollRegion.Bottom)
5048 {
5049 scroll(1);
5050 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
5051 }
5052 else
5053 {
5054 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
5055 }
5056#ifdef MCH_WRITE_DUMP
5057 if (fdDump)
5058 fputs("\\n\n", fdDump);
5059#endif
5060 s++;
5061 }
5062 else if (s[0] == '\r')
5063 {
5064 /* \r, carriage return: go to beginning of line */
5065 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
5066#ifdef MCH_WRITE_DUMP
5067 if (fdDump)
5068 fputs("\\r\n", fdDump);
5069#endif
5070 s++;
5071 }
5072 else if (s[0] == '\b')
5073 {
5074 /* \b, backspace: move cursor one position left */
5075 if (g_coord.X > g_srScrollRegion.Left)
5076 g_coord.X--;
5077 else if (g_coord.Y > g_srScrollRegion.Top)
5078 {
5079 g_coord.X = g_srScrollRegion.Right;
5080 g_coord.Y--;
5081 }
5082 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5083#ifdef MCH_WRITE_DUMP
5084 if (fdDump)
5085 fputs("\\b\n", fdDump);
5086#endif
5087 s++;
5088 }
5089 else if (s[0] == '\a')
5090 {
5091 /* \a, bell */
5092 MessageBeep(0xFFFFFFFF);
5093#ifdef MCH_WRITE_DUMP
5094 if (fdDump)
5095 fputs("\\a\n", fdDump);
5096#endif
5097 s++;
5098 }
5099 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
5100 {
5101#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005102 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005103#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00005104 char_u *p;
5105 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005106
5107 switch (s[2])
5108 {
5109 /* one or two numeric arguments, separated by ';' */
5110
5111 case '0': case '1': case '2': case '3': case '4':
5112 case '5': case '6': case '7': case '8': case '9':
5113 p = s + 2;
5114 arg1 = getdigits(&p); /* no check for length! */
5115 if (p > s + len)
5116 break;
5117
5118 if (*p == ';')
5119 {
5120 ++p;
5121 arg2 = getdigits(&p); /* no check for length! */
5122 if (p > s + len)
5123 break;
5124
5125 if (*p == 'H')
5126 gotoxy(arg2, arg1);
5127 else if (*p == 'r')
5128 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
5129 }
5130 else if (*p == 'A')
5131 {
5132 /* move cursor up arg1 lines in same column */
5133 gotoxy(g_coord.X + 1,
5134 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
5135 }
5136 else if (*p == 'C')
5137 {
5138 /* move cursor right arg1 columns in same line */
5139 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
5140 g_coord.Y + 1);
5141 }
5142 else if (*p == 'H')
5143 {
5144 gotoxy(1, arg1);
5145 }
5146 else if (*p == 'L')
5147 {
5148 insert_lines(arg1);
5149 }
5150 else if (*p == 'm')
5151 {
5152 if (arg1 == 0)
5153 normvideo();
5154 else
5155 textattr((WORD) arg1);
5156 }
5157 else if (*p == 'f')
5158 {
5159 textcolor((WORD) arg1);
5160 }
5161 else if (*p == 'b')
5162 {
5163 textbackground((WORD) arg1);
5164 }
5165 else if (*p == 'M')
5166 {
5167 delete_lines(arg1);
5168 }
5169
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005170 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005171 s = p + 1;
5172 break;
5173
5174
5175 /* Three-character escape sequences */
5176
5177 case 'A':
5178 /* move cursor up one line in same column */
5179 gotoxy(g_coord.X + 1,
5180 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
5181 goto got3;
5182
5183 case 'B':
5184 visual_bell();
5185 goto got3;
5186
5187 case 'C':
5188 /* move cursor right one column in same line */
5189 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
5190 g_coord.Y + 1);
5191 goto got3;
5192
5193 case 'E':
5194 termcap_mode_end();
5195 goto got3;
5196
5197 case 'F':
5198 standout();
5199 goto got3;
5200
5201 case 'f':
5202 standend();
5203 goto got3;
5204
5205 case 'H':
5206 gotoxy(1, 1);
5207 goto got3;
5208
5209 case 'j':
5210 clear_to_end_of_display();
5211 goto got3;
5212
5213 case 'J':
5214 clear_screen();
5215 goto got3;
5216
5217 case 'K':
5218 clear_to_end_of_line();
5219 goto got3;
5220
5221 case 'L':
5222 insert_lines(1);
5223 goto got3;
5224
5225 case 'M':
5226 delete_lines(1);
5227 goto got3;
5228
5229 case 'S':
5230 termcap_mode_start();
5231 goto got3;
5232
5233 case 'V':
5234 cursor_visible(TRUE);
5235 goto got3;
5236
5237 case 'v':
5238 cursor_visible(FALSE);
5239 goto got3;
5240
5241 got3:
5242 s += 3;
5243 len -= 2;
5244 }
5245
5246#ifdef MCH_WRITE_DUMP
5247 if (fdDump)
5248 {
5249 fputs("ESC | ", fdDump);
5250 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
5251 fputc('\n', fdDump);
5252 }
5253#endif
5254 }
5255 else
5256 {
5257 /* Write a single character */
5258 DWORD nWritten;
5259
5260 nWritten = write_chars(s, 1);
5261#ifdef MCH_WRITE_DUMP
5262 if (fdDump)
5263 {
5264 fputc('>', fdDump);
5265 fwrite(s, sizeof(char_u), nWritten, fdDump);
5266 fputs("<\n", fdDump);
5267 }
5268#endif
5269
5270 len -= (nWritten - 1);
5271 s += nWritten;
5272 }
5273 }
5274
5275#ifdef MCH_WRITE_DUMP
5276 if (fdDump)
5277 fflush(fdDump);
5278#endif
5279}
5280
5281#endif /* FEAT_GUI_W32 */
5282
5283
5284/*
5285 * Delay for half a second.
5286 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005287/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00005288 void
5289mch_delay(
5290 long msec,
5291 int ignoreinput)
5292{
5293#ifdef FEAT_GUI_W32
5294 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005295#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005296 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00005297# ifdef FEAT_MZSCHEME
5298 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
5299 {
5300 int towait = p_mzq;
5301
5302 /* if msec is large enough, wait by portions in p_mzq */
5303 while (msec > 0)
5304 {
5305 mzvim_check_threads();
5306 if (msec < towait)
5307 towait = msec;
5308 Sleep(towait);
5309 msec -= towait;
5310 }
5311 }
5312 else
5313# endif
5314 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005315 else
5316 WaitForChar(msec);
5317#endif
5318}
5319
5320
5321/*
5322 * this version of remove is not scared by a readonly (backup) file
5323 * Return 0 for success, -1 for failure.
5324 */
5325 int
5326mch_remove(char_u *name)
5327{
5328#ifdef FEAT_MBYTE
5329 WCHAR *wn = NULL;
5330 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005331#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005332
Bram Moolenaar12b559e2013-06-12 22:41:37 +02005333 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
5334
5335#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00005336 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5337 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005338 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005339 if (wn != NULL)
5340 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00005341 n = DeleteFileW(wn) ? 0 : -1;
5342 vim_free(wn);
5343 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5344 return n;
5345 /* Retry with non-wide function (for Windows 98). */
5346 }
5347 }
5348#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005349 return DeleteFile(name) ? 0 : -1;
5350}
5351
5352
5353/*
5354 * check for an "interrupt signal": CTRL-break or CTRL-C
5355 */
5356 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005357mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005358{
5359#ifndef FEAT_GUI_W32 /* never used */
5360 if (g_fCtrlCPressed || g_fCBrkPressed)
5361 {
5362 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
5363 got_int = TRUE;
5364 }
5365#endif
5366}
5367
5368
Bram Moolenaar071d4272004-06-13 20:20:40 +00005369#ifdef FEAT_MBYTE
5370/*
5371 * Same code as below, but with wide functions and no comments.
5372 * Return 0 for success, non-zero for failure.
5373 */
5374 int
5375mch_wrename(WCHAR *wold, WCHAR *wnew)
5376{
5377 WCHAR *p;
5378 int i;
5379 WCHAR szTempFile[_MAX_PATH + 1];
5380 WCHAR szNewPath[_MAX_PATH + 1];
5381 HANDLE hf;
5382
5383 if (!mch_windows95())
5384 {
5385 p = wold;
5386 for (i = 0; wold[i] != NUL; ++i)
5387 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
5388 && wold[i + 1] != 0)
5389 p = wold + i + 1;
5390 if ((int)(wold + i - p) < 8 || p[6] != '~')
5391 return (MoveFileW(wold, wnew) == 0);
5392 }
5393
5394 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
5395 return -1;
5396 *p = NUL;
5397
5398 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
5399 return -2;
5400
5401 if (!DeleteFileW(szTempFile))
5402 return -3;
5403
5404 if (!MoveFileW(wold, szTempFile))
5405 return -4;
5406
5407 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5408 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5409 return -5;
5410 if (!CloseHandle(hf))
5411 return -6;
5412
5413 if (!MoveFileW(szTempFile, wnew))
5414 {
5415 (void)MoveFileW(szTempFile, wold);
5416 return -7;
5417 }
5418
5419 DeleteFileW(szTempFile);
5420
5421 if (!DeleteFileW(wold))
5422 return -8;
5423
5424 return 0;
5425}
5426#endif
5427
5428
5429/*
5430 * mch_rename() works around a bug in rename (aka MoveFile) in
5431 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
5432 * file whose short file name is "FOO.BAR" (its long file name will
5433 * be correct: "foo.bar~"). Because a file can be accessed by
5434 * either its SFN or its LFN, "foo.bar" has effectively been
5435 * renamed to "foo.bar", which is not at all what was wanted. This
5436 * seems to happen only when renaming files with three-character
5437 * extensions by appending a suffix that does not include ".".
5438 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
5439 *
5440 * There is another problem, which isn't really a bug but isn't right either:
5441 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
5442 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
5443 * service pack 6. Doesn't seem to happen on Windows 98.
5444 *
5445 * Like rename(), returns 0 upon success, non-zero upon failure.
5446 * Should probably set errno appropriately when errors occur.
5447 */
5448 int
5449mch_rename(
5450 const char *pszOldFile,
5451 const char *pszNewFile)
5452{
5453 char szTempFile[_MAX_PATH+1];
5454 char szNewPath[_MAX_PATH+1];
5455 char *pszFilePart;
5456 HANDLE hf;
5457#ifdef FEAT_MBYTE
5458 WCHAR *wold = NULL;
5459 WCHAR *wnew = NULL;
5460 int retval = -1;
5461
5462 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5463 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005464 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
5465 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005466 if (wold != NULL && wnew != NULL)
5467 retval = mch_wrename(wold, wnew);
5468 vim_free(wold);
5469 vim_free(wnew);
5470 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5471 return retval;
5472 /* Retry with non-wide function (for Windows 98). */
5473 }
5474#endif
5475
5476 /*
5477 * No need to play tricks if not running Windows 95, unless the file name
5478 * contains a "~" as the seventh character.
5479 */
5480 if (!mch_windows95())
5481 {
5482 pszFilePart = (char *)gettail((char_u *)pszOldFile);
5483 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
5484 return rename(pszOldFile, pszNewFile);
5485 }
5486
5487 /* Get base path of new file name. Undocumented feature: If pszNewFile is
5488 * a directory, no error is returned and pszFilePart will be NULL. */
5489 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
5490 || pszFilePart == NULL)
5491 return -1;
5492 *pszFilePart = NUL;
5493
5494 /* Get (and create) a unique temporary file name in directory of new file */
5495 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
5496 return -2;
5497
5498 /* blow the temp file away */
5499 if (!DeleteFile(szTempFile))
5500 return -3;
5501
5502 /* rename old file to the temp file */
5503 if (!MoveFile(pszOldFile, szTempFile))
5504 return -4;
5505
5506 /* now create an empty file called pszOldFile; this prevents the operating
5507 * system using pszOldFile as an alias (SFN) if we're renaming within the
5508 * same directory. For example, we're editing a file called
5509 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
5510 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
5511 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005512 * cause all sorts of problems later in buf_write(). So, we create an
5513 * empty file called filena~1.txt and the system will have to find some
5514 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 */
5516 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
5517 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
5518 return -5;
5519 if (!CloseHandle(hf))
5520 return -6;
5521
5522 /* rename the temp file to the new file */
5523 if (!MoveFile(szTempFile, pszNewFile))
5524 {
5525 /* Renaming failed. Rename the file back to its old name, so that it
5526 * looks like nothing happened. */
5527 (void)MoveFile(szTempFile, pszOldFile);
5528
5529 return -7;
5530 }
5531
5532 /* Seems to be left around on Novell filesystems */
5533 DeleteFile(szTempFile);
5534
5535 /* finally, remove the empty old file */
5536 if (!DeleteFile(pszOldFile))
5537 return -8;
5538
5539 return 0; /* success */
5540}
5541
5542/*
5543 * Get the default shell for the current hardware platform
5544 */
5545 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005546default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005547{
5548 char* psz = NULL;
5549
5550 PlatformId();
5551
5552 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
5553 psz = "cmd.exe";
5554 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
5555 psz = "command.com";
5556
5557 return psz;
5558}
5559
5560/*
5561 * mch_access() extends access() to do more detailed check on network drives.
5562 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
5563 */
5564 int
5565mch_access(char *n, int p)
5566{
5567 HANDLE hFile;
5568 DWORD am;
5569 int retval = -1; /* default: fail */
5570#ifdef FEAT_MBYTE
5571 WCHAR *wn = NULL;
5572
5573 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005574 wn = enc_to_utf16(n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575#endif
5576
5577 if (mch_isdir(n))
5578 {
5579 char TempName[_MAX_PATH + 16] = "";
5580#ifdef FEAT_MBYTE
5581 WCHAR TempNameW[_MAX_PATH + 16] = L"";
5582#endif
5583
5584 if (p & R_OK)
5585 {
5586 /* Read check is performed by seeing if we can do a find file on
5587 * the directory for any file. */
5588#ifdef FEAT_MBYTE
5589 if (wn != NULL)
5590 {
5591 int i;
5592 WIN32_FIND_DATAW d;
5593
5594 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
5595 TempNameW[i] = wn[i];
5596 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
5597 TempNameW[i++] = '\\';
5598 TempNameW[i++] = '*';
5599 TempNameW[i++] = 0;
5600
5601 hFile = FindFirstFileW(TempNameW, &d);
5602 if (hFile == INVALID_HANDLE_VALUE)
5603 {
5604 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5605 goto getout;
5606
5607 /* Retry with non-wide function (for Windows 98). */
5608 vim_free(wn);
5609 wn = NULL;
5610 }
5611 else
5612 (void)FindClose(hFile);
5613 }
5614 if (wn == NULL)
5615#endif
5616 {
5617 char *pch;
5618 WIN32_FIND_DATA d;
5619
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00005620 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005621 pch = TempName + STRLEN(TempName) - 1;
5622 if (*pch != '\\' && *pch != '/')
5623 *++pch = '\\';
5624 *++pch = '*';
5625 *++pch = NUL;
5626
5627 hFile = FindFirstFile(TempName, &d);
5628 if (hFile == INVALID_HANDLE_VALUE)
5629 goto getout;
5630 (void)FindClose(hFile);
5631 }
5632 }
5633
5634 if (p & W_OK)
5635 {
5636 /* Trying to create a temporary file in the directory should catch
5637 * directories on read-only network shares. However, in
5638 * directories whose ACL allows writes but denies deletes will end
5639 * up keeping the temporary file :-(. */
5640#ifdef FEAT_MBYTE
5641 if (wn != NULL)
5642 {
5643 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
5644 {
5645 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
5646 goto getout;
5647
5648 /* Retry with non-wide function (for Windows 98). */
5649 vim_free(wn);
5650 wn = NULL;
5651 }
5652 else
5653 DeleteFileW(TempNameW);
5654 }
5655 if (wn == NULL)
5656#endif
5657 {
5658 if (!GetTempFileName(n, "VIM", 0, TempName))
5659 goto getout;
5660 mch_remove((char_u *)TempName);
5661 }
5662 }
5663 }
5664 else
5665 {
5666 /* Trying to open the file for the required access does ACL, read-only
5667 * network share, and file attribute checks. */
5668 am = ((p & W_OK) ? GENERIC_WRITE : 0)
5669 | ((p & R_OK) ? GENERIC_READ : 0);
5670#ifdef FEAT_MBYTE
5671 if (wn != NULL)
5672 {
5673 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5674 if (hFile == INVALID_HANDLE_VALUE
5675 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
5676 {
5677 /* Retry with non-wide function (for Windows 98). */
5678 vim_free(wn);
5679 wn = NULL;
5680 }
5681 }
5682 if (wn == NULL)
5683#endif
5684 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
5685 if (hFile == INVALID_HANDLE_VALUE)
5686 goto getout;
5687 CloseHandle(hFile);
5688 }
5689
5690 retval = 0; /* success */
5691getout:
5692#ifdef FEAT_MBYTE
5693 vim_free(wn);
5694#endif
5695 return retval;
5696}
5697
5698#if defined(FEAT_MBYTE) || defined(PROTO)
5699/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005700 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701 */
5702 int
5703mch_open(char *name, int flags, int mode)
5704{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005705 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
5706# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707 WCHAR *wn;
5708 int f;
5709
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005710 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005711 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005712 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005713 if (wn != NULL)
5714 {
5715 f = _wopen(wn, flags, mode);
5716 vim_free(wn);
5717 if (f >= 0)
5718 return f;
5719 /* Retry with non-wide function (for Windows 98). Can't use
5720 * GetLastError() here and it's unclear what errno gets set to if
5721 * the _wopen() fails for missing wide functions. */
5722 }
5723 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00005724# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005725
5726 return open(name, flags, mode);
5727}
5728
5729/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005730 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005731 */
5732 FILE *
5733mch_fopen(char *name, char *mode)
5734{
5735 WCHAR *wn, *wm;
5736 FILE *f = NULL;
5737
5738 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
5739# ifdef __BORLANDC__
5740 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
5741 && g_PlatformId == VER_PLATFORM_WIN32_NT
5742# endif
5743 )
5744 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005745# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005746 /* Work around an annoying assertion in the Microsoft debug CRT
5747 * when mode's text/binary setting doesn't match _get_fmode(). */
5748 char newMode = mode[strlen(mode) - 1];
5749 int oldMode = 0;
5750
5751 _get_fmode(&oldMode);
5752 if (newMode == 't')
5753 _set_fmode(_O_TEXT);
5754 else if (newMode == 'b')
5755 _set_fmode(_O_BINARY);
5756# endif
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005757 wn = enc_to_utf16(name, NULL);
5758 wm = enc_to_utf16(mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005759 if (wn != NULL && wm != NULL)
5760 f = _wfopen(wn, wm);
5761 vim_free(wn);
5762 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005763
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00005764# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00005765 _set_fmode(oldMode);
5766# endif
5767
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768 if (f != NULL)
5769 return f;
5770 /* Retry with non-wide function (for Windows 98). Can't use
5771 * GetLastError() here and it's unclear what errno gets set to if
5772 * the _wfopen() fails for missing wide functions. */
5773 }
5774
5775 return fopen(name, mode);
5776}
5777#endif
5778
5779#ifdef FEAT_MBYTE
5780/*
5781 * SUB STREAM (aka info stream) handling:
5782 *
5783 * NTFS can have sub streams for each file. Normal contents of file is
5784 * stored in the main stream, and extra contents (author information and
5785 * title and so on) can be stored in sub stream. After Windows 2000, user
5786 * can access and store those informations in sub streams via explorer's
5787 * property menuitem in right click menu. Those informations in sub streams
5788 * were lost when copying only the main stream. So we have to copy sub
5789 * streams.
5790 *
5791 * Incomplete explanation:
5792 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
5793 * More useful info and an example:
5794 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
5795 */
5796
5797/*
5798 * Copy info stream data "substream". Read from the file with BackupRead(sh)
5799 * and write to stream "substream" of file "to".
5800 * Errors are ignored.
5801 */
5802 static void
5803copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
5804{
5805 HANDLE hTo;
5806 WCHAR *to_name;
5807
5808 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
5809 wcscpy(to_name, to);
5810 wcscat(to_name, substream);
5811
5812 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
5813 FILE_ATTRIBUTE_NORMAL, NULL);
5814 if (hTo != INVALID_HANDLE_VALUE)
5815 {
5816 long done;
5817 DWORD todo;
5818 DWORD readcnt, written;
5819 char buf[4096];
5820
5821 /* Copy block of bytes at a time. Abort when something goes wrong. */
5822 for (done = 0; done < len; done += written)
5823 {
5824 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005825 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
5826 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005827 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
5828 FALSE, FALSE, context)
5829 || readcnt != todo
5830 || !WriteFile(hTo, buf, todo, &written, NULL)
5831 || written != todo)
5832 break;
5833 }
5834 CloseHandle(hTo);
5835 }
5836
5837 free(to_name);
5838}
5839
5840/*
5841 * Copy info streams from file "from" to file "to".
5842 */
5843 static void
5844copy_infostreams(char_u *from, char_u *to)
5845{
5846 WCHAR *fromw;
5847 WCHAR *tow;
5848 HANDLE sh;
5849 WIN32_STREAM_ID sid;
5850 int headersize;
5851 WCHAR streamname[_MAX_PATH];
5852 DWORD readcount;
5853 void *context = NULL;
5854 DWORD lo, hi;
5855 int len;
5856
5857 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00005858 fromw = enc_to_utf16(from, NULL);
5859 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005860 if (fromw != NULL && tow != NULL)
5861 {
5862 /* Open the file for reading. */
5863 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
5864 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
5865 if (sh != INVALID_HANDLE_VALUE)
5866 {
5867 /* Use BackupRead() to find the info streams. Repeat until we
5868 * have done them all.*/
5869 for (;;)
5870 {
5871 /* Get the header to find the length of the stream name. If
5872 * the "readcount" is zero we have done all info streams. */
5873 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005874 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005875 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
5876 &readcount, FALSE, FALSE, &context)
5877 || readcount == 0)
5878 break;
5879
5880 /* We only deal with streams that have a name. The normal
5881 * file data appears to be without a name, even though docs
5882 * suggest it is called "::$DATA". */
5883 if (sid.dwStreamNameSize > 0)
5884 {
5885 /* Read the stream name. */
5886 if (!BackupRead(sh, (LPBYTE)streamname,
5887 sid.dwStreamNameSize,
5888 &readcount, FALSE, FALSE, &context))
5889 break;
5890
5891 /* Copy an info stream with a name ":anything:$DATA".
5892 * Skip "::$DATA", it has no stream name (examples suggest
5893 * it might be used for the normal file contents).
5894 * Note that BackupRead() counts bytes, but the name is in
5895 * wide characters. */
5896 len = readcount / sizeof(WCHAR);
5897 streamname[len] = 0;
5898 if (len > 7 && wcsicmp(streamname + len - 6,
5899 L":$DATA") == 0)
5900 {
5901 streamname[len - 6] = 0;
5902 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00005903 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005904 }
5905 }
5906
5907 /* Advance to the next stream. We might try seeking too far,
5908 * but BackupSeek() doesn't skip over stream borders, thus
5909 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00005910 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005911 &lo, &hi, &context);
5912 }
5913
5914 /* Clear the context. */
5915 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
5916
5917 CloseHandle(sh);
5918 }
5919 }
5920 vim_free(fromw);
5921 vim_free(tow);
5922}
5923#endif
5924
5925/*
5926 * Copy file attributes from file "from" to file "to".
5927 * For Windows NT and later we copy info streams.
5928 * Always returns zero, errors are ignored.
5929 */
5930 int
5931mch_copy_file_attribute(char_u *from, char_u *to)
5932{
5933#ifdef FEAT_MBYTE
5934 /* File streams only work on Windows NT and later. */
5935 PlatformId();
5936 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
5937 copy_infostreams(from, to);
5938#endif
5939 return 0;
5940}
5941
5942#if defined(MYRESETSTKOFLW) || defined(PROTO)
5943/*
5944 * Recreate a destroyed stack guard page in win32.
5945 * Written by Benjamin Peterson.
5946 */
5947
5948/* These magic numbers are from the MS header files */
5949#define MIN_STACK_WIN9X 17
5950#define MIN_STACK_WINNT 2
5951
5952/*
5953 * This function does the same thing as _resetstkoflw(), which is only
5954 * available in DevStudio .net and later.
5955 * Returns 0 for failure, 1 for success.
5956 */
5957 int
5958myresetstkoflw(void)
5959{
5960 BYTE *pStackPtr;
5961 BYTE *pGuardPage;
5962 BYTE *pStackBase;
5963 BYTE *pLowestPossiblePage;
5964 MEMORY_BASIC_INFORMATION mbi;
5965 SYSTEM_INFO si;
5966 DWORD nPageSize;
5967 DWORD dummy;
5968
5969 /* This code will not work on win32s. */
5970 PlatformId();
5971 if (g_PlatformId == VER_PLATFORM_WIN32s)
5972 return 0;
5973
5974 /* We need to know the system page size. */
5975 GetSystemInfo(&si);
5976 nPageSize = si.dwPageSize;
5977
5978 /* ...and the current stack pointer */
5979 pStackPtr = (BYTE*)_alloca(1);
5980
5981 /* ...and the base of the stack. */
5982 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
5983 return 0;
5984 pStackBase = (BYTE*)mbi.AllocationBase;
5985
5986 /* ...and the page thats min_stack_req pages away from stack base; this is
5987 * the lowest page we could use. */
5988 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
5989 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
5990
5991 /* On Win95, we want the next page down from the end of the stack. */
5992 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
5993 {
5994 /* Find the page that's only 1 page down from the page that the stack
5995 * ptr is in. */
5996 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
5997 / (DWORD)nPageSize) - 1));
5998 if (pGuardPage < pLowestPossiblePage)
5999 return 0;
6000
6001 /* Apply the noaccess attribute to the page -- there's no guard
6002 * attribute in win95-type OSes. */
6003 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
6004 return 0;
6005 }
6006 else
6007 {
6008 /* On NT, however, we want the first committed page in the stack Start
6009 * at the stack base and move forward through memory until we find a
6010 * committed block. */
6011 BYTE *pBlock = pStackBase;
6012
Bram Moolenaara466c992005-07-09 21:03:22 +00006013 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006014 {
6015 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6016 return 0;
6017
6018 pBlock += mbi.RegionSize;
6019
6020 if (mbi.State & MEM_COMMIT)
6021 break;
6022 }
6023
6024 /* mbi now describes the first committed block in the stack. */
6025 if (mbi.Protect & PAGE_GUARD)
6026 return 1;
6027
6028 /* decide where the guard page should start */
6029 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6030 pGuardPage = pLowestPossiblePage;
6031 else
6032 pGuardPage = (BYTE*)mbi.BaseAddress;
6033
6034 /* allocate the guard page */
6035 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6036 return 0;
6037
6038 /* apply the guard attribute to the page */
6039 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6040 &dummy))
6041 return 0;
6042 }
6043
6044 return 1;
6045}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006046#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006047
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006048
6049#if defined(FEAT_MBYTE) || defined(PROTO)
6050/*
6051 * The command line arguments in UCS2
6052 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006053static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006054static LPWSTR *ArglistW = NULL;
6055static int global_argc = 0;
6056static char **global_argv;
6057
6058static int used_file_argc = 0; /* last argument in global_argv[] used
6059 for the argument list. */
6060static int *used_file_indexes = NULL; /* indexes in global_argv[] for
6061 command line arguments added to
6062 the argument list */
6063static int used_file_count = 0; /* nr of entries in used_file_indexes */
6064static int used_file_literal = FALSE; /* take file names literally */
6065static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006066static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006067static int used_alist_count = 0;
6068
6069
6070/*
6071 * Get the command line arguments. Unicode version.
6072 * Returns argc. Zero when something fails.
6073 */
6074 int
6075get_cmd_argsW(char ***argvp)
6076{
6077 char **argv = NULL;
6078 int argc = 0;
6079 int i;
6080
6081 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
6082 if (ArglistW != NULL)
6083 {
6084 argv = malloc((nArgsW + 1) * sizeof(char *));
6085 if (argv != NULL)
6086 {
6087 argc = nArgsW;
6088 argv[argc] = NULL;
6089 for (i = 0; i < argc; ++i)
6090 {
6091 int len;
6092
6093 /* Convert each Unicode argument to the current codepage. */
6094 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006095 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006096 (LPSTR *)&argv[i], &len, 0, 0);
6097 if (argv[i] == NULL)
6098 {
6099 /* Out of memory, clear everything. */
6100 while (i > 0)
6101 free(argv[--i]);
6102 free(argv);
6103 argc = 0;
6104 }
6105 }
6106 }
6107 }
6108
6109 global_argc = argc;
6110 global_argv = argv;
6111 if (argc > 0)
6112 used_file_indexes = malloc(argc * sizeof(int));
6113
6114 if (argvp != NULL)
6115 *argvp = argv;
6116 return argc;
6117}
6118
6119 void
6120free_cmd_argsW(void)
6121{
6122 if (ArglistW != NULL)
6123 {
6124 GlobalFree(ArglistW);
6125 ArglistW = NULL;
6126 }
6127}
6128
6129/*
6130 * Remember "name" is an argument that was added to the argument list.
6131 * This avoids that we have to re-parse the argument list when fix_arg_enc()
6132 * is called.
6133 */
6134 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006135used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006136{
6137 int i;
6138
6139 if (used_file_indexes == NULL)
6140 return;
6141 for (i = used_file_argc + 1; i < global_argc; ++i)
6142 if (STRCMP(global_argv[i], name) == 0)
6143 {
6144 used_file_argc = i;
6145 used_file_indexes[used_file_count++] = i;
6146 break;
6147 }
6148 used_file_literal = literal;
6149 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006150 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006151}
6152
6153/*
6154 * Remember the length of the argument list as it was. If it changes then we
6155 * leave it alone when 'encoding' is set.
6156 */
6157 void
6158set_alist_count(void)
6159{
6160 used_alist_count = GARGCOUNT;
6161}
6162
6163/*
6164 * Fix the encoding of the command line arguments. Invoked when 'encoding'
6165 * has been changed while starting up. Use the UCS-2 command line arguments
6166 * and convert them to 'encoding'.
6167 */
6168 void
6169fix_arg_enc(void)
6170{
6171 int i;
6172 int idx;
6173 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00006174 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006175
6176 /* Safety checks:
6177 * - if argument count differs between the wide and non-wide argument
6178 * list, something must be wrong.
6179 * - the file name arguments must have been located.
6180 * - the length of the argument list wasn't changed by the user.
6181 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00006182 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006183 || ArglistW == NULL
6184 || used_file_indexes == NULL
6185 || used_file_count == 0
6186 || used_alist_count != GARGCOUNT)
6187 return;
6188
Bram Moolenaar86b68352004-12-27 21:59:20 +00006189 /* Remember the buffer numbers for the arguments. */
6190 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
6191 if (fnum_list == NULL)
6192 return; /* out of memory */
6193 for (i = 0; i < GARGCOUNT; ++i)
6194 fnum_list[i] = GARGLIST[i].ae_fnum;
6195
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006196 /* Clear the argument list. Make room for the new arguments. */
6197 alist_clear(&global_alist);
6198 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006199 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006200
6201 for (i = 0; i < used_file_count; ++i)
6202 {
6203 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006204 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006205 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00006206 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00006207#ifdef FEAT_DIFF
6208 /* When using diff mode may need to concatenate file name to
6209 * directory name. Just like it's done in main(). */
6210 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
6211 && !mch_isdir(alist_name(&GARGLIST[0])))
6212 {
6213 char_u *r;
6214
6215 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
6216 if (r != NULL)
6217 {
6218 vim_free(str);
6219 str = r;
6220 }
6221 }
6222#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00006223 /* Re-use the old buffer by renaming it. When not using literal
6224 * names it's done by alist_expand() below. */
6225 if (used_file_literal)
6226 buf_set_name(fnum_list[i], str);
6227
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006228 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00006229 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006230 }
6231
6232 if (!used_file_literal)
6233 {
6234 /* Now expand wildcards in the arguments. */
6235 /* Temporarily add '(' and ')' to 'isfname'. These are valid
6236 * filename characters but are excluded from 'isfname' to make
6237 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
6238 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00006239 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006240 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
6241 }
6242
6243 /* If wildcard expansion failed, we are editing the first file of the
6244 * arglist and there is no file name: Edit the first argument now. */
6245 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
6246 {
6247 do_cmdline_cmd((char_u *)":rewind");
6248 if (GARGCOUNT == 1 && used_file_full_path)
6249 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
6250 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00006251
6252 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006253}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254#endif