blob: 8b507f6fbd0d6e30ad991442e3ef151fbf80949b [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * os_mswin.c
12 *
13 * Routines common to both Win16 and Win32.
14 */
15
16#ifdef WIN16
17# ifdef __BORLANDC__
18# pragma warn -par
19# pragma warn -ucp
20# pragma warn -use
21# pragma warn -aus
22# endif
23#endif
24
Bram Moolenaar071d4272004-06-13 20:20:40 +000025#include "vim.h"
26
Bram Moolenaar071d4272004-06-13 20:20:40 +000027#ifdef WIN16
28# define SHORT_FNAME /* always 8.3 file name */
Bram Moolenaar82881492012-11-20 16:53:39 +010029/* cproto fails on missing include files */
30# ifndef PROTO
31# include <dos.h>
32# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000033# include <string.h>
34#endif
35#include <sys/types.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000036#include <signal.h>
37#include <limits.h>
Bram Moolenaar82881492012-11-20 16:53:39 +010038#ifndef PROTO
39# include <process.h>
40#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000041
42#undef chdir
43#ifdef __GNUC__
44# ifndef __MINGW32__
45# include <dirent.h>
46# endif
47#else
48# include <direct.h>
49#endif
50
Bram Moolenaar82881492012-11-20 16:53:39 +010051#ifndef PROTO
52# if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
53# include <shellapi.h>
54# endif
55
56# if defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)
57# include <dlgs.h>
58# ifdef WIN3264
59# include <winspool.h>
60# else
61# include <print.h>
62# endif
63# include <commdlg.h>
Bram Moolenaar071d4272004-06-13 20:20:40 +000064#endif
65
Bram Moolenaar82881492012-11-20 16:53:39 +010066#endif /* PROTO */
Bram Moolenaar071d4272004-06-13 20:20:40 +000067
68#ifdef __MINGW32__
69# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
70# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
71# endif
72# ifndef RIGHTMOST_BUTTON_PRESSED
73# define RIGHTMOST_BUTTON_PRESSED 0x0002
74# endif
75# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
76# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
77# endif
78# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
79# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
80# endif
81# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
82# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
83# endif
84
85/*
86 * EventFlags
87 */
88# ifndef MOUSE_MOVED
89# define MOUSE_MOVED 0x0001
90# endif
91# ifndef DOUBLE_CLICK
92# define DOUBLE_CLICK 0x0002
93# endif
94#endif
95
96/*
97 * When generating prototypes for Win32 on Unix, these lines make the syntax
98 * errors disappear. They do not need to be correct.
99 */
100#ifdef PROTO
101#define WINAPI
102#define WINBASEAPI
103typedef int BOOL;
104typedef int CALLBACK;
105typedef int COLORREF;
106typedef int CONSOLE_CURSOR_INFO;
107typedef int COORD;
108typedef int DWORD;
109typedef int ENUMLOGFONT;
110typedef int HANDLE;
111typedef int HDC;
112typedef int HFONT;
113typedef int HICON;
114typedef int HWND;
115typedef int INPUT_RECORD;
116typedef int KEY_EVENT_RECORD;
117typedef int LOGFONT;
118typedef int LPARAM;
119typedef int LPBOOL;
120typedef int LPCSTR;
121typedef int LPCWSTR;
122typedef int LPSTR;
123typedef int LPTSTR;
124typedef int LPWSTR;
125typedef int LRESULT;
126typedef int MOUSE_EVENT_RECORD;
127typedef int NEWTEXTMETRIC;
128typedef int PACL;
129typedef int PRINTDLG;
130typedef int PSECURITY_DESCRIPTOR;
131typedef int PSID;
132typedef int SECURITY_INFORMATION;
133typedef int SHORT;
134typedef int SMALL_RECT;
135typedef int TEXTMETRIC;
136typedef int UINT;
137typedef int WCHAR;
138typedef int WORD;
139typedef int WPARAM;
140typedef void VOID;
141#endif
142
143/* Record all output and all keyboard & mouse input */
144/* #define MCH_WRITE_DUMP */
145
146#ifdef MCH_WRITE_DUMP
147FILE* fdDump = NULL;
148#endif
149
150#ifdef WIN3264
151extern DWORD g_PlatformId;
152#endif
153
154#ifndef FEAT_GUI_MSWIN
155extern char g_szOrigTitle[];
156#endif
157
158#ifdef FEAT_GUI
159extern HWND s_hwnd;
160#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000161static HWND s_hwnd = 0; /* console window handle, set by GetConsoleHwnd() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000162#endif
163
164extern int WSInitialized;
165
166/* Don't generate prototypes here, because some systems do have these
167 * functions. */
168#if defined(__GNUC__) && !defined(PROTO)
169# ifndef __MINGW32__
170int _stricoll(char *a, char *b)
171{
172 // the ANSI-ish correct way is to use strxfrm():
173 char a_buff[512], b_buff[512]; // file names, so this is enough on Win32
174 strxfrm(a_buff, a, 512);
175 strxfrm(b_buff, b, 512);
176 return strcoll(a_buff, b_buff);
177}
178
179char * _fullpath(char *buf, char *fname, int len)
180{
181 LPTSTR toss;
182
183 return (char *)GetFullPathName(fname, len, buf, &toss);
184}
185# endif
186
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100187# if !defined(__MINGW32__) || (__GNUC__ < 4)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000188int _chdrive(int drive)
189{
190 char temp [3] = "-:";
191 temp[0] = drive + 'A' - 1;
192 return !SetCurrentDirectory(temp);
193}
Bram Moolenaaraf62ff32013-03-19 14:48:29 +0100194# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000195#else
196# ifdef __BORLANDC__
197/* being a more ANSI compliant compiler, BorlandC doesn't define _stricoll:
198 * but it does in BC 5.02! */
199# if __BORLANDC__ < 0x502
200int _stricoll(char *a, char *b)
201{
202# if 1
203 // this is fast but not correct:
204 return stricmp(a, b);
205# else
206 // the ANSI-ish correct way is to use strxfrm():
207 char a_buff[512], b_buff[512]; // file names, so this is enough on Win32
208 strxfrm(a_buff, a, 512);
209 strxfrm(b_buff, b, 512);
210 return strcoll(a_buff, b_buff);
211# endif
212}
213# endif
214# endif
215#endif
216
217
218#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
219/*
220 * GUI version of mch_exit().
221 * Shut down and exit with status `r'
222 * Careful: mch_exit() may be called before mch_init()!
223 */
224 void
225mch_exit(int r)
226{
227 display_errors();
228
229 ml_close_all(TRUE); /* remove all memfiles */
230
231# ifdef FEAT_OLE
232 UninitOLE();
233# endif
234# ifdef FEAT_NETBEANS_INTG
235 if (WSInitialized)
236 {
237 WSInitialized = FALSE;
238 WSACleanup();
239 }
240# endif
241#ifdef DYNAMIC_GETTEXT
242 dyn_libintl_end();
243#endif
244
245 if (gui.in_use)
246 gui_exit(r);
Bram Moolenaar85c79d32007-02-20 01:59:20 +0000247
248#ifdef EXITFREE
249 free_all_mem();
250#endif
251
Bram Moolenaar071d4272004-06-13 20:20:40 +0000252 exit(r);
253}
254
255#endif /* FEAT_GUI_MSWIN */
256
257
258/*
259 * Init the tables for toupper() and tolower().
260 */
261 void
262mch_early_init(void)
263{
264 int i;
265
266#ifdef WIN3264
267 PlatformId();
268#endif
269
270 /* Init the tables for toupper() and tolower() */
271 for (i = 0; i < 256; ++i)
272 toupper_tab[i] = tolower_tab[i] = i;
273#ifdef WIN3264
274 CharUpperBuff(toupper_tab, 256);
275 CharLowerBuff(tolower_tab, 256);
276#else
277 AnsiUpperBuff(toupper_tab, 256);
278 AnsiLowerBuff(tolower_tab, 256);
279#endif
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000280
281#if defined(FEAT_MBYTE) && !defined(FEAT_GUI)
282 (void)get_cmd_argsW(NULL);
283#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000284}
285
286
287/*
288 * Return TRUE if the input comes from a terminal, FALSE otherwise.
289 */
290 int
291mch_input_isatty()
292{
293#ifdef FEAT_GUI_MSWIN
294 return OK; /* GUI always has a tty */
295#else
296 if (isatty(read_cmd_fd))
297 return TRUE;
298 return FALSE;
299#endif
300}
301
302#ifdef FEAT_TITLE
303/*
304 * mch_settitle(): set titlebar of our window
305 */
306 void
307mch_settitle(
308 char_u *title,
309 char_u *icon)
310{
311# ifdef FEAT_GUI_MSWIN
312 gui_mch_settitle(title, icon);
313# else
314 if (title != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000315 {
316# ifdef FEAT_MBYTE
317 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
318 {
319 /* Convert the title from 'encoding' to the active codepage. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000320 WCHAR *wp = enc_to_utf16(title, NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000321 int n;
322
323 if (wp != NULL)
324 {
325 n = SetConsoleTitleW(wp);
326 vim_free(wp);
327 if (n != 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
328 return;
329 }
330 }
331# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000332 SetConsoleTitle(title);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000333 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000334# endif
335}
336
337
338/*
339 * Restore the window/icon title.
340 * which is one of:
341 * 1: Just restore title
342 * 2: Just restore icon (which we don't have)
343 * 3: Restore title and icon (which we don't have)
344 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000345/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346 void
347mch_restore_title(
348 int which)
349{
350#ifndef FEAT_GUI_MSWIN
351 mch_settitle((which & 1) ? g_szOrigTitle : NULL, NULL);
352#endif
353}
354
355
356/*
357 * Return TRUE if we can restore the title (we can)
358 */
359 int
360mch_can_restore_title()
361{
362 return TRUE;
363}
364
365
366/*
367 * Return TRUE if we can restore the icon title (we can't)
368 */
369 int
370mch_can_restore_icon()
371{
372 return FALSE;
373}
374#endif /* FEAT_TITLE */
375
376
377/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000378 * Get absolute file name into buffer "buf" of length "len" bytes,
379 * turning all '/'s into '\\'s and getting the correct case of each component
380 * of the file name. Append a (back)slash to a directory name.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000381 * When 'shellslash' set do it the other way around.
382 * Return OK or FAIL.
383 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000384/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000385 int
386mch_FullName(
387 char_u *fname,
388 char_u *buf,
389 int len,
390 int force)
391{
392 int nResult = FAIL;
393
394#ifdef __BORLANDC__
395 if (*fname == NUL) /* Borland behaves badly here - make it consistent */
396 nResult = mch_dirname(buf, len);
397 else
398#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000399 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +0000400#ifdef FEAT_MBYTE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000401 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
402# ifdef __BORLANDC__
403 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
404 && g_PlatformId == VER_PLATFORM_WIN32_NT
405# endif
406 )
407 {
408 WCHAR *wname;
409 WCHAR wbuf[MAX_PATH];
410 char_u *cname = NULL;
411
412 /* Use the wide function:
413 * - convert the fname from 'encoding' to UCS2.
414 * - invoke _wfullpath()
415 * - convert the result from UCS2 to 'encoding'.
416 */
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000417 wname = enc_to_utf16(fname, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000418 if (wname != NULL && _wfullpath(wbuf, wname, MAX_PATH - 1) != NULL)
419 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000420 cname = utf16_to_enc((short_u *)wbuf, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000421 if (cname != NULL)
422 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +0000423 vim_strncpy(buf, cname, len - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000424 nResult = OK;
425 }
426 }
427 vim_free(wname);
428 vim_free(cname);
429 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000430 if (nResult == FAIL) /* fall back to non-wide function */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000431#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000432 {
433 if (_fullpath(buf, fname, len - 1) == NULL)
434 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +0000435 /* failed, use relative path name */
436 vim_strncpy(buf, fname, len - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000437 }
438 else
439 nResult = OK;
440 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000441 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442
443#ifdef USE_FNAME_CASE
444 fname_case(buf, len);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000445#else
446 slash_adjust(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447#endif
448
449 return nResult;
450}
451
452
453/*
454 * Return TRUE if "fname" does not depend on the current directory.
455 */
456 int
457mch_isFullName(char_u *fname)
458{
Bram Moolenaard2a203b2013-08-30 16:51:18 +0200459#ifdef FEAT_MBYTE
460 /* WinNT and later can use _MAX_PATH wide characters for a pathname, which
461 * means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
462 * UTF-8. */
463 char szName[_MAX_PATH * 3 + 1];
464#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465 char szName[_MAX_PATH + 1];
Bram Moolenaard2a203b2013-08-30 16:51:18 +0200466#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467
468 /* A name like "d:/foo" and "//server/share" is absolute */
469 if ((fname[0] && fname[1] == ':' && (fname[2] == '/' || fname[2] == '\\'))
470 || (fname[0] == fname[1] && (fname[0] == '/' || fname[0] == '\\')))
471 return TRUE;
472
473 /* A name that can't be made absolute probably isn't absolute. */
Bram Moolenaard2a203b2013-08-30 16:51:18 +0200474 if (mch_FullName(fname, szName, sizeof(szName) - 1, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475 return FALSE;
476
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000477 return pathcmp(fname, szName, -1) == 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478}
479
480/*
481 * Replace all slashes by backslashes.
482 * This used to be the other way around, but MS-DOS sometimes has problems
483 * with slashes (e.g. in a command name). We can't have mixed slashes and
484 * backslashes, because comparing file names will not work correctly. The
485 * commands that use a file name should try to avoid the need to type a
486 * backslash twice.
487 * When 'shellslash' set do it the other way around.
488 */
489 void
490slash_adjust(p)
491 char_u *p;
492{
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +0000493 while (*p)
494 {
495 if (*p == psepcN)
496 *p = psepc;
497 mb_ptr_adv(p);
498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000499}
500
Bram Moolenaar2ee95f72013-09-25 19:13:38 +0200501 static int
502stat_symlink_aware(const char *name, struct stat *stp)
503{
504#if defined(_MSC_VER) && _MSC_VER < 1700
505 /* Work around for VC10 or earlier. stat() can't handle symlinks properly.
506 * VC9 or earlier: stat() doesn't support a symlink at all. It retrieves
507 * status of a symlink itself.
508 * VC10: stat() supports a symlink to a normal file, but it doesn't support
509 * a symlink to a directory (always returns an error). */
510 WIN32_FIND_DATA findData;
511 HANDLE hFind, h;
512 DWORD attr = 0;
513 BOOL is_symlink = FALSE;
514
515 hFind = FindFirstFile(name, &findData);
516 if (hFind != INVALID_HANDLE_VALUE)
517 {
518 attr = findData.dwFileAttributes;
519 if ((attr & FILE_ATTRIBUTE_REPARSE_POINT)
520 && (findData.dwReserved0 == IO_REPARSE_TAG_SYMLINK))
521 is_symlink = TRUE;
522 FindClose(hFind);
523 }
524 if (is_symlink)
525 {
526 h = CreateFile(name, FILE_READ_ATTRIBUTES,
527 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
528 OPEN_EXISTING,
529 (attr & FILE_ATTRIBUTE_DIRECTORY)
530 ? FILE_FLAG_BACKUP_SEMANTICS : 0,
531 NULL);
532 if (h != INVALID_HANDLE_VALUE)
533 {
534 int fd, n;
535
536 fd = _open_osfhandle((intptr_t)h, _O_RDONLY);
537 n = _fstat(fd, (struct _stat*)stp);
538 _close(fd);
539 return n;
540 }
541 }
542#endif
543 return stat(name, stp);
544}
545
546#ifdef FEAT_MBYTE
547 static int
548wstat_symlink_aware(const WCHAR *name, struct _stat *stp)
549{
550# if defined(_MSC_VER) && _MSC_VER < 1700
551 /* Work around for VC10 or earlier. _wstat() can't handle symlinks properly.
552 * VC9 or earlier: _wstat() doesn't support a symlink at all. It retrieves
553 * status of a symlink itself.
554 * VC10: _wstat() supports a symlink to a normal file, but it doesn't
555 * support a symlink to a directory (always returns an error). */
556 int n;
557 BOOL is_symlink = FALSE;
558 HANDLE hFind, h;
559 DWORD attr = 0;
560 WIN32_FIND_DATAW findDataW;
561
562 hFind = FindFirstFileW(name, &findDataW);
563 if (hFind != INVALID_HANDLE_VALUE)
564 {
565 attr = findDataW.dwFileAttributes;
566 if ((attr & FILE_ATTRIBUTE_REPARSE_POINT)
567 && (findDataW.dwReserved0 == IO_REPARSE_TAG_SYMLINK))
568 is_symlink = TRUE;
569 FindClose(hFind);
570 }
571 if (is_symlink)
572 {
573 h = CreateFileW(name, FILE_READ_ATTRIBUTES,
574 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
575 OPEN_EXISTING,
576 (attr & FILE_ATTRIBUTE_DIRECTORY)
577 ? FILE_FLAG_BACKUP_SEMANTICS : 0,
578 NULL);
579 if (h != INVALID_HANDLE_VALUE)
580 {
581 int fd;
582
583 fd = _open_osfhandle((intptr_t)h, _O_RDONLY);
584 n = _fstat(fd, stp);
585 _close(fd);
586 return n;
587 }
588 }
589# endif
590 return _wstat(name, stp);
591}
592#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000593
594/*
595 * stat() can't handle a trailing '/' or '\', remove it first.
596 */
597 int
598vim_stat(const char *name, struct stat *stp)
599{
Bram Moolenaard2a203b2013-08-30 16:51:18 +0200600#ifdef FEAT_MBYTE
601 /* WinNT and later can use _MAX_PATH wide characters for a pathname, which
602 * means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
603 * UTF-8. */
604 char buf[_MAX_PATH * 3 + 1];
605#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000606 char buf[_MAX_PATH + 1];
Bram Moolenaard2a203b2013-08-30 16:51:18 +0200607#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608 char *p;
609
Bram Moolenaard2a203b2013-08-30 16:51:18 +0200610 vim_strncpy((char_u *)buf, (char_u *)name, sizeof(buf) - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000611 p = buf + strlen(buf);
612 if (p > buf)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000613 mb_ptr_back(buf, p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614 if (p > buf && (*p == '\\' || *p == '/') && p[-1] != ':')
615 *p = NUL;
616#ifdef FEAT_MBYTE
617 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
618# ifdef __BORLANDC__
619 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
620 && g_PlatformId == VER_PLATFORM_WIN32_NT
621# endif
622 )
623 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000624 WCHAR *wp = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000625 int n;
626
627 if (wp != NULL)
628 {
Bram Moolenaar2ee95f72013-09-25 19:13:38 +0200629 n = wstat_symlink_aware(wp, (struct _stat *)stp);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 vim_free(wp);
631 if (n >= 0)
632 return n;
633 /* Retry with non-wide function (for Windows 98). Can't use
634 * GetLastError() here and it's unclear what errno gets set to if
635 * the _wstat() fails for missing wide functions. */
636 }
637 }
638#endif
Bram Moolenaar2ee95f72013-09-25 19:13:38 +0200639 return stat_symlink_aware(buf, stp);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640}
641
642#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000643/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000644 void
645mch_settmode(int tmode)
646{
647 /* nothing to do */
648}
649
650 int
651mch_get_shellsize(void)
652{
653 /* never used */
654 return OK;
655}
656
657 void
658mch_set_shellsize(void)
659{
660 /* never used */
661}
662
663/*
664 * Rows and/or Columns has changed.
665 */
666 void
667mch_new_shellsize(void)
668{
669 /* never used */
670}
671
672#endif
673
674/*
675 * We have no job control, so fake it by starting a new shell.
676 */
677 void
678mch_suspend()
679{
680 suspend_shell();
681}
682
683#if defined(USE_MCH_ERRMSG) || defined(PROTO)
684
685#ifdef display_errors
686# undef display_errors
687#endif
688
689/*
690 * Display the saved error message(s).
691 */
692 void
693display_errors()
694{
695 char *p;
696
697 if (error_ga.ga_data != NULL)
698 {
699 /* avoid putting up a message box with blanks only */
700 for (p = (char *)error_ga.ga_data; *p; ++p)
701 if (!isspace(*p))
702 {
Bram Moolenaarc17ef8e2006-03-25 21:48:58 +0000703 (void)gui_mch_dialog(
704#ifdef FEAT_GUI
705 gui.starting ? VIM_INFO :
706#endif
707 VIM_ERROR,
708#ifdef FEAT_GUI
709 gui.starting ? (char_u *)_("Message") :
710#endif
711 (char_u *)_("Error"),
Bram Moolenaard2c340a2011-01-17 20:08:11 +0100712 p, (char_u *)_("&Ok"), 1, NULL, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713 break;
714 }
715 ga_clear(&error_ga);
716 }
717}
718#endif
719
720
721/*
722 * Return TRUE if "p" contain a wildcard that can be expanded by
723 * dos_expandpath().
724 */
725 int
726mch_has_exp_wildcard(char_u *p)
727{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000728 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000729 {
730 if (vim_strchr((char_u *)"?*[", *p) != NULL
731 || (*p == '~' && p[1] != NUL))
732 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000733 }
734 return FALSE;
735}
736
737/*
738 * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a
739 * shortened file name).
740 */
741 int
742mch_has_wildcard(char_u *p)
743{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000744 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000745 {
746 if (vim_strchr((char_u *)
747# ifdef VIM_BACKTICK
748 "?*$[`"
749# else
750 "?*$["
751# endif
752 , *p) != NULL
753 || (*p == '~' && p[1] != NUL))
754 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 }
756 return FALSE;
757}
758
759
760/*
761 * The normal _chdir() does not change the default drive. This one does.
762 * Returning 0 implies success; -1 implies failure.
763 */
764 int
765mch_chdir(char *path)
766{
767 if (path[0] == NUL) /* just checking... */
768 return -1;
769
Bram Moolenaara2974d72009-07-14 16:38:36 +0000770 if (p_verbose >= 5)
771 {
772 verbose_enter();
773 smsg((char_u *)"chdir(%s)", path);
774 verbose_leave();
775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000776 if (isalpha(path[0]) && path[1] == ':') /* has a drive name */
777 {
778 /* If we can change to the drive, skip that part of the path. If we
779 * can't then the current directory may be invalid, try using chdir()
780 * with the whole path. */
781 if (_chdrive(TOLOWER_ASC(path[0]) - 'a' + 1) == 0)
782 path += 2;
783 }
784
785 if (*path == NUL) /* drive name only */
786 return 0;
787
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000788#ifdef FEAT_MBYTE
789 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
790 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000791 WCHAR *p = enc_to_utf16(path, NULL);
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000792 int n;
793
794 if (p != NULL)
795 {
796 n = _wchdir(p);
797 vim_free(p);
798 if (n == 0)
799 return 0;
800 /* Retry with non-wide function (for Windows 98). */
801 }
802 }
803#endif
804
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805 return chdir(path); /* let the normal chdir() do the rest */
806}
807
808
809/*
810 * Switching off termcap mode is only allowed when Columns is 80, otherwise a
811 * crash may result. It's always allowed on NT or when running the GUI.
812 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000813/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000814 int
815can_end_termcap_mode(
816 int give_msg)
817{
818#ifdef FEAT_GUI_MSWIN
819 return TRUE; /* GUI starts a new console anyway */
820#else
821 if (g_PlatformId == VER_PLATFORM_WIN32_NT || Columns == 80)
822 return TRUE;
823 if (give_msg)
824 msg(_("'columns' is not 80, cannot execute external commands"));
825 return FALSE;
826#endif
827}
828
829#ifdef FEAT_GUI_MSWIN
830/*
831 * return non-zero if a character is available
832 */
833 int
834mch_char_avail()
835{
836 /* never used */
837 return TRUE;
838}
839#endif
840
841
842/*
843 * set screen mode, always fails.
844 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000845/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000846 int
847mch_screenmode(
848 char_u *arg)
849{
850 EMSG(_(e_screenmode));
851 return FAIL;
852}
853
854
855#if defined(FEAT_LIBCALL) || defined(PROTO)
856/*
857 * Call a DLL routine which takes either a string or int param
858 * and returns an allocated string.
859 * Return OK if it worked, FAIL if not.
860 */
861# ifdef WIN3264
862typedef LPTSTR (*MYSTRPROCSTR)(LPTSTR);
863typedef LPTSTR (*MYINTPROCSTR)(int);
864typedef int (*MYSTRPROCINT)(LPTSTR);
865typedef int (*MYINTPROCINT)(int);
866# else
867typedef LPSTR (*MYSTRPROCSTR)(LPSTR);
868typedef LPSTR (*MYINTPROCSTR)(int);
869typedef int (*MYSTRPROCINT)(LPSTR);
870typedef int (*MYINTPROCINT)(int);
871# endif
872
873# ifndef WIN16
874/*
875 * Check if a pointer points to a valid NUL terminated string.
876 * Return the length of the string, including terminating NUL.
877 * Returns 0 for an invalid pointer, 1 for an empty string.
878 */
879 static size_t
880check_str_len(char_u *str)
881{
882 SYSTEM_INFO si;
883 MEMORY_BASIC_INFORMATION mbi;
884 size_t length = 0;
885 size_t i;
886 const char *p;
887
888 /* get page size */
889 GetSystemInfo(&si);
890
891 /* get memory information */
892 if (VirtualQuery(str, &mbi, sizeof(mbi)))
893 {
894 /* pre cast these (typing savers) */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000895 long_u dwStr = (long_u)str;
896 long_u dwBaseAddress = (long_u)mbi.BaseAddress;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897
898 /* get start address of page that str is on */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000899 long_u strPage = dwStr - (dwStr - dwBaseAddress) % si.dwPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000900
901 /* get length from str to end of page */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000902 long_u pageLength = si.dwPageSize - (dwStr - strPage);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000903
Bram Moolenaar442b4222010-05-24 21:34:22 +0200904 for (p = str; !IsBadReadPtr(p, (UINT)pageLength);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905 p += pageLength, pageLength = si.dwPageSize)
906 for (i = 0; i < pageLength; ++i, ++length)
907 if (p[i] == NUL)
908 return length + 1;
909 }
910
911 return 0;
912}
913# endif
914
915 int
916mch_libcall(
917 char_u *libname,
918 char_u *funcname,
919 char_u *argstring, /* NULL when using a argint */
920 int argint,
921 char_u **string_result,/* NULL when using number_result */
922 int *number_result)
923{
924 HINSTANCE hinstLib;
925 MYSTRPROCSTR ProcAdd;
926 MYINTPROCSTR ProcAddI;
927 char_u *retval_str = NULL;
928 int retval_int = 0;
929 size_t len;
930
931 BOOL fRunTimeLinkSuccess = FALSE;
932
933 // Get a handle to the DLL module.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200934# ifdef WIN16
Bram Moolenaar071d4272004-06-13 20:20:40 +0000935 hinstLib = LoadLibrary(libname);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200936# else
937 hinstLib = vimLoadLib(libname);
938# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000939
940 // If the handle is valid, try to get the function address.
941 if (hinstLib != NULL)
942 {
943#ifdef HAVE_TRY_EXCEPT
944 __try
945 {
946#endif
947 if (argstring != NULL)
948 {
949 /* Call with string argument */
950 ProcAdd = (MYSTRPROCSTR) GetProcAddress(hinstLib, funcname);
951 if ((fRunTimeLinkSuccess = (ProcAdd != NULL)) != 0)
952 {
953 if (string_result == NULL)
954 retval_int = ((MYSTRPROCINT)ProcAdd)(argstring);
955 else
956 retval_str = (ProcAdd)(argstring);
957 }
958 }
959 else
960 {
961 /* Call with number argument */
962 ProcAddI = (MYINTPROCSTR) GetProcAddress(hinstLib, funcname);
963 if ((fRunTimeLinkSuccess = (ProcAddI != NULL)) != 0)
964 {
965 if (string_result == NULL)
966 retval_int = ((MYINTPROCINT)ProcAddI)(argint);
967 else
968 retval_str = (ProcAddI)(argint);
969 }
970 }
971
972 // Save the string before we free the library.
973 // Assume that a "1" result is an illegal pointer.
974 if (string_result == NULL)
975 *number_result = retval_int;
976 else if (retval_str != NULL
977# ifdef WIN16
978 && retval_str != (char_u *)1
979 && retval_str != (char_u *)-1
980 && !IsBadStringPtr(retval_str, INT_MAX)
981 && (len = strlen(retval_str) + 1) > 0
982# else
983 && (len = check_str_len(retval_str)) > 0
984# endif
985 )
986 {
987 *string_result = lalloc((long_u)len, TRUE);
988 if (*string_result != NULL)
989 mch_memmove(*string_result, retval_str, len);
990 }
991
992#ifdef HAVE_TRY_EXCEPT
993 }
994 __except(EXCEPTION_EXECUTE_HANDLER)
995 {
996 if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW)
997 RESETSTKOFLW();
998 fRunTimeLinkSuccess = 0;
999 }
1000#endif
1001
1002 // Free the DLL module.
1003 (void)FreeLibrary(hinstLib);
1004 }
1005
1006 if (!fRunTimeLinkSuccess)
1007 {
1008 EMSG2(_(e_libcall), funcname);
1009 return FAIL;
1010 }
1011
1012 return OK;
1013}
1014#endif
1015
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016/*
1017 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
1018 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001019/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001020 void
1021DumpPutS(
1022 const char *psz)
1023{
1024# ifdef MCH_WRITE_DUMP
1025 if (fdDump)
1026 {
1027 fputs(psz, fdDump);
1028 if (psz[strlen(psz) - 1] != '\n')
1029 fputc('\n', fdDump);
1030 fflush(fdDump);
1031 }
1032# endif
1033}
1034
1035#ifdef _DEBUG
1036
1037void __cdecl
1038Trace(
1039 char *pszFormat,
1040 ...)
1041{
1042 CHAR szBuff[2048];
1043 va_list args;
1044
1045 va_start(args, pszFormat);
1046 vsprintf(szBuff, pszFormat, args);
1047 va_end(args);
1048
1049 OutputDebugString(szBuff);
1050}
1051
1052#endif //_DEBUG
1053
Bram Moolenaar843ee412004-06-30 16:16:41 +00001054#if !defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001055# if defined(FEAT_TITLE) && defined(WIN3264)
1056extern HWND g_hWnd; /* This is in os_win32.c. */
1057# endif
1058
1059/*
1060 * Showing the printer dialog is tricky since we have no GUI
1061 * window to parent it. The following routines are needed to
1062 * get the window parenting and Z-order to work properly.
1063 */
1064 static void
1065GetConsoleHwnd(void)
1066{
1067# define MY_BUFSIZE 1024 // Buffer size for console window titles.
1068
1069 char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
1070 char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
1071
1072 /* Skip if it's already set. */
1073 if (s_hwnd != 0)
1074 return;
1075
1076# if defined(FEAT_TITLE) && defined(WIN3264)
1077 /* Window handle may have been found by init code (Windows NT only) */
1078 if (g_hWnd != 0)
1079 {
1080 s_hwnd = g_hWnd;
1081 return;
1082 }
1083# endif
1084
1085 GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
1086
1087 wsprintf(pszNewWindowTitle, "%s/%d/%d",
1088 pszOldWindowTitle,
1089 GetTickCount(),
1090 GetCurrentProcessId());
1091 SetConsoleTitle(pszNewWindowTitle);
1092 Sleep(40);
1093 s_hwnd = FindWindow(NULL, pszNewWindowTitle);
1094
1095 SetConsoleTitle(pszOldWindowTitle);
1096}
Bram Moolenaar843ee412004-06-30 16:16:41 +00001097
1098/*
1099 * Console implementation of ":winpos".
1100 */
1101 int
1102mch_get_winpos(int *x, int *y)
1103{
1104 RECT rect;
1105
1106 GetConsoleHwnd();
1107 GetWindowRect(s_hwnd, &rect);
1108 *x = rect.left;
1109 *y = rect.top;
1110 return OK;
1111}
1112
1113/*
1114 * Console implementation of ":winpos x y".
1115 */
1116 void
1117mch_set_winpos(int x, int y)
1118{
1119 GetConsoleHwnd();
1120 SetWindowPos(s_hwnd, NULL, x, y, 0, 0,
1121 SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1122}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123#endif
1124
1125#if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1126
1127# ifdef WIN16
1128# define TEXT(a) a
1129# endif
1130/*=================================================================
1131 * Win32 printer stuff
1132 */
1133
1134static HFONT prt_font_handles[2][2][2];
1135static PRINTDLG prt_dlg;
1136static const int boldface[2] = {FW_REGULAR, FW_BOLD};
1137static TEXTMETRIC prt_tm;
1138static int prt_line_height;
1139static int prt_number_width;
1140static int prt_left_margin;
1141static int prt_right_margin;
1142static int prt_top_margin;
1143static char_u szAppName[] = TEXT("VIM");
1144static HWND hDlgPrint;
1145static int *bUserAbort = NULL;
1146static char_u *prt_name = NULL;
1147
1148/* Defines which are also in vim.rc. */
1149#define IDC_BOX1 400
1150#define IDC_PRINTTEXT1 401
1151#define IDC_PRINTTEXT2 402
1152#define IDC_PROGRESS 403
1153
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001154#if !defined(FEAT_MBYTE) || defined(WIN16)
1155# define vimSetDlgItemText(h, i, s) SetDlgItemText(h, i, s)
1156#else
1157 static BOOL
1158vimSetDlgItemText(HWND hDlg, int nIDDlgItem, char_u *s)
1159{
1160 WCHAR *wp = NULL;
1161 BOOL ret;
1162
1163 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1164 {
1165 wp = enc_to_utf16(s, NULL);
1166 }
1167 if (wp != NULL)
1168 {
1169 ret = SetDlgItemTextW(hDlg, nIDDlgItem, wp);
1170 vim_free(wp);
1171 return ret;
1172 }
1173 return SetDlgItemText(hDlg, nIDDlgItem, s);
1174}
1175#endif
1176
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177/*
1178 * Convert BGR to RGB for Windows GDI calls
1179 */
1180 static COLORREF
1181swap_me(COLORREF colorref)
1182{
1183 int temp;
1184 char *ptr = (char *)&colorref;
1185
1186 temp = *(ptr);
1187 *(ptr ) = *(ptr + 2);
1188 *(ptr + 2) = temp;
1189 return colorref;
1190}
1191
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001192/* Attempt to make this work for old and new compilers */
Bram Moolenaar9f733d12011-09-21 20:09:42 +02001193#if !defined(_WIN64) && (!defined(_MSC_VER) || _MSC_VER < 1300)
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001194# define PDP_RETVAL BOOL
1195#else
1196# define PDP_RETVAL INT_PTR
1197#endif
1198
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001199/*ARGSUSED*/
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001200 static PDP_RETVAL CALLBACK
Bram Moolenaar071d4272004-06-13 20:20:40 +00001201PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
1202{
1203#ifdef FEAT_GETTEXT
1204 NONCLIENTMETRICS nm;
1205 static HFONT hfont;
1206#endif
1207
1208 switch (message)
1209 {
1210 case WM_INITDIALOG:
1211#ifdef FEAT_GETTEXT
1212 nm.cbSize = sizeof(NONCLIENTMETRICS);
1213 if (SystemParametersInfo(
1214 SPI_GETNONCLIENTMETRICS,
1215 sizeof(NONCLIENTMETRICS),
1216 &nm,
1217 0))
1218 {
1219 char buff[MAX_PATH];
1220 int i;
1221
1222 /* Translate the dialog texts */
1223 hfont = CreateFontIndirect(&nm.lfMessageFont);
1224 for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++)
1225 {
1226 SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1);
1227 if (GetDlgItemText(hDlg,i, buff, sizeof(buff)))
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001228 vimSetDlgItemText(hDlg,i, _(buff));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001229 }
1230 SendDlgItemMessage(hDlg, IDCANCEL,
1231 WM_SETFONT, (WPARAM)hfont, 1);
1232 if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff)))
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001233 vimSetDlgItemText(hDlg,IDCANCEL, _(buff));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 }
1235#endif
1236 SetWindowText(hDlg, szAppName);
1237 if (prt_name != NULL)
1238 {
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001239 vimSetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001240 vim_free(prt_name);
1241 prt_name = NULL;
1242 }
1243 EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED);
1244#ifndef FEAT_GUI
1245 BringWindowToTop(s_hwnd);
1246#endif
1247 return TRUE;
1248
1249 case WM_COMMAND:
1250 *bUserAbort = TRUE;
1251 EnableWindow(GetParent(hDlg), TRUE);
1252 DestroyWindow(hDlg);
1253 hDlgPrint = NULL;
1254#ifdef FEAT_GETTEXT
1255 DeleteObject(hfont);
1256#endif
1257 return TRUE;
1258 }
1259 return FALSE;
1260}
1261
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001262/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001263 static BOOL CALLBACK
1264AbortProc(HDC hdcPrn, int iCode)
1265{
1266 MSG msg;
1267
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001268 while (!*bUserAbort && pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001269 {
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001270 if (!hDlgPrint || !pIsDialogMessage(hDlgPrint, &msg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001271 {
1272 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001273 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001274 }
1275 }
1276 return !*bUserAbort;
1277}
1278
1279#ifndef FEAT_GUI
1280
Bram Moolenaar26fdd7d2011-11-30 13:42:44 +01001281 static UINT_PTR CALLBACK
Bram Moolenaar071d4272004-06-13 20:20:40 +00001282PrintHookProc(
1283 HWND hDlg, // handle to dialog box
1284 UINT uiMsg, // message identifier
1285 WPARAM wParam, // message parameter
1286 LPARAM lParam // message parameter
1287 )
1288{
1289 HWND hwndOwner;
1290 RECT rc, rcDlg, rcOwner;
1291 PRINTDLG *pPD;
1292
1293 if (uiMsg == WM_INITDIALOG)
1294 {
1295 // Get the owner window and dialog box rectangles.
1296 if ((hwndOwner = GetParent(hDlg)) == NULL)
1297 hwndOwner = GetDesktopWindow();
1298
1299 GetWindowRect(hwndOwner, &rcOwner);
1300 GetWindowRect(hDlg, &rcDlg);
1301 CopyRect(&rc, &rcOwner);
1302
1303 // Offset the owner and dialog box rectangles so that
1304 // right and bottom values represent the width and
1305 // height, and then offset the owner again to discard
1306 // space taken up by the dialog box.
1307
1308 OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
1309 OffsetRect(&rc, -rc.left, -rc.top);
1310 OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
1311
1312 // The new position is the sum of half the remaining
1313 // space and the owner's original position.
1314
1315 SetWindowPos(hDlg,
1316 HWND_TOP,
1317 rcOwner.left + (rc.right / 2),
1318 rcOwner.top + (rc.bottom / 2),
1319 0, 0, // ignores size arguments
1320 SWP_NOSIZE);
1321
1322 /* tackle the printdlg copiesctrl problem */
1323 pPD = (PRINTDLG *)lParam;
1324 pPD->nCopies = (WORD)pPD->lCustData;
1325 SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE );
1326 /* Bring the window to top */
1327 BringWindowToTop(GetParent(hDlg));
1328 SetForegroundWindow(hDlg);
1329 }
1330
1331 return FALSE;
1332}
1333#endif
1334
1335 void
1336mch_print_cleanup(void)
1337{
1338 int pifItalic;
1339 int pifBold;
1340 int pifUnderline;
1341
1342 for (pifBold = 0; pifBold <= 1; pifBold++)
1343 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1344 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1345 DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]);
1346
1347 if (prt_dlg.hDC != NULL)
1348 DeleteDC(prt_dlg.hDC);
1349 if (!*bUserAbort)
1350 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1351}
1352
1353 static int
1354to_device_units(int idx, int dpi, int physsize, int offset, int def_number)
1355{
1356 int ret = 0;
1357 int u;
1358 int nr;
1359
1360 u = prt_get_unit(idx);
1361 if (u == PRT_UNIT_NONE)
1362 {
1363 u = PRT_UNIT_PERC;
1364 nr = def_number;
1365 }
1366 else
1367 nr = printer_opts[idx].number;
1368
1369 switch (u)
1370 {
1371 case PRT_UNIT_PERC:
1372 ret = (physsize * nr) / 100;
1373 break;
1374 case PRT_UNIT_INCH:
1375 ret = (nr * dpi);
1376 break;
1377 case PRT_UNIT_MM:
1378 ret = (nr * 10 * dpi) / 254;
1379 break;
1380 case PRT_UNIT_POINT:
1381 ret = (nr * 10 * dpi) / 720;
1382 break;
1383 }
1384
1385 if (ret < offset)
1386 return 0;
1387 else
1388 return ret - offset;
1389}
1390
1391 static int
1392prt_get_cpl(void)
1393{
1394 int hr;
1395 int phyw;
1396 int dvoff;
1397 int rev_offset;
1398 int dpi;
1399#ifdef WIN16
1400 POINT pagesize;
1401#endif
1402
1403 GetTextMetrics(prt_dlg.hDC, &prt_tm);
1404 prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading;
1405
1406 hr = GetDeviceCaps(prt_dlg.hDC, HORZRES);
1407#ifdef WIN16
1408 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1409 phyw = pagesize.x;
1410 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1411 dvoff = pagesize.x;
1412#else
1413 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH);
1414 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX);
1415#endif
1416 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX);
1417
1418 rev_offset = phyw - (dvoff + hr);
1419
1420 prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10);
1421 if (prt_use_number())
1422 {
1423 prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth;
1424 prt_left_margin += prt_number_width;
1425 }
1426 else
1427 prt_number_width = 0;
1428
1429 prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw,
1430 rev_offset, 5);
1431
1432 return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth;
1433}
1434
1435 static int
1436prt_get_lpp(void)
1437{
1438 int vr;
1439 int phyw;
1440 int dvoff;
1441 int rev_offset;
1442 int bottom_margin;
1443 int dpi;
1444#ifdef WIN16
1445 POINT pagesize;
1446#endif
1447
1448 vr = GetDeviceCaps(prt_dlg.hDC, VERTRES);
1449#ifdef WIN16
1450 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1451 phyw = pagesize.y;
1452 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1453 dvoff = pagesize.y;
1454#else
1455 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT);
1456 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY);
1457#endif
1458 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY);
1459
1460 rev_offset = phyw - (dvoff + vr);
1461
1462 prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5);
1463
1464 /* adjust top margin if there is a header */
1465 prt_top_margin += prt_line_height * prt_header_height();
1466
1467 bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw,
1468 rev_offset, 5);
1469
1470 return (bottom_margin - prt_top_margin) / prt_line_height;
1471}
1472
1473 int
1474mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
1475{
1476 static HGLOBAL stored_dm = NULL;
1477 static HGLOBAL stored_devn = NULL;
1478 static int stored_nCopies = 1;
1479 static int stored_nFlags = 0;
1480
1481 LOGFONT fLogFont;
1482 int pifItalic;
1483 int pifBold;
1484 int pifUnderline;
1485
1486 DEVMODE *mem;
1487 DEVNAMES *devname;
1488 int i;
1489
1490 bUserAbort = &(psettings->user_abort);
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02001491 vim_memset(&prt_dlg, 0, sizeof(PRINTDLG));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492 prt_dlg.lStructSize = sizeof(PRINTDLG);
1493#ifndef FEAT_GUI
1494 GetConsoleHwnd(); /* get value of s_hwnd */
1495#endif
1496 prt_dlg.hwndOwner = s_hwnd;
1497 prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
1498 if (!forceit)
1499 {
1500 prt_dlg.hDevMode = stored_dm;
1501 prt_dlg.hDevNames = stored_devn;
1502 prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog
1503#ifndef FEAT_GUI
1504 /*
1505 * Use hook to prevent console window being sent to back
1506 */
1507 prt_dlg.lpfnPrintHook = PrintHookProc;
1508 prt_dlg.Flags |= PD_ENABLEPRINTHOOK;
1509#endif
1510 prt_dlg.Flags |= stored_nFlags;
1511 }
1512
1513 /*
1514 * If bang present, return default printer setup with no dialog
1515 * never show dialog if we are running over telnet
1516 */
1517 if (forceit
1518#ifndef FEAT_GUI
1519 || !term_console
1520#endif
1521 )
1522 {
1523 prt_dlg.Flags |= PD_RETURNDEFAULT;
1524#ifdef WIN3264
1525 /*
1526 * MSDN suggests setting the first parameter to WINSPOOL for
1527 * NT, but NULL appears to work just as well.
1528 */
1529 if (*p_pdev != NUL)
1530 prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL);
1531 else
1532#endif
1533 {
1534 prt_dlg.Flags |= PD_RETURNDEFAULT;
1535 if (PrintDlg(&prt_dlg) == 0)
1536 goto init_fail_dlg;
1537 }
1538 }
1539 else if (PrintDlg(&prt_dlg) == 0)
1540 goto init_fail_dlg;
1541 else
1542 {
1543 /*
1544 * keep the previous driver context
1545 */
1546 stored_dm = prt_dlg.hDevMode;
1547 stored_devn = prt_dlg.hDevNames;
1548 stored_nFlags = prt_dlg.Flags;
1549 stored_nCopies = prt_dlg.nCopies;
1550 }
1551
1552 if (prt_dlg.hDC == NULL)
1553 {
1554 EMSG(_("E237: Printer selection failed"));
1555 mch_print_cleanup();
1556 return FALSE;
1557 }
1558
1559 /* Not all printer drivers report the support of color (or grey) in the
1560 * same way. Let's set has_color if there appears to be some way to print
1561 * more than B&W. */
1562 i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS);
1563 psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1
1564 || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1
1565 || i > 2 || i == -1);
1566
1567 /* Ensure all font styles are baseline aligned */
1568 SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT);
1569
1570 /*
1571 * On some windows systems the nCopies parameter is not
1572 * passed back correctly. It must be retrieved from the
1573 * hDevMode struct.
1574 */
1575 mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode);
1576 if (mem != NULL)
1577 {
1578#ifdef WIN3264
1579 if (mem->dmCopies != 1)
1580 stored_nCopies = mem->dmCopies;
1581#endif
1582 if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX))
1583 psettings->duplex = TRUE;
1584 if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR))
1585 psettings->has_color = TRUE;
1586 }
1587 GlobalUnlock(prt_dlg.hDevMode);
1588
1589 devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames);
1590 if (devname != 0)
1591 {
1592 char_u *printer_name = (char_u *)devname + devname->wDeviceOffset;
1593 char_u *port_name = (char_u *)devname +devname->wOutputOffset;
1594 char_u *text = _("to %s on %s");
1595
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00001596 prt_name = alloc((unsigned)(STRLEN(printer_name) + STRLEN(port_name)
1597 + STRLEN(text)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 if (prt_name != NULL)
1599 wsprintf(prt_name, text, printer_name, port_name);
1600 }
1601 GlobalUnlock(prt_dlg.hDevNames);
1602
1603 /*
1604 * Initialise the font according to 'printfont'
1605 */
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02001606 vim_memset(&fLogFont, 0, sizeof(fLogFont));
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001607 if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 {
1609 EMSG2(_("E613: Unknown printer font: %s"), p_pfn);
1610 mch_print_cleanup();
1611 return FALSE;
1612 }
1613
1614 for (pifBold = 0; pifBold <= 1; pifBold++)
1615 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1616 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1617 {
1618 fLogFont.lfWeight = boldface[pifBold];
1619 fLogFont.lfItalic = pifItalic;
1620 fLogFont.lfUnderline = pifUnderline;
1621 prt_font_handles[pifBold][pifItalic][pifUnderline]
1622 = CreateFontIndirect(&fLogFont);
1623 }
1624
1625 SetBkMode(prt_dlg.hDC, OPAQUE);
1626 SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]);
1627
1628 /*
1629 * Fill in the settings struct
1630 */
1631 psettings->chars_per_line = prt_get_cpl();
1632 psettings->lines_per_page = prt_get_lpp();
1633 psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE)
1634 ? prt_dlg.nCopies : 1;
1635 psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE)
1636 ? 1 : prt_dlg.nCopies;
1637
1638 if (psettings->n_collated_copies == 0)
1639 psettings->n_collated_copies = 1;
1640
1641 if (psettings->n_uncollated_copies == 0)
1642 psettings->n_uncollated_copies = 1;
1643
1644 psettings->jobname = jobname;
1645
1646 return TRUE;
1647
1648init_fail_dlg:
1649 {
1650 DWORD err = CommDlgExtendedError();
1651
1652 if (err)
1653 {
1654#ifdef WIN16
1655 char buf[20];
1656
1657 sprintf(buf, "%ld", err);
1658 EMSG2(_("E238: Print error: %s"), buf);
1659#else
1660 char_u *buf;
1661
1662 /* I suspect FormatMessage() doesn't work for values returned by
1663 * CommDlgExtendedError(). What does? */
1664 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1665 FORMAT_MESSAGE_FROM_SYSTEM |
1666 FORMAT_MESSAGE_IGNORE_INSERTS,
1667 NULL, err, 0, (LPTSTR)(&buf), 0, NULL);
1668 EMSG2(_("E238: Print error: %s"),
1669 buf == NULL ? (char_u *)_("Unknown") : buf);
1670 LocalFree((LPVOID)(buf));
1671#endif
1672 }
1673 else
1674 msg_clr_eos(); /* Maybe canceled */
1675
1676 mch_print_cleanup();
1677 return FALSE;
1678 }
1679}
1680
1681
1682 int
1683mch_print_begin(prt_settings_T *psettings)
1684{
1685 int ret;
1686 static DOCINFO di;
1687 char szBuffer[300];
1688
1689 hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"),
1690 prt_dlg.hwndOwner, PrintDlgProc);
1691#ifdef WIN16
1692 Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL);
1693#else
1694 SetAbortProc(prt_dlg.hDC, AbortProc);
1695#endif
1696 wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname));
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001697 vimSetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001698
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02001699 vim_memset(&di, 0, sizeof(DOCINFO));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001700 di.cbSize = sizeof(DOCINFO);
1701 di.lpszDocName = psettings->jobname;
1702 ret = StartDoc(prt_dlg.hDC, &di);
1703
1704#ifdef FEAT_GUI
1705 /* Give focus back to main window (when using MDI). */
1706 SetFocus(s_hwnd);
1707#endif
1708
1709 return (ret > 0);
1710}
1711
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001712/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001713 void
1714mch_print_end(prt_settings_T *psettings)
1715{
1716 EndDoc(prt_dlg.hDC);
1717 if (!*bUserAbort)
1718 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1719}
1720
1721 int
1722mch_print_end_page(void)
1723{
1724 return (EndPage(prt_dlg.hDC) > 0);
1725}
1726
1727 int
1728mch_print_begin_page(char_u *msg)
1729{
1730 if (msg != NULL)
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001731 vimSetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001732 return (StartPage(prt_dlg.hDC) > 0);
1733}
1734
1735 int
1736mch_print_blank_page(void)
1737{
1738 return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
1739}
1740
1741static int prt_pos_x = 0;
1742static int prt_pos_y = 0;
1743
1744 void
1745mch_print_start_line(margin, page_line)
1746 int margin;
1747 int page_line;
1748{
1749 if (margin)
1750 prt_pos_x = -prt_number_width;
1751 else
1752 prt_pos_x = 0;
1753 prt_pos_y = page_line * prt_line_height
1754 + prt_tm.tmAscent + prt_tm.tmExternalLeading;
1755}
1756
1757 int
1758mch_print_text_out(char_u *p, int len)
1759{
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001760#if defined(FEAT_PROPORTIONAL_FONTS) || (defined(FEAT_MBYTE) && !defined(WIN16))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001761 SIZE sz;
1762#endif
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001763#if defined(FEAT_MBYTE) && !defined(WIN16)
1764 WCHAR *wp = NULL;
1765 int wlen = len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001766
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001767 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1768 {
1769 wp = enc_to_utf16(p, &wlen);
1770 }
1771 if (wp != NULL)
1772 {
1773 int ret = FALSE;
1774
1775 TextOutW(prt_dlg.hDC, prt_pos_x + prt_left_margin,
1776 prt_pos_y + prt_top_margin, wp, wlen);
1777 GetTextExtentPoint32W(prt_dlg.hDC, wp, wlen, &sz);
1778 vim_free(wp);
1779 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
1780 /* This is wrong when printing spaces for a TAB. */
1781 if (p[len] != NUL)
1782 {
1783 wlen = MB_PTR2LEN(p + len);
1784 wp = enc_to_utf16(p + len, &wlen);
1785 if (wp != NULL)
1786 {
1787 GetTextExtentPoint32W(prt_dlg.hDC, wp, 1, &sz);
1788 ret = (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
1789 vim_free(wp);
1790 }
1791 }
1792 return ret;
1793 }
1794#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795 TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin,
1796 prt_pos_y + prt_top_margin, p, len);
1797#ifndef FEAT_PROPORTIONAL_FONTS
1798 prt_pos_x += len * prt_tm.tmAveCharWidth;
1799 return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth
1800 + prt_tm.tmOverhang > prt_right_margin);
1801#else
1802# ifdef WIN16
1803 GetTextExtentPoint(prt_dlg.hDC, p, len, &sz);
1804# else
1805 GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz);
1806# endif
1807 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
1808 /* This is wrong when printing spaces for a TAB. */
1809 if (p[len] == NUL)
1810 return FALSE;
1811# ifdef WIN16
1812 GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz);
1813# else
1814 GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz);
1815# endif
1816 return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
1817#endif
1818}
1819
1820 void
1821mch_print_set_font(int iBold, int iItalic, int iUnderline)
1822{
1823 SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]);
1824}
1825
1826 void
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001827mch_print_set_bg(long_u bgcol)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001828{
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001829 SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
1830 swap_me((COLORREF)bgcol)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001831 /*
1832 * With a white background we can draw characters transparent, which is
1833 * good for italic characters that overlap to the next char cell.
1834 */
1835 if (bgcol == 0xffffffUL)
1836 SetBkMode(prt_dlg.hDC, TRANSPARENT);
1837 else
1838 SetBkMode(prt_dlg.hDC, OPAQUE);
1839}
1840
1841 void
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001842mch_print_set_fg(long_u fgcol)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001843{
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001844 SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
1845 swap_me((COLORREF)fgcol)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846}
1847
1848#endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
1849
Bram Moolenaar58d98232005-07-23 22:25:46 +00001850
1851
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852#if defined(FEAT_SHORTCUT) || defined(PROTO)
Bram Moolenaar82881492012-11-20 16:53:39 +01001853# ifndef PROTO
1854# include <shlobj.h>
1855# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001856
1857/*
1858 * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
1859 * to and return that name in allocated memory.
1860 * Otherwise NULL is returned.
1861 */
1862 char_u *
1863mch_resolve_shortcut(char_u *fname)
1864{
1865 HRESULT hr;
1866 IShellLink *psl = NULL;
1867 IPersistFile *ppf = NULL;
1868 OLECHAR wsz[MAX_PATH];
1869 WIN32_FIND_DATA ffd; // we get those free of charge
Bram Moolenaar604729e2013-08-30 16:44:19 +02001870 CHAR buf[MAX_PATH]; // could have simply reused 'wsz'...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001871 char_u *rfname = NULL;
1872 int len;
Bram Moolenaar604729e2013-08-30 16:44:19 +02001873# ifdef FEAT_MBYTE
1874 IShellLinkW *pslw = NULL;
1875 WIN32_FIND_DATAW ffdw; // we get those free of charge
1876# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001877
1878 /* Check if the file name ends in ".lnk". Avoid calling
1879 * CoCreateInstance(), it's quite slow. */
1880 if (fname == NULL)
1881 return rfname;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001882 len = (int)STRLEN(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001883 if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
1884 return rfname;
1885
1886 CoInitialize(NULL);
1887
Bram Moolenaar604729e2013-08-30 16:44:19 +02001888# ifdef FEAT_MBYTE
1889 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1890 {
1891 // create a link manager object and request its interface
1892 hr = CoCreateInstance(
1893 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1894 &IID_IShellLinkW, (void**)&pslw);
1895 if (hr == S_OK)
1896 {
1897 WCHAR *p = enc_to_utf16(fname, NULL);
1898
1899 if (p != NULL)
1900 {
1901 // Get a pointer to the IPersistFile interface.
1902 hr = pslw->lpVtbl->QueryInterface(
1903 pslw, &IID_IPersistFile, (void**)&ppf);
1904 if (hr != S_OK)
1905 goto shortcut_errorw;
1906
1907 // "load" the name and resolve the link
1908 hr = ppf->lpVtbl->Load(ppf, p, STGM_READ);
1909 if (hr != S_OK)
1910 goto shortcut_errorw;
1911# if 0 // This makes Vim wait a long time if the target does not exist.
1912 hr = pslw->lpVtbl->Resolve(pslw, NULL, SLR_NO_UI);
1913 if (hr != S_OK)
1914 goto shortcut_errorw;
1915# endif
1916
1917 // Get the path to the link target.
1918 ZeroMemory(wsz, MAX_PATH * sizeof(WCHAR));
1919 hr = pslw->lpVtbl->GetPath(pslw, wsz, MAX_PATH, &ffdw, 0);
1920 if (hr == S_OK && wsz[0] != NUL)
1921 rfname = utf16_to_enc(wsz, NULL);
1922
1923shortcut_errorw:
1924 vim_free(p);
1925 if (hr == S_OK)
1926 goto shortcut_end;
1927 }
1928 }
1929 /* Retry with non-wide function (for Windows 98). */
1930 }
1931# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001932 // create a link manager object and request its interface
1933 hr = CoCreateInstance(
1934 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1935 &IID_IShellLink, (void**)&psl);
1936 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001937 goto shortcut_end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938
1939 // Get a pointer to the IPersistFile interface.
1940 hr = psl->lpVtbl->QueryInterface(
1941 psl, &IID_IPersistFile, (void**)&ppf);
1942 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001943 goto shortcut_end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001944
1945 // full path string must be in Unicode.
1946 MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
1947
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00001948 // "load" the name and resolve the link
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
1950 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001951 goto shortcut_end;
1952# if 0 // This makes Vim wait a long time if the target doesn't exist.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001953 hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
1954 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001955 goto shortcut_end;
1956# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957
1958 // Get the path to the link target.
1959 ZeroMemory(buf, MAX_PATH);
1960 hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
1961 if (hr == S_OK && buf[0] != NUL)
1962 rfname = vim_strsave(buf);
1963
Bram Moolenaar604729e2013-08-30 16:44:19 +02001964shortcut_end:
Bram Moolenaar071d4272004-06-13 20:20:40 +00001965 // Release all interface pointers (both belong to the same object)
1966 if (ppf != NULL)
1967 ppf->lpVtbl->Release(ppf);
1968 if (psl != NULL)
1969 psl->lpVtbl->Release(psl);
Bram Moolenaar604729e2013-08-30 16:44:19 +02001970# ifdef FEAT_MBYTE
1971 if (pslw != NULL)
1972 pslw->lpVtbl->Release(pslw);
1973# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001974
1975 CoUninitialize();
1976 return rfname;
1977}
1978#endif
1979
1980#if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
1981/*
1982 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
1983 */
1984 void
1985win32_set_foreground()
1986{
1987# ifndef FEAT_GUI
1988 GetConsoleHwnd(); /* get value of s_hwnd */
1989# endif
1990 if (s_hwnd != 0)
1991 SetForegroundWindow(s_hwnd);
1992}
1993#endif
1994
1995#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
1996/*
1997 * Client-server code for Vim
1998 *
1999 * Originally written by Paul Moore
2000 */
2001
2002/* In order to handle inter-process messages, we need to have a window. But
2003 * the functions in this module can be called before the main GUI window is
2004 * created (and may also be called in the console version, where there is no
2005 * GUI window at all).
2006 *
2007 * So we create a hidden window, and arrange to destroy it on exit.
2008 */
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002009HWND message_window = 0; /* window that's handling messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010
2011#define VIM_CLASSNAME "VIM_MESSAGES"
2012#define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
2013
2014/* Communication is via WM_COPYDATA messages. The message type is send in
2015 * the dwData parameter. Types are defined here. */
2016#define COPYDATA_KEYS 0
2017#define COPYDATA_REPLY 1
2018#define COPYDATA_EXPR 10
2019#define COPYDATA_RESULT 11
2020#define COPYDATA_ERROR_RESULT 12
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002021#define COPYDATA_ENCODING 20
Bram Moolenaar071d4272004-06-13 20:20:40 +00002022
2023/* This is a structure containing a server HWND and its name. */
2024struct server_id
2025{
2026 HWND hwnd;
2027 char_u *name;
2028};
2029
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002030/* Last received 'encoding' that the client uses. */
2031static char_u *client_enc = NULL;
2032
2033/*
2034 * Tell the other side what encoding we are using.
2035 * Errors are ignored.
2036 */
2037 static void
2038serverSendEnc(HWND target)
2039{
2040 COPYDATASTRUCT data;
2041
2042 data.dwData = COPYDATA_ENCODING;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002043#ifdef FEAT_MBYTE
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002044 data.cbData = (DWORD)STRLEN(p_enc) + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002045 data.lpData = p_enc;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002046#else
Bram Moolenaar8765a4a2010-07-27 22:41:43 +02002047 data.cbData = (DWORD)STRLEN("latin1") + 1;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002048 data.lpData = "latin1";
2049#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002050 (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2051 (LPARAM)(&data));
2052}
2053
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054/*
2055 * Clean up on exit. This destroys the hidden message window.
2056 */
2057 static void
2058#ifdef __BORLANDC__
2059 _RTLENTRYF
2060#endif
2061CleanUpMessaging(void)
2062{
2063 if (message_window != 0)
2064 {
2065 DestroyWindow(message_window);
2066 message_window = 0;
2067 }
2068}
2069
2070static int save_reply(HWND server, char_u *reply, int expr);
2071
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002072/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 * The window procedure for the hidden message window.
2074 * It handles callback messages and notifications from servers.
2075 * In order to process these messages, it is necessary to run a
2076 * message loop. Code which may run before the main message loop
2077 * is started (in the GUI) is careful to pump messages when it needs
2078 * to. Features which require message delivery during normal use will
2079 * not work in the console version - this basically means those
2080 * features which allow Vim to act as a server, rather than a client.
2081 */
2082 static LRESULT CALLBACK
2083Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2084{
2085 if (msg == WM_COPYDATA)
2086 {
2087 /* This is a message from another Vim. The dwData member of the
2088 * COPYDATASTRUCT determines the type of message:
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002089 * COPYDATA_ENCODING:
2090 * The encoding that the client uses. Following messages will
2091 * use this encoding, convert if needed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 * COPYDATA_KEYS:
2093 * A key sequence. We are a server, and a client wants these keys
2094 * adding to the input queue.
2095 * COPYDATA_REPLY:
2096 * A reply. We are a client, and a server has sent this message
2097 * in response to a request. (server2client())
2098 * COPYDATA_EXPR:
2099 * An expression. We are a server, and a client wants us to
2100 * evaluate this expression.
2101 * COPYDATA_RESULT:
2102 * A reply. We are a client, and a server has sent this message
2103 * in response to a COPYDATA_EXPR.
2104 * COPYDATA_ERROR_RESULT:
2105 * A reply. We are a client, and a server has sent this message
2106 * in response to a COPYDATA_EXPR that failed to evaluate.
2107 */
2108 COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam;
2109 HWND sender = (HWND)wParam;
2110 COPYDATASTRUCT reply;
2111 char_u *res;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002112 int retval;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002113 char_u *str;
2114 char_u *tofree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002115
2116 switch (data->dwData)
2117 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002118 case COPYDATA_ENCODING:
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002119# ifdef FEAT_MBYTE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002120 /* Remember the encoding that the client uses. */
2121 vim_free(client_enc);
2122 client_enc = enc_canonize((char_u *)data->lpData);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002123# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002124 return 1;
2125
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 case COPYDATA_KEYS:
2127 /* Remember who sent this, for <client> */
2128 clientWindow = sender;
2129
2130 /* Add the received keys to the input buffer. The loop waiting
2131 * for the user to do something should check the input buffer. */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002132 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2133 server_to_input_buf(str);
2134 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002135
2136# ifdef FEAT_GUI
2137 /* Wake up the main GUI loop. */
2138 if (s_hwnd != 0)
2139 PostMessage(s_hwnd, WM_NULL, 0, 0);
2140# endif
2141 return 1;
2142
2143 case COPYDATA_EXPR:
2144 /* Remember who sent this, for <client> */
2145 clientWindow = sender;
2146
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002147 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2148 res = eval_client_expr_to_string(str);
2149 vim_free(tofree);
2150
Bram Moolenaar071d4272004-06-13 20:20:40 +00002151 if (res == NULL)
2152 {
2153 res = vim_strsave(_(e_invexprmsg));
2154 reply.dwData = COPYDATA_ERROR_RESULT;
2155 }
2156 else
2157 reply.dwData = COPYDATA_RESULT;
2158 reply.lpData = res;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002159 reply.cbData = (DWORD)STRLEN(res) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002160
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002161 serverSendEnc(sender);
Bram Moolenaar5246cd72013-06-16 16:41:47 +02002162 retval = (int)SendMessage(sender, WM_COPYDATA,
2163 (WPARAM)message_window, (LPARAM)(&reply));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002164 vim_free(res);
2165 return retval;
2166
2167 case COPYDATA_REPLY:
2168 case COPYDATA_RESULT:
2169 case COPYDATA_ERROR_RESULT:
2170 if (data->lpData != NULL)
2171 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002172 str = serverConvert(client_enc, (char_u *)data->lpData,
2173 &tofree);
2174 if (tofree == NULL)
2175 str = vim_strsave(str);
2176 if (save_reply(sender, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002177 (data->dwData == COPYDATA_REPLY ? 0 :
2178 (data->dwData == COPYDATA_RESULT ? 1 :
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002179 2))) == FAIL)
2180 vim_free(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002181#ifdef FEAT_AUTOCMD
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002182 else if (data->dwData == COPYDATA_REPLY)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002183 {
Bram Moolenaar427d51c2013-06-16 16:01:25 +02002184 char_u winstr[30];
2185
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002186 sprintf((char *)winstr, PRINTF_HEX_LONG_U, (long_u)sender);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002187 apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002188 TRUE, curbuf);
2189 }
2190#endif
2191 }
2192 return 1;
2193 }
2194
2195 return 0;
2196 }
2197
2198 else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2199 {
2200 /* When the message window is activated (brought to the foreground),
2201 * this actually applies to the text window. */
2202#ifndef FEAT_GUI
2203 GetConsoleHwnd(); /* get value of s_hwnd */
2204#endif
2205 if (s_hwnd != 0)
2206 {
2207 SetForegroundWindow(s_hwnd);
2208 return 0;
2209 }
2210 }
2211
2212 return DefWindowProc(hwnd, msg, wParam, lParam);
2213}
2214
2215/*
2216 * Initialise the message handling process. This involves creating a window
2217 * to handle messages - the window will not be visible.
2218 */
2219 void
2220serverInitMessaging(void)
2221{
2222 WNDCLASS wndclass;
2223 HINSTANCE s_hinst;
2224
2225 /* Clean up on exit */
2226 atexit(CleanUpMessaging);
2227
2228 /* Register a window class - we only really care
2229 * about the window procedure
2230 */
2231 s_hinst = (HINSTANCE)GetModuleHandle(0);
2232 wndclass.style = 0;
2233 wndclass.lpfnWndProc = Messaging_WndProc;
2234 wndclass.cbClsExtra = 0;
2235 wndclass.cbWndExtra = 0;
2236 wndclass.hInstance = s_hinst;
2237 wndclass.hIcon = NULL;
2238 wndclass.hCursor = NULL;
2239 wndclass.hbrBackground = NULL;
2240 wndclass.lpszMenuName = NULL;
2241 wndclass.lpszClassName = VIM_CLASSNAME;
2242 RegisterClass(&wndclass);
2243
2244 /* Create the message window. It will be hidden, so the details don't
2245 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2246 * focus from gvim. */
2247 message_window = CreateWindow(VIM_CLASSNAME, "",
2248 WS_POPUPWINDOW | WS_CAPTION,
2249 CW_USEDEFAULT, CW_USEDEFAULT,
2250 100, 100, NULL, NULL,
2251 s_hinst, NULL);
2252}
2253
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002254/* Used by serverSendToVim() to find an alternate server name. */
2255static char_u *altname_buf_ptr = NULL;
2256
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257/*
2258 * Get the title of the window "hwnd", which is the Vim server name, in
2259 * "name[namelen]" and return the length.
2260 * Returns zero if window "hwnd" is not a Vim server.
2261 */
2262 static int
2263getVimServerName(HWND hwnd, char *name, int namelen)
2264{
2265 int len;
2266 char buffer[VIM_CLASSNAME_LEN + 1];
2267
2268 /* Ignore windows which aren't Vim message windows */
2269 len = GetClassName(hwnd, buffer, sizeof(buffer));
2270 if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2271 return 0;
2272
2273 /* Get the title of the window */
2274 return GetWindowText(hwnd, name, namelen);
2275}
2276
2277 static BOOL CALLBACK
2278enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2279{
2280 struct server_id *id = (struct server_id *)lparam;
2281 char server[MAX_PATH];
2282
2283 /* Get the title of the window */
2284 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2285 return TRUE;
2286
2287 /* If this is the server we're looking for, return its HWND */
2288 if (STRICMP(server, id->name) == 0)
2289 {
2290 id->hwnd = hwnd;
2291 return FALSE;
2292 }
2293
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002294 /* If we are looking for an alternate server, remember this name. */
2295 if (altname_buf_ptr != NULL
2296 && STRNICMP(server, id->name, STRLEN(id->name)) == 0
2297 && vim_isdigit(server[STRLEN(id->name)]))
2298 {
2299 STRCPY(altname_buf_ptr, server);
2300 altname_buf_ptr = NULL; /* don't use another name */
2301 }
2302
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303 /* Otherwise, keep looking */
2304 return TRUE;
2305}
2306
2307 static BOOL CALLBACK
2308enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2309{
2310 garray_T *ga = (garray_T *)lparam;
2311 char server[MAX_PATH];
2312
2313 /* Get the title of the window */
2314 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2315 return TRUE;
2316
2317 /* Add the name to the list */
2318 ga_concat(ga, server);
2319 ga_concat(ga, "\n");
2320 return TRUE;
2321}
2322
2323 static HWND
2324findServer(char_u *name)
2325{
2326 struct server_id id;
2327
2328 id.name = name;
2329 id.hwnd = 0;
2330
2331 EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2332
2333 return id.hwnd;
2334}
2335
2336 void
2337serverSetName(char_u *name)
2338{
2339 char_u *ok_name;
2340 HWND hwnd = 0;
2341 int i = 0;
2342 char_u *p;
2343
2344 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002345 ok_name = alloc((unsigned)STRLEN(name) + 10);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346
2347 STRCPY(ok_name, name);
2348 p = ok_name + STRLEN(name);
2349
2350 for (;;)
2351 {
2352 /* This is inefficient - we're doing an EnumWindows loop for each
2353 * possible name. It would be better to grab all names in one go,
2354 * and scan the list each time...
2355 */
2356 hwnd = findServer(ok_name);
2357 if (hwnd == 0)
2358 break;
2359
2360 ++i;
2361 if (i >= 1000)
2362 break;
2363
2364 sprintf((char *)p, "%d", i);
2365 }
2366
2367 if (hwnd != 0)
2368 vim_free(ok_name);
2369 else
2370 {
2371 /* Remember the name */
2372 serverName = ok_name;
2373#ifdef FEAT_TITLE
2374 need_maketitle = TRUE; /* update Vim window title later */
2375#endif
2376
2377 /* Update the message window title */
2378 SetWindowText(message_window, ok_name);
2379
2380#ifdef FEAT_EVAL
2381 /* Set the servername variable */
2382 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2383#endif
2384 }
2385}
2386
2387 char_u *
2388serverGetVimNames(void)
2389{
2390 garray_T ga;
2391
2392 ga_init2(&ga, 1, 100);
2393
2394 EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
Bram Moolenaar269ec652004-07-29 08:43:53 +00002395 ga_append(&ga, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396
2397 return ga.ga_data;
2398}
2399
2400 int
2401serverSendReply(name, reply)
2402 char_u *name; /* Where to send. */
2403 char_u *reply; /* What to send. */
2404{
2405 HWND target;
2406 COPYDATASTRUCT data;
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002407 long_u n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002408
2409 /* The "name" argument is a magic cookie obtained from expand("<client>").
2410 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2411 * value of the client's message window HWND.
2412 */
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002413 sscanf((char *)name, SCANF_HEX_LONG_U, &n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 if (n == 0)
2415 return -1;
2416
2417 target = (HWND)n;
2418 if (!IsWindow(target))
2419 return -1;
2420
2421 data.dwData = COPYDATA_REPLY;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002422 data.cbData = (DWORD)STRLEN(reply) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 data.lpData = reply;
2424
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002425 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002426 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2427 (LPARAM)(&data)))
2428 return 0;
2429
2430 return -1;
2431}
2432
2433 int
2434serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2435 char_u *name; /* Where to send. */
2436 char_u *cmd; /* What to send. */
2437 char_u **result; /* Result of eval'ed expression */
2438 void *ptarget; /* HWND of server */
2439 int asExpr; /* Expression or keys? */
2440 int silent; /* don't complain about no server */
2441{
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002442 HWND target;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 COPYDATASTRUCT data;
2444 char_u *retval = NULL;
2445 int retcode = 0;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002446 char_u altname_buf[MAX_PATH];
2447
2448 /* If the server name does not end in a digit then we look for an
2449 * alternate name. e.g. when "name" is GVIM the we may find GVIM2. */
2450 if (STRLEN(name) > 1 && !vim_isdigit(name[STRLEN(name) - 1]))
2451 altname_buf_ptr = altname_buf;
2452 altname_buf[0] = NUL;
2453 target = findServer(name);
2454 altname_buf_ptr = NULL;
2455 if (target == 0 && altname_buf[0] != NUL)
2456 /* Use another server name we found. */
2457 target = findServer(altname_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458
2459 if (target == 0)
2460 {
2461 if (!silent)
2462 EMSG2(_(e_noserver), name);
2463 return -1;
2464 }
2465
2466 if (ptarget)
2467 *(HWND *)ptarget = target;
2468
2469 data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002470 data.cbData = (DWORD)STRLEN(cmd) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002471 data.lpData = cmd;
2472
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002473 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2475 (LPARAM)(&data)) == 0)
2476 return -1;
2477
2478 if (asExpr)
2479 retval = serverGetReply(target, &retcode, TRUE, TRUE);
2480
2481 if (result == NULL)
2482 vim_free(retval);
2483 else
2484 *result = retval; /* Caller assumes responsibility for freeing */
2485
2486 return retcode;
2487}
2488
2489/*
2490 * Bring the server to the foreground.
2491 */
2492 void
2493serverForeground(name)
2494 char_u *name;
2495{
2496 HWND target = findServer(name);
2497
2498 if (target != 0)
2499 SetForegroundWindow(target);
2500}
2501
2502/* Replies from server need to be stored until the client picks them up via
2503 * remote_read(). So we maintain a list of server-id/reply pairs.
2504 * Note that there could be multiple replies from one server pending if the
2505 * client is slow picking them up.
2506 * We just store the replies in a simple list. When we remove an entry, we
2507 * move list entries down to fill the gap.
2508 * The server ID is simply the HWND.
2509 */
2510typedef struct
2511{
2512 HWND server; /* server window */
2513 char_u *reply; /* reply string */
2514 int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002515} reply_T;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002516
2517static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
2518
2519#define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
2520#define REPLY_COUNT (reply_list.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521
2522/* Flag which is used to wait for a reply */
2523static int reply_received = 0;
2524
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002525/*
2526 * Store a reply. "reply" must be allocated memory (or NULL).
2527 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 static int
2529save_reply(HWND server, char_u *reply, int expr)
2530{
2531 reply_T *rep;
2532
2533 if (ga_grow(&reply_list, 1) == FAIL)
2534 return FAIL;
2535
2536 rep = REPLY_ITEM(REPLY_COUNT);
2537 rep->server = server;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002538 rep->reply = reply;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539 rep->expr_result = expr;
2540 if (rep->reply == NULL)
2541 return FAIL;
2542
2543 ++REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002544 reply_received = 1;
2545 return OK;
2546}
2547
2548/*
2549 * Get a reply from server "server".
2550 * When "expr_res" is non NULL, get the result of an expression, otherwise a
2551 * server2client() message.
2552 * When non NULL, point to return code. 0 => OK, -1 => ERROR
2553 * If "remove" is TRUE, consume the message, the caller must free it then.
2554 * if "wait" is TRUE block until a message arrives (or the server exits).
2555 */
2556 char_u *
2557serverGetReply(HWND server, int *expr_res, int remove, int wait)
2558{
2559 int i;
2560 char_u *reply;
2561 reply_T *rep;
2562
2563 /* When waiting, loop until the message waiting for is received. */
2564 for (;;)
2565 {
2566 /* Reset this here, in case a message arrives while we are going
2567 * through the already received messages. */
2568 reply_received = 0;
2569
2570 for (i = 0; i < REPLY_COUNT; ++i)
2571 {
2572 rep = REPLY_ITEM(i);
2573 if (rep->server == server
2574 && ((rep->expr_result != 0) == (expr_res != NULL)))
2575 {
2576 /* Save the values we've found for later */
2577 reply = rep->reply;
2578 if (expr_res != NULL)
2579 *expr_res = rep->expr_result == 1 ? 0 : -1;
2580
2581 if (remove)
2582 {
2583 /* Move the rest of the list down to fill the gap */
2584 mch_memmove(rep, rep + 1,
2585 (REPLY_COUNT - i - 1) * sizeof(reply_T));
2586 --REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002587 }
2588
2589 /* Return the reply to the caller, who takes on responsibility
2590 * for freeing it if "remove" is TRUE. */
2591 return reply;
2592 }
2593 }
2594
2595 /* If we got here, we didn't find a reply. Return immediately if the
2596 * "wait" parameter isn't set. */
2597 if (!wait)
2598 break;
2599
2600 /* We need to wait for a reply. Enter a message loop until the
2601 * "reply_received" flag gets set. */
2602
2603 /* Loop until we receive a reply */
2604 while (reply_received == 0)
2605 {
2606 /* Wait for a SendMessage() call to us. This could be the reply
2607 * we are waiting for. Use a timeout of a second, to catch the
2608 * situation that the server died unexpectedly. */
2609 MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
2610
2611 /* If the server has died, give up */
2612 if (!IsWindow(server))
2613 return NULL;
2614
2615 serverProcessPendingMessages();
2616 }
2617 }
2618
2619 return NULL;
2620}
2621
2622/*
2623 * Process any messages in the Windows message queue.
2624 */
2625 void
2626serverProcessPendingMessages(void)
2627{
2628 MSG msg;
2629
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02002630 while (pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002631 {
2632 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02002633 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 }
2635}
2636
2637#endif /* FEAT_CLIENTSERVER */
2638
2639#if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
2640 || defined(PROTO)
2641
2642struct charset_pair
2643{
2644 char *name;
2645 BYTE charset;
2646};
2647
2648static struct charset_pair
2649charset_pairs[] =
2650{
2651 {"ANSI", ANSI_CHARSET},
2652 {"CHINESEBIG5", CHINESEBIG5_CHARSET},
2653 {"DEFAULT", DEFAULT_CHARSET},
2654 {"HANGEUL", HANGEUL_CHARSET},
2655 {"OEM", OEM_CHARSET},
2656 {"SHIFTJIS", SHIFTJIS_CHARSET},
2657 {"SYMBOL", SYMBOL_CHARSET},
2658#ifdef WIN3264
2659 {"ARABIC", ARABIC_CHARSET},
2660 {"BALTIC", BALTIC_CHARSET},
2661 {"EASTEUROPE", EASTEUROPE_CHARSET},
2662 {"GB2312", GB2312_CHARSET},
2663 {"GREEK", GREEK_CHARSET},
2664 {"HEBREW", HEBREW_CHARSET},
2665 {"JOHAB", JOHAB_CHARSET},
2666 {"MAC", MAC_CHARSET},
2667 {"RUSSIAN", RUSSIAN_CHARSET},
2668 {"THAI", THAI_CHARSET},
2669 {"TURKISH", TURKISH_CHARSET},
2670# if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
2671 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
2672 {"VIETNAMESE", VIETNAMESE_CHARSET},
2673# endif
2674#endif
2675 {NULL, 0}
2676};
2677
2678/*
2679 * Convert a charset ID to a name.
2680 * Return NULL when not recognized.
2681 */
2682 char *
2683charset_id2name(int id)
2684{
2685 struct charset_pair *cp;
2686
2687 for (cp = charset_pairs; cp->name != NULL; ++cp)
2688 if ((BYTE)id == cp->charset)
2689 break;
2690 return cp->name;
2691}
2692
2693static const LOGFONT s_lfDefault =
2694{
2695 -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2696 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2697 PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
2698 "Fixedsys" /* see _ReadVimIni */
2699};
2700
2701/* Initialise the "current height" to -12 (same as s_lfDefault) just
2702 * in case the user specifies a font in "guifont" with no size before a font
2703 * with an explicit size has been set. This defaults the size to this value
2704 * (-12 equates to roughly 9pt).
2705 */
2706int current_font_height = -12; /* also used in gui_w48.c */
2707
2708/* Convert a string representing a point size into pixels. The string should
2709 * be a positive decimal number, with an optional decimal point (eg, "12", or
2710 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
2711 * character is stored in *end. The flag "vertical" says whether this
2712 * calculation is for a vertical (height) size or a horizontal (width) one.
2713 */
2714 static int
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002715points_to_pixels(char_u *str, char_u **end, int vertical, long_i pprinter_dc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716{
2717 int pixels;
2718 int points = 0;
2719 int divisor = 0;
2720 HWND hwnd = (HWND)0;
2721 HDC hdc;
2722 HDC printer_dc = (HDC)pprinter_dc;
2723
2724 while (*str != NUL)
2725 {
2726 if (*str == '.' && divisor == 0)
2727 {
2728 /* Start keeping a divisor, for later */
2729 divisor = 1;
2730 }
2731 else
2732 {
2733 if (!VIM_ISDIGIT(*str))
2734 break;
2735
2736 points *= 10;
2737 points += *str - '0';
2738 divisor *= 10;
2739 }
2740 ++str;
2741 }
2742
2743 if (divisor == 0)
2744 divisor = 1;
2745
2746 if (printer_dc == NULL)
2747 {
2748 hwnd = GetDesktopWindow();
2749 hdc = GetWindowDC(hwnd);
2750 }
2751 else
2752 hdc = printer_dc;
2753
2754 pixels = MulDiv(points,
2755 GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
2756 72 * divisor);
2757
2758 if (printer_dc == NULL)
2759 ReleaseDC(hwnd, hdc);
2760
2761 *end = str;
2762 return pixels;
2763}
2764
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002765/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766 static int CALLBACK
2767font_enumproc(
2768 ENUMLOGFONT *elf,
2769 NEWTEXTMETRIC *ntm,
2770 int type,
2771 LPARAM lparam)
2772{
2773 /* Return value:
2774 * 0 = terminate now (monospace & ANSI)
2775 * 1 = continue, still no luck...
2776 * 2 = continue, but we have an acceptable LOGFONT
2777 * (monospace, not ANSI)
2778 * We use these values, as EnumFontFamilies returns 1 if the
2779 * callback function is never called. So, we check the return as
2780 * 0 = perfect, 2 = OK, 1 = no good...
2781 * It's not pretty, but it works!
2782 */
2783
2784 LOGFONT *lf = (LOGFONT *)(lparam);
2785
2786#ifndef FEAT_PROPORTIONAL_FONTS
2787 /* Ignore non-monospace fonts without further ado */
2788 if ((ntm->tmPitchAndFamily & 1) != 0)
2789 return 1;
2790#endif
2791
2792 /* Remember this LOGFONT as a "possible" */
2793 *lf = elf->elfLogFont;
2794
2795 /* Terminate the scan as soon as we find an ANSI font */
2796 if (lf->lfCharSet == ANSI_CHARSET
2797 || lf->lfCharSet == OEM_CHARSET
2798 || lf->lfCharSet == DEFAULT_CHARSET)
2799 return 0;
2800
2801 /* Continue the scan - we have a non-ANSI font */
2802 return 2;
2803}
2804
2805 static int
2806init_logfont(LOGFONT *lf)
2807{
2808 int n;
2809 HWND hwnd = GetDesktopWindow();
2810 HDC hdc = GetWindowDC(hwnd);
2811
2812 n = EnumFontFamilies(hdc,
2813 (LPCSTR)lf->lfFaceName,
2814 (FONTENUMPROC)font_enumproc,
2815 (LPARAM)lf);
2816
2817 ReleaseDC(hwnd, hdc);
2818
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002819 /* If we couldn't find a usable font, return failure */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820 if (n == 1)
2821 return FAIL;
2822
2823 /* Tidy up the rest of the LOGFONT structure. We set to a basic
2824 * font - get_logfont() sets bold, italic, etc based on the user's
2825 * input.
2826 */
2827 lf->lfHeight = current_font_height;
2828 lf->lfWidth = 0;
2829 lf->lfItalic = FALSE;
2830 lf->lfUnderline = FALSE;
2831 lf->lfStrikeOut = FALSE;
2832 lf->lfWeight = FW_NORMAL;
2833
2834 /* Return success */
2835 return OK;
2836}
2837
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002838/*
2839 * Get font info from "name" into logfont "lf".
2840 * Return OK for a valid name, FAIL otherwise.
2841 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002842 int
2843get_logfont(
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002844 LOGFONT *lf,
2845 char_u *name,
2846 HDC printer_dc,
2847 int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002848{
2849 char_u *p;
2850 int i;
2851 static LOGFONT *lastlf = NULL;
2852
2853 *lf = s_lfDefault;
2854 if (name == NULL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002855 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856
2857 if (STRCMP(name, "*") == 0)
2858 {
2859#if defined(FEAT_GUI_W32)
2860 CHOOSEFONT cf;
2861 /* if name is "*", bring up std font dialog: */
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02002862 vim_memset(&cf, 0, sizeof(cf));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863 cf.lStructSize = sizeof(cf);
2864 cf.hwndOwner = s_hwnd;
2865 cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
2866 if (lastlf != NULL)
2867 *lf = *lastlf;
2868 cf.lpLogFont = lf;
2869 cf.nFontType = 0 ; //REGULAR_FONTTYPE;
2870 if (ChooseFont(&cf))
2871 goto theend;
2872#else
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002873 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874#endif
2875 }
2876
2877 /*
2878 * Split name up, it could be <name>:h<height>:w<width> etc.
2879 */
2880 for (p = name; *p && *p != ':'; p++)
2881 {
2882 if (p - name + 1 > LF_FACESIZE)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002883 return FAIL; /* Name too long */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002884 lf->lfFaceName[p - name] = *p;
2885 }
2886 if (p != name)
2887 lf->lfFaceName[p - name] = NUL;
2888
2889 /* First set defaults */
2890 lf->lfHeight = -12;
2891 lf->lfWidth = 0;
2892 lf->lfWeight = FW_NORMAL;
2893 lf->lfItalic = FALSE;
2894 lf->lfUnderline = FALSE;
2895 lf->lfStrikeOut = FALSE;
2896
2897 /*
2898 * If the font can't be found, try replacing '_' by ' '.
2899 */
2900 if (init_logfont(lf) == FAIL)
2901 {
2902 int did_replace = FALSE;
2903
2904 for (i = 0; lf->lfFaceName[i]; ++i)
2905 if (lf->lfFaceName[i] == '_')
2906 {
2907 lf->lfFaceName[i] = ' ';
2908 did_replace = TRUE;
2909 }
2910 if (!did_replace || init_logfont(lf) == FAIL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002911 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912 }
2913
2914 while (*p == ':')
2915 p++;
2916
2917 /* Set the values found after ':' */
2918 while (*p)
2919 {
2920 switch (*p++)
2921 {
2922 case 'h':
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002923 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (long_i)printer_dc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 break;
2925 case 'w':
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002926 lf->lfWidth = points_to_pixels(p, &p, FALSE, (long_i)printer_dc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002927 break;
2928 case 'b':
2929#ifndef MSWIN16_FASTTEXT
2930 lf->lfWeight = FW_BOLD;
2931#endif
2932 break;
2933 case 'i':
2934#ifndef MSWIN16_FASTTEXT
2935 lf->lfItalic = TRUE;
2936#endif
2937 break;
2938 case 'u':
2939 lf->lfUnderline = TRUE;
2940 break;
2941 case 's':
2942 lf->lfStrikeOut = TRUE;
2943 break;
2944 case 'c':
2945 {
2946 struct charset_pair *cp;
2947
2948 for (cp = charset_pairs; cp->name != NULL; ++cp)
2949 if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
2950 {
2951 lf->lfCharSet = cp->charset;
2952 p += strlen(cp->name);
2953 break;
2954 }
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002955 if (cp->name == NULL && verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 {
Bram Moolenaar051b7822005-05-19 21:00:46 +00002957 vim_snprintf((char *)IObuff, IOSIZE,
2958 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002959 EMSG(IObuff);
2960 break;
2961 }
2962 break;
2963 }
2964 default:
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002965 if (verbose)
2966 {
Bram Moolenaar051b7822005-05-19 21:00:46 +00002967 vim_snprintf((char *)IObuff, IOSIZE,
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002968 _("E245: Illegal char '%c' in font name \"%s\""),
2969 p[-1], name);
2970 EMSG(IObuff);
2971 }
2972 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973 }
2974 while (*p == ':')
2975 p++;
2976 }
2977
2978#if defined(FEAT_GUI_W32)
2979theend:
2980#endif
2981 /* ron: init lastlf */
2982 if (printer_dc == NULL)
2983 {
2984 vim_free(lastlf);
2985 lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
2986 if (lastlf != NULL)
2987 mch_memmove(lastlf, lf, sizeof(LOGFONT));
2988 }
2989
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002990 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002991}
2992
2993#endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */