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