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