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