blob: c1c297a63dfe17ec9a7b5d1806997cd0b45c89d6 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9/*
10 * os_win32.c
11 *
12 * Used for both the console version and the Win32 GUI. A lot of code is for
13 * the console version only, so there is a lot of "#ifndef FEAT_GUI_W32".
14 *
15 * Win32 (Windows NT and Windows 95) system-dependent routines.
16 * Portions lifted from the Win32 SDK samples, the MSDOS-dependent code,
17 * NetHack 3.1.3, GNU Emacs 19.30, and Vile 5.5.
18 *
19 * George V. Reilly <george@reilly.org> wrote most of this.
20 * Roger Knobbe <rogerk@wonderware.com> did the initial port of Vim 3.0.
21 */
22
Bram Moolenaar071d4272004-06-13 20:20:40 +000023#include "vim.h"
24
Bram Moolenaar325b7a22004-07-05 15:58:32 +000025#ifdef FEAT_MZSCHEME
26# include "if_mzsch.h"
27#endif
28
Bram Moolenaar071d4272004-06-13 20:20:40 +000029#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000030#include <signal.h>
31#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010032
33/* cproto fails on missing include files */
34#ifndef PROTO
35# include <process.h>
36#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000037
38#undef chdir
39#ifdef __GNUC__
40# ifndef __MINGW32__
41# include <dirent.h>
42# endif
43#else
44# include <direct.h>
45#endif
46
Bram Moolenaar82881492012-11-20 16:53:39 +010047#ifndef PROTO
48# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
49# include <shellapi.h>
50# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000051#endif
52
Bram Moolenaarfb630902016-10-29 14:55:00 +020053#ifdef FEAT_JOB_CHANNEL
54# include <tlhelp32.h>
55#endif
56
Bram Moolenaar071d4272004-06-13 20:20:40 +000057#ifdef __MINGW32__
58# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
59# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
60# endif
61# ifndef RIGHTMOST_BUTTON_PRESSED
62# define RIGHTMOST_BUTTON_PRESSED 0x0002
63# endif
64# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
65# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
66# endif
67# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
68# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
69# endif
70# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
71# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
72# endif
73
74/*
75 * EventFlags
76 */
77# ifndef MOUSE_MOVED
78# define MOUSE_MOVED 0x0001
79# endif
80# ifndef DOUBLE_CLICK
81# define DOUBLE_CLICK 0x0002
82# endif
83#endif
84
85/* Record all output and all keyboard & mouse input */
86/* #define MCH_WRITE_DUMP */
87
88#ifdef MCH_WRITE_DUMP
89FILE* fdDump = NULL;
90#endif
91
92/*
93 * When generating prototypes for Win32 on Unix, these lines make the syntax
94 * errors disappear. They do not need to be correct.
95 */
96#ifdef PROTO
97#define WINAPI
Bram Moolenaar071d4272004-06-13 20:20:40 +000098typedef char * LPCSTR;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +000099typedef char * LPWSTR;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000100typedef int ACCESS_MASK;
101typedef int BOOL;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int HANDLE;
Bram Moolenaaref269542016-01-19 13:22:12 +0100107typedef int LPHANDLE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HINSTANCE;
112typedef int HWND;
113typedef int INPUT_RECORD;
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200114typedef int INT;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000115typedef int KEY_EVENT_RECORD;
116typedef int LOGFONT;
117typedef int LPBOOL;
118typedef int LPCTSTR;
119typedef int LPDWORD;
120typedef int LPSTR;
121typedef int LPTSTR;
122typedef int LPVOID;
123typedef int MOUSE_EVENT_RECORD;
124typedef int PACL;
125typedef int PDWORD;
126typedef int PHANDLE;
127typedef int PRINTDLG;
128typedef int PSECURITY_DESCRIPTOR;
129typedef int PSID;
130typedef int SECURITY_INFORMATION;
131typedef int SHORT;
132typedef int SMALL_RECT;
133typedef int TEXTMETRIC;
134typedef int TOKEN_INFORMATION_CLASS;
135typedef int TRUSTEE;
136typedef int WORD;
137typedef int WCHAR;
138typedef void VOID;
Bram Moolenaar82881492012-11-20 16:53:39 +0100139typedef int BY_HANDLE_FILE_INFORMATION;
Bram Moolenaar32ac8cd2013-07-03 18:49:17 +0200140typedef int SE_OBJECT_TYPE;
141typedef int PSNSECINFO;
142typedef int PSNSECINFOW;
Bram Moolenaarb8e0bdb2014-11-12 16:10:48 +0100143typedef int STARTUPINFO;
144typedef int PROCESS_INFORMATION;
Bram Moolenaard90b6c02016-08-28 18:10:45 +0200145typedef int LPSECURITY_ATTRIBUTES;
146# define __stdcall /* empty */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000147#endif
148
Bram Moolenaar071d4272004-06-13 20:20:40 +0000149#if defined(__BORLANDC__)
150/* Strangely Borland uses a non-standard name. */
151# define wcsicmp(a, b) wcscmpi((a), (b))
152#endif
153
154#ifndef FEAT_GUI_W32
155/* Win32 Console handles for input and output */
156static HANDLE g_hConIn = INVALID_HANDLE_VALUE;
157static HANDLE g_hConOut = INVALID_HANDLE_VALUE;
158
159/* Win32 Screen buffer,coordinate,console I/O information */
160static SMALL_RECT g_srScrollRegion;
161static COORD g_coord; /* 0-based, but external coords are 1-based */
162
163/* The attribute of the screen when the editor was started */
164static WORD g_attrDefault = 7; /* lightgray text on black background */
165static WORD g_attrCurrent;
166
167static int g_fCBrkPressed = FALSE; /* set by ctrl-break interrupt */
168static int g_fCtrlCPressed = FALSE; /* set when ctrl-C or ctrl-break detected */
169static int g_fForceExit = FALSE; /* set when forcefully exiting */
170
171static void termcap_mode_start(void);
172static void termcap_mode_end(void);
173static void clear_chars(COORD coord, DWORD n);
174static void clear_screen(void);
175static void clear_to_end_of_display(void);
176static void clear_to_end_of_line(void);
177static void scroll(unsigned cLines);
178static void set_scroll_region(unsigned left, unsigned top,
179 unsigned right, unsigned bottom);
180static void insert_lines(unsigned cLines);
181static void delete_lines(unsigned cLines);
182static void gotoxy(unsigned x, unsigned y);
183static void normvideo(void);
184static void textattr(WORD wAttr);
185static void textcolor(WORD wAttr);
186static void textbackground(WORD wAttr);
187static void standout(void);
188static void standend(void);
189static void visual_bell(void);
190static void cursor_visible(BOOL fVisible);
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200191static DWORD write_chars(char_u *pchBuf, DWORD cbToWrite);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000192static void create_conin(void);
193static int s_cursor_visible = TRUE;
194static int did_create_conin = FALSE;
195#else
196static int s_dont_use_vimrun = TRUE;
197static int need_vimrun_warning = FALSE;
198static char *vimrun_path = "vimrun ";
199#endif
200
Bram Moolenaar12b559e2013-06-12 22:41:37 +0200201static int win32_getattrs(char_u *name);
202static int win32_setattrs(char_u *name, int attrs);
203static int win32_set_archive(char_u *name);
204
Bram Moolenaar071d4272004-06-13 20:20:40 +0000205#ifndef FEAT_GUI_W32
206static int suppress_winsize = 1; /* don't fiddle with console */
207#endif
208
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200209static char_u *exe_path = NULL;
210
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100211static BOOL win8_or_later = FALSE;
212
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100213#ifndef FEAT_GUI_W32
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100214/*
215 * Version of ReadConsoleInput() that works with IME.
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100216 * Works around problems on Windows 8.
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100217 */
218 static BOOL
219read_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100220 HANDLE hInput,
221 INPUT_RECORD *lpBuffer,
222 DWORD nLength,
223 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100224{
225 enum
226 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100227 IRSIZE = 10
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100228 };
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100229 static INPUT_RECORD s_irCache[IRSIZE];
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100230 static DWORD s_dwIndex = 0;
231 static DWORD s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100232 DWORD dwEvents;
Bram Moolenaardd415a62014-02-05 14:02:27 +0100233 int head;
234 int tail;
235 int i;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100236
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200237 if (nLength == -2)
238 return (s_dwMax > 0) ? TRUE : FALSE;
239
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100240 if (!win8_or_later)
241 {
242 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200243 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
244 return ReadConsoleInputW(hInput, lpBuffer, 1, &dwEvents);
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100245 }
246
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100247 if (s_dwMax == 0)
248 {
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100249 if (nLength == -1)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200250 return PeekConsoleInputW(hInput, lpBuffer, 1, lpEvents);
251 if (!ReadConsoleInputW(hInput, s_irCache, IRSIZE, &dwEvents))
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100252 return FALSE;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100253 s_dwIndex = 0;
254 s_dwMax = dwEvents;
255 if (dwEvents == 0)
256 {
257 *lpEvents = 0;
258 return TRUE;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100259 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100260
261 if (s_dwMax > 1)
262 {
263 head = 0;
264 tail = s_dwMax - 1;
265 while (head != tail)
266 {
267 if (s_irCache[head].EventType == WINDOW_BUFFER_SIZE_EVENT
268 && s_irCache[head + 1].EventType
269 == WINDOW_BUFFER_SIZE_EVENT)
270 {
271 /* Remove duplicate event to avoid flicker. */
272 for (i = head; i < tail; ++i)
273 s_irCache[i] = s_irCache[i + 1];
274 --tail;
275 continue;
276 }
277 head++;
278 }
279 s_dwMax = tail + 1;
280 }
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100281 }
Bram Moolenaardd415a62014-02-05 14:02:27 +0100282
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100283 *lpBuffer = s_irCache[s_dwIndex];
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200284 if (!(nLength == -1 || nLength == -2) && ++s_dwIndex >= s_dwMax)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100285 s_dwMax = 0;
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100286 *lpEvents = 1;
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100287 return TRUE;
288}
289
290/*
291 * Version of PeekConsoleInput() that works with IME.
292 */
293 static BOOL
294peek_console_input(
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100295 HANDLE hInput,
296 INPUT_RECORD *lpBuffer,
297 DWORD nLength,
298 LPDWORD lpEvents)
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100299{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100300 return read_console_input(hInput, lpBuffer, -1, lpEvents);
Bram Moolenaar3a69e112014-01-10 13:51:42 +0100301}
302
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100303# ifdef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200304 static DWORD
305msg_wait_for_multiple_objects(
306 DWORD nCount,
307 LPHANDLE pHandles,
308 BOOL fWaitAll,
309 DWORD dwMilliseconds,
310 DWORD dwWakeMask)
311{
312 if (read_console_input(NULL, NULL, -2, NULL))
313 return WAIT_OBJECT_0;
314 return MsgWaitForMultipleObjects(nCount, pHandles, fWaitAll,
315 dwMilliseconds, dwWakeMask);
316}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100317# endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200318
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100319# ifndef FEAT_CLIENTSERVER
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200320 static DWORD
321wait_for_single_object(
322 HANDLE hHandle,
323 DWORD dwMilliseconds)
324{
325 if (read_console_input(NULL, NULL, -2, NULL))
326 return WAIT_OBJECT_0;
327 return WaitForSingleObject(hHandle, dwMilliseconds);
328}
Bram Moolenaar418f81b2016-02-16 20:12:02 +0100329# endif
330#endif
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +0200331
Bram Moolenaar071d4272004-06-13 20:20:40 +0000332 static void
333get_exe_name(void)
334{
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100335 /* Maximum length of $PATH is more than MAXPATHL. 8191 is often mentioned
336 * as the maximum length that works (plus a NUL byte). */
337#define MAX_ENV_PATH_LEN 8192
338 char temp[MAX_ENV_PATH_LEN];
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200339 char_u *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000340
341 if (exe_name == NULL)
342 {
343 /* store the name of the executable, may be used for $VIM */
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100344 GetModuleFileName(NULL, temp, MAX_ENV_PATH_LEN - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000345 if (*temp != NUL)
346 exe_name = FullName_save((char_u *)temp, FALSE);
347 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000348
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200349 if (exe_path == NULL && exe_name != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000350 {
Bram Moolenaar6b5ef062010-10-27 12:18:00 +0200351 exe_path = vim_strnsave(exe_name,
352 (int)(gettail_sep(exe_name) - exe_name));
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200353 if (exe_path != NULL)
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000354 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200355 /* Append our starting directory to $PATH, so that when doing
356 * "!xxd" it's found in our starting directory. Needed because
357 * SearchPath() also looks there. */
358 p = mch_getenv("PATH");
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100359 if (p == NULL
360 || STRLEN(p) + STRLEN(exe_path) + 2 < MAX_ENV_PATH_LEN)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200361 {
Bram Moolenaar27d9ece2010-11-10 15:37:05 +0100362 if (p == NULL || *p == NUL)
363 temp[0] = NUL;
364 else
365 {
366 STRCPY(temp, p);
367 STRCAT(temp, ";");
368 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200369 STRCAT(temp, exe_path);
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100370 vim_setenv((char_u *)"PATH", (char_u *)temp);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200371 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000372 }
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000373 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000374}
375
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200376/*
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100377 * Unescape characters in "p" that appear in "escaped".
378 */
379 static void
380unescape_shellxquote(char_u *p, char_u *escaped)
381{
Bram Moolenaar4336cdf2012-02-29 13:58:47 +0100382 int l = (int)STRLEN(p);
Bram Moolenaar6b707b42012-02-21 21:22:44 +0100383 int n;
384
385 while (*p != NUL)
386 {
387 if (*p == '^' && vim_strchr(escaped, p[1]) != NULL)
388 mch_memmove(p, p + 1, l--);
389#ifdef FEAT_MBYTE
390 n = (*mb_ptr2len)(p);
391#else
392 n = 1;
393#endif
394 p += n;
395 l -= n;
396 }
397}
398
399/*
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200400 * Load library "name".
401 */
402 HINSTANCE
403vimLoadLib(char *name)
404{
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200405 HINSTANCE dll = NULL;
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200406
Bram Moolenaarfaca8402012-10-21 02:37:10 +0200407 /* NOTE: Do not use mch_dirname() and mch_chdir() here, they may call
408 * vimLoadLib() recursively, which causes a stack overflow. */
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200409 if (exe_path == NULL)
410 get_exe_name();
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200411 if (exe_path != NULL)
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200412 {
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200413 WCHAR old_dirw[MAXPATHL];
414
415 if (GetCurrentDirectoryW(MAXPATHL, old_dirw) != 0)
416 {
417 /* Change directory to where the executable is, both to make
418 * sure we find a .dll there and to avoid looking for a .dll
419 * in the current directory. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +0100420 SetCurrentDirectory((LPCSTR)exe_path);
Bram Moolenaar17aa8cc2012-10-21 21:38:45 +0200421 dll = LoadLibrary(name);
422 SetCurrentDirectoryW(old_dirw);
423 return dll;
424 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200425 }
426 return dll;
427}
428
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100429#if defined(DYNAMIC_ICONV) || defined(DYNAMIC_GETTEXT) || defined(PROTO)
430/*
431 * Get related information about 'funcname' which is imported by 'hInst'.
432 * If 'info' is 0, return the function address.
433 * If 'info' is 1, return the module name which the function is imported from.
434 */
435 static void *
436get_imported_func_info(HINSTANCE hInst, const char *funcname, int info)
437{
438 PBYTE pImage = (PBYTE)hInst;
439 PIMAGE_DOS_HEADER pDOS = (PIMAGE_DOS_HEADER)hInst;
440 PIMAGE_NT_HEADERS pPE;
441 PIMAGE_IMPORT_DESCRIPTOR pImpDesc;
442 PIMAGE_THUNK_DATA pIAT; /* Import Address Table */
443 PIMAGE_THUNK_DATA pINT; /* Import Name Table */
444 PIMAGE_IMPORT_BY_NAME pImpName;
445
446 if (pDOS->e_magic != IMAGE_DOS_SIGNATURE)
447 return NULL;
448 pPE = (PIMAGE_NT_HEADERS)(pImage + pDOS->e_lfanew);
449 if (pPE->Signature != IMAGE_NT_SIGNATURE)
450 return NULL;
451 pImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)(pImage
452 + pPE->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]
453 .VirtualAddress);
454 for (; pImpDesc->FirstThunk; ++pImpDesc)
455 {
456 if (!pImpDesc->OriginalFirstThunk)
457 continue;
458 pIAT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->FirstThunk);
459 pINT = (PIMAGE_THUNK_DATA)(pImage + pImpDesc->OriginalFirstThunk);
460 for (; pIAT->u1.Function; ++pIAT, ++pINT)
461 {
462 if (IMAGE_SNAP_BY_ORDINAL(pINT->u1.Ordinal))
463 continue;
464 pImpName = (PIMAGE_IMPORT_BY_NAME)(pImage
465 + (UINT_PTR)(pINT->u1.AddressOfData));
466 if (strcmp((char *)pImpName->Name, funcname) == 0)
467 {
468 switch (info)
469 {
470 case 0:
471 return (void *)pIAT->u1.Function;
472 case 1:
473 return (void *)(pImage + pImpDesc->Name);
474 default:
475 return NULL;
476 }
477 }
478 }
479 }
480 return NULL;
481}
482
483/*
484 * Get the module handle which 'funcname' in 'hInst' is imported from.
485 */
486 HINSTANCE
487find_imported_module_by_funcname(HINSTANCE hInst, const char *funcname)
488{
489 char *modulename;
490
491 modulename = (char *)get_imported_func_info(hInst, funcname, 1);
492 if (modulename != NULL)
493 return GetModuleHandleA(modulename);
494 return NULL;
495}
496
497/*
498 * Get the address of 'funcname' which is imported by 'hInst' DLL.
499 */
500 void *
501get_dll_import_func(HINSTANCE hInst, const char *funcname)
502{
503 return get_imported_func_info(hInst, funcname, 0);
504}
505#endif
506
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507#if defined(DYNAMIC_GETTEXT) || defined(PROTO)
508# ifndef GETTEXT_DLL
509# define GETTEXT_DLL "libintl.dll"
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100510# define GETTEXT_DLL_ALT "libintl-8.dll"
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511# endif
Bram Moolenaarf6a2b082012-06-29 13:14:03 +0200512/* Dummy functions */
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000513static char *null_libintl_gettext(const char *);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200514static char *null_libintl_ngettext(const char *, const char *, unsigned long n);
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000515static char *null_libintl_textdomain(const char *);
516static char *null_libintl_bindtextdomain(const char *, const char *);
517static char *null_libintl_bind_textdomain_codeset(const char *, const char *);
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100518static int null_libintl_putenv(const char *);
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100519static int null_libintl_wputenv(const wchar_t *);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000520
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200521static HINSTANCE hLibintlDLL = NULL;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000522char *(*dyn_libintl_gettext)(const char *) = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200523char *(*dyn_libintl_ngettext)(const char *, const char *, unsigned long n)
524 = null_libintl_ngettext;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000525char *(*dyn_libintl_textdomain)(const char *) = null_libintl_textdomain;
526char *(*dyn_libintl_bindtextdomain)(const char *, const char *)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000527 = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000528char *(*dyn_libintl_bind_textdomain_codeset)(const char *, const char *)
529 = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100530int (*dyn_libintl_putenv)(const char *) = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100531int (*dyn_libintl_wputenv)(const wchar_t *) = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000532
533 int
Bram Moolenaar05540972016-01-30 20:31:25 +0100534dyn_libintl_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000535{
536 int i;
537 static struct
538 {
539 char *name;
540 FARPROC *ptr;
541 } libintl_entry[] =
542 {
543 {"gettext", (FARPROC*)&dyn_libintl_gettext},
Bram Moolenaaree695f72016-08-03 22:08:45 +0200544 {"ngettext", (FARPROC*)&dyn_libintl_ngettext},
Bram Moolenaar071d4272004-06-13 20:20:40 +0000545 {"textdomain", (FARPROC*)&dyn_libintl_textdomain},
546 {"bindtextdomain", (FARPROC*)&dyn_libintl_bindtextdomain},
547 {NULL, NULL}
548 };
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100549 HINSTANCE hmsvcrt;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000550
551 /* No need to initialize twice. */
552 if (hLibintlDLL)
553 return 1;
554 /* Load gettext library (libintl.dll) */
Bram Moolenaar923e43b2016-01-28 15:07:38 +0100555 hLibintlDLL = vimLoadLib(GETTEXT_DLL);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100556#ifdef GETTEXT_DLL_ALT
Bram Moolenaar286eacd2016-01-16 18:05:50 +0100557 if (!hLibintlDLL)
558 hLibintlDLL = vimLoadLib(GETTEXT_DLL_ALT);
Bram Moolenaar938ee832016-01-24 15:36:03 +0100559#endif
560 if (!hLibintlDLL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000561 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200562 if (p_verbose > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000563 {
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200564 verbose_enter();
565 EMSG2(_(e_loadlib), GETTEXT_DLL);
566 verbose_leave();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000567 }
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200568 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000569 }
570 for (i = 0; libintl_entry[i].name != NULL
571 && libintl_entry[i].ptr != NULL; ++i)
572 {
573 if ((*libintl_entry[i].ptr = (FARPROC)GetProcAddress(hLibintlDLL,
574 libintl_entry[i].name)) == NULL)
575 {
576 dyn_libintl_end();
577 if (p_verbose > 0)
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000578 {
579 verbose_enter();
Bram Moolenaar071d4272004-06-13 20:20:40 +0000580 EMSG2(_(e_loadfunc), libintl_entry[i].name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +0000581 verbose_leave();
582 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000583 return 0;
584 }
585 }
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000586
587 /* The bind_textdomain_codeset() function is optional. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000588 dyn_libintl_bind_textdomain_codeset = (void *)GetProcAddress(hLibintlDLL,
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000589 "bind_textdomain_codeset");
590 if (dyn_libintl_bind_textdomain_codeset == NULL)
591 dyn_libintl_bind_textdomain_codeset =
592 null_libintl_bind_textdomain_codeset;
593
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100594 /* _putenv() function for the libintl.dll is optional. */
595 hmsvcrt = find_imported_module_by_funcname(hLibintlDLL, "getenv");
596 if (hmsvcrt != NULL)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100597 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100598 dyn_libintl_putenv = (void *)GetProcAddress(hmsvcrt, "_putenv");
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100599 dyn_libintl_wputenv = (void *)GetProcAddress(hmsvcrt, "_wputenv");
600 }
601 if (dyn_libintl_putenv == NULL || dyn_libintl_putenv == _putenv)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100602 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100603 if (dyn_libintl_wputenv == NULL || dyn_libintl_wputenv == _wputenv)
604 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100605
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606 return 1;
607}
608
609 void
Bram Moolenaar05540972016-01-30 20:31:25 +0100610dyn_libintl_end(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611{
612 if (hLibintlDLL)
613 FreeLibrary(hLibintlDLL);
614 hLibintlDLL = NULL;
615 dyn_libintl_gettext = null_libintl_gettext;
Bram Moolenaaree695f72016-08-03 22:08:45 +0200616 dyn_libintl_ngettext = null_libintl_ngettext;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000617 dyn_libintl_textdomain = null_libintl_textdomain;
618 dyn_libintl_bindtextdomain = null_libintl_bindtextdomain;
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000619 dyn_libintl_bind_textdomain_codeset = null_libintl_bind_textdomain_codeset;
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100620 dyn_libintl_putenv = null_libintl_putenv;
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100621 dyn_libintl_wputenv = null_libintl_wputenv;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000622}
623
624 static char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000625null_libintl_gettext(const char *msgid)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626{
627 return (char*)msgid;
628}
629
630 static char *
Bram Moolenaaree695f72016-08-03 22:08:45 +0200631null_libintl_ngettext(
632 const char *msgid,
633 const char *msgid_plural,
634 unsigned long n)
635{
Bram Moolenaarc90f2ae2016-08-04 22:00:15 +0200636 return (char *)(n == 1 ? msgid : msgid_plural);
Bram Moolenaaree695f72016-08-03 22:08:45 +0200637}
638
Bram Moolenaaree695f72016-08-03 22:08:45 +0200639 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100640null_libintl_bindtextdomain(
641 const char *domainname UNUSED,
642 const char *dirname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000643{
644 return NULL;
645}
646
647 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100648null_libintl_bind_textdomain_codeset(
649 const char *domainname UNUSED,
650 const char *codeset UNUSED)
Bram Moolenaar293ee4d2004-12-09 21:34:53 +0000651{
652 return NULL;
653}
654
655 static char *
Bram Moolenaar1266d672017-02-01 13:43:36 +0100656null_libintl_textdomain(const char *domainname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000657{
658 return NULL;
659}
660
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200661 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100662null_libintl_putenv(const char *envstring UNUSED)
Bram Moolenaar972c3b82017-01-12 21:44:49 +0100663{
664 return 0;
665}
666
Bram Moolenaare0ab9792017-08-02 23:18:25 +0200667 static int
Bram Moolenaar1266d672017-02-01 13:43:36 +0100668null_libintl_wputenv(const wchar_t *envstring UNUSED)
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +0100669{
670 return 0;
671}
672
Bram Moolenaar071d4272004-06-13 20:20:40 +0000673#endif /* DYNAMIC_GETTEXT */
674
675/* This symbol is not defined in older versions of the SDK or Visual C++ */
676
677#ifndef VER_PLATFORM_WIN32_WINDOWS
678# define VER_PLATFORM_WIN32_WINDOWS 1
679#endif
680
681DWORD g_PlatformId;
682
683#ifdef HAVE_ACL
Bram Moolenaar82881492012-11-20 16:53:39 +0100684# ifndef PROTO
685# include <aclapi.h>
686# endif
Bram Moolenaar27515922013-06-29 15:36:26 +0200687# ifndef PROTECTED_DACL_SECURITY_INFORMATION
688# define PROTECTED_DACL_SECURITY_INFORMATION 0x80000000L
689# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690#endif
691
Bram Moolenaar27515922013-06-29 15:36:26 +0200692#ifdef HAVE_ACL
693/*
694 * Enables or disables the specified privilege.
695 */
696 static BOOL
697win32_enable_privilege(LPTSTR lpszPrivilege, BOOL bEnable)
698{
Bram Moolenaarb0d5c962014-01-12 13:24:51 +0100699 BOOL bResult;
700 LUID luid;
701 HANDLE hToken;
702 TOKEN_PRIVILEGES tokenPrivileges;
Bram Moolenaar27515922013-06-29 15:36:26 +0200703
704 if (!OpenProcessToken(GetCurrentProcess(),
705 TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
706 return FALSE;
707
708 if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
709 {
710 CloseHandle(hToken);
711 return FALSE;
712 }
713
Bram Moolenaar45500912014-07-09 20:51:07 +0200714 tokenPrivileges.PrivilegeCount = 1;
Bram Moolenaar27515922013-06-29 15:36:26 +0200715 tokenPrivileges.Privileges[0].Luid = luid;
716 tokenPrivileges.Privileges[0].Attributes = bEnable ?
717 SE_PRIVILEGE_ENABLED : 0;
718
719 bResult = AdjustTokenPrivileges(hToken, FALSE, &tokenPrivileges,
720 sizeof(TOKEN_PRIVILEGES), NULL, NULL);
721
722 CloseHandle(hToken);
723
724 return bResult && GetLastError() == ERROR_SUCCESS;
725}
726#endif
727
Bram Moolenaar071d4272004-06-13 20:20:40 +0000728/*
729 * Set g_PlatformId to VER_PLATFORM_WIN32_NT (NT) or
730 * VER_PLATFORM_WIN32_WINDOWS (Win95).
731 */
732 void
733PlatformId(void)
734{
735 static int done = FALSE;
736
737 if (!done)
738 {
739 OSVERSIONINFO ovi;
740
741 ovi.dwOSVersionInfoSize = sizeof(ovi);
742 GetVersionEx(&ovi);
743
744 g_PlatformId = ovi.dwPlatformId;
745
Bram Moolenaarf50eb782014-02-05 13:36:54 +0100746 if ((ovi.dwMajorVersion == 6 && ovi.dwMinorVersion >= 2)
747 || ovi.dwMajorVersion > 6)
748 win8_or_later = TRUE;
749
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750#ifdef HAVE_ACL
Bram Moolenaarcea912a2016-10-12 14:20:24 +0200751 /* Enable privilege for getting or setting SACLs. */
752 win32_enable_privilege(SE_SECURITY_NAME, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000753#endif
754 done = TRUE;
755 }
756}
757
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758#ifndef FEAT_GUI_W32
759
760#define SHIFT (SHIFT_PRESSED)
761#define CTRL (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED)
762#define ALT (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED)
763#define ALT_GR (RIGHT_ALT_PRESSED | LEFT_CTRL_PRESSED)
764
765
766/* When uChar.AsciiChar is 0, then we need to look at wVirtualKeyCode.
767 * We map function keys to their ANSI terminal equivalents, as produced
768 * by ANSI.SYS, for compatibility with the MS-DOS version of Vim. Any
769 * ANSI key with a value >= '\300' is nonstandard, but provided anyway
770 * so that the user can have access to all SHIFT-, CTRL-, and ALT-
771 * combinations of function/arrow/etc keys.
772 */
773
Bram Moolenaard6f676d2005-06-01 21:51:55 +0000774static const struct
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775{
776 WORD wVirtKey;
777 BOOL fAnsiKey;
778 int chAlone;
779 int chShift;
780 int chCtrl;
781 int chAlt;
782} VirtKeyMap[] =
783{
784
785/* Key ANSI alone shift ctrl alt */
786 { VK_ESCAPE,FALSE, ESC, ESC, ESC, ESC, },
787
788 { VK_F1, TRUE, ';', 'T', '^', 'h', },
789 { VK_F2, TRUE, '<', 'U', '_', 'i', },
790 { VK_F3, TRUE, '=', 'V', '`', 'j', },
791 { VK_F4, TRUE, '>', 'W', 'a', 'k', },
792 { VK_F5, TRUE, '?', 'X', 'b', 'l', },
793 { VK_F6, TRUE, '@', 'Y', 'c', 'm', },
794 { VK_F7, TRUE, 'A', 'Z', 'd', 'n', },
795 { VK_F8, TRUE, 'B', '[', 'e', 'o', },
796 { VK_F9, TRUE, 'C', '\\', 'f', 'p', },
797 { VK_F10, TRUE, 'D', ']', 'g', 'q', },
798 { VK_F11, TRUE, '\205', '\207', '\211', '\213', },
799 { VK_F12, TRUE, '\206', '\210', '\212', '\214', },
800
801 { VK_HOME, TRUE, 'G', '\302', 'w', '\303', },
802 { VK_UP, TRUE, 'H', '\304', '\305', '\306', },
803 { VK_PRIOR, TRUE, 'I', '\307', '\204', '\310', }, /*PgUp*/
804 { VK_LEFT, TRUE, 'K', '\311', 's', '\312', },
805 { VK_RIGHT, TRUE, 'M', '\313', 't', '\314', },
806 { VK_END, TRUE, 'O', '\315', 'u', '\316', },
807 { VK_DOWN, TRUE, 'P', '\317', '\320', '\321', },
808 { VK_NEXT, TRUE, 'Q', '\322', 'v', '\323', }, /*PgDn*/
809 { VK_INSERT,TRUE, 'R', '\324', '\325', '\326', },
810 { VK_DELETE,TRUE, 'S', '\327', '\330', '\331', },
811
812 { VK_SNAPSHOT,TRUE, 0, 0, 0, 'r', }, /*PrtScrn*/
813
814#if 0
815 /* Most people don't have F13-F20, but what the hell... */
816 { VK_F13, TRUE, '\332', '\333', '\334', '\335', },
817 { VK_F14, TRUE, '\336', '\337', '\340', '\341', },
818 { VK_F15, TRUE, '\342', '\343', '\344', '\345', },
819 { VK_F16, TRUE, '\346', '\347', '\350', '\351', },
820 { VK_F17, TRUE, '\352', '\353', '\354', '\355', },
821 { VK_F18, TRUE, '\356', '\357', '\360', '\361', },
822 { VK_F19, TRUE, '\362', '\363', '\364', '\365', },
823 { VK_F20, TRUE, '\366', '\367', '\370', '\371', },
824#endif
825 { VK_ADD, TRUE, 'N', 'N', 'N', 'N', }, /* keyp '+' */
826 { VK_SUBTRACT, TRUE,'J', 'J', 'J', 'J', }, /* keyp '-' */
827 /* { VK_DIVIDE, TRUE,'N', 'N', 'N', 'N', }, keyp '/' */
828 { VK_MULTIPLY, TRUE,'7', '7', '7', '7', }, /* keyp '*' */
829
830 { VK_NUMPAD0,TRUE, '\332', '\333', '\334', '\335', },
831 { VK_NUMPAD1,TRUE, '\336', '\337', '\340', '\341', },
832 { VK_NUMPAD2,TRUE, '\342', '\343', '\344', '\345', },
833 { VK_NUMPAD3,TRUE, '\346', '\347', '\350', '\351', },
834 { VK_NUMPAD4,TRUE, '\352', '\353', '\354', '\355', },
835 { VK_NUMPAD5,TRUE, '\356', '\357', '\360', '\361', },
836 { VK_NUMPAD6,TRUE, '\362', '\363', '\364', '\365', },
837 { VK_NUMPAD7,TRUE, '\366', '\367', '\370', '\371', },
838 { VK_NUMPAD8,TRUE, '\372', '\373', '\374', '\375', },
839 /* Sorry, out of number space! <negri>*/
840 { VK_NUMPAD9,TRUE, '\376', '\377', '\377', '\367', },
841
842};
843
844
845#ifdef _MSC_VER
846// The ToAscii bug destroys several registers. Need to turn off optimization
847// or the GetConsoleKeyboardLayoutName hack will fail in non-debug versions
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000848# pragma warning(push)
849# pragma warning(disable: 4748)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000850# pragma optimize("", off)
851#endif
852
853#if defined(__GNUC__) && !defined(__MINGW32__) && !defined(__CYGWIN__)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200854# define UChar UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855#else
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200856# define UChar uChar.UnicodeChar
Bram Moolenaar071d4272004-06-13 20:20:40 +0000857#endif
858
859/* The return code indicates key code size. */
860 static int
861#ifdef __BORLANDC__
862 __stdcall
863#endif
864win32_kbd_patch_key(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000865 KEY_EVENT_RECORD *pker)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000866{
867 UINT uMods = pker->dwControlKeyState;
868 static int s_iIsDead = 0;
869 static WORD awAnsiCode[2];
870 static BYTE abKeystate[256];
871
872
873 if (s_iIsDead == 2)
874 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200875 pker->UChar = (WCHAR) awAnsiCode[1];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000876 s_iIsDead = 0;
877 return 1;
878 }
879
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200880 if (pker->UChar != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881 return 1;
882
Bram Moolenaar7db5fc82010-05-24 11:59:29 +0200883 vim_memset(abKeystate, 0, sizeof (abKeystate));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000884
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885 /* Clear any pending dead keys */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200886 ToUnicode(VK_SPACE, MapVirtualKey(VK_SPACE, 0), abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887
888 if (uMods & SHIFT_PRESSED)
889 abKeystate[VK_SHIFT] = 0x80;
890 if (uMods & CAPSLOCK_ON)
891 abKeystate[VK_CAPITAL] = 1;
892
893 if ((uMods & ALT_GR) == ALT_GR)
894 {
895 abKeystate[VK_CONTROL] = abKeystate[VK_LCONTROL] =
896 abKeystate[VK_MENU] = abKeystate[VK_RMENU] = 0x80;
897 }
898
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200899 s_iIsDead = ToUnicode(pker->wVirtualKeyCode, pker->wVirtualScanCode,
900 abKeystate, awAnsiCode, 2, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901
902 if (s_iIsDead > 0)
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200903 pker->UChar = (WCHAR) awAnsiCode[0];
Bram Moolenaar071d4272004-06-13 20:20:40 +0000904
905 return s_iIsDead;
906}
907
908#ifdef _MSC_VER
909/* MUST switch optimization on again here, otherwise a call to
910 * decode_key_event() may crash (e.g. when hitting caps-lock) */
911# pragma optimize("", on)
Bram Moolenaar7b5f8322006-03-23 22:47:08 +0000912# pragma warning(pop)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913
914# if (_MSC_VER < 1100)
915/* MUST turn off global optimisation for this next function, or
916 * pressing ctrl-minus in insert mode crashes Vim when built with
917 * VC4.1. -- negri. */
918# pragma optimize("g", off)
919# endif
920#endif
921
922static BOOL g_fJustGotFocus = FALSE;
923
924/*
925 * Decode a KEY_EVENT into one or two keystrokes
926 */
927 static BOOL
928decode_key_event(
929 KEY_EVENT_RECORD *pker,
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200930 WCHAR *pch,
931 WCHAR *pch2,
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932 int *pmodifiers,
933 BOOL fDoPost)
934{
935 int i;
936 const int nModifs = pker->dwControlKeyState & (SHIFT | ALT | CTRL);
937
938 *pch = *pch2 = NUL;
939 g_fJustGotFocus = FALSE;
940
941 /* ignore key up events */
942 if (!pker->bKeyDown)
943 return FALSE;
944
945 /* ignore some keystrokes */
946 switch (pker->wVirtualKeyCode)
947 {
948 /* modifiers */
949 case VK_SHIFT:
950 case VK_CONTROL:
951 case VK_MENU: /* Alt key */
952 return FALSE;
953
954 default:
955 break;
956 }
957
958 /* special cases */
Bram Moolenaarac360bf2015-09-01 20:31:20 +0200959 if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0 && pker->UChar == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000960 {
961 /* Ctrl-6 is Ctrl-^ */
962 if (pker->wVirtualKeyCode == '6')
963 {
964 *pch = Ctrl_HAT;
965 return TRUE;
966 }
967 /* Ctrl-2 is Ctrl-@ */
968 else if (pker->wVirtualKeyCode == '2')
969 {
970 *pch = NUL;
971 return TRUE;
972 }
973 /* Ctrl-- is Ctrl-_ */
974 else if (pker->wVirtualKeyCode == 0xBD)
975 {
976 *pch = Ctrl__;
977 return TRUE;
978 }
979 }
980
981 /* Shift-TAB */
982 if (pker->wVirtualKeyCode == VK_TAB && (nModifs & SHIFT_PRESSED))
983 {
984 *pch = K_NUL;
985 *pch2 = '\017';
986 return TRUE;
987 }
988
989 for (i = sizeof(VirtKeyMap) / sizeof(VirtKeyMap[0]); --i >= 0; )
990 {
991 if (VirtKeyMap[i].wVirtKey == pker->wVirtualKeyCode)
992 {
993 if (nModifs == 0)
994 *pch = VirtKeyMap[i].chAlone;
995 else if ((nModifs & SHIFT) != 0 && (nModifs & ~SHIFT) == 0)
996 *pch = VirtKeyMap[i].chShift;
997 else if ((nModifs & CTRL) != 0 && (nModifs & ~CTRL) == 0)
998 *pch = VirtKeyMap[i].chCtrl;
999 else if ((nModifs & ALT) != 0 && (nModifs & ~ALT) == 0)
1000 *pch = VirtKeyMap[i].chAlt;
1001
1002 if (*pch != 0)
1003 {
1004 if (VirtKeyMap[i].fAnsiKey)
1005 {
1006 *pch2 = *pch;
1007 *pch = K_NUL;
1008 }
1009
1010 return TRUE;
1011 }
1012 }
1013 }
1014
1015 i = win32_kbd_patch_key(pker);
1016
1017 if (i < 0)
1018 *pch = NUL;
1019 else
1020 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001021 *pch = (i > 0) ? pker->UChar : NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001022
1023 if (pmodifiers != NULL)
1024 {
1025 /* Pass on the ALT key as a modifier, but only when not combined
1026 * with CTRL (which is ALTGR). */
1027 if ((nModifs & ALT) != 0 && (nModifs & CTRL) == 0)
1028 *pmodifiers |= MOD_MASK_ALT;
1029
1030 /* Pass on SHIFT only for special keys, because we don't know when
1031 * it's already included with the character. */
1032 if ((nModifs & SHIFT) != 0 && *pch <= 0x20)
1033 *pmodifiers |= MOD_MASK_SHIFT;
1034
1035 /* Pass on CTRL only for non-special keys, because we don't know
1036 * when it's already included with the character. And not when
1037 * combined with ALT (which is ALTGR). */
1038 if ((nModifs & CTRL) != 0 && (nModifs & ALT) == 0
1039 && *pch >= 0x20 && *pch < 0x80)
1040 *pmodifiers |= MOD_MASK_CTRL;
1041 }
1042 }
1043
1044 return (*pch != NUL);
1045}
1046
1047#ifdef _MSC_VER
1048# pragma optimize("", on)
1049#endif
1050
1051#endif /* FEAT_GUI_W32 */
1052
1053
1054#ifdef FEAT_MOUSE
1055
1056/*
1057 * For the GUI the mouse handling is in gui_w32.c.
1058 */
1059# ifdef FEAT_GUI_W32
1060 void
Bram Moolenaar1266d672017-02-01 13:43:36 +01001061mch_setmouse(int on UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001062{
1063}
1064# else
1065static int g_fMouseAvail = FALSE; /* mouse present */
1066static int g_fMouseActive = FALSE; /* mouse enabled */
1067static int g_nMouseClick = -1; /* mouse status */
1068static int g_xMouse; /* mouse x coordinate */
1069static int g_yMouse; /* mouse y coordinate */
1070
1071/*
1072 * Enable or disable mouse input
1073 */
1074 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001075mch_setmouse(int on)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076{
1077 DWORD cmodein;
1078
1079 if (!g_fMouseAvail)
1080 return;
1081
1082 g_fMouseActive = on;
1083 GetConsoleMode(g_hConIn, &cmodein);
1084
1085 if (g_fMouseActive)
1086 cmodein |= ENABLE_MOUSE_INPUT;
1087 else
1088 cmodein &= ~ENABLE_MOUSE_INPUT;
1089
1090 SetConsoleMode(g_hConIn, cmodein);
1091}
1092
Bram Moolenaar071d4272004-06-13 20:20:40 +00001093/*
1094 * Decode a MOUSE_EVENT. If it's a valid event, return MOUSE_LEFT,
1095 * MOUSE_MIDDLE, or MOUSE_RIGHT for a click; MOUSE_DRAG for a mouse
1096 * move with a button held down; and MOUSE_RELEASE after a MOUSE_DRAG
1097 * or a MOUSE_LEFT, _MIDDLE, or _RIGHT. We encode the button type,
1098 * the number of clicks, and the Shift/Ctrl/Alt modifiers in g_nMouseClick,
1099 * and we return the mouse position in g_xMouse and g_yMouse.
1100 *
1101 * Every MOUSE_LEFT, _MIDDLE, or _RIGHT will be followed by zero or more
1102 * MOUSE_DRAGs and one MOUSE_RELEASE. MOUSE_RELEASE will be followed only
1103 * by MOUSE_LEFT, _MIDDLE, or _RIGHT.
1104 *
1105 * For multiple clicks, we send, say, MOUSE_LEFT/1 click, MOUSE_RELEASE,
1106 * MOUSE_LEFT/2 clicks, MOUSE_RELEASE, MOUSE_LEFT/3 clicks, MOUSE_RELEASE, ....
1107 *
1108 * Windows will send us MOUSE_MOVED notifications whenever the mouse
1109 * moves, even if it stays within the same character cell. We ignore
1110 * all MOUSE_MOVED messages if the position hasn't really changed, and
1111 * we ignore all MOUSE_MOVED messages where no button is held down (i.e.,
1112 * we're only interested in MOUSE_DRAG).
1113 *
1114 * All of this is complicated by the code that fakes MOUSE_MIDDLE on
1115 * 2-button mouses by pressing the left & right buttons simultaneously.
1116 * In practice, it's almost impossible to click both at the same time,
1117 * so we need to delay a little. Also, we tend not to get MOUSE_RELEASE
1118 * in such cases, if the user is clicking quickly.
1119 */
1120 static BOOL
1121decode_mouse_event(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001122 MOUSE_EVENT_RECORD *pmer)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123{
1124 static int s_nOldButton = -1;
1125 static int s_nOldMouseClick = -1;
1126 static int s_xOldMouse = -1;
1127 static int s_yOldMouse = -1;
1128 static linenr_T s_old_topline = 0;
1129#ifdef FEAT_DIFF
1130 static int s_old_topfill = 0;
1131#endif
1132 static int s_cClicks = 1;
1133 static BOOL s_fReleased = TRUE;
1134 static DWORD s_dwLastClickTime = 0;
1135 static BOOL s_fNextIsMiddle = FALSE;
1136
1137 static DWORD cButtons = 0; /* number of buttons supported */
1138
1139 const DWORD LEFT = FROM_LEFT_1ST_BUTTON_PRESSED;
1140 const DWORD MIDDLE = FROM_LEFT_2ND_BUTTON_PRESSED;
1141 const DWORD RIGHT = RIGHTMOST_BUTTON_PRESSED;
1142 const DWORD LEFT_RIGHT = LEFT | RIGHT;
1143
1144 int nButton;
1145
1146 if (cButtons == 0 && !GetNumberOfConsoleMouseButtons(&cButtons))
1147 cButtons = 2;
1148
1149 if (!g_fMouseAvail || !g_fMouseActive)
1150 {
1151 g_nMouseClick = -1;
1152 return FALSE;
1153 }
1154
1155 /* get a spurious MOUSE_EVENT immediately after receiving focus; ignore */
1156 if (g_fJustGotFocus)
1157 {
1158 g_fJustGotFocus = FALSE;
1159 return FALSE;
1160 }
1161
1162 /* unprocessed mouse click? */
1163 if (g_nMouseClick != -1)
1164 return TRUE;
1165
1166 nButton = -1;
1167 g_xMouse = pmer->dwMousePosition.X;
1168 g_yMouse = pmer->dwMousePosition.Y;
1169
1170 if (pmer->dwEventFlags == MOUSE_MOVED)
1171 {
1172 /* ignore MOUSE_MOVED events if (x, y) hasn't changed. (We get these
1173 * events even when the mouse moves only within a char cell.) */
1174 if (s_xOldMouse == g_xMouse && s_yOldMouse == g_yMouse)
1175 return FALSE;
1176 }
1177
1178 /* If no buttons are pressed... */
1179 if ((pmer->dwButtonState & ((1 << cButtons) - 1)) == 0)
1180 {
1181 /* If the last thing returned was MOUSE_RELEASE, ignore this */
1182 if (s_fReleased)
1183 return FALSE;
1184
1185 nButton = MOUSE_RELEASE;
1186 s_fReleased = TRUE;
1187 }
1188 else /* one or more buttons pressed */
1189 {
1190 /* on a 2-button mouse, hold down left and right buttons
1191 * simultaneously to get MIDDLE. */
1192
1193 if (cButtons == 2 && s_nOldButton != MOUSE_DRAG)
1194 {
1195 DWORD dwLR = (pmer->dwButtonState & LEFT_RIGHT);
1196
1197 /* if either left or right button only is pressed, see if the
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001198 * next mouse event has both of them pressed */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001199 if (dwLR == LEFT || dwLR == RIGHT)
1200 {
1201 for (;;)
1202 {
1203 /* wait a short time for next input event */
1204 if (WaitForSingleObject(g_hConIn, p_mouset / 3)
1205 != WAIT_OBJECT_0)
1206 break;
1207 else
1208 {
1209 DWORD cRecords = 0;
1210 INPUT_RECORD ir;
1211 MOUSE_EVENT_RECORD* pmer2 = &ir.Event.MouseEvent;
1212
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001213 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001214
1215 if (cRecords == 0 || ir.EventType != MOUSE_EVENT
1216 || !(pmer2->dwButtonState & LEFT_RIGHT))
1217 break;
1218 else
1219 {
1220 if (pmer2->dwEventFlags != MOUSE_MOVED)
1221 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001222 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001223
1224 return decode_mouse_event(pmer2);
1225 }
1226 else if (s_xOldMouse == pmer2->dwMousePosition.X &&
1227 s_yOldMouse == pmer2->dwMousePosition.Y)
1228 {
1229 /* throw away spurious mouse move */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001230 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231
1232 /* are there any more mouse events in queue? */
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001233 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234
1235 if (cRecords==0 || ir.EventType != MOUSE_EVENT)
1236 break;
1237 }
1238 else
1239 break;
1240 }
1241 }
1242 }
1243 }
1244 }
1245
1246 if (s_fNextIsMiddle)
1247 {
1248 nButton = (pmer->dwEventFlags == MOUSE_MOVED)
1249 ? MOUSE_DRAG : MOUSE_MIDDLE;
1250 s_fNextIsMiddle = FALSE;
1251 }
1252 else if (cButtons == 2 &&
1253 ((pmer->dwButtonState & LEFT_RIGHT) == LEFT_RIGHT))
1254 {
1255 nButton = MOUSE_MIDDLE;
1256
1257 if (! s_fReleased && pmer->dwEventFlags != MOUSE_MOVED)
1258 {
1259 s_fNextIsMiddle = TRUE;
1260 nButton = MOUSE_RELEASE;
1261 }
1262 }
1263 else if ((pmer->dwButtonState & LEFT) == LEFT)
1264 nButton = MOUSE_LEFT;
1265 else if ((pmer->dwButtonState & MIDDLE) == MIDDLE)
1266 nButton = MOUSE_MIDDLE;
1267 else if ((pmer->dwButtonState & RIGHT) == RIGHT)
1268 nButton = MOUSE_RIGHT;
1269
1270 if (! s_fReleased && ! s_fNextIsMiddle
1271 && nButton != s_nOldButton && s_nOldButton != MOUSE_DRAG)
1272 return FALSE;
1273
1274 s_fReleased = s_fNextIsMiddle;
1275 }
1276
1277 if (pmer->dwEventFlags == 0 || pmer->dwEventFlags == DOUBLE_CLICK)
1278 {
1279 /* button pressed or released, without mouse moving */
1280 if (nButton != -1 && nButton != MOUSE_RELEASE)
1281 {
1282 DWORD dwCurrentTime = GetTickCount();
1283
1284 if (s_xOldMouse != g_xMouse
1285 || s_yOldMouse != g_yMouse
1286 || s_nOldButton != nButton
1287 || s_old_topline != curwin->w_topline
1288#ifdef FEAT_DIFF
1289 || s_old_topfill != curwin->w_topfill
1290#endif
1291 || (int)(dwCurrentTime - s_dwLastClickTime) > p_mouset)
1292 {
1293 s_cClicks = 1;
1294 }
1295 else if (++s_cClicks > 4)
1296 {
1297 s_cClicks = 1;
1298 }
1299
1300 s_dwLastClickTime = dwCurrentTime;
1301 }
1302 }
1303 else if (pmer->dwEventFlags == MOUSE_MOVED)
1304 {
1305 if (nButton != -1 && nButton != MOUSE_RELEASE)
1306 nButton = MOUSE_DRAG;
1307
1308 s_cClicks = 1;
1309 }
1310
1311 if (nButton == -1)
1312 return FALSE;
1313
1314 if (nButton != MOUSE_RELEASE)
1315 s_nOldButton = nButton;
1316
1317 g_nMouseClick = nButton;
1318
1319 if (pmer->dwControlKeyState & SHIFT_PRESSED)
1320 g_nMouseClick |= MOUSE_SHIFT;
1321 if (pmer->dwControlKeyState & (RIGHT_CTRL_PRESSED | LEFT_CTRL_PRESSED))
1322 g_nMouseClick |= MOUSE_CTRL;
1323 if (pmer->dwControlKeyState & (RIGHT_ALT_PRESSED | LEFT_ALT_PRESSED))
1324 g_nMouseClick |= MOUSE_ALT;
1325
1326 if (nButton != MOUSE_DRAG && nButton != MOUSE_RELEASE)
1327 SET_NUM_MOUSE_CLICKS(g_nMouseClick, s_cClicks);
1328
1329 /* only pass on interesting (i.e., different) mouse events */
1330 if (s_xOldMouse == g_xMouse
1331 && s_yOldMouse == g_yMouse
1332 && s_nOldMouseClick == g_nMouseClick)
1333 {
1334 g_nMouseClick = -1;
1335 return FALSE;
1336 }
1337
1338 s_xOldMouse = g_xMouse;
1339 s_yOldMouse = g_yMouse;
1340 s_old_topline = curwin->w_topline;
1341#ifdef FEAT_DIFF
1342 s_old_topfill = curwin->w_topfill;
1343#endif
1344 s_nOldMouseClick = g_nMouseClick;
1345
1346 return TRUE;
1347}
1348
1349# endif /* FEAT_GUI_W32 */
1350#endif /* FEAT_MOUSE */
1351
1352
1353#ifdef MCH_CURSOR_SHAPE
1354/*
1355 * Set the shape of the cursor.
1356 * 'thickness' can be from 1 (thin) to 99 (block)
1357 */
1358 static void
1359mch_set_cursor_shape(int thickness)
1360{
1361 CONSOLE_CURSOR_INFO ConsoleCursorInfo;
1362 ConsoleCursorInfo.dwSize = thickness;
1363 ConsoleCursorInfo.bVisible = s_cursor_visible;
1364
1365 SetConsoleCursorInfo(g_hConOut, &ConsoleCursorInfo);
1366 if (s_cursor_visible)
1367 SetConsoleCursorPosition(g_hConOut, g_coord);
1368}
1369
1370 void
1371mch_update_cursor(void)
1372{
1373 int idx;
1374 int thickness;
1375
1376 /*
1377 * How the cursor is drawn depends on the current mode.
1378 */
1379 idx = get_shape_idx(FALSE);
1380
1381 if (shape_table[idx].shape == SHAPE_BLOCK)
1382 thickness = 99; /* 100 doesn't work on W95 */
1383 else
1384 thickness = shape_table[idx].percentage;
1385 mch_set_cursor_shape(thickness);
1386}
1387#endif
1388
1389#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1390/*
1391 * Handle FOCUS_EVENT.
1392 */
1393 static void
1394handle_focus_event(INPUT_RECORD ir)
1395{
1396 g_fJustGotFocus = ir.Event.FocusEvent.bSetFocus;
1397 ui_focus_change((int)g_fJustGotFocus);
1398}
1399
1400/*
1401 * Wait until console input from keyboard or mouse is available,
1402 * or the time is up.
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001403 * When "ignore_input" is TRUE even wait when input is available.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001404 * Return TRUE if something is available FALSE if not.
1405 */
1406 static int
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001407WaitForChar(long msec, int ignore_input)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001408{
1409 DWORD dwNow = 0, dwEndTime = 0;
1410 INPUT_RECORD ir;
1411 DWORD cRecords;
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001412 WCHAR ch, ch2;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001413#ifdef FEAT_TIMERS
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001414 int tb_change_cnt = typebuf.tb_change_cnt;
Bram Moolenaar4445f7e2016-04-20 20:55:56 +02001415#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001416
1417 if (msec > 0)
1418 /* Wait until the specified time has elapsed. */
1419 dwEndTime = GetTickCount() + msec;
1420 else if (msec < 0)
1421 /* Wait forever. */
1422 dwEndTime = INFINITE;
1423
1424 /* We need to loop until the end of the time period, because
1425 * we might get multiple unusable mouse events in that time.
1426 */
1427 for (;;)
1428 {
Bram Moolenaarca568ae2016-02-01 21:32:58 +01001429#ifdef MESSAGE_QUEUE
1430 parse_queued_messages();
1431#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001432#ifdef FEAT_MZSCHEME
1433 mzvim_check_threads();
1434#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001435#ifdef FEAT_CLIENTSERVER
1436 serverProcessPendingMessages();
1437#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001438
Bram Moolenaar071d4272004-06-13 20:20:40 +00001439 if (0
1440#ifdef FEAT_MOUSE
1441 || g_nMouseClick != -1
1442#endif
1443#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001444 || (!ignore_input && input_available())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001445#endif
1446 )
1447 return TRUE;
1448
1449 if (msec > 0)
1450 {
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001451 /* If the specified wait time has passed, return. Beware that
1452 * GetTickCount() may wrap around (overflow). */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001453 dwNow = GetTickCount();
Bram Moolenaarb7512b72013-08-10 12:45:09 +02001454 if ((int)(dwNow - dwEndTime) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 break;
1456 }
1457 if (msec != 0)
1458 {
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001459 DWORD dwWaitTime = dwEndTime - dwNow;
1460
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01001461#ifdef FEAT_JOB_CHANNEL
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001462 /* Check channel while waiting for input. */
Bram Moolenaar9186a272016-02-23 19:34:01 +01001463 if (dwWaitTime > 100)
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001464 {
Bram Moolenaar9186a272016-02-23 19:34:01 +01001465 dwWaitTime = 100;
Bram Moolenaar8a8199e2016-11-26 15:13:33 +01001466 /* If there is readahead then parse_queued_messages() timed out
1467 * and we should call it again soon. */
1468 if (channel_any_readahead())
1469 dwWaitTime = 10;
1470 }
Bram Moolenaar9186a272016-02-23 19:34:01 +01001471#endif
Bram Moolenaarc3719bd2017-11-18 22:13:31 +01001472#ifdef FEAT_BEVAL_GUI
Bram Moolenaar59716a22017-03-01 20:32:44 +01001473 if (p_beval && dwWaitTime > 100)
1474 /* The 'balloonexpr' may indirectly invoke a callback while
1475 * waiting for a character, need to check often. */
1476 dwWaitTime = 100;
1477#endif
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001478#ifdef FEAT_MZSCHEME
1479 if (mzthreads_allowed() && p_mzq > 0
1480 && (msec < 0 || (long)dwWaitTime > p_mzq))
1481 dwWaitTime = p_mzq; /* don't wait longer than 'mzquantum' */
1482#endif
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001483#ifdef FEAT_TIMERS
1484 {
1485 long due_time;
1486
1487 /* When waiting very briefly don't trigger timers. */
1488 if (dwWaitTime > 10)
1489 {
1490 /* Trigger timers and then get the time in msec until the
1491 * next one is due. Wait up to that time. */
1492 due_time = check_due_timer();
Bram Moolenaar40b1b542016-04-20 20:18:23 +02001493 if (typebuf.tb_change_cnt != tb_change_cnt)
1494 {
1495 /* timer may have used feedkeys() */
1496 return FALSE;
1497 }
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001498 if (due_time > 0 && dwWaitTime > (DWORD)due_time)
1499 dwWaitTime = due_time;
1500 }
1501 }
1502#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001503#ifdef FEAT_CLIENTSERVER
1504 /* Wait for either an event on the console input or a message in
1505 * the client-server window. */
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001506 if (msg_wait_for_multiple_objects(1, &g_hConIn, FALSE,
Bram Moolenaar325b7a22004-07-05 15:58:32 +00001507 dwWaitTime, QS_SENDMESSAGE) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001508#else
Bram Moolenaarbb86ebb2015-08-04 19:27:05 +02001509 if (wait_for_single_object(g_hConIn, dwWaitTime) != WAIT_OBJECT_0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510#endif
1511 continue;
1512 }
1513
1514 cRecords = 0;
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001515 peek_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516
1517#ifdef FEAT_MBYTE_IME
1518 if (State & CMDLINE && msg_row == Rows - 1)
1519 {
1520 CONSOLE_SCREEN_BUFFER_INFO csbi;
1521
1522 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
1523 {
1524 if (csbi.dwCursorPosition.Y != msg_row)
1525 {
1526 /* The screen is now messed up, must redraw the
1527 * command line and later all the windows. */
1528 redraw_all_later(CLEAR);
1529 cmdline_row -= (msg_row - csbi.dwCursorPosition.Y);
1530 redrawcmd();
1531 }
1532 }
1533 }
1534#endif
1535
1536 if (cRecords > 0)
1537 {
1538 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown)
1539 {
1540#ifdef FEAT_MBYTE_IME
1541 /* Windows IME sends two '\n's with only one 'ENTER'. First:
1542 * wVirtualKeyCode == 13. second: wVirtualKeyCode == 0 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001543 if (ir.Event.KeyEvent.UChar == 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00001544 && ir.Event.KeyEvent.wVirtualKeyCode == 13)
1545 {
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001546 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001547 continue;
1548 }
1549#endif
1550 if (decode_key_event(&ir.Event.KeyEvent, &ch, &ch2,
1551 NULL, FALSE))
1552 return TRUE;
1553 }
1554
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001555 read_console_input(g_hConIn, &ir, 1, &cRecords);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001556
1557 if (ir.EventType == FOCUS_EVENT)
1558 handle_focus_event(ir);
1559 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1560 shell_resized();
1561#ifdef FEAT_MOUSE
1562 else if (ir.EventType == MOUSE_EVENT
1563 && decode_mouse_event(&ir.Event.MouseEvent))
1564 return TRUE;
1565#endif
1566 }
1567 else if (msec == 0)
1568 break;
1569 }
1570
1571#ifdef FEAT_CLIENTSERVER
1572 /* Something might have been received while we were waiting. */
1573 if (input_available())
1574 return TRUE;
1575#endif
Bram Moolenaarf12d9832016-01-29 21:11:25 +01001576
Bram Moolenaar071d4272004-06-13 20:20:40 +00001577 return FALSE;
1578}
1579
1580#ifndef FEAT_GUI_MSWIN
1581/*
1582 * return non-zero if a character is available
1583 */
1584 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00001585mch_char_avail(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001586{
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001587 return WaitForChar(0L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001588}
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001589
1590# if defined(FEAT_TERMINAL) || defined(PROTO)
1591/*
1592 * Check for any pending input or messages.
1593 */
1594 int
1595mch_check_messages(void)
1596{
1597 return WaitForChar(0L, TRUE);
1598}
1599# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001600#endif
1601
1602/*
1603 * Create the console input. Used when reading stdin doesn't work.
1604 */
1605 static void
1606create_conin(void)
1607{
1608 g_hConIn = CreateFile("CONIN$", GENERIC_READ|GENERIC_WRITE,
1609 FILE_SHARE_READ|FILE_SHARE_WRITE,
1610 (LPSECURITY_ATTRIBUTES) NULL,
Bram Moolenaareb3593b2006-04-22 22:33:57 +00001611 OPEN_EXISTING, 0, (HANDLE)NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 did_create_conin = TRUE;
1613}
1614
1615/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01001616 * Get a keystroke or a mouse event, use a blocking wait.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001618 static WCHAR
1619tgetch(int *pmodifiers, WCHAR *pch2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620{
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001621 WCHAR ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001622
1623 for (;;)
1624 {
1625 INPUT_RECORD ir;
1626 DWORD cRecords = 0;
1627
1628#ifdef FEAT_CLIENTSERVER
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001629 (void)WaitForChar(-1L, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630 if (input_available())
1631 return 0;
1632# ifdef FEAT_MOUSE
1633 if (g_nMouseClick != -1)
1634 return 0;
1635# endif
1636#endif
Bram Moolenaar3a69e112014-01-10 13:51:42 +01001637 if (read_console_input(g_hConIn, &ir, 1, &cRecords) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001638 {
1639 if (did_create_conin)
1640 read_error_exit();
1641 create_conin();
1642 continue;
1643 }
1644
1645 if (ir.EventType == KEY_EVENT)
1646 {
1647 if (decode_key_event(&ir.Event.KeyEvent, &ch, pch2,
1648 pmodifiers, TRUE))
1649 return ch;
1650 }
1651 else if (ir.EventType == FOCUS_EVENT)
1652 handle_focus_event(ir);
1653 else if (ir.EventType == WINDOW_BUFFER_SIZE_EVENT)
1654 shell_resized();
1655#ifdef FEAT_MOUSE
1656 else if (ir.EventType == MOUSE_EVENT)
1657 {
1658 if (decode_mouse_event(&ir.Event.MouseEvent))
1659 return 0;
1660 }
1661#endif
1662 }
1663}
1664#endif /* !FEAT_GUI_W32 */
1665
1666
1667/*
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02001668 * mch_inchar(): low-level input function.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 * Get one or more characters from the keyboard or the mouse.
1670 * If time == 0, do not wait for characters.
1671 * If time == n, wait a short time for characters.
1672 * If time == -1, wait forever for characters.
1673 * Returns the number of characters read into buf.
1674 */
1675 int
1676mch_inchar(
Bram Moolenaar1266d672017-02-01 13:43:36 +01001677 char_u *buf UNUSED,
1678 int maxlen UNUSED,
1679 long time UNUSED,
1680 int tb_change_cnt UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001681{
1682#ifndef FEAT_GUI_W32 /* this isn't used for the GUI */
1683
1684 int len;
1685 int c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001686#define TYPEAHEADLEN 20
1687 static char_u typeahead[TYPEAHEADLEN]; /* previously typed bytes. */
1688 static int typeaheadlen = 0;
1689
1690 /* First use any typeahead that was kept because "buf" was too small. */
1691 if (typeaheadlen > 0)
1692 goto theend;
1693
Bram Moolenaar071d4272004-06-13 20:20:40 +00001694 if (time >= 0)
1695 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001696 if (!WaitForChar(time, FALSE)) /* no character available */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001697 return 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698 }
1699 else /* time == -1, wait forever */
1700 {
1701 mch_set_winsize_now(); /* Allow winsize changes from now on */
1702
Bram Moolenaar3918c952005-03-15 22:34:55 +00001703 /*
1704 * If there is no character available within 2 seconds (default)
1705 * write the autoscript file to disk. Or cause the CursorHold event
1706 * to be triggered.
1707 */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001708 if (!WaitForChar(p_ut, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001709 {
1710#ifdef FEAT_AUTOCMD
Bram Moolenaard35f9712005-12-18 22:02:33 +00001711 if (trigger_cursorhold() && maxlen >= 3)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001712 {
Bram Moolenaar3918c952005-03-15 22:34:55 +00001713 buf[0] = K_SPECIAL;
1714 buf[1] = KS_EXTRA;
1715 buf[2] = (int)KE_CURSORHOLD;
1716 return 3;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001717 }
1718#endif
Bram Moolenaar702517d2005-06-27 22:34:07 +00001719 before_blocking();
Bram Moolenaar071d4272004-06-13 20:20:40 +00001720 }
1721 }
1722
1723 /*
1724 * Try to read as many characters as there are, until the buffer is full.
1725 */
1726
1727 /* we will get at least one key. Get more if they are available. */
1728 g_fCBrkPressed = FALSE;
1729
1730#ifdef MCH_WRITE_DUMP
1731 if (fdDump)
1732 fputc('[', fdDump);
1733#endif
1734
1735 /* Keep looping until there is something in the typeahead buffer and more
1736 * to get and still room in the buffer (up to two bytes for a char and
1737 * three bytes for a modifier). */
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02001738 while ((typeaheadlen == 0 || WaitForChar(0L, FALSE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 && typeaheadlen + 5 <= TYPEAHEADLEN)
1740 {
1741 if (typebuf_changed(tb_change_cnt))
1742 {
1743 /* "buf" may be invalid now if a client put something in the
1744 * typeahead buffer and "buf" is in the typeahead buffer. */
1745 typeaheadlen = 0;
1746 break;
1747 }
1748#ifdef FEAT_MOUSE
1749 if (g_nMouseClick != -1)
1750 {
1751# ifdef MCH_WRITE_DUMP
1752 if (fdDump)
1753 fprintf(fdDump, "{%02x @ %d, %d}",
1754 g_nMouseClick, g_xMouse, g_yMouse);
1755# endif
1756 typeahead[typeaheadlen++] = ESC + 128;
1757 typeahead[typeaheadlen++] = 'M';
1758 typeahead[typeaheadlen++] = g_nMouseClick;
1759 typeahead[typeaheadlen++] = g_xMouse + '!';
1760 typeahead[typeaheadlen++] = g_yMouse + '!';
1761 g_nMouseClick = -1;
1762 }
1763 else
1764#endif
1765 {
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001766 WCHAR ch2 = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 int modifiers = 0;
1768
1769 c = tgetch(&modifiers, &ch2);
1770
1771 if (typebuf_changed(tb_change_cnt))
1772 {
1773 /* "buf" may be invalid now if a client put something in the
1774 * typeahead buffer and "buf" is in the typeahead buffer. */
1775 typeaheadlen = 0;
1776 break;
1777 }
1778
1779 if (c == Ctrl_C && ctrl_c_interrupts)
1780 {
1781#if defined(FEAT_CLIENTSERVER)
1782 trash_input_buf();
1783#endif
1784 got_int = TRUE;
1785 }
1786
1787#ifdef FEAT_MOUSE
1788 if (g_nMouseClick == -1)
1789#endif
1790 {
1791 int n = 1;
Bram Moolenaar45500912014-07-09 20:51:07 +02001792 int conv = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793
Bram Moolenaarac360bf2015-09-01 20:31:20 +02001794#ifdef FEAT_MBYTE
1795 if (ch2 == NUL)
1796 {
1797 int i;
1798 char_u *p;
1799 WCHAR ch[2];
1800
1801 ch[0] = c;
1802 if (c >= 0xD800 && c <= 0xDBFF) /* High surrogate */
1803 {
1804 ch[1] = tgetch(&modifiers, &ch2);
1805 n++;
1806 }
1807 p = utf16_to_enc(ch, &n);
1808 if (p != NULL)
1809 {
1810 for (i = 0; i < n; i++)
1811 typeahead[typeaheadlen + i] = p[i];
1812 vim_free(p);
1813 }
1814 }
1815 else
1816#endif
1817 typeahead[typeaheadlen] = c;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 if (ch2 != NUL)
1819 {
Bram Moolenaar3660a102017-11-28 18:07:59 +01001820 if (c == K_NUL)
1821 {
1822 /* fAnsiKey */
1823 typeahead[typeaheadlen + n] = (char_u)ch2;
1824 n++;
1825 }
1826 else
1827 {
1828 typeahead[typeaheadlen + n] = 3;
1829 typeahead[typeaheadlen + n + 1] = (char_u)ch2;
1830 n += 2;
1831 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001833
Bram Moolenaar45500912014-07-09 20:51:07 +02001834 if (conv)
1835 {
1836 char_u *p = typeahead + typeaheadlen;
Bram Moolenaar45500912014-07-09 20:51:07 +02001837
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001838 if (*p != K_NUL)
Bram Moolenaar45500912014-07-09 20:51:07 +02001839 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001840 char_u *e = typeahead + TYPEAHEADLEN;
1841
1842 while (*p && p < e)
Bram Moolenaar45500912014-07-09 20:51:07 +02001843 {
Bram Moolenaar1ec4dd42015-01-20 19:39:35 +01001844 if (*p == K_NUL)
1845 {
1846 ++p;
1847 mch_memmove(p + 1, p, ((size_t)(e - p)) - 1);
1848 *p = 3;
1849 ++n;
1850 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001851 ++p;
Bram Moolenaar45500912014-07-09 20:51:07 +02001852 }
Bram Moolenaar45500912014-07-09 20:51:07 +02001853 }
1854 }
1855
Bram Moolenaar071d4272004-06-13 20:20:40 +00001856 /* Use the ALT key to set the 8th bit of the character
1857 * when it's one byte, the 8th bit isn't set yet and not
1858 * using a double-byte encoding (would become a lead
1859 * byte). */
1860 if ((modifiers & MOD_MASK_ALT)
1861 && n == 1
1862 && (typeahead[typeaheadlen] & 0x80) == 0
1863#ifdef FEAT_MBYTE
1864 && !enc_dbcs
1865#endif
1866 )
1867 {
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001868#ifdef FEAT_MBYTE
1869 n = (*mb_char2bytes)(typeahead[typeaheadlen] | 0x80,
1870 typeahead + typeaheadlen);
1871#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001872 typeahead[typeaheadlen] |= 0x80;
Bram Moolenaar85a3e5c2007-11-20 16:22:16 +00001873#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001874 modifiers &= ~MOD_MASK_ALT;
1875 }
1876
1877 if (modifiers != 0)
1878 {
1879 /* Prepend modifiers to the character. */
1880 mch_memmove(typeahead + typeaheadlen + 3,
1881 typeahead + typeaheadlen, n);
1882 typeahead[typeaheadlen++] = K_SPECIAL;
1883 typeahead[typeaheadlen++] = (char_u)KS_MODIFIER;
1884 typeahead[typeaheadlen++] = modifiers;
1885 }
1886
1887 typeaheadlen += n;
1888
1889#ifdef MCH_WRITE_DUMP
1890 if (fdDump)
1891 fputc(c, fdDump);
1892#endif
1893 }
1894 }
1895 }
1896
1897#ifdef MCH_WRITE_DUMP
1898 if (fdDump)
1899 {
1900 fputs("]\n", fdDump);
1901 fflush(fdDump);
1902 }
1903#endif
1904
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905theend:
1906 /* Move typeahead to "buf", as much as fits. */
1907 len = 0;
1908 while (len < maxlen && typeaheadlen > 0)
1909 {
1910 buf[len++] = typeahead[0];
1911 mch_memmove(typeahead, typeahead + 1, --typeaheadlen);
1912 }
1913 return len;
1914
1915#else /* FEAT_GUI_W32 */
1916 return 0;
1917#endif /* FEAT_GUI_W32 */
1918}
1919
Bram Moolenaar82881492012-11-20 16:53:39 +01001920#ifndef PROTO
1921# ifndef __MINGW32__
1922# include <shellapi.h> /* required for FindExecutable() */
1923# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924#endif
1925
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001926/*
Bram Moolenaar43663192017-03-05 14:29:12 +01001927 * If "use_path" is TRUE: Return TRUE if "name" is in $PATH.
1928 * If "use_path" is FALSE: Return TRUE if "name" exists.
1929 * When returning TRUE and "path" is not NULL save the path and set "*path" to
1930 * the allocated memory.
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00001931 * TODO: Should somehow check if it's really executable.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001932 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001933 static int
Bram Moolenaar43663192017-03-05 14:29:12 +01001934executable_exists(char *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001935{
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001936 char *dum;
1937 char fname[_MAX_PATH];
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001938 char *curpath, *newpath;
1939 long n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001940
Bram Moolenaar43663192017-03-05 14:29:12 +01001941 if (!use_path)
1942 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01001943 if (mch_getperm((char_u *)name) != -1 && !mch_isdir((char_u *)name))
Bram Moolenaar43663192017-03-05 14:29:12 +01001944 {
1945 if (path != NULL)
Bram Moolenaar066029e2017-03-05 15:19:32 +01001946 {
Bram Moolenaarf7e894d2017-03-05 19:49:13 +01001947 if (mch_isFullName((char_u *)name))
Bram Moolenaar066029e2017-03-05 15:19:32 +01001948 *path = vim_strsave((char_u *)name);
1949 else
1950 *path = FullName_save((char_u *)name, FALSE);
1951 }
Bram Moolenaar43663192017-03-05 14:29:12 +01001952 return TRUE;
1953 }
1954 return FALSE;
1955 }
1956
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001957#ifdef FEAT_MBYTE
1958 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001959 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001960 WCHAR *p = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001961 WCHAR fnamew[_MAX_PATH];
1962 WCHAR *dumw;
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001963 WCHAR *wcurpath, *wnewpath;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001964
1965 if (p != NULL)
1966 {
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001967 wcurpath = _wgetenv(L"PATH");
1968 wnewpath = (WCHAR*)alloc((unsigned)(wcslen(wcurpath) + 3)
1969 * sizeof(WCHAR));
1970 if (wnewpath == NULL)
1971 return FALSE;
1972 wcscpy(wnewpath, L".;");
1973 wcscat(wnewpath, wcurpath);
1974 n = (long)SearchPathW(wnewpath, p, NULL, _MAX_PATH, fnamew, &dumw);
1975 vim_free(wnewpath);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001976 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02001977 if (n == 0)
1978 return FALSE;
1979 if (GetFileAttributesW(fnamew) & FILE_ATTRIBUTE_DIRECTORY)
1980 return FALSE;
1981 if (path != NULL)
1982 *path = utf16_to_enc(fnamew, NULL);
1983 return TRUE;
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001984 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001985 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001986#endif
Bram Moolenaarc40bdee2014-08-29 17:45:32 +02001987
1988 curpath = getenv("PATH");
1989 newpath = (char*)alloc((unsigned)(STRLEN(curpath) + 3));
1990 if (newpath == NULL)
1991 return FALSE;
1992 STRCPY(newpath, ".;");
1993 STRCAT(newpath, curpath);
1994 n = (long)SearchPath(newpath, name, NULL, _MAX_PATH, fname, &dum);
1995 vim_free(newpath);
1996 if (n == 0)
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001997 return FALSE;
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01001998 if (mch_isdir((char_u *)fname))
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00001999 return FALSE;
Bram Moolenaarc7f02552014-04-01 21:00:59 +02002000 if (path != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002001 *path = vim_strsave((char_u *)fname);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00002002 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003}
2004
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002005#if ((defined(__MINGW32__) || defined (__CYGWIN32__)) && \
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02002006 __MSVCRT_VERSION__ >= 0x800) || (defined(_MSC_VER) && _MSC_VER >= 1400)
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002007/*
2008 * Bad parameter handler.
2009 *
2010 * Certain MS CRT functions will intentionally crash when passed invalid
2011 * parameters to highlight possible security holes. Setting this function as
2012 * the bad parameter handler will prevent the crash.
2013 *
2014 * In debug builds the parameters contain CRT information that might help track
2015 * down the source of a problem, but in non-debug builds the arguments are all
2016 * NULL/0. Debug builds will also produce assert dialogs from the CRT, it is
2017 * worth allowing these to make debugging of issues easier.
2018 */
2019 static void
2020bad_param_handler(const wchar_t *expression,
2021 const wchar_t *function,
2022 const wchar_t *file,
2023 unsigned int line,
2024 uintptr_t pReserved)
2025{
2026}
2027
2028# define SET_INVALID_PARAM_HANDLER \
2029 ((void)_set_invalid_parameter_handler(bad_param_handler))
2030#else
2031# define SET_INVALID_PARAM_HANDLER
2032#endif
2033
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034#ifdef FEAT_GUI_W32
2035
2036/*
2037 * GUI version of mch_init().
2038 */
2039 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002040mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041{
2042#ifndef __MINGW32__
2043 extern int _fmode;
2044#endif
2045
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002046 /* Silently handle invalid parameters to CRT functions */
2047 SET_INVALID_PARAM_HANDLER;
2048
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049 /* Let critical errors result in a failure, not in a dialog box. Required
2050 * for the timestamp test to work on removed floppies. */
2051 SetErrorMode(SEM_FAILCRITICALERRORS);
2052
2053 _fmode = O_BINARY; /* we do our own CR-LF translation */
2054
2055 /* Specify window size. Is there a place to get the default from? */
2056 Rows = 25;
2057 Columns = 80;
2058
2059 /* Look for 'vimrun' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 {
2061 char_u vimrun_location[_MAX_PATH + 4];
2062
2063 /* First try in same directory as gvim.exe */
2064 STRCPY(vimrun_location, exe_name);
2065 STRCPY(gettail(vimrun_location), "vimrun.exe");
2066 if (mch_getperm(vimrun_location) >= 0)
2067 {
2068 if (*skiptowhite(vimrun_location) != NUL)
2069 {
2070 /* Enclose path with white space in double quotes. */
2071 mch_memmove(vimrun_location + 1, vimrun_location,
2072 STRLEN(vimrun_location) + 1);
2073 *vimrun_location = '"';
2074 STRCPY(gettail(vimrun_location), "vimrun\" ");
2075 }
2076 else
2077 STRCPY(gettail(vimrun_location), "vimrun ");
2078
2079 vimrun_path = (char *)vim_strsave(vimrun_location);
2080 s_dont_use_vimrun = FALSE;
2081 }
Bram Moolenaar43663192017-03-05 14:29:12 +01002082 else if (executable_exists("vimrun.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002083 s_dont_use_vimrun = FALSE;
2084
2085 /* Don't give the warning for a missing vimrun.exe right now, but only
2086 * when vimrun was supposed to be used. Don't bother people that do
2087 * not need vimrun.exe. */
2088 if (s_dont_use_vimrun)
2089 need_vimrun_warning = TRUE;
2090 }
2091
2092 /*
2093 * If "finstr.exe" doesn't exist, use "grep -n" for 'grepprg'.
2094 * Otherwise the default "findstr /n" is used.
2095 */
Bram Moolenaar43663192017-03-05 14:29:12 +01002096 if (!executable_exists("findstr.exe", NULL, TRUE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097 set_option_value((char_u *)"grepprg", 0, (char_u *)"grep -n", 0);
2098
2099#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002100 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002101#endif
2102}
2103
2104
2105#else /* FEAT_GUI_W32 */
2106
2107#define SRWIDTH(sr) ((sr).Right - (sr).Left + 1)
2108#define SRHEIGHT(sr) ((sr).Bottom - (sr).Top + 1)
2109
2110/*
2111 * ClearConsoleBuffer()
2112 * Description:
2113 * Clears the entire contents of the console screen buffer, using the
2114 * specified attribute.
2115 * Returns:
2116 * TRUE on success
2117 */
2118 static BOOL
2119ClearConsoleBuffer(WORD wAttribute)
2120{
2121 CONSOLE_SCREEN_BUFFER_INFO csbi;
2122 COORD coord;
2123 DWORD NumCells, dummy;
2124
2125 if (!GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2126 return FALSE;
2127
2128 NumCells = csbi.dwSize.X * csbi.dwSize.Y;
2129 coord.X = 0;
2130 coord.Y = 0;
2131 if (!FillConsoleOutputCharacter(g_hConOut, ' ', NumCells,
2132 coord, &dummy))
2133 {
2134 return FALSE;
2135 }
2136 if (!FillConsoleOutputAttribute(g_hConOut, wAttribute, NumCells,
2137 coord, &dummy))
2138 {
2139 return FALSE;
2140 }
2141
2142 return TRUE;
2143}
2144
2145/*
2146 * FitConsoleWindow()
2147 * Description:
2148 * Checks if the console window will fit within given buffer dimensions.
2149 * Also, if requested, will shrink the window to fit.
2150 * Returns:
2151 * TRUE on success
2152 */
2153 static BOOL
2154FitConsoleWindow(
2155 COORD dwBufferSize,
2156 BOOL WantAdjust)
2157{
2158 CONSOLE_SCREEN_BUFFER_INFO csbi;
2159 COORD dwWindowSize;
2160 BOOL NeedAdjust = FALSE;
2161
2162 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
2163 {
2164 /*
2165 * A buffer resize will fail if the current console window does
2166 * not lie completely within that buffer. To avoid this, we might
2167 * have to move and possibly shrink the window.
2168 */
2169 if (csbi.srWindow.Right >= dwBufferSize.X)
2170 {
2171 dwWindowSize.X = SRWIDTH(csbi.srWindow);
2172 if (dwWindowSize.X > dwBufferSize.X)
2173 dwWindowSize.X = dwBufferSize.X;
2174 csbi.srWindow.Right = dwBufferSize.X - 1;
2175 csbi.srWindow.Left = dwBufferSize.X - dwWindowSize.X;
2176 NeedAdjust = TRUE;
2177 }
2178 if (csbi.srWindow.Bottom >= dwBufferSize.Y)
2179 {
2180 dwWindowSize.Y = SRHEIGHT(csbi.srWindow);
2181 if (dwWindowSize.Y > dwBufferSize.Y)
2182 dwWindowSize.Y = dwBufferSize.Y;
2183 csbi.srWindow.Bottom = dwBufferSize.Y - 1;
2184 csbi.srWindow.Top = dwBufferSize.Y - dwWindowSize.Y;
2185 NeedAdjust = TRUE;
2186 }
2187 if (NeedAdjust && WantAdjust)
2188 {
2189 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &csbi.srWindow))
2190 return FALSE;
2191 }
2192 return TRUE;
2193 }
2194
2195 return FALSE;
2196}
2197
2198typedef struct ConsoleBufferStruct
2199{
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002200 BOOL IsValid;
2201 CONSOLE_SCREEN_BUFFER_INFO Info;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002202 PCHAR_INFO Buffer;
2203 COORD BufferSize;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002204 PSMALL_RECT Regions;
2205 int NumRegions;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002206} ConsoleBuffer;
2207
2208/*
2209 * SaveConsoleBuffer()
2210 * Description:
2211 * Saves important information about the console buffer, including the
2212 * actual buffer contents. The saved information is suitable for later
2213 * restoration by RestoreConsoleBuffer().
2214 * Returns:
2215 * TRUE if all information was saved; FALSE otherwise
2216 * If FALSE, still sets cb->IsValid if buffer characteristics were saved.
2217 */
2218 static BOOL
2219SaveConsoleBuffer(
2220 ConsoleBuffer *cb)
2221{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002222 DWORD NumCells;
2223 COORD BufferCoord;
2224 SMALL_RECT ReadRegion;
2225 WORD Y, Y_incr;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002226 int i, numregions;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002227
Bram Moolenaar071d4272004-06-13 20:20:40 +00002228 if (cb == NULL)
2229 return FALSE;
2230
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002231 if (!GetConsoleScreenBufferInfo(g_hConOut, &cb->Info))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 {
2233 cb->IsValid = FALSE;
2234 return FALSE;
2235 }
2236 cb->IsValid = TRUE;
2237
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002238 /*
2239 * Allocate a buffer large enough to hold the entire console screen
2240 * buffer. If this ConsoleBuffer structure has already been initialized
2241 * with a buffer of the correct size, then just use that one.
2242 */
2243 if (!cb->IsValid || cb->Buffer == NULL ||
2244 cb->BufferSize.X != cb->Info.dwSize.X ||
2245 cb->BufferSize.Y != cb->Info.dwSize.Y)
2246 {
2247 cb->BufferSize.X = cb->Info.dwSize.X;
2248 cb->BufferSize.Y = cb->Info.dwSize.Y;
2249 NumCells = cb->BufferSize.X * cb->BufferSize.Y;
2250 vim_free(cb->Buffer);
2251 cb->Buffer = (PCHAR_INFO)alloc(NumCells * sizeof(CHAR_INFO));
2252 if (cb->Buffer == NULL)
2253 return FALSE;
2254 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002255
2256 /*
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002257 * We will now copy the console screen buffer into our buffer.
2258 * ReadConsoleOutput() seems to be limited as far as how much you
2259 * can read at a time. Empirically, this number seems to be about
2260 * 12000 cells (rows * columns). Start at position (0, 0) and copy
2261 * in chunks until it is all copied. The chunks will all have the
2262 * same horizontal characteristics, so initialize them now. The
2263 * height of each chunk will be (12000 / width).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002264 */
Bram Moolenaar61594242015-09-01 20:23:37 +02002265 BufferCoord.X = 0;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002266 ReadRegion.Left = 0;
2267 ReadRegion.Right = cb->Info.dwSize.X - 1;
2268 Y_incr = 12000 / cb->Info.dwSize.X;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002269
2270 numregions = (cb->Info.dwSize.Y + Y_incr - 1) / Y_incr;
2271 if (cb->Regions == NULL || numregions != cb->NumRegions)
2272 {
2273 cb->NumRegions = numregions;
2274 vim_free(cb->Regions);
2275 cb->Regions = (PSMALL_RECT)alloc(cb->NumRegions * sizeof(SMALL_RECT));
2276 if (cb->Regions == NULL)
2277 {
2278 vim_free(cb->Buffer);
2279 cb->Buffer = NULL;
2280 return FALSE;
2281 }
2282 }
2283
2284 for (i = 0, Y = 0; i < cb->NumRegions; i++, Y += Y_incr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 {
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002286 /*
2287 * Read into position (0, Y) in our buffer.
2288 */
2289 BufferCoord.Y = Y;
2290 /*
2291 * Read the region whose top left corner is (0, Y) and whose bottom
2292 * right corner is (width - 1, Y + Y_incr - 1). This should define
2293 * a region of size width by Y_incr. Don't worry if this region is
2294 * too large for the remaining buffer; it will be cropped.
2295 */
2296 ReadRegion.Top = Y;
2297 ReadRegion.Bottom = Y + Y_incr - 1;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002298 if (!ReadConsoleOutputW(g_hConOut, /* output handle */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002299 cb->Buffer, /* our buffer */
2300 cb->BufferSize, /* dimensions of our buffer */
2301 BufferCoord, /* offset in our buffer */
2302 &ReadRegion)) /* region to save */
2303 {
2304 vim_free(cb->Buffer);
2305 cb->Buffer = NULL;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002306 vim_free(cb->Regions);
2307 cb->Regions = NULL;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002308 return FALSE;
2309 }
Bram Moolenaar444fda22017-08-11 20:37:00 +02002310 cb->Regions[i] = ReadRegion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002311 }
2312
2313 return TRUE;
2314}
2315
2316/*
2317 * RestoreConsoleBuffer()
2318 * Description:
2319 * Restores important information about the console buffer, including the
2320 * actual buffer contents, if desired. The information to restore is in
2321 * the same format used by SaveConsoleBuffer().
2322 * Returns:
2323 * TRUE on success
2324 */
2325 static BOOL
2326RestoreConsoleBuffer(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002327 ConsoleBuffer *cb,
2328 BOOL RestoreScreen)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002330 COORD BufferCoord;
2331 SMALL_RECT WriteRegion;
Bram Moolenaar444fda22017-08-11 20:37:00 +02002332 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333
2334 if (cb == NULL || !cb->IsValid)
2335 return FALSE;
2336
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002337 /*
2338 * Before restoring the buffer contents, clear the current buffer, and
2339 * restore the cursor position and window information. Doing this now
2340 * prevents old buffer contents from "flashing" onto the screen.
2341 */
2342 if (RestoreScreen)
2343 ClearConsoleBuffer(cb->Info.wAttributes);
2344
2345 FitConsoleWindow(cb->Info.dwSize, TRUE);
2346 if (!SetConsoleScreenBufferSize(g_hConOut, cb->Info.dwSize))
2347 return FALSE;
2348 if (!SetConsoleTextAttribute(g_hConOut, cb->Info.wAttributes))
2349 return FALSE;
2350
2351 if (!RestoreScreen)
2352 {
2353 /*
2354 * No need to restore the screen buffer contents, so we're done.
2355 */
2356 return TRUE;
2357 }
2358
2359 if (!SetConsoleCursorPosition(g_hConOut, cb->Info.dwCursorPosition))
2360 return FALSE;
2361 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &cb->Info.srWindow))
2362 return FALSE;
2363
2364 /*
2365 * Restore the screen buffer contents.
2366 */
2367 if (cb->Buffer != NULL)
2368 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002369 for (i = 0; i < cb->NumRegions; i++)
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002370 {
Bram Moolenaar444fda22017-08-11 20:37:00 +02002371 BufferCoord.X = cb->Regions[i].Left;
2372 BufferCoord.Y = cb->Regions[i].Top;
2373 WriteRegion = cb->Regions[i];
2374 if (!WriteConsoleOutputW(g_hConOut, /* output handle */
2375 cb->Buffer, /* our buffer */
2376 cb->BufferSize, /* dimensions of our buffer */
2377 BufferCoord, /* offset in our buffer */
2378 &WriteRegion)) /* region to restore */
2379 {
2380 return FALSE;
2381 }
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002382 }
2383 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002384
2385 return TRUE;
2386}
2387
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002388#define FEAT_RESTORE_ORIG_SCREEN
2389#ifdef FEAT_RESTORE_ORIG_SCREEN
2390static ConsoleBuffer g_cbOrig = { 0 };
2391#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002392static ConsoleBuffer g_cbNonTermcap = { 0 };
2393static ConsoleBuffer g_cbTermcap = { 0 };
2394
2395#ifdef FEAT_TITLE
2396#ifdef __BORLANDC__
2397typedef HWND (__stdcall *GETCONSOLEWINDOWPROC)(VOID);
2398#else
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002399typedef HWND (WINAPI *GETCONSOLEWINDOWPROC)(VOID);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400#endif
2401char g_szOrigTitle[256] = { 0 };
2402HWND g_hWnd = NULL; /* also used in os_mswin.c */
2403static HICON g_hOrigIconSmall = NULL;
2404static HICON g_hOrigIcon = NULL;
2405static HICON g_hVimIcon = NULL;
2406static BOOL g_fCanChangeIcon = FALSE;
2407
2408/* ICON* are not defined in VC++ 4.0 */
2409#ifndef ICON_SMALL
2410#define ICON_SMALL 0
2411#endif
2412#ifndef ICON_BIG
2413#define ICON_BIG 1
2414#endif
2415/*
2416 * GetConsoleIcon()
2417 * Description:
2418 * Attempts to retrieve the small icon and/or the big icon currently in
2419 * use by a given window.
2420 * Returns:
2421 * TRUE on success
2422 */
2423 static BOOL
2424GetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002425 HWND hWnd,
2426 HICON *phIconSmall,
2427 HICON *phIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002428{
2429 if (hWnd == NULL)
2430 return FALSE;
2431
2432 if (phIconSmall != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002433 *phIconSmall = (HICON)SendMessage(hWnd, WM_GETICON,
2434 (WPARAM)ICON_SMALL, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435 if (phIcon != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002436 *phIcon = (HICON)SendMessage(hWnd, WM_GETICON,
2437 (WPARAM)ICON_BIG, (LPARAM)0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438 return TRUE;
2439}
2440
2441/*
2442 * SetConsoleIcon()
2443 * Description:
2444 * Attempts to change the small icon and/or the big icon currently in
2445 * use by a given window.
2446 * Returns:
2447 * TRUE on success
2448 */
2449 static BOOL
2450SetConsoleIcon(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002451 HWND hWnd,
2452 HICON hIconSmall,
2453 HICON hIcon)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002454{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455 if (hWnd == NULL)
2456 return FALSE;
2457
2458 if (hIconSmall != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002459 SendMessage(hWnd, WM_SETICON,
2460 (WPARAM)ICON_SMALL, (LPARAM)hIconSmall);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002461 if (hIcon != NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002462 SendMessage(hWnd, WM_SETICON,
2463 (WPARAM)ICON_BIG, (LPARAM) hIcon);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002464 return TRUE;
2465}
2466
2467/*
2468 * SaveConsoleTitleAndIcon()
2469 * Description:
2470 * Saves the current console window title in g_szOrigTitle, for later
2471 * restoration. Also, attempts to obtain a handle to the console window,
2472 * and use it to save the small and big icons currently in use by the
2473 * console window. This is not always possible on some versions of Windows;
2474 * nor is it possible when running Vim remotely using Telnet (since the
2475 * console window the user sees is owned by a remote process).
2476 */
2477 static void
2478SaveConsoleTitleAndIcon(void)
2479{
Bram Moolenaar071d4272004-06-13 20:20:40 +00002480 /* Save the original title. */
2481 if (!GetConsoleTitle(g_szOrigTitle, sizeof(g_szOrigTitle)))
2482 return;
2483
2484 /*
2485 * Obtain a handle to the console window using GetConsoleWindow() from
2486 * KERNEL32.DLL; we need to handle in order to change the window icon.
2487 * This function only exists on NT-based Windows, starting with Windows
2488 * 2000. On older operating systems, we can't change the window icon
2489 * anyway.
2490 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002491 g_hWnd = GetConsoleWindow();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 if (g_hWnd == NULL)
2493 return;
2494
2495 /* Save the original console window icon. */
2496 GetConsoleIcon(g_hWnd, &g_hOrigIconSmall, &g_hOrigIcon);
2497 if (g_hOrigIconSmall == NULL || g_hOrigIcon == NULL)
2498 return;
2499
2500 /* Extract the first icon contained in the Vim executable. */
Bram Moolenaarcddc91c2014-09-23 21:53:41 +02002501 if (mch_icon_load((HANDLE *)&g_hVimIcon) == FAIL || g_hVimIcon == NULL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002502 g_hVimIcon = ExtractIcon(NULL, (LPCSTR)exe_name, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 if (g_hVimIcon != NULL)
2504 g_fCanChangeIcon = TRUE;
2505}
2506#endif
2507
2508static int g_fWindInitCalled = FALSE;
2509static int g_fTermcapMode = FALSE;
2510static CONSOLE_CURSOR_INFO g_cci;
2511static DWORD g_cmodein = 0;
2512static DWORD g_cmodeout = 0;
2513
2514/*
2515 * non-GUI version of mch_init().
2516 */
2517 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002518mch_init(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002519{
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002520#ifndef FEAT_RESTORE_ORIG_SCREEN
2521 CONSOLE_SCREEN_BUFFER_INFO csbi;
2522#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523#ifndef __MINGW32__
2524 extern int _fmode;
2525#endif
2526
Bram Moolenaard32a99a2010-09-21 17:29:23 +02002527 /* Silently handle invalid parameters to CRT functions */
2528 SET_INVALID_PARAM_HANDLER;
2529
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 /* Let critical errors result in a failure, not in a dialog box. Required
2531 * for the timestamp test to work on removed floppies. */
2532 SetErrorMode(SEM_FAILCRITICALERRORS);
2533
2534 _fmode = O_BINARY; /* we do our own CR-LF translation */
2535 out_flush();
2536
2537 /* Obtain handles for the standard Console I/O devices */
2538 if (read_cmd_fd == 0)
2539 g_hConIn = GetStdHandle(STD_INPUT_HANDLE);
2540 else
2541 create_conin();
2542 g_hConOut = GetStdHandle(STD_OUTPUT_HANDLE);
2543
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002544#ifdef FEAT_RESTORE_ORIG_SCREEN
2545 /* Save the initial console buffer for later restoration */
2546 SaveConsoleBuffer(&g_cbOrig);
2547 g_attrCurrent = g_attrDefault = g_cbOrig.Info.wAttributes;
2548#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002549 /* Get current text attributes */
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01002550 GetConsoleScreenBufferInfo(g_hConOut, &csbi);
2551 g_attrCurrent = g_attrDefault = csbi.wAttributes;
2552#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002553 if (cterm_normal_fg_color == 0)
2554 cterm_normal_fg_color = (g_attrCurrent & 0xf) + 1;
2555 if (cterm_normal_bg_color == 0)
2556 cterm_normal_bg_color = ((g_attrCurrent >> 4) & 0xf) + 1;
2557
2558 /* set termcap codes to current text attributes */
2559 update_tcap(g_attrCurrent);
2560
2561 GetConsoleCursorInfo(g_hConOut, &g_cci);
2562 GetConsoleMode(g_hConIn, &g_cmodein);
2563 GetConsoleMode(g_hConOut, &g_cmodeout);
2564
2565#ifdef FEAT_TITLE
2566 SaveConsoleTitleAndIcon();
2567 /*
2568 * Set both the small and big icons of the console window to Vim's icon.
2569 * Note that Vim presently only has one size of icon (32x32), but it
2570 * automatically gets scaled down to 16x16 when setting the small icon.
2571 */
2572 if (g_fCanChangeIcon)
2573 SetConsoleIcon(g_hWnd, g_hVimIcon, g_hVimIcon);
2574#endif
2575
2576 ui_get_shellsize();
2577
2578#ifdef MCH_WRITE_DUMP
2579 fdDump = fopen("dump", "wt");
2580
2581 if (fdDump)
2582 {
2583 time_t t;
2584
2585 time(&t);
2586 fputs(ctime(&t), fdDump);
2587 fflush(fdDump);
2588 }
2589#endif
2590
2591 g_fWindInitCalled = TRUE;
2592
2593#ifdef FEAT_MOUSE
2594 g_fMouseAvail = GetSystemMetrics(SM_MOUSEPRESENT);
2595#endif
2596
2597#ifdef FEAT_CLIPBOARD
Bram Moolenaar693e40c2013-02-26 14:56:42 +01002598 win_clip_init();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600}
2601
2602/*
2603 * non-GUI version of mch_exit().
2604 * Shut down and exit with status `r'
2605 * Careful: mch_exit() may be called before mch_init()!
2606 */
2607 void
2608mch_exit(int r)
2609{
Bram Moolenaar955f1982017-02-05 15:10:51 +01002610 exiting = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611
Bram Moolenaar955f1982017-02-05 15:10:51 +01002612 stoptermcap();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002613 if (g_fWindInitCalled)
2614 settmode(TMODE_COOK);
2615
2616 ml_close_all(TRUE); /* remove all memfiles */
2617
2618 if (g_fWindInitCalled)
2619 {
2620#ifdef FEAT_TITLE
2621 mch_restore_title(3);
2622 /*
2623 * Restore both the small and big icons of the console window to
2624 * what they were at startup. Don't do this when the window is
2625 * closed, Vim would hang here.
2626 */
2627 if (g_fCanChangeIcon && !g_fForceExit)
2628 SetConsoleIcon(g_hWnd, g_hOrigIconSmall, g_hOrigIcon);
2629#endif
2630
2631#ifdef MCH_WRITE_DUMP
2632 if (fdDump)
2633 {
2634 time_t t;
2635
2636 time(&t);
2637 fputs(ctime(&t), fdDump);
2638 fclose(fdDump);
2639 }
2640 fdDump = NULL;
2641#endif
2642 }
2643
2644 SetConsoleCursorInfo(g_hConOut, &g_cci);
2645 SetConsoleMode(g_hConIn, g_cmodein);
2646 SetConsoleMode(g_hConOut, g_cmodeout);
2647
2648#ifdef DYNAMIC_GETTEXT
2649 dyn_libintl_end();
2650#endif
2651
2652 exit(r);
2653}
2654#endif /* !FEAT_GUI_W32 */
2655
Bram Moolenaar071d4272004-06-13 20:20:40 +00002656/*
2657 * Do we have an interactive window?
2658 */
2659 int
2660mch_check_win(
Bram Moolenaar1266d672017-02-01 13:43:36 +01002661 int argc UNUSED,
2662 char **argv UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002663{
2664 get_exe_name();
2665
2666#ifdef FEAT_GUI_W32
2667 return OK; /* GUI always has a tty */
2668#else
2669 if (isatty(1))
2670 return OK;
2671 return FAIL;
2672#endif
2673}
2674
2675
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002676#ifdef FEAT_MBYTE
2677/*
2678 * fname_casew(): Wide version of fname_case(). Set the case of the file name,
2679 * if it already exists. When "len" is > 0, also expand short to long
2680 * filenames.
2681 * Return FAIL if wide functions are not available, OK otherwise.
2682 * NOTE: much of this is identical to fname_case(), keep in sync!
2683 */
2684 static int
2685fname_casew(
2686 WCHAR *name,
2687 int len)
2688{
2689 WCHAR szTrueName[_MAX_PATH + 2];
2690 WCHAR szTrueNameTemp[_MAX_PATH + 2];
2691 WCHAR *ptrue, *ptruePrev;
2692 WCHAR *porig, *porigPrev;
2693 int flen;
2694 WIN32_FIND_DATAW fb;
Bram Moolenaar73c61632013-12-07 14:48:10 +01002695 HANDLE hFind = INVALID_HANDLE_VALUE;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002696 int c;
2697 int slen;
2698
2699 flen = (int)wcslen(name);
2700 if (flen > _MAX_PATH)
2701 return OK;
2702
2703 /* slash_adjust(name) not needed, already adjusted by fname_case(). */
2704
2705 /* Build the new name in szTrueName[] one component at a time. */
2706 porig = name;
2707 ptrue = szTrueName;
2708
2709 if (iswalpha(porig[0]) && porig[1] == L':')
2710 {
2711 /* copy leading drive letter */
2712 *ptrue++ = *porig++;
2713 *ptrue++ = *porig++;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002714 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002715 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002716
2717 while (*porig != NUL)
2718 {
2719 /* copy \ characters */
2720 while (*porig == psepc)
2721 *ptrue++ = *porig++;
2722
2723 ptruePrev = ptrue;
2724 porigPrev = porig;
2725 while (*porig != NUL && *porig != psepc)
2726 {
2727 *ptrue++ = *porig++;
2728 }
2729 *ptrue = NUL;
2730
2731 /* To avoid a slow failure append "\*" when searching a directory,
2732 * server or network share. */
2733 wcscpy(szTrueNameTemp, szTrueName);
2734 slen = (int)wcslen(szTrueNameTemp);
2735 if (*porig == psepc && slen + 2 < _MAX_PATH)
2736 wcscpy(szTrueNameTemp + slen, L"\\*");
2737
2738 /* Skip "", "." and "..". */
2739 if (ptrue > ptruePrev
2740 && (ptruePrev[0] != L'.'
2741 || (ptruePrev[1] != NUL
2742 && (ptruePrev[1] != L'.' || ptruePrev[2] != NUL)))
2743 && (hFind = FindFirstFileW(szTrueNameTemp, &fb))
2744 != INVALID_HANDLE_VALUE)
2745 {
2746 c = *porig;
2747 *porig = NUL;
2748
2749 /* Only use the match when it's the same name (ignoring case) or
2750 * expansion is allowed and there is a match with the short name
2751 * and there is enough room. */
2752 if (_wcsicoll(porigPrev, fb.cFileName) == 0
2753 || (len > 0
2754 && (_wcsicoll(porigPrev, fb.cAlternateFileName) == 0
2755 && (int)(ptruePrev - szTrueName)
2756 + (int)wcslen(fb.cFileName) < len)))
2757 {
2758 wcscpy(ptruePrev, fb.cFileName);
2759
2760 /* Look for exact match and prefer it if found. Must be a
2761 * long name, otherwise there would be only one match. */
2762 while (FindNextFileW(hFind, &fb))
2763 {
2764 if (*fb.cAlternateFileName != NUL
2765 && (wcscoll(porigPrev, fb.cFileName) == 0
2766 || (len > 0
2767 && (_wcsicoll(porigPrev,
2768 fb.cAlternateFileName) == 0
2769 && (int)(ptruePrev - szTrueName)
2770 + (int)wcslen(fb.cFileName) < len))))
2771 {
2772 wcscpy(ptruePrev, fb.cFileName);
2773 break;
2774 }
2775 }
2776 }
2777 FindClose(hFind);
2778 *porig = c;
2779 ptrue = ptruePrev + wcslen(ptruePrev);
2780 }
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002781 }
2782
2783 wcscpy(name, szTrueName);
2784 return OK;
2785}
2786#endif
2787
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788/*
2789 * fname_case(): Set the case of the file name, if it already exists.
2790 * When "len" is > 0, also expand short to long filenames.
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002791 * NOTE: much of this is identical to fname_casew(), keep in sync!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792 */
2793 void
2794fname_case(
2795 char_u *name,
2796 int len)
2797{
2798 char szTrueName[_MAX_PATH + 2];
Bram Moolenaar464c9252010-10-13 20:37:41 +02002799 char szTrueNameTemp[_MAX_PATH + 2];
Bram Moolenaar071d4272004-06-13 20:20:40 +00002800 char *ptrue, *ptruePrev;
2801 char *porig, *porigPrev;
2802 int flen;
2803 WIN32_FIND_DATA fb;
2804 HANDLE hFind;
2805 int c;
Bram Moolenaar464c9252010-10-13 20:37:41 +02002806 int slen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002807
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00002808 flen = (int)STRLEN(name);
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002809 if (flen == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002810 return;
2811
2812 slash_adjust(name);
2813
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002814#ifdef FEAT_MBYTE
2815 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2816 {
2817 WCHAR *p = enc_to_utf16(name, NULL);
2818
2819 if (p != NULL)
2820 {
2821 char_u *q;
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002822 WCHAR buf[_MAX_PATH + 1];
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002823
Bram Moolenaar21d89b62014-10-07 10:38:40 +02002824 wcsncpy(buf, p, _MAX_PATH);
2825 buf[_MAX_PATH] = L'\0';
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002826 vim_free(p);
2827
2828 if (fname_casew(buf, (len > 0) ? _MAX_PATH : 0) == OK)
2829 {
2830 q = utf16_to_enc(buf, NULL);
2831 if (q != NULL)
2832 {
2833 vim_strncpy(name, q, (len > 0) ? len - 1 : flen);
2834 vim_free(q);
2835 return;
2836 }
2837 }
2838 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02002839 return;
Bram Moolenaar65f04f62013-08-30 17:29:16 +02002840 }
2841#endif
2842
2843 /* If 'enc' is utf-8, flen can be larger than _MAX_PATH.
2844 * So we should check this after calling wide function. */
2845 if (flen > _MAX_PATH)
2846 return;
2847
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848 /* Build the new name in szTrueName[] one component at a time. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002849 porig = (char *)name;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850 ptrue = szTrueName;
2851
2852 if (isalpha(porig[0]) && porig[1] == ':')
2853 {
2854 /* copy leading drive letter */
2855 *ptrue++ = *porig++;
2856 *ptrue++ = *porig++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857 }
Bram Moolenaar73c61632013-12-07 14:48:10 +01002858 *ptrue = NUL; /* in case nothing follows */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859
2860 while (*porig != NUL)
2861 {
2862 /* copy \ characters */
2863 while (*porig == psepc)
2864 *ptrue++ = *porig++;
2865
2866 ptruePrev = ptrue;
2867 porigPrev = porig;
2868 while (*porig != NUL && *porig != psepc)
2869 {
2870#ifdef FEAT_MBYTE
2871 int l;
2872
2873 if (enc_dbcs)
2874 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002875 l = (*mb_ptr2len)((char_u *)porig);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002876 while (--l >= 0)
2877 *ptrue++ = *porig++;
2878 }
2879 else
2880#endif
2881 *ptrue++ = *porig++;
2882 }
2883 *ptrue = NUL;
2884
Bram Moolenaar464c9252010-10-13 20:37:41 +02002885 /* To avoid a slow failure append "\*" when searching a directory,
2886 * server or network share. */
2887 STRCPY(szTrueNameTemp, szTrueName);
Bram Moolenaar6b5ef062010-10-27 12:18:00 +02002888 slen = (int)strlen(szTrueNameTemp);
Bram Moolenaar464c9252010-10-13 20:37:41 +02002889 if (*porig == psepc && slen + 2 < _MAX_PATH)
2890 STRCPY(szTrueNameTemp + slen, "\\*");
2891
Bram Moolenaar071d4272004-06-13 20:20:40 +00002892 /* Skip "", "." and "..". */
2893 if (ptrue > ptruePrev
2894 && (ptruePrev[0] != '.'
2895 || (ptruePrev[1] != NUL
2896 && (ptruePrev[1] != '.' || ptruePrev[2] != NUL)))
Bram Moolenaar464c9252010-10-13 20:37:41 +02002897 && (hFind = FindFirstFile(szTrueNameTemp, &fb))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 != INVALID_HANDLE_VALUE)
2899 {
2900 c = *porig;
2901 *porig = NUL;
2902
2903 /* Only use the match when it's the same name (ignoring case) or
2904 * expansion is allowed and there is a match with the short name
2905 * and there is enough room. */
2906 if (_stricoll(porigPrev, fb.cFileName) == 0
2907 || (len > 0
2908 && (_stricoll(porigPrev, fb.cAlternateFileName) == 0
2909 && (int)(ptruePrev - szTrueName)
2910 + (int)strlen(fb.cFileName) < len)))
2911 {
2912 STRCPY(ptruePrev, fb.cFileName);
2913
2914 /* Look for exact match and prefer it if found. Must be a
2915 * long name, otherwise there would be only one match. */
2916 while (FindNextFile(hFind, &fb))
2917 {
2918 if (*fb.cAlternateFileName != NUL
2919 && (strcoll(porigPrev, fb.cFileName) == 0
2920 || (len > 0
2921 && (_stricoll(porigPrev,
2922 fb.cAlternateFileName) == 0
2923 && (int)(ptruePrev - szTrueName)
2924 + (int)strlen(fb.cFileName) < len))))
2925 {
2926 STRCPY(ptruePrev, fb.cFileName);
2927 break;
2928 }
2929 }
2930 }
2931 FindClose(hFind);
2932 *porig = c;
2933 ptrue = ptruePrev + strlen(ptruePrev);
2934 }
2935 }
2936
2937 STRCPY(name, szTrueName);
2938}
2939
2940
2941/*
2942 * Insert user name in s[len].
2943 */
2944 int
2945mch_get_user_name(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00002946 char_u *s,
2947 int len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002948{
Bram Moolenaar41a09032007-10-01 18:34:34 +00002949 char szUserName[256 + 1]; /* UNLEN is 256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 DWORD cch = sizeof szUserName;
2951
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002952#ifdef FEAT_MBYTE
2953 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2954 {
2955 WCHAR wszUserName[256 + 1]; /* UNLEN is 256 */
2956 DWORD wcch = sizeof(wszUserName) / sizeof(WCHAR);
2957
2958 if (GetUserNameW(wszUserName, &wcch))
2959 {
2960 char_u *p = utf16_to_enc(wszUserName, NULL);
2961
2962 if (p != NULL)
2963 {
2964 vim_strncpy(s, p, len - 1);
2965 vim_free(p);
2966 return OK;
2967 }
2968 }
Bram Moolenaarc8020ee2013-12-11 18:18:06 +01002969 }
2970#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002971 if (GetUserName(szUserName, &cch))
2972 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01002973 vim_strncpy(s, (char_u *)szUserName, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002974 return OK;
2975 }
2976 s[0] = NUL;
2977 return FAIL;
2978}
2979
2980
2981/*
2982 * Insert host name in s[len].
2983 */
2984 void
2985mch_get_host_name(
2986 char_u *s,
2987 int len)
2988{
2989 DWORD cch = len;
2990
Bram Moolenaar2cc87382013-12-11 18:21:45 +01002991#ifdef FEAT_MBYTE
2992 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
2993 {
2994 WCHAR wszHostName[256 + 1];
2995 DWORD wcch = sizeof(wszHostName) / sizeof(WCHAR);
2996
2997 if (GetComputerNameW(wszHostName, &wcch))
2998 {
2999 char_u *p = utf16_to_enc(wszHostName, NULL);
3000
3001 if (p != NULL)
3002 {
3003 vim_strncpy(s, p, len - 1);
3004 vim_free(p);
3005 return;
3006 }
3007 }
Bram Moolenaar2cc87382013-12-11 18:21:45 +01003008 }
3009#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003010 if (!GetComputerName((LPSTR)s, &cch))
3011 vim_strncpy(s, (char_u *)"PC (Win32 Vim)", len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003012}
3013
3014
3015/*
3016 * return process ID
3017 */
3018 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003019mch_get_pid(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003020{
3021 return (long)GetCurrentProcessId();
3022}
3023
3024
3025/*
3026 * Get name of current directory into buffer 'buf' of length 'len' bytes.
3027 * Return OK for success, FAIL for failure.
3028 */
3029 int
3030mch_dirname(
3031 char_u *buf,
3032 int len)
3033{
3034 /*
3035 * Originally this was:
3036 * return (getcwd(buf, len) != NULL ? OK : FAIL);
3037 * But the Win32s known bug list says that getcwd() doesn't work
3038 * so use the Win32 system call instead. <Negri>
3039 */
3040#ifdef FEAT_MBYTE
3041 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3042 {
3043 WCHAR wbuf[_MAX_PATH + 1];
3044
3045 if (GetCurrentDirectoryW(_MAX_PATH, wbuf) != 0)
3046 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003047 char_u *p = utf16_to_enc(wbuf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048
3049 if (p != NULL)
3050 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003051 vim_strncpy(buf, p, len - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052 vim_free(p);
3053 return OK;
3054 }
3055 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003056 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003057 }
3058#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003059 return (GetCurrentDirectory(len, (LPSTR)buf) != 0 ? OK : FAIL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060}
3061
3062/*
Bram Moolenaarffa22202013-11-21 12:34:11 +01003063 * Get file permissions for "name".
3064 * Return mode_t or -1 for error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 */
3066 long
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003067mch_getperm(char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003068{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003069 stat_T st;
Bram Moolenaarffa22202013-11-21 12:34:11 +01003070 int n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003071
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003072 n = mch_stat((char *)name, &st);
Bram Moolenaar78cf3f02014-01-10 18:16:07 +01003073 return n == 0 ? (long)(unsigned short)st.st_mode : -1L;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074}
3075
3076
3077/*
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003078 * Set file permission for "name" to "perm".
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003079 *
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003080 * Return FAIL for failure, OK otherwise.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081 */
3082 int
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003083mch_setperm(char_u *name, long perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003084{
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003085 long n = -1;
3086
Bram Moolenaar071d4272004-06-13 20:20:40 +00003087#ifdef FEAT_MBYTE
3088 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3089 {
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003090 WCHAR *p = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091
3092 if (p != NULL)
3093 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003094 n = _wchmod(p, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003095 vim_free(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003096 if (n == -1)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003097 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 }
3099 }
Bram Moolenaare24a9c02013-07-24 13:49:22 +02003100 if (n == -1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003101#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003102 n = _chmod((const char *)name, perm);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003103 if (n == -1)
3104 return FAIL;
3105
3106 win32_set_archive(name);
3107
3108 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003109}
3110
3111/*
3112 * Set hidden flag for "name".
3113 */
3114 void
3115mch_hide(char_u *name)
3116{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003117 int attrs = win32_getattrs(name);
3118 if (attrs == -1)
3119 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003121 attrs |= FILE_ATTRIBUTE_HIDDEN;
3122 win32_setattrs(name, attrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003123}
3124
3125/*
Bram Moolenaar8a52ba72015-11-02 14:45:56 +01003126 * Return TRUE if file "name" exists and is hidden.
3127 */
3128 int
3129mch_ishidden(char_u *name)
3130{
3131 int f = win32_getattrs(name);
3132
3133 if (f == -1)
3134 return FALSE; /* file does not exist at all */
3135
3136 return (f & FILE_ATTRIBUTE_HIDDEN) != 0;
3137}
3138
3139/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003140 * return TRUE if "name" is a directory
3141 * return FALSE if "name" is not a directory or upon error
3142 */
3143 int
3144mch_isdir(char_u *name)
3145{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003146 int f = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003147
3148 if (f == -1)
3149 return FALSE; /* file does not exist at all */
3150
3151 return (f & FILE_ATTRIBUTE_DIRECTORY) != 0;
3152}
3153
3154/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003155 * return TRUE if "name" is a directory, NOT a symlink to a directory
3156 * return FALSE if "name" is not a directory
3157 * return FALSE for error
3158 */
3159 int
3160mch_isrealdir(char_u *name)
3161{
3162 return mch_isdir(name) && !mch_is_symbolic_link(name);
3163}
3164
3165/*
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003166 * Create directory "name".
3167 * Return 0 on success, -1 on error.
3168 */
3169 int
3170mch_mkdir(char_u *name)
3171{
3172#ifdef FEAT_MBYTE
3173 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3174 {
3175 WCHAR *p;
3176 int retval;
3177
3178 p = enc_to_utf16(name, NULL);
3179 if (p == NULL)
3180 return -1;
3181 retval = _wmkdir(p);
3182 vim_free(p);
3183 return retval;
3184 }
3185#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003186 return _mkdir((const char *)name);
Bram Moolenaar3c9c99c2011-05-05 18:31:59 +02003187}
3188
3189/*
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003190 * Delete directory "name".
3191 * Return 0 on success, -1 on error.
3192 */
3193 int
3194mch_rmdir(char_u *name)
3195{
3196#ifdef FEAT_MBYTE
3197 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3198 {
3199 WCHAR *p;
3200 int retval;
3201
3202 p = enc_to_utf16(name, NULL);
3203 if (p == NULL)
3204 return -1;
3205 retval = _wrmdir(p);
3206 vim_free(p);
3207 return retval;
3208 }
3209#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003210 return _rmdir((const char *)name);
Bram Moolenaar4cf76792016-01-16 22:02:57 +01003211}
3212
3213/*
Bram Moolenaar03f48552006-02-28 23:52:23 +00003214 * Return TRUE if file "fname" has more than one link.
3215 */
3216 int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003217mch_is_hard_link(char_u *fname)
Bram Moolenaar03f48552006-02-28 23:52:23 +00003218{
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003219 BY_HANDLE_FILE_INFORMATION info;
3220
3221 return win32_fileinfo(fname, &info) == FILEINFO_OK
3222 && info.nNumberOfLinks > 1;
3223}
3224
3225/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01003226 * Return TRUE if "name" is a symbolic link (or a junction).
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003227 */
3228 int
Bram Moolenaar203258c2016-01-17 22:15:16 +01003229mch_is_symbolic_link(char_u *name)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003230{
3231 HANDLE hFind;
3232 int res = FALSE;
3233 WIN32_FIND_DATAA findDataA;
3234 DWORD fileFlags = 0, reparseTag = 0;
3235#ifdef FEAT_MBYTE
3236 WCHAR *wn = NULL;
3237 WIN32_FIND_DATAW findDataW;
3238
3239 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003240 wn = enc_to_utf16(name, NULL);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003241 if (wn != NULL)
3242 {
3243 hFind = FindFirstFileW(wn, &findDataW);
3244 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003245 if (hFind != INVALID_HANDLE_VALUE)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003246 {
3247 fileFlags = findDataW.dwFileAttributes;
3248 reparseTag = findDataW.dwReserved0;
3249 }
3250 }
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003251 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003252#endif
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003253 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003254 hFind = FindFirstFile((LPCSTR)name, &findDataA);
Bram Moolenaar03e114b2013-06-16 16:34:56 +02003255 if (hFind != INVALID_HANDLE_VALUE)
3256 {
3257 fileFlags = findDataA.dwFileAttributes;
3258 reparseTag = findDataA.dwReserved0;
3259 }
3260 }
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003261
3262 if (hFind != INVALID_HANDLE_VALUE)
3263 FindClose(hFind);
3264
3265 if ((fileFlags & FILE_ATTRIBUTE_REPARSE_POINT)
Bram Moolenaar203258c2016-01-17 22:15:16 +01003266 && (reparseTag == IO_REPARSE_TAG_SYMLINK
3267 || reparseTag == IO_REPARSE_TAG_MOUNT_POINT))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003268 res = TRUE;
3269
3270 return res;
3271}
3272
3273/*
3274 * Return TRUE if file "fname" has more than one link or if it is a symbolic
3275 * link.
3276 */
3277 int
3278mch_is_linked(char_u *fname)
3279{
3280 if (mch_is_hard_link(fname) || mch_is_symbolic_link(fname))
3281 return TRUE;
3282 return FALSE;
3283}
3284
3285/*
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003286 * Get the by-handle-file-information for "fname".
3287 * Returns FILEINFO_OK when OK.
3288 * returns FILEINFO_ENC_FAIL when enc_to_utf16() failed.
3289 * Returns FILEINFO_READ_FAIL when CreateFile() failed.
3290 * Returns FILEINFO_INFO_FAIL when GetFileInformationByHandle() failed.
3291 */
3292 int
3293win32_fileinfo(char_u *fname, BY_HANDLE_FILE_INFORMATION *info)
3294{
Bram Moolenaar03f48552006-02-28 23:52:23 +00003295 HANDLE hFile;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003296 int res = FILEINFO_READ_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003297#ifdef FEAT_MBYTE
3298 WCHAR *wn = NULL;
3299
3300 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003301 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00003302 wn = enc_to_utf16(fname, NULL);
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003303 if (wn == NULL)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003304 return FILEINFO_ENC_FAIL;
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003305 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00003306 if (wn != NULL)
3307 {
3308 hFile = CreateFileW(wn, /* file name */
3309 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003310 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003311 NULL, /* security descriptor */
3312 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003313 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003314 NULL); /* handle to template file */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003315 vim_free(wn);
Bram Moolenaar03f48552006-02-28 23:52:23 +00003316 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003317 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003318#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003319 hFile = CreateFile((LPCSTR)fname, /* file name */
3320 GENERIC_READ, /* access mode */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003321 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share mode */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003322 NULL, /* security descriptor */
3323 OPEN_EXISTING, /* creation disposition */
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003324 FILE_FLAG_BACKUP_SEMANTICS, /* file attributes */
Bram Moolenaar03f48552006-02-28 23:52:23 +00003325 NULL); /* handle to template file */
3326
3327 if (hFile != INVALID_HANDLE_VALUE)
3328 {
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003329 if (GetFileInformationByHandle(hFile, info) != 0)
3330 res = FILEINFO_OK;
3331 else
3332 res = FILEINFO_INFO_FAIL;
Bram Moolenaar03f48552006-02-28 23:52:23 +00003333 CloseHandle(hFile);
3334 }
3335
Bram Moolenaar03f48552006-02-28 23:52:23 +00003336 return res;
3337}
3338
3339/*
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003340 * get file attributes for `name'
3341 * -1 : error
3342 * else FILE_ATTRIBUTE_* defined in winnt.h
3343 */
Bram Moolenaarffa22202013-11-21 12:34:11 +01003344 static int
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003345win32_getattrs(char_u *name)
3346{
3347 int attr;
3348#ifdef FEAT_MBYTE
3349 WCHAR *p = NULL;
3350
3351 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3352 p = enc_to_utf16(name, NULL);
3353
3354 if (p != NULL)
3355 {
3356 attr = GetFileAttributesW(p);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003357 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003358 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003359 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003360#endif
3361 attr = GetFileAttributes((char *)name);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003362
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003363 return attr;
3364}
3365
3366/*
3367 * set file attributes for `name' to `attrs'
3368 *
3369 * return -1 for failure, 0 otherwise
3370 */
3371 static
3372 int
3373win32_setattrs(char_u *name, int attrs)
3374{
3375 int res;
3376#ifdef FEAT_MBYTE
3377 WCHAR *p = NULL;
3378
3379 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3380 p = enc_to_utf16(name, NULL);
3381
3382 if (p != NULL)
3383 {
3384 res = SetFileAttributesW(p, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003385 vim_free(p);
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003386 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003387 else
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003388#endif
3389 res = SetFileAttributes((char *)name, attrs);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003390
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003391 return res ? 0 : -1;
3392}
3393
3394/*
3395 * Set archive flag for "name".
3396 */
3397 static
3398 int
3399win32_set_archive(char_u *name)
3400{
3401 int attrs = win32_getattrs(name);
3402 if (attrs == -1)
3403 return -1;
3404
3405 attrs |= FILE_ATTRIBUTE_ARCHIVE;
3406 return win32_setattrs(name, attrs);
3407}
3408
3409/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003410 * Return TRUE if file or directory "name" is writable (not readonly).
3411 * Strange semantics of Win32: a readonly directory is writable, but you can't
3412 * delete a file. Let's say this means it is writable.
3413 */
3414 int
3415mch_writable(char_u *name)
3416{
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003417 int attrs = win32_getattrs(name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003419 return (attrs != -1 && (!(attrs & FILE_ATTRIBUTE_READONLY)
3420 || (attrs & FILE_ATTRIBUTE_DIRECTORY)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003421}
3422
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423/*
Bram Moolenaar43663192017-03-05 14:29:12 +01003424 * Return TRUE if "name" can be executed, FALSE if not.
Bram Moolenaar77b77102015-03-21 22:18:41 +01003425 * If "use_path" is FALSE only check if "name" is executable.
Bram Moolenaar43663192017-03-05 14:29:12 +01003426 * When returning TRUE and "path" is not NULL save the path and set "*path" to
3427 * the allocated memory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003428 */
3429 int
Bram Moolenaar77b77102015-03-21 22:18:41 +01003430mch_can_exe(char_u *name, char_u **path, int use_path)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431{
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003432 char_u buf[_MAX_PATH];
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00003433 int len = (int)STRLEN(name);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003434 char_u *p;
3435
3436 if (len >= _MAX_PATH) /* safety check */
3437 return FALSE;
3438
3439 /* If there already is an extension try using the name directly. Also do
3440 * this with a Unix-shell like 'shell'. */
3441 if (vim_strchr(gettail(name), '.') != NULL
3442 || strstr((char *)gettail(p_sh), "sh") != NULL)
Bram Moolenaar43663192017-03-05 14:29:12 +01003443 if (executable_exists((char *)name, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003444 return TRUE;
3445
3446 /*
3447 * Loop over all extensions in $PATHEXT.
3448 */
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00003449 vim_strncpy(buf, name, _MAX_PATH - 1);
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003450 p = mch_getenv("PATHEXT");
3451 if (p == NULL)
3452 p = (char_u *)".com;.exe;.bat;.cmd";
3453 while (*p)
3454 {
3455 if (p[0] == '.' && (p[1] == NUL || p[1] == ';'))
3456 {
3457 /* A single "." means no extension is added. */
3458 buf[len] = NUL;
3459 ++p;
3460 if (*p)
3461 ++p;
3462 }
3463 else
3464 copy_option_part(&p, buf + len, _MAX_PATH - len, ";");
Bram Moolenaar43663192017-03-05 14:29:12 +01003465 if (executable_exists((char *)buf, path, use_path))
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00003466 return TRUE;
3467 }
3468 return FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469}
Bram Moolenaar071d4272004-06-13 20:20:40 +00003470
3471/*
3472 * Check what "name" is:
3473 * NODE_NORMAL: file or directory (or doesn't exist)
3474 * NODE_WRITABLE: writable device, socket, fifo, etc.
3475 * NODE_OTHER: non-writable things
3476 */
3477 int
3478mch_nodetype(char_u *name)
3479{
3480 HANDLE hFile;
3481 int type;
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003482#ifdef FEAT_MBYTE
3483 WCHAR *wn = NULL;
3484#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485
Bram Moolenaar043545e2006-10-10 16:44:07 +00003486 /* We can't open a file with a name "\\.\con" or "\\.\prn" and trying to
3487 * read from it later will cause Vim to hang. Thus return NODE_WRITABLE
3488 * here. */
3489 if (STRNCMP(name, "\\\\.\\", 4) == 0)
3490 return NODE_WRITABLE;
3491
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003492#ifdef FEAT_MBYTE
3493 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003494 wn = enc_to_utf16(name, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003495
3496 if (wn != NULL)
3497 {
3498 hFile = CreateFileW(wn, /* file name */
3499 GENERIC_WRITE, /* access mode */
3500 0, /* share mode */
3501 NULL, /* security descriptor */
3502 OPEN_EXISTING, /* creation disposition */
3503 0, /* file attributes */
3504 NULL); /* handle to template file */
3505 vim_free(wn);
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003506 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003507 else
Bram Moolenaar4dee1bb2013-08-30 17:11:33 +02003508#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01003509 hFile = CreateFile((LPCSTR)name, /* file name */
3510 GENERIC_WRITE, /* access mode */
3511 0, /* share mode */
3512 NULL, /* security descriptor */
3513 OPEN_EXISTING, /* creation disposition */
3514 0, /* file attributes */
3515 NULL); /* handle to template file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003516
3517 if (hFile == INVALID_HANDLE_VALUE)
3518 return NODE_NORMAL;
3519
3520 type = GetFileType(hFile);
3521 CloseHandle(hFile);
3522 if (type == FILE_TYPE_CHAR)
3523 return NODE_WRITABLE;
3524 if (type == FILE_TYPE_DISK)
3525 return NODE_NORMAL;
3526 return NODE_OTHER;
3527}
3528
3529#ifdef HAVE_ACL
3530struct my_acl
3531{
3532 PSECURITY_DESCRIPTOR pSecurityDescriptor;
3533 PSID pSidOwner;
3534 PSID pSidGroup;
3535 PACL pDacl;
3536 PACL pSacl;
3537};
3538#endif
3539
3540/*
3541 * Return a pointer to the ACL of file "fname" in allocated memory.
3542 * Return NULL if the ACL is not available for whatever reason.
3543 */
3544 vim_acl_T
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003545mch_get_acl(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003546{
3547#ifndef HAVE_ACL
3548 return (vim_acl_T)NULL;
3549#else
3550 struct my_acl *p = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003551 DWORD err;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003552
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003553 p = (struct my_acl *)alloc_clear((unsigned)sizeof(struct my_acl));
3554 if (p != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555 {
Bram Moolenaar27515922013-06-29 15:36:26 +02003556# ifdef FEAT_MBYTE
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003557 WCHAR *wn = NULL;
Bram Moolenaar27515922013-06-29 15:36:26 +02003558
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003559 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3560 wn = enc_to_utf16(fname, NULL);
3561 if (wn != NULL)
3562 {
3563 /* Try to retrieve the entire security descriptor. */
3564 err = GetNamedSecurityInfoW(
3565 wn, // Abstract filename
3566 SE_FILE_OBJECT, // File Object
3567 OWNER_SECURITY_INFORMATION |
3568 GROUP_SECURITY_INFORMATION |
3569 DACL_SECURITY_INFORMATION |
3570 SACL_SECURITY_INFORMATION,
3571 &p->pSidOwner, // Ownership information.
3572 &p->pSidGroup, // Group membership.
3573 &p->pDacl, // Discretionary information.
3574 &p->pSacl, // For auditing purposes.
3575 &p->pSecurityDescriptor);
3576 if (err == ERROR_ACCESS_DENIED ||
3577 err == ERROR_PRIVILEGE_NOT_HELD)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003579 /* Retrieve only DACL. */
3580 (void)GetNamedSecurityInfoW(
3581 wn,
3582 SE_FILE_OBJECT,
3583 DACL_SECURITY_INFORMATION,
3584 NULL,
3585 NULL,
3586 &p->pDacl,
3587 NULL,
3588 &p->pSecurityDescriptor);
Bram Moolenaar27515922013-06-29 15:36:26 +02003589 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003590 if (p->pSecurityDescriptor == NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003591 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003592 mch_free_acl((vim_acl_T)p);
3593 p = NULL;
3594 }
3595 vim_free(wn);
3596 }
3597 else
3598# endif
3599 {
3600 /* Try to retrieve the entire security descriptor. */
3601 err = GetNamedSecurityInfo(
3602 (LPSTR)fname, // Abstract filename
3603 SE_FILE_OBJECT, // File Object
3604 OWNER_SECURITY_INFORMATION |
3605 GROUP_SECURITY_INFORMATION |
3606 DACL_SECURITY_INFORMATION |
3607 SACL_SECURITY_INFORMATION,
3608 &p->pSidOwner, // Ownership information.
3609 &p->pSidGroup, // Group membership.
3610 &p->pDacl, // Discretionary information.
3611 &p->pSacl, // For auditing purposes.
3612 &p->pSecurityDescriptor);
3613 if (err == ERROR_ACCESS_DENIED ||
3614 err == ERROR_PRIVILEGE_NOT_HELD)
3615 {
3616 /* Retrieve only DACL. */
3617 (void)GetNamedSecurityInfo(
3618 (LPSTR)fname,
3619 SE_FILE_OBJECT,
3620 DACL_SECURITY_INFORMATION,
3621 NULL,
3622 NULL,
3623 &p->pDacl,
3624 NULL,
3625 &p->pSecurityDescriptor);
3626 }
3627 if (p->pSecurityDescriptor == NULL)
3628 {
3629 mch_free_acl((vim_acl_T)p);
3630 p = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003631 }
3632 }
3633 }
3634
3635 return (vim_acl_T)p;
3636#endif
3637}
3638
Bram Moolenaar27515922013-06-29 15:36:26 +02003639#ifdef HAVE_ACL
3640/*
3641 * Check if "acl" contains inherited ACE.
3642 */
3643 static BOOL
3644is_acl_inherited(PACL acl)
3645{
3646 DWORD i;
3647 ACL_SIZE_INFORMATION acl_info;
3648 PACCESS_ALLOWED_ACE ace;
3649
3650 acl_info.AceCount = 0;
3651 GetAclInformation(acl, &acl_info, sizeof(acl_info), AclSizeInformation);
3652 for (i = 0; i < acl_info.AceCount; i++)
3653 {
3654 GetAce(acl, i, (LPVOID *)&ace);
3655 if (ace->Header.AceFlags & INHERITED_ACE)
3656 return TRUE;
3657 }
3658 return FALSE;
3659}
3660#endif
3661
Bram Moolenaar071d4272004-06-13 20:20:40 +00003662/*
3663 * Set the ACL of file "fname" to "acl" (unless it's NULL).
3664 * Errors are ignored.
3665 * This must only be called with "acl" equal to what mch_get_acl() returned.
3666 */
3667 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003668mch_set_acl(char_u *fname, vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003669{
3670#ifdef HAVE_ACL
3671 struct my_acl *p = (struct my_acl *)acl;
Bram Moolenaar27515922013-06-29 15:36:26 +02003672 SECURITY_INFORMATION sec_info = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003673
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003674 if (p != NULL)
Bram Moolenaar27515922013-06-29 15:36:26 +02003675 {
3676# ifdef FEAT_MBYTE
3677 WCHAR *wn = NULL;
3678# endif
3679
3680 /* Set security flags */
3681 if (p->pSidOwner)
3682 sec_info |= OWNER_SECURITY_INFORMATION;
3683 if (p->pSidGroup)
3684 sec_info |= GROUP_SECURITY_INFORMATION;
3685 if (p->pDacl)
3686 {
3687 sec_info |= DACL_SECURITY_INFORMATION;
3688 /* Do not inherit its parent's DACL.
3689 * If the DACL is inherited, Cygwin permissions would be changed.
3690 */
3691 if (!is_acl_inherited(p->pDacl))
3692 sec_info |= PROTECTED_DACL_SECURITY_INFORMATION;
3693 }
3694 if (p->pSacl)
3695 sec_info |= SACL_SECURITY_INFORMATION;
3696
3697# ifdef FEAT_MBYTE
3698 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
3699 wn = enc_to_utf16(fname, NULL);
3700 if (wn != NULL)
3701 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003702 (void)SetNamedSecurityInfoW(
Bram Moolenaar27515922013-06-29 15:36:26 +02003703 wn, // Abstract filename
3704 SE_FILE_OBJECT, // File Object
3705 sec_info,
3706 p->pSidOwner, // Ownership information.
3707 p->pSidGroup, // Group membership.
3708 p->pDacl, // Discretionary information.
3709 p->pSacl // For auditing purposes.
3710 );
3711 vim_free(wn);
3712 }
3713 else
3714# endif
3715 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02003716 (void)SetNamedSecurityInfo(
Bram Moolenaar27515922013-06-29 15:36:26 +02003717 (LPSTR)fname, // Abstract filename
3718 SE_FILE_OBJECT, // File Object
3719 sec_info,
3720 p->pSidOwner, // Ownership information.
3721 p->pSidGroup, // Group membership.
3722 p->pDacl, // Discretionary information.
3723 p->pSacl // For auditing purposes.
3724 );
3725 }
3726 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727#endif
3728}
3729
3730 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003731mch_free_acl(vim_acl_T acl)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732{
3733#ifdef HAVE_ACL
3734 struct my_acl *p = (struct my_acl *)acl;
3735
3736 if (p != NULL)
3737 {
3738 LocalFree(p->pSecurityDescriptor); // Free the memory just in case
3739 vim_free(p);
3740 }
3741#endif
3742}
3743
3744#ifndef FEAT_GUI_W32
3745
3746/*
3747 * handler for ctrl-break, ctrl-c interrupts, and fatal events.
3748 */
3749 static BOOL WINAPI
3750handler_routine(
3751 DWORD dwCtrlType)
3752{
Bram Moolenaar589b1102017-08-12 16:39:05 +02003753 INPUT_RECORD ir;
3754 DWORD out;
3755
Bram Moolenaar071d4272004-06-13 20:20:40 +00003756 switch (dwCtrlType)
3757 {
3758 case CTRL_C_EVENT:
3759 if (ctrl_c_interrupts)
3760 g_fCtrlCPressed = TRUE;
3761 return TRUE;
3762
3763 case CTRL_BREAK_EVENT:
3764 g_fCBrkPressed = TRUE;
Bram Moolenaar589b1102017-08-12 16:39:05 +02003765 ctrl_break_was_pressed = TRUE;
3766 /* ReadConsoleInput is blocking, send a key event to continue. */
3767 ir.EventType = KEY_EVENT;
3768 ir.Event.KeyEvent.bKeyDown = TRUE;
3769 ir.Event.KeyEvent.wRepeatCount = 1;
3770 ir.Event.KeyEvent.wVirtualKeyCode = VK_CANCEL;
3771 ir.Event.KeyEvent.wVirtualScanCode = 0;
3772 ir.Event.KeyEvent.dwControlKeyState = 0;
3773 ir.Event.KeyEvent.uChar.UnicodeChar = 0;
3774 WriteConsoleInput(g_hConIn, &ir, 1, &out);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003775 return TRUE;
3776
3777 /* fatal events: shut down gracefully */
3778 case CTRL_CLOSE_EVENT:
3779 case CTRL_LOGOFF_EVENT:
3780 case CTRL_SHUTDOWN_EVENT:
3781 windgoto((int)Rows - 1, 0);
3782 g_fForceExit = TRUE;
3783
Bram Moolenaar0fde2902008-03-16 13:54:13 +00003784 vim_snprintf((char *)IObuff, IOSIZE, _("Vim: Caught %s event\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003785 (dwCtrlType == CTRL_CLOSE_EVENT
3786 ? _("close")
3787 : dwCtrlType == CTRL_LOGOFF_EVENT
3788 ? _("logoff")
3789 : _("shutdown")));
3790#ifdef DEBUG
3791 OutputDebugString(IObuff);
3792#endif
3793
3794 preserve_exit(); /* output IObuff, preserve files and exit */
3795
3796 return TRUE; /* not reached */
3797
3798 default:
3799 return FALSE;
3800 }
3801}
3802
3803
3804/*
3805 * set the tty in (raw) ? "raw" : "cooked" mode
3806 */
3807 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003808mch_settmode(int tmode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003809{
3810 DWORD cmodein;
3811 DWORD cmodeout;
3812 BOOL bEnableHandler;
3813
3814 GetConsoleMode(g_hConIn, &cmodein);
3815 GetConsoleMode(g_hConOut, &cmodeout);
3816 if (tmode == TMODE_RAW)
3817 {
3818 cmodein &= ~(ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3819 ENABLE_ECHO_INPUT);
3820#ifdef FEAT_MOUSE
3821 if (g_fMouseActive)
3822 cmodein |= ENABLE_MOUSE_INPUT;
3823#endif
3824 cmodeout &= ~(ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3825 bEnableHandler = TRUE;
3826 }
3827 else /* cooked */
3828 {
3829 cmodein |= (ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT |
3830 ENABLE_ECHO_INPUT);
3831 cmodeout |= (ENABLE_PROCESSED_OUTPUT | ENABLE_WRAP_AT_EOL_OUTPUT);
3832 bEnableHandler = FALSE;
3833 }
3834 SetConsoleMode(g_hConIn, cmodein);
3835 SetConsoleMode(g_hConOut, cmodeout);
3836 SetConsoleCtrlHandler(handler_routine, bEnableHandler);
3837
3838#ifdef MCH_WRITE_DUMP
3839 if (fdDump)
3840 {
3841 fprintf(fdDump, "mch_settmode(%s, in = %x, out = %x)\n",
3842 tmode == TMODE_RAW ? "raw" :
3843 tmode == TMODE_COOK ? "cooked" : "normal",
3844 cmodein, cmodeout);
3845 fflush(fdDump);
3846 }
3847#endif
3848}
3849
3850
3851/*
3852 * Get the size of the current window in `Rows' and `Columns'
3853 * Return OK when size could be determined, FAIL otherwise.
3854 */
3855 int
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003856mch_get_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857{
3858 CONSOLE_SCREEN_BUFFER_INFO csbi;
3859
3860 if (!g_fTermcapMode && g_cbTermcap.IsValid)
3861 {
3862 /*
3863 * For some reason, we are trying to get the screen dimensions
3864 * even though we are not in termcap mode. The 'Rows' and 'Columns'
3865 * variables are really intended to mean the size of Vim screen
3866 * while in termcap mode.
3867 */
3868 Rows = g_cbTermcap.Info.dwSize.Y;
3869 Columns = g_cbTermcap.Info.dwSize.X;
3870 }
3871 else if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3872 {
3873 Rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3874 Columns = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3875 }
3876 else
3877 {
3878 Rows = 25;
3879 Columns = 80;
3880 }
3881 return OK;
3882}
3883
3884/*
3885 * Set a console window to `xSize' * `ySize'
3886 */
3887 static void
3888ResizeConBufAndWindow(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003889 HANDLE hConsole,
3890 int xSize,
3891 int ySize)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892{
3893 CONSOLE_SCREEN_BUFFER_INFO csbi; /* hold current console buffer info */
3894 SMALL_RECT srWindowRect; /* hold the new console size */
3895 COORD coordScreen;
3896
3897#ifdef MCH_WRITE_DUMP
3898 if (fdDump)
3899 {
3900 fprintf(fdDump, "ResizeConBufAndWindow(%d, %d)\n", xSize, ySize);
3901 fflush(fdDump);
3902 }
3903#endif
3904
3905 /* get the largest size we can size the console window to */
3906 coordScreen = GetLargestConsoleWindowSize(hConsole);
3907
3908 /* define the new console window size and scroll position */
3909 srWindowRect.Left = srWindowRect.Top = (SHORT) 0;
3910 srWindowRect.Right = (SHORT) (min(xSize, coordScreen.X) - 1);
3911 srWindowRect.Bottom = (SHORT) (min(ySize, coordScreen.Y) - 1);
3912
3913 if (GetConsoleScreenBufferInfo(g_hConOut, &csbi))
3914 {
3915 int sx, sy;
3916
3917 sx = csbi.srWindow.Right - csbi.srWindow.Left + 1;
3918 sy = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
3919 if (sy < ySize || sx < xSize)
3920 {
3921 /*
3922 * Increasing number of lines/columns, do buffer first.
3923 * Use the maximal size in x and y direction.
3924 */
3925 if (sy < ySize)
3926 coordScreen.Y = ySize;
3927 else
3928 coordScreen.Y = sy;
3929 if (sx < xSize)
3930 coordScreen.X = xSize;
3931 else
3932 coordScreen.X = sx;
3933 SetConsoleScreenBufferSize(hConsole, coordScreen);
3934 }
3935 }
3936
3937 if (!SetConsoleWindowInfo(g_hConOut, TRUE, &srWindowRect))
3938 {
3939#ifdef MCH_WRITE_DUMP
3940 if (fdDump)
3941 {
3942 fprintf(fdDump, "SetConsoleWindowInfo failed: %lx\n",
3943 GetLastError());
3944 fflush(fdDump);
3945 }
3946#endif
3947 }
3948
3949 /* define the new console buffer size */
3950 coordScreen.X = xSize;
3951 coordScreen.Y = ySize;
3952
3953 if (!SetConsoleScreenBufferSize(hConsole, coordScreen))
3954 {
3955#ifdef MCH_WRITE_DUMP
3956 if (fdDump)
3957 {
3958 fprintf(fdDump, "SetConsoleScreenBufferSize failed: %lx\n",
3959 GetLastError());
3960 fflush(fdDump);
3961 }
3962#endif
3963 }
3964}
3965
3966
3967/*
3968 * Set the console window to `Rows' * `Columns'
3969 */
3970 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00003971mch_set_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003972{
3973 COORD coordScreen;
3974
3975 /* Don't change window size while still starting up */
3976 if (suppress_winsize != 0)
3977 {
3978 suppress_winsize = 2;
3979 return;
3980 }
3981
3982 if (term_console)
3983 {
3984 coordScreen = GetLargestConsoleWindowSize(g_hConOut);
3985
3986 /* Clamp Rows and Columns to reasonable values */
3987 if (Rows > coordScreen.Y)
3988 Rows = coordScreen.Y;
3989 if (Columns > coordScreen.X)
3990 Columns = coordScreen.X;
3991
3992 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
3993 }
3994}
3995
3996/*
3997 * Rows and/or Columns has changed.
3998 */
3999 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004000mch_new_shellsize(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004001{
4002 set_scroll_region(0, 0, Columns - 1, Rows - 1);
4003}
4004
4005
4006/*
4007 * Called when started up, to set the winsize that was delayed.
4008 */
4009 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004010mch_set_winsize_now(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004011{
4012 if (suppress_winsize == 2)
4013 {
4014 suppress_winsize = 0;
4015 mch_set_shellsize();
4016 shell_resized();
4017 }
4018 suppress_winsize = 0;
4019}
4020#endif /* FEAT_GUI_W32 */
4021
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004022 static BOOL
4023vim_create_process(
Bram Moolenaar36c85b22013-12-12 20:25:44 +01004024 char *cmd,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004025 BOOL inherit_handles,
Bram Moolenaar3f1138e2014-01-05 13:29:26 +01004026 DWORD flags,
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004027 STARTUPINFO *si,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004028 PROCESS_INFORMATION *pi,
4029 LPVOID *env,
4030 char *cwd)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004031{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004032#ifdef FEAT_MBYTE
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004033 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4034 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004035 BOOL ret;
4036 WCHAR *wcmd, *wcwd = NULL;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004037
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004038 wcmd = enc_to_utf16((char_u *)cmd, NULL);
4039 if (wcmd == NULL)
4040 goto fallback;
4041 if (cwd != NULL)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004042 {
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004043 wcwd = enc_to_utf16((char_u *)cwd, NULL);
4044 if (wcwd == NULL)
4045 {
4046 vim_free(wcmd);
4047 goto fallback;
4048 }
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004049 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004050
4051 ret = CreateProcessW(
4052 NULL, /* Executable name */
4053 wcmd, /* Command to execute */
4054 NULL, /* Process security attributes */
4055 NULL, /* Thread security attributes */
4056 inherit_handles, /* Inherit handles */
4057 flags, /* Creation flags */
4058 env, /* Environment */
4059 wcwd, /* Current directory */
4060 (LPSTARTUPINFOW)si, /* Startup information */
4061 pi); /* Process information */
4062 vim_free(wcmd);
4063 if (wcwd != NULL)
4064 vim_free(wcwd);
4065 return ret;
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004066 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004067fallback:
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004068#endif
4069 return CreateProcess(
4070 NULL, /* Executable name */
4071 cmd, /* Command to execute */
4072 NULL, /* Process security attributes */
4073 NULL, /* Thread security attributes */
4074 inherit_handles, /* Inherit handles */
4075 flags, /* Creation flags */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004076 env, /* Environment */
4077 cwd, /* Current directory */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004078 si, /* Startup information */
4079 pi); /* Process information */
4080}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004081
4082
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004083 static HINSTANCE
4084vim_shell_execute(
4085 char *cmd,
4086 INT n_show_cmd)
4087{
4088#ifdef FEAT_MBYTE
4089 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4090 {
4091 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
4092 if (wcmd != NULL)
4093 {
4094 HINSTANCE ret;
4095 ret = ShellExecuteW(NULL, NULL, wcmd, NULL, NULL, n_show_cmd);
4096 vim_free(wcmd);
4097 return ret;
4098 }
4099 }
4100#endif
4101 return ShellExecute(NULL, NULL, cmd, NULL, NULL, n_show_cmd);
4102}
4103
4104
Bram Moolenaar071d4272004-06-13 20:20:40 +00004105#if defined(FEAT_GUI_W32) || defined(PROTO)
4106
4107/*
4108 * Specialised version of system() for Win32 GUI mode.
4109 * This version proceeds as follows:
4110 * 1. Create a console window for use by the subprocess
4111 * 2. Run the subprocess (it gets the allocated console by default)
4112 * 3. Wait for the subprocess to terminate and get its exit code
4113 * 4. Prompt the user to press a key to close the console window
4114 */
4115 static int
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004116mch_system_classic(char *cmd, int options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004117{
4118 STARTUPINFO si;
4119 PROCESS_INFORMATION pi;
4120 DWORD ret = 0;
4121 HWND hwnd = GetFocus();
4122
4123 si.cb = sizeof(si);
4124 si.lpReserved = NULL;
4125 si.lpDesktop = NULL;
4126 si.lpTitle = NULL;
4127 si.dwFlags = STARTF_USESHOWWINDOW;
4128 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004129 * It's nicer to run a filter command in a minimized window.
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004130 * Don't activate the window to keep focus on Vim.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004131 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004132 if (options & SHELL_DOOUT)
Bram Moolenaar96e5cee2010-11-24 12:35:21 +01004133 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134 else
4135 si.wShowWindow = SW_SHOWNORMAL;
4136 si.cbReserved2 = 0;
4137 si.lpReserved2 = NULL;
4138
Bram Moolenaar071d4272004-06-13 20:20:40 +00004139 /* Now, run the command */
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004140 vim_create_process(cmd, FALSE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004141 CREATE_DEFAULT_ERROR_MODE | CREATE_NEW_CONSOLE,
4142 &si, &pi, NULL, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004143
4144 /* Wait for the command to terminate before continuing */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004145 {
4146#ifdef FEAT_GUI
4147 int delay = 1;
4148
4149 /* Keep updating the window while waiting for the shell to finish. */
4150 for (;;)
4151 {
4152 MSG msg;
4153
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004154 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 {
4156 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02004157 pDispatchMessage(&msg);
Bram Moolenaare4195c52012-08-02 12:31:44 +02004158 delay = 1;
4159 continue;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004160 }
4161 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4162 break;
4163
4164 /* We start waiting for a very short time and then increase it, so
4165 * that we respond quickly when the process is quick, and don't
4166 * consume too much overhead when it's slow. */
4167 if (delay < 50)
4168 delay += 10;
4169 }
4170#else
4171 WaitForSingleObject(pi.hProcess, INFINITE);
4172#endif
4173
4174 /* Get the command exit code */
4175 GetExitCodeProcess(pi.hProcess, &ret);
4176 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177
4178 /* Close the handles to the subprocess, so that it goes away */
4179 CloseHandle(pi.hThread);
4180 CloseHandle(pi.hProcess);
4181
4182 /* Try to get input focus back. Doesn't always work though. */
4183 PostMessage(hwnd, WM_SETFOCUS, 0, 0);
4184
4185 return ret;
4186}
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004187
4188/*
4189 * Thread launched by the gui to send the current buffer data to the
4190 * process. This way avoid to hang up vim totally if the children
4191 * process take a long time to process the lines.
4192 */
Bram Moolenaar4c38d662016-08-03 20:54:57 +02004193 static unsigned int __stdcall
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004194sub_process_writer(LPVOID param)
4195{
4196 HANDLE g_hChildStd_IN_Wr = param;
4197 linenr_T lnum = curbuf->b_op_start.lnum;
4198 DWORD len = 0;
4199 DWORD l;
4200 char_u *lp = ml_get(lnum);
4201 char_u *s;
4202 int written = 0;
4203
4204 for (;;)
4205 {
4206 l = (DWORD)STRLEN(lp + written);
4207 if (l == 0)
4208 len = 0;
4209 else if (lp[written] == NL)
4210 {
4211 /* NL -> NUL translation */
4212 WriteFile(g_hChildStd_IN_Wr, "", 1, &len, NULL);
4213 }
4214 else
4215 {
4216 s = vim_strchr(lp + written, NL);
4217 WriteFile(g_hChildStd_IN_Wr, (char *)lp + written,
4218 s == NULL ? l : (DWORD)(s - (lp + written)),
4219 &len, NULL);
4220 }
4221 if (len == (int)l)
4222 {
4223 /* Finished a line, add a NL, unless this line should not have
4224 * one. */
4225 if (lnum != curbuf->b_op_end.lnum
Bram Moolenaar34d72d42015-07-17 14:18:08 +02004226 || (!curbuf->b_p_bin
4227 && curbuf->b_p_fixeol)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004228 || (lnum != curbuf->b_no_eol_lnum
4229 && (lnum != curbuf->b_ml.ml_line_count
4230 || curbuf->b_p_eol)))
4231 {
Bram Moolenaaraf62ff32013-03-19 14:48:29 +01004232 WriteFile(g_hChildStd_IN_Wr, "\n", 1, (LPDWORD)&ignored, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004233 }
4234
4235 ++lnum;
4236 if (lnum > curbuf->b_op_end.lnum)
4237 break;
4238
4239 lp = ml_get(lnum);
4240 written = 0;
4241 }
4242 else if (len > 0)
4243 written += len;
4244 }
4245
4246 /* finished all the lines, close pipe */
4247 CloseHandle(g_hChildStd_IN_Wr);
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004248 return 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004249}
4250
4251
4252# define BUFLEN 100 /* length for buffer, stolen from unix version */
4253
4254/*
4255 * This function read from the children's stdout and write the
4256 * data on screen or in the buffer accordingly.
4257 */
4258 static void
4259dump_pipe(int options,
4260 HANDLE g_hChildStd_OUT_Rd,
4261 garray_T *ga,
4262 char_u buffer[],
4263 DWORD *buffer_off)
4264{
4265 DWORD availableBytes = 0;
4266 DWORD i;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004267 int ret;
4268 DWORD len;
4269 DWORD toRead;
4270 int repeatCount;
4271
4272 /* we query the pipe to see if there is any data to read
4273 * to avoid to perform a blocking read */
4274 ret = PeekNamedPipe(g_hChildStd_OUT_Rd, /* pipe to query */
4275 NULL, /* optional buffer */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004276 0, /* buffer size */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004277 NULL, /* number of read bytes */
4278 &availableBytes, /* available bytes total */
4279 NULL); /* byteLeft */
4280
4281 repeatCount = 0;
4282 /* We got real data in the pipe, read it */
Bram Moolenaarf6a2b082012-06-29 13:14:03 +02004283 while (ret != 0 && availableBytes > 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004284 {
4285 repeatCount++;
4286 toRead =
4287# ifdef FEAT_MBYTE
4288 (DWORD)(BUFLEN - *buffer_off);
4289# else
4290 (DWORD)BUFLEN;
4291# endif
4292 toRead = availableBytes < toRead ? availableBytes : toRead;
4293 ReadFile(g_hChildStd_OUT_Rd, buffer
4294# ifdef FEAT_MBYTE
4295 + *buffer_off, toRead
4296# else
4297 , toRead
4298# endif
4299 , &len, NULL);
4300
4301 /* If we haven't read anything, there is a problem */
4302 if (len == 0)
4303 break;
4304
4305 availableBytes -= len;
4306
4307 if (options & SHELL_READ)
4308 {
4309 /* Do NUL -> NL translation, append NL separated
4310 * lines to the current buffer. */
4311 for (i = 0; i < len; ++i)
4312 {
4313 if (buffer[i] == NL)
4314 append_ga_line(ga);
4315 else if (buffer[i] == NUL)
4316 ga_append(ga, NL);
4317 else
4318 ga_append(ga, buffer[i]);
4319 }
4320 }
4321# ifdef FEAT_MBYTE
4322 else if (has_mbyte)
4323 {
4324 int l;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004325 int c;
4326 char_u *p;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004327
4328 len += *buffer_off;
4329 buffer[len] = NUL;
4330
4331 /* Check if the last character in buffer[] is
4332 * incomplete, keep these bytes for the next
4333 * round. */
4334 for (p = buffer; p < buffer + len; p += l)
4335 {
Bram Moolenaard3c907b2016-08-17 21:32:09 +02004336 l = MB_CPTR2LEN(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004337 if (l == 0)
4338 l = 1; /* NUL byte? */
4339 else if (MB_BYTE2LEN(*p) != l)
4340 break;
4341 }
4342 if (p == buffer) /* no complete character */
4343 {
4344 /* avoid getting stuck at an illegal byte */
4345 if (len >= 12)
4346 ++p;
4347 else
4348 {
4349 *buffer_off = len;
4350 return;
4351 }
4352 }
4353 c = *p;
4354 *p = NUL;
4355 msg_puts(buffer);
4356 if (p < buffer + len)
4357 {
4358 *p = c;
4359 *buffer_off = (DWORD)((buffer + len) - p);
4360 mch_memmove(buffer, p, *buffer_off);
4361 return;
4362 }
4363 *buffer_off = 0;
4364 }
4365# endif /* FEAT_MBYTE */
4366 else
4367 {
4368 buffer[len] = NUL;
4369 msg_puts(buffer);
4370 }
4371
4372 windgoto(msg_row, msg_col);
4373 cursor_on();
4374 out_flush();
4375 }
4376}
4377
4378/*
4379 * Version of system to use for windows NT > 5.0 (Win2K), use pipe
4380 * for communication and doesn't open any new window.
4381 */
4382 static int
4383mch_system_piped(char *cmd, int options)
4384{
4385 STARTUPINFO si;
4386 PROCESS_INFORMATION pi;
4387 DWORD ret = 0;
4388
4389 HANDLE g_hChildStd_IN_Rd = NULL;
4390 HANDLE g_hChildStd_IN_Wr = NULL;
4391 HANDLE g_hChildStd_OUT_Rd = NULL;
4392 HANDLE g_hChildStd_OUT_Wr = NULL;
4393
4394 char_u buffer[BUFLEN + 1]; /* reading buffer + size */
4395 DWORD len;
4396
4397 /* buffer used to receive keys */
4398 char_u ta_buf[BUFLEN + 1]; /* TypeAHead */
4399 int ta_len = 0; /* valid bytes in ta_buf[] */
4400
4401 DWORD i;
4402 int c;
4403 int noread_cnt = 0;
4404 garray_T ga;
4405 int delay = 1;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004406 DWORD buffer_off = 0; /* valid bytes in buffer[] */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004407 char *p = NULL;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004408
4409 SECURITY_ATTRIBUTES saAttr;
4410
4411 /* Set the bInheritHandle flag so pipe handles are inherited. */
4412 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
4413 saAttr.bInheritHandle = TRUE;
4414 saAttr.lpSecurityDescriptor = NULL;
4415
4416 if ( ! CreatePipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr, 0)
4417 /* Ensure the read handle to the pipe for STDOUT is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004418 || ! SetHandleInformation(g_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004419 /* Create a pipe for the child process's STDIN. */
4420 || ! CreatePipe(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr, 0)
4421 /* Ensure the write handle to the pipe for STDIN is not inherited. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004422 || ! SetHandleInformation(g_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0) )
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004423 {
4424 CloseHandle(g_hChildStd_IN_Rd);
4425 CloseHandle(g_hChildStd_IN_Wr);
4426 CloseHandle(g_hChildStd_OUT_Rd);
4427 CloseHandle(g_hChildStd_OUT_Wr);
4428 MSG_PUTS(_("\nCannot create pipes\n"));
4429 }
4430
4431 si.cb = sizeof(si);
4432 si.lpReserved = NULL;
4433 si.lpDesktop = NULL;
4434 si.lpTitle = NULL;
4435 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
4436
4437 /* set-up our file redirection */
4438 si.hStdError = g_hChildStd_OUT_Wr;
4439 si.hStdOutput = g_hChildStd_OUT_Wr;
4440 si.hStdInput = g_hChildStd_IN_Rd;
4441 si.wShowWindow = SW_HIDE;
4442 si.cbReserved2 = 0;
4443 si.lpReserved2 = NULL;
4444
4445 if (options & SHELL_READ)
4446 ga_init2(&ga, 1, BUFLEN);
4447
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004448 if (cmd != NULL)
4449 {
4450 p = (char *)vim_strsave((char_u *)cmd);
4451 if (p != NULL)
4452 unescape_shellxquote((char_u *)p, p_sxe);
4453 else
4454 p = cmd;
4455 }
4456
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004457 /* Now, run the command.
4458 * About "Inherit handles" being TRUE: this command can be litigious,
4459 * handle inheritance was deactivated for pending temp file, but, if we
4460 * deactivate it, the pipes don't work for some reason. */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004461 vim_create_process(p, TRUE, CREATE_DEFAULT_ERROR_MODE,
4462 &si, &pi, NULL, NULL);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004463
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004464 if (p != cmd)
4465 vim_free(p);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004466
4467 /* Close our unused side of the pipes */
4468 CloseHandle(g_hChildStd_IN_Rd);
4469 CloseHandle(g_hChildStd_OUT_Wr);
4470
4471 if (options & SHELL_WRITE)
4472 {
Bram Moolenaar86f2cd52016-08-02 21:55:17 +02004473 HANDLE thread = (HANDLE)
4474 _beginthreadex(NULL, /* security attributes */
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004475 0, /* default stack size */
4476 sub_process_writer, /* function to be executed */
4477 g_hChildStd_IN_Wr, /* parameter */
4478 0, /* creation flag, start immediately */
4479 NULL); /* we don't care about thread id */
4480 CloseHandle(thread);
4481 g_hChildStd_IN_Wr = NULL;
4482 }
4483
4484 /* Keep updating the window while waiting for the shell to finish. */
4485 for (;;)
4486 {
4487 MSG msg;
4488
Bram Moolenaar175d0702013-12-11 18:36:33 +01004489 if (pPeekMessage(&msg, (HWND)NULL, 0, 0, PM_REMOVE))
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004490 {
4491 TranslateMessage(&msg);
Bram Moolenaar175d0702013-12-11 18:36:33 +01004492 pDispatchMessage(&msg);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004493 }
4494
4495 /* write pipe information in the window */
4496 if ((options & (SHELL_READ|SHELL_WRITE))
4497# ifdef FEAT_GUI
4498 || gui.in_use
4499# endif
4500 )
4501 {
4502 len = 0;
4503 if (!(options & SHELL_EXPAND)
4504 && ((options &
4505 (SHELL_READ|SHELL_WRITE|SHELL_COOKED))
4506 != (SHELL_READ|SHELL_WRITE|SHELL_COOKED)
4507# ifdef FEAT_GUI
4508 || gui.in_use
4509# endif
4510 )
4511 && (ta_len > 0 || noread_cnt > 4))
4512 {
4513 if (ta_len == 0)
4514 {
4515 /* Get extra characters when we don't have any. Reset the
4516 * counter and timer. */
4517 noread_cnt = 0;
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004518 len = ui_inchar(ta_buf, BUFLEN, 10L, 0);
4519 }
4520 if (ta_len > 0 || len > 0)
4521 {
4522 /*
4523 * For pipes: Check for CTRL-C: send interrupt signal to
4524 * child. Check for CTRL-D: EOF, close pipe to child.
4525 */
4526 if (len == 1 && cmd != NULL)
4527 {
4528 if (ta_buf[ta_len] == Ctrl_C)
4529 {
4530 /* Learn what exit code is expected, for
4531 * now put 9 as SIGKILL */
4532 TerminateProcess(pi.hProcess, 9);
4533 }
4534 if (ta_buf[ta_len] == Ctrl_D)
4535 {
4536 CloseHandle(g_hChildStd_IN_Wr);
4537 g_hChildStd_IN_Wr = NULL;
4538 }
4539 }
4540
4541 /* replace K_BS by <BS> and K_DEL by <DEL> */
4542 for (i = ta_len; i < ta_len + len; ++i)
4543 {
4544 if (ta_buf[i] == CSI && len - i > 2)
4545 {
4546 c = TERMCAP2KEY(ta_buf[i + 1], ta_buf[i + 2]);
4547 if (c == K_DEL || c == K_KDEL || c == K_BS)
4548 {
4549 mch_memmove(ta_buf + i + 1, ta_buf + i + 3,
4550 (size_t)(len - i - 2));
4551 if (c == K_DEL || c == K_KDEL)
4552 ta_buf[i] = DEL;
4553 else
4554 ta_buf[i] = Ctrl_H;
4555 len -= 2;
4556 }
4557 }
4558 else if (ta_buf[i] == '\r')
4559 ta_buf[i] = '\n';
4560# ifdef FEAT_MBYTE
4561 if (has_mbyte)
4562 i += (*mb_ptr2len_len)(ta_buf + i,
4563 ta_len + len - i) - 1;
4564# endif
4565 }
4566
4567 /*
4568 * For pipes: echo the typed characters. For a pty this
4569 * does not seem to work.
4570 */
4571 for (i = ta_len; i < ta_len + len; ++i)
4572 {
4573 if (ta_buf[i] == '\n' || ta_buf[i] == '\b')
4574 msg_putchar(ta_buf[i]);
4575# ifdef FEAT_MBYTE
4576 else if (has_mbyte)
4577 {
4578 int l = (*mb_ptr2len)(ta_buf + i);
4579
4580 msg_outtrans_len(ta_buf + i, l);
4581 i += l - 1;
4582 }
4583# endif
4584 else
4585 msg_outtrans_len(ta_buf + i, 1);
4586 }
4587 windgoto(msg_row, msg_col);
4588 out_flush();
4589
4590 ta_len += len;
4591
4592 /*
4593 * Write the characters to the child, unless EOF has been
4594 * typed for pipes. Write one character at a time, to
4595 * avoid losing too much typeahead. When writing buffer
4596 * lines, drop the typed characters (only check for
4597 * CTRL-C).
4598 */
4599 if (options & SHELL_WRITE)
4600 ta_len = 0;
4601 else if (g_hChildStd_IN_Wr != NULL)
4602 {
4603 WriteFile(g_hChildStd_IN_Wr, (char*)ta_buf,
4604 1, &len, NULL);
4605 // if we are typing in, we want to keep things reactive
4606 delay = 1;
4607 if (len > 0)
4608 {
4609 ta_len -= len;
4610 mch_memmove(ta_buf, ta_buf + len, ta_len);
4611 }
4612 }
4613 }
4614 }
4615 }
4616
4617 if (ta_len)
4618 ui_inchar_undo(ta_buf, ta_len);
4619
4620 if (WaitForSingleObject(pi.hProcess, delay) != WAIT_TIMEOUT)
4621 {
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004622 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004623 break;
4624 }
4625
4626 ++noread_cnt;
Bram Moolenaar2eba1822011-08-27 15:10:04 +02004627 dump_pipe(options, g_hChildStd_OUT_Rd, &ga, buffer, &buffer_off);
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004628
4629 /* We start waiting for a very short time and then increase it, so
4630 * that we respond quickly when the process is quick, and don't
4631 * consume too much overhead when it's slow. */
4632 if (delay < 50)
4633 delay += 10;
4634 }
4635
4636 /* Close the pipe */
4637 CloseHandle(g_hChildStd_OUT_Rd);
4638 if (g_hChildStd_IN_Wr != NULL)
4639 CloseHandle(g_hChildStd_IN_Wr);
4640
4641 WaitForSingleObject(pi.hProcess, INFINITE);
4642
4643 /* Get the command exit code */
4644 GetExitCodeProcess(pi.hProcess, &ret);
4645
4646 if (options & SHELL_READ)
4647 {
4648 if (ga.ga_len > 0)
4649 {
4650 append_ga_line(&ga);
4651 /* remember that the NL was missing */
4652 curbuf->b_no_eol_lnum = curwin->w_cursor.lnum;
4653 }
4654 else
4655 curbuf->b_no_eol_lnum = 0;
4656 ga_clear(&ga);
4657 }
4658
4659 /* Close the handles to the subprocess, so that it goes away */
4660 CloseHandle(pi.hThread);
4661 CloseHandle(pi.hProcess);
4662
4663 return ret;
4664}
4665
4666 static int
4667mch_system(char *cmd, int options)
4668{
4669 /* if we can pipe and the shelltemp option is off */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004670 if (!p_stmp)
Bram Moolenaar4b9669f2011-07-07 16:20:52 +02004671 return mch_system_piped(cmd, options);
4672 else
4673 return mch_system_classic(cmd, options);
4674}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004675#else
4676
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004677# ifdef FEAT_MBYTE
4678 static int
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004679mch_system(char *cmd, int options)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004680{
4681 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4682 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004683 WCHAR *wcmd = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004684 if (wcmd != NULL)
4685 {
4686 int ret = _wsystem(wcmd);
4687 vim_free(wcmd);
4688 return ret;
4689 }
4690 }
4691 return system(cmd);
4692}
4693# else
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01004694# define mch_system(c, o) system(c)
Bram Moolenaar910cffb2013-12-11 17:58:35 +01004695# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004696
4697#endif
4698
4699/*
4700 * Either execute a command by calling the shell or start a new shell
4701 */
4702 int
4703mch_call_shell(
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00004704 char_u *cmd,
4705 int options) /* SHELL_*, see vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004706{
4707 int x = 0;
4708 int tmode = cur_tmode;
4709#ifdef FEAT_TITLE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004710 char szShellTitle[512];
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004711# ifdef FEAT_MBYTE
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004712 int did_set_title = FALSE;
4713
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004714 /* Change the title to reflect that we are in a subshell. */
4715 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4716 {
4717 WCHAR szShellTitle[512];
4718
4719 if (GetConsoleTitleW(szShellTitle,
4720 sizeof(szShellTitle)/sizeof(WCHAR) - 4) > 0)
4721 {
4722 if (cmd == NULL)
4723 wcscat(szShellTitle, L" :sh");
4724 else
4725 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004726 WCHAR *wn = enc_to_utf16((char_u *)cmd, NULL);
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004727
4728 if (wn != NULL)
4729 {
4730 wcscat(szShellTitle, L" - !");
4731 if ((wcslen(szShellTitle) + wcslen(wn) <
4732 sizeof(szShellTitle)/sizeof(WCHAR)))
4733 wcscat(szShellTitle, wn);
4734 SetConsoleTitleW(szShellTitle);
4735 vim_free(wn);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004736 did_set_title = TRUE;
Bram Moolenaar1df52d72014-10-15 22:50:10 +02004737 }
4738 }
4739 }
4740 }
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004741 if (!did_set_title)
4742# endif
4743 /* Change the title to reflect that we are in a subshell. */
4744 if (GetConsoleTitle(szShellTitle, sizeof(szShellTitle) - 4) > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004745 {
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004746 if (cmd == NULL)
4747 strcat(szShellTitle, " :sh");
4748 else
4749 {
4750 strcat(szShellTitle, " - !");
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004751 if ((strlen(szShellTitle) + strlen((char *)cmd)
4752 < sizeof(szShellTitle)))
4753 strcat(szShellTitle, (char *)cmd);
Bram Moolenaar799d6ab2014-10-16 16:16:37 +02004754 }
4755 SetConsoleTitle(szShellTitle);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004757#endif
4758
4759 out_flush();
4760
4761#ifdef MCH_WRITE_DUMP
4762 if (fdDump)
4763 {
4764 fprintf(fdDump, "mch_call_shell(\"%s\", %d)\n", cmd, options);
4765 fflush(fdDump);
4766 }
4767#endif
4768
4769 /*
4770 * Catch all deadly signals while running the external command, because a
4771 * CTRL-C, Ctrl-Break or illegal instruction might otherwise kill us.
4772 */
4773 signal(SIGINT, SIG_IGN);
4774#if defined(__GNUC__) && !defined(__MINGW32__)
4775 signal(SIGKILL, SIG_IGN);
4776#else
4777 signal(SIGBREAK, SIG_IGN);
4778#endif
4779 signal(SIGILL, SIG_IGN);
4780 signal(SIGFPE, SIG_IGN);
4781 signal(SIGSEGV, SIG_IGN);
4782 signal(SIGTERM, SIG_IGN);
4783 signal(SIGABRT, SIG_IGN);
4784
4785 if (options & SHELL_COOKED)
4786 settmode(TMODE_COOK); /* set to normal mode */
4787
4788 if (cmd == NULL)
4789 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004790 x = mch_system((char *)p_sh, options);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004791 }
4792 else
4793 {
4794 /* we use "command" or "cmd" to start the shell; slow but easy */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004795 char_u *newcmd = NULL;
4796 char_u *cmdbase = cmd;
4797 long_u cmdlen;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004798
4799 /* Skip a leading ", ( and "(. */
4800 if (*cmdbase == '"' )
4801 ++cmdbase;
4802 if (*cmdbase == '(')
4803 ++cmdbase;
4804
Bram Moolenaar1c465442017-03-12 20:10:05 +01004805 if ((STRNICMP(cmdbase, "start", 5) == 0) && VIM_ISWHITE(cmdbase[5]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004806 {
4807 STARTUPINFO si;
4808 PROCESS_INFORMATION pi;
4809 DWORD flags = CREATE_NEW_CONSOLE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004810 INT n_show_cmd = SW_SHOWNORMAL;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004811 char_u *p;
4812
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004813 ZeroMemory(&si, sizeof(si));
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004814 si.cb = sizeof(si);
4815 si.lpReserved = NULL;
4816 si.lpDesktop = NULL;
4817 si.lpTitle = NULL;
4818 si.dwFlags = 0;
4819 si.cbReserved2 = 0;
4820 si.lpReserved2 = NULL;
4821
4822 cmdbase = skipwhite(cmdbase + 5);
4823 if ((STRNICMP(cmdbase, "/min", 4) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004824 && VIM_ISWHITE(cmdbase[4]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004825 {
4826 cmdbase = skipwhite(cmdbase + 4);
4827 si.dwFlags = STARTF_USESHOWWINDOW;
4828 si.wShowWindow = SW_SHOWMINNOACTIVE;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004829 n_show_cmd = SW_SHOWMINNOACTIVE;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004830 }
4831 else if ((STRNICMP(cmdbase, "/b", 2) == 0)
Bram Moolenaar1c465442017-03-12 20:10:05 +01004832 && VIM_ISWHITE(cmdbase[2]))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004833 {
4834 cmdbase = skipwhite(cmdbase + 2);
4835 flags = CREATE_NO_WINDOW;
4836 si.dwFlags = STARTF_USESTDHANDLES;
4837 si.hStdInput = CreateFile("\\\\.\\NUL", // File name
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004838 GENERIC_READ, // Access flags
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004839 0, // Share flags
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004840 NULL, // Security att.
4841 OPEN_EXISTING, // Open flags
4842 FILE_ATTRIBUTE_NORMAL, // File att.
4843 NULL); // Temp file
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004844 si.hStdOutput = si.hStdInput;
4845 si.hStdError = si.hStdInput;
4846 }
4847
4848 /* Remove a trailing ", ) and )" if they have a match
4849 * at the start of the command. */
4850 if (cmdbase > cmd)
4851 {
4852 p = cmdbase + STRLEN(cmdbase);
4853 if (p > cmdbase && p[-1] == '"' && *cmd == '"')
4854 *--p = NUL;
4855 if (p > cmdbase && p[-1] == ')'
4856 && (*cmd =='(' || cmd[1] == '('))
4857 *--p = NUL;
4858 }
4859
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004860 newcmd = cmdbase;
4861 unescape_shellxquote(cmdbase, p_sxe);
4862
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004863 /*
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004864 * If creating new console, arguments are passed to the
4865 * 'cmd.exe' as-is. If it's not, arguments are not treated
4866 * correctly for current 'cmd.exe'. So unescape characters in
4867 * shellxescape except '|' for avoiding to be treated as
4868 * argument to them. Pass the arguments to sub-shell.
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004869 */
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004870 if (flags != CREATE_NEW_CONSOLE)
4871 {
4872 char_u *subcmd;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004873 char_u *cmd_shell = mch_getenv("COMSPEC");
4874
4875 if (cmd_shell == NULL || *cmd_shell == NUL)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004876 cmd_shell = (char_u *)default_shell();
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004877
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004878 subcmd = vim_strsave_escaped_ext(cmdbase,
4879 (char_u *)"|", '^', FALSE);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004880 if (subcmd != NULL)
4881 {
4882 /* make "cmd.exe /c arguments" */
4883 cmdlen = STRLEN(cmd_shell) + STRLEN(subcmd) + 5;
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004884 newcmd = lalloc(cmdlen, TRUE);
4885 if (newcmd != NULL)
4886 vim_snprintf((char *)newcmd, cmdlen, "%s /c %s",
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004887 cmd_shell, subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004888 else
4889 newcmd = cmdbase;
Bram Moolenaaree7d1002012-02-22 15:34:08 +01004890 vim_free(subcmd);
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004891 }
4892 }
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004893
4894 /*
4895 * Now, start the command as a process, so that it doesn't
4896 * inherit our handles which causes unpleasant dangling swap
4897 * files if we exit before the spawned process
4898 */
Bram Moolenaar05aafed2017-08-11 19:12:11 +02004899 if (vim_create_process((char *)newcmd, FALSE, flags,
4900 &si, &pi, NULL, NULL))
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004901 x = 0;
Bram Moolenaarb2964f22017-03-21 19:29:26 +01004902 else if (vim_shell_execute((char *)newcmd, n_show_cmd)
4903 > (HINSTANCE)32)
4904 x = 0;
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004905 else
4906 {
4907 x = -1;
4908#ifdef FEAT_GUI_W32
4909 EMSG(_("E371: Command not found"));
4910#endif
4911 }
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004912
4913 if (newcmd != cmdbase)
4914 vim_free(newcmd);
4915
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004916 if (si.dwFlags == STARTF_USESTDHANDLES && si.hStdInput != NULL)
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004917 {
Bram Moolenaarfcc3f462014-01-24 19:55:37 +01004918 /* Close the handle to \\.\NUL created above. */
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004919 CloseHandle(si.hStdInput);
4920 }
4921 /* Close the handles to the subprocess, so that it goes away */
4922 CloseHandle(pi.hThread);
4923 CloseHandle(pi.hProcess);
4924 }
4925 else
4926 {
Bram Moolenaarfb7df7b2012-02-22 13:07:05 +01004927 cmdlen = (
Bram Moolenaar071d4272004-06-13 20:20:40 +00004928#ifdef FEAT_GUI_W32
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004929 (!p_stmp ? 0 : STRLEN(vimrun_path)) +
Bram Moolenaar071d4272004-06-13 20:20:40 +00004930#endif
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004931 STRLEN(p_sh) + STRLEN(p_shcf) + STRLEN(cmd) + 10);
4932
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004933 newcmd = lalloc(cmdlen, TRUE);
4934 if (newcmd != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004935 {
4936#if defined(FEAT_GUI_W32)
4937 if (need_vimrun_warning)
4938 {
Bram Moolenaar63e43442016-11-19 17:28:44 +01004939 char *msg = _("VIMRUN.EXE not found in your $PATH.\n"
4940 "External commands will not pause after completion.\n"
4941 "See :help win32-vimrun for more information.");
4942 char *title = _("Vim Warning");
4943# ifdef FEAT_MBYTE
4944 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
4945 {
4946 WCHAR *wmsg = enc_to_utf16((char_u *)msg, NULL);
4947 WCHAR *wtitle = enc_to_utf16((char_u *)title, NULL);
4948
4949 if (wmsg != NULL && wtitle != NULL)
4950 MessageBoxW(NULL, wmsg, wtitle, MB_ICONWARNING);
4951 vim_free(wmsg);
4952 vim_free(wtitle);
4953 }
4954 else
4955# endif
4956 MessageBox(NULL, msg, title, MB_ICONWARNING);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004957 need_vimrun_warning = FALSE;
4958 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004959 if (!s_dont_use_vimrun && p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004960 /* Use vimrun to execute the command. It opens a console
4961 * window, which can be closed without killing Vim. */
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004962 vim_snprintf((char *)newcmd, cmdlen, "%s%s%s %s %s",
Bram Moolenaar071d4272004-06-13 20:20:40 +00004963 vimrun_path,
4964 (msg_silent != 0 || (options & SHELL_DOOUT))
4965 ? "-s " : "",
4966 p_sh, p_shcf, cmd);
4967 else
4968#endif
Bram Moolenaarcc448b32010-07-14 16:52:17 +02004969 vim_snprintf((char *)newcmd, cmdlen, "%s %s %s",
Bram Moolenaar0fde2902008-03-16 13:54:13 +00004970 p_sh, p_shcf, cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 x = mch_system((char *)newcmd, options);
Bram Moolenaar6b707b42012-02-21 21:22:44 +01004972 vim_free(newcmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974 }
4975 }
4976
4977 if (tmode == TMODE_RAW)
4978 settmode(TMODE_RAW); /* set to raw mode */
4979
4980 /* Print the return value, unless "vimrun" was used. */
4981 if (x != 0 && !(options & SHELL_SILENT) && !emsg_silent
4982#if defined(FEAT_GUI_W32)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02004983 && ((options & SHELL_DOOUT) || s_dont_use_vimrun || !p_stmp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004984#endif
4985 )
4986 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01004987 smsg((char_u *)_("shell returned %d"), x);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004988 msg_putchar('\n');
4989 }
4990#ifdef FEAT_TITLE
4991 resettitle();
4992#endif
4993
4994 signal(SIGINT, SIG_DFL);
4995#if defined(__GNUC__) && !defined(__MINGW32__)
4996 signal(SIGKILL, SIG_DFL);
4997#else
4998 signal(SIGBREAK, SIG_DFL);
4999#endif
5000 signal(SIGILL, SIG_DFL);
5001 signal(SIGFPE, SIG_DFL);
5002 signal(SIGSEGV, SIG_DFL);
5003 signal(SIGTERM, SIG_DFL);
5004 signal(SIGABRT, SIG_DFL);
5005
5006 return x;
5007}
5008
Bram Moolenaar509ce2a2016-03-11 22:52:15 +01005009#if defined(FEAT_JOB_CHANNEL) || defined(PROTO)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005010 static HANDLE
5011job_io_file_open(
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005012 char_u *fname,
5013 DWORD dwDesiredAccess,
5014 DWORD dwShareMode,
5015 LPSECURITY_ATTRIBUTES lpSecurityAttributes,
5016 DWORD dwCreationDisposition,
5017 DWORD dwFlagsAndAttributes)
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005018{
5019 HANDLE h;
5020# ifdef FEAT_MBYTE
5021 WCHAR *wn = NULL;
5022 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5023 {
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005024 wn = enc_to_utf16(fname, NULL);
5025 if (wn != NULL)
5026 {
5027 h = CreateFileW(wn, dwDesiredAccess, dwShareMode,
5028 lpSecurityAttributes, dwCreationDisposition,
5029 dwFlagsAndAttributes, NULL);
5030 vim_free(wn);
5031 }
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005032 }
5033 if (wn == NULL)
5034# endif
Bram Moolenaar972c3b82017-01-12 21:44:49 +01005035 h = CreateFile((LPCSTR)fname, dwDesiredAccess, dwShareMode,
5036 lpSecurityAttributes, dwCreationDisposition,
5037 dwFlagsAndAttributes, NULL);
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005038 return h;
5039}
5040
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005041/*
5042 * Turn the dictionary "env" into a NUL separated list that can be used as the
5043 * environment argument of vim_create_process().
5044 */
Bram Moolenaarba6febd2017-10-30 21:56:23 +01005045 void
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005046win32_build_env(dict_T *env, garray_T *gap, int is_terminal)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005047{
5048 hashitem_T *hi;
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005049 long_u todo = env != NULL ? env->dv_hashtab.ht_used : 0;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005050 LPVOID base = GetEnvironmentStringsW();
5051
5052 /* for last \0 */
5053 if (ga_grow(gap, 1) == FAIL)
5054 return;
5055
5056 if (base)
5057 {
5058 WCHAR *p = (WCHAR*) base;
5059
5060 /* for last \0 */
5061 if (ga_grow(gap, 1) == FAIL)
5062 return;
5063
5064 while (*p != 0 || *(p + 1) != 0)
5065 {
5066 if (ga_grow(gap, 1) == OK)
5067 *((WCHAR*)gap->ga_data + gap->ga_len++) = *p;
5068 p++;
5069 }
5070 FreeEnvironmentStrings(base);
5071 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5072 }
5073
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005074 if (env != NULL)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005075 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005076 for (hi = env->dv_hashtab.ht_array; todo > 0; ++hi)
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005077 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005078 if (!HASHITEM_EMPTY(hi))
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005079 {
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005080 typval_T *item = &dict_lookup(hi)->di_tv;
5081 WCHAR *wkey = enc_to_utf16((char_u *)hi->hi_key, NULL);
5082 WCHAR *wval = enc_to_utf16(get_tv_string(item), NULL);
5083 --todo;
5084 if (wkey != NULL && wval != NULL)
5085 {
5086 size_t n;
5087 size_t lkey = wcslen(wkey);
5088 size_t lval = wcslen(wval);
Bram Moolenaar60104f12017-08-14 23:25:04 +02005089
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005090 if (ga_grow(gap, (int)(lkey + lval + 2)) != OK)
5091 continue;
5092 for (n = 0; n < lkey; n++)
5093 *((WCHAR*)gap->ga_data + gap->ga_len++) = wkey[n];
5094 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'=';
5095 for (n = 0; n < lval; n++)
5096 *((WCHAR*)gap->ga_data + gap->ga_len++) = wval[n];
5097 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5098 }
5099 if (wkey != NULL) vim_free(wkey);
5100 if (wval != NULL) vim_free(wval);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005101 }
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005102 }
5103 }
5104
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005105# ifdef FEAT_CLIENTSERVER
5106 if (is_terminal)
5107 {
5108 char_u *servername = get_vim_var_str(VV_SEND_SERVER);
5109 size_t lval = STRLEN(servername);
5110 size_t n;
5111
5112 if (ga_grow(gap, (int)(14 + lval + 2)) == OK)
5113 {
5114 for (n = 0; n < 15; n++)
5115 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5116 (WCHAR)"VIM_SERVERNAME="[n];
5117 for (n = 0; n < lval; n++)
5118 *((WCHAR*)gap->ga_data + gap->ga_len++) =
5119 (WCHAR)servername[n];
5120 *((WCHAR*)gap->ga_data + gap->ga_len++) = L'\0';
5121 }
5122 }
5123# endif
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005124}
5125
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005126 void
Bram Moolenaar5a1feb82017-07-22 18:04:08 +02005127mch_job_start(char *cmd, job_T *job, jobopt_T *options)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005128{
5129 STARTUPINFO si;
5130 PROCESS_INFORMATION pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005131 HANDLE jo;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005132 SECURITY_ATTRIBUTES saAttr;
5133 channel_T *channel = NULL;
Bram Moolenaard8070362016-02-15 21:56:54 +01005134 HANDLE ifd[2];
5135 HANDLE ofd[2];
5136 HANDLE efd[2];
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005137 garray_T ga;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005138
5139 int use_null_for_in = options->jo_io[PART_IN] == JIO_NULL;
5140 int use_null_for_out = options->jo_io[PART_OUT] == JIO_NULL;
5141 int use_null_for_err = options->jo_io[PART_ERR] == JIO_NULL;
5142 int use_file_for_in = options->jo_io[PART_IN] == JIO_FILE;
5143 int use_file_for_out = options->jo_io[PART_OUT] == JIO_FILE;
5144 int use_file_for_err = options->jo_io[PART_ERR] == JIO_FILE;
5145 int use_out_for_err = options->jo_io[PART_ERR] == JIO_OUT;
5146
5147 if (use_out_for_err && use_null_for_out)
5148 use_null_for_err = TRUE;
Bram Moolenaard8070362016-02-15 21:56:54 +01005149
5150 ifd[0] = INVALID_HANDLE_VALUE;
5151 ifd[1] = INVALID_HANDLE_VALUE;
5152 ofd[0] = INVALID_HANDLE_VALUE;
5153 ofd[1] = INVALID_HANDLE_VALUE;
5154 efd[0] = INVALID_HANDLE_VALUE;
5155 efd[1] = INVALID_HANDLE_VALUE;
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005156 ga_init2(&ga, (int)sizeof(wchar_t), 500);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005157
Bram Moolenaar14207f42016-10-27 21:13:10 +02005158 jo = CreateJobObject(NULL, NULL);
5159 if (jo == NULL)
5160 {
5161 job->jv_status = JOB_FAILED;
5162 goto failed;
5163 }
5164
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005165 if (options->jo_env != NULL)
Bram Moolenaar52dbb5e2017-11-21 18:11:27 +01005166 win32_build_env(options->jo_env, &ga, FALSE);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005167
Bram Moolenaar76467df2016-02-12 19:30:26 +01005168 ZeroMemory(&pi, sizeof(pi));
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005169 ZeroMemory(&si, sizeof(si));
5170 si.cb = sizeof(si);
Bram Moolenaard8070362016-02-15 21:56:54 +01005171 si.dwFlags |= STARTF_USESHOWWINDOW;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005172 si.wShowWindow = SW_HIDE;
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005173
Bram Moolenaard8070362016-02-15 21:56:54 +01005174 saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
5175 saAttr.bInheritHandle = TRUE;
5176 saAttr.lpSecurityDescriptor = NULL;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005177
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005178 if (use_file_for_in)
5179 {
5180 char_u *fname = options->jo_io_name[PART_IN];
5181
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005182 ifd[0] = job_io_file_open(fname, GENERIC_READ,
5183 FILE_SHARE_READ | FILE_SHARE_WRITE,
5184 &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL);
5185 if (ifd[0] == INVALID_HANDLE_VALUE)
Bram Moolenaar94d01912016-03-08 13:48:51 +01005186 {
5187 EMSG2(_(e_notopen), fname);
5188 goto failed;
5189 }
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005190 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005191 else if (!use_null_for_in &&
5192 (!CreatePipe(&ifd[0], &ifd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005193 || !SetHandleInformation(ifd[1], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005194 goto failed;
5195
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005196 if (use_file_for_out)
5197 {
5198 char_u *fname = options->jo_io_name[PART_OUT];
5199
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005200 ofd[1] = job_io_file_open(fname, GENERIC_WRITE,
5201 FILE_SHARE_READ | FILE_SHARE_WRITE,
5202 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5203 if (ofd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005204 {
5205 EMSG2(_(e_notopen), fname);
5206 goto failed;
5207 }
5208 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005209 else if (!use_null_for_out &&
5210 (!CreatePipe(&ofd[0], &ofd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005211 || !SetHandleInformation(ofd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaarb69fccf2016-03-06 23:06:25 +01005212 goto failed;
5213
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005214 if (use_file_for_err)
5215 {
5216 char_u *fname = options->jo_io_name[PART_ERR];
5217
Bram Moolenaar7bffaa92016-03-10 21:46:03 +01005218 efd[1] = job_io_file_open(fname, GENERIC_WRITE,
5219 FILE_SHARE_READ | FILE_SHARE_WRITE,
5220 &saAttr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL);
5221 if (efd[1] == INVALID_HANDLE_VALUE)
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005222 {
5223 EMSG2(_(e_notopen), fname);
5224 goto failed;
5225 }
5226 }
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005227 else if (!use_out_for_err && !use_null_for_err &&
5228 (!CreatePipe(&efd[0], &efd[1], &saAttr, 0)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02005229 || !SetHandleInformation(efd[0], HANDLE_FLAG_INHERIT, 0)))
Bram Moolenaard8070362016-02-15 21:56:54 +01005230 goto failed;
Bram Moolenaar13d6fb12016-03-08 18:40:52 +01005231
Bram Moolenaard8070362016-02-15 21:56:54 +01005232 si.dwFlags |= STARTF_USESTDHANDLES;
5233 si.hStdInput = ifd[0];
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005234 si.hStdOutput = ofd[1];
5235 si.hStdError = use_out_for_err ? ofd[1] : efd[1];
5236
5237 if (!use_null_for_in || !use_null_for_out || !use_null_for_err)
5238 {
Bram Moolenaarde279892016-03-11 22:19:44 +01005239 if (options->jo_set & JO_CHANNEL)
5240 {
5241 channel = options->jo_channel;
5242 if (channel != NULL)
5243 ++channel->ch_refcount;
5244 }
5245 else
5246 channel = add_channel();
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005247 if (channel == NULL)
5248 goto failed;
5249 }
Bram Moolenaard8070362016-02-15 21:56:54 +01005250
5251 if (!vim_create_process(cmd, TRUE,
Bram Moolenaar14207f42016-10-27 21:13:10 +02005252 CREATE_SUSPENDED |
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005253 CREATE_DEFAULT_ERROR_MODE |
5254 CREATE_NEW_PROCESS_GROUP |
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005255 CREATE_UNICODE_ENVIRONMENT |
Bram Moolenaar76467df2016-02-12 19:30:26 +01005256 CREATE_NEW_CONSOLE,
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005257 &si, &pi,
5258 ga.ga_data,
5259 (char *)options->jo_cwd))
Bram Moolenaar76467df2016-02-12 19:30:26 +01005260 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005261 CloseHandle(jo);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005262 job->jv_status = JOB_FAILED;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005263 goto failed;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005264 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005265
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005266 ga_clear(&ga);
5267
Bram Moolenaar14207f42016-10-27 21:13:10 +02005268 if (!AssignProcessToJobObject(jo, pi.hProcess))
5269 {
5270 /* if failing, switch the way to terminate
5271 * process with TerminateProcess. */
5272 CloseHandle(jo);
5273 jo = NULL;
5274 }
5275 ResumeThread(pi.hThread);
Bram Moolenaar75578a32016-03-10 16:33:31 +01005276 CloseHandle(pi.hThread);
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005277 job->jv_proc_info = pi;
Bram Moolenaar14207f42016-10-27 21:13:10 +02005278 job->jv_job_object = jo;
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005279 job->jv_status = JOB_STARTED;
5280
Bram Moolenaar641ad6c2016-09-01 18:32:11 +02005281 CloseHandle(ifd[0]);
5282 CloseHandle(ofd[1]);
5283 if (!use_out_for_err && !use_null_for_err)
Bram Moolenaarc25558b2016-03-03 21:02:23 +01005284 CloseHandle(efd[1]);
Bram Moolenaard8070362016-02-15 21:56:54 +01005285
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005286 job->jv_channel = channel;
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005287 if (channel != NULL)
5288 {
5289 channel_set_pipes(channel,
5290 use_file_for_in || use_null_for_in
5291 ? INVALID_FD : (sock_T)ifd[1],
5292 use_file_for_out || use_null_for_out
5293 ? INVALID_FD : (sock_T)ofd[0],
5294 use_out_for_err || use_file_for_err || use_null_for_err
5295 ? INVALID_FD : (sock_T)efd[0]);
5296 channel_set_job(channel, job, options);
Bram Moolenaard5d3d302016-03-09 20:54:51 +01005297 }
Bram Moolenaar7b3ca762016-02-14 19:13:43 +01005298 return;
5299
5300failed:
Bram Moolenaard8070362016-02-15 21:56:54 +01005301 CloseHandle(ifd[0]);
5302 CloseHandle(ofd[0]);
5303 CloseHandle(efd[0]);
5304 CloseHandle(ifd[1]);
5305 CloseHandle(ofd[1]);
5306 CloseHandle(efd[1]);
Bram Moolenaarde279892016-03-11 22:19:44 +01005307 channel_unref(channel);
Bram Moolenaar05aafed2017-08-11 19:12:11 +02005308 ga_clear(&ga);
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005309}
5310
5311 char *
5312mch_job_status(job_T *job)
5313{
5314 DWORD dwExitCode = 0;
5315
Bram Moolenaar76467df2016-02-12 19:30:26 +01005316 if (!GetExitCodeProcess(job->jv_proc_info.hProcess, &dwExitCode)
5317 || dwExitCode != STILL_ACTIVE)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005318 {
Bram Moolenaareab089d2016-02-21 19:32:02 +01005319 job->jv_exitval = (int)dwExitCode;
Bram Moolenaar7df915d2016-11-17 17:25:32 +01005320 if (job->jv_status < JOB_ENDED)
Bram Moolenaar97792de2016-10-15 18:36:49 +02005321 {
5322 ch_log(job->jv_channel, "Job ended");
5323 job->jv_status = JOB_ENDED;
5324 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005325 return "dead";
5326 }
5327 return "run";
5328}
5329
Bram Moolenaar97792de2016-10-15 18:36:49 +02005330 job_T *
5331mch_detect_ended_job(job_T *job_list)
5332{
5333 HANDLE jobHandles[MAXIMUM_WAIT_OBJECTS];
5334 job_T *jobArray[MAXIMUM_WAIT_OBJECTS];
5335 job_T *job = job_list;
5336
5337 while (job != NULL)
5338 {
5339 DWORD n;
5340 DWORD result;
5341
5342 for (n = 0; n < MAXIMUM_WAIT_OBJECTS
5343 && job != NULL; job = job->jv_next)
5344 {
5345 if (job->jv_status == JOB_STARTED)
5346 {
5347 jobHandles[n] = job->jv_proc_info.hProcess;
5348 jobArray[n] = job;
5349 ++n;
5350 }
5351 }
5352 if (n == 0)
5353 continue;
5354 result = WaitForMultipleObjects(n, jobHandles, FALSE, 0);
5355 if (result >= WAIT_OBJECT_0 && result < WAIT_OBJECT_0 + n)
5356 {
5357 job_T *wait_job = jobArray[result - WAIT_OBJECT_0];
5358
5359 if (STRCMP(mch_job_status(wait_job), "dead") == 0)
5360 return wait_job;
5361 }
5362 }
5363 return NULL;
5364}
5365
Bram Moolenaarfb630902016-10-29 14:55:00 +02005366 static BOOL
5367terminate_all(HANDLE process, int code)
5368{
5369 PROCESSENTRY32 pe;
5370 HANDLE h = INVALID_HANDLE_VALUE;
5371 DWORD pid = GetProcessId(process);
5372
5373 if (pid != 0)
5374 {
5375 h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
5376 if (h != INVALID_HANDLE_VALUE)
5377 {
5378 pe.dwSize = sizeof(PROCESSENTRY32);
5379 if (!Process32First(h, &pe))
5380 goto theend;
5381
5382 do
5383 {
5384 if (pe.th32ParentProcessID == pid)
5385 {
5386 HANDLE ph = OpenProcess(
5387 PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
5388 if (ph != NULL)
5389 {
5390 terminate_all(ph, code);
5391 CloseHandle(ph);
5392 }
5393 }
5394 } while (Process32Next(h, &pe));
5395
5396 CloseHandle(h);
5397 }
5398 }
5399
5400theend:
5401 return TerminateProcess(process, code);
5402}
5403
5404/*
5405 * Send a (deadly) signal to "job".
5406 * Return FAIL if it didn't work.
5407 */
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005408 int
Bram Moolenaar2d33e902017-08-11 16:31:54 +02005409mch_signal_job(job_T *job, char_u *how)
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005410{
Bram Moolenaar923d9262016-02-25 20:56:01 +01005411 int ret;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005412
Bram Moolenaar923d9262016-02-25 20:56:01 +01005413 if (STRCMP(how, "term") == 0 || STRCMP(how, "kill") == 0 || *how == NUL)
Bram Moolenaar76467df2016-02-12 19:30:26 +01005414 {
Bram Moolenaarfb630902016-10-29 14:55:00 +02005415 /* deadly signal */
Bram Moolenaar14207f42016-10-27 21:13:10 +02005416 if (job->jv_job_object != NULL)
5417 return TerminateJobObject(job->jv_job_object, 0) ? OK : FAIL;
Bram Moolenaarfb630902016-10-29 14:55:00 +02005418 return terminate_all(job->jv_proc_info.hProcess, 0) ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005419 }
5420
5421 if (!AttachConsole(job->jv_proc_info.dwProcessId))
5422 return FAIL;
5423 ret = GenerateConsoleCtrlEvent(
Bram Moolenaar923d9262016-02-25 20:56:01 +01005424 STRCMP(how, "int") == 0 ? CTRL_C_EVENT : CTRL_BREAK_EVENT,
5425 job->jv_proc_info.dwProcessId)
5426 ? OK : FAIL;
Bram Moolenaar76467df2016-02-12 19:30:26 +01005427 FreeConsole();
5428 return ret;
5429}
5430
5431/*
5432 * Clear the data related to "job".
5433 */
5434 void
5435mch_clear_job(job_T *job)
5436{
5437 if (job->jv_status != JOB_FAILED)
5438 {
Bram Moolenaar14207f42016-10-27 21:13:10 +02005439 if (job->jv_job_object != NULL)
5440 CloseHandle(job->jv_job_object);
Bram Moolenaar76467df2016-02-12 19:30:26 +01005441 CloseHandle(job->jv_proc_info.hProcess);
5442 }
Bram Moolenaar942d6b22016-02-07 19:57:16 +01005443}
5444#endif
5445
Bram Moolenaar071d4272004-06-13 20:20:40 +00005446
5447#ifndef FEAT_GUI_W32
5448
5449/*
5450 * Start termcap mode
5451 */
5452 static void
5453termcap_mode_start(void)
5454{
5455 DWORD cmodein;
5456
5457 if (g_fTermcapMode)
5458 return;
5459
5460 SaveConsoleBuffer(&g_cbNonTermcap);
5461
5462 if (g_cbTermcap.IsValid)
5463 {
5464 /*
5465 * We've been in termcap mode before. Restore certain screen
5466 * characteristics, including the buffer size and the window
5467 * size. Since we will be redrawing the screen, we don't need
5468 * to restore the actual contents of the buffer.
5469 */
5470 RestoreConsoleBuffer(&g_cbTermcap, FALSE);
5471 SetConsoleWindowInfo(g_hConOut, TRUE, &g_cbTermcap.Info.srWindow);
5472 Rows = g_cbTermcap.Info.dwSize.Y;
5473 Columns = g_cbTermcap.Info.dwSize.X;
5474 }
5475 else
5476 {
5477 /*
5478 * This is our first time entering termcap mode. Clear the console
5479 * screen buffer, and resize the buffer to match the current window
5480 * size. We will use this as the size of our editing environment.
5481 */
5482 ClearConsoleBuffer(g_attrCurrent);
5483 ResizeConBufAndWindow(g_hConOut, Columns, Rows);
5484 }
5485
5486#ifdef FEAT_TITLE
5487 resettitle();
5488#endif
5489
5490 GetConsoleMode(g_hConIn, &cmodein);
5491#ifdef FEAT_MOUSE
5492 if (g_fMouseActive)
5493 cmodein |= ENABLE_MOUSE_INPUT;
5494 else
5495 cmodein &= ~ENABLE_MOUSE_INPUT;
5496#endif
5497 cmodein |= ENABLE_WINDOW_INPUT;
5498 SetConsoleMode(g_hConIn, cmodein);
5499
5500 redraw_later_clear();
5501 g_fTermcapMode = TRUE;
5502}
5503
5504
5505/*
5506 * End termcap mode
5507 */
5508 static void
5509termcap_mode_end(void)
5510{
5511 DWORD cmodein;
5512 ConsoleBuffer *cb;
5513 COORD coord;
5514 DWORD dwDummy;
5515
5516 if (!g_fTermcapMode)
5517 return;
5518
5519 SaveConsoleBuffer(&g_cbTermcap);
5520
5521 GetConsoleMode(g_hConIn, &cmodein);
5522 cmodein &= ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT);
5523 SetConsoleMode(g_hConIn, cmodein);
5524
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005525#ifdef FEAT_RESTORE_ORIG_SCREEN
5526 cb = exiting ? &g_cbOrig : &g_cbNonTermcap;
5527#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00005528 cb = &g_cbNonTermcap;
Bram Moolenaar4c0aac52015-10-30 16:46:55 +01005529#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005530 RestoreConsoleBuffer(cb, p_rs);
5531 SetConsoleCursorInfo(g_hConOut, &g_cci);
5532
5533 if (p_rs || exiting)
5534 {
5535 /*
5536 * Clear anything that happens to be on the current line.
5537 */
5538 coord.X = 0;
5539 coord.Y = (SHORT) (p_rs ? cb->Info.dwCursorPosition.Y : (Rows - 1));
5540 FillConsoleOutputCharacter(g_hConOut, ' ',
5541 cb->Info.dwSize.X, coord, &dwDummy);
5542 /*
5543 * The following is just for aesthetics. If we are exiting without
5544 * restoring the screen, then we want to have a prompt string
5545 * appear at the bottom line. However, the command interpreter
5546 * seems to always advance the cursor one line before displaying
5547 * the prompt string, which causes the screen to scroll. To
5548 * counter this, move the cursor up one line before exiting.
5549 */
5550 if (exiting && !p_rs)
5551 coord.Y--;
5552 /*
5553 * Position the cursor at the leftmost column of the desired row.
5554 */
5555 SetConsoleCursorPosition(g_hConOut, coord);
5556 }
5557
5558 g_fTermcapMode = FALSE;
5559}
5560#endif /* FEAT_GUI_W32 */
5561
5562
5563#ifdef FEAT_GUI_W32
5564 void
5565mch_write(
Bram Moolenaar1266d672017-02-01 13:43:36 +01005566 char_u *s UNUSED,
5567 int len UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005568{
5569 /* never used */
5570}
5571
5572#else
5573
5574/*
5575 * clear `n' chars, starting from `coord'
5576 */
5577 static void
5578clear_chars(
5579 COORD coord,
5580 DWORD n)
5581{
5582 DWORD dwDummy;
5583
5584 FillConsoleOutputCharacter(g_hConOut, ' ', n, coord, &dwDummy);
5585 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, n, coord, &dwDummy);
5586}
5587
5588
5589/*
5590 * Clear the screen
5591 */
5592 static void
5593clear_screen(void)
5594{
5595 g_coord.X = g_coord.Y = 0;
5596 clear_chars(g_coord, Rows * Columns);
5597}
5598
5599
5600/*
5601 * Clear to end of display
5602 */
5603 static void
5604clear_to_end_of_display(void)
5605{
5606 clear_chars(g_coord, (Rows - g_coord.Y - 1)
5607 * Columns + (Columns - g_coord.X));
5608}
5609
5610
5611/*
5612 * Clear to end of line
5613 */
5614 static void
5615clear_to_end_of_line(void)
5616{
5617 clear_chars(g_coord, Columns - g_coord.X);
5618}
5619
5620
5621/*
5622 * Scroll the scroll region up by `cLines' lines
5623 */
5624 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005625scroll(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005626{
5627 COORD oldcoord = g_coord;
5628
5629 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Top + 1);
5630 delete_lines(cLines);
5631
5632 g_coord = oldcoord;
5633}
5634
5635
5636/*
5637 * Set the scroll region
5638 */
5639 static void
5640set_scroll_region(
5641 unsigned left,
5642 unsigned top,
5643 unsigned right,
5644 unsigned bottom)
5645{
5646 if (left >= right
5647 || top >= bottom
5648 || right > (unsigned) Columns - 1
5649 || bottom > (unsigned) Rows - 1)
5650 return;
5651
5652 g_srScrollRegion.Left = left;
5653 g_srScrollRegion.Top = top;
5654 g_srScrollRegion.Right = right;
5655 g_srScrollRegion.Bottom = bottom;
5656}
5657
5658
5659/*
5660 * Insert `cLines' lines at the current cursor position
5661 */
5662 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005663insert_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005664{
5665 SMALL_RECT source;
5666 COORD dest;
5667 CHAR_INFO fill;
5668
5669 dest.X = 0;
5670 dest.Y = g_coord.Y + cLines;
5671
5672 source.Left = 0;
5673 source.Top = g_coord.Y;
5674 source.Right = g_srScrollRegion.Right;
5675 source.Bottom = g_srScrollRegion.Bottom - cLines;
5676
5677 fill.Char.AsciiChar = ' ';
5678 fill.Attributes = g_attrCurrent;
5679
5680 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5681
5682 /* Here we have to deal with a win32 console flake: If the scroll
5683 * region looks like abc and we scroll c to a and fill with d we get
5684 * cbd... if we scroll block c one line at a time to a, we get cdd...
5685 * vim expects cdd consistently... So we have to deal with that
5686 * here... (this also occurs scrolling the same way in the other
5687 * direction). */
5688
5689 if (source.Bottom < dest.Y)
5690 {
5691 COORD coord;
5692
5693 coord.X = 0;
5694 coord.Y = source.Bottom;
5695 clear_chars(coord, Columns * (dest.Y - source.Bottom));
5696 }
5697}
5698
5699
5700/*
5701 * Delete `cLines' lines at the current cursor position
5702 */
5703 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005704delete_lines(unsigned cLines)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005705{
5706 SMALL_RECT source;
5707 COORD dest;
5708 CHAR_INFO fill;
5709 int nb;
5710
5711 dest.X = 0;
5712 dest.Y = g_coord.Y;
5713
5714 source.Left = 0;
5715 source.Top = g_coord.Y + cLines;
5716 source.Right = g_srScrollRegion.Right;
5717 source.Bottom = g_srScrollRegion.Bottom;
5718
5719 fill.Char.AsciiChar = ' ';
5720 fill.Attributes = g_attrCurrent;
5721
5722 ScrollConsoleScreenBuffer(g_hConOut, &source, NULL, dest, &fill);
5723
5724 /* Here we have to deal with a win32 console flake: If the scroll
5725 * region looks like abc and we scroll c to a and fill with d we get
5726 * cbd... if we scroll block c one line at a time to a, we get cdd...
5727 * vim expects cdd consistently... So we have to deal with that
5728 * here... (this also occurs scrolling the same way in the other
5729 * direction). */
5730
5731 nb = dest.Y + (source.Bottom - source.Top) + 1;
5732
5733 if (nb < source.Top)
5734 {
5735 COORD coord;
5736
5737 coord.X = 0;
5738 coord.Y = nb;
5739 clear_chars(coord, Columns * (source.Top - nb));
5740 }
5741}
5742
5743
5744/*
5745 * Set the cursor position
5746 */
5747 static void
5748gotoxy(
5749 unsigned x,
5750 unsigned y)
5751{
5752 if (x < 1 || x > (unsigned)Columns || y < 1 || y > (unsigned)Rows)
5753 return;
5754
5755 /* external cursor coords are 1-based; internal are 0-based */
5756 g_coord.X = x - 1;
5757 g_coord.Y = y - 1;
5758 SetConsoleCursorPosition(g_hConOut, g_coord);
5759}
5760
5761
5762/*
5763 * Set the current text attribute = (foreground | background)
5764 * See ../doc/os_win32.txt for the numbers.
5765 */
5766 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005767textattr(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005768{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005769 g_attrCurrent = wAttr & 0xff;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005770
5771 SetConsoleTextAttribute(g_hConOut, wAttr);
5772}
5773
5774
5775 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005776textcolor(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005777{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005778 g_attrCurrent = (g_attrCurrent & 0xf0) + (wAttr & 0x0f);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005779
5780 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5781}
5782
5783
5784 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005785textbackground(WORD wAttr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005786{
Bram Moolenaar6383b922015-03-24 17:12:19 +01005787 g_attrCurrent = (g_attrCurrent & 0x0f) + ((wAttr & 0x0f) << 4);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005788
5789 SetConsoleTextAttribute(g_hConOut, g_attrCurrent);
5790}
5791
5792
5793/*
5794 * restore the default text attribute (whatever we started with)
5795 */
5796 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005797normvideo(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798{
5799 textattr(g_attrDefault);
5800}
5801
5802
5803static WORD g_attrPreStandout = 0;
5804
5805/*
5806 * Make the text standout, by brightening it
5807 */
5808 static void
5809standout(void)
5810{
5811 g_attrPreStandout = g_attrCurrent;
5812 textattr((WORD) (g_attrCurrent|FOREGROUND_INTENSITY|BACKGROUND_INTENSITY));
5813}
5814
5815
5816/*
5817 * Turn off standout mode
5818 */
5819 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005820standend(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821{
5822 if (g_attrPreStandout)
5823 {
5824 textattr(g_attrPreStandout);
5825 g_attrPreStandout = 0;
5826 }
5827}
5828
5829
5830/*
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00005831 * Set normal fg/bg color, based on T_ME. Called when t_me has been set.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005832 */
5833 void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005834mch_set_normal_colors(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005835{
5836 char_u *p;
5837 int n;
5838
5839 cterm_normal_fg_color = (g_attrDefault & 0xf) + 1;
5840 cterm_normal_bg_color = ((g_attrDefault >> 4) & 0xf) + 1;
5841 if (T_ME[0] == ESC && T_ME[1] == '|')
5842 {
5843 p = T_ME + 2;
5844 n = getdigits(&p);
5845 if (*p == 'm' && n > 0)
5846 {
5847 cterm_normal_fg_color = (n & 0xf) + 1;
5848 cterm_normal_bg_color = ((n >> 4) & 0xf) + 1;
5849 }
5850 }
5851}
5852
5853
5854/*
5855 * visual bell: flash the screen
5856 */
5857 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005858visual_bell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005859{
5860 COORD coordOrigin = {0, 0};
5861 WORD attrFlash = ~g_attrCurrent & 0xff;
5862
5863 DWORD dwDummy;
5864 LPWORD oldattrs = (LPWORD)alloc(Rows * Columns * sizeof(WORD));
5865
5866 if (oldattrs == NULL)
5867 return;
5868 ReadConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5869 coordOrigin, &dwDummy);
5870 FillConsoleOutputAttribute(g_hConOut, attrFlash, Rows * Columns,
5871 coordOrigin, &dwDummy);
5872
5873 Sleep(15); /* wait for 15 msec */
5874 WriteConsoleOutputAttribute(g_hConOut, oldattrs, Rows * Columns,
5875 coordOrigin, &dwDummy);
5876 vim_free(oldattrs);
5877}
5878
5879
5880/*
5881 * Make the cursor visible or invisible
5882 */
5883 static void
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00005884cursor_visible(BOOL fVisible)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005885{
5886 s_cursor_visible = fVisible;
5887#ifdef MCH_CURSOR_SHAPE
5888 mch_update_cursor();
5889#endif
5890}
5891
5892
5893/*
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02005894 * Write "cbToWrite" bytes in `pchBuf' to the screen.
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005895 * Returns the number of bytes actually written (at least one).
Bram Moolenaar071d4272004-06-13 20:20:40 +00005896 */
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005897 static DWORD
Bram Moolenaar071d4272004-06-13 20:20:40 +00005898write_chars(
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005899 char_u *pchBuf,
5900 DWORD cbToWrite)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005901{
5902 COORD coord = g_coord;
5903 DWORD written;
5904
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005905#ifdef FEAT_MBYTE
5906 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
5907 {
5908 static WCHAR *unicodebuf = NULL;
5909 static int unibuflen = 0;
5910 int length;
5911 DWORD n, cchwritten, cells;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005912
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005913 length = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite, 0, 0);
5914 if (unicodebuf == NULL || length > unibuflen)
5915 {
5916 vim_free(unicodebuf);
5917 unicodebuf = (WCHAR *)lalloc(length * sizeof(WCHAR), FALSE);
5918 unibuflen = length;
5919 }
5920 MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pchBuf, cbToWrite,
5921 unicodebuf, unibuflen);
5922
5923 cells = mb_string2cells(pchBuf, cbToWrite);
5924 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cells,
5925 coord, &written);
5926 /* When writing fails or didn't write a single character, pretend one
5927 * character was written, otherwise we get stuck. */
5928 if (WriteConsoleOutputCharacterW(g_hConOut, unicodebuf, length,
5929 coord, &cchwritten) == 0
5930 || cchwritten == 0)
5931 cchwritten = 1;
5932
5933 if (cchwritten == length)
5934 {
5935 written = cbToWrite;
5936 g_coord.X += (SHORT)cells;
5937 }
5938 else
5939 {
5940 char_u *p = pchBuf;
5941 for (n = 0; n < cchwritten; n++)
Bram Moolenaar91acfff2017-03-12 19:22:36 +01005942 MB_CPTR_ADV(p);
Bram Moolenaarac360bf2015-09-01 20:31:20 +02005943 written = p - pchBuf;
5944 g_coord.X += (SHORT)mb_string2cells(pchBuf, written);
5945 }
5946 }
5947 else
5948#endif
5949 {
5950 FillConsoleOutputAttribute(g_hConOut, g_attrCurrent, cbToWrite,
5951 coord, &written);
5952 /* When writing fails or didn't write a single character, pretend one
5953 * character was written, otherwise we get stuck. */
5954 if (WriteConsoleOutputCharacter(g_hConOut, (LPCSTR)pchBuf, cbToWrite,
5955 coord, &written) == 0
5956 || written == 0)
5957 written = 1;
5958
5959 g_coord.X += (SHORT) written;
5960 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005961
5962 while (g_coord.X > g_srScrollRegion.Right)
5963 {
5964 g_coord.X -= (SHORT) Columns;
5965 if (g_coord.Y < g_srScrollRegion.Bottom)
5966 g_coord.Y++;
5967 }
5968
5969 gotoxy(g_coord.X + 1, g_coord.Y + 1);
5970
5971 return written;
5972}
5973
5974
5975/*
5976 * mch_write(): write the output buffer to the screen, translating ESC
5977 * sequences into calls to console output routines.
5978 */
5979 void
5980mch_write(
5981 char_u *s,
5982 int len)
5983{
5984 s[len] = NUL;
5985
5986 if (!term_console)
5987 {
5988 write(1, s, (unsigned)len);
5989 return;
5990 }
5991
5992 /* translate ESC | sequences into faked bios calls */
5993 while (len--)
5994 {
5995 /* optimization: use one single write_chars for runs of text,
5996 * rather than once per character It ain't curses, but it helps. */
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01005997 DWORD prefix = (DWORD)strcspn((char *)s, "\n\r\b\a\033");
Bram Moolenaar071d4272004-06-13 20:20:40 +00005998
5999 if (p_wd)
6000 {
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006001 WaitForChar(p_wd, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002 if (prefix != 0)
6003 prefix = 1;
6004 }
6005
6006 if (prefix != 0)
6007 {
6008 DWORD nWritten;
6009
6010 nWritten = write_chars(s, prefix);
6011#ifdef MCH_WRITE_DUMP
6012 if (fdDump)
6013 {
6014 fputc('>', fdDump);
6015 fwrite(s, sizeof(char_u), nWritten, fdDump);
6016 fputs("<\n", fdDump);
6017 }
6018#endif
6019 len -= (nWritten - 1);
6020 s += nWritten;
6021 }
6022 else if (s[0] == '\n')
6023 {
6024 /* \n, newline: go to the beginning of the next line or scroll */
6025 if (g_coord.Y == g_srScrollRegion.Bottom)
6026 {
6027 scroll(1);
6028 gotoxy(g_srScrollRegion.Left + 1, g_srScrollRegion.Bottom + 1);
6029 }
6030 else
6031 {
6032 gotoxy(g_srScrollRegion.Left + 1, g_coord.Y + 2);
6033 }
6034#ifdef MCH_WRITE_DUMP
6035 if (fdDump)
6036 fputs("\\n\n", fdDump);
6037#endif
6038 s++;
6039 }
6040 else if (s[0] == '\r')
6041 {
6042 /* \r, carriage return: go to beginning of line */
6043 gotoxy(g_srScrollRegion.Left+1, g_coord.Y + 1);
6044#ifdef MCH_WRITE_DUMP
6045 if (fdDump)
6046 fputs("\\r\n", fdDump);
6047#endif
6048 s++;
6049 }
6050 else if (s[0] == '\b')
6051 {
6052 /* \b, backspace: move cursor one position left */
6053 if (g_coord.X > g_srScrollRegion.Left)
6054 g_coord.X--;
6055 else if (g_coord.Y > g_srScrollRegion.Top)
6056 {
6057 g_coord.X = g_srScrollRegion.Right;
6058 g_coord.Y--;
6059 }
6060 gotoxy(g_coord.X + 1, g_coord.Y + 1);
6061#ifdef MCH_WRITE_DUMP
6062 if (fdDump)
6063 fputs("\\b\n", fdDump);
6064#endif
6065 s++;
6066 }
6067 else if (s[0] == '\a')
6068 {
6069 /* \a, bell */
6070 MessageBeep(0xFFFFFFFF);
6071#ifdef MCH_WRITE_DUMP
6072 if (fdDump)
6073 fputs("\\a\n", fdDump);
6074#endif
6075 s++;
6076 }
6077 else if (s[0] == ESC && len >= 3-1 && s[1] == '|')
6078 {
6079#ifdef MCH_WRITE_DUMP
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006080 char_u *old_s = s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006081#endif
Bram Moolenaarc0197e22004-09-13 20:26:32 +00006082 char_u *p;
6083 int arg1 = 0, arg2 = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006084
6085 switch (s[2])
6086 {
6087 /* one or two numeric arguments, separated by ';' */
6088
6089 case '0': case '1': case '2': case '3': case '4':
6090 case '5': case '6': case '7': case '8': case '9':
6091 p = s + 2;
6092 arg1 = getdigits(&p); /* no check for length! */
6093 if (p > s + len)
6094 break;
6095
6096 if (*p == ';')
6097 {
6098 ++p;
6099 arg2 = getdigits(&p); /* no check for length! */
6100 if (p > s + len)
6101 break;
6102
6103 if (*p == 'H')
6104 gotoxy(arg2, arg1);
6105 else if (*p == 'r')
6106 set_scroll_region(0, arg1 - 1, Columns - 1, arg2 - 1);
6107 }
6108 else if (*p == 'A')
6109 {
6110 /* move cursor up arg1 lines in same column */
6111 gotoxy(g_coord.X + 1,
6112 max(g_srScrollRegion.Top, g_coord.Y - arg1) + 1);
6113 }
6114 else if (*p == 'C')
6115 {
6116 /* move cursor right arg1 columns in same line */
6117 gotoxy(min(g_srScrollRegion.Right, g_coord.X + arg1) + 1,
6118 g_coord.Y + 1);
6119 }
6120 else if (*p == 'H')
6121 {
6122 gotoxy(1, arg1);
6123 }
6124 else if (*p == 'L')
6125 {
6126 insert_lines(arg1);
6127 }
6128 else if (*p == 'm')
6129 {
6130 if (arg1 == 0)
6131 normvideo();
6132 else
6133 textattr((WORD) arg1);
6134 }
6135 else if (*p == 'f')
6136 {
6137 textcolor((WORD) arg1);
6138 }
6139 else if (*p == 'b')
6140 {
6141 textbackground((WORD) arg1);
6142 }
6143 else if (*p == 'M')
6144 {
6145 delete_lines(arg1);
6146 }
6147
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006148 len -= (int)(p - s);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006149 s = p + 1;
6150 break;
6151
6152
6153 /* Three-character escape sequences */
6154
6155 case 'A':
6156 /* move cursor up one line in same column */
6157 gotoxy(g_coord.X + 1,
6158 max(g_srScrollRegion.Top, g_coord.Y - 1) + 1);
6159 goto got3;
6160
6161 case 'B':
6162 visual_bell();
6163 goto got3;
6164
6165 case 'C':
6166 /* move cursor right one column in same line */
6167 gotoxy(min(g_srScrollRegion.Right, g_coord.X + 1) + 1,
6168 g_coord.Y + 1);
6169 goto got3;
6170
6171 case 'E':
6172 termcap_mode_end();
6173 goto got3;
6174
6175 case 'F':
6176 standout();
6177 goto got3;
6178
6179 case 'f':
6180 standend();
6181 goto got3;
6182
6183 case 'H':
6184 gotoxy(1, 1);
6185 goto got3;
6186
6187 case 'j':
6188 clear_to_end_of_display();
6189 goto got3;
6190
6191 case 'J':
6192 clear_screen();
6193 goto got3;
6194
6195 case 'K':
6196 clear_to_end_of_line();
6197 goto got3;
6198
6199 case 'L':
6200 insert_lines(1);
6201 goto got3;
6202
6203 case 'M':
6204 delete_lines(1);
6205 goto got3;
6206
6207 case 'S':
6208 termcap_mode_start();
6209 goto got3;
6210
6211 case 'V':
6212 cursor_visible(TRUE);
6213 goto got3;
6214
6215 case 'v':
6216 cursor_visible(FALSE);
6217 goto got3;
6218
6219 got3:
6220 s += 3;
6221 len -= 2;
6222 }
6223
6224#ifdef MCH_WRITE_DUMP
6225 if (fdDump)
6226 {
6227 fputs("ESC | ", fdDump);
6228 fwrite(old_s + 2, sizeof(char_u), s - old_s - 2, fdDump);
6229 fputc('\n', fdDump);
6230 }
6231#endif
6232 }
6233 else
6234 {
6235 /* Write a single character */
6236 DWORD nWritten;
6237
6238 nWritten = write_chars(s, 1);
6239#ifdef MCH_WRITE_DUMP
6240 if (fdDump)
6241 {
6242 fputc('>', fdDump);
6243 fwrite(s, sizeof(char_u), nWritten, fdDump);
6244 fputs("<\n", fdDump);
6245 }
6246#endif
6247
6248 len -= (nWritten - 1);
6249 s += nWritten;
6250 }
6251 }
6252
6253#ifdef MCH_WRITE_DUMP
6254 if (fdDump)
6255 fflush(fdDump);
6256#endif
6257}
6258
6259#endif /* FEAT_GUI_W32 */
6260
6261
6262/*
Bram Moolenaar0e0b3dd2016-03-17 17:58:56 +01006263 * Delay for "msec" milliseconds.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264 */
6265 void
6266mch_delay(
6267 long msec,
Bram Moolenaar1266d672017-02-01 13:43:36 +01006268 int ignoreinput UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006269{
6270#ifdef FEAT_GUI_W32
6271 Sleep((int)msec); /* never wait for input */
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006272#else /* Console */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273 if (ignoreinput)
Bram Moolenaar325b7a22004-07-05 15:58:32 +00006274# ifdef FEAT_MZSCHEME
6275 if (mzthreads_allowed() && p_mzq > 0 && msec > p_mzq)
6276 {
6277 int towait = p_mzq;
6278
6279 /* if msec is large enough, wait by portions in p_mzq */
6280 while (msec > 0)
6281 {
6282 mzvim_check_threads();
6283 if (msec < towait)
6284 towait = msec;
6285 Sleep(towait);
6286 msec -= towait;
6287 }
6288 }
6289 else
6290# endif
6291 Sleep((int)msec);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006292 else
Bram Moolenaare9c21ae2017-08-03 20:44:48 +02006293 WaitForChar(msec, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294#endif
6295}
6296
6297
6298/*
Bram Moolenaar203258c2016-01-17 22:15:16 +01006299 * This version of remove is not scared by a readonly (backup) file.
6300 * This can also remove a symbolic link like Unix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 * Return 0 for success, -1 for failure.
6302 */
6303 int
6304mch_remove(char_u *name)
6305{
6306#ifdef FEAT_MBYTE
6307 WCHAR *wn = NULL;
6308 int n;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006309#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006310
Bram Moolenaar203258c2016-01-17 22:15:16 +01006311 /*
6312 * On Windows, deleting a directory's symbolic link is done by
6313 * RemoveDirectory(): mch_rmdir. It seems unnatural, but it is fact.
6314 */
6315 if (mch_isdir(name) && mch_is_symbolic_link(name))
6316 return mch_rmdir(name);
6317
Bram Moolenaar12b559e2013-06-12 22:41:37 +02006318 win32_setattrs(name, FILE_ATTRIBUTE_NORMAL);
6319
6320#ifdef FEAT_MBYTE
Bram Moolenaar071d4272004-06-13 20:20:40 +00006321 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6322 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006323 wn = enc_to_utf16(name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006324 if (wn != NULL)
6325 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006326 n = DeleteFileW(wn) ? 0 : -1;
6327 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006328 return n;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006329 }
6330 }
6331#endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006332 return DeleteFile((LPCSTR)name) ? 0 : -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006333}
6334
6335
6336/*
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006337 * Check for an "interrupt signal": CTRL-break or CTRL-C.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006338 */
6339 void
Bram Moolenaarb9c31e72016-09-29 15:18:57 +02006340mch_breakcheck(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006341{
6342#ifndef FEAT_GUI_W32 /* never used */
6343 if (g_fCtrlCPressed || g_fCBrkPressed)
6344 {
Bram Moolenaar9698ad72017-08-12 14:52:15 +02006345 ctrl_break_was_pressed = g_fCBrkPressed;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006346 g_fCtrlCPressed = g_fCBrkPressed = FALSE;
6347 got_int = TRUE;
6348 }
6349#endif
6350}
6351
Bram Moolenaaree273972016-01-02 21:11:51 +01006352/* physical RAM to leave for the OS */
6353#define WINNT_RESERVE_BYTES (256*1024*1024)
Bram Moolenaaree273972016-01-02 21:11:51 +01006354
6355/*
6356 * How much main memory in KiB that can be used by VIM.
6357 */
Bram Moolenaaree273972016-01-02 21:11:51 +01006358 long_u
Bram Moolenaar1266d672017-02-01 13:43:36 +01006359mch_total_mem(int special UNUSED)
Bram Moolenaaree273972016-01-02 21:11:51 +01006360{
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006361 MEMORYSTATUSEX ms;
6362
Bram Moolenaaree273972016-01-02 21:11:51 +01006363 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006364 /* Need to use GlobalMemoryStatusEx() when there is more memory than
6365 * what fits in 32 bits. But it's not always available. */
6366 ms.dwLength = sizeof(MEMORYSTATUSEX);
6367 GlobalMemoryStatusEx(&ms);
6368 if (ms.ullAvailVirtual < ms.ullTotalPhys)
Bram Moolenaaree273972016-01-02 21:11:51 +01006369 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006370 /* Process address space fits in physical RAM, use all of it. */
6371 return (long_u)(ms.ullAvailVirtual / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006372 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006373 if (ms.ullTotalPhys <= WINNT_RESERVE_BYTES)
Bram Moolenaaree273972016-01-02 21:11:51 +01006374 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006375 /* Catch old NT box or perverse hardware setup. */
6376 return (long_u)((ms.ullTotalPhys / 2) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006377 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006378 /* Use physical RAM less reserve for OS + data. */
6379 return (long_u)((ms.ullTotalPhys - WINNT_RESERVE_BYTES) / 1024);
Bram Moolenaaree273972016-01-02 21:11:51 +01006380}
Bram Moolenaar071d4272004-06-13 20:20:40 +00006381
Bram Moolenaar071d4272004-06-13 20:20:40 +00006382#ifdef FEAT_MBYTE
6383/*
6384 * Same code as below, but with wide functions and no comments.
6385 * Return 0 for success, non-zero for failure.
6386 */
6387 int
6388mch_wrename(WCHAR *wold, WCHAR *wnew)
6389{
6390 WCHAR *p;
6391 int i;
6392 WCHAR szTempFile[_MAX_PATH + 1];
6393 WCHAR szNewPath[_MAX_PATH + 1];
6394 HANDLE hf;
6395
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006396 p = wold;
6397 for (i = 0; wold[i] != NUL; ++i)
6398 if ((wold[i] == '/' || wold[i] == '\\' || wold[i] == ':')
6399 && wold[i + 1] != 0)
6400 p = wold + i + 1;
6401 if ((int)(wold + i - p) < 8 || p[6] != '~')
6402 return (MoveFileW(wold, wnew) == 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006403
6404 if (GetFullPathNameW(wnew, _MAX_PATH, szNewPath, &p) == 0 || p == NULL)
6405 return -1;
6406 *p = NUL;
6407
6408 if (GetTempFileNameW(szNewPath, L"VIM", 0, szTempFile) == 0)
6409 return -2;
6410
6411 if (!DeleteFileW(szTempFile))
6412 return -3;
6413
6414 if (!MoveFileW(wold, szTempFile))
6415 return -4;
6416
6417 if ((hf = CreateFileW(wold, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6418 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6419 return -5;
6420 if (!CloseHandle(hf))
6421 return -6;
6422
6423 if (!MoveFileW(szTempFile, wnew))
6424 {
6425 (void)MoveFileW(szTempFile, wold);
6426 return -7;
6427 }
6428
6429 DeleteFileW(szTempFile);
6430
6431 if (!DeleteFileW(wold))
6432 return -8;
6433
6434 return 0;
6435}
6436#endif
6437
6438
6439/*
6440 * mch_rename() works around a bug in rename (aka MoveFile) in
6441 * Windows 95: rename("foo.bar", "foo.bar~") will generate a
6442 * file whose short file name is "FOO.BAR" (its long file name will
6443 * be correct: "foo.bar~"). Because a file can be accessed by
6444 * either its SFN or its LFN, "foo.bar" has effectively been
6445 * renamed to "foo.bar", which is not at all what was wanted. This
6446 * seems to happen only when renaming files with three-character
6447 * extensions by appending a suffix that does not include ".".
6448 * Windows NT gets it right, however, with an SFN of "FOO~1.BAR".
6449 *
6450 * There is another problem, which isn't really a bug but isn't right either:
6451 * When renaming "abcdef~1.txt" to "abcdef~1.txt~", the short name can be
6452 * "abcdef~1.txt" again. This has been reported on Windows NT 4.0 with
6453 * service pack 6. Doesn't seem to happen on Windows 98.
6454 *
6455 * Like rename(), returns 0 upon success, non-zero upon failure.
6456 * Should probably set errno appropriately when errors occur.
6457 */
6458 int
6459mch_rename(
6460 const char *pszOldFile,
6461 const char *pszNewFile)
6462{
6463 char szTempFile[_MAX_PATH+1];
6464 char szNewPath[_MAX_PATH+1];
6465 char *pszFilePart;
6466 HANDLE hf;
6467#ifdef FEAT_MBYTE
6468 WCHAR *wold = NULL;
6469 WCHAR *wnew = NULL;
6470 int retval = -1;
6471
6472 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
6473 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006474 wold = enc_to_utf16((char_u *)pszOldFile, NULL);
6475 wnew = enc_to_utf16((char_u *)pszNewFile, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006476 if (wold != NULL && wnew != NULL)
6477 retval = mch_wrename(wold, wnew);
6478 vim_free(wold);
6479 vim_free(wnew);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006480 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006481 }
6482#endif
6483
6484 /*
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006485 * No need to play tricks unless the file name contains a "~" as the
6486 * seventh character.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006487 */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006488 pszFilePart = (char *)gettail((char_u *)pszOldFile);
6489 if (STRLEN(pszFilePart) < 8 || pszFilePart[6] != '~')
6490 return rename(pszOldFile, pszNewFile);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006491
6492 /* Get base path of new file name. Undocumented feature: If pszNewFile is
6493 * a directory, no error is returned and pszFilePart will be NULL. */
6494 if (GetFullPathName(pszNewFile, _MAX_PATH, szNewPath, &pszFilePart) == 0
6495 || pszFilePart == NULL)
6496 return -1;
6497 *pszFilePart = NUL;
6498
6499 /* Get (and create) a unique temporary file name in directory of new file */
6500 if (GetTempFileName(szNewPath, "VIM", 0, szTempFile) == 0)
6501 return -2;
6502
6503 /* blow the temp file away */
6504 if (!DeleteFile(szTempFile))
6505 return -3;
6506
6507 /* rename old file to the temp file */
6508 if (!MoveFile(pszOldFile, szTempFile))
6509 return -4;
6510
6511 /* now create an empty file called pszOldFile; this prevents the operating
6512 * system using pszOldFile as an alias (SFN) if we're renaming within the
6513 * same directory. For example, we're editing a file called
6514 * filename.asc.txt by its SFN, filena~1.txt. If we rename filena~1.txt
6515 * to filena~1.txt~ (i.e., we're making a backup while writing it), the
6516 * SFN for filena~1.txt~ will be filena~1.txt, by default, which will
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006517 * cause all sorts of problems later in buf_write(). So, we create an
6518 * empty file called filena~1.txt and the system will have to find some
6519 * other SFN for filena~1.txt~, such as filena~2.txt
Bram Moolenaar071d4272004-06-13 20:20:40 +00006520 */
6521 if ((hf = CreateFile(pszOldFile, GENERIC_WRITE, 0, NULL, CREATE_NEW,
6522 FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
6523 return -5;
6524 if (!CloseHandle(hf))
6525 return -6;
6526
6527 /* rename the temp file to the new file */
6528 if (!MoveFile(szTempFile, pszNewFile))
6529 {
6530 /* Renaming failed. Rename the file back to its old name, so that it
6531 * looks like nothing happened. */
6532 (void)MoveFile(szTempFile, pszOldFile);
6533
6534 return -7;
6535 }
6536
6537 /* Seems to be left around on Novell filesystems */
6538 DeleteFile(szTempFile);
6539
6540 /* finally, remove the empty old file */
6541 if (!DeleteFile(pszOldFile))
6542 return -8;
6543
6544 return 0; /* success */
6545}
6546
6547/*
6548 * Get the default shell for the current hardware platform
6549 */
6550 char *
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006551default_shell(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006552{
Bram Moolenaar071d4272004-06-13 20:20:40 +00006553 PlatformId();
6554
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006555 return "cmd.exe";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006556}
6557
6558/*
6559 * mch_access() extends access() to do more detailed check on network drives.
6560 * Returns 0 if file "n" has access rights according to "p", -1 otherwise.
6561 */
6562 int
6563mch_access(char *n, int p)
6564{
6565 HANDLE hFile;
6566 DWORD am;
6567 int retval = -1; /* default: fail */
6568#ifdef FEAT_MBYTE
6569 WCHAR *wn = NULL;
6570
6571 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006572 wn = enc_to_utf16((char_u *)n, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006573#endif
6574
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006575 if (mch_isdir((char_u *)n))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576 {
6577 char TempName[_MAX_PATH + 16] = "";
6578#ifdef FEAT_MBYTE
6579 WCHAR TempNameW[_MAX_PATH + 16] = L"";
6580#endif
6581
6582 if (p & R_OK)
6583 {
6584 /* Read check is performed by seeing if we can do a find file on
6585 * the directory for any file. */
6586#ifdef FEAT_MBYTE
6587 if (wn != NULL)
6588 {
6589 int i;
6590 WIN32_FIND_DATAW d;
6591
6592 for (i = 0; i < _MAX_PATH && wn[i] != 0; ++i)
6593 TempNameW[i] = wn[i];
6594 if (TempNameW[i - 1] != '\\' && TempNameW[i - 1] != '/')
6595 TempNameW[i++] = '\\';
6596 TempNameW[i++] = '*';
6597 TempNameW[i++] = 0;
6598
6599 hFile = FindFirstFileW(TempNameW, &d);
6600 if (hFile == INVALID_HANDLE_VALUE)
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006601 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006602 else
6603 (void)FindClose(hFile);
6604 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006605 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006606#endif
6607 {
6608 char *pch;
6609 WIN32_FIND_DATA d;
6610
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006611 vim_strncpy((char_u *)TempName, (char_u *)n, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006612 pch = TempName + STRLEN(TempName) - 1;
6613 if (*pch != '\\' && *pch != '/')
6614 *++pch = '\\';
6615 *++pch = '*';
6616 *++pch = NUL;
6617
6618 hFile = FindFirstFile(TempName, &d);
6619 if (hFile == INVALID_HANDLE_VALUE)
6620 goto getout;
6621 (void)FindClose(hFile);
6622 }
6623 }
6624
6625 if (p & W_OK)
6626 {
6627 /* Trying to create a temporary file in the directory should catch
6628 * directories on read-only network shares. However, in
6629 * directories whose ACL allows writes but denies deletes will end
6630 * up keeping the temporary file :-(. */
6631#ifdef FEAT_MBYTE
6632 if (wn != NULL)
6633 {
6634 if (!GetTempFileNameW(wn, L"VIM", 0, TempNameW))
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006635 goto getout;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006636 else
6637 DeleteFileW(TempNameW);
6638 }
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006639 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006640#endif
6641 {
6642 if (!GetTempFileName(n, "VIM", 0, TempName))
6643 goto getout;
6644 mch_remove((char_u *)TempName);
6645 }
6646 }
6647 }
6648 else
6649 {
6650 /* Trying to open the file for the required access does ACL, read-only
6651 * network share, and file attribute checks. */
6652 am = ((p & W_OK) ? GENERIC_WRITE : 0)
6653 | ((p & R_OK) ? GENERIC_READ : 0);
6654#ifdef FEAT_MBYTE
6655 if (wn != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006656 hFile = CreateFileW(wn, am, 0, NULL, OPEN_EXISTING, 0, NULL);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006657 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00006658#endif
6659 hFile = CreateFile(n, am, 0, NULL, OPEN_EXISTING, 0, NULL);
6660 if (hFile == INVALID_HANDLE_VALUE)
6661 goto getout;
6662 CloseHandle(hFile);
6663 }
6664
6665 retval = 0; /* success */
6666getout:
6667#ifdef FEAT_MBYTE
6668 vim_free(wn);
6669#endif
6670 return retval;
6671}
6672
6673#if defined(FEAT_MBYTE) || defined(PROTO)
6674/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006675 * Version of open() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006676 */
6677 int
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006678mch_open(const char *name, int flags, int mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006679{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006680 /* _wopen() does not work with Borland C 5.5: creates a read-only file. */
6681# ifndef __BORLANDC__
Bram Moolenaar071d4272004-06-13 20:20:40 +00006682 WCHAR *wn;
6683 int f;
6684
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006685 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006686 {
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006687 wn = enc_to_utf16((char_u *)name, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006688 if (wn != NULL)
6689 {
6690 f = _wopen(wn, flags, mode);
6691 vim_free(wn);
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006692 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006693 }
6694 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006695# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006696
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006697 /* open() can open a file which name is longer than _MAX_PATH bytes
6698 * and shorter than _MAX_PATH characters successfully, but sometimes it
6699 * causes unexpected error in another part. We make it an error explicitly
6700 * here. */
6701 if (strlen(name) >= _MAX_PATH)
6702 return -1;
6703
Bram Moolenaar071d4272004-06-13 20:20:40 +00006704 return open(name, flags, mode);
6705}
6706
6707/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006708 * Version of fopen() that may use UTF-16 file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006709 */
6710 FILE *
Bram Moolenaarb6843a02017-08-02 22:07:12 +02006711mch_fopen(const char *name, const char *mode)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712{
6713 WCHAR *wn, *wm;
6714 FILE *f = NULL;
6715
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006716 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006717 {
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006718# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006719 /* Work around an annoying assertion in the Microsoft debug CRT
6720 * when mode's text/binary setting doesn't match _get_fmode(). */
6721 char newMode = mode[strlen(mode) - 1];
6722 int oldMode = 0;
6723
6724 _get_fmode(&oldMode);
6725 if (newMode == 't')
6726 _set_fmode(_O_TEXT);
6727 else if (newMode == 'b')
6728 _set_fmode(_O_BINARY);
6729# endif
Bram Moolenaar6aa2cd42016-02-16 15:06:59 +01006730 wn = enc_to_utf16((char_u *)name, NULL);
6731 wm = enc_to_utf16((char_u *)mode, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006732 if (wn != NULL && wm != NULL)
6733 f = _wfopen(wn, wm);
6734 vim_free(wn);
6735 vim_free(wm);
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006736
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00006737# if defined(DEBUG) && _MSC_VER >= 1400
Bram Moolenaar0fde2902008-03-16 13:54:13 +00006738 _set_fmode(oldMode);
6739# endif
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006740 return f;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006741 }
6742
Bram Moolenaarf9e6c3b2014-11-05 18:36:03 +01006743 /* fopen() can open a file which name is longer than _MAX_PATH bytes
6744 * and shorter than _MAX_PATH characters successfully, but sometimes it
6745 * causes unexpected error in another part. We make it an error explicitly
6746 * here. */
6747 if (strlen(name) >= _MAX_PATH)
6748 return NULL;
6749
Bram Moolenaar071d4272004-06-13 20:20:40 +00006750 return fopen(name, mode);
6751}
6752#endif
6753
6754#ifdef FEAT_MBYTE
6755/*
6756 * SUB STREAM (aka info stream) handling:
6757 *
6758 * NTFS can have sub streams for each file. Normal contents of file is
6759 * stored in the main stream, and extra contents (author information and
6760 * title and so on) can be stored in sub stream. After Windows 2000, user
6761 * can access and store those informations in sub streams via explorer's
6762 * property menuitem in right click menu. Those informations in sub streams
6763 * were lost when copying only the main stream. So we have to copy sub
6764 * streams.
6765 *
6766 * Incomplete explanation:
6767 * http://msdn.microsoft.com/library/en-us/dnw2k/html/ntfs5.asp
6768 * More useful info and an example:
6769 * http://www.sysinternals.com/ntw2k/source/misc.shtml#streams
6770 */
6771
6772/*
6773 * Copy info stream data "substream". Read from the file with BackupRead(sh)
6774 * and write to stream "substream" of file "to".
6775 * Errors are ignored.
6776 */
6777 static void
6778copy_substream(HANDLE sh, void *context, WCHAR *to, WCHAR *substream, long len)
6779{
6780 HANDLE hTo;
6781 WCHAR *to_name;
6782
6783 to_name = malloc((wcslen(to) + wcslen(substream) + 1) * sizeof(WCHAR));
6784 wcscpy(to_name, to);
6785 wcscat(to_name, substream);
6786
6787 hTo = CreateFileW(to_name, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,
6788 FILE_ATTRIBUTE_NORMAL, NULL);
6789 if (hTo != INVALID_HANDLE_VALUE)
6790 {
6791 long done;
6792 DWORD todo;
6793 DWORD readcnt, written;
6794 char buf[4096];
6795
6796 /* Copy block of bytes at a time. Abort when something goes wrong. */
6797 for (done = 0; done < len; done += written)
6798 {
6799 /* (size_t) cast for Borland C 5.5 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006800 todo = (DWORD)((size_t)(len - done) > sizeof(buf) ? sizeof(buf)
6801 : (size_t)(len - done));
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802 if (!BackupRead(sh, (LPBYTE)buf, todo, &readcnt,
6803 FALSE, FALSE, context)
6804 || readcnt != todo
6805 || !WriteFile(hTo, buf, todo, &written, NULL)
6806 || written != todo)
6807 break;
6808 }
6809 CloseHandle(hTo);
6810 }
6811
6812 free(to_name);
6813}
6814
6815/*
6816 * Copy info streams from file "from" to file "to".
6817 */
6818 static void
6819copy_infostreams(char_u *from, char_u *to)
6820{
6821 WCHAR *fromw;
6822 WCHAR *tow;
6823 HANDLE sh;
6824 WIN32_STREAM_ID sid;
6825 int headersize;
6826 WCHAR streamname[_MAX_PATH];
6827 DWORD readcount;
6828 void *context = NULL;
6829 DWORD lo, hi;
6830 int len;
6831
6832 /* Convert the file names to wide characters. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00006833 fromw = enc_to_utf16(from, NULL);
6834 tow = enc_to_utf16(to, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006835 if (fromw != NULL && tow != NULL)
6836 {
6837 /* Open the file for reading. */
6838 sh = CreateFileW(fromw, GENERIC_READ, FILE_SHARE_READ, NULL,
6839 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
6840 if (sh != INVALID_HANDLE_VALUE)
6841 {
6842 /* Use BackupRead() to find the info streams. Repeat until we
6843 * have done them all.*/
6844 for (;;)
6845 {
6846 /* Get the header to find the length of the stream name. If
6847 * the "readcount" is zero we have done all info streams. */
6848 ZeroMemory(&sid, sizeof(WIN32_STREAM_ID));
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00006849 headersize = (int)((char *)&sid.cStreamName - (char *)&sid.dwStreamId);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850 if (!BackupRead(sh, (LPBYTE)&sid, headersize,
6851 &readcount, FALSE, FALSE, &context)
6852 || readcount == 0)
6853 break;
6854
6855 /* We only deal with streams that have a name. The normal
6856 * file data appears to be without a name, even though docs
6857 * suggest it is called "::$DATA". */
6858 if (sid.dwStreamNameSize > 0)
6859 {
6860 /* Read the stream name. */
6861 if (!BackupRead(sh, (LPBYTE)streamname,
6862 sid.dwStreamNameSize,
6863 &readcount, FALSE, FALSE, &context))
6864 break;
6865
6866 /* Copy an info stream with a name ":anything:$DATA".
6867 * Skip "::$DATA", it has no stream name (examples suggest
6868 * it might be used for the normal file contents).
6869 * Note that BackupRead() counts bytes, but the name is in
6870 * wide characters. */
6871 len = readcount / sizeof(WCHAR);
6872 streamname[len] = 0;
6873 if (len > 7 && wcsicmp(streamname + len - 6,
6874 L":$DATA") == 0)
6875 {
6876 streamname[len - 6] = 0;
6877 copy_substream(sh, &context, tow, streamname,
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00006878 (long)sid.Size.u.LowPart);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006879 }
6880 }
6881
6882 /* Advance to the next stream. We might try seeking too far,
6883 * but BackupSeek() doesn't skip over stream borders, thus
6884 * that's OK. */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00006885 (void)BackupSeek(sh, sid.Size.u.LowPart, sid.Size.u.HighPart,
Bram Moolenaar071d4272004-06-13 20:20:40 +00006886 &lo, &hi, &context);
6887 }
6888
6889 /* Clear the context. */
6890 (void)BackupRead(sh, NULL, 0, &readcount, TRUE, FALSE, &context);
6891
6892 CloseHandle(sh);
6893 }
6894 }
6895 vim_free(fromw);
6896 vim_free(tow);
6897}
6898#endif
6899
6900/*
6901 * Copy file attributes from file "from" to file "to".
6902 * For Windows NT and later we copy info streams.
6903 * Always returns zero, errors are ignored.
6904 */
6905 int
6906mch_copy_file_attribute(char_u *from, char_u *to)
6907{
6908#ifdef FEAT_MBYTE
6909 /* File streams only work on Windows NT and later. */
6910 PlatformId();
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006911 copy_infostreams(from, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912#endif
6913 return 0;
6914}
6915
6916#if defined(MYRESETSTKOFLW) || defined(PROTO)
6917/*
6918 * Recreate a destroyed stack guard page in win32.
6919 * Written by Benjamin Peterson.
6920 */
6921
6922/* These magic numbers are from the MS header files */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006923#define MIN_STACK_WINNT 2
6924
6925/*
6926 * This function does the same thing as _resetstkoflw(), which is only
6927 * available in DevStudio .net and later.
6928 * Returns 0 for failure, 1 for success.
6929 */
6930 int
6931myresetstkoflw(void)
6932{
6933 BYTE *pStackPtr;
6934 BYTE *pGuardPage;
6935 BYTE *pStackBase;
6936 BYTE *pLowestPossiblePage;
6937 MEMORY_BASIC_INFORMATION mbi;
6938 SYSTEM_INFO si;
6939 DWORD nPageSize;
6940 DWORD dummy;
6941
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 PlatformId();
Bram Moolenaar071d4272004-06-13 20:20:40 +00006943
6944 /* We need to know the system page size. */
6945 GetSystemInfo(&si);
6946 nPageSize = si.dwPageSize;
6947
6948 /* ...and the current stack pointer */
6949 pStackPtr = (BYTE*)_alloca(1);
6950
6951 /* ...and the base of the stack. */
6952 if (VirtualQuery(pStackPtr, &mbi, sizeof mbi) == 0)
6953 return 0;
6954 pStackBase = (BYTE*)mbi.AllocationBase;
6955
6956 /* ...and the page thats min_stack_req pages away from stack base; this is
6957 * the lowest page we could use. */
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006958 pLowestPossiblePage = pStackBase + MIN_STACK_WINNT * nPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959
Bram Moolenaar071d4272004-06-13 20:20:40 +00006960 {
Bram Moolenaarcea912a2016-10-12 14:20:24 +02006961 /* We want the first committed page in the stack Start at the stack
6962 * base and move forward through memory until we find a committed block.
6963 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 BYTE *pBlock = pStackBase;
6965
Bram Moolenaara466c992005-07-09 21:03:22 +00006966 for (;;)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006967 {
6968 if (VirtualQuery(pBlock, &mbi, sizeof mbi) == 0)
6969 return 0;
6970
6971 pBlock += mbi.RegionSize;
6972
6973 if (mbi.State & MEM_COMMIT)
6974 break;
6975 }
6976
6977 /* mbi now describes the first committed block in the stack. */
6978 if (mbi.Protect & PAGE_GUARD)
6979 return 1;
6980
6981 /* decide where the guard page should start */
6982 if ((long_u)(mbi.BaseAddress) < (long_u)pLowestPossiblePage)
6983 pGuardPage = pLowestPossiblePage;
6984 else
6985 pGuardPage = (BYTE*)mbi.BaseAddress;
6986
6987 /* allocate the guard page */
6988 if (!VirtualAlloc(pGuardPage, nPageSize, MEM_COMMIT, PAGE_READWRITE))
6989 return 0;
6990
6991 /* apply the guard attribute to the page */
6992 if (!VirtualProtect(pGuardPage, nPageSize, PAGE_READWRITE | PAGE_GUARD,
6993 &dummy))
6994 return 0;
6995 }
6996
6997 return 1;
6998}
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00006999#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007000
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007001
7002#if defined(FEAT_MBYTE) || defined(PROTO)
7003/*
7004 * The command line arguments in UCS2
7005 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007006static int nArgsW = 0;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007007static LPWSTR *ArglistW = NULL;
7008static int global_argc = 0;
7009static char **global_argv;
7010
7011static int used_file_argc = 0; /* last argument in global_argv[] used
7012 for the argument list. */
7013static int *used_file_indexes = NULL; /* indexes in global_argv[] for
7014 command line arguments added to
7015 the argument list */
7016static int used_file_count = 0; /* nr of entries in used_file_indexes */
7017static int used_file_literal = FALSE; /* take file names literally */
7018static int used_file_full_path = FALSE; /* file name was full path */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007019static int used_file_diff_mode = FALSE; /* file name was with diff mode */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007020static int used_alist_count = 0;
7021
7022
7023/*
7024 * Get the command line arguments. Unicode version.
7025 * Returns argc. Zero when something fails.
7026 */
7027 int
7028get_cmd_argsW(char ***argvp)
7029{
7030 char **argv = NULL;
7031 int argc = 0;
7032 int i;
7033
Bram Moolenaar14993322014-09-09 12:25:33 +02007034 free_cmd_argsW();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007035 ArglistW = CommandLineToArgvW(GetCommandLineW(), &nArgsW);
7036 if (ArglistW != NULL)
7037 {
7038 argv = malloc((nArgsW + 1) * sizeof(char *));
7039 if (argv != NULL)
7040 {
7041 argc = nArgsW;
7042 argv[argc] = NULL;
7043 for (i = 0; i < argc; ++i)
7044 {
7045 int len;
7046
7047 /* Convert each Unicode argument to the current codepage. */
7048 WideCharToMultiByte_alloc(GetACP(), 0,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00007049 ArglistW[i], (int)wcslen(ArglistW[i]) + 1,
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007050 (LPSTR *)&argv[i], &len, 0, 0);
7051 if (argv[i] == NULL)
7052 {
7053 /* Out of memory, clear everything. */
7054 while (i > 0)
7055 free(argv[--i]);
7056 free(argv);
Bram Moolenaar73c61632013-12-07 14:48:10 +01007057 argv = NULL;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007058 argc = 0;
7059 }
7060 }
7061 }
7062 }
7063
7064 global_argc = argc;
7065 global_argv = argv;
7066 if (argc > 0)
Bram Moolenaar14993322014-09-09 12:25:33 +02007067 {
7068 if (used_file_indexes != NULL)
7069 free(used_file_indexes);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007070 used_file_indexes = malloc(argc * sizeof(int));
Bram Moolenaar14993322014-09-09 12:25:33 +02007071 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007072
7073 if (argvp != NULL)
7074 *argvp = argv;
7075 return argc;
7076}
7077
7078 void
7079free_cmd_argsW(void)
7080{
7081 if (ArglistW != NULL)
7082 {
7083 GlobalFree(ArglistW);
7084 ArglistW = NULL;
7085 }
7086}
7087
7088/*
7089 * Remember "name" is an argument that was added to the argument list.
7090 * This avoids that we have to re-parse the argument list when fix_arg_enc()
7091 * is called.
7092 */
7093 void
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007094used_file_arg(char *name, int literal, int full_path, int diff_mode)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007095{
7096 int i;
7097
7098 if (used_file_indexes == NULL)
7099 return;
7100 for (i = used_file_argc + 1; i < global_argc; ++i)
7101 if (STRCMP(global_argv[i], name) == 0)
7102 {
7103 used_file_argc = i;
7104 used_file_indexes[used_file_count++] = i;
7105 break;
7106 }
7107 used_file_literal = literal;
7108 used_file_full_path = full_path;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007109 used_file_diff_mode = diff_mode;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007110}
7111
7112/*
7113 * Remember the length of the argument list as it was. If it changes then we
7114 * leave it alone when 'encoding' is set.
7115 */
7116 void
7117set_alist_count(void)
7118{
7119 used_alist_count = GARGCOUNT;
7120}
7121
7122/*
7123 * Fix the encoding of the command line arguments. Invoked when 'encoding'
7124 * has been changed while starting up. Use the UCS-2 command line arguments
7125 * and convert them to 'encoding'.
7126 */
7127 void
7128fix_arg_enc(void)
7129{
7130 int i;
7131 int idx;
7132 char_u *str;
Bram Moolenaar86b68352004-12-27 21:59:20 +00007133 int *fnum_list;
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007134
7135 /* Safety checks:
7136 * - if argument count differs between the wide and non-wide argument
7137 * list, something must be wrong.
7138 * - the file name arguments must have been located.
7139 * - the length of the argument list wasn't changed by the user.
7140 */
Bram Moolenaard857f0e2005-06-21 22:37:39 +00007141 if (global_argc != nArgsW
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007142 || ArglistW == NULL
7143 || used_file_indexes == NULL
7144 || used_file_count == 0
7145 || used_alist_count != GARGCOUNT)
7146 return;
7147
Bram Moolenaar86b68352004-12-27 21:59:20 +00007148 /* Remember the buffer numbers for the arguments. */
7149 fnum_list = (int *)alloc((int)sizeof(int) * GARGCOUNT);
7150 if (fnum_list == NULL)
7151 return; /* out of memory */
7152 for (i = 0; i < GARGCOUNT; ++i)
7153 fnum_list[i] = GARGLIST[i].ae_fnum;
7154
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007155 /* Clear the argument list. Make room for the new arguments. */
7156 alist_clear(&global_alist);
7157 if (ga_grow(&global_alist.al_ga, used_file_count) == FAIL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007158 return; /* out of memory */
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007159
7160 for (i = 0; i < used_file_count; ++i)
7161 {
7162 idx = used_file_indexes[i];
Bram Moolenaar36f692d2008-11-20 16:10:17 +00007163 str = utf16_to_enc(ArglistW[idx], NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007164 if (str != NULL)
Bram Moolenaar86b68352004-12-27 21:59:20 +00007165 {
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007166 int literal = used_file_literal;
7167
Bram Moolenaar910f66f2006-04-05 20:41:53 +00007168#ifdef FEAT_DIFF
7169 /* When using diff mode may need to concatenate file name to
7170 * directory name. Just like it's done in main(). */
7171 if (used_file_diff_mode && mch_isdir(str) && GARGCOUNT > 0
7172 && !mch_isdir(alist_name(&GARGLIST[0])))
7173 {
7174 char_u *r;
7175
7176 r = concat_fnames(str, gettail(alist_name(&GARGLIST[0])), TRUE);
7177 if (r != NULL)
7178 {
7179 vim_free(str);
7180 str = r;
7181 }
7182 }
7183#endif
Bram Moolenaar86b68352004-12-27 21:59:20 +00007184 /* Re-use the old buffer by renaming it. When not using literal
7185 * names it's done by alist_expand() below. */
7186 if (used_file_literal)
7187 buf_set_name(fnum_list[i], str);
7188
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007189 /* Check backtick literal. backtick literal is already expanded in
7190 * main.c, so this part add str as literal. */
7191 if (literal == FALSE)
7192 {
Bram Moolenaar116a0f82017-08-07 21:17:57 +02007193 size_t len = STRLEN(str);
7194
Bram Moolenaar39d21e32017-08-05 23:09:31 +02007195 if (len > 2 && *str == '`' && *(str + len - 1) == '`')
7196 literal = TRUE;
7197 }
7198 alist_add(&global_alist, str, literal ? 2 : 0);
Bram Moolenaar86b68352004-12-27 21:59:20 +00007199 }
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007200 }
7201
7202 if (!used_file_literal)
7203 {
7204 /* Now expand wildcards in the arguments. */
7205 /* Temporarily add '(' and ')' to 'isfname'. These are valid
7206 * filename characters but are excluded from 'isfname' to make
7207 * "gf" work on a file name in parenthesis (e.g.: see vim.h). */
7208 do_cmdline_cmd((char_u *)":let SaVe_ISF = &isf|set isf+=(,)");
Bram Moolenaar86b68352004-12-27 21:59:20 +00007209 alist_expand(fnum_list, used_alist_count);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007210 do_cmdline_cmd((char_u *)":let &isf = SaVe_ISF|unlet SaVe_ISF");
7211 }
7212
7213 /* If wildcard expansion failed, we are editing the first file of the
7214 * arglist and there is no file name: Edit the first argument now. */
7215 if (curwin->w_arg_idx == 0 && curbuf->b_fname == NULL)
7216 {
7217 do_cmdline_cmd((char_u *)":rewind");
7218 if (GARGCOUNT == 1 && used_file_full_path)
7219 (void)vim_chdirfile(alist_name(&GARGLIST[0]));
7220 }
Bram Moolenaar86b68352004-12-27 21:59:20 +00007221
7222 set_alist_count();
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +00007223}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007224#endif
Bram Moolenaar7c23d1d2017-02-01 13:14:16 +01007225
7226 int
7227mch_setenv(char *var, char *value, int x)
7228{
7229 char_u *envbuf;
7230
7231 envbuf = alloc((unsigned)(STRLEN(var) + STRLEN(value) + 2));
7232 if (envbuf == NULL)
7233 return -1;
7234
7235 sprintf((char *)envbuf, "%s=%s", var, value);
7236
7237#ifdef FEAT_MBYTE
7238 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
7239 {
7240 WCHAR *p = enc_to_utf16(envbuf, NULL);
7241
7242 vim_free(envbuf);
7243 if (p == NULL)
7244 return -1;
7245 _wputenv(p);
7246# ifdef libintl_wputenv
7247 libintl_wputenv(p);
7248# endif
7249 /* Unlike Un*x systems, we can free the string for _wputenv(). */
7250 vim_free(p);
7251 }
7252 else
7253#endif
7254 {
7255 _putenv((char *)envbuf);
7256# ifdef libintl_putenv
7257 libintl_putenv((char *)envbuf);
7258# endif
7259 /* Unlike Un*x systems, we can free the string for _putenv(). */
7260 vim_free(envbuf);
7261 }
7262
7263 return 0;
7264}