#include "vimio.h"
#include "vim.h"
#ifdef FEAT_MZSCHEME
# include "if_mzsch.h"
#endif
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <limits.h>
#include <process.h>
#undef chdir
#ifdef __GNUC__
# ifndef __MINGW32__
# include <dirent.h>
# endif
#else
# include <direct.h>
#endif
#if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
# include <shellapi.h>
#endif
#ifdef __MINGW32__
# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
# endif
# ifndef RIGHTMOST_BUTTON_PRESSED
# define RIGHTMOST_BUTTON_PRESSED 0x0002
# endif
# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
# endif
# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
# endif
# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
# endif
# ifndef MOUSE_MOVED
# define MOUSE_MOVED 0x0001
# endif
# ifndef DOUBLE_CLICK
# define DOUBLE_CLICK 0x0002
# endif
#endif
#ifdef MCH_WRITE_DUMP
FILE* fdDump = NULL;
#endif
#ifdef PROTO
#define WINAPI
#define WINBASEAPI
typedef char * LPCSTR;
typedef char * LPWSTR;
typedef int ACCESS_MASK;
typedef int BOOL;
typedef int COLORREF;
typedef int CONSOLE_CURSOR_INFO;
typedef int COORD;
typedef int DWORD;
typedef int HANDLE;
typedef int HDC;
typedef int HFONT;
typedef int HICON;
typedef int HINSTANCE;
typedef int HWND;
typedef int INPUT_RECORD;
typedef int KEY_EVENT_RECORD;
typedef int LOGFONT;
typedef int LPBOOL;
typedef int LPCTSTR;
typedef int LPDWORD;
typedef int LPSTR;
typedef int LPTSTR;
typedef int LPVOID;
typedef int MOUSE_EVENT_RECORD;
typedef int PACL;
typedef int PDWORD;
typedef int PHANDLE;
typedef int PRINTDLG;
typedef int PSECURITY_DESCRIPTOR;
typedef int PSID;
typedef int SECURITY_INFORMATION;
typedef int SHORT;
typedef int SMALL_RECT;
typedef int TEXTMETRIC;
typedef int TOKEN_INFORMATION_CLASS;
typedef int TRUSTEE;
typedef int WORD;
typedef int WCHAR;
typedef void VOID;
#endif
#ifndef FEAT_GUI_W32
#ifndef WINBASEAPI
# define WINBASEAPI __stdcall
#endif
#if defined(__BORLANDC__)
typedef BOOL (__stdcall *PFNGCKLN)(LPSTR);
#else
typedef WINBASEAPI BOOL (WINAPI *PFNGCKLN)(LPSTR);
#endif
static PFNGCKLN s_pfnGetConsoleKeyboardLayoutName = NULL;
#endif
#if defined(__BORLANDC__)
# define wcsicmp(a, b) wcscmpi((a), (b))
#endif
#ifndef FEAT_GUI_W32
static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
static SMALL_RECT g_srScrollRegion;
static COORD g_coord;
static WORD g_attrDefault = 7;
static WORD g_attrCurrent;
static int g_fCBrkPressed = FALSE;
static int g_fCtrlCPressed = FALSE;
static int g_fForceExit = FALSE;
static void termcap_mode_start(void);
static void termcap_mode_end(void);
static void clear_chars(COORD coord, DWORD n);
static void clear_screen(void);
static void clear_to_end_of_display(void);
static void clear_to_end_of_line(void);
static void scroll(unsigned cLines);
static void set_scroll_region(unsigned left, unsigned top,
unsigned right, unsigned bottom);
static void insert_lines(unsigned cLines);
static void delete_lines(unsigned cLines);
static void gotoxy(unsigned x, unsigned y);
static void normvideo(void);
static void textattr(WORD wAttr);
static void textcolor(WORD wAttr);
static void textbackground(WORD wAttr);
static void standout(void);
static void standend(void);
static void visual_bell(void);
static void cursor_visible(BOOL fVisible);
static BOOL write_chars(LPCSTR pchBuf, DWORD cchToWrite);
static char_u tgetch(int *pmodifiers, char_u *pch2);
static void create_conin(void);
static int s_cursor_visible = TRUE;
static int did_create_conin = FALSE;
#else
static int s_dont_use_vimrun = TRUE;
static int need_vimrun_warning = FALSE;
static char *vimrun_path = "vimrun ";
#endif
#ifndef FEAT_GUI_W32
static int suppress_winsize = 1;
#endif
static void
get_exe_name(void)
{
char temp[256];
static int did_set_PATH = FALSE;
if (exe_name == NULL)
{
GetModuleFileName(NULL, temp, 255);
if (*temp != NUL)
exe_name = FullName_save((char_u *)temp, FALSE);
}
if (!did_set_PATH && exe_name != NULL)
{
char_u *p;
char_u *newpath;
p = mch_getenv("PATH");
newpath = alloc((unsigned)(STRLEN(p) + STRLEN(exe_name) + 2));
if (newpath != NULL)
{
STRCPY(newpath, p);
STRCAT(newpath, ";");
vim_strncpy(newpath + STRLEN(newpath), exe_name,
gettail_sep(exe_name) - exe_name);
vim_setenv((char_u *)"PATH", newpath);
vim_free(newpath);
}
did_set_PATH = TRUE;
}
}
#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
# ifndef GETTEXT_DLL
# define GETTEXT_DLL "libintl.dll"
# endif
static char *null_libintl_gettext(const char *);
static char *null_libintl_textdomain(const char *);
static char *null_libintl_bindtextdomain(const char *, const char *);
static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
static HINSTANCE hLibintlDLL = 0;
char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
= null_libintl_bindtextdomain;
char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
= null_libintl_bind_textdomain_codeset;
int
dyn_libintl_init(char *libname)
{
int i;
static struct
{
char *name;
FARPROC *ptr;
} libintl_entry[] =
{
{"gettext", (FARPROC*)&dyn_libintl_gettext},
{"textdomain", (FARPROC*)&dyn_libintl_textdomain},
{"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
{NULL, NULL}
};
if (hLibintlDLL)
return 1;
hLibintlDLL = LoadLibrary(libname != NULL ? libname : GETTEXT_DLL);
if (!hLibintlDLL)
{
char_u dirname[_MAX_PATH];
get_exe_name();
STRCPY(dirname, exe_name);
STRCPY(gettail(dirname), GETTEXT_DLL);
hLibintlDLL = LoadLibrary((char *)dirname);
if (!hLibintlDLL)
{
if (p_verbose > 0)
{
verbose_enter();
EMSG2(_(e_loadlib), GETTEXT_DLL);
verbose_leave();
}
return 0;
}
}
for (i = 0; libintl_entry[i].name != NULL
&& libintl_entry[i].ptr != NULL; ++i)
{
if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
libintl_entry[i].name)) == NULL)
{
dyn_libintl_end();
if (p_verbose > 0)
{
verbose_enter();
EMSG2(_(e_loadfunc), libintl_entry[i].name);
verbose_leave();
}
return 0;
}
}
dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
"bind_textdomain_codeset");
if (dyn_libintl_bind_textdomain_codeset == NULL)
dyn_libintl_bind_textdomain_codeset =
null_libintl_bind_textdomain_codeset;
return 1;
}
void
dyn_libintl_end()
{
if (hLibintlDLL)
FreeLibrary(hLibintlDLL);
hLibintlDLL = NULL;
dyn_libintl_gettext = null_libintl_gettext;
dyn_libintl_textdomain = null_libintl_textdomain;
dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
}
static char *
null_libintl_gettext(const char *msgid)
{
return (char*)msgid;
}
static char *
null_libintl_bindtextdomain(const char *domainname, const char *dirname)
{
return NULL;
}
static char *
null_libintl_bind_textdomain_codeset(const char *domainname,
const char *codeset)
{
return NULL;
}
static char *
null_libintl_textdomain(const char *domainname)
{
return NULL;
}
#endif
#ifndef VER_PLATFORM_WIN32_WINDOWS
# define VER_PLATFORM_WIN32_WINDOWS 1
#endif
DWORD g_PlatformId;
#ifdef HAVE_ACL
# include <aclapi.h>
typedef DWORD (WINAPI *PSNSECINFO) (LPTSTR, enum SE_OBJECT_TYPE,
SECURITY_INFORMATION, PSID, PSID, PACL, PACL);
typedef DWORD (WINAPI *PGNSECINFO) (LPSTR, enum SE_OBJECT_TYPE,
SECURITY_INFORMATION, PSID *, PSID *, PACL *, PACL *,
PSECURITY_DESCRIPTOR *);
static HANDLE advapi_lib = NULL;
static PSNSECINFO pSetNamedSecurityInfo;
static PGNSECINFO pGetNamedSecurityInfo;
#endif
void
PlatformId(void)
{
static int done = FALSE;
if (!done)
{
OSVERSIONINFO ovi;
ovi.dwOSVersionInfoSize = sizeof(ovi);
GetVersionEx(&ovi);
g_PlatformId = ovi.dwPlatformId;
#ifdef HAVE_ACL
if (g_PlatformId == VER_PLATFORM_WIN32_NT)
{
advapi_lib = LoadLibrary("ADVAPI32.DLL");
if (advapi_lib != NULL)
{
pSetNamedSecurityInfo = (PSNSECINFO)GetProcAddress(advapi_lib,
"SetNamedSecurityInfoA");
pGetNamedSecurityInfo = (PGNSECINFO)GetProcAddress(advapi_lib,
"GetNamedSecurityInfoA");
if (pSetNamedSecurityInfo == NULL
|| pGetNamedSecurityInfo == NULL)
{
FreeLibrary(advapi_lib);
advapi_lib = NULL;
}
}
}
#endif
done = TRUE;
}
}
int
mch_windows95(void)
{
return g_PlatformId == VER_PLATFORM_WIN32_WINDOWS;
}
#ifdef FEAT_GUI_W32
static int old_num_windows;
static int num_windows;
static BOOL CALLBACK
win32ssynch_cb(HWND hwnd, LPARAM lparam)
{
num_windows++;
return TRUE;
}
#endif
#ifndef FEAT_GUI_W32
#define SHIFT (SHIFT_PRESSED)
#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
static const struct
{
WORD wVirtKey;
BOOL fAnsiKey;
int chAlone;
int chShift;
int chCtrl;
int chAlt;
} VirtKeyMap[] =
{
{ VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
{ VK_F1, TRUE, ';', 'T', '^', 'h', },
{ VK_F2, TRUE, '<', 'U', '_', 'i', },
{ VK_F3, TRUE, '=', 'V', '`', 'j', },
{ VK_F4, TRUE, '>', 'W', 'a', 'k', },
{ VK_F5, TRUE, '?', 'X', 'b', 'l', },
{ VK_F6, TRUE, '@', 'Y', 'c', 'm', },
{ VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
{ VK_F8, TRUE, 'B', '[', 'e', 'o', },
{ VK_F9, TRUE, 'C', '\\', 'f', 'p', },
{ VK_F10, TRUE, 'D', ']', 'g', 'q', },
{ VK_F11, TRUE, '\205', '\207', '\211', '\213', },
{ VK_F12, TRUE, '\206', '\210', '\212', '\214', },
{ VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
{ VK_UP, TRUE, 'H', '\304', '\305', '\306', },
{ VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', },
{ VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
{ VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
{ VK_END, TRUE, 'O', '\315', 'u', '\316', },
{ VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
{ VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', },
{ VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
{ VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
{ VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', },
#if 0
{ VK_F13, TRUE, '\332', '\333', '\334', '\335', },
{ VK_F14, TRUE, '\336', '\337', '\340', '\341', },
{ VK_F15, TRUE, '\342', '\343', '\344', '\345', },
{ VK_F16, TRUE, '\346', '\347', '\350', '\351', },
{ VK_F17, TRUE, '\352', '\353', '\354', '\355', },
{ VK_F18, TRUE, '\356', '\357', '\360', '\361', },
{ VK_F19, TRUE, '\362', '\363', '\364', '\365', },
{ VK_F20, TRUE, '\366', '\367', '\370', '\371', },
#endif
{ VK_ADD, TRUE, 'N', 'N', 'N', 'N', },
{ VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', },
{ VK_MULTIPLY, TRUE,'7', '7', '7', '7', },
{ VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
{ VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
{ VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
{ VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
{ VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
{ VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
{ VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
{ VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
{ VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
{ VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
};
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4748)
# pragma optimize("", off)
#endif
#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
# define AChar AsciiChar
#else
# define AChar uChar.AsciiChar
#endif
static int
#ifdef __BORLANDC__
__stdcall
#endif
win32_kbd_patch_key(
KEY_EVENT_RECORD *pker)
{
UINT uMods = pker->dwControlKeyState;
static int s_iIsDead = 0;
static WORD awAnsiCode[2];
static BYTE abKeystate[256];
if (s_iIsDead == 2)
{
pker->AChar = (CHAR) awAnsiCode[1];
s_iIsDead = 0;
return 1;
}
if (pker->AChar != 0)
return 1;
memset(abKeystate, 0, sizeof (abKeystate));
if (s_pfnGetConsoleKeyboardLayoutName != NULL)
{
CHAR szKLID[KL_NAMELENGTH];
if ((*s_pfnGetConsoleKeyboardLayoutName)(szKLID))
(void)LoadKeyboardLayout(szKLID, KLF_ACTIVATE);
}
ToAscii(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 0);
if (uMods & SHIFT_PRESSED)
abKeystate[VK_SHIFT] = 0x80;
if (uMods & CAPSLOCK_ON)
abKeystate[VK_CAPITAL] = 1;
if ((uMods & ALT_GR) == ALT_GR)
{
abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
}
s_iIsDead = ToAscii(pker->wVirtualKeyCode, pker->wVirtualScanCode,
abKeystate, awAnsiCode, 0);
if (s_iIsDead > 0)
pker->AChar = (CHAR) awAnsiCode[0];
return s_iIsDead;
}
#ifdef _MSC_VER
# pragma optimize("", on)
# pragma warning(pop)
# if (_MSC_VER < 1100)
# pragma optimize("g", off)
# endif
#endif
static BOOL g_fJustGotFocus = FALSE;
static BOOL
decode_key_event(
KEY_EVENT_RECORD *pker,
char_u *pch,
char_u *pch2,
int *pmodifiers,
BOOL fDoPost)
{
int i;
const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
*pch = *pch2 = NUL;
g_fJustGotFocus = FALSE;
if (!pker->bKeyDown)
return FALSE;
switch (pker->wVirtualKeyCode)
{
case VK_SHIFT:
case VK_CONTROL:
case VK_MENU:
return FALSE;
default:
break;
}
if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->AChar == NUL)
{
if (pker->wVirtualKeyCode == '6')
{
*pch = Ctrl_HAT;
return TRUE;
}
else if (pker->wVirtualKeyCode == '2')
{
*pch = NUL;
return TRUE;
}
else if (pker->wVirtualKeyCode == 0xBD)
{
*pch = Ctrl__;
return TRUE;
}
}
if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
{
*pch = K_NUL;
*pch2 = '\017';
return TRUE;
}
for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
{
if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
{
if (nModifs == 0)
*pch = VirtKeyMap[i].chAlone;
else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
*pch = VirtKeyMap[i].chShift;
else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
*pch = VirtKeyMap[i].chCtrl;
else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
*pch = VirtKeyMap[i].chAlt;
if (*pch != 0)
{
if (VirtKeyMap[i].fAnsiKey)
{
*pch2 = *pch;
*pch = K_NUL;
}
return TRUE;
}
}
}
i = win32_kbd_patch_key(pker);
if (i < 0)
*pch = NUL;
else
{
*pch = (i > 0) ? pker->AChar : NUL;
if (pmodifiers != NULL)
{
if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
*pmodifiers |= MOD_MASK_ALT;
if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
*pmodifiers |= MOD_MASK_SHIFT;
if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
&& *pch >= 0x20 && *pch < 0x80)
*pmodifiers |= MOD_MASK_CTRL;
}
}
return (*pch != NUL);
}
#ifdef _MSC_VER
# pragma optimize("", on)
#endif
#endif
#ifdef FEAT_MOUSE
# ifdef FEAT_GUI_W32
void
mch_setmouse(int on)
{
}
# else
static int g_fMouseAvail = FALSE;
static int g_fMouseActive = FALSE;
static int g_nMouseClick = -1;
static int g_xMouse;
static int g_yMouse;
void
mch_setmouse(int on)
{
DWORD cmodein;
if (!g_fMouseAvail)
return;
g_fMouseActive = on;
GetConsoleMode(g_hConIn, &cmodein);
if (g_fMouseActive)
cmodein |= ENABLE_MOUSE_INPUT;
else
cmodein &= ~ENABLE_MOUSE_INPUT;
SetConsoleMode(g_hConIn, cmodein);
}
static BOOL
decode_mouse_event(
MOUSE_EVENT_RECORD *pmer)
{
static int s_nOldButton = -1;
static int s_nOldMouseClick = -1;
static int s_xOldMouse = -1;
static int s_yOldMouse = -1;
static linenr_T s_old_topline = 0;
#ifdef FEAT_DIFF
static int s_old_topfill = 0;
#endif
static int s_cClicks = 1;
static BOOL s_fReleased = TRUE;
static DWORD s_dwLastClickTime = 0;
static BOOL s_fNextIsMiddle = FALSE;
static DWORD cButtons = 0;
const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
const DWORD LEFT_RIGHT = LEFT | RIGHT;
int nButton;
if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
cButtons = 2;
if (!g_fMouseAvail || !g_fMouseActive)
{
g_nMouseClick = -1;
return FALSE;
}
if (g_fJustGotFocus)
{
g_fJustGotFocus = FALSE;
return FALSE;
}
if (g_nMouseClick != -1)
return TRUE;
nButton = -1;
g_xMouse = pmer->dwMousePosition.X;
g_yMouse = pmer->dwMousePosition.Y;
if (pmer->dwEventFlags == MOUSE_MOVED)
{
if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
return FALSE;
}
if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
{
if (s_fReleased)
return FALSE;
nButton = MOUSE_RELEASE;
s_fReleased = TRUE;
}
else
{
if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
{
DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
if (dwLR == LEFT || dwLR == RIGHT)
{
for (;;)
{
if (WaitForSingleObject(g_hConIn, p_mouset / 3)
!= WAIT_OBJECT_0)
break;
else
{
DWORD cRecords = 0;
INPUT_RECORD ir;
MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
if (cRecords == 0 || ir.EventType != MOUSE_EVENT
|| !(pmer2->dwButtonState & LEFT_RIGHT))
break;
else
{
if (pmer2->dwEventFlags != MOUSE_MOVED)
{
ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
return decode_mouse_event(pmer2);
}
else if (s_xOldMouse == pmer2->dwMousePosition.X &&
s_yOldMouse == pmer2->dwMousePosition.Y)
{
ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
if (cRecords==0 || ir.EventType != MOUSE_EVENT)
break;
}
else
break;
}
}
}
}
}
if (s_fNextIsMiddle)
{
nButton = (pmer->dwEventFlags == MOUSE_MOVED)
? MOUSE_DRAG : MOUSE_MIDDLE;
s_fNextIsMiddle = FALSE;
}
else if (cButtons == 2 &&
((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
{
nButton = MOUSE_MIDDLE;
if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
{
s_fNextIsMiddle = TRUE;
nButton = MOUSE_RELEASE;
}
}
else if ((pmer->dwButtonState & LEFT) == LEFT)
nButton = MOUSE_LEFT;
else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
nButton = MOUSE_MIDDLE;
else if ((pmer->dwButtonState & RIGHT) == RIGHT)
nButton = MOUSE_RIGHT;
if (! s_fReleased && ! s_fNextIsMiddle
&& nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
return FALSE;
s_fReleased = s_fNextIsMiddle;
}
if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
{
if (nButton != -1 && nButton != MOUSE_RELEASE)
{
DWORD dwCurrentTime = GetTickCount();
if (s_xOldMouse != g_xMouse
|| s_yOldMouse != g_yMouse
|| s_nOldButton != nButton
|| s_old_topline != curwin->w_topline
#ifdef FEAT_DIFF
|| s_old_topfill != curwin->w_topfill
#endif
|| (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
{
s_cClicks = 1;
}
else if (++s_cClicks > 4)
{
s_cClicks = 1;
}
s_dwLastClickTime = dwCurrentTime;
}
}
else if (pmer->dwEventFlags == MOUSE_MOVED)
{
if (nButton != -1 && nButton != MOUSE_RELEASE)
nButton = MOUSE_DRAG;
s_cClicks = 1;
}
if (nButton == -1)
return FALSE;
if (nButton != MOUSE_RELEASE)
s_nOldButton = nButton;
g_nMouseClick = nButton;
if (pmer->dwControlKeyState & SHIFT_PRESSED)
g_nMouseClick |= MOUSE_SHIFT;
if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
g_nMouseClick |= MOUSE_CTRL;
if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
g_nMouseClick |= MOUSE_ALT;
if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
if (s_xOldMouse == g_xMouse
&& s_yOldMouse == g_yMouse
&& s_nOldMouseClick == g_nMouseClick)
{
g_nMouseClick = -1;
return FALSE;
}
s_xOldMouse = g_xMouse;
s_yOldMouse = g_yMouse;
s_old_topline = curwin->w_topline;
#ifdef FEAT_DIFF
s_old_topfill = curwin->w_topfill;
#endif
s_nOldMouseClick = g_nMouseClick;
return TRUE;
}
# endif
#endif
#ifdef MCH_CURSOR_SHAPE
static void
mch_set_cursor_shape(int thickness)
{
CONSOLE_CURSOR_INFO ConsoleCursorInfo;
ConsoleCursorInfo.dwSize = thickness;
ConsoleCursorInfo.bVisible = s_cursor_visible;
SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
if (s_cursor_visible)
SetConsoleCursorPosition(g_hConOut, g_coord);
}
void
mch_update_cursor(void)
{
int idx;
int thickness;
idx = get_shape_idx(FALSE);
if (shape_table[idx].shape == SHAPE_BLOCK)
thickness = 99;
else
thickness = shape_table[idx].percentage;
mch_set_cursor_shape(thickness);
}
#endif
#ifndef FEAT_GUI_W32
static void
handle_focus_event(INPUT_RECORD ir)
{
g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
ui_focus_change((int)g_fJustGotFocus);
}
static int
WaitForChar(long msec)
{
DWORD dwNow = 0, dwEndTime = 0;
INPUT_RECORD ir;
DWORD cRecords;
char_u ch, ch2;
if (msec > 0)
dwEndTime = GetTickCount() + msec;
else if (msec < 0)
dwEndTime = INFINITE;
for (;;)
{
#ifdef FEAT_MZSCHEME
mzvim_check_threads();
#endif
#ifdef FEAT_CLIENTSERVER
serverProcessPendingMessages();
#endif
if (0
#ifdef FEAT_MOUSE
|| g_nMouseClick != -1
#endif
#ifdef FEAT_CLIENTSERVER
|| input_available()
#endif
)
return TRUE;
if (msec > 0)
{
dwNow = GetTickCount();
if (dwNow >= dwEndTime)
break;
}
if (msec != 0)
{
DWORD dwWaitTime = dwEndTime - dwNow;
#ifdef FEAT_MZSCHEME
if (mzthreads_allowed() && p_mzq > 0
&& (msec < 0 || (long)dwWaitTime > p_mzq))
dwWaitTime = p_mzq;
#endif
#ifdef FEAT_CLIENTSERVER
if (MsgWaitForMultipleObjects(1, &g_hConIn, FALSE,
dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
#else
if (WaitForSingleObject(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
#endif
continue;
}
cRecords = 0;
PeekConsoleInput(g_hConIn, &ir, 1, &cRecords);
#ifdef FEAT_MBYTE_IME
if (State & CMDLINE && msg_row == Rows - 1)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
{
if (csbi.dwCursorPosition.Y != msg_row)
{
redraw_all_later(CLEAR);
cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
redrawcmd();
}
}
}
#endif
if (cRecords > 0)
{
if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
{
#ifdef FEAT_MBYTE_IME
if (ir.Event.KeyEvent.uChar.UnicodeChar == 0
&& ir.Event.KeyEvent.wVirtualKeyCode == 13)
{
ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
continue;
}
#endif
if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
NULL, FALSE))
return TRUE;
}
ReadConsoleInput(g_hConIn, &ir, 1, &cRecords);
if (ir.EventType == FOCUS_EVENT)
handle_focus_event(ir);
else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
shell_resized();
#ifdef FEAT_MOUSE
else if (ir.EventType == MOUSE_EVENT
&& decode_mouse_event(&ir.Event.MouseEvent))
return TRUE;
#endif
}
else if (msec == 0)
break;
}
#ifdef FEAT_CLIENTSERVER
if (input_available())
return TRUE;
#endif
return FALSE;
}
#ifndef FEAT_GUI_MSWIN
int
mch_char_avail(void)
{
return WaitForChar(0L);
}
#endif
static void
create_conin(void)
{
g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
(LPSECURITY_ATTRIBUTES) NULL,
OPEN_EXISTING, 0, (HANDLE)NULL);
did_create_conin = TRUE;
}
static char_u
tgetch(int *pmodifiers, char_u *pch2)
{
char_u ch;
for (;;)
{
INPUT_RECORD ir;
DWORD cRecords = 0;
#ifdef FEAT_CLIENTSERVER
(void)WaitForChar(-1L);
if (input_available())
return 0;
# ifdef FEAT_MOUSE
if (g_nMouseClick != -1)
return 0;
# endif
#endif
if (ReadConsoleInput(g_hConIn, &ir, 1, &cRecords) == 0)
{
if (did_create_conin)
read_error_exit();
create_conin();
continue;
}
if (ir.EventType == KEY_EVENT)
{
if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
pmodifiers, TRUE))
return ch;
}
else if (ir.EventType == FOCUS_EVENT)
handle_focus_event(ir);
else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
shell_resized();
#ifdef FEAT_MOUSE
else if (ir.EventType == MOUSE_EVENT)
{
if (decode_mouse_event(&ir.Event.MouseEvent))
return 0;
}
#endif
}
}
#endif
int
mch_inchar(
char_u *buf,
int maxlen,
long time,
int tb_change_cnt)
{
#ifndef FEAT_GUI_W32
int len;
int c;
#define TYPEAHEADLEN 20
static char_u typeahead[TYPEAHEADLEN];
static int typeaheadlen = 0;
if (typeaheadlen > 0)
goto theend;
#ifdef FEAT_SNIFF
if (want_sniff_request)
{
if (sniff_request_waiting)
{
typeahead[typeaheadlen++] = CSI;
typeahead[typeaheadlen++] = (char_u)KS_EXTRA;
typeahead[typeaheadlen++] = (char_u)KE_SNIFF;
sniff_request_waiting = 0;
want_sniff_request = 0;
goto theend;
}
else if (time < 0 || time > 250)
{
time = 250;
}
}
#endif
if (time >= 0)
{
if (!WaitForChar(time))
return 0;
}
else
{
mch_set_winsize_now();
if (!WaitForChar(p_ut))
{
#ifdef FEAT_AUTOCMD
if (trigger_cursorhold() && maxlen >= 3)
{
buf[0] = K_SPECIAL;
buf[1] = KS_EXTRA;
buf[2] = (int)KE_CURSORHOLD;
return 3;
}
#endif
before_blocking();
}
}
g_fCBrkPressed = FALSE;
#ifdef MCH_WRITE_DUMP
if (fdDump)
fputc('[', fdDump);
#endif
while ((typeaheadlen == 0 || WaitForChar(0L))
&& typeaheadlen + 5 <= TYPEAHEADLEN)
{
if (typebuf_changed(tb_change_cnt))
{
typeaheadlen = 0;
break;
}
#ifdef FEAT_MOUSE
if (g_nMouseClick != -1)
{
# ifdef MCH_WRITE_DUMP
if (fdDump)
fprintf(fdDump, "{%02x @ %d, %d}",
g_nMouseClick, g_xMouse, g_yMouse);
# endif
typeahead[typeaheadlen++] = ESC + 128;
typeahead[typeaheadlen++] = 'M';
typeahead[typeaheadlen++] = g_nMouseClick;
typeahead[typeaheadlen++] = g_xMouse + '!';
typeahead[typeaheadlen++] = g_yMouse + '!';
g_nMouseClick = -1;
}
else
#endif
{
char_u ch2 = NUL;
int modifiers = 0;
c = tgetch(&modifiers, &ch2);
if (typebuf_changed(tb_change_cnt))
{
typeaheadlen = 0;
break;
}
if (c == Ctrl_C && ctrl_c_interrupts)
{
#if defined(FEAT_CLIENTSERVER)
trash_input_buf();
#endif
got_int = TRUE;
}
#ifdef FEAT_MOUSE
if (g_nMouseClick == -1)
#endif
{
int n = 1;
typeahead[typeaheadlen] = c;
if (ch2 != NUL)
{
typeahead[typeaheadlen + 1] = ch2;
++n;
}
#ifdef FEAT_MBYTE
if (input_conv.vc_type != CONV_NONE
&& (ch2 == NUL || c != K_NUL))
n = convert_input(typeahead + typeaheadlen, n,
TYPEAHEADLEN - typeaheadlen);
#endif
if ((modifiers & MOD_MASK_ALT)
&& n == 1
&& (typeahead[typeaheadlen] & 0x80) == 0
#ifdef FEAT_MBYTE
&& !enc_dbcs
#endif
)
{
typeahead[typeaheadlen] |= 0x80;
modifiers &= ~MOD_MASK_ALT;
}
if (modifiers != 0)
{
mch_memmove(typeahead + typeaheadlen + 3,
typeahead + typeaheadlen, n);
typeahead[typeaheadlen++] = K_SPECIAL;
typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
typeahead[typeaheadlen++] = modifiers;
}
typeaheadlen += n;
#ifdef MCH_WRITE_DUMP
if (fdDump)
fputc(c, fdDump);
#endif
}
}
}
#ifdef MCH_WRITE_DUMP
if (fdDump)
{
fputs("]\n", fdDump);
fflush(fdDump);
}
#endif
theend:
len = 0;
while (len < maxlen && typeaheadlen > 0)
{
buf[len++] = typeahead[0];
mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
}
return len;
#else
return 0;
#endif
}
#ifndef __MINGW32__
# include <shellapi.h>
#endif
static int
executable_exists(char *name)
{
char *dum;
char fname[_MAX_PATH];
#ifdef FEAT_MBYTE
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
{
WCHAR *p = enc_to_ucs2(name, NULL);
WCHAR fnamew[_MAX_PATH];
WCHAR *dumw;
long n;
if (p != NULL)
{
n = (long)SearchPathW(NULL, p, NULL, _MAX_PATH, fnamew, &dumw);
vim_free(p);
if (n > 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
{
if (n == 0)
return FALSE;
if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
return FALSE;
return TRUE;
}
}
}
#endif
if (SearchPath(NULL, name, NULL, _MAX_PATH, fname, &dum) == 0)
return FALSE;
if (mch_isdir(fname))
return FALSE;
return TRUE;
}
#ifdef FEAT_GUI_W32
void
mch_init(void)
{
#ifndef __MINGW32__
extern int _fmode;
#endif
SetErrorMode(SEM_FAILCRITICALERRORS);
_fmode = O_BINARY;
Rows = 25;
Columns = 80;
if (!gui_is_win32s())
{
char_u vimrun_location[_MAX_PATH + 4];
STRCPY(vimrun_location, exe_name);
STRCPY(gettail(vimrun_location), "vimrun.exe");
if (mch_getperm(vimrun_location) >= 0)
{
if (*skiptowhite(vimrun_location) != NUL)
{
mch_memmove(vimrun_location + 1, vimrun_location,
STRLEN(vimrun_location) + 1);
*vimrun_location = '"';
STRCPY(gettail(vimrun_location), "vimrun\" ");
}
else
STRCPY(gettail(vimrun_location), "vimrun ");
vimrun_path = (char *)vim_strsave(vimrun_location);
s_dont_use_vimrun = FALSE;
}
else if (executable_exists("vimrun.exe"))
s_dont_use_vimrun = FALSE;
if (s_dont_use_vimrun)
need_vimrun_warning = TRUE;
}
if (!executable_exists("findstr.exe"))
set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
#ifdef FEAT_CLIPBOARD
clip_init(TRUE);
clip_star.format = RegisterClipboardFormat("VimClipboard2");
clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
#endif
}
#else
#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
static BOOL
ClearConsoleBuffer(WORD wAttribute)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
COORD coord;
DWORD NumCells, dummy;
if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
return FALSE;
NumCells = csbi.dwSize.X * csbi.dwSize.Y;
coord.X = 0;
coord.Y = 0;
if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
coord, &dummy))
{
return FALSE;
}
if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
coord, &dummy))
{
return FALSE;
}
return TRUE;
}
static BOOL
FitConsoleWindow(
COORD dwBufferSize,
BOOL WantAdjust)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
COORD dwWindowSize;
BOOL NeedAdjust = FALSE;
if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
{
if (csbi.srWindow.Right >= dwBufferSize.X)
{
dwWindowSize.X = SRWIDTH(csbi.srWindow);
if (dwWindowSize.X > dwBufferSize.X)
dwWindowSize.X = dwBufferSize.X;
csbi.srWindow.Right = dwBufferSize.X - 1;
csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
NeedAdjust = TRUE;
}
if (csbi.srWindow.Bottom >= dwBufferSize.Y)
{
dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
if (dwWindowSize.Y > dwBufferSize.Y)
dwWindowSize.Y = dwBufferSize.Y;
csbi.srWindow.Bottom = dwBufferSize.Y - 1;
csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
NeedAdjust = TRUE;
}
if (NeedAdjust && WantAdjust)
{
if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
return FALSE;
}
return TRUE;
}
return FALSE;
}
typedef struct ConsoleBufferStruct
{
BOOL IsValid;
CONSOLE_SCREEN_BUFFER_INFO Info;
PCHAR_INFO Buffer;
COORD BufferSize;
} ConsoleBuffer;
static BOOL
SaveConsoleBuffer(
ConsoleBuffer *cb)
{
DWORD NumCells;
COORD BufferCoord;
SMALL_RECT ReadRegion;
WORD Y, Y_incr;
if (cb == NULL)
return FALSE;
if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
{
cb->IsValid = FALSE;
return FALSE;
}
cb->IsValid = TRUE;
if (!cb->IsValid || cb->Buffer == NULL ||
cb->BufferSize.X != cb->Info.dwSize.X ||
cb->BufferSize.Y != cb->Info.dwSize.Y)
{
cb->BufferSize.X = cb->Info.dwSize.X;
cb->BufferSize.Y = cb->Info.dwSize.Y;
NumCells = cb->BufferSize.X * cb->BufferSize.Y;
if (cb->Buffer != NULL)
vim_free(cb->Buffer);
cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
if (cb->Buffer == NULL)
return FALSE;
}
BufferCoord.X = 0;
ReadRegion.Left = 0;
ReadRegion.Right = cb->Info.dwSize.X - 1;
Y_incr = 12000 / cb->Info.dwSize.X;
for (Y = 0; Y < cb->BufferSize.Y; Y += Y_incr)
{
BufferCoord.Y = Y;
ReadRegion.Top = Y;
ReadRegion.Bottom = Y + Y_incr - 1;
if (!ReadConsoleOutput(g_hConOut,
cb->Buffer,
cb->BufferSize,
BufferCoord,
&ReadRegion))
{
vim_free(cb->Buffer);
cb->Buffer = NULL;
return FALSE;
}
}
return TRUE;
}
static BOOL
RestoreConsoleBuffer(
ConsoleBuffer *cb,
BOOL RestoreScreen)
{
COORD BufferCoord;
SMALL_RECT WriteRegion;
if (cb == NULL || !cb->IsValid)
return FALSE;
if (RestoreScreen)
ClearConsoleBuffer(cb->Info.wAttributes);
FitConsoleWindow(cb->Info.dwSize, TRUE);
if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
return FALSE;
if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
return FALSE;
if (!RestoreScreen)
{
return TRUE;
}
if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
return FALSE;
if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
return FALSE;
if (cb->Buffer != NULL)
{
BufferCoord.X = 0;
BufferCoord.Y = 0;
WriteRegion.Left = 0;
WriteRegion.Top = 0;
WriteRegion.Right = cb->Info.dwSize.X - 1;
WriteRegion.Bottom = cb->Info.dwSize.Y - 1;
if (!WriteConsoleOutput(g_hConOut,
cb->Buffer,
cb->BufferSize,
BufferCoord,
&WriteRegion))
{
return FALSE;
}
}
return TRUE;
}
#define FEAT_RESTORE_ORIG_SCREEN
#ifdef FEAT_RESTORE_ORIG_SCREEN
static ConsoleBuffer g_cbOrig = { 0 };
#endif
static ConsoleBuffer g_cbNonTermcap = { 0 };
static ConsoleBuffer g_cbTermcap = { 0 };
#ifdef FEAT_TITLE
#ifdef __BORLANDC__
typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
#else
typedef WINBASEAPI HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
#endif
char g_szOrigTitle[256] = { 0 };
HWND g_hWnd = NULL;
static HICON g_hOrigIconSmall = NULL;
static HICON g_hOrigIcon = NULL;
static HICON g_hVimIcon = NULL;
static BOOL g_fCanChangeIcon = FALSE;
#ifndef ICON_SMALL
#define ICON_SMALL 0
#endif
#ifndef ICON_BIG
#define ICON_BIG 1
#endif
static BOOL
GetConsoleIcon(
HWND hWnd,
HICON *phIconSmall,
HICON *phIcon)
{
if (hWnd == NULL)
return FALSE;
if (phIconSmall != NULL)
*phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
(WPARAM)ICON_SMALL, (LPARAM)0);
if (phIcon != NULL)
*phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
(WPARAM)ICON_BIG, (LPARAM)0);
return TRUE;
}
static BOOL
SetConsoleIcon(
HWND hWnd,
HICON hIconSmall,
HICON hIcon)
{
HICON hPrevIconSmall;
HICON hPrevIcon;
if (hWnd == NULL)
return FALSE;
if (hIconSmall != NULL)
hPrevIconSmall = (HICON)SendMessage(hWnd, WM_SETICON,
(WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
if (hIcon != NULL)
hPrevIcon = (HICON)SendMessage(hWnd, WM_SETICON,
(WPARAM)ICON_BIG,(LPARAM) hIcon);
return TRUE;
}
static void
SaveConsoleTitleAndIcon(void)
{
GETCONSOLEWINDOWPROC GetConsoleWindowProc;
if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
return;
if ((GetConsoleWindowProc = (GETCONSOLEWINDOWPROC)
GetProcAddress(GetModuleHandle("KERNEL32.DLL"),
"GetConsoleWindow")) != NULL)
{
g_hWnd = (*GetConsoleWindowProc)();
}
if (g_hWnd == NULL)
return;
GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
return;
g_hVimIcon = ExtractIcon(NULL, exe_name, 0);
if (g_hVimIcon != NULL)
g_fCanChangeIcon = TRUE;
}
#endif
static int g_fWindInitCalled = FALSE;
static int g_fTermcapMode = FALSE;
static CONSOLE_CURSOR_INFO g_cci;
static DWORD g_cmodein = 0;
static DWORD g_cmodeout = 0;
void
mch_init(void)
{
#ifndef FEAT_RESTORE_ORIG_SCREEN
CONSOLE_SCREEN_BUFFER_INFO csbi;
#endif
#ifndef __MINGW32__
extern int _fmode;
#endif
SetErrorMode(SEM_FAILCRITICALERRORS);
_fmode = O_BINARY;
out_flush();
if (read_cmd_fd == 0)
g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
else
create_conin();
g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
#ifdef FEAT_RESTORE_ORIG_SCREEN
SaveConsoleBuffer(&g_cbOrig);
g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
#else
GetConsoleScreenBufferInfo(g_hConOut, &csbi);
g_attrCurrent = g_attrDefault = csbi.wAttributes;
#endif
if (cterm_normal_fg_color == 0)
cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
if (cterm_normal_bg_color == 0)
cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
update_tcap(g_attrCurrent);
GetConsoleCursorInfo(g_hConOut, &g_cci);
GetConsoleMode(g_hConIn, &g_cmodein);
GetConsoleMode(g_hConOut, &g_cmodeout);
#ifdef FEAT_TITLE
SaveConsoleTitleAndIcon();
if (g_fCanChangeIcon)
SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
#endif
ui_get_shellsize();
#ifdef MCH_WRITE_DUMP
fdDump = fopen("dump", "wt");
if (fdDump)
{
time_t t;
time(&t);
fputs(ctime(&t), fdDump);
fflush(fdDump);
}
#endif
g_fWindInitCalled = TRUE;
#ifdef FEAT_MOUSE
g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
#endif
#ifdef FEAT_CLIPBOARD
clip_init(TRUE);
clip_star.format = RegisterClipboardFormat("VimClipboard2");
clip_star.format_raw = RegisterClipboardFormat("VimRawBytes");
#endif
s_pfnGetConsoleKeyboardLayoutName =
(PFNGCKLN) GetProcAddress(GetModuleHandle("kernel32.dll"),
"GetConsoleKeyboardLayoutNameA");
}
void
mch_exit(int r)
{
stoptermcap();
if (g_fWindInitCalled)
settmode(TMODE_COOK);
ml_close_all(TRUE);
if (g_fWindInitCalled)
{
#ifdef FEAT_TITLE
mch_restore_title(3);
if (g_fCanChangeIcon && !g_fForceExit)
SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
#endif
#ifdef MCH_WRITE_DUMP
if (fdDump)
{
time_t t;
time(&t);
fputs(ctime(&t), fdDump);
fclose(fdDump);
}
fdDump = NULL;
#endif
}
SetConsoleCursorInfo(g_hConOut, &g_cci);
SetConsoleMode(g_hConIn, g_cmodein);
SetConsoleMode(g_hConOut, g_cmodeout);
#ifdef DYNAMIC_GETTEXT
dyn_libintl_end();
#endif
exit(r);
}
#endif
int
mch_check_win(
int argc,
char **argv)
{
get_exe_name();
#ifdef FEAT_GUI_W32
return OK;
#else
if (isatty(1))
return OK;
return FAIL;
#endif
}
void
fname_case(
char_u *name,
int len)
{
char szTrueName[_MAX_PATH + 2];
char *ptrue, *ptruePrev;
char *porig, *porigPrev;
int flen;
WIN32_FIND_DATA fb;
HANDLE hFind;
int c;
flen = (int)STRLEN(name);
if (flen == 0 || flen > _MAX_PATH)
return;
slash_adjust(name);
porig = name;
ptrue = szTrueName;
if (isalpha(porig[0]) && porig[1] == ':')
{
*ptrue++ = *porig++;
*ptrue++ = *porig++;
*ptrue = NUL;
}
while (*porig != NUL)
{
while (*porig == psepc)
*ptrue++ = *porig++;
ptruePrev = ptrue;
porigPrev = porig;
while (*porig != NUL && *porig != psepc)
{
#ifdef FEAT_MBYTE
int l;
if (enc_dbcs)
{
l = (*mb_ptr2len)(porig);
while (--l >= 0)
*ptrue++ = *porig++;
}
else
#endif
*ptrue++ = *porig++;
}
*ptrue = NUL;
if (ptrue > ptruePrev
&& (ptruePrev[0] != '.'
|| (ptruePrev[1] != NUL
&& (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
&& (hFind = FindFirstFile(szTrueName, &fb))
!= INVALID_HANDLE_VALUE)
{
c = *porig;
*porig = NUL;
if (_stricoll(porigPrev, fb.cFileName) == 0
|| (len > 0
&& (_stricoll(porigPrev, fb.cAlternateFileName) == 0
&& (int)(ptruePrev - szTrueName)
+ (int)strlen(fb.cFileName) < len)))
{
STRCPY(ptruePrev, fb.cFileName);
while (FindNextFile(hFind, &fb))
{
if (*fb.cAlternateFileName != NUL
&& (strcoll(porigPrev, fb.cFileName) == 0
|| (len > 0
&& (_stricoll(porigPrev,
fb.cAlternateFileName) == 0
&& (int)(ptruePrev - szTrueName)
+ (int)strlen(fb.cFileName) < len))))
{
STRCPY(ptruePrev, fb.cFileName);
break;
}
}
}
FindClose(hFind);
*porig = c;
ptrue = ptruePrev + strlen(ptruePrev);
}
}
STRCPY(name, szTrueName);
}
int
mch_get_user_name(
char_u *s,
int len)
{
char szUserName[MAX_COMPUTERNAME_LENGTH + 1];
DWORD cch = sizeof szUserName;
if (GetUserName(szUserName, &cch))
{
vim_strncpy(s, szUserName, len - 1);
return OK;
}
s[0] = NUL;
return FAIL;
}
void
mch_get_host_name(
char_u *s,
int len)
{
DWORD cch = len;
if (!GetComputerName(s, &cch))
vim_strncpy(s, "PC (Win32 Vim)", len - 1);
}
long
mch_get_pid(void)
{
return (long)GetCurrentProcessId();
}
int
mch_dirname(
char_u *buf,
int len)
{
#ifdef FEAT_MBYTE
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
{
WCHAR wbuf[_MAX_PATH + 1];
if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
{
char_u *p = ucs2_to_enc(wbuf, NULL);
if (p != NULL)
{
vim_strncpy(buf, p, len - 1);
vim_free(p);
return OK;
}
}
}
#endif
return (GetCurrentDirectory(len, buf) != 0 ? OK : FAIL);
}
long
mch_getperm(char_u *name)
{
#ifdef FEAT_MBYTE
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
{
WCHAR *p = enc_to_ucs2(name, NULL);
long n;
if (p != NULL)
{
n = (long)GetFileAttributesW(p);
vim_free(p);
if (n >= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return n;
}
}
#endif
return (long)GetFileAttributes((char *)name);
}
int
mch_setperm(
char_u *name,
long perm)
{
perm |= FILE_ATTRIBUTE_ARCHIVE;
#ifdef FEAT_MBYTE
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
{
WCHAR *p = enc_to_ucs2(name, NULL);
long n;
if (p != NULL)
{
n = (long)SetFileAttributesW(p, perm);
vim_free(p);
if (n || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return n ? OK : FAIL;
}
}
#endif
return SetFileAttributes((char *)name, perm) ? OK : FAIL;
}
void
mch_hide(char_u *name)
{
int perm;
#ifdef FEAT_MBYTE
WCHAR *p = NULL;
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
p = enc_to_ucs2(name, NULL);
#endif
#ifdef FEAT_MBYTE
if (p != NULL)
{
perm = GetFileAttributesW(p);
if (perm < 0 && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
vim_free(p);
p = NULL;
}
}
if (p == NULL)
#endif
perm = GetFileAttributes((char *)name);
if (perm >= 0)
{
perm |= FILE_ATTRIBUTE_HIDDEN;
#ifdef FEAT_MBYTE
if (p != NULL)
{
if (SetFileAttributesW(p, perm) == 0
&& GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
vim_free(p);
p = NULL;
}
}
if (p == NULL)
#endif
SetFileAttributes((char *)name, perm);
}
#ifdef FEAT_MBYTE
vim_free(p);
#endif
}
int
mch_isdir(char_u *name)
{
int f = mch_getperm(name);
if (f == -1)
return FALSE;
return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
int
mch_is_linked(char_u *fname)
{
HANDLE hFile;
int res = 0;
BY_HANDLE_FILE_INFORMATION inf;
#ifdef FEAT_MBYTE
WCHAR *wn = NULL;
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
wn = enc_to_ucs2(fname, NULL);
if (wn != NULL)
{
hFile = CreateFileW(wn,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE
&& GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
vim_free(wn);
wn = NULL;
}
}
if (wn == NULL)
#endif
hFile = CreateFile(fname,
GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
if (GetFileInformationByHandle(hFile, &inf) != 0
&& inf.nNumberOfLinks > 1)
res = 1;
CloseHandle(hFile);
}
#ifdef FEAT_MBYTE
vim_free(wn);
#endif
return res;
}
int
mch_writable(char_u *name)
{
int perm = mch_getperm(name);
return (perm != -1 && (!(perm & FILE_ATTRIBUTE_READONLY)
|| (perm & FILE_ATTRIBUTE_DIRECTORY)));
}
int
mch_can_exe(char_u *name)
{
char_u buf[_MAX_PATH];
int len = (int)STRLEN(name);
char_u *p;
if (len >= _MAX_PATH)
return FALSE;
if (vim_strchr(gettail(name), '.') != NULL
|| strstr((char *)gettail(p_sh), "sh") != NULL)
if (executable_exists((char *)name))
return TRUE;
vim_strncpy(buf, name, _MAX_PATH - 1);
p = mch_getenv("PATHEXT");
if (p == NULL)
p = (char_u *)".com;.exe;.bat;.cmd";
while (*p)
{
if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
{
buf[len] = NUL;
++p;
if (*p)
++p;
}
else
copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
if (executable_exists((char *)buf))
return TRUE;
}
return FALSE;
}
int
mch_nodetype(char_u *name)
{
HANDLE hFile;
int type;
hFile = CreateFile(name,
GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
return NODE_NORMAL;
type = GetFileType(hFile);
CloseHandle(hFile);
if (type == FILE_TYPE_CHAR)
return NODE_WRITABLE;
if (type == FILE_TYPE_DISK)
return NODE_NORMAL;
return NODE_OTHER;
}
#ifdef HAVE_ACL
struct my_acl
{
PSECURITY_DESCRIPTOR pSecurityDescriptor;
PSID pSidOwner;
PSID pSidGroup;
PACL pDacl;
PACL pSacl;
};
#endif
vim_acl_T
mch_get_acl(char_u *fname)
{
#ifndef HAVE_ACL
return (vim_acl_T)NULL;
#else
struct my_acl *p = NULL;
if (g_PlatformId == VER_PLATFORM_WIN32_NT && advapi_lib != NULL)
{
p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
if (p != NULL)
{
if (pGetNamedSecurityInfo(
(LPTSTR)fname, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION |
GROUP_SECURITY_INFORMATION |
DACL_SECURITY_INFORMATION |
SACL_SECURITY_INFORMATION,
&p->pSidOwner, &p->pSidGroup, &p->pDacl, &p->pSacl, &p->pSecurityDescriptor
) != ERROR_SUCCESS)
{
mch_free_acl((vim_acl_T)p);
p = NULL;
}
}
}
return (vim_acl_T)p;
#endif
}
void
mch_set_acl(char_u *fname, vim_acl_T acl)
{
#ifdef HAVE_ACL
struct my_acl *p = (struct my_acl *)acl;
if (p != NULL && advapi_lib != NULL)
(void)pSetNamedSecurityInfo(
(LPTSTR)fname, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION |
GROUP_SECURITY_INFORMATION |
DACL_SECURITY_INFORMATION |
SACL_SECURITY_INFORMATION,
p->pSidOwner, p->pSidGroup, p->pDacl, p->pSacl );
#endif
}
void
mch_free_acl(vim_acl_T acl)
{
#ifdef HAVE_ACL
struct my_acl *p = (struct my_acl *)acl;
if (p != NULL)
{
LocalFree(p->pSecurityDescriptor); vim_free(p);
}
#endif
}
#ifndef FEAT_GUI_W32
static BOOL WINAPI
handler_routine(
DWORD dwCtrlType)
{
switch (dwCtrlType)
{
case CTRL_C_EVENT:
if (ctrl_c_interrupts)
g_fCtrlCPressed = TRUE;
return TRUE;
case CTRL_BREAK_EVENT:
g_fCBrkPressed = TRUE;
return TRUE;
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
windgoto((int)Rows - 1, 0);
g_fForceExit = TRUE;
sprintf((char *)IObuff, _("Vim: Caught %s event\n"),
(dwCtrlType == CTRL_CLOSE_EVENT
? _("close")
: dwCtrlType == CTRL_LOGOFF_EVENT
? _("logoff")
: _("shutdown")));
#ifdef DEBUG
OutputDebugString(IObuff);
#endif
preserve_exit();
return TRUE;
default:
return FALSE;
}
}
void
mch_settmode(int tmode)
{
DWORD cmodein;
DWORD cmodeout;
BOOL bEnableHandler;
GetConsoleMode(g_hConIn, &cmodein);
GetConsoleMode(g_hConOut, &cmodeout);
if (tmode == TMODE_RAW)
{
cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
ENABLE_ECHO_INPUT);
#ifdef FEAT_MOUSE
if (g_fMouseActive)
cmodein |= ENABLE_MOUSE_INPUT;
#endif
cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
bEnableHandler = TRUE;
}
else
{
cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
ENABLE_ECHO_INPUT);
cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
bEnableHandler = FALSE;
}
SetConsoleMode(g_hConIn, cmodein);
SetConsoleMode(g_hConOut, cmodeout);
SetConsoleCtrlHandler(handler_routine, bEnableHandler);
#ifdef MCH_WRITE_DUMP
if (fdDump)
{
fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
tmode == TMODE_RAW ? "raw" :
tmode == TMODE_COOK ? "cooked" : "normal",
cmodein, cmodeout);
fflush(fdDump);
}
#endif
}
int
mch_get_shellsize(void)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
if (!g_fTermcapMode && g_cbTermcap.IsValid)
{
Rows = g_cbTermcap.Info.dwSize.Y;
Columns = g_cbTermcap.Info.dwSize.X;
}
else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
{
Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
}
else
{
Rows = 25;
Columns = 80;
}
return OK;
}
static void
ResizeConBufAndWindow(
HANDLE hConsole,
int xSize,
int ySize)
{
CONSOLE_SCREEN_BUFFER_INFO csbi;
SMALL_RECT srWindowRect;
COORD coordScreen;
#ifdef MCH_WRITE_DUMP
if (fdDump)
{
fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
fflush(fdDump);
}
#endif
coordScreen = GetLargestConsoleWindowSize(hConsole);
srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
{
int sx, sy;
sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
if (sy < ySize || sx < xSize)
{
if (sy < ySize)
coordScreen.Y = ySize;
else
coordScreen.Y = sy;
if (sx < xSize)
coordScreen.X = xSize;
else
coordScreen.X = sx;
SetConsoleScreenBufferSize(hConsole, coordScreen);
}
}
if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
{
#ifdef MCH_WRITE_DUMP
if (fdDump)
{
fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
GetLastError());
fflush(fdDump);
}
#endif
}
coordScreen.X = xSize;
coordScreen.Y = ySize;
if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
{
#ifdef MCH_WRITE_DUMP
if (fdDump)
{
fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
GetLastError());
fflush(fdDump);
}
#endif
}
}
void
mch_set_shellsize(void)
{
COORD coordScreen;
if (suppress_winsize != 0)
{
suppress_winsize = 2;
return;
}
if (term_console)
{
coordScreen = GetLargestConsoleWindowSize(g_hConOut);
if (Rows > coordScreen.Y)
Rows = coordScreen.Y;
if (Columns > coordScreen.X)
Columns = coordScreen.X;
ResizeConBufAndWindow(g_hConOut, Columns, Rows);
}
}
void
mch_new_shellsize(void)
{
set_scroll_region(0, 0, Columns - 1, Rows - 1);
}
void
mch_set_winsize_now(void)
{
if (suppress_winsize == 2)
{
suppress_winsize = 0;
mch_set_shellsize();
shell_resized();
}
suppress_winsize = 0;
}
#endif
#if defined(FEAT_GUI_W32) || defined(PROTO)
static int
mch_system(char *cmd, int options)
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
DWORD ret = 0;
HWND hwnd = GetFocus();
si.cb = sizeof(si);
si.lpReserved = NULL;
si.lpDesktop = NULL;
si.lpTitle = NULL;
si.dwFlags = STARTF_USESHOWWINDOW;
if ((options & SHELL_DOOUT) && !mch_windows95() && !gui_is_win32s())
si.wShowWindow = SW_SHOWMINIMIZED;
else
si.wShowWindow = SW_SHOWNORMAL;
si.cbReserved2 = 0;
si.lpReserved2 = NULL;
if (mch_windows95()
&& (STRNICMP(cmd, "c:/command.com", 14) == 0
|| STRNICMP(cmd, "c:\\command.com", 14) == 0))
cmd += 3;
CreateProcess(NULL,
cmd,
NULL,
NULL,
FALSE,
CREATE_DEFAULT_ERROR_MODE |
CREATE_NEW_CONSOLE,
NULL,
NULL,
&si,
&pi);
if (g_PlatformId != VER_PLATFORM_WIN32s)
{
#ifdef FEAT_GUI
int delay = 1;
for (;;)
{
MSG msg;
if (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
break;
if (delay < 50)
delay += 10;
}
#else
WaitForSingleObject(pi.hProcess, INFINITE);
#endif
GetExitCodeProcess(pi.hProcess, &ret);
}
else
{
num_windows = 0;
EnumWindows(win32ssynch_cb, 0);
old_num_windows = num_windows;
do
{
Sleep(1000);
num_windows = 0;
EnumWindows(win32ssynch_cb, 0);
} while (num_windows == old_num_windows);
ret = 0;
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
PostMessage(hwnd, WM_SETFOCUS, 0, 0);
return ret;
}
#else
# define mch_system(c, o) system(c)
#endif
int
mch_call_shell(
char_u *cmd,
int options)
{
int x = 0;
int tmode = cur_tmode;
#ifdef FEAT_TITLE
char szShellTitle[512];
if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
{
if (cmd == NULL)
strcat(szShellTitle, " :sh");
else
{
strcat(szShellTitle, " - !");
if ((strlen(szShellTitle) + strlen(cmd) < sizeof(szShellTitle)))
strcat(szShellTitle, cmd);
}
mch_settitle(szShellTitle, NULL);
}
#endif
out_flush();
#ifdef MCH_WRITE_DUMP
if (fdDump)
{
fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
fflush(fdDump);
}
#endif
signal(SIGINT, SIG_IGN);
#if defined(__GNUC__) && !defined(__MINGW32__)
signal(SIGKILL, SIG_IGN);
#else
signal(SIGBREAK, SIG_IGN);
#endif
signal(SIGILL, SIG_IGN);
signal(SIGFPE, SIG_IGN);
signal(SIGSEGV, SIG_IGN);
signal(SIGTERM, SIG_IGN);
signal(SIGABRT, SIG_IGN);
if (options & SHELL_COOKED)
settmode(TMODE_COOK);
if (cmd == NULL)
{
x = mch_system(p_sh, options);
}
else
{
char_u *newcmd;
newcmd = lalloc((long_u) (
#ifdef FEAT_GUI_W32
STRLEN(vimrun_path) +
#endif
STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10), TRUE);
if (newcmd != NULL)
{
char_u *cmdbase = (*cmd == '"' ? cmd + 1 : cmd);
if ((STRNICMP(cmdbase, "start", 5) == 0) && vim_iswhite(cmdbase[5]))
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
si.cb = sizeof(si);
si.lpReserved = NULL;
si.lpDesktop = NULL;
si.lpTitle = NULL;
si.dwFlags = 0;
si.cbReserved2 = 0;
si.lpReserved2 = NULL;
cmdbase = skipwhite(cmdbase + 5);
if ((STRNICMP(cmdbase, "/min", 4) == 0)
&& vim_iswhite(cmdbase[4]))
{
cmdbase = skipwhite(cmdbase + 4);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOWMINNOACTIVE;
}
if (*cmd == '"' && *p_sxq == NUL)
{
newcmd[0] = '"';
STRCPY(newcmd + 1, cmdbase);
}
else
{
STRCPY(newcmd, cmdbase);
if (*cmd == '"' && *newcmd != NUL)
newcmd[STRLEN(newcmd) - 1] = NUL;
}
if (CreateProcess (NULL, newcmd, NULL, NULL, FALSE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi)) x = 0;
else
{
x = -1;
#ifdef FEAT_GUI_W32
EMSG(_("E371: Command not found"));
#endif
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
else
{
#if defined(FEAT_GUI_W32)
if (need_vimrun_warning)
{
MessageBox(NULL,
_("VIMRUN.EXE not found in your $PATH.\n"
"External commands will not pause after completion.\n"
"See :help win32-vimrun for more information."),
_("Vim Warning"),
MB_ICONWARNING);
need_vimrun_warning = FALSE;
}
if (!s_dont_use_vimrun)
sprintf((char *)newcmd, "%s%s%s %s %s",
vimrun_path,
(msg_silent != 0 || (options & SHELL_DOOUT))
? "-s " : "",
p_sh, p_shcf, cmd);
else
#endif
sprintf((char *)newcmd, "%s %s %s", p_sh, p_shcf, cmd);
x = mch_system((char *)newcmd, options);
}
vim_free(newcmd);
}
}
if (tmode == TMODE_RAW)
settmode(TMODE_RAW);
if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
#if defined(FEAT_GUI_W32)
&& ((options & SHELL_DOOUT) || s_dont_use_vimrun)
#endif
)
{
smsg(_("shell returned %d"), x);
msg_putchar('\n');
}
#ifdef FEAT_TITLE
resettitle();
#endif
signal(SIGINT, SIG_DFL);
#if defined(__GNUC__) && !defined(__MINGW32__)
signal(SIGKILL, SIG_DFL);
#else
signal(SIGBREAK, SIG_DFL);
#endif
signal(SIGILL, SIG_DFL);
signal(SIGFPE, SIG_DFL);
signal(SIGSEGV, SIG_DFL);
signal(SIGTERM, SIG_DFL);
signal(SIGABRT, SIG_DFL);
return x;
}
#ifndef FEAT_GUI_W32
static void
termcap_mode_start(void)
{
DWORD cmodein;
if (g_fTermcapMode)
return;
SaveConsoleBuffer(&g_cbNonTermcap);
if (g_cbTermcap.IsValid)
{
RestoreConsoleBuffer(&g_cbTermcap, FALSE);
SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
Rows = g_cbTermcap.Info.dwSize.Y;
Columns = g_cbTermcap.Info.dwSize.X;
}
else
{
ClearConsoleBuffer(g_attrCurrent);
ResizeConBufAndWindow(g_hConOut, Columns, Rows);
}
#ifdef FEAT_TITLE
resettitle();
#endif
GetConsoleMode(g_hConIn, &cmodein);
#ifdef FEAT_MOUSE
if (g_fMouseActive)
cmodein |= ENABLE_MOUSE_INPUT;
else
cmodein &= ~ENABLE_MOUSE_INPUT;
#endif
cmodein |= ENABLE_WINDOW_INPUT;
SetConsoleMode(g_hConIn, cmodein);
redraw_later_clear();
g_fTermcapMode = TRUE;
}
static void
termcap_mode_end(void)
{
DWORD cmodein;
ConsoleBuffer *cb;
COORD coord;
DWORD dwDummy;
if (!g_fTermcapMode)
return;
SaveConsoleBuffer(&g_cbTermcap);
GetConsoleMode(g_hConIn, &cmodein);
cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
SetConsoleMode(g_hConIn, cmodein);
#ifdef FEAT_RESTORE_ORIG_SCREEN
cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
#else
cb = &g_cbNonTermcap;
#endif
RestoreConsoleBuffer(cb, p_rs);
SetConsoleCursorInfo(g_hConOut, &g_cci);
if (p_rs || exiting)
{
coord.X = 0;
coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
FillConsoleOutputCharacter(g_hConOut, ' ',
cb->Info.dwSize.X, coord, &dwDummy);
if (exiting && !p_rs)
coord.Y--;
SetConsoleCursorPosition(g_hConOut, coord);
}
g_fTermcapMode = FALSE;
}
#endif
#ifdef FEAT_GUI_W32
void
mch_write(
char_u *s,
int len)
{
}
#else
static void
clear_chars(
COORD coord,
DWORD n)
{
DWORD dwDummy;
FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
}
static void
clear_screen(void)
{
g_coord.X = g_coord.Y = 0;
clear_chars(g_coord, Rows * Columns);
}
static void
clear_to_end_of_display(void)
{
clear_chars(g_coord, (Rows - g_coord.Y - 1)
* Columns + (Columns - g_coord.X));
}
static void
clear_to_end_of_line(void)
{
clear_chars(g_coord, Columns - g_coord.X);
}
static void
scroll(unsigned cLines)
{
COORD oldcoord = g_coord;
gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
delete_lines(cLines);
g_coord = oldcoord;
}
static void
set_scroll_region(
unsigned left,
unsigned top,
unsigned right,
unsigned bottom)
{
if (left >= right
|| top >= bottom
|| right > (unsigned) Columns - 1
|| bottom > (unsigned) Rows - 1)
return;
g_srScrollRegion.Left = left;
g_srScrollRegion.Top = top;
g_srScrollRegion.Right = right;
g_srScrollRegion.Bottom = bottom;
}
static void
insert_lines(unsigned cLines)
{
SMALL_RECT source;
COORD dest;
CHAR_INFO fill;
dest.X = 0;
dest.Y = g_coord.Y + cLines;
source.Left = 0;
source.Top = g_coord.Y;
source.Right = g_srScrollRegion.Right;
source.Bottom = g_srScrollRegion.Bottom - cLines;
fill.Char.AsciiChar = ' ';
fill.Attributes = g_attrCurrent;
ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
if (source.Bottom < dest.Y)
{
COORD coord;
coord.X = 0;
coord.Y = source.Bottom;
clear_chars(coord, Columns * (dest.Y - source.Bottom));
}
}
static void
delete_lines(unsigned cLines)
{
SMALL_RECT source;
COORD dest;
CHAR_INFO fill;
int nb;
dest.X = 0;
dest.Y = g_coord.Y;
source.Left = 0;
source.Top = g_coord.Y + cLines;
source.Right = g_srScrollRegion.Right;
source.Bottom = g_srScrollRegion.Bottom;
fill.Char.AsciiChar = ' ';
fill.Attributes = g_attrCurrent;
ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
nb = dest.Y + (source.Bottom - source.Top) + 1;
if (nb < source.Top)
{
COORD coord;
coord.X = 0;
coord.Y = nb;
clear_chars(coord, Columns * (source.Top - nb));
}
}
static void
gotoxy(
unsigned x,
unsigned y)
{
if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
return;
g_coord.X = x - 1;
g_coord.Y = y - 1;
SetConsoleCursorPosition(g_hConOut, g_coord);
}
static void
textattr(WORD wAttr)
{
g_attrCurrent = wAttr;
SetConsoleTextAttribute(g_hConOut, wAttr);
}
static void
textcolor(WORD wAttr)
{
g_attrCurrent = (g_attrCurrent & 0xf0) + wAttr;
SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
}
static void
textbackground(WORD wAttr)
{
g_attrCurrent = (g_attrCurrent & 0x0f) + (wAttr << 4);
SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
}
static void
normvideo(void)
{
textattr(g_attrDefault);
}
static WORD g_attrPreStandout = 0;
static void
standout(void)
{
g_attrPreStandout = g_attrCurrent;
textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
}
static void
standend(void)
{
if (g_attrPreStandout)
{
textattr(g_attrPreStandout);
g_attrPreStandout = 0;
}
}
void
mch_set_normal_colors(void)
{
char_u *p;
int n;
cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
if (T_ME[0] == ESC && T_ME[1] == '|')
{
p = T_ME + 2;
n = getdigits(&p);
if (*p == 'm' && n > 0)
{
cterm_normal_fg_color = (n & 0xf) + 1;
cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
}
}
}
static void
visual_bell(void)
{
COORD coordOrigin = {0, 0};
WORD attrFlash = ~g_attrCurrent & 0xff;
DWORD dwDummy;
LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
if (oldattrs == NULL)
return;
ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
coordOrigin, &dwDummy);
FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
coordOrigin, &dwDummy);
Sleep(15);
WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
coordOrigin, &dwDummy);
vim_free(oldattrs);
}
static void
cursor_visible(BOOL fVisible)
{
s_cursor_visible = fVisible;
#ifdef MCH_CURSOR_SHAPE
mch_update_cursor();
#endif
}
static BOOL
write_chars(
LPCSTR pchBuf,
DWORD cchToWrite)
{
COORD coord = g_coord;
DWORD written;
FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cchToWrite,
coord, &written);
if (WriteConsoleOutputCharacter(g_hConOut, pchBuf, cchToWrite,
coord, &written) == 0
|| written == 0)
written = 1;
g_coord.X += (SHORT) written;
while (g_coord.X > g_srScrollRegion.Right)
{
g_coord.X -= (SHORT) Columns;
if (g_coord.Y < g_srScrollRegion.Bottom)
g_coord.Y++;
}
gotoxy(g_coord.X + 1, g_coord.Y + 1);
return written;
}
void
mch_write(
char_u *s,
int len)
{
s[len] = NUL;
if (!term_console)
{
write(1, s, (unsigned)len);
return;
}
while (len--)
{
DWORD prefix = (DWORD)strcspn(s, "\n\r\b\a\033");
if (p_wd)
{
WaitForChar(p_wd);
if (prefix != 0)
prefix = 1;
}
if (prefix != 0)
{
DWORD nWritten;
nWritten = write_chars(s, prefix);
#ifdef MCH_WRITE_DUMP
if (fdDump)
{
fputc('>', fdDump);
fwrite(s, sizeof(char_u), nWritten, fdDump);
fputs("<\n", fdDump);
}
#endif
len -= (nWritten - 1);
s += nWritten;
}
else if (s[0] == '\n')
{
if (g_coord.Y == g_srScrollRegion.Bottom)
{
scroll(1);
gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
}
else
{
gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
}
#ifdef MCH_WRITE_DUMP
if (fdDump)
fputs("\\n\n", fdDump);
#endif
s++;
}
else if (s[0] == '\r')
{
gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
#ifdef MCH_WRITE_DUMP
if (fdDump)
fputs("\\r\n", fdDump);
#endif
s++;
}
else if (s[0] == '\b')
{
if (g_coord.X > g_srScrollRegion.Left)
g_coord.X--;
else if (g_coord.Y > g_srScrollRegion.Top)
{
g_coord.X = g_srScrollRegion.Right;
g_coord.Y--;
}
gotoxy(g_coord.X + 1, g_coord.Y + 1);
#ifdef MCH_WRITE_DUMP
if (fdDump)
fputs("\\b\n", fdDump);
#endif
s++;
}
else if (s[0] == '\a')
{
MessageBeep(0xFFFFFFFF);
#ifdef MCH_WRITE_DUMP
if (fdDump)
fputs("\\a\n", fdDump);
#endif
s++;
}
else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
{
#ifdef MCH_WRITE_DUMP
char_u *old_s = s;
#endif
char_u *p;
int arg1 = 0, arg2 = 0;
switch (s[2])
{
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
p = s + 2;
arg1 = getdigits(&p);
if (p > s + len)
break;
if (*p == ';')
{
++p;
arg2 = getdigits(&p);
if (p > s + len)
break;
if (*p == 'H')
gotoxy(arg2, arg1);
else if (*p == 'r')
set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
}
else if (*p == 'A')
{
gotoxy(g_coord.X + 1,
max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
}
else if (*p == 'C')
{
gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
g_coord.Y + 1);
}
else if (*p == 'H')
{
gotoxy(1, arg1);
}
else if (*p == 'L')
{
insert_lines(arg1);
}
else if (*p == 'm')
{
if (arg1 == 0)
normvideo();
else
textattr((WORD) arg1);
}
else if (*p == 'f')
{
textcolor((WORD) arg1);
}
else if (*p == 'b')
{
textbackground((WORD) arg1);
}
else if (*p == 'M')
{
delete_lines(arg1);
}
len -= (int)(p - s);
s = p + 1;
break;
case 'A':
gotoxy(g_coord.X + 1,
max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
goto got3;
case 'B':
visual_bell();
goto got3;
case 'C':
gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
g_coord.Y + 1);
goto got3;
case 'E':
termcap_mode_end();
goto got3;
case 'F':
standout();
goto got3;
case 'f':
standend();
goto got3;
case 'H':
gotoxy(1, 1);
goto got3;
case 'j':
clear_to_end_of_display();
goto got3;
case 'J':
clear_screen();
goto got3;
case 'K':
clear_to_end_of_line();
goto got3;
case 'L':
insert_lines(1);
goto got3;
case 'M':
delete_lines(1);
goto got3;
case 'S':
termcap_mode_start();
goto got3;
case 'V':
cursor_visible(TRUE);
goto got3;
case 'v':
cursor_visible(FALSE);
goto got3;
got3:
s += 3;
len -= 2;
}
#ifdef MCH_WRITE_DUMP
if (fdDump)
{
fputs("ESC | ", fdDump);
fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
fputc('\n', fdDump);
}
#endif
}
else
{
DWORD nWritten;
nWritten = write_chars(s, 1);
#ifdef MCH_WRITE_DUMP
if (fdDump)
{
fputc('>', fdDump);
fwrite(s, sizeof(char_u), nWritten, fdDump);
fputs("<\n", fdDump);
}
#endif
len -= (nWritten - 1);
s += nWritten;
}
}
#ifdef MCH_WRITE_DUMP
if (fdDump)
fflush(fdDump);
#endif
}
#endif
void
mch_delay(
long msec,
int ignoreinput)
{
#ifdef FEAT_GUI_W32
Sleep((int)msec);
#else
if (ignoreinput)
# ifdef FEAT_MZSCHEME
if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
{
int towait = p_mzq;
while (msec > 0)
{
mzvim_check_threads();
if (msec < towait)
towait = msec;
Sleep(towait);
msec -= towait;
}
}
else
# endif
Sleep((int)msec);
else
WaitForChar(msec);
#endif
}
int
mch_remove(char_u *name)
{
#ifdef FEAT_MBYTE
WCHAR *wn = NULL;
int n;
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
{
wn = enc_to_ucs2(name, NULL);
if (wn != NULL)
{
SetFileAttributesW(wn, FILE_ATTRIBUTE_NORMAL);
n = DeleteFileW(wn) ? 0 : -1;
vim_free(wn);
if (n == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return n;
}
}
#endif
SetFileAttributes(name, FILE_ATTRIBUTE_NORMAL);
return DeleteFile(name) ? 0 : -1;
}
void
mch_breakcheck(void)
{
#ifndef FEAT_GUI_W32
if (g_fCtrlCPressed || g_fCBrkPressed)
{
g_fCtrlCPressed = g_fCBrkPressed = FALSE;
got_int = TRUE;
}
#endif
}
long_u
mch_avail_mem(int special)
{
MEMORYSTATUS ms;
ms.dwLength = sizeof(MEMORYSTATUS);
GlobalMemoryStatus(&ms);
return (long_u) (ms.dwAvailPhys + ms.dwAvailPageFile);
}
#ifdef FEAT_MBYTE
int
mch_wrename(WCHAR *wold, WCHAR *wnew)
{
WCHAR *p;
int i;
WCHAR szTempFile[_MAX_PATH + 1];
WCHAR szNewPath[_MAX_PATH + 1];
HANDLE hf;
if (!mch_windows95())
{
p = wold;
for (i = 0; wold[i] != NUL; ++i)
if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
&& wold[i + 1] != 0)
p = wold + i + 1;
if ((int)(wold + i - p) < 8 || p[6] != '~')
return (MoveFileW(wold, wnew) == 0);
}
if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
return -1;
*p = NUL;
if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
return -2;
if (!DeleteFileW(szTempFile))
return -3;
if (!MoveFileW(wold, szTempFile))
return -4;
if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
return -5;
if (!CloseHandle(hf))
return -6;
if (!MoveFileW(szTempFile, wnew))
{
(void)MoveFileW(szTempFile, wold);
return -7;
}
DeleteFileW(szTempFile);
if (!DeleteFileW(wold))
return -8;
return 0;
}
#endif
int
mch_rename(
const char *pszOldFile,
const char *pszNewFile)
{
char szTempFile[_MAX_PATH+1];
char szNewPath[_MAX_PATH+1];
char *pszFilePart;
HANDLE hf;
#ifdef FEAT_MBYTE
WCHAR *wold = NULL;
WCHAR *wnew = NULL;
int retval = -1;
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
{
wold = enc_to_ucs2((char_u *)pszOldFile, NULL);
wnew = enc_to_ucs2((char_u *)pszNewFile, NULL);
if (wold != NULL && wnew != NULL)
retval = mch_wrename(wold, wnew);
vim_free(wold);
vim_free(wnew);
if (retval == 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
return retval;
}
#endif
if (!mch_windows95())
{
pszFilePart = (char *)gettail((char_u *)pszOldFile);
if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
return rename(pszOldFile, pszNewFile);
}
if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
|| pszFilePart == NULL)
return -1;
*pszFilePart = NUL;
if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
return -2;
if (!DeleteFile(szTempFile))
return -3;
if (!MoveFile(pszOldFile, szTempFile))
return -4;
if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
return -5;
if (!CloseHandle(hf))
return -6;
if (!MoveFile(szTempFile, pszNewFile))
{
(void)MoveFile(szTempFile, pszOldFile);
return -7;
}
DeleteFile(szTempFile);
if (!DeleteFile(pszOldFile))
return -8;
return 0;
}
char *
default_shell(void)
{
char* psz = NULL;
PlatformId();
if (g_PlatformId == VER_PLATFORM_WIN32_NT)
psz = "cmd.exe";
else if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
psz = "command.com";
return psz;
}
int
mch_access(char *n, int p)
{
HANDLE hFile;
DWORD am;
int retval = -1;
#ifdef FEAT_MBYTE
WCHAR *wn = NULL;
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
wn = enc_to_ucs2(n, NULL);
#endif
if (mch_isdir(n))
{
char TempName[_MAX_PATH + 16] = "";
#ifdef FEAT_MBYTE
WCHAR TempNameW[_MAX_PATH + 16] = L"";
#endif
if (p & R_OK)
{
#ifdef FEAT_MBYTE
if (wn != NULL)
{
int i;
WIN32_FIND_DATAW d;
for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
TempNameW[i] = wn[i];
if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
TempNameW[i++] = '\\';
TempNameW[i++] = '*';
TempNameW[i++] = 0;
hFile = FindFirstFileW(TempNameW, &d);
if (hFile == INVALID_HANDLE_VALUE)
{
if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
goto getout;
vim_free(wn);
wn = NULL;
}
else
(void)FindClose(hFile);
}
if (wn == NULL)
#endif
{
char *pch;
WIN32_FIND_DATA d;
vim_strncpy(TempName, n, _MAX_PATH);
pch = TempName + STRLEN(TempName) - 1;
if (*pch != '\\' && *pch != '/')
*++pch = '\\';
*++pch = '*';
*++pch = NUL;
hFile = FindFirstFile(TempName, &d);
if (hFile == INVALID_HANDLE_VALUE)
goto getout;
(void)FindClose(hFile);
}
}
if (p & W_OK)
{
#ifdef FEAT_MBYTE
if (wn != NULL)
{
if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
{
if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
goto getout;
vim_free(wn);
wn = NULL;
}
else
DeleteFileW(TempNameW);
}
if (wn == NULL)
#endif
{
if (!GetTempFileName(n, "VIM", 0, TempName))
goto getout;
mch_remove((char_u *)TempName);
}
}
}
else
{
am = ((p & W_OK) ? GENERIC_WRITE : 0)
| ((p & R_OK) ? GENERIC_READ : 0);
#ifdef FEAT_MBYTE
if (wn != NULL)
{
hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE
&& GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
vim_free(wn);
wn = NULL;
}
}
if (wn == NULL)
#endif
hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
goto getout;
CloseHandle(hFile);
}
retval = 0;
getout:
#ifdef FEAT_MBYTE
vim_free(wn);
#endif
return retval;
}
#if defined(FEAT_MBYTE) || defined(PROTO)
int
mch_open(char *name, int flags, int mode)
{
# ifndef __BORLANDC__
WCHAR *wn;
int f;
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
{
wn = enc_to_ucs2(name, NULL);
if (wn != NULL)
{
f = _wopen(wn, flags, mode);
vim_free(wn);
if (f >= 0)
return f;
}
}
# endif
return open(name, flags, mode);
}
FILE *
mch_fopen(char *name, char *mode)
{
WCHAR *wn, *wm;
FILE *f = NULL;
if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
# ifdef __BORLANDC__
&& g_PlatformId == VER_PLATFORM_WIN32_NT
# endif
)
{
wn = enc_to_ucs2(name, NULL);
wm = enc_to_ucs2(mode, NULL);
if (wn != NULL && wm != NULL)
f = _wfopen(wn, wm);
vim_free(wn);
vim_free(wm);
if (f != NULL)
return f;
}
return fopen(name, mode);
}
#endif
#ifdef FEAT_MBYTE
static void
copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
{
HANDLE hTo;
WCHAR *to_name;
to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
wcscpy(to_name, to);
wcscat(to_name, substream);
hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL, NULL);
if (hTo != INVALID_HANDLE_VALUE)
{
long done;
DWORD todo;
DWORD readcnt, written;
char buf[4096];
for (done = 0; done < len; done += written)
{
todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
: (size_t)(len - done));
if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
FALSE, FALSE, context)
|| readcnt != todo
|| !WriteFile(hTo, buf, todo, &written, NULL)
|| written != todo)
break;
}
CloseHandle(hTo);
}
free(to_name);
}
static void
copy_infostreams(char_u *from, char_u *to)
{
WCHAR *fromw;
WCHAR *tow;
HANDLE sh;
WIN32_STREAM_ID sid;
int headersize;
WCHAR streamname[_MAX_PATH];
DWORD readcount;
void *context = NULL;
DWORD lo, hi;
int len;
fromw = enc_to_ucs2(from, NULL);
tow = enc_to_ucs2(to, NULL);
if (fromw != NULL && tow != NULL)
{
sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (sh != INVALID_HANDLE_VALUE)
{
for (;;)
{
ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
if (!BackupRead(sh, (LPBYTE)&sid, headersize,
&readcount, FALSE, FALSE, &context)
|| readcount == 0)
break;
if (sid.dwStreamNameSize > 0)
{
if (!BackupRead(sh, (LPBYTE)streamname,
sid.dwStreamNameSize,
&readcount, FALSE, FALSE, &context))
break;
len = readcount / sizeof(WCHAR);
streamname[len] = 0;
if (len > 7 && wcsicmp(streamname + len - 6,
L":$DATA") == 0)
{
streamname[len - 6] = 0;
copy_substream(sh, &context, tow, streamname,
(long)sid.Size.u.LowPart);
}
}
(void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
&lo, &hi, &context);
}
(void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
CloseHandle(sh);
}
}
vim_free(fromw);
vim_free(tow);
}
#endif
int
mch_copy_file_attribute(char_u *from, char_u *to)
{
#ifdef FEAT_MBYTE
PlatformId();
if (g_PlatformId == VER_PLATFORM_WIN32_NT)
copy_infostreams(from, to);
#endif
return 0;
}
#if defined(MYRESETSTKOFLW) || defined(PROTO)
#define MIN_STACK_WIN9X 17
#define MIN_STACK_WINNT 2
int
myresetstkoflw(void)
{
BYTE *pStackPtr;
BYTE *pGuardPage;
BYTE *pStackBase;
BYTE *pLowestPossiblePage;
MEMORY_BASIC_INFORMATION mbi;
SYSTEM_INFO si;
DWORD nPageSize;
DWORD dummy;
PlatformId();
if (g_PlatformId == VER_PLATFORM_WIN32s)
return 0;
GetSystemInfo(&si);
nPageSize = si.dwPageSize;
pStackPtr = (BYTE*)_alloca(1);
if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
return 0;
pStackBase = (BYTE*)mbi.AllocationBase;
pLowestPossiblePage = pStackBase + ((g_PlatformId == VER_PLATFORM_WIN32_NT)
? MIN_STACK_WINNT : MIN_STACK_WIN9X) * nPageSize;
if (g_PlatformId == VER_PLATFORM_WIN32_WINDOWS)
{
pGuardPage = (BYTE*)((DWORD)nPageSize * (((DWORD)pStackPtr
/ (DWORD)nPageSize) - 1));
if (pGuardPage < pLowestPossiblePage)
return 0;
if (!VirtualProtect(pGuardPage, nPageSize, PAGE_NOACCESS, &dummy))
return 0;
}
else
{
BYTE *pBlock = pStackBase;
for (;;)
{
if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
return 0;
pBlock += mbi.RegionSize;
if (mbi.State & MEM_COMMIT)
break;
}
if (mbi.Protect & PAGE_GUARD)
return 1;
if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
pGuardPage = pLowestPossiblePage;
else
pGuardPage = (BYTE*)mbi.BaseAddress;
if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
return 0;
if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
&dummy))
return 0;
}
return 1;
}
#endif
#if defined(FEAT_MBYTE) || defined(PROTO)
static int nArgsW = 0;
static LPWSTR *ArglistW = NULL;
static int global_argc = 0;
static char **global_argv;
static int used_file_argc = 0;
static int *used_file_indexes = NULL;
static int used_file_count = 0;
static int used_file_literal = FALSE;
static int used_file_full_path = FALSE;
static int used_file_diff_mode = FALSE;
static int used_alist_count = 0;
int
get_cmd_argsW(char ***argvp)
{
char **argv = NULL;
int argc = 0;
int i;
ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
if (ArglistW != NULL)
{
argv = malloc((nArgsW + 1) * sizeof(char *));
if (argv != NULL)
{
argc = nArgsW;
argv[argc] = NULL;
for (i = 0; i < argc; ++i)
{
int len;
WideCharToMultiByte_alloc(GetACP(), 0,
ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
(LPSTR *)&argv[i], &len, 0, 0);
if (argv[i] == NULL)
{
while (i > 0)
free(argv[--i]);
free(argv);
argc = 0;
}
}
}
}
global_argc = argc;
global_argv = argv;
if (argc > 0)
used_file_indexes = malloc(argc * sizeof(int));
if (argvp != NULL)
*argvp = argv;
return argc;
}
void
free_cmd_argsW(void)
{
if (ArglistW != NULL)
{
GlobalFree(ArglistW);
ArglistW = NULL;
}
}
void
used_file_arg(char *name, int literal, int full_path, int diff_mode)
{
int i;
if (used_file_indexes == NULL)
return;
for (i = used_file_argc + 1; i < global_argc; ++i)
if (STRCMP(global_argv[i], name) == 0)
{
used_file_argc = i;
used_file_indexes[used_file_count++] = i;
break;
}
used_file_literal = literal;
used_file_full_path = full_path;
used_file_diff_mode = diff_mode;
}
void
set_alist_count(void)
{
used_alist_count = GARGCOUNT;
}
void
fix_arg_enc(void)
{
int i;
int idx;
char_u *str;
int *fnum_list;
if (global_argc != nArgsW
|| ArglistW == NULL
|| used_file_indexes == NULL
|| used_file_count == 0
|| used_alist_count != GARGCOUNT)
return;
fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
if (fnum_list == NULL)
return;
for (i = 0; i < GARGCOUNT; ++i)
fnum_list[i] = GARGLIST[i].ae_fnum;
alist_clear(&global_alist);
if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
return;
for (i = 0; i < used_file_count; ++i)
{
idx = used_file_indexes[i];
str = ucs2_to_enc(ArglistW[idx], NULL);
if (str != NULL)
{
#ifdef FEAT_DIFF
if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
&& !mch_isdir(alist_name(&GARGLIST[0])))
{
char_u *r;
r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
if (r != NULL)
{
vim_free(str);
str = r;
}
}
#endif
if (used_file_literal)
buf_set_name(fnum_list[i], str);
alist_add(&global_alist, str, used_file_literal ? 2 : 0);
}
}
if (!used_file_literal)
{
do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
alist_expand(fnum_list, used_alist_count);
do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
}
if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
{
do_cmdline_cmd((char_u *)":rewind");
if (GARGCOUNT == 1 && used_file_full_path)
(void)vim_chdirfile(alist_name(&GARGLIST[0]));
}
set_alist_count();
}
#endif