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