blob: 330ce5a572699b0399e79733c7e2ba99210a3015 [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 Moolenaar362e1a32006-03-06 23:29:24 +000023#include "vimio.h"
Bram Moolenaar071d4272004-06-13 20:20:40 +000024#include "vim.h"
25
Bram Moolenaar325b7a22004-07-05 15:58:32 +000026#ifdef FEAT_MZSCHEME
27# include "if_mzsch.h"
28#endif
29
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#ifdef HAVE_FCNTL_H
31# include <fcntl.h>
32#endif
33#include <sys/types.h>
34#include <errno.h>
35#include <signal.h>
36#include <limits.h>
37#include <process.h>
38
39#undef chdir
40#ifdef __GNUC__
41# ifndef __MINGW32__
42# include <dirent.h>
43# endif
44#else
45# include <direct.h>
46#endif
47
48#if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50#endif
51
52#ifdef __MINGW32__
53# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
54# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
55# endif
56# ifndef RIGHTMOST_BUTTON_PRESSED
57# define RIGHTMOST_BUTTON_PRESSED 0x0002
58# endif
59# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
60# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
61# endif
62# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
63# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
64# endif
65# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
66# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
67# endif
68
69/*
70 * EventFlags
71 */
72# ifndef MOUSE_MOVED
73# define MOUSE_MOVED 0x0001
74# endif
75# ifndef DOUBLE_CLICK
76# define DOUBLE_CLICK 0x0002
77# endif
78#endif
79
80/* Record all output and all keyboard & mouse input */
81/* #define MCH_WRITE_DUMP */
82
83#ifdef MCH_WRITE_DUMP
84FILE* fdDump = NULL;
85#endif
86
87/*
88 * When generating prototypes for Win32 on Unix, these lines make the syntax
89 * errors disappear. They do not need to be correct.
90 */
91#ifdef PROTO
92#define WINAPI
93#define WINBASEAPI
94typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000095typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +000096typedef int ACCESS_MASK;
97typedef int BOOL;
98typedef int COLORREF;
99typedef int CONSOLE_CURSOR_INFO;
100typedef int COORD;
101typedef int DWORD;
102typedef int HANDLE;
103typedef int HDC;
104typedef int HFONT;
105typedef int HICON;
106typedef int HINSTANCE;
107typedef int HWND;
108typedef int INPUT_RECORD;
109typedef int KEY_EVENT_RECORD;
110typedef int LOGFONT;
111typedef int LPBOOL;
112typedef int LPCTSTR;
113typedef int LPDWORD;
114typedef int LPSTR;
115typedef int LPTSTR;
116typedef int LPVOID;
117typedef int MOUSE_EVENT_RECORD;
118typedef int PACL;
119typedef int PDWORD;
120typedef int PHANDLE;
121typedef int PRINTDLG;
122typedef int PSECURITY_DESCRIPTOR;
123typedef int PSID;
124typedef int SECURITY_INFORMATION;
125typedef int SHORT;
126typedef int SMALL_RECT;
127typedef int TEXTMETRIC;
128typedef int TOKEN_INFORMATION_CLASS;
129typedef int TRUSTEE;
130typedef int WORD;
131typedef int WCHAR;
132typedef void VOID;
133#endif
134
135#ifndef FEAT_GUI_W32
136/* Undocumented API in kernel32.dll needed to work around dead key bug in
137 * console-mode applications in NT 4.0. If you switch keyboard layouts
138 * in a console app to a layout that includes dead keys and then hit a
139 * dead key, a call to ToAscii will trash the stack. My thanks to Ian James
140 * and Michael Dietrich for helping me figure out this workaround.
141 */
142
143/* WINBASEAPI BOOL WINAPI GetConsoleKeyboardLayoutNameA(LPSTR); */
144#ifndef WINBASEAPI
145# define WINBASEAPI __stdcall
146#endif
147#if defined(__BORLANDC__)
148typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
149#else
150typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
151#endif
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000152static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000153#endif
154
155#if defined(__BORLANDC__)
156/* Strangely Borland uses a non-standard name. */
157# define wcsicmp(a, b) wcscmpi((a), (b))
158#endif
159
160#ifndef FEAT_GUI_W32
161/* Win32 Console handles for input and output */
162static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
163static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
164
165/* Win32 Screen buffer,coordinate,console I/O information */
166static SMALL_RECT g_srScrollRegion;
167static COORD g_coord; /* 0-based, but external coords are 1-based */
168
169/* The attribute of the screen when the editor was started */
170static WORD g_attrDefault = 7; /* lightgray text on black background */
171static WORD g_attrCurrent;
172
173static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
174static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
175static int g_fForceExit = FALSE; /* set when forcefully exiting */
176
177static void termcap_mode_start(void);
178static void termcap_mode_end(void);
179static void clear_chars(COORD coord, DWORD n);
180static void clear_screen(void);
181static void clear_to_end_of_display(void);
182static void clear_to_end_of_line(void);
183static void scroll(unsigned cLines);
184static void set_scroll_region(unsigned left, unsigned top,
185 unsigned right, unsigned bottom);
186static void insert_lines(unsigned cLines);
187static void delete_lines(unsigned cLines);
188static void gotoxy(unsigned x, unsigned y);
189static void normvideo(void);
190static void textattr(WORD wAttr);
191static void textcolor(WORD wAttr);
192static void textbackground(WORD wAttr);
193static void standout(void);
194static void standend(void);
195static void visual_bell(void);
196static void cursor_visible(BOOL fVisible);
197static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
198static char_u tgetch(int *pmodifiers, char_u *pch2);
199static void create_conin(void);
200static int s_cursor_visible = TRUE;
201static int did_create_conin = FALSE;
202#else
203static int s_dont_use_vimrun = TRUE;
204static int need_vimrun_warning = FALSE;
205static char *vimrun_path = "vimrun ";
206#endif
207
208#ifndef FEAT_GUI_W32
209static int suppress_winsize = 1; /* don't fiddle with console */
210#endif
211
212 static void
213get_exe_name(void)
214{
215 char temp[256];
216
217 if (exe_name == NULL)
218 {
219 /* store the name of the executable, may be used for $VIM */
220 GetModuleFileName(NULL, temp, 255);
221 if (*temp != NUL)
222 exe_name = FullName_save((char_u *)temp, FALSE);
223 }
224}
225
226#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
227# ifndef GETTEXT_DLL
228# define GETTEXT_DLL "libintl.dll"
229# endif
230/* Dummy funcitons */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000231static char *null_libintl_gettext(const char *);
232static char *null_libintl_textdomain(const char *);
233static char *null_libintl_bindtextdomain(const char *, const char *);
234static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000235
236static HINSTANCE hLibintlDLL = 0;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000237char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
238char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
239char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000240 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000241char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
242 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243
244 int
245dyn_libintl_init(char *libname)
246{
247 int i;
248 static struct
249 {
250 char *name;
251 FARPROC *ptr;
252 } libintl_entry[] =
253 {
254 {"gettext", (FARPROC*)&dyn_libintl_gettext},
255 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
256 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
257 {NULL, NULL}
258 };
259
260 /* No need to initialize twice. */
261 if (hLibintlDLL)
262 return 1;
263 /* Load gettext library (libintl.dll) */
264 hLibintlDLL = LoadLibrary(libname != NULL ? libname : GETTEXT_DLL);
265 if (!hLibintlDLL)
266 {
267 char_u dirname[_MAX_PATH];
268
269 /* Try using the path from gvim.exe to find the .dll there. */
270 get_exe_name();
271 STRCPY(dirname, exe_name);
272 STRCPY(gettail(dirname), GETTEXT_DLL);
273 hLibintlDLL = LoadLibrary((char *)dirname);
274 if (!hLibintlDLL)
275 {
276 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000277 {
278 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000279 EMSG2(_(e_loadlib), GETTEXT_DLL);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000280 verbose_leave();
281 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000282 return 0;
283 }
284 }
285 for (i = 0; libintl_entry[i].name != NULL
286 && libintl_entry[i].ptr != NULL; ++i)
287 {
288 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
289 libintl_entry[i].name)) == NULL)
290 {
291 dyn_libintl_end();
292 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000293 {
294 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000295 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000296 verbose_leave();
297 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000298 return 0;
299 }
300 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000301
302 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000303 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000304 "bind_textdomain_codeset");
305 if (dyn_libintl_bind_textdomain_codeset == NULL)
306 dyn_libintl_bind_textdomain_codeset =
307 null_libintl_bind_textdomain_codeset;
308
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309 return 1;
310}
311
312 void
313dyn_libintl_end()
314{
315 if (hLibintlDLL)
316 FreeLibrary(hLibintlDLL);
317 hLibintlDLL = NULL;
318 dyn_libintl_gettext = null_libintl_gettext;
319 dyn_libintl_textdomain = null_libintl_textdomain;
320 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000321 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000322}
323
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000324/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000326null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000327{
328 return (char*)msgid;
329}
330
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000331/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000332 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000333null_libintl_bindtextdomain(const char *domainname, const char *dirname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000334{
335 return NULL;
336}
337
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000338/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000339 static char *
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000340null_libintl_bind_textdomain_codeset(const char *domainname,
341 const char *codeset)
342{
343 return NULL;
344}
345
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000346/*ARGSUSED*/
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000347 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000348null_libintl_textdomain(const char *domainname)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000349{
350 return NULL;
351}
352
353#endif /* DYNAMIC_GETTEXT */
354
355/* This symbol is not defined in older versions of the SDK or Visual C++ */
356
357#ifndef VER_PLATFORM_WIN32_WINDOWS
358# define VER_PLATFORM_WIN32_WINDOWS 1
359#endif
360
361DWORD g_PlatformId;
362
363#ifdef HAVE_ACL
364# include <aclapi.h>
365/*
366 * These are needed to dynamically load the ADVAPI DLL, which is not
367 * implemented under Windows 95 (and causes VIM to crash)
368 */
369typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
370 SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
371typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
372 SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
373 PSECURITY_DESCRIPTOR *);
374
375static HANDLE advapi_lib = NULL; /* Handle for ADVAPI library */
376static PSNSECINFO pSetNamedSecurityInfo;
377static PGNSECINFO pGetNamedSecurityInfo;
378#endif
379
380/*
381 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
382 * VER_PLATFORM_WIN32_WINDOWS (Win95).
383 */
384 void
385PlatformId(void)
386{
387 static int done = FALSE;
388
389 if (!done)
390 {
391 OSVERSIONINFO ovi;
392
393 ovi.dwOSVersionInfoSize = sizeof(ovi);
394 GetVersionEx(&ovi);
395
396 g_PlatformId = ovi.dwPlatformId;
397
398#ifdef HAVE_ACL
399 /*
400 * Load the ADVAPI runtime if we are on anything
401 * other than Windows 95
402 */
403 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
404 {
405 /*
406 * do this load. Problems: Doesn't unload at end of run (this is
407 * theoretically okay, since Windows should unload it when VIM
408 * terminates). Should we be using the 'mch_libcall' routines?
409 * Seems like a lot of overhead to load/unload ADVAPI32.DLL each
410 * time we verify security...
411 */
412 advapi_lib = LoadLibrary("ADVAPI32.DLL");
413 if (advapi_lib != NULL)
414 {
415 pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
416 "SetNamedSecurityInfoA");
417 pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
418 "GetNamedSecurityInfoA");
419 if (pSetNamedSecurityInfo == NULL
420 || pGetNamedSecurityInfo == NULL)
421 {
422 /* If we can't get the function addresses, set advapi_lib
423 * to NULL so that we don't use them. */
424 FreeLibrary(advapi_lib);
425 advapi_lib = NULL;
426 }
427 }
428 }
429#endif
430 done = TRUE;
431 }
432}
433
434/*
435 * Return TRUE when running on Windows 95 (or 98 or ME).
436 * Only to be used after mch_init().
437 */
438 int
439mch_windows95(void)
440{
441 return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
442}
443
444#ifdef FEAT_GUI_W32
445/*
446 * Used to work around the "can't do synchronous spawn"
447 * problem on Win32s, without resorting to Universal Thunk.
448 */
449static int old_num_windows;
450static int num_windows;
451
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000452/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000453 static BOOL CALLBACK
454win32ssynch_cb(HWND hwnd, LPARAM lparam)
455{
456 num_windows++;
457 return TRUE;
458}
459#endif
460
461#ifndef FEAT_GUI_W32
462
463#define SHIFT (SHIFT_PRESSED)
464#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
465#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
466#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
467
468
469/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
470 * We map function keys to their ANSI terminal equivalents, as produced
471 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
472 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
473 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
474 * combinations of function/arrow/etc keys.
475 */
476
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000477static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478{
479 WORD wVirtKey;
480 BOOL fAnsiKey;
481 int chAlone;
482 int chShift;
483 int chCtrl;
484 int chAlt;
485} VirtKeyMap[] =
486{
487
488/* Key ANSI alone shift ctrl alt */
489 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
490
491 { VK_F1, TRUE, ';', 'T', '^', 'h', },
492 { VK_F2, TRUE, '<', 'U', '_', 'i', },
493 { VK_F3, TRUE, '=', 'V', '`', 'j', },
494 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
495 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
496 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
497 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
498 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
499 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
500 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
501 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
502 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
503
504 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
505 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
506 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
507 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
508 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
509 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
510 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
511 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
512 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
513 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
514
515 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
516
517#if 0
518 /* Most people don't have F13-F20, but what the hell... */
519 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
520 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
521 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
522 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
523 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
524 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
525 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
526 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
527#endif
528 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
529 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
530 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
531 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
532
533 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
534 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
535 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
536 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
537 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
538 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
539 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
540 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
541 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
542 /* Sorry, out of number space! <negri>*/
543 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
544
545};
546
547
548#ifdef _MSC_VER
549// The ToAscii bug destroys several registers. Need to turn off optimization
550// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
551# pragma optimize("", off)
552#endif
553
554#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
555# define AChar AsciiChar
556#else
557# define AChar uChar.AsciiChar
558#endif
559
560/* The return code indicates key code size. */
561 static int
562#ifdef __BORLANDC__
563 __stdcall
564#endif
565win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000566 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000567{
568 UINT uMods = pker->dwControlKeyState;
569 static int s_iIsDead = 0;
570 static WORD awAnsiCode[2];
571 static BYTE abKeystate[256];
572
573
574 if (s_iIsDead == 2)
575 {
576 pker->AChar = (CHAR) awAnsiCode[1];
577 s_iIsDead = 0;
578 return 1;
579 }
580
581 if (pker->AChar != 0)
582 return 1;
583
584 memset(abKeystate, 0, sizeof (abKeystate));
585
586 // Should only be non-NULL on NT 4.0
587 if (s_pfnGetConsoleKeyboardLayoutName != NULL)
588 {
589 CHAR szKLID[KL_NAMELENGTH];
590
591 if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
592 (void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
593 }
594
595 /* Clear any pending dead keys */
596 ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
597
598 if (uMods & SHIFT_PRESSED)
599 abKeystate[VK_SHIFT] = 0x80;
600 if (uMods & CAPSLOCK_ON)
601 abKeystate[VK_CAPITAL] = 1;
602
603 if ((uMods & ALT_GR) == ALT_GR)
604 {
605 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
606 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
607 }
608
609 s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
610 abKeystate, awAnsiCode, 0);
611
612 if (s_iIsDead > 0)
613 pker->AChar = (CHAR) awAnsiCode[0];
614
615 return s_iIsDead;
616}
617
618#ifdef _MSC_VER
619/* MUST switch optimization on again here, otherwise a call to
620 * decode_key_event() may crash (e.g. when hitting caps-lock) */
621# pragma optimize("", on)
622
623# if (_MSC_VER < 1100)
624/* MUST turn off global optimisation for this next function, or
625 * pressing ctrl-minus in insert mode crashes Vim when built with
626 * VC4.1. -- negri. */
627# pragma optimize("g", off)
628# endif
629#endif
630
631static BOOL g_fJustGotFocus = FALSE;
632
633/*
634 * Decode a KEY_EVENT into one or two keystrokes
635 */
636 static BOOL
637decode_key_event(
638 KEY_EVENT_RECORD *pker,
639 char_u *pch,
640 char_u *pch2,
641 int *pmodifiers,
642 BOOL fDoPost)
643{
644 int i;
645 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
646
647 *pch = *pch2 = NUL;
648 g_fJustGotFocus = FALSE;
649
650 /* ignore key up events */
651 if (!pker->bKeyDown)
652 return FALSE;
653
654 /* ignore some keystrokes */
655 switch (pker->wVirtualKeyCode)
656 {
657 /* modifiers */
658 case VK_SHIFT:
659 case VK_CONTROL:
660 case VK_MENU: /* Alt key */
661 return FALSE;
662
663 default:
664 break;
665 }
666
667 /* special cases */
668 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
669 {
670 /* Ctrl-6 is Ctrl-^ */
671 if (pker->wVirtualKeyCode == '6')
672 {
673 *pch = Ctrl_HAT;
674 return TRUE;
675 }
676 /* Ctrl-2 is Ctrl-@ */
677 else if (pker->wVirtualKeyCode == '2')
678 {
679 *pch = NUL;
680 return TRUE;
681 }
682 /* Ctrl-- is Ctrl-_ */
683 else if (pker->wVirtualKeyCode == 0xBD)
684 {
685 *pch = Ctrl__;
686 return TRUE;
687 }
688 }
689
690 /* Shift-TAB */
691 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
692 {
693 *pch = K_NUL;
694 *pch2 = '\017';
695 return TRUE;
696 }
697
698 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
699 {
700 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
701 {
702 if (nModifs == 0)
703 *pch = VirtKeyMap[i].chAlone;
704 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
705 *pch = VirtKeyMap[i].chShift;
706 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
707 *pch = VirtKeyMap[i].chCtrl;
708 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
709 *pch = VirtKeyMap[i].chAlt;
710
711 if (*pch != 0)
712 {
713 if (VirtKeyMap[i].fAnsiKey)
714 {
715 *pch2 = *pch;
716 *pch = K_NUL;
717 }
718
719 return TRUE;
720 }
721 }
722 }
723
724 i = win32_kbd_patch_key(pker);
725
726 if (i < 0)
727 *pch = NUL;
728 else
729 {
730 *pch = (i > 0) ? pker->AChar : NUL;
731
732 if (pmodifiers != NULL)
733 {
734 /* Pass on the ALT key as a modifier, but only when not combined
735 * with CTRL (which is ALTGR). */
736 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
737 *pmodifiers |= MOD_MASK_ALT;
738
739 /* Pass on SHIFT only for special keys, because we don't know when
740 * it's already included with the character. */
741 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
742 *pmodifiers |= MOD_MASK_SHIFT;
743
744 /* Pass on CTRL only for non-special keys, because we don't know
745 * when it's already included with the character. And not when
746 * combined with ALT (which is ALTGR). */
747 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
748 && *pch >= 0x20 && *pch < 0x80)
749 *pmodifiers |= MOD_MASK_CTRL;
750 }
751 }
752
753 return (*pch != NUL);
754}
755
756#ifdef _MSC_VER
757# pragma optimize("", on)
758#endif
759
760#endif /* FEAT_GUI_W32 */
761
762
763#ifdef FEAT_MOUSE
764
765/*
766 * For the GUI the mouse handling is in gui_w32.c.
767 */
768# ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000769/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000771mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772{
773}
774# else
775static int g_fMouseAvail = FALSE; /* mouse present */
776static int g_fMouseActive = FALSE; /* mouse enabled */
777static int g_nMouseClick = -1; /* mouse status */
778static int g_xMouse; /* mouse x coordinate */
779static int g_yMouse; /* mouse y coordinate */
780
781/*
782 * Enable or disable mouse input
783 */
784 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000785mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000786{
787 DWORD cmodein;
788
789 if (!g_fMouseAvail)
790 return;
791
792 g_fMouseActive = on;
793 GetConsoleMode(g_hConIn, &cmodein);
794
795 if (g_fMouseActive)
796 cmodein |= ENABLE_MOUSE_INPUT;
797 else
798 cmodein &= ~ENABLE_MOUSE_INPUT;
799
800 SetConsoleMode(g_hConIn, cmodein);
801}
802
803
804/*
805 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
806 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
807 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
808 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
809 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
810 * and we return the mouse position in g_xMouse and g_yMouse.
811 *
812 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
813 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
814 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
815 *
816 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
817 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
818 *
819 * Windows will send us MOUSE_MOVED notifications whenever the mouse
820 * moves, even if it stays within the same character cell. We ignore
821 * all MOUSE_MOVED messages if the position hasn't really changed, and
822 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
823 * we're only interested in MOUSE_DRAG).
824 *
825 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
826 * 2-button mouses by pressing the left & right buttons simultaneously.
827 * In practice, it's almost impossible to click both at the same time,
828 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
829 * in such cases, if the user is clicking quickly.
830 */
831 static BOOL
832decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000833 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000834{
835 static int s_nOldButton = -1;
836 static int s_nOldMouseClick = -1;
837 static int s_xOldMouse = -1;
838 static int s_yOldMouse = -1;
839 static linenr_T s_old_topline = 0;
840#ifdef FEAT_DIFF
841 static int s_old_topfill = 0;
842#endif
843 static int s_cClicks = 1;
844 static BOOL s_fReleased = TRUE;
845 static DWORD s_dwLastClickTime = 0;
846 static BOOL s_fNextIsMiddle = FALSE;
847
848 static DWORD cButtons = 0; /* number of buttons supported */
849
850 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
851 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
852 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
853 const DWORD LEFT_RIGHT = LEFT | RIGHT;
854
855 int nButton;
856
857 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
858 cButtons = 2;
859
860 if (!g_fMouseAvail || !g_fMouseActive)
861 {
862 g_nMouseClick = -1;
863 return FALSE;
864 }
865
866 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
867 if (g_fJustGotFocus)
868 {
869 g_fJustGotFocus = FALSE;
870 return FALSE;
871 }
872
873 /* unprocessed mouse click? */
874 if (g_nMouseClick != -1)
875 return TRUE;
876
877 nButton = -1;
878 g_xMouse = pmer->dwMousePosition.X;
879 g_yMouse = pmer->dwMousePosition.Y;
880
881 if (pmer->dwEventFlags == MOUSE_MOVED)
882 {
883 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
884 * events even when the mouse moves only within a char cell.) */
885 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
886 return FALSE;
887 }
888
889 /* If no buttons are pressed... */
890 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
891 {
892 /* If the last thing returned was MOUSE_RELEASE, ignore this */
893 if (s_fReleased)
894 return FALSE;
895
896 nButton = MOUSE_RELEASE;
897 s_fReleased = TRUE;
898 }
899 else /* one or more buttons pressed */
900 {
901 /* on a 2-button mouse, hold down left and right buttons
902 * simultaneously to get MIDDLE. */
903
904 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
905 {
906 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
907
908 /* if either left or right button only is pressed, see if the
909 * the next mouse event has both of them pressed */
910 if (dwLR == LEFT || dwLR == RIGHT)
911 {
912 for (;;)
913 {
914 /* wait a short time for next input event */
915 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
916 != WAIT_OBJECT_0)
917 break;
918 else
919 {
920 DWORD cRecords = 0;
921 INPUT_RECORD ir;
922 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
923
924 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
925
926 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
927 || !(pmer2->dwButtonState & LEFT_RIGHT))
928 break;
929 else
930 {
931 if (pmer2->dwEventFlags != MOUSE_MOVED)
932 {
933 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
934
935 return decode_mouse_event(pmer2);
936 }
937 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
938 s_yOldMouse == pmer2->dwMousePosition.Y)
939 {
940 /* throw away spurious mouse move */
941 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
942
943 /* are there any more mouse events in queue? */
944 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
945
946 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
947 break;
948 }
949 else
950 break;
951 }
952 }
953 }
954 }
955 }
956
957 if (s_fNextIsMiddle)
958 {
959 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
960 ? MOUSE_DRAG : MOUSE_MIDDLE;
961 s_fNextIsMiddle = FALSE;
962 }
963 else if (cButtons == 2 &&
964 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
965 {
966 nButton = MOUSE_MIDDLE;
967
968 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
969 {
970 s_fNextIsMiddle = TRUE;
971 nButton = MOUSE_RELEASE;
972 }
973 }
974 else if ((pmer->dwButtonState & LEFT) == LEFT)
975 nButton = MOUSE_LEFT;
976 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
977 nButton = MOUSE_MIDDLE;
978 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
979 nButton = MOUSE_RIGHT;
980
981 if (! s_fReleased && ! s_fNextIsMiddle
982 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
983 return FALSE;
984
985 s_fReleased = s_fNextIsMiddle;
986 }
987
988 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
989 {
990 /* button pressed or released, without mouse moving */
991 if (nButton != -1 && nButton != MOUSE_RELEASE)
992 {
993 DWORD dwCurrentTime = GetTickCount();
994
995 if (s_xOldMouse != g_xMouse
996 || s_yOldMouse != g_yMouse
997 || s_nOldButton != nButton
998 || s_old_topline != curwin->w_topline
999#ifdef FEAT_DIFF
1000 || s_old_topfill != curwin->w_topfill
1001#endif
1002 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1003 {
1004 s_cClicks = 1;
1005 }
1006 else if (++s_cClicks > 4)
1007 {
1008 s_cClicks = 1;
1009 }
1010
1011 s_dwLastClickTime = dwCurrentTime;
1012 }
1013 }
1014 else if (pmer->dwEventFlags == MOUSE_MOVED)
1015 {
1016 if (nButton != -1 && nButton != MOUSE_RELEASE)
1017 nButton = MOUSE_DRAG;
1018
1019 s_cClicks = 1;
1020 }
1021
1022 if (nButton == -1)
1023 return FALSE;
1024
1025 if (nButton != MOUSE_RELEASE)
1026 s_nOldButton = nButton;
1027
1028 g_nMouseClick = nButton;
1029
1030 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1031 g_nMouseClick |= MOUSE_SHIFT;
1032 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1033 g_nMouseClick |= MOUSE_CTRL;
1034 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1035 g_nMouseClick |= MOUSE_ALT;
1036
1037 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1038 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1039
1040 /* only pass on interesting (i.e., different) mouse events */
1041 if (s_xOldMouse == g_xMouse
1042 && s_yOldMouse == g_yMouse
1043 && s_nOldMouseClick == g_nMouseClick)
1044 {
1045 g_nMouseClick = -1;
1046 return FALSE;
1047 }
1048
1049 s_xOldMouse = g_xMouse;
1050 s_yOldMouse = g_yMouse;
1051 s_old_topline = curwin->w_topline;
1052#ifdef FEAT_DIFF
1053 s_old_topfill = curwin->w_topfill;
1054#endif
1055 s_nOldMouseClick = g_nMouseClick;
1056
1057 return TRUE;
1058}
1059
1060# endif /* FEAT_GUI_W32 */
1061#endif /* FEAT_MOUSE */
1062
1063
1064#ifdef MCH_CURSOR_SHAPE
1065/*
1066 * Set the shape of the cursor.
1067 * 'thickness' can be from 1 (thin) to 99 (block)
1068 */
1069 static void
1070mch_set_cursor_shape(int thickness)
1071{
1072 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1073 ConsoleCursorInfo.dwSize = thickness;
1074 ConsoleCursorInfo.bVisible = s_cursor_visible;
1075
1076 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1077 if (s_cursor_visible)
1078 SetConsoleCursorPosition(g_hConOut, g_coord);
1079}
1080
1081 void
1082mch_update_cursor(void)
1083{
1084 int idx;
1085 int thickness;
1086
1087 /*
1088 * How the cursor is drawn depends on the current mode.
1089 */
1090 idx = get_shape_idx(FALSE);
1091
1092 if (shape_table[idx].shape == SHAPE_BLOCK)
1093 thickness = 99; /* 100 doesn't work on W95 */
1094 else
1095 thickness = shape_table[idx].percentage;
1096 mch_set_cursor_shape(thickness);
1097}
1098#endif
1099
1100#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1101/*
1102 * Handle FOCUS_EVENT.
1103 */
1104 static void
1105handle_focus_event(INPUT_RECORD ir)
1106{
1107 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1108 ui_focus_change((int)g_fJustGotFocus);
1109}
1110
1111/*
1112 * Wait until console input from keyboard or mouse is available,
1113 * or the time is up.
1114 * Return TRUE if something is available FALSE if not.
1115 */
1116 static int
1117WaitForChar(long msec)
1118{
1119 DWORD dwNow = 0, dwEndTime = 0;
1120 INPUT_RECORD ir;
1121 DWORD cRecords;
1122 char_u ch, ch2;
1123
1124 if (msec > 0)
1125 /* Wait until the specified time has elapsed. */
1126 dwEndTime = GetTickCount() + msec;
1127 else if (msec < 0)
1128 /* Wait forever. */
1129 dwEndTime = INFINITE;
1130
1131 /* We need to loop until the end of the time period, because
1132 * we might get multiple unusable mouse events in that time.
1133 */
1134 for (;;)
1135 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001136#ifdef FEAT_MZSCHEME
1137 mzvim_check_threads();
1138#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001139#ifdef FEAT_CLIENTSERVER
1140 serverProcessPendingMessages();
1141#endif
1142 if (0
1143#ifdef FEAT_MOUSE
1144 || g_nMouseClick != -1
1145#endif
1146#ifdef FEAT_CLIENTSERVER
1147 || input_available()
1148#endif
1149 )
1150 return TRUE;
1151
1152 if (msec > 0)
1153 {
1154 /* If the specified wait time has passed, return. */
1155 dwNow = GetTickCount();
1156 if (dwNow >= dwEndTime)
1157 break;
1158 }
1159 if (msec != 0)
1160 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001161 DWORD dwWaitTime = dwEndTime - dwNow;
1162
1163#ifdef FEAT_MZSCHEME
1164 if (mzthreads_allowed() && p_mzq > 0
1165 && (msec < 0 || (long)dwWaitTime > p_mzq))
1166 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1167#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168#ifdef FEAT_CLIENTSERVER
1169 /* Wait for either an event on the console input or a message in
1170 * the client-server window. */
1171 if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001172 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001173#else
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001174 if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001175#endif
1176 continue;
1177 }
1178
1179 cRecords = 0;
1180 PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
1181
1182#ifdef FEAT_MBYTE_IME
1183 if (State & CMDLINE && msg_row == Rows - 1)
1184 {
1185 CONSOLE_SCREEN_BUFFER_INFO csbi;
1186
1187 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1188 {
1189 if (csbi.dwCursorPosition.Y != msg_row)
1190 {
1191 /* The screen is now messed up, must redraw the
1192 * command line and later all the windows. */
1193 redraw_all_later(CLEAR);
1194 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1195 redrawcmd();
1196 }
1197 }
1198 }
1199#endif
1200
1201 if (cRecords > 0)
1202 {
1203 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1204 {
1205#ifdef FEAT_MBYTE_IME
1206 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1207 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
1208 if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
1209 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1210 {
1211 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1212 continue;
1213 }
1214#endif
1215 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1216 NULL, FALSE))
1217 return TRUE;
1218 }
1219
1220 ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
1221
1222 if (ir.EventType == FOCUS_EVENT)
1223 handle_focus_event(ir);
1224 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1225 shell_resized();
1226#ifdef FEAT_MOUSE
1227 else if (ir.EventType == MOUSE_EVENT
1228 && decode_mouse_event(&ir.Event.MouseEvent))
1229 return TRUE;
1230#endif
1231 }
1232 else if (msec == 0)
1233 break;
1234 }
1235
1236#ifdef FEAT_CLIENTSERVER
1237 /* Something might have been received while we were waiting. */
1238 if (input_available())
1239 return TRUE;
1240#endif
1241 return FALSE;
1242}
1243
1244#ifndef FEAT_GUI_MSWIN
1245/*
1246 * return non-zero if a character is available
1247 */
1248 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001249mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001250{
1251 return WaitForChar(0L);
1252}
1253#endif
1254
1255/*
1256 * Create the console input. Used when reading stdin doesn't work.
1257 */
1258 static void
1259create_conin(void)
1260{
1261 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1262 FILE_SHARE_READ|FILE_SHARE_WRITE,
1263 (LPSECURITY_ATTRIBUTES) NULL,
1264 OPEN_EXISTING, (DWORD)NULL, (HANDLE)NULL);
1265 did_create_conin = TRUE;
1266}
1267
1268/*
1269 * Get a keystroke or a mouse event
1270 */
1271 static char_u
1272tgetch(int *pmodifiers, char_u *pch2)
1273{
1274 char_u ch;
1275
1276 for (;;)
1277 {
1278 INPUT_RECORD ir;
1279 DWORD cRecords = 0;
1280
1281#ifdef FEAT_CLIENTSERVER
1282 (void)WaitForChar(-1L);
1283 if (input_available())
1284 return 0;
1285# ifdef FEAT_MOUSE
1286 if (g_nMouseClick != -1)
1287 return 0;
1288# endif
1289#endif
1290 if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
1291 {
1292 if (did_create_conin)
1293 read_error_exit();
1294 create_conin();
1295 continue;
1296 }
1297
1298 if (ir.EventType == KEY_EVENT)
1299 {
1300 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1301 pmodifiers, TRUE))
1302 return ch;
1303 }
1304 else if (ir.EventType == FOCUS_EVENT)
1305 handle_focus_event(ir);
1306 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1307 shell_resized();
1308#ifdef FEAT_MOUSE
1309 else if (ir.EventType == MOUSE_EVENT)
1310 {
1311 if (decode_mouse_event(&ir.Event.MouseEvent))
1312 return 0;
1313 }
1314#endif
1315 }
1316}
1317#endif /* !FEAT_GUI_W32 */
1318
1319
1320/*
1321 * mch_inchar(): low-level input funcion.
1322 * Get one or more characters from the keyboard or the mouse.
1323 * If time == 0, do not wait for characters.
1324 * If time == n, wait a short time for characters.
1325 * If time == -1, wait forever for characters.
1326 * Returns the number of characters read into buf.
1327 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00001328/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329 int
1330mch_inchar(
1331 char_u *buf,
1332 int maxlen,
1333 long time,
1334 int tb_change_cnt)
1335{
1336#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1337
1338 int len;
1339 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001340#define TYPEAHEADLEN 20
1341 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1342 static int typeaheadlen = 0;
1343
1344 /* First use any typeahead that was kept because "buf" was too small. */
1345 if (typeaheadlen > 0)
1346 goto theend;
1347
1348#ifdef FEAT_SNIFF
1349 if (want_sniff_request)
1350 {
1351 if (sniff_request_waiting)
1352 {
1353 /* return K_SNIFF */
1354 typeahead[typeaheadlen++] = CSI;
1355 typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
1356 typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
1357 sniff_request_waiting = 0;
1358 want_sniff_request = 0;
1359 goto theend;
1360 }
1361 else if (time < 0 || time > 250)
1362 {
1363 /* don't wait too long, a request might be pending */
1364 time = 250;
1365 }
1366 }
1367#endif
1368
1369 if (time >= 0)
1370 {
1371 if (!WaitForChar(time)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001373 }
1374 else /* time == -1, wait forever */
1375 {
1376 mch_set_winsize_now(); /* Allow winsize changes from now on */
1377
Bram Moolenaar3918c952005-03-15 22:34:55 +00001378 /*
1379 * If there is no character available within 2 seconds (default)
1380 * write the autoscript file to disk. Or cause the CursorHold event
1381 * to be triggered.
1382 */
1383 if (!WaitForChar(p_ut))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384 {
1385#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001386 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001387 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001388 buf[0] = K_SPECIAL;
1389 buf[1] = KS_EXTRA;
1390 buf[2] = (int)KE_CURSORHOLD;
1391 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001392 }
1393#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001394 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001395 }
1396 }
1397
1398 /*
1399 * Try to read as many characters as there are, until the buffer is full.
1400 */
1401
1402 /* we will get at least one key. Get more if they are available. */
1403 g_fCBrkPressed = FALSE;
1404
1405#ifdef MCH_WRITE_DUMP
1406 if (fdDump)
1407 fputc('[', fdDump);
1408#endif
1409
1410 /* Keep looping until there is something in the typeahead buffer and more
1411 * to get and still room in the buffer (up to two bytes for a char and
1412 * three bytes for a modifier). */
1413 while ((typeaheadlen == 0 || WaitForChar(0L))
1414 && typeaheadlen + 5 <= TYPEAHEADLEN)
1415 {
1416 if (typebuf_changed(tb_change_cnt))
1417 {
1418 /* "buf" may be invalid now if a client put something in the
1419 * typeahead buffer and "buf" is in the typeahead buffer. */
1420 typeaheadlen = 0;
1421 break;
1422 }
1423#ifdef FEAT_MOUSE
1424 if (g_nMouseClick != -1)
1425 {
1426# ifdef MCH_WRITE_DUMP
1427 if (fdDump)
1428 fprintf(fdDump, "{%02x @ %d, %d}",
1429 g_nMouseClick, g_xMouse, g_yMouse);
1430# endif
1431 typeahead[typeaheadlen++] = ESC + 128;
1432 typeahead[typeaheadlen++] = 'M';
1433 typeahead[typeaheadlen++] = g_nMouseClick;
1434 typeahead[typeaheadlen++] = g_xMouse + '!';
1435 typeahead[typeaheadlen++] = g_yMouse + '!';
1436 g_nMouseClick = -1;
1437 }
1438 else
1439#endif
1440 {
1441 char_u ch2 = NUL;
1442 int modifiers = 0;
1443
1444 c = tgetch(&modifiers, &ch2);
1445
1446 if (typebuf_changed(tb_change_cnt))
1447 {
1448 /* "buf" may be invalid now if a client put something in the
1449 * typeahead buffer and "buf" is in the typeahead buffer. */
1450 typeaheadlen = 0;
1451 break;
1452 }
1453
1454 if (c == Ctrl_C && ctrl_c_interrupts)
1455 {
1456#if defined(FEAT_CLIENTSERVER)
1457 trash_input_buf();
1458#endif
1459 got_int = TRUE;
1460 }
1461
1462#ifdef FEAT_MOUSE
1463 if (g_nMouseClick == -1)
1464#endif
1465 {
1466 int n = 1;
1467
1468 /* A key may have one or two bytes. */
1469 typeahead[typeaheadlen] = c;
1470 if (ch2 != NUL)
1471 {
1472 typeahead[typeaheadlen + 1] = ch2;
1473 ++n;
1474 }
1475#ifdef FEAT_MBYTE
1476 /* Only convert normal characters, not special keys. Need to
1477 * convert before applying ALT, otherwise mapping <M-x> breaks
1478 * when 'tenc' is set. */
1479 if (input_conv.vc_type != CONV_NONE
1480 && (ch2 == NUL || c != K_NUL))
1481 n = convert_input(typeahead + typeaheadlen, n,
1482 TYPEAHEADLEN - typeaheadlen);
1483#endif
1484
1485 /* Use the ALT key to set the 8th bit of the character
1486 * when it's one byte, the 8th bit isn't set yet and not
1487 * using a double-byte encoding (would become a lead
1488 * byte). */
1489 if ((modifiers & MOD_MASK_ALT)
1490 && n == 1
1491 && (typeahead[typeaheadlen] & 0x80) == 0
1492#ifdef FEAT_MBYTE
1493 && !enc_dbcs
1494#endif
1495 )
1496 {
1497 typeahead[typeaheadlen] |= 0x80;
1498 modifiers &= ~MOD_MASK_ALT;
1499 }
1500
1501 if (modifiers != 0)
1502 {
1503 /* Prepend modifiers to the character. */
1504 mch_memmove(typeahead + typeaheadlen + 3,
1505 typeahead + typeaheadlen, n);
1506 typeahead[typeaheadlen++] = K_SPECIAL;
1507 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1508 typeahead[typeaheadlen++] = modifiers;
1509 }
1510
1511 typeaheadlen += n;
1512
1513#ifdef MCH_WRITE_DUMP
1514 if (fdDump)
1515 fputc(c, fdDump);
1516#endif
1517 }
1518 }
1519 }
1520
1521#ifdef MCH_WRITE_DUMP
1522 if (fdDump)
1523 {
1524 fputs("]\n", fdDump);
1525 fflush(fdDump);
1526 }
1527#endif
1528
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529theend:
1530 /* Move typeahead to "buf", as much as fits. */
1531 len = 0;
1532 while (len < maxlen && typeaheadlen > 0)
1533 {
1534 buf[len++] = typeahead[0];
1535 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1536 }
1537 return len;
1538
1539#else /* FEAT_GUI_W32 */
1540 return 0;
1541#endif /* FEAT_GUI_W32 */
1542}
1543
1544#ifndef __MINGW32__
1545# include <shellapi.h> /* required for FindExecutable() */
1546#endif
1547
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001548/*
1549 * Return TRUE if "name" is in $PATH.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001550 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001551 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552 static int
1553executable_exists(char *name)
1554{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001555 char *dum;
1556 char fname[_MAX_PATH];
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001558#ifdef FEAT_MBYTE
1559 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 {
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001561 WCHAR *p = enc_to_ucs2(name, NULL);
1562 WCHAR fnamew[_MAX_PATH];
1563 WCHAR *dumw;
1564 long n;
1565
1566 if (p != NULL)
1567 {
1568 n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
1569 vim_free(p);
1570 if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
1571 {
1572 if (n == 0)
1573 return FALSE;
1574 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1575 return FALSE;
1576 return TRUE;
1577 }
1578 /* Retry with non-wide function (for Windows 98). */
1579 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001581#endif
1582 if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
1583 return FALSE;
1584 if (mch_isdir(fname))
1585 return FALSE;
1586 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001587}
1588
1589#ifdef FEAT_GUI_W32
1590
1591/*
1592 * GUI version of mch_init().
1593 */
1594 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001595mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001596{
1597#ifndef __MINGW32__
1598 extern int _fmode;
1599#endif
1600
1601 /* Let critical errors result in a failure, not in a dialog box. Required
1602 * for the timestamp test to work on removed floppies. */
1603 SetErrorMode(SEM_FAILCRITICALERRORS);
1604
1605 _fmode = O_BINARY; /* we do our own CR-LF translation */
1606
1607 /* Specify window size. Is there a place to get the default from? */
1608 Rows = 25;
1609 Columns = 80;
1610
1611 /* Look for 'vimrun' */
1612 if (!gui_is_win32s())
1613 {
1614 char_u vimrun_location[_MAX_PATH + 4];
1615
1616 /* First try in same directory as gvim.exe */
1617 STRCPY(vimrun_location, exe_name);
1618 STRCPY(gettail(vimrun_location), "vimrun.exe");
1619 if (mch_getperm(vimrun_location) >= 0)
1620 {
1621 if (*skiptowhite(vimrun_location) != NUL)
1622 {
1623 /* Enclose path with white space in double quotes. */
1624 mch_memmove(vimrun_location + 1, vimrun_location,
1625 STRLEN(vimrun_location) + 1);
1626 *vimrun_location = '"';
1627 STRCPY(gettail(vimrun_location), "vimrun\" ");
1628 }
1629 else
1630 STRCPY(gettail(vimrun_location), "vimrun ");
1631
1632 vimrun_path = (char *)vim_strsave(vimrun_location);
1633 s_dont_use_vimrun = FALSE;
1634 }
1635 else if (executable_exists("vimrun.exe"))
1636 s_dont_use_vimrun = FALSE;
1637
1638 /* Don't give the warning for a missing vimrun.exe right now, but only
1639 * when vimrun was supposed to be used. Don't bother people that do
1640 * not need vimrun.exe. */
1641 if (s_dont_use_vimrun)
1642 need_vimrun_warning = TRUE;
1643 }
1644
1645 /*
1646 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
1647 * Otherwise the default "findstr /n" is used.
1648 */
1649 if (!executable_exists("findstr.exe"))
1650 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
1651
1652#ifdef FEAT_CLIPBOARD
1653 clip_init(TRUE);
1654
1655 /*
1656 * Vim's own clipboard format recognises whether the text is char, line, or
1657 * rectangular block. Only useful for copying between two Vims.
1658 * "VimClipboard" was used for previous versions, using the first
1659 * character to specify MCHAR, MLINE or MBLOCK.
1660 */
1661 clip_star.format = RegisterClipboardFormat("VimClipboard2");
1662 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
1663#endif
1664}
1665
1666
1667#else /* FEAT_GUI_W32 */
1668
1669#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
1670#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
1671
1672/*
1673 * ClearConsoleBuffer()
1674 * Description:
1675 * Clears the entire contents of the console screen buffer, using the
1676 * specified attribute.
1677 * Returns:
1678 * TRUE on success
1679 */
1680 static BOOL
1681ClearConsoleBuffer(WORD wAttribute)
1682{
1683 CONSOLE_SCREEN_BUFFER_INFO csbi;
1684 COORD coord;
1685 DWORD NumCells, dummy;
1686
1687 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1688 return FALSE;
1689
1690 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
1691 coord.X = 0;
1692 coord.Y = 0;
1693 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
1694 coord, &dummy))
1695 {
1696 return FALSE;
1697 }
1698 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
1699 coord, &dummy))
1700 {
1701 return FALSE;
1702 }
1703
1704 return TRUE;
1705}
1706
1707/*
1708 * FitConsoleWindow()
1709 * Description:
1710 * Checks if the console window will fit within given buffer dimensions.
1711 * Also, if requested, will shrink the window to fit.
1712 * Returns:
1713 * TRUE on success
1714 */
1715 static BOOL
1716FitConsoleWindow(
1717 COORD dwBufferSize,
1718 BOOL WantAdjust)
1719{
1720 CONSOLE_SCREEN_BUFFER_INFO csbi;
1721 COORD dwWindowSize;
1722 BOOL NeedAdjust = FALSE;
1723
1724 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1725 {
1726 /*
1727 * A buffer resize will fail if the current console window does
1728 * not lie completely within that buffer. To avoid this, we might
1729 * have to move and possibly shrink the window.
1730 */
1731 if (csbi.srWindow.Right >= dwBufferSize.X)
1732 {
1733 dwWindowSize.X = SRWIDTH(csbi.srWindow);
1734 if (dwWindowSize.X > dwBufferSize.X)
1735 dwWindowSize.X = dwBufferSize.X;
1736 csbi.srWindow.Right = dwBufferSize.X - 1;
1737 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
1738 NeedAdjust = TRUE;
1739 }
1740 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
1741 {
1742 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
1743 if (dwWindowSize.Y > dwBufferSize.Y)
1744 dwWindowSize.Y = dwBufferSize.Y;
1745 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
1746 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
1747 NeedAdjust = TRUE;
1748 }
1749 if (NeedAdjust && WantAdjust)
1750 {
1751 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
1752 return FALSE;
1753 }
1754 return TRUE;
1755 }
1756
1757 return FALSE;
1758}
1759
1760typedef struct ConsoleBufferStruct
1761{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001762 BOOL IsValid;
1763 CONSOLE_SCREEN_BUFFER_INFO Info;
1764 PCHAR_INFO Buffer;
1765 COORD BufferSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001766} ConsoleBuffer;
1767
1768/*
1769 * SaveConsoleBuffer()
1770 * Description:
1771 * Saves important information about the console buffer, including the
1772 * actual buffer contents. The saved information is suitable for later
1773 * restoration by RestoreConsoleBuffer().
1774 * Returns:
1775 * TRUE if all information was saved; FALSE otherwise
1776 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
1777 */
1778 static BOOL
1779SaveConsoleBuffer(
1780 ConsoleBuffer *cb)
1781{
1782 DWORD NumCells;
1783 COORD BufferCoord;
1784 SMALL_RECT ReadRegion;
1785 WORD Y, Y_incr;
1786
1787 if (cb == NULL)
1788 return FALSE;
1789
1790 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
1791 {
1792 cb->IsValid = FALSE;
1793 return FALSE;
1794 }
1795 cb->IsValid = TRUE;
1796
1797 /*
1798 * Allocate a buffer large enough to hold the entire console screen
1799 * buffer. If this ConsoleBuffer structure has already been initialized
1800 * with a buffer of the correct size, then just use that one.
1801 */
1802 if (!cb->IsValid || cb->Buffer == NULL ||
1803 cb->BufferSize.X != cb->Info.dwSize.X ||
1804 cb->BufferSize.Y != cb->Info.dwSize.Y)
1805 {
1806 cb->BufferSize.X = cb->Info.dwSize.X;
1807 cb->BufferSize.Y = cb->Info.dwSize.Y;
1808 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
1809 if (cb->Buffer != NULL)
1810 vim_free(cb->Buffer);
1811 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
1812 if (cb->Buffer == NULL)
1813 return FALSE;
1814 }
1815
1816 /*
1817 * We will now copy the console screen buffer into our buffer.
1818 * ReadConsoleOutput() seems to be limited as far as how much you
1819 * can read at a time. Empirically, this number seems to be about
1820 * 12000 cells (rows * columns). Start at position (0, 0) and copy
1821 * in chunks until it is all copied. The chunks will all have the
1822 * same horizontal characteristics, so initialize them now. The
1823 * height of each chunk will be (12000 / width).
1824 */
1825 BufferCoord.X = 0;
1826 ReadRegion.Left = 0;
1827 ReadRegion.Right = cb->Info.dwSize.X - 1;
1828 Y_incr = 12000 / cb->Info.dwSize.X;
1829 for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
1830 {
1831 /*
1832 * Read into position (0, Y) in our buffer.
1833 */
1834 BufferCoord.Y = Y;
1835 /*
1836 * Read the region whose top left corner is (0, Y) and whose bottom
1837 * right corner is (width - 1, Y + Y_incr - 1). This should define
1838 * a region of size width by Y_incr. Don't worry if this region is
1839 * too large for the remaining buffer; it will be cropped.
1840 */
1841 ReadRegion.Top = Y;
1842 ReadRegion.Bottom = Y + Y_incr - 1;
1843 if (!ReadConsoleOutput(g_hConOut, /* output handle */
1844 cb->Buffer, /* our buffer */
1845 cb->BufferSize, /* dimensions of our buffer */
1846 BufferCoord, /* offset in our buffer */
1847 &ReadRegion)) /* region to save */
1848 {
1849 vim_free(cb->Buffer);
1850 cb->Buffer = NULL;
1851 return FALSE;
1852 }
1853 }
1854
1855 return TRUE;
1856}
1857
1858/*
1859 * RestoreConsoleBuffer()
1860 * Description:
1861 * Restores important information about the console buffer, including the
1862 * actual buffer contents, if desired. The information to restore is in
1863 * the same format used by SaveConsoleBuffer().
1864 * Returns:
1865 * TRUE on success
1866 */
1867 static BOOL
1868RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001869 ConsoleBuffer *cb,
1870 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871{
1872 COORD BufferCoord;
1873 SMALL_RECT WriteRegion;
1874
1875 if (cb == NULL || !cb->IsValid)
1876 return FALSE;
1877
1878 /*
1879 * Before restoring the buffer contents, clear the current buffer, and
1880 * restore the cursor position and window information. Doing this now
1881 * prevents old buffer contents from "flashing" onto the screen.
1882 */
1883 if (RestoreScreen)
1884 ClearConsoleBuffer(cb->Info.wAttributes);
1885
1886 FitConsoleWindow(cb->Info.dwSize, TRUE);
1887 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
1888 return FALSE;
1889 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
1890 return FALSE;
1891
1892 if (!RestoreScreen)
1893 {
1894 /*
1895 * No need to restore the screen buffer contents, so we're done.
1896 */
1897 return TRUE;
1898 }
1899
1900 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
1901 return FALSE;
1902 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
1903 return FALSE;
1904
1905 /*
1906 * Restore the screen buffer contents.
1907 */
1908 if (cb->Buffer != NULL)
1909 {
1910 BufferCoord.X = 0;
1911 BufferCoord.Y = 0;
1912 WriteRegion.Left = 0;
1913 WriteRegion.Top = 0;
1914 WriteRegion.Right = cb->Info.dwSize.X - 1;
1915 WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
1916 if (!WriteConsoleOutput(g_hConOut, /* output handle */
1917 cb->Buffer, /* our buffer */
1918 cb->BufferSize, /* dimensions of our buffer */
1919 BufferCoord, /* offset in our buffer */
1920 &WriteRegion)) /* region to restore */
1921 {
1922 return FALSE;
1923 }
1924 }
1925
1926 return TRUE;
1927}
1928
Bram Moolenaar362e1a32006-03-06 23:29:24 +00001929#define FEAT_RESTORE_ORIG_SCREEN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001930#ifdef FEAT_RESTORE_ORIG_SCREEN
1931static ConsoleBuffer g_cbOrig = { 0 };
1932#endif
1933static ConsoleBuffer g_cbNonTermcap = { 0 };
1934static ConsoleBuffer g_cbTermcap = { 0 };
1935
1936#ifdef FEAT_TITLE
1937#ifdef __BORLANDC__
1938typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
1939#else
1940typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
1941#endif
1942char g_szOrigTitle[256] = { 0 };
1943HWND g_hWnd = NULL; /* also used in os_mswin.c */
1944static HICON g_hOrigIconSmall = NULL;
1945static HICON g_hOrigIcon = NULL;
1946static HICON g_hVimIcon = NULL;
1947static BOOL g_fCanChangeIcon = FALSE;
1948
1949/* ICON* are not defined in VC++ 4.0 */
1950#ifndef ICON_SMALL
1951#define ICON_SMALL 0
1952#endif
1953#ifndef ICON_BIG
1954#define ICON_BIG 1
1955#endif
1956/*
1957 * GetConsoleIcon()
1958 * Description:
1959 * Attempts to retrieve the small icon and/or the big icon currently in
1960 * use by a given window.
1961 * Returns:
1962 * TRUE on success
1963 */
1964 static BOOL
1965GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001966 HWND hWnd,
1967 HICON *phIconSmall,
1968 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001969{
1970 if (hWnd == NULL)
1971 return FALSE;
1972
1973 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001974 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
1975 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001977 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
1978 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979 return TRUE;
1980}
1981
1982/*
1983 * SetConsoleIcon()
1984 * Description:
1985 * Attempts to change the small icon and/or the big icon currently in
1986 * use by a given window.
1987 * Returns:
1988 * TRUE on success
1989 */
1990 static BOOL
1991SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001992 HWND hWnd,
1993 HICON hIconSmall,
1994 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001995{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001996 HICON hPrevIconSmall;
1997 HICON hPrevIcon;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998
1999 if (hWnd == NULL)
2000 return FALSE;
2001
2002 if (hIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002003 hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
2004 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005 if (hIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002006 hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
2007 (WPARAM)ICON_BIG,(LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 return TRUE;
2009}
2010
2011/*
2012 * SaveConsoleTitleAndIcon()
2013 * Description:
2014 * Saves the current console window title in g_szOrigTitle, for later
2015 * restoration. Also, attempts to obtain a handle to the console window,
2016 * and use it to save the small and big icons currently in use by the
2017 * console window. This is not always possible on some versions of Windows;
2018 * nor is it possible when running Vim remotely using Telnet (since the
2019 * console window the user sees is owned by a remote process).
2020 */
2021 static void
2022SaveConsoleTitleAndIcon(void)
2023{
2024 GETCONSOLEWINDOWPROC GetConsoleWindowProc;
2025
2026 /* Save the original title. */
2027 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2028 return;
2029
2030 /*
2031 * Obtain a handle to the console window using GetConsoleWindow() from
2032 * KERNEL32.DLL; we need to handle in order to change the window icon.
2033 * This function only exists on NT-based Windows, starting with Windows
2034 * 2000. On older operating systems, we can't change the window icon
2035 * anyway.
2036 */
2037 if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
2038 GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
2039 "GetConsoleWindow")) != NULL)
2040 {
2041 g_hWnd = (*GetConsoleWindowProc)();
2042 }
2043 if (g_hWnd == NULL)
2044 return;
2045
2046 /* Save the original console window icon. */
2047 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2048 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2049 return;
2050
2051 /* Extract the first icon contained in the Vim executable. */
2052 g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
2053 if (g_hVimIcon != NULL)
2054 g_fCanChangeIcon = TRUE;
2055}
2056#endif
2057
2058static int g_fWindInitCalled = FALSE;
2059static int g_fTermcapMode = FALSE;
2060static CONSOLE_CURSOR_INFO g_cci;
2061static DWORD g_cmodein = 0;
2062static DWORD g_cmodeout = 0;
2063
2064/*
2065 * non-GUI version of mch_init().
2066 */
2067 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002068mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069{
2070#ifndef FEAT_RESTORE_ORIG_SCREEN
2071 CONSOLE_SCREEN_BUFFER_INFO csbi;
2072#endif
2073#ifndef __MINGW32__
2074 extern int _fmode;
2075#endif
2076
2077 /* Let critical errors result in a failure, not in a dialog box. Required
2078 * for the timestamp test to work on removed floppies. */
2079 SetErrorMode(SEM_FAILCRITICALERRORS);
2080
2081 _fmode = O_BINARY; /* we do our own CR-LF translation */
2082 out_flush();
2083
2084 /* Obtain handles for the standard Console I/O devices */
2085 if (read_cmd_fd == 0)
2086 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2087 else
2088 create_conin();
2089 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2090
2091#ifdef FEAT_RESTORE_ORIG_SCREEN
2092 /* Save the initial console buffer for later restoration */
2093 SaveConsoleBuffer(&g_cbOrig);
2094 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2095#else
2096 /* Get current text attributes */
2097 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2098 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2099#endif
2100 if (cterm_normal_fg_color == 0)
2101 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2102 if (cterm_normal_bg_color == 0)
2103 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2104
2105 /* set termcap codes to current text attributes */
2106 update_tcap(g_attrCurrent);
2107
2108 GetConsoleCursorInfo(g_hConOut, &g_cci);
2109 GetConsoleMode(g_hConIn, &g_cmodein);
2110 GetConsoleMode(g_hConOut, &g_cmodeout);
2111
2112#ifdef FEAT_TITLE
2113 SaveConsoleTitleAndIcon();
2114 /*
2115 * Set both the small and big icons of the console window to Vim's icon.
2116 * Note that Vim presently only has one size of icon (32x32), but it
2117 * automatically gets scaled down to 16x16 when setting the small icon.
2118 */
2119 if (g_fCanChangeIcon)
2120 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2121#endif
2122
2123 ui_get_shellsize();
2124
2125#ifdef MCH_WRITE_DUMP
2126 fdDump = fopen("dump", "wt");
2127
2128 if (fdDump)
2129 {
2130 time_t t;
2131
2132 time(&t);
2133 fputs(ctime(&t), fdDump);
2134 fflush(fdDump);
2135 }
2136#endif
2137
2138 g_fWindInitCalled = TRUE;
2139
2140#ifdef FEAT_MOUSE
2141 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2142#endif
2143
2144#ifdef FEAT_CLIPBOARD
2145 clip_init(TRUE);
2146
2147 /*
2148 * Vim's own clipboard format recognises whether the text is char, line, or
2149 * rectangular block. Only useful for copying between two Vims.
2150 * "VimClipboard" was used for previous versions, using the first
2151 * character to specify MCHAR, MLINE or MBLOCK.
2152 */
2153 clip_star.format = RegisterClipboardFormat("VimClipboard2");
2154 clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
2155#endif
2156
2157 /* This will be NULL on anything but NT 4.0 */
2158 s_pfnGetConsoleKeyboardLayoutName =
2159 (PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
2160 "GetConsoleKeyboardLayoutNameA");
2161}
2162
2163/*
2164 * non-GUI version of mch_exit().
2165 * Shut down and exit with status `r'
2166 * Careful: mch_exit() may be called before mch_init()!
2167 */
2168 void
2169mch_exit(int r)
2170{
2171 stoptermcap();
2172
2173 if (g_fWindInitCalled)
2174 settmode(TMODE_COOK);
2175
2176 ml_close_all(TRUE); /* remove all memfiles */
2177
2178 if (g_fWindInitCalled)
2179 {
2180#ifdef FEAT_TITLE
2181 mch_restore_title(3);
2182 /*
2183 * Restore both the small and big icons of the console window to
2184 * what they were at startup. Don't do this when the window is
2185 * closed, Vim would hang here.
2186 */
2187 if (g_fCanChangeIcon && !g_fForceExit)
2188 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2189#endif
2190
2191#ifdef MCH_WRITE_DUMP
2192 if (fdDump)
2193 {
2194 time_t t;
2195
2196 time(&t);
2197 fputs(ctime(&t), fdDump);
2198 fclose(fdDump);
2199 }
2200 fdDump = NULL;
2201#endif
2202 }
2203
2204 SetConsoleCursorInfo(g_hConOut, &g_cci);
2205 SetConsoleMode(g_hConIn, g_cmodein);
2206 SetConsoleMode(g_hConOut, g_cmodeout);
2207
2208#ifdef DYNAMIC_GETTEXT
2209 dyn_libintl_end();
2210#endif
2211
2212 exit(r);
2213}
2214#endif /* !FEAT_GUI_W32 */
2215
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216/*
2217 * Do we have an interactive window?
2218 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002219/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002220 int
2221mch_check_win(
2222 int argc,
2223 char **argv)
2224{
2225 get_exe_name();
2226
2227#ifdef FEAT_GUI_W32
2228 return OK; /* GUI always has a tty */
2229#else
2230 if (isatty(1))
2231 return OK;
2232 return FAIL;
2233#endif
2234}
2235
2236
2237/*
2238 * fname_case(): Set the case of the file name, if it already exists.
2239 * When "len" is > 0, also expand short to long filenames.
2240 */
2241 void
2242fname_case(
2243 char_u *name,
2244 int len)
2245{
2246 char szTrueName[_MAX_PATH + 2];
2247 char *ptrue, *ptruePrev;
2248 char *porig, *porigPrev;
2249 int flen;
2250 WIN32_FIND_DATA fb;
2251 HANDLE hFind;
2252 int c;
2253
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002254 flen = (int)STRLEN(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255 if (flen == 0 || flen > _MAX_PATH)
2256 return;
2257
2258 slash_adjust(name);
2259
2260 /* Build the new name in szTrueName[] one component at a time. */
2261 porig = name;
2262 ptrue = szTrueName;
2263
2264 if (isalpha(porig[0]) && porig[1] == ':')
2265 {
2266 /* copy leading drive letter */
2267 *ptrue++ = *porig++;
2268 *ptrue++ = *porig++;
2269 *ptrue = NUL; /* in case nothing follows */
2270 }
2271
2272 while (*porig != NUL)
2273 {
2274 /* copy \ characters */
2275 while (*porig == psepc)
2276 *ptrue++ = *porig++;
2277
2278 ptruePrev = ptrue;
2279 porigPrev = porig;
2280 while (*porig != NUL && *porig != psepc)
2281 {
2282#ifdef FEAT_MBYTE
2283 int l;
2284
2285 if (enc_dbcs)
2286 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00002287 l = (*mb_ptr2len)(porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002288 while (--l >= 0)
2289 *ptrue++ = *porig++;
2290 }
2291 else
2292#endif
2293 *ptrue++ = *porig++;
2294 }
2295 *ptrue = NUL;
2296
2297 /* Skip "", "." and "..". */
2298 if (ptrue > ptruePrev
2299 && (ptruePrev[0] != '.'
2300 || (ptruePrev[1] != NUL
2301 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
2302 && (hFind = FindFirstFile(szTrueName, &fb))
2303 != INVALID_HANDLE_VALUE)
2304 {
2305 c = *porig;
2306 *porig = NUL;
2307
2308 /* Only use the match when it's the same name (ignoring case) or
2309 * expansion is allowed and there is a match with the short name
2310 * and there is enough room. */
2311 if (_stricoll(porigPrev, fb.cFileName) == 0
2312 || (len > 0
2313 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2314 && (int)(ptruePrev - szTrueName)
2315 + (int)strlen(fb.cFileName) < len)))
2316 {
2317 STRCPY(ptruePrev, fb.cFileName);
2318
2319 /* Look for exact match and prefer it if found. Must be a
2320 * long name, otherwise there would be only one match. */
2321 while (FindNextFile(hFind, &fb))
2322 {
2323 if (*fb.cAlternateFileName != NUL
2324 && (strcoll(porigPrev, fb.cFileName) == 0
2325 || (len > 0
2326 && (_stricoll(porigPrev,
2327 fb.cAlternateFileName) == 0
2328 && (int)(ptruePrev - szTrueName)
2329 + (int)strlen(fb.cFileName) < len))))
2330 {
2331 STRCPY(ptruePrev, fb.cFileName);
2332 break;
2333 }
2334 }
2335 }
2336 FindClose(hFind);
2337 *porig = c;
2338 ptrue = ptruePrev + strlen(ptruePrev);
2339 }
2340 }
2341
2342 STRCPY(name, szTrueName);
2343}
2344
2345
2346/*
2347 * Insert user name in s[len].
2348 */
2349 int
2350mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002351 char_u *s,
2352 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353{
2354 char szUserName[MAX_COMPUTERNAME_LENGTH + 1];
2355 DWORD cch = sizeof szUserName;
2356
2357 if (GetUserName(szUserName, &cch))
2358 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002359 vim_strncpy(s, szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002360 return OK;
2361 }
2362 s[0] = NUL;
2363 return FAIL;
2364}
2365
2366
2367/*
2368 * Insert host name in s[len].
2369 */
2370 void
2371mch_get_host_name(
2372 char_u *s,
2373 int len)
2374{
2375 DWORD cch = len;
2376
2377 if (!GetComputerName(s, &cch))
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002378 vim_strncpy(s, "PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379}
2380
2381
2382/*
2383 * return process ID
2384 */
2385 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002386mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002387{
2388 return (long)GetCurrentProcessId();
2389}
2390
2391
2392/*
2393 * Get name of current directory into buffer 'buf' of length 'len' bytes.
2394 * Return OK for success, FAIL for failure.
2395 */
2396 int
2397mch_dirname(
2398 char_u *buf,
2399 int len)
2400{
2401 /*
2402 * Originally this was:
2403 * return (getcwd(buf, len) != NULL ? OK : FAIL);
2404 * But the Win32s known bug list says that getcwd() doesn't work
2405 * so use the Win32 system call instead. <Negri>
2406 */
2407#ifdef FEAT_MBYTE
2408 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2409 {
2410 WCHAR wbuf[_MAX_PATH + 1];
2411
2412 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
2413 {
2414 char_u *p = ucs2_to_enc(wbuf, NULL);
2415
2416 if (p != NULL)
2417 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002418 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002419 vim_free(p);
2420 return OK;
2421 }
2422 }
2423 /* Retry with non-wide function (for Windows 98). */
2424 }
2425#endif
2426 return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
2427}
2428
2429/*
2430 * get file permissions for `name'
2431 * -1 : error
2432 * else FILE_ATTRIBUTE_* defined in winnt.h
2433 */
2434 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002435mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436{
2437#ifdef FEAT_MBYTE
2438 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2439 {
2440 WCHAR *p = enc_to_ucs2(name, NULL);
2441 long n;
2442
2443 if (p != NULL)
2444 {
2445 n = (long)GetFileAttributesW(p);
2446 vim_free(p);
2447 if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2448 return n;
2449 /* Retry with non-wide function (for Windows 98). */
2450 }
2451 }
2452#endif
2453 return (long)GetFileAttributes((char *)name);
2454}
2455
2456
2457/*
2458 * set file permission for `name' to `perm'
2459 */
2460 int
2461mch_setperm(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002462 char_u *name,
2463 long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464{
2465 perm |= FILE_ATTRIBUTE_ARCHIVE; /* file has changed, set archive bit */
2466#ifdef FEAT_MBYTE
2467 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2468 {
2469 WCHAR *p = enc_to_ucs2(name, NULL);
2470 long n;
2471
2472 if (p != NULL)
2473 {
2474 n = (long)SetFileAttributesW(p, perm);
2475 vim_free(p);
2476 if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
2477 return n ? OK : FAIL;
2478 /* Retry with non-wide function (for Windows 98). */
2479 }
2480 }
2481#endif
2482 return SetFileAttributes((char *)name, perm) ? OK : FAIL;
2483}
2484
2485/*
2486 * Set hidden flag for "name".
2487 */
2488 void
2489mch_hide(char_u *name)
2490{
2491 int perm;
2492#ifdef FEAT_MBYTE
2493 WCHAR *p = NULL;
2494
2495 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2496 p = enc_to_ucs2(name, NULL);
2497#endif
2498
2499#ifdef FEAT_MBYTE
2500 if (p != NULL)
2501 {
2502 perm = GetFileAttributesW(p);
2503 if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2504 {
2505 /* Retry with non-wide function (for Windows 98). */
2506 vim_free(p);
2507 p = NULL;
2508 }
2509 }
2510 if (p == NULL)
2511#endif
2512 perm = GetFileAttributes((char *)name);
2513 if (perm >= 0)
2514 {
2515 perm |= FILE_ATTRIBUTE_HIDDEN;
2516#ifdef FEAT_MBYTE
2517 if (p != NULL)
2518 {
2519 if (SetFileAttributesW(p, perm) == 0
2520 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2521 {
2522 /* Retry with non-wide function (for Windows 98). */
2523 vim_free(p);
2524 p = NULL;
2525 }
2526 }
2527 if (p == NULL)
2528#endif
2529 SetFileAttributes((char *)name, perm);
2530 }
2531#ifdef FEAT_MBYTE
2532 vim_free(p);
2533#endif
2534}
2535
2536/*
2537 * return TRUE if "name" is a directory
2538 * return FALSE if "name" is not a directory or upon error
2539 */
2540 int
2541mch_isdir(char_u *name)
2542{
2543 int f = mch_getperm(name);
2544
2545 if (f == -1)
2546 return FALSE; /* file does not exist at all */
2547
2548 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
2549}
2550
2551/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00002552 * Return TRUE if file "fname" has more than one link.
2553 */
2554 int
2555mch_is_linked(char_u *fname)
2556{
2557 HANDLE hFile;
2558 int res = 0;
2559 BY_HANDLE_FILE_INFORMATION inf;
2560#ifdef FEAT_MBYTE
2561 WCHAR *wn = NULL;
2562
2563 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2564 wn = enc_to_ucs2(fname, NULL);
2565 if (wn != NULL)
2566 {
2567 hFile = CreateFileW(wn, /* file name */
2568 GENERIC_READ, /* access mode */
2569 0, /* share mode */
2570 NULL, /* security descriptor */
2571 OPEN_EXISTING, /* creation disposition */
2572 0, /* file attributes */
2573 NULL); /* handle to template file */
2574 if (hFile == INVALID_HANDLE_VALUE
2575 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
2576 {
2577 /* Retry with non-wide function (for Windows 98). */
2578 vim_free(wn);
2579 wn = NULL;
2580 }
2581 }
2582 if (wn == NULL)
2583#endif
2584 hFile = CreateFile(fname, /* file name */
2585 GENERIC_READ, /* access mode */
2586 0, /* share mode */
2587 NULL, /* security descriptor */
2588 OPEN_EXISTING, /* creation disposition */
2589 0, /* file attributes */
2590 NULL); /* handle to template file */
2591
2592 if (hFile != INVALID_HANDLE_VALUE)
2593 {
2594 if (GetFileInformationByHandle(hFile, &inf) != 0
2595 && inf.nNumberOfLinks > 1)
2596 res = 1;
2597 CloseHandle(hFile);
2598 }
2599
2600#ifdef FEAT_MBYTE
2601 vim_free(wn);
2602#endif
2603 return res;
2604}
2605
2606/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002607 * Return TRUE if file or directory "name" is writable (not readonly).
2608 * Strange semantics of Win32: a readonly directory is writable, but you can't
2609 * delete a file. Let's say this means it is writable.
2610 */
2611 int
2612mch_writable(char_u *name)
2613{
2614 int perm = mch_getperm(name);
2615
2616 return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
2617 || (perm & FILE_ATTRIBUTE_DIRECTORY)));
2618}
2619
Bram Moolenaar071d4272004-06-13 20:20:40 +00002620/*
2621 * Return 1 if "name" can be executed, 0 if not.
2622 * Return -1 if unknown.
2623 */
2624 int
2625mch_can_exe(char_u *name)
2626{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002627 char_u buf[_MAX_PATH];
2628 int len = STRLEN(name);
2629 char_u *p;
2630
2631 if (len >= _MAX_PATH) /* safety check */
2632 return FALSE;
2633
2634 /* If there already is an extension try using the name directly. Also do
2635 * this with a Unix-shell like 'shell'. */
2636 if (vim_strchr(gettail(name), '.') != NULL
2637 || strstr((char *)gettail(p_sh), "sh") != NULL)
2638 if (executable_exists((char *)name))
2639 return TRUE;
2640
2641 /*
2642 * Loop over all extensions in $PATHEXT.
2643 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00002644 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00002645 p = mch_getenv("PATHEXT");
2646 if (p == NULL)
2647 p = (char_u *)".com;.exe;.bat;.cmd";
2648 while (*p)
2649 {
2650 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
2651 {
2652 /* A single "." means no extension is added. */
2653 buf[len] = NUL;
2654 ++p;
2655 if (*p)
2656 ++p;
2657 }
2658 else
2659 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
2660 if (executable_exists((char *)buf))
2661 return TRUE;
2662 }
2663 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002664}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002665
2666/*
2667 * Check what "name" is:
2668 * NODE_NORMAL: file or directory (or doesn't exist)
2669 * NODE_WRITABLE: writable device, socket, fifo, etc.
2670 * NODE_OTHER: non-writable things
2671 */
2672 int
2673mch_nodetype(char_u *name)
2674{
2675 HANDLE hFile;
2676 int type;
2677
2678 hFile = CreateFile(name, /* file name */
2679 GENERIC_WRITE, /* access mode */
2680 0, /* share mode */
2681 NULL, /* security descriptor */
2682 OPEN_EXISTING, /* creation disposition */
2683 0, /* file attributes */
2684 NULL); /* handle to template file */
2685
2686 if (hFile == INVALID_HANDLE_VALUE)
2687 return NODE_NORMAL;
2688
2689 type = GetFileType(hFile);
2690 CloseHandle(hFile);
2691 if (type == FILE_TYPE_CHAR)
2692 return NODE_WRITABLE;
2693 if (type == FILE_TYPE_DISK)
2694 return NODE_NORMAL;
2695 return NODE_OTHER;
2696}
2697
2698#ifdef HAVE_ACL
2699struct my_acl
2700{
2701 PSECURITY_DESCRIPTOR pSecurityDescriptor;
2702 PSID pSidOwner;
2703 PSID pSidGroup;
2704 PACL pDacl;
2705 PACL pSacl;
2706};
2707#endif
2708
2709/*
2710 * Return a pointer to the ACL of file "fname" in allocated memory.
2711 * Return NULL if the ACL is not available for whatever reason.
2712 */
2713 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002714mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002715{
2716#ifndef HAVE_ACL
2717 return (vim_acl_T)NULL;
2718#else
2719 struct my_acl *p = NULL;
2720
2721 /* This only works on Windows NT and 2000. */
2722 if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
2723 {
2724 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
2725 if (p != NULL)
2726 {
2727 if (pGetNamedSecurityInfo(
2728 (LPTSTR)fname, // Abstract filename
2729 SE_FILE_OBJECT, // File Object
2730 // Retrieve the entire security descriptor.
2731 OWNER_SECURITY_INFORMATION |
2732 GROUP_SECURITY_INFORMATION |
2733 DACL_SECURITY_INFORMATION |
2734 SACL_SECURITY_INFORMATION,
2735 &p->pSidOwner, // Ownership information.
2736 &p->pSidGroup, // Group membership.
2737 &p->pDacl, // Discretionary information.
2738 &p->pSacl, // For auditing purposes.
2739 &p->pSecurityDescriptor
2740 ) != ERROR_SUCCESS)
2741 {
2742 mch_free_acl((vim_acl_T)p);
2743 p = NULL;
2744 }
2745 }
2746 }
2747
2748 return (vim_acl_T)p;
2749#endif
2750}
2751
2752/*
2753 * Set the ACL of file "fname" to "acl" (unless it's NULL).
2754 * Errors are ignored.
2755 * This must only be called with "acl" equal to what mch_get_acl() returned.
2756 */
2757 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002758mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002759{
2760#ifdef HAVE_ACL
2761 struct my_acl *p = (struct my_acl *)acl;
2762
2763 if (p != NULL && advapi_lib != NULL)
2764 (void)pSetNamedSecurityInfo(
2765 (LPTSTR)fname, // Abstract filename
2766 SE_FILE_OBJECT, // File Object
2767 // Retrieve the entire security descriptor.
2768 OWNER_SECURITY_INFORMATION |
2769 GROUP_SECURITY_INFORMATION |
2770 DACL_SECURITY_INFORMATION |
2771 SACL_SECURITY_INFORMATION,
2772 p->pSidOwner, // Ownership information.
2773 p->pSidGroup, // Group membership.
2774 p->pDacl, // Discretionary information.
2775 p->pSacl // For auditing purposes.
2776 );
2777#endif
2778}
2779
2780 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002781mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782{
2783#ifdef HAVE_ACL
2784 struct my_acl *p = (struct my_acl *)acl;
2785
2786 if (p != NULL)
2787 {
2788 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
2789 vim_free(p);
2790 }
2791#endif
2792}
2793
2794#ifndef FEAT_GUI_W32
2795
2796/*
2797 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
2798 */
2799 static BOOL WINAPI
2800handler_routine(
2801 DWORD dwCtrlType)
2802{
2803 switch (dwCtrlType)
2804 {
2805 case CTRL_C_EVENT:
2806 if (ctrl_c_interrupts)
2807 g_fCtrlCPressed = TRUE;
2808 return TRUE;
2809
2810 case CTRL_BREAK_EVENT:
2811 g_fCBrkPressed = TRUE;
2812 return TRUE;
2813
2814 /* fatal events: shut down gracefully */
2815 case CTRL_CLOSE_EVENT:
2816 case CTRL_LOGOFF_EVENT:
2817 case CTRL_SHUTDOWN_EVENT:
2818 windgoto((int)Rows - 1, 0);
2819 g_fForceExit = TRUE;
2820
2821 sprintf((char *)IObuff, _("Vim: Caught %s event\n"),
2822 (dwCtrlType == CTRL_CLOSE_EVENT
2823 ? _("close")
2824 : dwCtrlType == CTRL_LOGOFF_EVENT
2825 ? _("logoff")
2826 : _("shutdown")));
2827#ifdef DEBUG
2828 OutputDebugString(IObuff);
2829#endif
2830
2831 preserve_exit(); /* output IObuff, preserve files and exit */
2832
2833 return TRUE; /* not reached */
2834
2835 default:
2836 return FALSE;
2837 }
2838}
2839
2840
2841/*
2842 * set the tty in (raw) ? "raw" : "cooked" mode
2843 */
2844 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002845mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846{
2847 DWORD cmodein;
2848 DWORD cmodeout;
2849 BOOL bEnableHandler;
2850
2851 GetConsoleMode(g_hConIn, &cmodein);
2852 GetConsoleMode(g_hConOut, &cmodeout);
2853 if (tmode == TMODE_RAW)
2854 {
2855 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2856 ENABLE_ECHO_INPUT);
2857#ifdef FEAT_MOUSE
2858 if (g_fMouseActive)
2859 cmodein |= ENABLE_MOUSE_INPUT;
2860#endif
2861 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2862 bEnableHandler = TRUE;
2863 }
2864 else /* cooked */
2865 {
2866 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
2867 ENABLE_ECHO_INPUT);
2868 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
2869 bEnableHandler = FALSE;
2870 }
2871 SetConsoleMode(g_hConIn, cmodein);
2872 SetConsoleMode(g_hConOut, cmodeout);
2873 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
2874
2875#ifdef MCH_WRITE_DUMP
2876 if (fdDump)
2877 {
2878 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
2879 tmode == TMODE_RAW ? "raw" :
2880 tmode == TMODE_COOK ? "cooked" : "normal",
2881 cmodein, cmodeout);
2882 fflush(fdDump);
2883 }
2884#endif
2885}
2886
2887
2888/*
2889 * Get the size of the current window in `Rows' and `Columns'
2890 * Return OK when size could be determined, FAIL otherwise.
2891 */
2892 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002893mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002894{
2895 CONSOLE_SCREEN_BUFFER_INFO csbi;
2896
2897 if (!g_fTermcapMode && g_cbTermcap.IsValid)
2898 {
2899 /*
2900 * For some reason, we are trying to get the screen dimensions
2901 * even though we are not in termcap mode. The 'Rows' and 'Columns'
2902 * variables are really intended to mean the size of Vim screen
2903 * while in termcap mode.
2904 */
2905 Rows = g_cbTermcap.Info.dwSize.Y;
2906 Columns = g_cbTermcap.Info.dwSize.X;
2907 }
2908 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2909 {
2910 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2911 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2912 }
2913 else
2914 {
2915 Rows = 25;
2916 Columns = 80;
2917 }
2918 return OK;
2919}
2920
2921/*
2922 * Set a console window to `xSize' * `ySize'
2923 */
2924 static void
2925ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002926 HANDLE hConsole,
2927 int xSize,
2928 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929{
2930 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
2931 SMALL_RECT srWindowRect; /* hold the new console size */
2932 COORD coordScreen;
2933
2934#ifdef MCH_WRITE_DUMP
2935 if (fdDump)
2936 {
2937 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
2938 fflush(fdDump);
2939 }
2940#endif
2941
2942 /* get the largest size we can size the console window to */
2943 coordScreen = GetLargestConsoleWindowSize(hConsole);
2944
2945 /* define the new console window size and scroll position */
2946 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
2947 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
2948 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
2949
2950 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2951 {
2952 int sx, sy;
2953
2954 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
2955 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
2956 if (sy < ySize || sx < xSize)
2957 {
2958 /*
2959 * Increasing number of lines/columns, do buffer first.
2960 * Use the maximal size in x and y direction.
2961 */
2962 if (sy < ySize)
2963 coordScreen.Y = ySize;
2964 else
2965 coordScreen.Y = sy;
2966 if (sx < xSize)
2967 coordScreen.X = xSize;
2968 else
2969 coordScreen.X = sx;
2970 SetConsoleScreenBufferSize(hConsole, coordScreen);
2971 }
2972 }
2973
2974 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
2975 {
2976#ifdef MCH_WRITE_DUMP
2977 if (fdDump)
2978 {
2979 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
2980 GetLastError());
2981 fflush(fdDump);
2982 }
2983#endif
2984 }
2985
2986 /* define the new console buffer size */
2987 coordScreen.X = xSize;
2988 coordScreen.Y = ySize;
2989
2990 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
2991 {
2992#ifdef MCH_WRITE_DUMP
2993 if (fdDump)
2994 {
2995 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
2996 GetLastError());
2997 fflush(fdDump);
2998 }
2999#endif
3000 }
3001}
3002
3003
3004/*
3005 * Set the console window to `Rows' * `Columns'
3006 */
3007 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003008mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003009{
3010 COORD coordScreen;
3011
3012 /* Don't change window size while still starting up */
3013 if (suppress_winsize != 0)
3014 {
3015 suppress_winsize = 2;
3016 return;
3017 }
3018
3019 if (term_console)
3020 {
3021 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3022
3023 /* Clamp Rows and Columns to reasonable values */
3024 if (Rows > coordScreen.Y)
3025 Rows = coordScreen.Y;
3026 if (Columns > coordScreen.X)
3027 Columns = coordScreen.X;
3028
3029 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3030 }
3031}
3032
3033/*
3034 * Rows and/or Columns has changed.
3035 */
3036 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003037mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003038{
3039 set_scroll_region(0, 0, Columns - 1, Rows - 1);
3040}
3041
3042
3043/*
3044 * Called when started up, to set the winsize that was delayed.
3045 */
3046 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003047mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048{
3049 if (suppress_winsize == 2)
3050 {
3051 suppress_winsize = 0;
3052 mch_set_shellsize();
3053 shell_resized();
3054 }
3055 suppress_winsize = 0;
3056}
3057#endif /* FEAT_GUI_W32 */
3058
3059
3060
3061#if defined(FEAT_GUI_W32) || defined(PROTO)
3062
3063/*
3064 * Specialised version of system() for Win32 GUI mode.
3065 * This version proceeds as follows:
3066 * 1. Create a console window for use by the subprocess
3067 * 2. Run the subprocess (it gets the allocated console by default)
3068 * 3. Wait for the subprocess to terminate and get its exit code
3069 * 4. Prompt the user to press a key to close the console window
3070 */
3071 static int
3072mch_system(char *cmd, int options)
3073{
3074 STARTUPINFO si;
3075 PROCESS_INFORMATION pi;
3076 DWORD ret = 0;
3077 HWND hwnd = GetFocus();
3078
3079 si.cb = sizeof(si);
3080 si.lpReserved = NULL;
3081 si.lpDesktop = NULL;
3082 si.lpTitle = NULL;
3083 si.dwFlags = STARTF_USESHOWWINDOW;
3084 /*
3085 * It's nicer to run a filter command in a minimized window, but in
3086 * Windows 95 this makes the command MUCH slower. We can't do it under
3087 * Win32s either as it stops the synchronous spawn workaround working.
3088 */
3089 if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
3090 si.wShowWindow = SW_SHOWMINIMIZED;
3091 else
3092 si.wShowWindow = SW_SHOWNORMAL;
3093 si.cbReserved2 = 0;
3094 si.lpReserved2 = NULL;
3095
3096 /* There is a strange error on Windows 95 when using "c:\\command.com".
3097 * When the "c:\\" is left out it works OK...? */
3098 if (mch_windows95()
3099 && (STRNICMP(cmd, "c:/command.com", 14) == 0
3100 || STRNICMP(cmd, "c:\\command.com", 14) == 0))
3101 cmd += 3;
3102
3103 /* Now, run the command */
3104 CreateProcess(NULL, /* Executable name */
3105 cmd, /* Command to execute */
3106 NULL, /* Process security attributes */
3107 NULL, /* Thread security attributes */
3108 FALSE, /* Inherit handles */
3109 CREATE_DEFAULT_ERROR_MODE | /* Creation flags */
3110 CREATE_NEW_CONSOLE,
3111 NULL, /* Environment */
3112 NULL, /* Current directory */
3113 &si, /* Startup information */
3114 &pi); /* Process information */
3115
3116
3117 /* Wait for the command to terminate before continuing */
3118 if (g_PlatformId != VER_PLATFORM_WIN32s)
3119 {
3120#ifdef FEAT_GUI
3121 int delay = 1;
3122
3123 /* Keep updating the window while waiting for the shell to finish. */
3124 for (;;)
3125 {
3126 MSG msg;
3127
3128 if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
3129 {
3130 TranslateMessage(&msg);
3131 DispatchMessage(&msg);
3132 }
3133 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
3134 break;
3135
3136 /* We start waiting for a very short time and then increase it, so
3137 * that we respond quickly when the process is quick, and don't
3138 * consume too much overhead when it's slow. */
3139 if (delay < 50)
3140 delay += 10;
3141 }
3142#else
3143 WaitForSingleObject(pi.hProcess, INFINITE);
3144#endif
3145
3146 /* Get the command exit code */
3147 GetExitCodeProcess(pi.hProcess, &ret);
3148 }
3149 else
3150 {
3151 /*
3152 * This ugly code is the only quick way of performing
3153 * a synchronous spawn under Win32s. Yuk.
3154 */
3155 num_windows = 0;
3156 EnumWindows(win32ssynch_cb, 0);
3157 old_num_windows = num_windows;
3158 do
3159 {
3160 Sleep(1000);
3161 num_windows = 0;
3162 EnumWindows(win32ssynch_cb, 0);
3163 } while (num_windows == old_num_windows);
3164 ret = 0;
3165 }
3166
3167 /* Close the handles to the subprocess, so that it goes away */
3168 CloseHandle(pi.hThread);
3169 CloseHandle(pi.hProcess);
3170
3171 /* Try to get input focus back. Doesn't always work though. */
3172 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
3173
3174 return ret;
3175}
3176#else
3177
3178# define mch_system(c, o) system(c)
3179
3180#endif
3181
3182/*
3183 * Either execute a command by calling the shell or start a new shell
3184 */
3185 int
3186mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003187 char_u *cmd,
3188 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003189{
3190 int x = 0;
3191 int tmode = cur_tmode;
3192#ifdef FEAT_TITLE
3193 char szShellTitle[512];
3194
3195 /* Change the title to reflect that we are in a subshell. */
3196 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
3197 {
3198 if (cmd == NULL)
3199 strcat(szShellTitle, " :sh");
3200 else
3201 {
3202 strcat(szShellTitle, " - !");
3203 if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
3204 strcat(szShellTitle, cmd);
3205 }
3206 mch_settitle(szShellTitle, NULL);
3207 }
3208#endif
3209
3210 out_flush();
3211
3212#ifdef MCH_WRITE_DUMP
3213 if (fdDump)
3214 {
3215 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
3216 fflush(fdDump);
3217 }
3218#endif
3219
3220 /*
3221 * Catch all deadly signals while running the external command, because a
3222 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
3223 */
3224 signal(SIGINT, SIG_IGN);
3225#if defined(__GNUC__) && !defined(__MINGW32__)
3226 signal(SIGKILL, SIG_IGN);
3227#else
3228 signal(SIGBREAK, SIG_IGN);
3229#endif
3230 signal(SIGILL, SIG_IGN);
3231 signal(SIGFPE, SIG_IGN);
3232 signal(SIGSEGV, SIG_IGN);
3233 signal(SIGTERM, SIG_IGN);
3234 signal(SIGABRT, SIG_IGN);
3235
3236 if (options & SHELL_COOKED)
3237 settmode(TMODE_COOK); /* set to normal mode */
3238
3239 if (cmd == NULL)
3240 {
3241 x = mch_system(p_sh, options);
3242 }
3243 else
3244 {
3245 /* we use "command" or "cmd" to start the shell; slow but easy */
3246 char_u *newcmd;
3247
3248 newcmd = lalloc((long_u) (
3249#ifdef FEAT_GUI_W32
3250 STRLEN(vimrun_path) +
3251#endif
3252 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10), TRUE);
3253 if (newcmd != NULL)
3254 {
3255 char_u *cmdbase = (*cmd == '"' ? cmd + 1 : cmd);
3256
3257 if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
3258 {
3259 STARTUPINFO si;
3260 PROCESS_INFORMATION pi;
3261
3262 si.cb = sizeof(si);
3263 si.lpReserved = NULL;
3264 si.lpDesktop = NULL;
3265 si.lpTitle = NULL;
3266 si.dwFlags = 0;
3267 si.cbReserved2 = 0;
3268 si.lpReserved2 = NULL;
3269
3270 cmdbase = skipwhite(cmdbase + 5);
3271 if ((STRNICMP(cmdbase, "/min", 4) == 0)
3272 && vim_iswhite(cmdbase[4]))
3273 {
3274 cmdbase = skipwhite(cmdbase + 4);
3275 si.dwFlags = STARTF_USESHOWWINDOW;
3276 si.wShowWindow = SW_SHOWMINNOACTIVE;
3277 }
3278
3279 /* When the command is in double quotes, but 'shellxquote' is
3280 * empty, keep the double quotes around the command.
3281 * Otherwise remove the double quotes, they aren't needed
3282 * here, because we don't use a shell to run the command. */
3283 if (*cmd == '"' && *p_sxq == NUL)
3284 {
3285 newcmd[0] = '"';
3286 STRCPY(newcmd + 1, cmdbase);
3287 }
3288 else
3289 {
3290 STRCPY(newcmd, cmdbase);
3291 if (*cmd == '"' && *newcmd != NUL)
3292 newcmd[STRLEN(newcmd) - 1] = NUL;
3293 }
3294
3295 /*
3296 * Now, start the command as a process, so that it doesn't
3297 * inherit our handles which causes unpleasant dangling swap
3298 * files if we exit before the spawned process
3299 */
3300 if (CreateProcess (NULL, // Executable name
3301 newcmd, // Command to execute
3302 NULL, // Process security attributes
3303 NULL, // Thread security attributes
3304 FALSE, // Inherit handles
3305 CREATE_NEW_CONSOLE, // Creation flags
3306 NULL, // Environment
3307 NULL, // Current directory
3308 &si, // Startup information
3309 &pi)) // Process information
3310 x = 0;
3311 else
3312 {
3313 x = -1;
3314#ifdef FEAT_GUI_W32
3315 EMSG(_("E371: Command not found"));
3316#endif
3317 }
3318 /* Close the handles to the subprocess, so that it goes away */
3319 CloseHandle(pi.hThread);
3320 CloseHandle(pi.hProcess);
3321 }
3322 else
3323 {
3324#if defined(FEAT_GUI_W32)
3325 if (need_vimrun_warning)
3326 {
3327 MessageBox(NULL,
3328 _("VIMRUN.EXE not found in your $PATH.\n"
3329 "External commands will not pause after completion.\n"
3330 "See :help win32-vimrun for more information."),
3331 _("Vim Warning"),
3332 MB_ICONWARNING);
3333 need_vimrun_warning = FALSE;
3334 }
3335 if (!s_dont_use_vimrun)
3336 /* Use vimrun to execute the command. It opens a console
3337 * window, which can be closed without killing Vim. */
3338 sprintf((char *)newcmd, "%s%s%s %s %s",
3339 vimrun_path,
3340 (msg_silent != 0 || (options & SHELL_DOOUT))
3341 ? "-s " : "",
3342 p_sh, p_shcf, cmd);
3343 else
3344#endif
3345 sprintf((char *)newcmd, "%s %s %s", p_sh, p_shcf, cmd);
3346 x = mch_system((char *)newcmd, options);
3347 }
3348 vim_free(newcmd);
3349 }
3350 }
3351
3352 if (tmode == TMODE_RAW)
3353 settmode(TMODE_RAW); /* set to raw mode */
3354
3355 /* Print the return value, unless "vimrun" was used. */
3356 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
3357#if defined(FEAT_GUI_W32)
3358 && ((options & SHELL_DOOUT) || s_dont_use_vimrun)
3359#endif
3360 )
3361 {
3362 smsg(_("shell returned %d"), x);
3363 msg_putchar('\n');
3364 }
3365#ifdef FEAT_TITLE
3366 resettitle();
3367#endif
3368
3369 signal(SIGINT, SIG_DFL);
3370#if defined(__GNUC__) && !defined(__MINGW32__)
3371 signal(SIGKILL, SIG_DFL);
3372#else
3373 signal(SIGBREAK, SIG_DFL);
3374#endif
3375 signal(SIGILL, SIG_DFL);
3376 signal(SIGFPE, SIG_DFL);
3377 signal(SIGSEGV, SIG_DFL);
3378 signal(SIGTERM, SIG_DFL);
3379 signal(SIGABRT, SIG_DFL);
3380
3381 return x;
3382}
3383
3384
3385#ifndef FEAT_GUI_W32
3386
3387/*
3388 * Start termcap mode
3389 */
3390 static void
3391termcap_mode_start(void)
3392{
3393 DWORD cmodein;
3394
3395 if (g_fTermcapMode)
3396 return;
3397
3398 SaveConsoleBuffer(&g_cbNonTermcap);
3399
3400 if (g_cbTermcap.IsValid)
3401 {
3402 /*
3403 * We've been in termcap mode before. Restore certain screen
3404 * characteristics, including the buffer size and the window
3405 * size. Since we will be redrawing the screen, we don't need
3406 * to restore the actual contents of the buffer.
3407 */
3408 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
3409 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
3410 Rows = g_cbTermcap.Info.dwSize.Y;
3411 Columns = g_cbTermcap.Info.dwSize.X;
3412 }
3413 else
3414 {
3415 /*
3416 * This is our first time entering termcap mode. Clear the console
3417 * screen buffer, and resize the buffer to match the current window
3418 * size. We will use this as the size of our editing environment.
3419 */
3420 ClearConsoleBuffer(g_attrCurrent);
3421 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3422 }
3423
3424#ifdef FEAT_TITLE
3425 resettitle();
3426#endif
3427
3428 GetConsoleMode(g_hConIn, &cmodein);
3429#ifdef FEAT_MOUSE
3430 if (g_fMouseActive)
3431 cmodein |= ENABLE_MOUSE_INPUT;
3432 else
3433 cmodein &= ~ENABLE_MOUSE_INPUT;
3434#endif
3435 cmodein |= ENABLE_WINDOW_INPUT;
3436 SetConsoleMode(g_hConIn, cmodein);
3437
3438 redraw_later_clear();
3439 g_fTermcapMode = TRUE;
3440}
3441
3442
3443/*
3444 * End termcap mode
3445 */
3446 static void
3447termcap_mode_end(void)
3448{
3449 DWORD cmodein;
3450 ConsoleBuffer *cb;
3451 COORD coord;
3452 DWORD dwDummy;
3453
3454 if (!g_fTermcapMode)
3455 return;
3456
3457 SaveConsoleBuffer(&g_cbTermcap);
3458
3459 GetConsoleMode(g_hConIn, &cmodein);
3460 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
3461 SetConsoleMode(g_hConIn, cmodein);
3462
3463#ifdef FEAT_RESTORE_ORIG_SCREEN
3464 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
3465#else
3466 cb = &g_cbNonTermcap;
3467#endif
3468 RestoreConsoleBuffer(cb, p_rs);
3469 SetConsoleCursorInfo(g_hConOut, &g_cci);
3470
3471 if (p_rs || exiting)
3472 {
3473 /*
3474 * Clear anything that happens to be on the current line.
3475 */
3476 coord.X = 0;
3477 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
3478 FillConsoleOutputCharacter(g_hConOut, ' ',
3479 cb->Info.dwSize.X, coord, &dwDummy);
3480 /*
3481 * The following is just for aesthetics. If we are exiting without
3482 * restoring the screen, then we want to have a prompt string
3483 * appear at the bottom line. However, the command interpreter
3484 * seems to always advance the cursor one line before displaying
3485 * the prompt string, which causes the screen to scroll. To
3486 * counter this, move the cursor up one line before exiting.
3487 */
3488 if (exiting && !p_rs)
3489 coord.Y--;
3490 /*
3491 * Position the cursor at the leftmost column of the desired row.
3492 */
3493 SetConsoleCursorPosition(g_hConOut, coord);
3494 }
3495
3496 g_fTermcapMode = FALSE;
3497}
3498#endif /* FEAT_GUI_W32 */
3499
3500
3501#ifdef FEAT_GUI_W32
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003502/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00003503 void
3504mch_write(
3505 char_u *s,
3506 int len)
3507{
3508 /* never used */
3509}
3510
3511#else
3512
3513/*
3514 * clear `n' chars, starting from `coord'
3515 */
3516 static void
3517clear_chars(
3518 COORD coord,
3519 DWORD n)
3520{
3521 DWORD dwDummy;
3522
3523 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
3524 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
3525}
3526
3527
3528/*
3529 * Clear the screen
3530 */
3531 static void
3532clear_screen(void)
3533{
3534 g_coord.X = g_coord.Y = 0;
3535 clear_chars(g_coord, Rows * Columns);
3536}
3537
3538
3539/*
3540 * Clear to end of display
3541 */
3542 static void
3543clear_to_end_of_display(void)
3544{
3545 clear_chars(g_coord, (Rows - g_coord.Y - 1)
3546 * Columns + (Columns - g_coord.X));
3547}
3548
3549
3550/*
3551 * Clear to end of line
3552 */
3553 static void
3554clear_to_end_of_line(void)
3555{
3556 clear_chars(g_coord, Columns - g_coord.X);
3557}
3558
3559
3560/*
3561 * Scroll the scroll region up by `cLines' lines
3562 */
3563 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003564scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003565{
3566 COORD oldcoord = g_coord;
3567
3568 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
3569 delete_lines(cLines);
3570
3571 g_coord = oldcoord;
3572}
3573
3574
3575/*
3576 * Set the scroll region
3577 */
3578 static void
3579set_scroll_region(
3580 unsigned left,
3581 unsigned top,
3582 unsigned right,
3583 unsigned bottom)
3584{
3585 if (left >= right
3586 || top >= bottom
3587 || right > (unsigned) Columns - 1
3588 || bottom > (unsigned) Rows - 1)
3589 return;
3590
3591 g_srScrollRegion.Left = left;
3592 g_srScrollRegion.Top = top;
3593 g_srScrollRegion.Right = right;
3594 g_srScrollRegion.Bottom = bottom;
3595}
3596
3597
3598/*
3599 * Insert `cLines' lines at the current cursor position
3600 */
3601 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003602insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003603{
3604 SMALL_RECT source;
3605 COORD dest;
3606 CHAR_INFO fill;
3607
3608 dest.X = 0;
3609 dest.Y = g_coord.Y + cLines;
3610
3611 source.Left = 0;
3612 source.Top = g_coord.Y;
3613 source.Right = g_srScrollRegion.Right;
3614 source.Bottom = g_srScrollRegion.Bottom - cLines;
3615
3616 fill.Char.AsciiChar = ' ';
3617 fill.Attributes = g_attrCurrent;
3618
3619 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3620
3621 /* Here we have to deal with a win32 console flake: If the scroll
3622 * region looks like abc and we scroll c to a and fill with d we get
3623 * cbd... if we scroll block c one line at a time to a, we get cdd...
3624 * vim expects cdd consistently... So we have to deal with that
3625 * here... (this also occurs scrolling the same way in the other
3626 * direction). */
3627
3628 if (source.Bottom < dest.Y)
3629 {
3630 COORD coord;
3631
3632 coord.X = 0;
3633 coord.Y = source.Bottom;
3634 clear_chars(coord, Columns * (dest.Y - source.Bottom));
3635 }
3636}
3637
3638
3639/*
3640 * Delete `cLines' lines at the current cursor position
3641 */
3642 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003643delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003644{
3645 SMALL_RECT source;
3646 COORD dest;
3647 CHAR_INFO fill;
3648 int nb;
3649
3650 dest.X = 0;
3651 dest.Y = g_coord.Y;
3652
3653 source.Left = 0;
3654 source.Top = g_coord.Y + cLines;
3655 source.Right = g_srScrollRegion.Right;
3656 source.Bottom = g_srScrollRegion.Bottom;
3657
3658 fill.Char.AsciiChar = ' ';
3659 fill.Attributes = g_attrCurrent;
3660
3661 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
3662
3663 /* Here we have to deal with a win32 console flake: If the scroll
3664 * region looks like abc and we scroll c to a and fill with d we get
3665 * cbd... if we scroll block c one line at a time to a, we get cdd...
3666 * vim expects cdd consistently... So we have to deal with that
3667 * here... (this also occurs scrolling the same way in the other
3668 * direction). */
3669
3670 nb = dest.Y + (source.Bottom - source.Top) + 1;
3671
3672 if (nb < source.Top)
3673 {
3674 COORD coord;
3675
3676 coord.X = 0;
3677 coord.Y = nb;
3678 clear_chars(coord, Columns * (source.Top - nb));
3679 }
3680}
3681
3682
3683/*
3684 * Set the cursor position
3685 */
3686 static void
3687gotoxy(
3688 unsigned x,
3689 unsigned y)
3690{
3691 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
3692 return;
3693
3694 /* external cursor coords are 1-based; internal are 0-based */
3695 g_coord.X = x - 1;
3696 g_coord.Y = y - 1;
3697 SetConsoleCursorPosition(g_hConOut, g_coord);
3698}
3699
3700
3701/*
3702 * Set the current text attribute = (foreground | background)
3703 * See ../doc/os_win32.txt for the numbers.
3704 */
3705 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003706textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003707{
3708 g_attrCurrent = wAttr;
3709
3710 SetConsoleTextAttribute(g_hConOut, wAttr);
3711}
3712
3713
3714 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003715textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003716{
3717 g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
3718
3719 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3720}
3721
3722
3723 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003724textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003725{
3726 g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
3727
3728 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
3729}
3730
3731
3732/*
3733 * restore the default text attribute (whatever we started with)
3734 */
3735 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003736normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003737{
3738 textattr(g_attrDefault);
3739}
3740
3741
3742static WORD g_attrPreStandout = 0;
3743
3744/*
3745 * Make the text standout, by brightening it
3746 */
3747 static void
3748standout(void)
3749{
3750 g_attrPreStandout = g_attrCurrent;
3751 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
3752}
3753
3754
3755/*
3756 * Turn off standout mode
3757 */
3758 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003759standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003760{
3761 if (g_attrPreStandout)
3762 {
3763 textattr(g_attrPreStandout);
3764 g_attrPreStandout = 0;
3765 }
3766}
3767
3768
3769/*
3770 * Set normal fg/bg color, based on T_ME. Called whem t_me has been set.
3771 */
3772 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003773mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003774{
3775 char_u *p;
3776 int n;
3777
3778 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
3779 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
3780 if (T_ME[0] == ESC && T_ME[1] == '|')
3781 {
3782 p = T_ME + 2;
3783 n = getdigits(&p);
3784 if (*p == 'm' && n > 0)
3785 {
3786 cterm_normal_fg_color = (n & 0xf) + 1;
3787 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
3788 }
3789 }
3790}
3791
3792
3793/*
3794 * visual bell: flash the screen
3795 */
3796 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003797visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003798{
3799 COORD coordOrigin = {0, 0};
3800 WORD attrFlash = ~g_attrCurrent & 0xff;
3801
3802 DWORD dwDummy;
3803 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
3804
3805 if (oldattrs == NULL)
3806 return;
3807 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3808 coordOrigin, &dwDummy);
3809 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
3810 coordOrigin, &dwDummy);
3811
3812 Sleep(15); /* wait for 15 msec */
3813 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
3814 coordOrigin, &dwDummy);
3815 vim_free(oldattrs);
3816}
3817
3818
3819/*
3820 * Make the cursor visible or invisible
3821 */
3822 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003823cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003824{
3825 s_cursor_visible = fVisible;
3826#ifdef MCH_CURSOR_SHAPE
3827 mch_update_cursor();
3828#endif
3829}
3830
3831
3832/*
3833 * write `cchToWrite' characters in `pchBuf' to the screen
3834 * Returns the number of characters actually written (at least one).
3835 */
3836 static BOOL
3837write_chars(
3838 LPCSTR pchBuf,
3839 DWORD cchToWrite)
3840{
3841 COORD coord = g_coord;
3842 DWORD written;
3843
3844 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
3845 coord, &written);
3846 /* When writing fails or didn't write a single character, pretend one
3847 * character was written, otherwise we get stuck. */
3848 if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
3849 coord, &written) == 0
3850 || written == 0)
3851 written = 1;
3852
3853 g_coord.X += (SHORT) written;
3854
3855 while (g_coord.X > g_srScrollRegion.Right)
3856 {
3857 g_coord.X -= (SHORT) Columns;
3858 if (g_coord.Y < g_srScrollRegion.Bottom)
3859 g_coord.Y++;
3860 }
3861
3862 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3863
3864 return written;
3865}
3866
3867
3868/*
3869 * mch_write(): write the output buffer to the screen, translating ESC
3870 * sequences into calls to console output routines.
3871 */
3872 void
3873mch_write(
3874 char_u *s,
3875 int len)
3876{
3877 s[len] = NUL;
3878
3879 if (!term_console)
3880 {
3881 write(1, s, (unsigned)len);
3882 return;
3883 }
3884
3885 /* translate ESC | sequences into faked bios calls */
3886 while (len--)
3887 {
3888 /* optimization: use one single write_chars for runs of text,
3889 * rather than once per character It ain't curses, but it helps. */
3890 DWORD prefix = strcspn(s, "\n\r\b\a\033");
3891
3892 if (p_wd)
3893 {
3894 WaitForChar(p_wd);
3895 if (prefix != 0)
3896 prefix = 1;
3897 }
3898
3899 if (prefix != 0)
3900 {
3901 DWORD nWritten;
3902
3903 nWritten = write_chars(s, prefix);
3904#ifdef MCH_WRITE_DUMP
3905 if (fdDump)
3906 {
3907 fputc('>', fdDump);
3908 fwrite(s, sizeof(char_u), nWritten, fdDump);
3909 fputs("<\n", fdDump);
3910 }
3911#endif
3912 len -= (nWritten - 1);
3913 s += nWritten;
3914 }
3915 else if (s[0] == '\n')
3916 {
3917 /* \n, newline: go to the beginning of the next line or scroll */
3918 if (g_coord.Y == g_srScrollRegion.Bottom)
3919 {
3920 scroll(1);
3921 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
3922 }
3923 else
3924 {
3925 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
3926 }
3927#ifdef MCH_WRITE_DUMP
3928 if (fdDump)
3929 fputs("\\n\n", fdDump);
3930#endif
3931 s++;
3932 }
3933 else if (s[0] == '\r')
3934 {
3935 /* \r, carriage return: go to beginning of line */
3936 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
3937#ifdef MCH_WRITE_DUMP
3938 if (fdDump)
3939 fputs("\\r\n", fdDump);
3940#endif
3941 s++;
3942 }
3943 else if (s[0] == '\b')
3944 {
3945 /* \b, backspace: move cursor one position left */
3946 if (g_coord.X > g_srScrollRegion.Left)
3947 g_coord.X--;
3948 else if (g_coord.Y > g_srScrollRegion.Top)
3949 {
3950 g_coord.X = g_srScrollRegion.Right;
3951 g_coord.Y--;
3952 }
3953 gotoxy(g_coord.X + 1, g_coord.Y + 1);
3954#ifdef MCH_WRITE_DUMP
3955 if (fdDump)
3956 fputs("\\b\n", fdDump);
3957#endif
3958 s++;
3959 }
3960 else if (s[0] == '\a')
3961 {
3962 /* \a, bell */
3963 MessageBeep(0xFFFFFFFF);
3964#ifdef MCH_WRITE_DUMP
3965 if (fdDump)
3966 fputs("\\a\n", fdDump);
3967#endif
3968 s++;
3969 }
3970 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
3971 {
3972#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003973 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003974#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00003975 char_u *p;
3976 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003977
3978 switch (s[2])
3979 {
3980 /* one or two numeric arguments, separated by ';' */
3981
3982 case '0': case '1': case '2': case '3': case '4':
3983 case '5': case '6': case '7': case '8': case '9':
3984 p = s + 2;
3985 arg1 = getdigits(&p); /* no check for length! */
3986 if (p > s + len)
3987 break;
3988
3989 if (*p == ';')
3990 {
3991 ++p;
3992 arg2 = getdigits(&p); /* no check for length! */
3993 if (p > s + len)
3994 break;
3995
3996 if (*p == 'H')
3997 gotoxy(arg2, arg1);
3998 else if (*p == 'r')
3999 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
4000 }
4001 else if (*p == 'A')
4002 {
4003 /* move cursor up arg1 lines in same column */
4004 gotoxy(g_coord.X + 1,
4005 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
4006 }
4007 else if (*p == 'C')
4008 {
4009 /* move cursor right arg1 columns in same line */
4010 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
4011 g_coord.Y + 1);
4012 }
4013 else if (*p == 'H')
4014 {
4015 gotoxy(1, arg1);
4016 }
4017 else if (*p == 'L')
4018 {
4019 insert_lines(arg1);
4020 }
4021 else if (*p == 'm')
4022 {
4023 if (arg1 == 0)
4024 normvideo();
4025 else
4026 textattr((WORD) arg1);
4027 }
4028 else if (*p == 'f')
4029 {
4030 textcolor((WORD) arg1);
4031 }
4032 else if (*p == 'b')
4033 {
4034 textbackground((WORD) arg1);
4035 }
4036 else if (*p == 'M')
4037 {
4038 delete_lines(arg1);
4039 }
4040
4041 len -= p - s;
4042 s = p + 1;
4043 break;
4044
4045
4046 /* Three-character escape sequences */
4047
4048 case 'A':
4049 /* move cursor up one line in same column */
4050 gotoxy(g_coord.X + 1,
4051 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
4052 goto got3;
4053
4054 case 'B':
4055 visual_bell();
4056 goto got3;
4057
4058 case 'C':
4059 /* move cursor right one column in same line */
4060 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
4061 g_coord.Y + 1);
4062 goto got3;
4063
4064 case 'E':
4065 termcap_mode_end();
4066 goto got3;
4067
4068 case 'F':
4069 standout();
4070 goto got3;
4071
4072 case 'f':
4073 standend();
4074 goto got3;
4075
4076 case 'H':
4077 gotoxy(1, 1);
4078 goto got3;
4079
4080 case 'j':
4081 clear_to_end_of_display();
4082 goto got3;
4083
4084 case 'J':
4085 clear_screen();
4086 goto got3;
4087
4088 case 'K':
4089 clear_to_end_of_line();
4090 goto got3;
4091
4092 case 'L':
4093 insert_lines(1);
4094 goto got3;
4095
4096 case 'M':
4097 delete_lines(1);
4098 goto got3;
4099
4100 case 'S':
4101 termcap_mode_start();
4102 goto got3;
4103
4104 case 'V':
4105 cursor_visible(TRUE);
4106 goto got3;
4107
4108 case 'v':
4109 cursor_visible(FALSE);
4110 goto got3;
4111
4112 got3:
4113 s += 3;
4114 len -= 2;
4115 }
4116
4117#ifdef MCH_WRITE_DUMP
4118 if (fdDump)
4119 {
4120 fputs("ESC | ", fdDump);
4121 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
4122 fputc('\n', fdDump);
4123 }
4124#endif
4125 }
4126 else
4127 {
4128 /* Write a single character */
4129 DWORD nWritten;
4130
4131 nWritten = write_chars(s, 1);
4132#ifdef MCH_WRITE_DUMP
4133 if (fdDump)
4134 {
4135 fputc('>', fdDump);
4136 fwrite(s, sizeof(char_u), nWritten, fdDump);
4137 fputs("<\n", fdDump);
4138 }
4139#endif
4140
4141 len -= (nWritten - 1);
4142 s += nWritten;
4143 }
4144 }
4145
4146#ifdef MCH_WRITE_DUMP
4147 if (fdDump)
4148 fflush(fdDump);
4149#endif
4150}
4151
4152#endif /* FEAT_GUI_W32 */
4153
4154
4155/*
4156 * Delay for half a second.
4157 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004158/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004159 void
4160mch_delay(
4161 long msec,
4162 int ignoreinput)
4163{
4164#ifdef FEAT_GUI_W32
4165 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004166#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004167 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00004168# ifdef FEAT_MZSCHEME
4169 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
4170 {
4171 int towait = p_mzq;
4172
4173 /* if msec is large enough, wait by portions in p_mzq */
4174 while (msec > 0)
4175 {
4176 mzvim_check_threads();
4177 if (msec < towait)
4178 towait = msec;
4179 Sleep(towait);
4180 msec -= towait;
4181 }
4182 }
4183 else
4184# endif
4185 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186 else
4187 WaitForChar(msec);
4188#endif
4189}
4190
4191
4192/*
4193 * this version of remove is not scared by a readonly (backup) file
4194 * Return 0 for success, -1 for failure.
4195 */
4196 int
4197mch_remove(char_u *name)
4198{
4199#ifdef FEAT_MBYTE
4200 WCHAR *wn = NULL;
4201 int n;
4202
4203 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4204 {
4205 wn = enc_to_ucs2(name, NULL);
4206 if (wn != NULL)
4207 {
4208 SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
4209 n = DeleteFileW(wn) ? 0 : -1;
4210 vim_free(wn);
4211 if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4212 return n;
4213 /* Retry with non-wide function (for Windows 98). */
4214 }
4215 }
4216#endif
4217 SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
4218 return DeleteFile(name) ? 0 : -1;
4219}
4220
4221
4222/*
4223 * check for an "interrupt signal": CTRL-break or CTRL-C
4224 */
4225 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004226mch_breakcheck(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227{
4228#ifndef FEAT_GUI_W32 /* never used */
4229 if (g_fCtrlCPressed || g_fCBrkPressed)
4230 {
4231 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
4232 got_int = TRUE;
4233 }
4234#endif
4235}
4236
4237
4238/*
4239 * How much memory is available?
4240 * Return sum of available physical and page file memory.
4241 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004242/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243 long_u
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004244mch_avail_mem(int special)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245{
4246 MEMORYSTATUS ms;
4247
4248 ms.dwLength = sizeof(MEMORYSTATUS);
4249 GlobalMemoryStatus(&ms);
4250 return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
4251}
4252
4253#ifdef FEAT_MBYTE
4254/*
4255 * Same code as below, but with wide functions and no comments.
4256 * Return 0 for success, non-zero for failure.
4257 */
4258 int
4259mch_wrename(WCHAR *wold, WCHAR *wnew)
4260{
4261 WCHAR *p;
4262 int i;
4263 WCHAR szTempFile[_MAX_PATH + 1];
4264 WCHAR szNewPath[_MAX_PATH + 1];
4265 HANDLE hf;
4266
4267 if (!mch_windows95())
4268 {
4269 p = wold;
4270 for (i = 0; wold[i] != NUL; ++i)
4271 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
4272 && wold[i + 1] != 0)
4273 p = wold + i + 1;
4274 if ((int)(wold + i - p) < 8 || p[6] != '~')
4275 return (MoveFileW(wold, wnew) == 0);
4276 }
4277
4278 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
4279 return -1;
4280 *p = NUL;
4281
4282 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
4283 return -2;
4284
4285 if (!DeleteFileW(szTempFile))
4286 return -3;
4287
4288 if (!MoveFileW(wold, szTempFile))
4289 return -4;
4290
4291 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4292 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4293 return -5;
4294 if (!CloseHandle(hf))
4295 return -6;
4296
4297 if (!MoveFileW(szTempFile, wnew))
4298 {
4299 (void)MoveFileW(szTempFile, wold);
4300 return -7;
4301 }
4302
4303 DeleteFileW(szTempFile);
4304
4305 if (!DeleteFileW(wold))
4306 return -8;
4307
4308 return 0;
4309}
4310#endif
4311
4312
4313/*
4314 * mch_rename() works around a bug in rename (aka MoveFile) in
4315 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
4316 * file whose short file name is "FOO.BAR" (its long file name will
4317 * be correct: "foo.bar~"). Because a file can be accessed by
4318 * either its SFN or its LFN, "foo.bar" has effectively been
4319 * renamed to "foo.bar", which is not at all what was wanted. This
4320 * seems to happen only when renaming files with three-character
4321 * extensions by appending a suffix that does not include ".".
4322 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
4323 *
4324 * There is another problem, which isn't really a bug but isn't right either:
4325 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
4326 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
4327 * service pack 6. Doesn't seem to happen on Windows 98.
4328 *
4329 * Like rename(), returns 0 upon success, non-zero upon failure.
4330 * Should probably set errno appropriately when errors occur.
4331 */
4332 int
4333mch_rename(
4334 const char *pszOldFile,
4335 const char *pszNewFile)
4336{
4337 char szTempFile[_MAX_PATH+1];
4338 char szNewPath[_MAX_PATH+1];
4339 char *pszFilePart;
4340 HANDLE hf;
4341#ifdef FEAT_MBYTE
4342 WCHAR *wold = NULL;
4343 WCHAR *wnew = NULL;
4344 int retval = -1;
4345
4346 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4347 {
4348 wold = enc_to_ucs2((char_u *)pszOldFile, NULL);
4349 wnew = enc_to_ucs2((char_u *)pszNewFile, NULL);
4350 if (wold != NULL && wnew != NULL)
4351 retval = mch_wrename(wold, wnew);
4352 vim_free(wold);
4353 vim_free(wnew);
4354 if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4355 return retval;
4356 /* Retry with non-wide function (for Windows 98). */
4357 }
4358#endif
4359
4360 /*
4361 * No need to play tricks if not running Windows 95, unless the file name
4362 * contains a "~" as the seventh character.
4363 */
4364 if (!mch_windows95())
4365 {
4366 pszFilePart = (char *)gettail((char_u *)pszOldFile);
4367 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
4368 return rename(pszOldFile, pszNewFile);
4369 }
4370
4371 /* Get base path of new file name. Undocumented feature: If pszNewFile is
4372 * a directory, no error is returned and pszFilePart will be NULL. */
4373 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
4374 || pszFilePart == NULL)
4375 return -1;
4376 *pszFilePart = NUL;
4377
4378 /* Get (and create) a unique temporary file name in directory of new file */
4379 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
4380 return -2;
4381
4382 /* blow the temp file away */
4383 if (!DeleteFile(szTempFile))
4384 return -3;
4385
4386 /* rename old file to the temp file */
4387 if (!MoveFile(pszOldFile, szTempFile))
4388 return -4;
4389
4390 /* now create an empty file called pszOldFile; this prevents the operating
4391 * system using pszOldFile as an alias (SFN) if we're renaming within the
4392 * same directory. For example, we're editing a file called
4393 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
4394 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
4395 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004396 * cause all sorts of problems later in buf_write(). So, we create an
4397 * empty file called filena~1.txt and the system will have to find some
4398 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00004399 */
4400 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
4401 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
4402 return -5;
4403 if (!CloseHandle(hf))
4404 return -6;
4405
4406 /* rename the temp file to the new file */
4407 if (!MoveFile(szTempFile, pszNewFile))
4408 {
4409 /* Renaming failed. Rename the file back to its old name, so that it
4410 * looks like nothing happened. */
4411 (void)MoveFile(szTempFile, pszOldFile);
4412
4413 return -7;
4414 }
4415
4416 /* Seems to be left around on Novell filesystems */
4417 DeleteFile(szTempFile);
4418
4419 /* finally, remove the empty old file */
4420 if (!DeleteFile(pszOldFile))
4421 return -8;
4422
4423 return 0; /* success */
4424}
4425
4426/*
4427 * Get the default shell for the current hardware platform
4428 */
4429 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004430default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004431{
4432 char* psz = NULL;
4433
4434 PlatformId();
4435
4436 if (g_PlatformId == VER_PLATFORM_WIN32_NT) /* Windows NT */
4437 psz = "cmd.exe";
4438 else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS) /* Windows 95 */
4439 psz = "command.com";
4440
4441 return psz;
4442}
4443
4444/*
4445 * mch_access() extends access() to do more detailed check on network drives.
4446 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
4447 */
4448 int
4449mch_access(char *n, int p)
4450{
4451 HANDLE hFile;
4452 DWORD am;
4453 int retval = -1; /* default: fail */
4454#ifdef FEAT_MBYTE
4455 WCHAR *wn = NULL;
4456
4457 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4458 wn = enc_to_ucs2(n, NULL);
4459#endif
4460
4461 if (mch_isdir(n))
4462 {
4463 char TempName[_MAX_PATH + 16] = "";
4464#ifdef FEAT_MBYTE
4465 WCHAR TempNameW[_MAX_PATH + 16] = L"";
4466#endif
4467
4468 if (p & R_OK)
4469 {
4470 /* Read check is performed by seeing if we can do a find file on
4471 * the directory for any file. */
4472#ifdef FEAT_MBYTE
4473 if (wn != NULL)
4474 {
4475 int i;
4476 WIN32_FIND_DATAW d;
4477
4478 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
4479 TempNameW[i] = wn[i];
4480 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
4481 TempNameW[i++] = '\\';
4482 TempNameW[i++] = '*';
4483 TempNameW[i++] = 0;
4484
4485 hFile = FindFirstFileW(TempNameW, &d);
4486 if (hFile == INVALID_HANDLE_VALUE)
4487 {
4488 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4489 goto getout;
4490
4491 /* Retry with non-wide function (for Windows 98). */
4492 vim_free(wn);
4493 wn = NULL;
4494 }
4495 else
4496 (void)FindClose(hFile);
4497 }
4498 if (wn == NULL)
4499#endif
4500 {
4501 char *pch;
4502 WIN32_FIND_DATA d;
4503
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00004504 vim_strncpy(TempName, n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004505 pch = TempName + STRLEN(TempName) - 1;
4506 if (*pch != '\\' && *pch != '/')
4507 *++pch = '\\';
4508 *++pch = '*';
4509 *++pch = NUL;
4510
4511 hFile = FindFirstFile(TempName, &d);
4512 if (hFile == INVALID_HANDLE_VALUE)
4513 goto getout;
4514 (void)FindClose(hFile);
4515 }
4516 }
4517
4518 if (p & W_OK)
4519 {
4520 /* Trying to create a temporary file in the directory should catch
4521 * directories on read-only network shares. However, in
4522 * directories whose ACL allows writes but denies deletes will end
4523 * up keeping the temporary file :-(. */
4524#ifdef FEAT_MBYTE
4525 if (wn != NULL)
4526 {
4527 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
4528 {
4529 if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
4530 goto getout;
4531
4532 /* Retry with non-wide function (for Windows 98). */
4533 vim_free(wn);
4534 wn = NULL;
4535 }
4536 else
4537 DeleteFileW(TempNameW);
4538 }
4539 if (wn == NULL)
4540#endif
4541 {
4542 if (!GetTempFileName(n, "VIM", 0, TempName))
4543 goto getout;
4544 mch_remove((char_u *)TempName);
4545 }
4546 }
4547 }
4548 else
4549 {
4550 /* Trying to open the file for the required access does ACL, read-only
4551 * network share, and file attribute checks. */
4552 am = ((p & W_OK) ? GENERIC_WRITE : 0)
4553 | ((p & R_OK) ? GENERIC_READ : 0);
4554#ifdef FEAT_MBYTE
4555 if (wn != NULL)
4556 {
4557 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4558 if (hFile == INVALID_HANDLE_VALUE
4559 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
4560 {
4561 /* Retry with non-wide function (for Windows 98). */
4562 vim_free(wn);
4563 wn = NULL;
4564 }
4565 }
4566 if (wn == NULL)
4567#endif
4568 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
4569 if (hFile == INVALID_HANDLE_VALUE)
4570 goto getout;
4571 CloseHandle(hFile);
4572 }
4573
4574 retval = 0; /* success */
4575getout:
4576#ifdef FEAT_MBYTE
4577 vim_free(wn);
4578#endif
4579 return retval;
4580}
4581
4582#if defined(FEAT_MBYTE) || defined(PROTO)
4583/*
4584 * Version of open() that may use ucs2 file name.
4585 */
4586 int
4587mch_open(char *name, int flags, int mode)
4588{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004589 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
4590# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00004591 WCHAR *wn;
4592 int f;
4593
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004594 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004595 {
4596 wn = enc_to_ucs2(name, NULL);
4597 if (wn != NULL)
4598 {
4599 f = _wopen(wn, flags, mode);
4600 vim_free(wn);
4601 if (f >= 0)
4602 return f;
4603 /* Retry with non-wide function (for Windows 98). Can't use
4604 * GetLastError() here and it's unclear what errno gets set to if
4605 * the _wopen() fails for missing wide functions. */
4606 }
4607 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004608# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004609
4610 return open(name, flags, mode);
4611}
4612
4613/*
4614 * Version of fopen() that may use ucs2 file name.
4615 */
4616 FILE *
4617mch_fopen(char *name, char *mode)
4618{
4619 WCHAR *wn, *wm;
4620 FILE *f = NULL;
4621
4622 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
4623# ifdef __BORLANDC__
4624 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
4625 && g_PlatformId == VER_PLATFORM_WIN32_NT
4626# endif
4627 )
4628 {
4629 wn = enc_to_ucs2(name, NULL);
4630 wm = enc_to_ucs2(mode, NULL);
4631 if (wn != NULL && wm != NULL)
4632 f = _wfopen(wn, wm);
4633 vim_free(wn);
4634 vim_free(wm);
4635 if (f != NULL)
4636 return f;
4637 /* Retry with non-wide function (for Windows 98). Can't use
4638 * GetLastError() here and it's unclear what errno gets set to if
4639 * the _wfopen() fails for missing wide functions. */
4640 }
4641
4642 return fopen(name, mode);
4643}
4644#endif
4645
4646#ifdef FEAT_MBYTE
4647/*
4648 * SUB STREAM (aka info stream) handling:
4649 *
4650 * NTFS can have sub streams for each file. Normal contents of file is
4651 * stored in the main stream, and extra contents (author information and
4652 * title and so on) can be stored in sub stream. After Windows 2000, user
4653 * can access and store those informations in sub streams via explorer's
4654 * property menuitem in right click menu. Those informations in sub streams
4655 * were lost when copying only the main stream. So we have to copy sub
4656 * streams.
4657 *
4658 * Incomplete explanation:
4659 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
4660 * More useful info and an example:
4661 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
4662 */
4663
4664/*
4665 * Copy info stream data "substream". Read from the file with BackupRead(sh)
4666 * and write to stream "substream" of file "to".
4667 * Errors are ignored.
4668 */
4669 static void
4670copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
4671{
4672 HANDLE hTo;
4673 WCHAR *to_name;
4674
4675 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
4676 wcscpy(to_name, to);
4677 wcscat(to_name, substream);
4678
4679 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
4680 FILE_ATTRIBUTE_NORMAL, NULL);
4681 if (hTo != INVALID_HANDLE_VALUE)
4682 {
4683 long done;
4684 DWORD todo;
4685 DWORD readcnt, written;
4686 char buf[4096];
4687
4688 /* Copy block of bytes at a time. Abort when something goes wrong. */
4689 for (done = 0; done < len; done += written)
4690 {
4691 /* (size_t) cast for Borland C 5.5 */
4692 todo = (size_t)(len - done) > sizeof(buf) ? sizeof(buf)
4693 : (size_t)(len - done);
4694 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
4695 FALSE, FALSE, context)
4696 || readcnt != todo
4697 || !WriteFile(hTo, buf, todo, &written, NULL)
4698 || written != todo)
4699 break;
4700 }
4701 CloseHandle(hTo);
4702 }
4703
4704 free(to_name);
4705}
4706
4707/*
4708 * Copy info streams from file "from" to file "to".
4709 */
4710 static void
4711copy_infostreams(char_u *from, char_u *to)
4712{
4713 WCHAR *fromw;
4714 WCHAR *tow;
4715 HANDLE sh;
4716 WIN32_STREAM_ID sid;
4717 int headersize;
4718 WCHAR streamname[_MAX_PATH];
4719 DWORD readcount;
4720 void *context = NULL;
4721 DWORD lo, hi;
4722 int len;
4723
4724 /* Convert the file names to wide characters. */
4725 fromw = enc_to_ucs2(from, NULL);
4726 tow = enc_to_ucs2(to, NULL);
4727 if (fromw != NULL && tow != NULL)
4728 {
4729 /* Open the file for reading. */
4730 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
4731 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
4732 if (sh != INVALID_HANDLE_VALUE)
4733 {
4734 /* Use BackupRead() to find the info streams. Repeat until we
4735 * have done them all.*/
4736 for (;;)
4737 {
4738 /* Get the header to find the length of the stream name. If
4739 * the "readcount" is zero we have done all info streams. */
4740 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
4741 headersize = (char *)&sid.cStreamName - (char *)&sid.dwStreamId;
4742 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
4743 &readcount, FALSE, FALSE, &context)
4744 || readcount == 0)
4745 break;
4746
4747 /* We only deal with streams that have a name. The normal
4748 * file data appears to be without a name, even though docs
4749 * suggest it is called "::$DATA". */
4750 if (sid.dwStreamNameSize > 0)
4751 {
4752 /* Read the stream name. */
4753 if (!BackupRead(sh, (LPBYTE)streamname,
4754 sid.dwStreamNameSize,
4755 &readcount, FALSE, FALSE, &context))
4756 break;
4757
4758 /* Copy an info stream with a name ":anything:$DATA".
4759 * Skip "::$DATA", it has no stream name (examples suggest
4760 * it might be used for the normal file contents).
4761 * Note that BackupRead() counts bytes, but the name is in
4762 * wide characters. */
4763 len = readcount / sizeof(WCHAR);
4764 streamname[len] = 0;
4765 if (len > 7 && wcsicmp(streamname + len - 6,
4766 L":$DATA") == 0)
4767 {
4768 streamname[len - 6] = 0;
4769 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004770 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 }
4772 }
4773
4774 /* Advance to the next stream. We might try seeking too far,
4775 * but BackupSeek() doesn't skip over stream borders, thus
4776 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00004777 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004778 &lo, &hi, &context);
4779 }
4780
4781 /* Clear the context. */
4782 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
4783
4784 CloseHandle(sh);
4785 }
4786 }
4787 vim_free(fromw);
4788 vim_free(tow);
4789}
4790#endif
4791
4792/*
4793 * Copy file attributes from file "from" to file "to".
4794 * For Windows NT and later we copy info streams.
4795 * Always returns zero, errors are ignored.
4796 */
4797 int
4798mch_copy_file_attribute(char_u *from, char_u *to)
4799{
4800#ifdef FEAT_MBYTE
4801 /* File streams only work on Windows NT and later. */
4802 PlatformId();
4803 if (g_PlatformId == VER_PLATFORM_WIN32_NT)
4804 copy_infostreams(from, to);
4805#endif
4806 return 0;
4807}
4808
4809#if defined(MYRESETSTKOFLW) || defined(PROTO)
4810/*
4811 * Recreate a destroyed stack guard page in win32.
4812 * Written by Benjamin Peterson.
4813 */
4814
4815/* These magic numbers are from the MS header files */
4816#define MIN_STACK_WIN9X 17
4817#define MIN_STACK_WINNT 2
4818
4819/*
4820 * This function does the same thing as _resetstkoflw(), which is only
4821 * available in DevStudio .net and later.
4822 * Returns 0 for failure, 1 for success.
4823 */
4824 int
4825myresetstkoflw(void)
4826{
4827 BYTE *pStackPtr;
4828 BYTE *pGuardPage;
4829 BYTE *pStackBase;
4830 BYTE *pLowestPossiblePage;
4831 MEMORY_BASIC_INFORMATION mbi;
4832 SYSTEM_INFO si;
4833 DWORD nPageSize;
4834 DWORD dummy;
4835
4836 /* This code will not work on win32s. */
4837 PlatformId();
4838 if (g_PlatformId == VER_PLATFORM_WIN32s)
4839 return 0;
4840
4841 /* We need to know the system page size. */
4842 GetSystemInfo(&si);
4843 nPageSize = si.dwPageSize;
4844
4845 /* ...and the current stack pointer */
4846 pStackPtr = (BYTE*)_alloca(1);
4847
4848 /* ...and the base of the stack. */
4849 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
4850 return 0;
4851 pStackBase = (BYTE*)mbi.AllocationBase;
4852
4853 /* ...and the page thats min_stack_req pages away from stack base; this is
4854 * the lowest page we could use. */
4855 pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
4856 ? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
4857
4858 /* On Win95, we want the next page down from the end of the stack. */
4859 if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
4860 {
4861 /* Find the page that's only 1 page down from the page that the stack
4862 * ptr is in. */
4863 pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
4864 / (DWORD)nPageSize) - 1));
4865 if (pGuardPage < pLowestPossiblePage)
4866 return 0;
4867
4868 /* Apply the noaccess attribute to the page -- there's no guard
4869 * attribute in win95-type OSes. */
4870 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
4871 return 0;
4872 }
4873 else
4874 {
4875 /* On NT, however, we want the first committed page in the stack Start
4876 * at the stack base and move forward through memory until we find a
4877 * committed block. */
4878 BYTE *pBlock = pStackBase;
4879
Bram Moolenaara466c992005-07-09 21:03:22 +00004880 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004881 {
4882 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
4883 return 0;
4884
4885 pBlock += mbi.RegionSize;
4886
4887 if (mbi.State & MEM_COMMIT)
4888 break;
4889 }
4890
4891 /* mbi now describes the first committed block in the stack. */
4892 if (mbi.Protect & PAGE_GUARD)
4893 return 1;
4894
4895 /* decide where the guard page should start */
4896 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
4897 pGuardPage = pLowestPossiblePage;
4898 else
4899 pGuardPage = (BYTE*)mbi.BaseAddress;
4900
4901 /* allocate the guard page */
4902 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
4903 return 0;
4904
4905 /* apply the guard attribute to the page */
4906 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
4907 &dummy))
4908 return 0;
4909 }
4910
4911 return 1;
4912}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004913#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004915
4916#if defined(FEAT_MBYTE) || defined(PROTO)
4917/*
4918 * The command line arguments in UCS2
4919 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00004920static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004921static LPWSTR *ArglistW = NULL;
4922static int global_argc = 0;
4923static char **global_argv;
4924
4925static int used_file_argc = 0; /* last argument in global_argv[] used
4926 for the argument list. */
4927static int *used_file_indexes = NULL; /* indexes in global_argv[] for
4928 command line arguments added to
4929 the argument list */
4930static int used_file_count = 0; /* nr of entries in used_file_indexes */
4931static int used_file_literal = FALSE; /* take file names literally */
4932static int used_file_full_path = FALSE; /* file name was full path */
4933static int used_alist_count = 0;
4934
4935
4936/*
4937 * Get the command line arguments. Unicode version.
4938 * Returns argc. Zero when something fails.
4939 */
4940 int
4941get_cmd_argsW(char ***argvp)
4942{
4943 char **argv = NULL;
4944 int argc = 0;
4945 int i;
4946
4947 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
4948 if (ArglistW != NULL)
4949 {
4950 argv = malloc((nArgsW + 1) * sizeof(char *));
4951 if (argv != NULL)
4952 {
4953 argc = nArgsW;
4954 argv[argc] = NULL;
4955 for (i = 0; i < argc; ++i)
4956 {
4957 int len;
4958
4959 /* Convert each Unicode argument to the current codepage. */
4960 WideCharToMultiByte_alloc(GetACP(), 0,
4961 ArglistW[i], wcslen(ArglistW[i]) + 1,
4962 (LPSTR *)&argv[i], &len, 0, 0);
4963 if (argv[i] == NULL)
4964 {
4965 /* Out of memory, clear everything. */
4966 while (i > 0)
4967 free(argv[--i]);
4968 free(argv);
4969 argc = 0;
4970 }
4971 }
4972 }
4973 }
4974
4975 global_argc = argc;
4976 global_argv = argv;
4977 if (argc > 0)
4978 used_file_indexes = malloc(argc * sizeof(int));
4979
4980 if (argvp != NULL)
4981 *argvp = argv;
4982 return argc;
4983}
4984
4985 void
4986free_cmd_argsW(void)
4987{
4988 if (ArglistW != NULL)
4989 {
4990 GlobalFree(ArglistW);
4991 ArglistW = NULL;
4992 }
4993}
4994
4995/*
4996 * Remember "name" is an argument that was added to the argument list.
4997 * This avoids that we have to re-parse the argument list when fix_arg_enc()
4998 * is called.
4999 */
5000 void
5001used_file_arg(char *name, int literal, int full_path)
5002{
5003 int i;
5004
5005 if (used_file_indexes == NULL)
5006 return;
5007 for (i = used_file_argc + 1; i < global_argc; ++i)
5008 if (STRCMP(global_argv[i], name) == 0)
5009 {
5010 used_file_argc = i;
5011 used_file_indexes[used_file_count++] = i;
5012 break;
5013 }
5014 used_file_literal = literal;
5015 used_file_full_path = full_path;
5016}
5017
5018/*
5019 * Remember the length of the argument list as it was. If it changes then we
5020 * leave it alone when 'encoding' is set.
5021 */
5022 void
5023set_alist_count(void)
5024{
5025 used_alist_count = GARGCOUNT;
5026}
5027
5028/*
5029 * Fix the encoding of the command line arguments. Invoked when 'encoding'
5030 * has been changed while starting up. Use the UCS-2 command line arguments
5031 * and convert them to 'encoding'.
5032 */
5033 void
5034fix_arg_enc(void)
5035{
5036 int i;
5037 int idx;
5038 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00005039 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005040
5041 /* Safety checks:
5042 * - if argument count differs between the wide and non-wide argument
5043 * list, something must be wrong.
5044 * - the file name arguments must have been located.
5045 * - the length of the argument list wasn't changed by the user.
5046 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00005047 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005048 || ArglistW == NULL
5049 || used_file_indexes == NULL
5050 || used_file_count == 0
5051 || used_alist_count != GARGCOUNT)
5052 return;
5053
Bram Moolenaar86b68352004-12-27 21:59:20 +00005054 /* Remember the buffer numbers for the arguments. */
5055 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
5056 if (fnum_list == NULL)
5057 return; /* out of memory */
5058 for (i = 0; i < GARGCOUNT; ++i)
5059 fnum_list[i] = GARGLIST[i].ae_fnum;
5060
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005061 /* Clear the argument list. Make room for the new arguments. */
5062 alist_clear(&global_alist);
5063 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005064 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005065
5066 for (i = 0; i < used_file_count; ++i)
5067 {
5068 idx = used_file_indexes[i];
5069 str = ucs2_to_enc(ArglistW[idx], NULL);
5070 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00005071 {
5072 /* Re-use the old buffer by renaming it. When not using literal
5073 * names it's done by alist_expand() below. */
5074 if (used_file_literal)
5075 buf_set_name(fnum_list[i], str);
5076
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005077 alist_add(&global_alist, str, used_file_literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00005078 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005079 }
5080
5081 if (!used_file_literal)
5082 {
5083 /* Now expand wildcards in the arguments. */
5084 /* Temporarily add '(' and ')' to 'isfname'. These are valid
5085 * filename characters but are excluded from 'isfname' to make
5086 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
5087 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00005088 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005089 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
5090 }
5091
5092 /* If wildcard expansion failed, we are editing the first file of the
5093 * arglist and there is no file name: Edit the first argument now. */
5094 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
5095 {
5096 do_cmdline_cmd((char_u *)":rewind");
5097 if (GARGCOUNT == 1 && used_file_full_path)
5098 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
5099 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00005100
5101 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005102}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005103#endif