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