blob: 67b7960978388ed482f33066e640222715f772ab [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
501
502/*
503 * stat() can't handle a trailing '/' or '\', remove it first.
504 */
505 int
506vim_stat(const char *name, struct stat *stp)
507{
Bram Moolenaard2a203b2013-08-30 16:51:18 +0200508#ifdef FEAT_MBYTE
509 /* WinNT and later can use _MAX_PATH wide characters for a pathname, which
510 * means that the maximum pathname is _MAX_PATH * 3 bytes when 'enc' is
511 * UTF-8. */
512 char buf[_MAX_PATH * 3 + 1];
513#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000514 char buf[_MAX_PATH + 1];
Bram Moolenaard2a203b2013-08-30 16:51:18 +0200515#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000516 char *p;
517
Bram Moolenaard2a203b2013-08-30 16:51:18 +0200518 vim_strncpy((char_u *)buf, (char_u *)name, sizeof(buf) - 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519 p = buf + strlen(buf);
520 if (p > buf)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000521 mb_ptr_back(buf, p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000522 if (p > buf && (*p == '\\' || *p == '/') && p[-1] != ':')
523 *p = NUL;
524#ifdef FEAT_MBYTE
525 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
526# ifdef __BORLANDC__
527 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
528 && g_PlatformId == VER_PLATFORM_WIN32_NT
529# endif
530 )
531 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000532 WCHAR *wp = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533 int n;
534
535 if (wp != NULL)
536 {
537 n = _wstat(wp, (struct _stat *)stp);
538 vim_free(wp);
539 if (n >= 0)
540 return n;
541 /* Retry with non-wide function (for Windows 98). Can't use
542 * GetLastError() here and it's unclear what errno gets set to if
543 * the _wstat() fails for missing wide functions. */
544 }
545 }
546#endif
547 return stat(buf, stp);
548}
549
550#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000551/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552 void
553mch_settmode(int tmode)
554{
555 /* nothing to do */
556}
557
558 int
559mch_get_shellsize(void)
560{
561 /* never used */
562 return OK;
563}
564
565 void
566mch_set_shellsize(void)
567{
568 /* never used */
569}
570
571/*
572 * Rows and/or Columns has changed.
573 */
574 void
575mch_new_shellsize(void)
576{
577 /* never used */
578}
579
580#endif
581
582/*
583 * We have no job control, so fake it by starting a new shell.
584 */
585 void
586mch_suspend()
587{
588 suspend_shell();
589}
590
591#if defined(USE_MCH_ERRMSG) || defined(PROTO)
592
593#ifdef display_errors
594# undef display_errors
595#endif
596
597/*
598 * Display the saved error message(s).
599 */
600 void
601display_errors()
602{
603 char *p;
604
605 if (error_ga.ga_data != NULL)
606 {
607 /* avoid putting up a message box with blanks only */
608 for (p = (char *)error_ga.ga_data; *p; ++p)
609 if (!isspace(*p))
610 {
Bram Moolenaarc17ef8e2006-03-25 21:48:58 +0000611 (void)gui_mch_dialog(
612#ifdef FEAT_GUI
613 gui.starting ? VIM_INFO :
614#endif
615 VIM_ERROR,
616#ifdef FEAT_GUI
617 gui.starting ? (char_u *)_("Message") :
618#endif
619 (char_u *)_("Error"),
Bram Moolenaard2c340a2011-01-17 20:08:11 +0100620 p, (char_u *)_("&Ok"), 1, NULL, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000621 break;
622 }
623 ga_clear(&error_ga);
624 }
625}
626#endif
627
628
629/*
630 * Return TRUE if "p" contain a wildcard that can be expanded by
631 * dos_expandpath().
632 */
633 int
634mch_has_exp_wildcard(char_u *p)
635{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000636 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000637 {
638 if (vim_strchr((char_u *)"?*[", *p) != NULL
639 || (*p == '~' && p[1] != NUL))
640 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000641 }
642 return FALSE;
643}
644
645/*
646 * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a
647 * shortened file name).
648 */
649 int
650mch_has_wildcard(char_u *p)
651{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000652 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000653 {
654 if (vim_strchr((char_u *)
655# ifdef VIM_BACKTICK
656 "?*$[`"
657# else
658 "?*$["
659# endif
660 , *p) != NULL
661 || (*p == '~' && p[1] != NUL))
662 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000663 }
664 return FALSE;
665}
666
667
668/*
669 * The normal _chdir() does not change the default drive. This one does.
670 * Returning 0 implies success; -1 implies failure.
671 */
672 int
673mch_chdir(char *path)
674{
675 if (path[0] == NUL) /* just checking... */
676 return -1;
677
Bram Moolenaara2974d72009-07-14 16:38:36 +0000678 if (p_verbose >= 5)
679 {
680 verbose_enter();
681 smsg((char_u *)"chdir(%s)", path);
682 verbose_leave();
683 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684 if (isalpha(path[0]) && path[1] == ':') /* has a drive name */
685 {
686 /* If we can change to the drive, skip that part of the path. If we
687 * can't then the current directory may be invalid, try using chdir()
688 * with the whole path. */
689 if (_chdrive(TOLOWER_ASC(path[0]) - 'a' + 1) == 0)
690 path += 2;
691 }
692
693 if (*path == NUL) /* drive name only */
694 return 0;
695
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000696#ifdef FEAT_MBYTE
697 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
698 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000699 WCHAR *p = enc_to_utf16(path, NULL);
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000700 int n;
701
702 if (p != NULL)
703 {
704 n = _wchdir(p);
705 vim_free(p);
706 if (n == 0)
707 return 0;
708 /* Retry with non-wide function (for Windows 98). */
709 }
710 }
711#endif
712
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713 return chdir(path); /* let the normal chdir() do the rest */
714}
715
716
717/*
718 * Switching off termcap mode is only allowed when Columns is 80, otherwise a
719 * crash may result. It's always allowed on NT or when running the GUI.
720 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000721/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722 int
723can_end_termcap_mode(
724 int give_msg)
725{
726#ifdef FEAT_GUI_MSWIN
727 return TRUE; /* GUI starts a new console anyway */
728#else
729 if (g_PlatformId == VER_PLATFORM_WIN32_NT || Columns == 80)
730 return TRUE;
731 if (give_msg)
732 msg(_("'columns' is not 80, cannot execute external commands"));
733 return FALSE;
734#endif
735}
736
737#ifdef FEAT_GUI_MSWIN
738/*
739 * return non-zero if a character is available
740 */
741 int
742mch_char_avail()
743{
744 /* never used */
745 return TRUE;
746}
747#endif
748
749
750/*
751 * set screen mode, always fails.
752 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000753/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754 int
755mch_screenmode(
756 char_u *arg)
757{
758 EMSG(_(e_screenmode));
759 return FAIL;
760}
761
762
763#if defined(FEAT_LIBCALL) || defined(PROTO)
764/*
765 * Call a DLL routine which takes either a string or int param
766 * and returns an allocated string.
767 * Return OK if it worked, FAIL if not.
768 */
769# ifdef WIN3264
770typedef LPTSTR (*MYSTRPROCSTR)(LPTSTR);
771typedef LPTSTR (*MYINTPROCSTR)(int);
772typedef int (*MYSTRPROCINT)(LPTSTR);
773typedef int (*MYINTPROCINT)(int);
774# else
775typedef LPSTR (*MYSTRPROCSTR)(LPSTR);
776typedef LPSTR (*MYINTPROCSTR)(int);
777typedef int (*MYSTRPROCINT)(LPSTR);
778typedef int (*MYINTPROCINT)(int);
779# endif
780
781# ifndef WIN16
782/*
783 * Check if a pointer points to a valid NUL terminated string.
784 * Return the length of the string, including terminating NUL.
785 * Returns 0 for an invalid pointer, 1 for an empty string.
786 */
787 static size_t
788check_str_len(char_u *str)
789{
790 SYSTEM_INFO si;
791 MEMORY_BASIC_INFORMATION mbi;
792 size_t length = 0;
793 size_t i;
794 const char *p;
795
796 /* get page size */
797 GetSystemInfo(&si);
798
799 /* get memory information */
800 if (VirtualQuery(str, &mbi, sizeof(mbi)))
801 {
802 /* pre cast these (typing savers) */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000803 long_u dwStr = (long_u)str;
804 long_u dwBaseAddress = (long_u)mbi.BaseAddress;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805
806 /* get start address of page that str is on */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000807 long_u strPage = dwStr - (dwStr - dwBaseAddress) % si.dwPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000808
809 /* get length from str to end of page */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000810 long_u pageLength = si.dwPageSize - (dwStr - strPage);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000811
Bram Moolenaar442b4222010-05-24 21:34:22 +0200812 for (p = str; !IsBadReadPtr(p, (UINT)pageLength);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813 p += pageLength, pageLength = si.dwPageSize)
814 for (i = 0; i < pageLength; ++i, ++length)
815 if (p[i] == NUL)
816 return length + 1;
817 }
818
819 return 0;
820}
821# endif
822
823 int
824mch_libcall(
825 char_u *libname,
826 char_u *funcname,
827 char_u *argstring, /* NULL when using a argint */
828 int argint,
829 char_u **string_result,/* NULL when using number_result */
830 int *number_result)
831{
832 HINSTANCE hinstLib;
833 MYSTRPROCSTR ProcAdd;
834 MYINTPROCSTR ProcAddI;
835 char_u *retval_str = NULL;
836 int retval_int = 0;
837 size_t len;
838
839 BOOL fRunTimeLinkSuccess = FALSE;
840
841 // Get a handle to the DLL module.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200842# ifdef WIN16
Bram Moolenaar071d4272004-06-13 20:20:40 +0000843 hinstLib = LoadLibrary(libname);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200844# else
845 hinstLib = vimLoadLib(libname);
846# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847
848 // If the handle is valid, try to get the function address.
849 if (hinstLib != NULL)
850 {
851#ifdef HAVE_TRY_EXCEPT
852 __try
853 {
854#endif
855 if (argstring != NULL)
856 {
857 /* Call with string argument */
858 ProcAdd = (MYSTRPROCSTR) GetProcAddress(hinstLib, funcname);
859 if ((fRunTimeLinkSuccess = (ProcAdd != NULL)) != 0)
860 {
861 if (string_result == NULL)
862 retval_int = ((MYSTRPROCINT)ProcAdd)(argstring);
863 else
864 retval_str = (ProcAdd)(argstring);
865 }
866 }
867 else
868 {
869 /* Call with number argument */
870 ProcAddI = (MYINTPROCSTR) GetProcAddress(hinstLib, funcname);
871 if ((fRunTimeLinkSuccess = (ProcAddI != NULL)) != 0)
872 {
873 if (string_result == NULL)
874 retval_int = ((MYINTPROCINT)ProcAddI)(argint);
875 else
876 retval_str = (ProcAddI)(argint);
877 }
878 }
879
880 // Save the string before we free the library.
881 // Assume that a "1" result is an illegal pointer.
882 if (string_result == NULL)
883 *number_result = retval_int;
884 else if (retval_str != NULL
885# ifdef WIN16
886 && retval_str != (char_u *)1
887 && retval_str != (char_u *)-1
888 && !IsBadStringPtr(retval_str, INT_MAX)
889 && (len = strlen(retval_str) + 1) > 0
890# else
891 && (len = check_str_len(retval_str)) > 0
892# endif
893 )
894 {
895 *string_result = lalloc((long_u)len, TRUE);
896 if (*string_result != NULL)
897 mch_memmove(*string_result, retval_str, len);
898 }
899
900#ifdef HAVE_TRY_EXCEPT
901 }
902 __except(EXCEPTION_EXECUTE_HANDLER)
903 {
904 if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW)
905 RESETSTKOFLW();
906 fRunTimeLinkSuccess = 0;
907 }
908#endif
909
910 // Free the DLL module.
911 (void)FreeLibrary(hinstLib);
912 }
913
914 if (!fRunTimeLinkSuccess)
915 {
916 EMSG2(_(e_libcall), funcname);
917 return FAIL;
918 }
919
920 return OK;
921}
922#endif
923
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924/*
925 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
926 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000927/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000928 void
929DumpPutS(
930 const char *psz)
931{
932# ifdef MCH_WRITE_DUMP
933 if (fdDump)
934 {
935 fputs(psz, fdDump);
936 if (psz[strlen(psz) - 1] != '\n')
937 fputc('\n', fdDump);
938 fflush(fdDump);
939 }
940# endif
941}
942
943#ifdef _DEBUG
944
945void __cdecl
946Trace(
947 char *pszFormat,
948 ...)
949{
950 CHAR szBuff[2048];
951 va_list args;
952
953 va_start(args, pszFormat);
954 vsprintf(szBuff, pszFormat, args);
955 va_end(args);
956
957 OutputDebugString(szBuff);
958}
959
960#endif //_DEBUG
961
Bram Moolenaar843ee412004-06-30 16:16:41 +0000962#if !defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000963# if defined(FEAT_TITLE) && defined(WIN3264)
964extern HWND g_hWnd; /* This is in os_win32.c. */
965# endif
966
967/*
968 * Showing the printer dialog is tricky since we have no GUI
969 * window to parent it. The following routines are needed to
970 * get the window parenting and Z-order to work properly.
971 */
972 static void
973GetConsoleHwnd(void)
974{
975# define MY_BUFSIZE 1024 // Buffer size for console window titles.
976
977 char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
978 char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
979
980 /* Skip if it's already set. */
981 if (s_hwnd != 0)
982 return;
983
984# if defined(FEAT_TITLE) && defined(WIN3264)
985 /* Window handle may have been found by init code (Windows NT only) */
986 if (g_hWnd != 0)
987 {
988 s_hwnd = g_hWnd;
989 return;
990 }
991# endif
992
993 GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
994
995 wsprintf(pszNewWindowTitle, "%s/%d/%d",
996 pszOldWindowTitle,
997 GetTickCount(),
998 GetCurrentProcessId());
999 SetConsoleTitle(pszNewWindowTitle);
1000 Sleep(40);
1001 s_hwnd = FindWindow(NULL, pszNewWindowTitle);
1002
1003 SetConsoleTitle(pszOldWindowTitle);
1004}
Bram Moolenaar843ee412004-06-30 16:16:41 +00001005
1006/*
1007 * Console implementation of ":winpos".
1008 */
1009 int
1010mch_get_winpos(int *x, int *y)
1011{
1012 RECT rect;
1013
1014 GetConsoleHwnd();
1015 GetWindowRect(s_hwnd, &rect);
1016 *x = rect.left;
1017 *y = rect.top;
1018 return OK;
1019}
1020
1021/*
1022 * Console implementation of ":winpos x y".
1023 */
1024 void
1025mch_set_winpos(int x, int y)
1026{
1027 GetConsoleHwnd();
1028 SetWindowPos(s_hwnd, NULL, x, y, 0, 0,
1029 SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1030}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001031#endif
1032
1033#if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1034
1035# ifdef WIN16
1036# define TEXT(a) a
1037# endif
1038/*=================================================================
1039 * Win32 printer stuff
1040 */
1041
1042static HFONT prt_font_handles[2][2][2];
1043static PRINTDLG prt_dlg;
1044static const int boldface[2] = {FW_REGULAR, FW_BOLD};
1045static TEXTMETRIC prt_tm;
1046static int prt_line_height;
1047static int prt_number_width;
1048static int prt_left_margin;
1049static int prt_right_margin;
1050static int prt_top_margin;
1051static char_u szAppName[] = TEXT("VIM");
1052static HWND hDlgPrint;
1053static int *bUserAbort = NULL;
1054static char_u *prt_name = NULL;
1055
1056/* Defines which are also in vim.rc. */
1057#define IDC_BOX1 400
1058#define IDC_PRINTTEXT1 401
1059#define IDC_PRINTTEXT2 402
1060#define IDC_PROGRESS 403
1061
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001062#if !defined(FEAT_MBYTE) || defined(WIN16)
1063# define vimSetDlgItemText(h, i, s) SetDlgItemText(h, i, s)
1064#else
1065 static BOOL
1066vimSetDlgItemText(HWND hDlg, int nIDDlgItem, char_u *s)
1067{
1068 WCHAR *wp = NULL;
1069 BOOL ret;
1070
1071 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1072 {
1073 wp = enc_to_utf16(s, NULL);
1074 }
1075 if (wp != NULL)
1076 {
1077 ret = SetDlgItemTextW(hDlg, nIDDlgItem, wp);
1078 vim_free(wp);
1079 return ret;
1080 }
1081 return SetDlgItemText(hDlg, nIDDlgItem, s);
1082}
1083#endif
1084
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085/*
1086 * Convert BGR to RGB for Windows GDI calls
1087 */
1088 static COLORREF
1089swap_me(COLORREF colorref)
1090{
1091 int temp;
1092 char *ptr = (char *)&colorref;
1093
1094 temp = *(ptr);
1095 *(ptr ) = *(ptr + 2);
1096 *(ptr + 2) = temp;
1097 return colorref;
1098}
1099
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001100/* Attempt to make this work for old and new compilers */
Bram Moolenaar9f733d12011-09-21 20:09:42 +02001101#if !defined(_WIN64) && (!defined(_MSC_VER) || _MSC_VER < 1300)
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001102# define PDP_RETVAL BOOL
1103#else
1104# define PDP_RETVAL INT_PTR
1105#endif
1106
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001107/*ARGSUSED*/
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001108 static PDP_RETVAL CALLBACK
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
1110{
1111#ifdef FEAT_GETTEXT
1112 NONCLIENTMETRICS nm;
1113 static HFONT hfont;
1114#endif
1115
1116 switch (message)
1117 {
1118 case WM_INITDIALOG:
1119#ifdef FEAT_GETTEXT
1120 nm.cbSize = sizeof(NONCLIENTMETRICS);
1121 if (SystemParametersInfo(
1122 SPI_GETNONCLIENTMETRICS,
1123 sizeof(NONCLIENTMETRICS),
1124 &nm,
1125 0))
1126 {
1127 char buff[MAX_PATH];
1128 int i;
1129
1130 /* Translate the dialog texts */
1131 hfont = CreateFontIndirect(&nm.lfMessageFont);
1132 for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++)
1133 {
1134 SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1);
1135 if (GetDlgItemText(hDlg,i, buff, sizeof(buff)))
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001136 vimSetDlgItemText(hDlg,i, _(buff));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137 }
1138 SendDlgItemMessage(hDlg, IDCANCEL,
1139 WM_SETFONT, (WPARAM)hfont, 1);
1140 if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff)))
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001141 vimSetDlgItemText(hDlg,IDCANCEL, _(buff));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001142 }
1143#endif
1144 SetWindowText(hDlg, szAppName);
1145 if (prt_name != NULL)
1146 {
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001147 vimSetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001148 vim_free(prt_name);
1149 prt_name = NULL;
1150 }
1151 EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED);
1152#ifndef FEAT_GUI
1153 BringWindowToTop(s_hwnd);
1154#endif
1155 return TRUE;
1156
1157 case WM_COMMAND:
1158 *bUserAbort = TRUE;
1159 EnableWindow(GetParent(hDlg), TRUE);
1160 DestroyWindow(hDlg);
1161 hDlgPrint = NULL;
1162#ifdef FEAT_GETTEXT
1163 DeleteObject(hfont);
1164#endif
1165 return TRUE;
1166 }
1167 return FALSE;
1168}
1169
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001170/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001171 static BOOL CALLBACK
1172AbortProc(HDC hdcPrn, int iCode)
1173{
1174 MSG msg;
1175
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001176 while (!*bUserAbort && pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001177 {
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001178 if (!hDlgPrint || !pIsDialogMessage(hDlgPrint, &msg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001179 {
1180 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001181 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001182 }
1183 }
1184 return !*bUserAbort;
1185}
1186
1187#ifndef FEAT_GUI
1188
Bram Moolenaar26fdd7d2011-11-30 13:42:44 +01001189 static UINT_PTR CALLBACK
Bram Moolenaar071d4272004-06-13 20:20:40 +00001190PrintHookProc(
1191 HWND hDlg, // handle to dialog box
1192 UINT uiMsg, // message identifier
1193 WPARAM wParam, // message parameter
1194 LPARAM lParam // message parameter
1195 )
1196{
1197 HWND hwndOwner;
1198 RECT rc, rcDlg, rcOwner;
1199 PRINTDLG *pPD;
1200
1201 if (uiMsg == WM_INITDIALOG)
1202 {
1203 // Get the owner window and dialog box rectangles.
1204 if ((hwndOwner = GetParent(hDlg)) == NULL)
1205 hwndOwner = GetDesktopWindow();
1206
1207 GetWindowRect(hwndOwner, &rcOwner);
1208 GetWindowRect(hDlg, &rcDlg);
1209 CopyRect(&rc, &rcOwner);
1210
1211 // Offset the owner and dialog box rectangles so that
1212 // right and bottom values represent the width and
1213 // height, and then offset the owner again to discard
1214 // space taken up by the dialog box.
1215
1216 OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
1217 OffsetRect(&rc, -rc.left, -rc.top);
1218 OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
1219
1220 // The new position is the sum of half the remaining
1221 // space and the owner's original position.
1222
1223 SetWindowPos(hDlg,
1224 HWND_TOP,
1225 rcOwner.left + (rc.right / 2),
1226 rcOwner.top + (rc.bottom / 2),
1227 0, 0, // ignores size arguments
1228 SWP_NOSIZE);
1229
1230 /* tackle the printdlg copiesctrl problem */
1231 pPD = (PRINTDLG *)lParam;
1232 pPD->nCopies = (WORD)pPD->lCustData;
1233 SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE );
1234 /* Bring the window to top */
1235 BringWindowToTop(GetParent(hDlg));
1236 SetForegroundWindow(hDlg);
1237 }
1238
1239 return FALSE;
1240}
1241#endif
1242
1243 void
1244mch_print_cleanup(void)
1245{
1246 int pifItalic;
1247 int pifBold;
1248 int pifUnderline;
1249
1250 for (pifBold = 0; pifBold <= 1; pifBold++)
1251 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1252 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1253 DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]);
1254
1255 if (prt_dlg.hDC != NULL)
1256 DeleteDC(prt_dlg.hDC);
1257 if (!*bUserAbort)
1258 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1259}
1260
1261 static int
1262to_device_units(int idx, int dpi, int physsize, int offset, int def_number)
1263{
1264 int ret = 0;
1265 int u;
1266 int nr;
1267
1268 u = prt_get_unit(idx);
1269 if (u == PRT_UNIT_NONE)
1270 {
1271 u = PRT_UNIT_PERC;
1272 nr = def_number;
1273 }
1274 else
1275 nr = printer_opts[idx].number;
1276
1277 switch (u)
1278 {
1279 case PRT_UNIT_PERC:
1280 ret = (physsize * nr) / 100;
1281 break;
1282 case PRT_UNIT_INCH:
1283 ret = (nr * dpi);
1284 break;
1285 case PRT_UNIT_MM:
1286 ret = (nr * 10 * dpi) / 254;
1287 break;
1288 case PRT_UNIT_POINT:
1289 ret = (nr * 10 * dpi) / 720;
1290 break;
1291 }
1292
1293 if (ret < offset)
1294 return 0;
1295 else
1296 return ret - offset;
1297}
1298
1299 static int
1300prt_get_cpl(void)
1301{
1302 int hr;
1303 int phyw;
1304 int dvoff;
1305 int rev_offset;
1306 int dpi;
1307#ifdef WIN16
1308 POINT pagesize;
1309#endif
1310
1311 GetTextMetrics(prt_dlg.hDC, &prt_tm);
1312 prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading;
1313
1314 hr = GetDeviceCaps(prt_dlg.hDC, HORZRES);
1315#ifdef WIN16
1316 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1317 phyw = pagesize.x;
1318 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1319 dvoff = pagesize.x;
1320#else
1321 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH);
1322 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX);
1323#endif
1324 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX);
1325
1326 rev_offset = phyw - (dvoff + hr);
1327
1328 prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10);
1329 if (prt_use_number())
1330 {
1331 prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth;
1332 prt_left_margin += prt_number_width;
1333 }
1334 else
1335 prt_number_width = 0;
1336
1337 prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw,
1338 rev_offset, 5);
1339
1340 return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth;
1341}
1342
1343 static int
1344prt_get_lpp(void)
1345{
1346 int vr;
1347 int phyw;
1348 int dvoff;
1349 int rev_offset;
1350 int bottom_margin;
1351 int dpi;
1352#ifdef WIN16
1353 POINT pagesize;
1354#endif
1355
1356 vr = GetDeviceCaps(prt_dlg.hDC, VERTRES);
1357#ifdef WIN16
1358 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1359 phyw = pagesize.y;
1360 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1361 dvoff = pagesize.y;
1362#else
1363 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT);
1364 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY);
1365#endif
1366 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY);
1367
1368 rev_offset = phyw - (dvoff + vr);
1369
1370 prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5);
1371
1372 /* adjust top margin if there is a header */
1373 prt_top_margin += prt_line_height * prt_header_height();
1374
1375 bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw,
1376 rev_offset, 5);
1377
1378 return (bottom_margin - prt_top_margin) / prt_line_height;
1379}
1380
1381 int
1382mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
1383{
1384 static HGLOBAL stored_dm = NULL;
1385 static HGLOBAL stored_devn = NULL;
1386 static int stored_nCopies = 1;
1387 static int stored_nFlags = 0;
1388
1389 LOGFONT fLogFont;
1390 int pifItalic;
1391 int pifBold;
1392 int pifUnderline;
1393
1394 DEVMODE *mem;
1395 DEVNAMES *devname;
1396 int i;
1397
1398 bUserAbort = &(psettings->user_abort);
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02001399 vim_memset(&prt_dlg, 0, sizeof(PRINTDLG));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001400 prt_dlg.lStructSize = sizeof(PRINTDLG);
1401#ifndef FEAT_GUI
1402 GetConsoleHwnd(); /* get value of s_hwnd */
1403#endif
1404 prt_dlg.hwndOwner = s_hwnd;
1405 prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
1406 if (!forceit)
1407 {
1408 prt_dlg.hDevMode = stored_dm;
1409 prt_dlg.hDevNames = stored_devn;
1410 prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog
1411#ifndef FEAT_GUI
1412 /*
1413 * Use hook to prevent console window being sent to back
1414 */
1415 prt_dlg.lpfnPrintHook = PrintHookProc;
1416 prt_dlg.Flags |= PD_ENABLEPRINTHOOK;
1417#endif
1418 prt_dlg.Flags |= stored_nFlags;
1419 }
1420
1421 /*
1422 * If bang present, return default printer setup with no dialog
1423 * never show dialog if we are running over telnet
1424 */
1425 if (forceit
1426#ifndef FEAT_GUI
1427 || !term_console
1428#endif
1429 )
1430 {
1431 prt_dlg.Flags |= PD_RETURNDEFAULT;
1432#ifdef WIN3264
1433 /*
1434 * MSDN suggests setting the first parameter to WINSPOOL for
1435 * NT, but NULL appears to work just as well.
1436 */
1437 if (*p_pdev != NUL)
1438 prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL);
1439 else
1440#endif
1441 {
1442 prt_dlg.Flags |= PD_RETURNDEFAULT;
1443 if (PrintDlg(&prt_dlg) == 0)
1444 goto init_fail_dlg;
1445 }
1446 }
1447 else if (PrintDlg(&prt_dlg) == 0)
1448 goto init_fail_dlg;
1449 else
1450 {
1451 /*
1452 * keep the previous driver context
1453 */
1454 stored_dm = prt_dlg.hDevMode;
1455 stored_devn = prt_dlg.hDevNames;
1456 stored_nFlags = prt_dlg.Flags;
1457 stored_nCopies = prt_dlg.nCopies;
1458 }
1459
1460 if (prt_dlg.hDC == NULL)
1461 {
1462 EMSG(_("E237: Printer selection failed"));
1463 mch_print_cleanup();
1464 return FALSE;
1465 }
1466
1467 /* Not all printer drivers report the support of color (or grey) in the
1468 * same way. Let's set has_color if there appears to be some way to print
1469 * more than B&W. */
1470 i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS);
1471 psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1
1472 || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1
1473 || i > 2 || i == -1);
1474
1475 /* Ensure all font styles are baseline aligned */
1476 SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT);
1477
1478 /*
1479 * On some windows systems the nCopies parameter is not
1480 * passed back correctly. It must be retrieved from the
1481 * hDevMode struct.
1482 */
1483 mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode);
1484 if (mem != NULL)
1485 {
1486#ifdef WIN3264
1487 if (mem->dmCopies != 1)
1488 stored_nCopies = mem->dmCopies;
1489#endif
1490 if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX))
1491 psettings->duplex = TRUE;
1492 if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR))
1493 psettings->has_color = TRUE;
1494 }
1495 GlobalUnlock(prt_dlg.hDevMode);
1496
1497 devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames);
1498 if (devname != 0)
1499 {
1500 char_u *printer_name = (char_u *)devname + devname->wDeviceOffset;
1501 char_u *port_name = (char_u *)devname +devname->wOutputOffset;
1502 char_u *text = _("to %s on %s");
1503
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00001504 prt_name = alloc((unsigned)(STRLEN(printer_name) + STRLEN(port_name)
1505 + STRLEN(text)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001506 if (prt_name != NULL)
1507 wsprintf(prt_name, text, printer_name, port_name);
1508 }
1509 GlobalUnlock(prt_dlg.hDevNames);
1510
1511 /*
1512 * Initialise the font according to 'printfont'
1513 */
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02001514 vim_memset(&fLogFont, 0, sizeof(fLogFont));
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001515 if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516 {
1517 EMSG2(_("E613: Unknown printer font: %s"), p_pfn);
1518 mch_print_cleanup();
1519 return FALSE;
1520 }
1521
1522 for (pifBold = 0; pifBold <= 1; pifBold++)
1523 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1524 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1525 {
1526 fLogFont.lfWeight = boldface[pifBold];
1527 fLogFont.lfItalic = pifItalic;
1528 fLogFont.lfUnderline = pifUnderline;
1529 prt_font_handles[pifBold][pifItalic][pifUnderline]
1530 = CreateFontIndirect(&fLogFont);
1531 }
1532
1533 SetBkMode(prt_dlg.hDC, OPAQUE);
1534 SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]);
1535
1536 /*
1537 * Fill in the settings struct
1538 */
1539 psettings->chars_per_line = prt_get_cpl();
1540 psettings->lines_per_page = prt_get_lpp();
1541 psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE)
1542 ? prt_dlg.nCopies : 1;
1543 psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE)
1544 ? 1 : prt_dlg.nCopies;
1545
1546 if (psettings->n_collated_copies == 0)
1547 psettings->n_collated_copies = 1;
1548
1549 if (psettings->n_uncollated_copies == 0)
1550 psettings->n_uncollated_copies = 1;
1551
1552 psettings->jobname = jobname;
1553
1554 return TRUE;
1555
1556init_fail_dlg:
1557 {
1558 DWORD err = CommDlgExtendedError();
1559
1560 if (err)
1561 {
1562#ifdef WIN16
1563 char buf[20];
1564
1565 sprintf(buf, "%ld", err);
1566 EMSG2(_("E238: Print error: %s"), buf);
1567#else
1568 char_u *buf;
1569
1570 /* I suspect FormatMessage() doesn't work for values returned by
1571 * CommDlgExtendedError(). What does? */
1572 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1573 FORMAT_MESSAGE_FROM_SYSTEM |
1574 FORMAT_MESSAGE_IGNORE_INSERTS,
1575 NULL, err, 0, (LPTSTR)(&buf), 0, NULL);
1576 EMSG2(_("E238: Print error: %s"),
1577 buf == NULL ? (char_u *)_("Unknown") : buf);
1578 LocalFree((LPVOID)(buf));
1579#endif
1580 }
1581 else
1582 msg_clr_eos(); /* Maybe canceled */
1583
1584 mch_print_cleanup();
1585 return FALSE;
1586 }
1587}
1588
1589
1590 int
1591mch_print_begin(prt_settings_T *psettings)
1592{
1593 int ret;
1594 static DOCINFO di;
1595 char szBuffer[300];
1596
1597 hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"),
1598 prt_dlg.hwndOwner, PrintDlgProc);
1599#ifdef WIN16
1600 Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL);
1601#else
1602 SetAbortProc(prt_dlg.hDC, AbortProc);
1603#endif
1604 wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname));
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001605 vimSetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001606
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02001607 vim_memset(&di, 0, sizeof(DOCINFO));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 di.cbSize = sizeof(DOCINFO);
1609 di.lpszDocName = psettings->jobname;
1610 ret = StartDoc(prt_dlg.hDC, &di);
1611
1612#ifdef FEAT_GUI
1613 /* Give focus back to main window (when using MDI). */
1614 SetFocus(s_hwnd);
1615#endif
1616
1617 return (ret > 0);
1618}
1619
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001620/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621 void
1622mch_print_end(prt_settings_T *psettings)
1623{
1624 EndDoc(prt_dlg.hDC);
1625 if (!*bUserAbort)
1626 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1627}
1628
1629 int
1630mch_print_end_page(void)
1631{
1632 return (EndPage(prt_dlg.hDC) > 0);
1633}
1634
1635 int
1636mch_print_begin_page(char_u *msg)
1637{
1638 if (msg != NULL)
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001639 vimSetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 return (StartPage(prt_dlg.hDC) > 0);
1641}
1642
1643 int
1644mch_print_blank_page(void)
1645{
1646 return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
1647}
1648
1649static int prt_pos_x = 0;
1650static int prt_pos_y = 0;
1651
1652 void
1653mch_print_start_line(margin, page_line)
1654 int margin;
1655 int page_line;
1656{
1657 if (margin)
1658 prt_pos_x = -prt_number_width;
1659 else
1660 prt_pos_x = 0;
1661 prt_pos_y = page_line * prt_line_height
1662 + prt_tm.tmAscent + prt_tm.tmExternalLeading;
1663}
1664
1665 int
1666mch_print_text_out(char_u *p, int len)
1667{
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001668#if defined(FEAT_PROPORTIONAL_FONTS) || (defined(FEAT_MBYTE) && !defined(WIN16))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001669 SIZE sz;
1670#endif
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001671#if defined(FEAT_MBYTE) && !defined(WIN16)
1672 WCHAR *wp = NULL;
1673 int wlen = len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001674
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001675 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1676 {
1677 wp = enc_to_utf16(p, &wlen);
1678 }
1679 if (wp != NULL)
1680 {
1681 int ret = FALSE;
1682
1683 TextOutW(prt_dlg.hDC, prt_pos_x + prt_left_margin,
1684 prt_pos_y + prt_top_margin, wp, wlen);
1685 GetTextExtentPoint32W(prt_dlg.hDC, wp, wlen, &sz);
1686 vim_free(wp);
1687 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
1688 /* This is wrong when printing spaces for a TAB. */
1689 if (p[len] != NUL)
1690 {
1691 wlen = MB_PTR2LEN(p + len);
1692 wp = enc_to_utf16(p + len, &wlen);
1693 if (wp != NULL)
1694 {
1695 GetTextExtentPoint32W(prt_dlg.hDC, wp, 1, &sz);
1696 ret = (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
1697 vim_free(wp);
1698 }
1699 }
1700 return ret;
1701 }
1702#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001703 TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin,
1704 prt_pos_y + prt_top_margin, p, len);
1705#ifndef FEAT_PROPORTIONAL_FONTS
1706 prt_pos_x += len * prt_tm.tmAveCharWidth;
1707 return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth
1708 + prt_tm.tmOverhang > prt_right_margin);
1709#else
1710# ifdef WIN16
1711 GetTextExtentPoint(prt_dlg.hDC, p, len, &sz);
1712# else
1713 GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz);
1714# endif
1715 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
1716 /* This is wrong when printing spaces for a TAB. */
1717 if (p[len] == NUL)
1718 return FALSE;
1719# ifdef WIN16
1720 GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz);
1721# else
1722 GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz);
1723# endif
1724 return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
1725#endif
1726}
1727
1728 void
1729mch_print_set_font(int iBold, int iItalic, int iUnderline)
1730{
1731 SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]);
1732}
1733
1734 void
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001735mch_print_set_bg(long_u bgcol)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001736{
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001737 SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
1738 swap_me((COLORREF)bgcol)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001739 /*
1740 * With a white background we can draw characters transparent, which is
1741 * good for italic characters that overlap to the next char cell.
1742 */
1743 if (bgcol == 0xffffffUL)
1744 SetBkMode(prt_dlg.hDC, TRANSPARENT);
1745 else
1746 SetBkMode(prt_dlg.hDC, OPAQUE);
1747}
1748
1749 void
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001750mch_print_set_fg(long_u fgcol)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001751{
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001752 SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
1753 swap_me((COLORREF)fgcol)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754}
1755
1756#endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
1757
Bram Moolenaar58d98232005-07-23 22:25:46 +00001758
1759
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760#if defined(FEAT_SHORTCUT) || defined(PROTO)
Bram Moolenaar82881492012-11-20 16:53:39 +01001761# ifndef PROTO
1762# include <shlobj.h>
1763# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764
1765/*
1766 * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
1767 * to and return that name in allocated memory.
1768 * Otherwise NULL is returned.
1769 */
1770 char_u *
1771mch_resolve_shortcut(char_u *fname)
1772{
1773 HRESULT hr;
1774 IShellLink *psl = NULL;
1775 IPersistFile *ppf = NULL;
1776 OLECHAR wsz[MAX_PATH];
1777 WIN32_FIND_DATA ffd; // we get those free of charge
Bram Moolenaar604729e2013-08-30 16:44:19 +02001778 CHAR buf[MAX_PATH]; // could have simply reused 'wsz'...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001779 char_u *rfname = NULL;
1780 int len;
Bram Moolenaar604729e2013-08-30 16:44:19 +02001781# ifdef FEAT_MBYTE
1782 IShellLinkW *pslw = NULL;
1783 WIN32_FIND_DATAW ffdw; // we get those free of charge
1784# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001785
1786 /* Check if the file name ends in ".lnk". Avoid calling
1787 * CoCreateInstance(), it's quite slow. */
1788 if (fname == NULL)
1789 return rfname;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001790 len = (int)STRLEN(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001791 if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
1792 return rfname;
1793
1794 CoInitialize(NULL);
1795
Bram Moolenaar604729e2013-08-30 16:44:19 +02001796# ifdef FEAT_MBYTE
1797 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1798 {
1799 // create a link manager object and request its interface
1800 hr = CoCreateInstance(
1801 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1802 &IID_IShellLinkW, (void**)&pslw);
1803 if (hr == S_OK)
1804 {
1805 WCHAR *p = enc_to_utf16(fname, NULL);
1806
1807 if (p != NULL)
1808 {
1809 // Get a pointer to the IPersistFile interface.
1810 hr = pslw->lpVtbl->QueryInterface(
1811 pslw, &IID_IPersistFile, (void**)&ppf);
1812 if (hr != S_OK)
1813 goto shortcut_errorw;
1814
1815 // "load" the name and resolve the link
1816 hr = ppf->lpVtbl->Load(ppf, p, STGM_READ);
1817 if (hr != S_OK)
1818 goto shortcut_errorw;
1819# if 0 // This makes Vim wait a long time if the target does not exist.
1820 hr = pslw->lpVtbl->Resolve(pslw, NULL, SLR_NO_UI);
1821 if (hr != S_OK)
1822 goto shortcut_errorw;
1823# endif
1824
1825 // Get the path to the link target.
1826 ZeroMemory(wsz, MAX_PATH * sizeof(WCHAR));
1827 hr = pslw->lpVtbl->GetPath(pslw, wsz, MAX_PATH, &ffdw, 0);
1828 if (hr == S_OK && wsz[0] != NUL)
1829 rfname = utf16_to_enc(wsz, NULL);
1830
1831shortcut_errorw:
1832 vim_free(p);
1833 if (hr == S_OK)
1834 goto shortcut_end;
1835 }
1836 }
1837 /* Retry with non-wide function (for Windows 98). */
1838 }
1839# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001840 // create a link manager object and request its interface
1841 hr = CoCreateInstance(
1842 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1843 &IID_IShellLink, (void**)&psl);
1844 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001845 goto shortcut_end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001846
1847 // Get a pointer to the IPersistFile interface.
1848 hr = psl->lpVtbl->QueryInterface(
1849 psl, &IID_IPersistFile, (void**)&ppf);
1850 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001851 goto shortcut_end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852
1853 // full path string must be in Unicode.
1854 MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
1855
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00001856 // "load" the name and resolve the link
Bram Moolenaar071d4272004-06-13 20:20:40 +00001857 hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
1858 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001859 goto shortcut_end;
1860# if 0 // This makes Vim wait a long time if the target doesn't exist.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001861 hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
1862 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001863 goto shortcut_end;
1864# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001865
1866 // Get the path to the link target.
1867 ZeroMemory(buf, MAX_PATH);
1868 hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
1869 if (hr == S_OK && buf[0] != NUL)
1870 rfname = vim_strsave(buf);
1871
Bram Moolenaar604729e2013-08-30 16:44:19 +02001872shortcut_end:
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873 // Release all interface pointers (both belong to the same object)
1874 if (ppf != NULL)
1875 ppf->lpVtbl->Release(ppf);
1876 if (psl != NULL)
1877 psl->lpVtbl->Release(psl);
Bram Moolenaar604729e2013-08-30 16:44:19 +02001878# ifdef FEAT_MBYTE
1879 if (pslw != NULL)
1880 pslw->lpVtbl->Release(pslw);
1881# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001882
1883 CoUninitialize();
1884 return rfname;
1885}
1886#endif
1887
1888#if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
1889/*
1890 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
1891 */
1892 void
1893win32_set_foreground()
1894{
1895# ifndef FEAT_GUI
1896 GetConsoleHwnd(); /* get value of s_hwnd */
1897# endif
1898 if (s_hwnd != 0)
1899 SetForegroundWindow(s_hwnd);
1900}
1901#endif
1902
1903#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
1904/*
1905 * Client-server code for Vim
1906 *
1907 * Originally written by Paul Moore
1908 */
1909
1910/* In order to handle inter-process messages, we need to have a window. But
1911 * the functions in this module can be called before the main GUI window is
1912 * created (and may also be called in the console version, where there is no
1913 * GUI window at all).
1914 *
1915 * So we create a hidden window, and arrange to destroy it on exit.
1916 */
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001917HWND message_window = 0; /* window that's handling messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918
1919#define VIM_CLASSNAME "VIM_MESSAGES"
1920#define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
1921
1922/* Communication is via WM_COPYDATA messages. The message type is send in
1923 * the dwData parameter. Types are defined here. */
1924#define COPYDATA_KEYS 0
1925#define COPYDATA_REPLY 1
1926#define COPYDATA_EXPR 10
1927#define COPYDATA_RESULT 11
1928#define COPYDATA_ERROR_RESULT 12
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001929#define COPYDATA_ENCODING 20
Bram Moolenaar071d4272004-06-13 20:20:40 +00001930
1931/* This is a structure containing a server HWND and its name. */
1932struct server_id
1933{
1934 HWND hwnd;
1935 char_u *name;
1936};
1937
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001938/* Last received 'encoding' that the client uses. */
1939static char_u *client_enc = NULL;
1940
1941/*
1942 * Tell the other side what encoding we are using.
1943 * Errors are ignored.
1944 */
1945 static void
1946serverSendEnc(HWND target)
1947{
1948 COPYDATASTRUCT data;
1949
1950 data.dwData = COPYDATA_ENCODING;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001951#ifdef FEAT_MBYTE
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001952 data.cbData = (DWORD)STRLEN(p_enc) + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001953 data.lpData = p_enc;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001954#else
Bram Moolenaar8765a4a2010-07-27 22:41:43 +02001955 data.cbData = (DWORD)STRLEN("latin1") + 1;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001956 data.lpData = "latin1";
1957#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001958 (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
1959 (LPARAM)(&data));
1960}
1961
Bram Moolenaar071d4272004-06-13 20:20:40 +00001962/*
1963 * Clean up on exit. This destroys the hidden message window.
1964 */
1965 static void
1966#ifdef __BORLANDC__
1967 _RTLENTRYF
1968#endif
1969CleanUpMessaging(void)
1970{
1971 if (message_window != 0)
1972 {
1973 DestroyWindow(message_window);
1974 message_window = 0;
1975 }
1976}
1977
1978static int save_reply(HWND server, char_u *reply, int expr);
1979
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001980/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 * The window procedure for the hidden message window.
1982 * It handles callback messages and notifications from servers.
1983 * In order to process these messages, it is necessary to run a
1984 * message loop. Code which may run before the main message loop
1985 * is started (in the GUI) is careful to pump messages when it needs
1986 * to. Features which require message delivery during normal use will
1987 * not work in the console version - this basically means those
1988 * features which allow Vim to act as a server, rather than a client.
1989 */
1990 static LRESULT CALLBACK
1991Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1992{
1993 if (msg == WM_COPYDATA)
1994 {
1995 /* This is a message from another Vim. The dwData member of the
1996 * COPYDATASTRUCT determines the type of message:
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001997 * COPYDATA_ENCODING:
1998 * The encoding that the client uses. Following messages will
1999 * use this encoding, convert if needed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000 * COPYDATA_KEYS:
2001 * A key sequence. We are a server, and a client wants these keys
2002 * adding to the input queue.
2003 * COPYDATA_REPLY:
2004 * A reply. We are a client, and a server has sent this message
2005 * in response to a request. (server2client())
2006 * COPYDATA_EXPR:
2007 * An expression. We are a server, and a client wants us to
2008 * evaluate this expression.
2009 * COPYDATA_RESULT:
2010 * A reply. We are a client, and a server has sent this message
2011 * in response to a COPYDATA_EXPR.
2012 * COPYDATA_ERROR_RESULT:
2013 * A reply. We are a client, and a server has sent this message
2014 * in response to a COPYDATA_EXPR that failed to evaluate.
2015 */
2016 COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam;
2017 HWND sender = (HWND)wParam;
2018 COPYDATASTRUCT reply;
2019 char_u *res;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 int retval;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002021 char_u *str;
2022 char_u *tofree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023
2024 switch (data->dwData)
2025 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002026 case COPYDATA_ENCODING:
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002027# ifdef FEAT_MBYTE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002028 /* Remember the encoding that the client uses. */
2029 vim_free(client_enc);
2030 client_enc = enc_canonize((char_u *)data->lpData);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002031# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002032 return 1;
2033
Bram Moolenaar071d4272004-06-13 20:20:40 +00002034 case COPYDATA_KEYS:
2035 /* Remember who sent this, for <client> */
2036 clientWindow = sender;
2037
2038 /* Add the received keys to the input buffer. The loop waiting
2039 * for the user to do something should check the input buffer. */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002040 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2041 server_to_input_buf(str);
2042 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002043
2044# ifdef FEAT_GUI
2045 /* Wake up the main GUI loop. */
2046 if (s_hwnd != 0)
2047 PostMessage(s_hwnd, WM_NULL, 0, 0);
2048# endif
2049 return 1;
2050
2051 case COPYDATA_EXPR:
2052 /* Remember who sent this, for <client> */
2053 clientWindow = sender;
2054
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002055 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2056 res = eval_client_expr_to_string(str);
2057 vim_free(tofree);
2058
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059 if (res == NULL)
2060 {
2061 res = vim_strsave(_(e_invexprmsg));
2062 reply.dwData = COPYDATA_ERROR_RESULT;
2063 }
2064 else
2065 reply.dwData = COPYDATA_RESULT;
2066 reply.lpData = res;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002067 reply.cbData = (DWORD)STRLEN(res) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002069 serverSendEnc(sender);
Bram Moolenaar5246cd72013-06-16 16:41:47 +02002070 retval = (int)SendMessage(sender, WM_COPYDATA,
2071 (WPARAM)message_window, (LPARAM)(&reply));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002072 vim_free(res);
2073 return retval;
2074
2075 case COPYDATA_REPLY:
2076 case COPYDATA_RESULT:
2077 case COPYDATA_ERROR_RESULT:
2078 if (data->lpData != NULL)
2079 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002080 str = serverConvert(client_enc, (char_u *)data->lpData,
2081 &tofree);
2082 if (tofree == NULL)
2083 str = vim_strsave(str);
2084 if (save_reply(sender, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002085 (data->dwData == COPYDATA_REPLY ? 0 :
2086 (data->dwData == COPYDATA_RESULT ? 1 :
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002087 2))) == FAIL)
2088 vim_free(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002089#ifdef FEAT_AUTOCMD
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002090 else if (data->dwData == COPYDATA_REPLY)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091 {
Bram Moolenaar427d51c2013-06-16 16:01:25 +02002092 char_u winstr[30];
2093
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002094 sprintf((char *)winstr, PRINTF_HEX_LONG_U, (long_u)sender);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002095 apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002096 TRUE, curbuf);
2097 }
2098#endif
2099 }
2100 return 1;
2101 }
2102
2103 return 0;
2104 }
2105
2106 else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2107 {
2108 /* When the message window is activated (brought to the foreground),
2109 * this actually applies to the text window. */
2110#ifndef FEAT_GUI
2111 GetConsoleHwnd(); /* get value of s_hwnd */
2112#endif
2113 if (s_hwnd != 0)
2114 {
2115 SetForegroundWindow(s_hwnd);
2116 return 0;
2117 }
2118 }
2119
2120 return DefWindowProc(hwnd, msg, wParam, lParam);
2121}
2122
2123/*
2124 * Initialise the message handling process. This involves creating a window
2125 * to handle messages - the window will not be visible.
2126 */
2127 void
2128serverInitMessaging(void)
2129{
2130 WNDCLASS wndclass;
2131 HINSTANCE s_hinst;
2132
2133 /* Clean up on exit */
2134 atexit(CleanUpMessaging);
2135
2136 /* Register a window class - we only really care
2137 * about the window procedure
2138 */
2139 s_hinst = (HINSTANCE)GetModuleHandle(0);
2140 wndclass.style = 0;
2141 wndclass.lpfnWndProc = Messaging_WndProc;
2142 wndclass.cbClsExtra = 0;
2143 wndclass.cbWndExtra = 0;
2144 wndclass.hInstance = s_hinst;
2145 wndclass.hIcon = NULL;
2146 wndclass.hCursor = NULL;
2147 wndclass.hbrBackground = NULL;
2148 wndclass.lpszMenuName = NULL;
2149 wndclass.lpszClassName = VIM_CLASSNAME;
2150 RegisterClass(&wndclass);
2151
2152 /* Create the message window. It will be hidden, so the details don't
2153 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2154 * focus from gvim. */
2155 message_window = CreateWindow(VIM_CLASSNAME, "",
2156 WS_POPUPWINDOW | WS_CAPTION,
2157 CW_USEDEFAULT, CW_USEDEFAULT,
2158 100, 100, NULL, NULL,
2159 s_hinst, NULL);
2160}
2161
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002162/* Used by serverSendToVim() to find an alternate server name. */
2163static char_u *altname_buf_ptr = NULL;
2164
Bram Moolenaar071d4272004-06-13 20:20:40 +00002165/*
2166 * Get the title of the window "hwnd", which is the Vim server name, in
2167 * "name[namelen]" and return the length.
2168 * Returns zero if window "hwnd" is not a Vim server.
2169 */
2170 static int
2171getVimServerName(HWND hwnd, char *name, int namelen)
2172{
2173 int len;
2174 char buffer[VIM_CLASSNAME_LEN + 1];
2175
2176 /* Ignore windows which aren't Vim message windows */
2177 len = GetClassName(hwnd, buffer, sizeof(buffer));
2178 if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2179 return 0;
2180
2181 /* Get the title of the window */
2182 return GetWindowText(hwnd, name, namelen);
2183}
2184
2185 static BOOL CALLBACK
2186enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2187{
2188 struct server_id *id = (struct server_id *)lparam;
2189 char server[MAX_PATH];
2190
2191 /* Get the title of the window */
2192 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2193 return TRUE;
2194
2195 /* If this is the server we're looking for, return its HWND */
2196 if (STRICMP(server, id->name) == 0)
2197 {
2198 id->hwnd = hwnd;
2199 return FALSE;
2200 }
2201
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002202 /* If we are looking for an alternate server, remember this name. */
2203 if (altname_buf_ptr != NULL
2204 && STRNICMP(server, id->name, STRLEN(id->name)) == 0
2205 && vim_isdigit(server[STRLEN(id->name)]))
2206 {
2207 STRCPY(altname_buf_ptr, server);
2208 altname_buf_ptr = NULL; /* don't use another name */
2209 }
2210
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211 /* Otherwise, keep looking */
2212 return TRUE;
2213}
2214
2215 static BOOL CALLBACK
2216enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2217{
2218 garray_T *ga = (garray_T *)lparam;
2219 char server[MAX_PATH];
2220
2221 /* Get the title of the window */
2222 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2223 return TRUE;
2224
2225 /* Add the name to the list */
2226 ga_concat(ga, server);
2227 ga_concat(ga, "\n");
2228 return TRUE;
2229}
2230
2231 static HWND
2232findServer(char_u *name)
2233{
2234 struct server_id id;
2235
2236 id.name = name;
2237 id.hwnd = 0;
2238
2239 EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2240
2241 return id.hwnd;
2242}
2243
2244 void
2245serverSetName(char_u *name)
2246{
2247 char_u *ok_name;
2248 HWND hwnd = 0;
2249 int i = 0;
2250 char_u *p;
2251
2252 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002253 ok_name = alloc((unsigned)STRLEN(name) + 10);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002254
2255 STRCPY(ok_name, name);
2256 p = ok_name + STRLEN(name);
2257
2258 for (;;)
2259 {
2260 /* This is inefficient - we're doing an EnumWindows loop for each
2261 * possible name. It would be better to grab all names in one go,
2262 * and scan the list each time...
2263 */
2264 hwnd = findServer(ok_name);
2265 if (hwnd == 0)
2266 break;
2267
2268 ++i;
2269 if (i >= 1000)
2270 break;
2271
2272 sprintf((char *)p, "%d", i);
2273 }
2274
2275 if (hwnd != 0)
2276 vim_free(ok_name);
2277 else
2278 {
2279 /* Remember the name */
2280 serverName = ok_name;
2281#ifdef FEAT_TITLE
2282 need_maketitle = TRUE; /* update Vim window title later */
2283#endif
2284
2285 /* Update the message window title */
2286 SetWindowText(message_window, ok_name);
2287
2288#ifdef FEAT_EVAL
2289 /* Set the servername variable */
2290 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2291#endif
2292 }
2293}
2294
2295 char_u *
2296serverGetVimNames(void)
2297{
2298 garray_T ga;
2299
2300 ga_init2(&ga, 1, 100);
2301
2302 EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
Bram Moolenaar269ec652004-07-29 08:43:53 +00002303 ga_append(&ga, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002304
2305 return ga.ga_data;
2306}
2307
2308 int
2309serverSendReply(name, reply)
2310 char_u *name; /* Where to send. */
2311 char_u *reply; /* What to send. */
2312{
2313 HWND target;
2314 COPYDATASTRUCT data;
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002315 long_u n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316
2317 /* The "name" argument is a magic cookie obtained from expand("<client>").
2318 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2319 * value of the client's message window HWND.
2320 */
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002321 sscanf((char *)name, SCANF_HEX_LONG_U, &n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322 if (n == 0)
2323 return -1;
2324
2325 target = (HWND)n;
2326 if (!IsWindow(target))
2327 return -1;
2328
2329 data.dwData = COPYDATA_REPLY;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002330 data.cbData = (DWORD)STRLEN(reply) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002331 data.lpData = reply;
2332
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002333 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002334 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2335 (LPARAM)(&data)))
2336 return 0;
2337
2338 return -1;
2339}
2340
2341 int
2342serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2343 char_u *name; /* Where to send. */
2344 char_u *cmd; /* What to send. */
2345 char_u **result; /* Result of eval'ed expression */
2346 void *ptarget; /* HWND of server */
2347 int asExpr; /* Expression or keys? */
2348 int silent; /* don't complain about no server */
2349{
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002350 HWND target;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 COPYDATASTRUCT data;
2352 char_u *retval = NULL;
2353 int retcode = 0;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002354 char_u altname_buf[MAX_PATH];
2355
2356 /* If the server name does not end in a digit then we look for an
2357 * alternate name. e.g. when "name" is GVIM the we may find GVIM2. */
2358 if (STRLEN(name) > 1 && !vim_isdigit(name[STRLEN(name) - 1]))
2359 altname_buf_ptr = altname_buf;
2360 altname_buf[0] = NUL;
2361 target = findServer(name);
2362 altname_buf_ptr = NULL;
2363 if (target == 0 && altname_buf[0] != NUL)
2364 /* Use another server name we found. */
2365 target = findServer(altname_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002366
2367 if (target == 0)
2368 {
2369 if (!silent)
2370 EMSG2(_(e_noserver), name);
2371 return -1;
2372 }
2373
2374 if (ptarget)
2375 *(HWND *)ptarget = target;
2376
2377 data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002378 data.cbData = (DWORD)STRLEN(cmd) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 data.lpData = cmd;
2380
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002381 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2383 (LPARAM)(&data)) == 0)
2384 return -1;
2385
2386 if (asExpr)
2387 retval = serverGetReply(target, &retcode, TRUE, TRUE);
2388
2389 if (result == NULL)
2390 vim_free(retval);
2391 else
2392 *result = retval; /* Caller assumes responsibility for freeing */
2393
2394 return retcode;
2395}
2396
2397/*
2398 * Bring the server to the foreground.
2399 */
2400 void
2401serverForeground(name)
2402 char_u *name;
2403{
2404 HWND target = findServer(name);
2405
2406 if (target != 0)
2407 SetForegroundWindow(target);
2408}
2409
2410/* Replies from server need to be stored until the client picks them up via
2411 * remote_read(). So we maintain a list of server-id/reply pairs.
2412 * Note that there could be multiple replies from one server pending if the
2413 * client is slow picking them up.
2414 * We just store the replies in a simple list. When we remove an entry, we
2415 * move list entries down to fill the gap.
2416 * The server ID is simply the HWND.
2417 */
2418typedef struct
2419{
2420 HWND server; /* server window */
2421 char_u *reply; /* reply string */
2422 int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002423} reply_T;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424
2425static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
2426
2427#define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
2428#define REPLY_COUNT (reply_list.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429
2430/* Flag which is used to wait for a reply */
2431static int reply_received = 0;
2432
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002433/*
2434 * Store a reply. "reply" must be allocated memory (or NULL).
2435 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002436 static int
2437save_reply(HWND server, char_u *reply, int expr)
2438{
2439 reply_T *rep;
2440
2441 if (ga_grow(&reply_list, 1) == FAIL)
2442 return FAIL;
2443
2444 rep = REPLY_ITEM(REPLY_COUNT);
2445 rep->server = server;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002446 rep->reply = reply;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447 rep->expr_result = expr;
2448 if (rep->reply == NULL)
2449 return FAIL;
2450
2451 ++REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452 reply_received = 1;
2453 return OK;
2454}
2455
2456/*
2457 * Get a reply from server "server".
2458 * When "expr_res" is non NULL, get the result of an expression, otherwise a
2459 * server2client() message.
2460 * When non NULL, point to return code. 0 => OK, -1 => ERROR
2461 * If "remove" is TRUE, consume the message, the caller must free it then.
2462 * if "wait" is TRUE block until a message arrives (or the server exits).
2463 */
2464 char_u *
2465serverGetReply(HWND server, int *expr_res, int remove, int wait)
2466{
2467 int i;
2468 char_u *reply;
2469 reply_T *rep;
2470
2471 /* When waiting, loop until the message waiting for is received. */
2472 for (;;)
2473 {
2474 /* Reset this here, in case a message arrives while we are going
2475 * through the already received messages. */
2476 reply_received = 0;
2477
2478 for (i = 0; i < REPLY_COUNT; ++i)
2479 {
2480 rep = REPLY_ITEM(i);
2481 if (rep->server == server
2482 && ((rep->expr_result != 0) == (expr_res != NULL)))
2483 {
2484 /* Save the values we've found for later */
2485 reply = rep->reply;
2486 if (expr_res != NULL)
2487 *expr_res = rep->expr_result == 1 ? 0 : -1;
2488
2489 if (remove)
2490 {
2491 /* Move the rest of the list down to fill the gap */
2492 mch_memmove(rep, rep + 1,
2493 (REPLY_COUNT - i - 1) * sizeof(reply_T));
2494 --REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 }
2496
2497 /* Return the reply to the caller, who takes on responsibility
2498 * for freeing it if "remove" is TRUE. */
2499 return reply;
2500 }
2501 }
2502
2503 /* If we got here, we didn't find a reply. Return immediately if the
2504 * "wait" parameter isn't set. */
2505 if (!wait)
2506 break;
2507
2508 /* We need to wait for a reply. Enter a message loop until the
2509 * "reply_received" flag gets set. */
2510
2511 /* Loop until we receive a reply */
2512 while (reply_received == 0)
2513 {
2514 /* Wait for a SendMessage() call to us. This could be the reply
2515 * we are waiting for. Use a timeout of a second, to catch the
2516 * situation that the server died unexpectedly. */
2517 MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
2518
2519 /* If the server has died, give up */
2520 if (!IsWindow(server))
2521 return NULL;
2522
2523 serverProcessPendingMessages();
2524 }
2525 }
2526
2527 return NULL;
2528}
2529
2530/*
2531 * Process any messages in the Windows message queue.
2532 */
2533 void
2534serverProcessPendingMessages(void)
2535{
2536 MSG msg;
2537
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02002538 while (pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539 {
2540 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02002541 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 }
2543}
2544
2545#endif /* FEAT_CLIENTSERVER */
2546
2547#if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
2548 || defined(PROTO)
2549
2550struct charset_pair
2551{
2552 char *name;
2553 BYTE charset;
2554};
2555
2556static struct charset_pair
2557charset_pairs[] =
2558{
2559 {"ANSI", ANSI_CHARSET},
2560 {"CHINESEBIG5", CHINESEBIG5_CHARSET},
2561 {"DEFAULT", DEFAULT_CHARSET},
2562 {"HANGEUL", HANGEUL_CHARSET},
2563 {"OEM", OEM_CHARSET},
2564 {"SHIFTJIS", SHIFTJIS_CHARSET},
2565 {"SYMBOL", SYMBOL_CHARSET},
2566#ifdef WIN3264
2567 {"ARABIC", ARABIC_CHARSET},
2568 {"BALTIC", BALTIC_CHARSET},
2569 {"EASTEUROPE", EASTEUROPE_CHARSET},
2570 {"GB2312", GB2312_CHARSET},
2571 {"GREEK", GREEK_CHARSET},
2572 {"HEBREW", HEBREW_CHARSET},
2573 {"JOHAB", JOHAB_CHARSET},
2574 {"MAC", MAC_CHARSET},
2575 {"RUSSIAN", RUSSIAN_CHARSET},
2576 {"THAI", THAI_CHARSET},
2577 {"TURKISH", TURKISH_CHARSET},
2578# if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
2579 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
2580 {"VIETNAMESE", VIETNAMESE_CHARSET},
2581# endif
2582#endif
2583 {NULL, 0}
2584};
2585
2586/*
2587 * Convert a charset ID to a name.
2588 * Return NULL when not recognized.
2589 */
2590 char *
2591charset_id2name(int id)
2592{
2593 struct charset_pair *cp;
2594
2595 for (cp = charset_pairs; cp->name != NULL; ++cp)
2596 if ((BYTE)id == cp->charset)
2597 break;
2598 return cp->name;
2599}
2600
2601static const LOGFONT s_lfDefault =
2602{
2603 -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2604 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2605 PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
2606 "Fixedsys" /* see _ReadVimIni */
2607};
2608
2609/* Initialise the "current height" to -12 (same as s_lfDefault) just
2610 * in case the user specifies a font in "guifont" with no size before a font
2611 * with an explicit size has been set. This defaults the size to this value
2612 * (-12 equates to roughly 9pt).
2613 */
2614int current_font_height = -12; /* also used in gui_w48.c */
2615
2616/* Convert a string representing a point size into pixels. The string should
2617 * be a positive decimal number, with an optional decimal point (eg, "12", or
2618 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
2619 * character is stored in *end. The flag "vertical" says whether this
2620 * calculation is for a vertical (height) size or a horizontal (width) one.
2621 */
2622 static int
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002623points_to_pixels(char_u *str, char_u **end, int vertical, long_i pprinter_dc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002624{
2625 int pixels;
2626 int points = 0;
2627 int divisor = 0;
2628 HWND hwnd = (HWND)0;
2629 HDC hdc;
2630 HDC printer_dc = (HDC)pprinter_dc;
2631
2632 while (*str != NUL)
2633 {
2634 if (*str == '.' && divisor == 0)
2635 {
2636 /* Start keeping a divisor, for later */
2637 divisor = 1;
2638 }
2639 else
2640 {
2641 if (!VIM_ISDIGIT(*str))
2642 break;
2643
2644 points *= 10;
2645 points += *str - '0';
2646 divisor *= 10;
2647 }
2648 ++str;
2649 }
2650
2651 if (divisor == 0)
2652 divisor = 1;
2653
2654 if (printer_dc == NULL)
2655 {
2656 hwnd = GetDesktopWindow();
2657 hdc = GetWindowDC(hwnd);
2658 }
2659 else
2660 hdc = printer_dc;
2661
2662 pixels = MulDiv(points,
2663 GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
2664 72 * divisor);
2665
2666 if (printer_dc == NULL)
2667 ReleaseDC(hwnd, hdc);
2668
2669 *end = str;
2670 return pixels;
2671}
2672
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002673/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002674 static int CALLBACK
2675font_enumproc(
2676 ENUMLOGFONT *elf,
2677 NEWTEXTMETRIC *ntm,
2678 int type,
2679 LPARAM lparam)
2680{
2681 /* Return value:
2682 * 0 = terminate now (monospace & ANSI)
2683 * 1 = continue, still no luck...
2684 * 2 = continue, but we have an acceptable LOGFONT
2685 * (monospace, not ANSI)
2686 * We use these values, as EnumFontFamilies returns 1 if the
2687 * callback function is never called. So, we check the return as
2688 * 0 = perfect, 2 = OK, 1 = no good...
2689 * It's not pretty, but it works!
2690 */
2691
2692 LOGFONT *lf = (LOGFONT *)(lparam);
2693
2694#ifndef FEAT_PROPORTIONAL_FONTS
2695 /* Ignore non-monospace fonts without further ado */
2696 if ((ntm->tmPitchAndFamily & 1) != 0)
2697 return 1;
2698#endif
2699
2700 /* Remember this LOGFONT as a "possible" */
2701 *lf = elf->elfLogFont;
2702
2703 /* Terminate the scan as soon as we find an ANSI font */
2704 if (lf->lfCharSet == ANSI_CHARSET
2705 || lf->lfCharSet == OEM_CHARSET
2706 || lf->lfCharSet == DEFAULT_CHARSET)
2707 return 0;
2708
2709 /* Continue the scan - we have a non-ANSI font */
2710 return 2;
2711}
2712
2713 static int
2714init_logfont(LOGFONT *lf)
2715{
2716 int n;
2717 HWND hwnd = GetDesktopWindow();
2718 HDC hdc = GetWindowDC(hwnd);
2719
2720 n = EnumFontFamilies(hdc,
2721 (LPCSTR)lf->lfFaceName,
2722 (FONTENUMPROC)font_enumproc,
2723 (LPARAM)lf);
2724
2725 ReleaseDC(hwnd, hdc);
2726
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002727 /* If we couldn't find a usable font, return failure */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002728 if (n == 1)
2729 return FAIL;
2730
2731 /* Tidy up the rest of the LOGFONT structure. We set to a basic
2732 * font - get_logfont() sets bold, italic, etc based on the user's
2733 * input.
2734 */
2735 lf->lfHeight = current_font_height;
2736 lf->lfWidth = 0;
2737 lf->lfItalic = FALSE;
2738 lf->lfUnderline = FALSE;
2739 lf->lfStrikeOut = FALSE;
2740 lf->lfWeight = FW_NORMAL;
2741
2742 /* Return success */
2743 return OK;
2744}
2745
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002746/*
2747 * Get font info from "name" into logfont "lf".
2748 * Return OK for a valid name, FAIL otherwise.
2749 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750 int
2751get_logfont(
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002752 LOGFONT *lf,
2753 char_u *name,
2754 HDC printer_dc,
2755 int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002756{
2757 char_u *p;
2758 int i;
2759 static LOGFONT *lastlf = NULL;
2760
2761 *lf = s_lfDefault;
2762 if (name == NULL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002763 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002764
2765 if (STRCMP(name, "*") == 0)
2766 {
2767#if defined(FEAT_GUI_W32)
2768 CHOOSEFONT cf;
2769 /* if name is "*", bring up std font dialog: */
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02002770 vim_memset(&cf, 0, sizeof(cf));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771 cf.lStructSize = sizeof(cf);
2772 cf.hwndOwner = s_hwnd;
2773 cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
2774 if (lastlf != NULL)
2775 *lf = *lastlf;
2776 cf.lpLogFont = lf;
2777 cf.nFontType = 0 ; //REGULAR_FONTTYPE;
2778 if (ChooseFont(&cf))
2779 goto theend;
2780#else
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002781 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002782#endif
2783 }
2784
2785 /*
2786 * Split name up, it could be <name>:h<height>:w<width> etc.
2787 */
2788 for (p = name; *p && *p != ':'; p++)
2789 {
2790 if (p - name + 1 > LF_FACESIZE)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002791 return FAIL; /* Name too long */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002792 lf->lfFaceName[p - name] = *p;
2793 }
2794 if (p != name)
2795 lf->lfFaceName[p - name] = NUL;
2796
2797 /* First set defaults */
2798 lf->lfHeight = -12;
2799 lf->lfWidth = 0;
2800 lf->lfWeight = FW_NORMAL;
2801 lf->lfItalic = FALSE;
2802 lf->lfUnderline = FALSE;
2803 lf->lfStrikeOut = FALSE;
2804
2805 /*
2806 * If the font can't be found, try replacing '_' by ' '.
2807 */
2808 if (init_logfont(lf) == FAIL)
2809 {
2810 int did_replace = FALSE;
2811
2812 for (i = 0; lf->lfFaceName[i]; ++i)
2813 if (lf->lfFaceName[i] == '_')
2814 {
2815 lf->lfFaceName[i] = ' ';
2816 did_replace = TRUE;
2817 }
2818 if (!did_replace || init_logfont(lf) == FAIL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002819 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820 }
2821
2822 while (*p == ':')
2823 p++;
2824
2825 /* Set the values found after ':' */
2826 while (*p)
2827 {
2828 switch (*p++)
2829 {
2830 case 'h':
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002831 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (long_i)printer_dc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002832 break;
2833 case 'w':
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002834 lf->lfWidth = points_to_pixels(p, &p, FALSE, (long_i)printer_dc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002835 break;
2836 case 'b':
2837#ifndef MSWIN16_FASTTEXT
2838 lf->lfWeight = FW_BOLD;
2839#endif
2840 break;
2841 case 'i':
2842#ifndef MSWIN16_FASTTEXT
2843 lf->lfItalic = TRUE;
2844#endif
2845 break;
2846 case 'u':
2847 lf->lfUnderline = TRUE;
2848 break;
2849 case 's':
2850 lf->lfStrikeOut = TRUE;
2851 break;
2852 case 'c':
2853 {
2854 struct charset_pair *cp;
2855
2856 for (cp = charset_pairs; cp->name != NULL; ++cp)
2857 if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
2858 {
2859 lf->lfCharSet = cp->charset;
2860 p += strlen(cp->name);
2861 break;
2862 }
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002863 if (cp->name == NULL && verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002864 {
Bram Moolenaar051b7822005-05-19 21:00:46 +00002865 vim_snprintf((char *)IObuff, IOSIZE,
2866 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867 EMSG(IObuff);
2868 break;
2869 }
2870 break;
2871 }
2872 default:
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002873 if (verbose)
2874 {
Bram Moolenaar051b7822005-05-19 21:00:46 +00002875 vim_snprintf((char *)IObuff, IOSIZE,
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002876 _("E245: Illegal char '%c' in font name \"%s\""),
2877 p[-1], name);
2878 EMSG(IObuff);
2879 }
2880 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002881 }
2882 while (*p == ':')
2883 p++;
2884 }
2885
2886#if defined(FEAT_GUI_W32)
2887theend:
2888#endif
2889 /* ron: init lastlf */
2890 if (printer_dc == NULL)
2891 {
2892 vim_free(lastlf);
2893 lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
2894 if (lastlf != NULL)
2895 mch_memmove(lastlf, lf, sizeof(LOGFONT));
2896 }
2897
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002898 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002899}
2900
2901#endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */