blob: 77f559917658d7e55026df9e36ad09626e523ea0 [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{
459 char szName[_MAX_PATH + 1];
460
461 /* A name like "d:/foo" and "//server/share" is absolute */
462 if ((fname[0] && fname[1] == ':' && (fname[2] == '/' || fname[2] == '\\'))
463 || (fname[0] == fname[1] && (fname[0] == '/' || fname[0] == '\\')))
464 return TRUE;
465
466 /* A name that can't be made absolute probably isn't absolute. */
467 if (mch_FullName(fname, szName, _MAX_PATH, FALSE) == FAIL)
468 return FALSE;
469
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000470 return pathcmp(fname, szName, -1) == 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000471}
472
473/*
474 * Replace all slashes by backslashes.
475 * This used to be the other way around, but MS-DOS sometimes has problems
476 * with slashes (e.g. in a command name). We can't have mixed slashes and
477 * backslashes, because comparing file names will not work correctly. The
478 * commands that use a file name should try to avoid the need to type a
479 * backslash twice.
480 * When 'shellslash' set do it the other way around.
481 */
482 void
483slash_adjust(p)
484 char_u *p;
485{
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +0000486 while (*p)
487 {
488 if (*p == psepcN)
489 *p = psepc;
490 mb_ptr_adv(p);
491 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000492}
493
494
495/*
496 * stat() can't handle a trailing '/' or '\', remove it first.
497 */
498 int
499vim_stat(const char *name, struct stat *stp)
500{
501 char buf[_MAX_PATH + 1];
502 char *p;
503
Bram Moolenaar84110ac2005-07-20 21:56:21 +0000504 vim_strncpy((char_u *)buf, (char_u *)name, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000505 p = buf + strlen(buf);
506 if (p > buf)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000507 mb_ptr_back(buf, p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000508 if (p > buf && (*p == '\\' || *p == '/') && p[-1] != ':')
509 *p = NUL;
510#ifdef FEAT_MBYTE
511 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
512# ifdef __BORLANDC__
513 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
514 && g_PlatformId == VER_PLATFORM_WIN32_NT
515# endif
516 )
517 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000518 WCHAR *wp = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519 int n;
520
521 if (wp != NULL)
522 {
523 n = _wstat(wp, (struct _stat *)stp);
524 vim_free(wp);
525 if (n >= 0)
526 return n;
527 /* Retry with non-wide function (for Windows 98). Can't use
528 * GetLastError() here and it's unclear what errno gets set to if
529 * the _wstat() fails for missing wide functions. */
530 }
531 }
532#endif
533 return stat(buf, stp);
534}
535
536#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000537/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000538 void
539mch_settmode(int tmode)
540{
541 /* nothing to do */
542}
543
544 int
545mch_get_shellsize(void)
546{
547 /* never used */
548 return OK;
549}
550
551 void
552mch_set_shellsize(void)
553{
554 /* never used */
555}
556
557/*
558 * Rows and/or Columns has changed.
559 */
560 void
561mch_new_shellsize(void)
562{
563 /* never used */
564}
565
566#endif
567
568/*
569 * We have no job control, so fake it by starting a new shell.
570 */
571 void
572mch_suspend()
573{
574 suspend_shell();
575}
576
577#if defined(USE_MCH_ERRMSG) || defined(PROTO)
578
579#ifdef display_errors
580# undef display_errors
581#endif
582
583/*
584 * Display the saved error message(s).
585 */
586 void
587display_errors()
588{
589 char *p;
590
591 if (error_ga.ga_data != NULL)
592 {
593 /* avoid putting up a message box with blanks only */
594 for (p = (char *)error_ga.ga_data; *p; ++p)
595 if (!isspace(*p))
596 {
Bram Moolenaarc17ef8e2006-03-25 21:48:58 +0000597 (void)gui_mch_dialog(
598#ifdef FEAT_GUI
599 gui.starting ? VIM_INFO :
600#endif
601 VIM_ERROR,
602#ifdef FEAT_GUI
603 gui.starting ? (char_u *)_("Message") :
604#endif
605 (char_u *)_("Error"),
Bram Moolenaard2c340a2011-01-17 20:08:11 +0100606 p, (char_u *)_("&Ok"), 1, NULL, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000607 break;
608 }
609 ga_clear(&error_ga);
610 }
611}
612#endif
613
614
615/*
616 * Return TRUE if "p" contain a wildcard that can be expanded by
617 * dos_expandpath().
618 */
619 int
620mch_has_exp_wildcard(char_u *p)
621{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000622 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000623 {
624 if (vim_strchr((char_u *)"?*[", *p) != NULL
625 || (*p == '~' && p[1] != NUL))
626 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000627 }
628 return FALSE;
629}
630
631/*
632 * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a
633 * shortened file name).
634 */
635 int
636mch_has_wildcard(char_u *p)
637{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000638 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000639 {
640 if (vim_strchr((char_u *)
641# ifdef VIM_BACKTICK
642 "?*$[`"
643# else
644 "?*$["
645# endif
646 , *p) != NULL
647 || (*p == '~' && p[1] != NUL))
648 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000649 }
650 return FALSE;
651}
652
653
654/*
655 * The normal _chdir() does not change the default drive. This one does.
656 * Returning 0 implies success; -1 implies failure.
657 */
658 int
659mch_chdir(char *path)
660{
661 if (path[0] == NUL) /* just checking... */
662 return -1;
663
Bram Moolenaara2974d72009-07-14 16:38:36 +0000664 if (p_verbose >= 5)
665 {
666 verbose_enter();
667 smsg((char_u *)"chdir(%s)", path);
668 verbose_leave();
669 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000670 if (isalpha(path[0]) && path[1] == ':') /* has a drive name */
671 {
672 /* If we can change to the drive, skip that part of the path. If we
673 * can't then the current directory may be invalid, try using chdir()
674 * with the whole path. */
675 if (_chdrive(TOLOWER_ASC(path[0]) - 'a' + 1) == 0)
676 path += 2;
677 }
678
679 if (*path == NUL) /* drive name only */
680 return 0;
681
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000682#ifdef FEAT_MBYTE
683 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
684 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000685 WCHAR *p = enc_to_utf16(path, NULL);
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000686 int n;
687
688 if (p != NULL)
689 {
690 n = _wchdir(p);
691 vim_free(p);
692 if (n == 0)
693 return 0;
694 /* Retry with non-wide function (for Windows 98). */
695 }
696 }
697#endif
698
Bram Moolenaar071d4272004-06-13 20:20:40 +0000699 return chdir(path); /* let the normal chdir() do the rest */
700}
701
702
703/*
704 * Switching off termcap mode is only allowed when Columns is 80, otherwise a
705 * crash may result. It's always allowed on NT or when running the GUI.
706 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000707/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000708 int
709can_end_termcap_mode(
710 int give_msg)
711{
712#ifdef FEAT_GUI_MSWIN
713 return TRUE; /* GUI starts a new console anyway */
714#else
715 if (g_PlatformId == VER_PLATFORM_WIN32_NT || Columns == 80)
716 return TRUE;
717 if (give_msg)
718 msg(_("'columns' is not 80, cannot execute external commands"));
719 return FALSE;
720#endif
721}
722
723#ifdef FEAT_GUI_MSWIN
724/*
725 * return non-zero if a character is available
726 */
727 int
728mch_char_avail()
729{
730 /* never used */
731 return TRUE;
732}
733#endif
734
735
736/*
737 * set screen mode, always fails.
738 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000739/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 int
741mch_screenmode(
742 char_u *arg)
743{
744 EMSG(_(e_screenmode));
745 return FAIL;
746}
747
748
749#if defined(FEAT_LIBCALL) || defined(PROTO)
750/*
751 * Call a DLL routine which takes either a string or int param
752 * and returns an allocated string.
753 * Return OK if it worked, FAIL if not.
754 */
755# ifdef WIN3264
756typedef LPTSTR (*MYSTRPROCSTR)(LPTSTR);
757typedef LPTSTR (*MYINTPROCSTR)(int);
758typedef int (*MYSTRPROCINT)(LPTSTR);
759typedef int (*MYINTPROCINT)(int);
760# else
761typedef LPSTR (*MYSTRPROCSTR)(LPSTR);
762typedef LPSTR (*MYINTPROCSTR)(int);
763typedef int (*MYSTRPROCINT)(LPSTR);
764typedef int (*MYINTPROCINT)(int);
765# endif
766
767# ifndef WIN16
768/*
769 * Check if a pointer points to a valid NUL terminated string.
770 * Return the length of the string, including terminating NUL.
771 * Returns 0 for an invalid pointer, 1 for an empty string.
772 */
773 static size_t
774check_str_len(char_u *str)
775{
776 SYSTEM_INFO si;
777 MEMORY_BASIC_INFORMATION mbi;
778 size_t length = 0;
779 size_t i;
780 const char *p;
781
782 /* get page size */
783 GetSystemInfo(&si);
784
785 /* get memory information */
786 if (VirtualQuery(str, &mbi, sizeof(mbi)))
787 {
788 /* pre cast these (typing savers) */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000789 long_u dwStr = (long_u)str;
790 long_u dwBaseAddress = (long_u)mbi.BaseAddress;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000791
792 /* get start address of page that str is on */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000793 long_u strPage = dwStr - (dwStr - dwBaseAddress) % si.dwPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794
795 /* get length from str to end of page */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000796 long_u pageLength = si.dwPageSize - (dwStr - strPage);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000797
Bram Moolenaar442b4222010-05-24 21:34:22 +0200798 for (p = str; !IsBadReadPtr(p, (UINT)pageLength);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000799 p += pageLength, pageLength = si.dwPageSize)
800 for (i = 0; i < pageLength; ++i, ++length)
801 if (p[i] == NUL)
802 return length + 1;
803 }
804
805 return 0;
806}
807# endif
808
809 int
810mch_libcall(
811 char_u *libname,
812 char_u *funcname,
813 char_u *argstring, /* NULL when using a argint */
814 int argint,
815 char_u **string_result,/* NULL when using number_result */
816 int *number_result)
817{
818 HINSTANCE hinstLib;
819 MYSTRPROCSTR ProcAdd;
820 MYINTPROCSTR ProcAddI;
821 char_u *retval_str = NULL;
822 int retval_int = 0;
823 size_t len;
824
825 BOOL fRunTimeLinkSuccess = FALSE;
826
827 // Get a handle to the DLL module.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200828# ifdef WIN16
Bram Moolenaar071d4272004-06-13 20:20:40 +0000829 hinstLib = LoadLibrary(libname);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200830# else
831 hinstLib = vimLoadLib(libname);
832# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000833
834 // If the handle is valid, try to get the function address.
835 if (hinstLib != NULL)
836 {
837#ifdef HAVE_TRY_EXCEPT
838 __try
839 {
840#endif
841 if (argstring != NULL)
842 {
843 /* Call with string argument */
844 ProcAdd = (MYSTRPROCSTR) GetProcAddress(hinstLib, funcname);
845 if ((fRunTimeLinkSuccess = (ProcAdd != NULL)) != 0)
846 {
847 if (string_result == NULL)
848 retval_int = ((MYSTRPROCINT)ProcAdd)(argstring);
849 else
850 retval_str = (ProcAdd)(argstring);
851 }
852 }
853 else
854 {
855 /* Call with number argument */
856 ProcAddI = (MYINTPROCSTR) GetProcAddress(hinstLib, funcname);
857 if ((fRunTimeLinkSuccess = (ProcAddI != NULL)) != 0)
858 {
859 if (string_result == NULL)
860 retval_int = ((MYINTPROCINT)ProcAddI)(argint);
861 else
862 retval_str = (ProcAddI)(argint);
863 }
864 }
865
866 // Save the string before we free the library.
867 // Assume that a "1" result is an illegal pointer.
868 if (string_result == NULL)
869 *number_result = retval_int;
870 else if (retval_str != NULL
871# ifdef WIN16
872 && retval_str != (char_u *)1
873 && retval_str != (char_u *)-1
874 && !IsBadStringPtr(retval_str, INT_MAX)
875 && (len = strlen(retval_str) + 1) > 0
876# else
877 && (len = check_str_len(retval_str)) > 0
878# endif
879 )
880 {
881 *string_result = lalloc((long_u)len, TRUE);
882 if (*string_result != NULL)
883 mch_memmove(*string_result, retval_str, len);
884 }
885
886#ifdef HAVE_TRY_EXCEPT
887 }
888 __except(EXCEPTION_EXECUTE_HANDLER)
889 {
890 if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW)
891 RESETSTKOFLW();
892 fRunTimeLinkSuccess = 0;
893 }
894#endif
895
896 // Free the DLL module.
897 (void)FreeLibrary(hinstLib);
898 }
899
900 if (!fRunTimeLinkSuccess)
901 {
902 EMSG2(_(e_libcall), funcname);
903 return FAIL;
904 }
905
906 return OK;
907}
908#endif
909
Bram Moolenaar071d4272004-06-13 20:20:40 +0000910/*
911 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
912 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000913/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000914 void
915DumpPutS(
916 const char *psz)
917{
918# ifdef MCH_WRITE_DUMP
919 if (fdDump)
920 {
921 fputs(psz, fdDump);
922 if (psz[strlen(psz) - 1] != '\n')
923 fputc('\n', fdDump);
924 fflush(fdDump);
925 }
926# endif
927}
928
929#ifdef _DEBUG
930
931void __cdecl
932Trace(
933 char *pszFormat,
934 ...)
935{
936 CHAR szBuff[2048];
937 va_list args;
938
939 va_start(args, pszFormat);
940 vsprintf(szBuff, pszFormat, args);
941 va_end(args);
942
943 OutputDebugString(szBuff);
944}
945
946#endif //_DEBUG
947
Bram Moolenaar843ee412004-06-30 16:16:41 +0000948#if !defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949# if defined(FEAT_TITLE) && defined(WIN3264)
950extern HWND g_hWnd; /* This is in os_win32.c. */
951# endif
952
953/*
954 * Showing the printer dialog is tricky since we have no GUI
955 * window to parent it. The following routines are needed to
956 * get the window parenting and Z-order to work properly.
957 */
958 static void
959GetConsoleHwnd(void)
960{
961# define MY_BUFSIZE 1024 // Buffer size for console window titles.
962
963 char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
964 char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
965
966 /* Skip if it's already set. */
967 if (s_hwnd != 0)
968 return;
969
970# if defined(FEAT_TITLE) && defined(WIN3264)
971 /* Window handle may have been found by init code (Windows NT only) */
972 if (g_hWnd != 0)
973 {
974 s_hwnd = g_hWnd;
975 return;
976 }
977# endif
978
979 GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
980
981 wsprintf(pszNewWindowTitle, "%s/%d/%d",
982 pszOldWindowTitle,
983 GetTickCount(),
984 GetCurrentProcessId());
985 SetConsoleTitle(pszNewWindowTitle);
986 Sleep(40);
987 s_hwnd = FindWindow(NULL, pszNewWindowTitle);
988
989 SetConsoleTitle(pszOldWindowTitle);
990}
Bram Moolenaar843ee412004-06-30 16:16:41 +0000991
992/*
993 * Console implementation of ":winpos".
994 */
995 int
996mch_get_winpos(int *x, int *y)
997{
998 RECT rect;
999
1000 GetConsoleHwnd();
1001 GetWindowRect(s_hwnd, &rect);
1002 *x = rect.left;
1003 *y = rect.top;
1004 return OK;
1005}
1006
1007/*
1008 * Console implementation of ":winpos x y".
1009 */
1010 void
1011mch_set_winpos(int x, int y)
1012{
1013 GetConsoleHwnd();
1014 SetWindowPos(s_hwnd, NULL, x, y, 0, 0,
1015 SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1016}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001017#endif
1018
1019#if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1020
1021# ifdef WIN16
1022# define TEXT(a) a
1023# endif
1024/*=================================================================
1025 * Win32 printer stuff
1026 */
1027
1028static HFONT prt_font_handles[2][2][2];
1029static PRINTDLG prt_dlg;
1030static const int boldface[2] = {FW_REGULAR, FW_BOLD};
1031static TEXTMETRIC prt_tm;
1032static int prt_line_height;
1033static int prt_number_width;
1034static int prt_left_margin;
1035static int prt_right_margin;
1036static int prt_top_margin;
1037static char_u szAppName[] = TEXT("VIM");
1038static HWND hDlgPrint;
1039static int *bUserAbort = NULL;
1040static char_u *prt_name = NULL;
1041
1042/* Defines which are also in vim.rc. */
1043#define IDC_BOX1 400
1044#define IDC_PRINTTEXT1 401
1045#define IDC_PRINTTEXT2 402
1046#define IDC_PROGRESS 403
1047
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001048#if !defined(FEAT_MBYTE) || defined(WIN16)
1049# define vimSetDlgItemText(h, i, s) SetDlgItemText(h, i, s)
1050#else
1051 static BOOL
1052vimSetDlgItemText(HWND hDlg, int nIDDlgItem, char_u *s)
1053{
1054 WCHAR *wp = NULL;
1055 BOOL ret;
1056
1057 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1058 {
1059 wp = enc_to_utf16(s, NULL);
1060 }
1061 if (wp != NULL)
1062 {
1063 ret = SetDlgItemTextW(hDlg, nIDDlgItem, wp);
1064 vim_free(wp);
1065 return ret;
1066 }
1067 return SetDlgItemText(hDlg, nIDDlgItem, s);
1068}
1069#endif
1070
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071/*
1072 * Convert BGR to RGB for Windows GDI calls
1073 */
1074 static COLORREF
1075swap_me(COLORREF colorref)
1076{
1077 int temp;
1078 char *ptr = (char *)&colorref;
1079
1080 temp = *(ptr);
1081 *(ptr ) = *(ptr + 2);
1082 *(ptr + 2) = temp;
1083 return colorref;
1084}
1085
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001086/* Attempt to make this work for old and new compilers */
Bram Moolenaar9f733d12011-09-21 20:09:42 +02001087#if !defined(_WIN64) && (!defined(_MSC_VER) || _MSC_VER < 1300)
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001088# define PDP_RETVAL BOOL
1089#else
1090# define PDP_RETVAL INT_PTR
1091#endif
1092
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001093/*ARGSUSED*/
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001094 static PDP_RETVAL CALLBACK
Bram Moolenaar071d4272004-06-13 20:20:40 +00001095PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
1096{
1097#ifdef FEAT_GETTEXT
1098 NONCLIENTMETRICS nm;
1099 static HFONT hfont;
1100#endif
1101
1102 switch (message)
1103 {
1104 case WM_INITDIALOG:
1105#ifdef FEAT_GETTEXT
1106 nm.cbSize = sizeof(NONCLIENTMETRICS);
1107 if (SystemParametersInfo(
1108 SPI_GETNONCLIENTMETRICS,
1109 sizeof(NONCLIENTMETRICS),
1110 &nm,
1111 0))
1112 {
1113 char buff[MAX_PATH];
1114 int i;
1115
1116 /* Translate the dialog texts */
1117 hfont = CreateFontIndirect(&nm.lfMessageFont);
1118 for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++)
1119 {
1120 SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1);
1121 if (GetDlgItemText(hDlg,i, buff, sizeof(buff)))
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001122 vimSetDlgItemText(hDlg,i, _(buff));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123 }
1124 SendDlgItemMessage(hDlg, IDCANCEL,
1125 WM_SETFONT, (WPARAM)hfont, 1);
1126 if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff)))
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001127 vimSetDlgItemText(hDlg,IDCANCEL, _(buff));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001128 }
1129#endif
1130 SetWindowText(hDlg, szAppName);
1131 if (prt_name != NULL)
1132 {
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001133 vimSetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134 vim_free(prt_name);
1135 prt_name = NULL;
1136 }
1137 EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED);
1138#ifndef FEAT_GUI
1139 BringWindowToTop(s_hwnd);
1140#endif
1141 return TRUE;
1142
1143 case WM_COMMAND:
1144 *bUserAbort = TRUE;
1145 EnableWindow(GetParent(hDlg), TRUE);
1146 DestroyWindow(hDlg);
1147 hDlgPrint = NULL;
1148#ifdef FEAT_GETTEXT
1149 DeleteObject(hfont);
1150#endif
1151 return TRUE;
1152 }
1153 return FALSE;
1154}
1155
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001156/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001157 static BOOL CALLBACK
1158AbortProc(HDC hdcPrn, int iCode)
1159{
1160 MSG msg;
1161
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001162 while (!*bUserAbort && pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163 {
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001164 if (!hDlgPrint || !pIsDialogMessage(hDlgPrint, &msg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001165 {
1166 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001167 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001168 }
1169 }
1170 return !*bUserAbort;
1171}
1172
1173#ifndef FEAT_GUI
1174
Bram Moolenaar26fdd7d2011-11-30 13:42:44 +01001175 static UINT_PTR CALLBACK
Bram Moolenaar071d4272004-06-13 20:20:40 +00001176PrintHookProc(
1177 HWND hDlg, // handle to dialog box
1178 UINT uiMsg, // message identifier
1179 WPARAM wParam, // message parameter
1180 LPARAM lParam // message parameter
1181 )
1182{
1183 HWND hwndOwner;
1184 RECT rc, rcDlg, rcOwner;
1185 PRINTDLG *pPD;
1186
1187 if (uiMsg == WM_INITDIALOG)
1188 {
1189 // Get the owner window and dialog box rectangles.
1190 if ((hwndOwner = GetParent(hDlg)) == NULL)
1191 hwndOwner = GetDesktopWindow();
1192
1193 GetWindowRect(hwndOwner, &rcOwner);
1194 GetWindowRect(hDlg, &rcDlg);
1195 CopyRect(&rc, &rcOwner);
1196
1197 // Offset the owner and dialog box rectangles so that
1198 // right and bottom values represent the width and
1199 // height, and then offset the owner again to discard
1200 // space taken up by the dialog box.
1201
1202 OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
1203 OffsetRect(&rc, -rc.left, -rc.top);
1204 OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
1205
1206 // The new position is the sum of half the remaining
1207 // space and the owner's original position.
1208
1209 SetWindowPos(hDlg,
1210 HWND_TOP,
1211 rcOwner.left + (rc.right / 2),
1212 rcOwner.top + (rc.bottom / 2),
1213 0, 0, // ignores size arguments
1214 SWP_NOSIZE);
1215
1216 /* tackle the printdlg copiesctrl problem */
1217 pPD = (PRINTDLG *)lParam;
1218 pPD->nCopies = (WORD)pPD->lCustData;
1219 SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE );
1220 /* Bring the window to top */
1221 BringWindowToTop(GetParent(hDlg));
1222 SetForegroundWindow(hDlg);
1223 }
1224
1225 return FALSE;
1226}
1227#endif
1228
1229 void
1230mch_print_cleanup(void)
1231{
1232 int pifItalic;
1233 int pifBold;
1234 int pifUnderline;
1235
1236 for (pifBold = 0; pifBold <= 1; pifBold++)
1237 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1238 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1239 DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]);
1240
1241 if (prt_dlg.hDC != NULL)
1242 DeleteDC(prt_dlg.hDC);
1243 if (!*bUserAbort)
1244 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1245}
1246
1247 static int
1248to_device_units(int idx, int dpi, int physsize, int offset, int def_number)
1249{
1250 int ret = 0;
1251 int u;
1252 int nr;
1253
1254 u = prt_get_unit(idx);
1255 if (u == PRT_UNIT_NONE)
1256 {
1257 u = PRT_UNIT_PERC;
1258 nr = def_number;
1259 }
1260 else
1261 nr = printer_opts[idx].number;
1262
1263 switch (u)
1264 {
1265 case PRT_UNIT_PERC:
1266 ret = (physsize * nr) / 100;
1267 break;
1268 case PRT_UNIT_INCH:
1269 ret = (nr * dpi);
1270 break;
1271 case PRT_UNIT_MM:
1272 ret = (nr * 10 * dpi) / 254;
1273 break;
1274 case PRT_UNIT_POINT:
1275 ret = (nr * 10 * dpi) / 720;
1276 break;
1277 }
1278
1279 if (ret < offset)
1280 return 0;
1281 else
1282 return ret - offset;
1283}
1284
1285 static int
1286prt_get_cpl(void)
1287{
1288 int hr;
1289 int phyw;
1290 int dvoff;
1291 int rev_offset;
1292 int dpi;
1293#ifdef WIN16
1294 POINT pagesize;
1295#endif
1296
1297 GetTextMetrics(prt_dlg.hDC, &prt_tm);
1298 prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading;
1299
1300 hr = GetDeviceCaps(prt_dlg.hDC, HORZRES);
1301#ifdef WIN16
1302 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1303 phyw = pagesize.x;
1304 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1305 dvoff = pagesize.x;
1306#else
1307 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH);
1308 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX);
1309#endif
1310 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX);
1311
1312 rev_offset = phyw - (dvoff + hr);
1313
1314 prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10);
1315 if (prt_use_number())
1316 {
1317 prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth;
1318 prt_left_margin += prt_number_width;
1319 }
1320 else
1321 prt_number_width = 0;
1322
1323 prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw,
1324 rev_offset, 5);
1325
1326 return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth;
1327}
1328
1329 static int
1330prt_get_lpp(void)
1331{
1332 int vr;
1333 int phyw;
1334 int dvoff;
1335 int rev_offset;
1336 int bottom_margin;
1337 int dpi;
1338#ifdef WIN16
1339 POINT pagesize;
1340#endif
1341
1342 vr = GetDeviceCaps(prt_dlg.hDC, VERTRES);
1343#ifdef WIN16
1344 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1345 phyw = pagesize.y;
1346 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1347 dvoff = pagesize.y;
1348#else
1349 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT);
1350 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY);
1351#endif
1352 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY);
1353
1354 rev_offset = phyw - (dvoff + vr);
1355
1356 prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5);
1357
1358 /* adjust top margin if there is a header */
1359 prt_top_margin += prt_line_height * prt_header_height();
1360
1361 bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw,
1362 rev_offset, 5);
1363
1364 return (bottom_margin - prt_top_margin) / prt_line_height;
1365}
1366
1367 int
1368mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
1369{
1370 static HGLOBAL stored_dm = NULL;
1371 static HGLOBAL stored_devn = NULL;
1372 static int stored_nCopies = 1;
1373 static int stored_nFlags = 0;
1374
1375 LOGFONT fLogFont;
1376 int pifItalic;
1377 int pifBold;
1378 int pifUnderline;
1379
1380 DEVMODE *mem;
1381 DEVNAMES *devname;
1382 int i;
1383
1384 bUserAbort = &(psettings->user_abort);
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02001385 vim_memset(&prt_dlg, 0, sizeof(PRINTDLG));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001386 prt_dlg.lStructSize = sizeof(PRINTDLG);
1387#ifndef FEAT_GUI
1388 GetConsoleHwnd(); /* get value of s_hwnd */
1389#endif
1390 prt_dlg.hwndOwner = s_hwnd;
1391 prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
1392 if (!forceit)
1393 {
1394 prt_dlg.hDevMode = stored_dm;
1395 prt_dlg.hDevNames = stored_devn;
1396 prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog
1397#ifndef FEAT_GUI
1398 /*
1399 * Use hook to prevent console window being sent to back
1400 */
1401 prt_dlg.lpfnPrintHook = PrintHookProc;
1402 prt_dlg.Flags |= PD_ENABLEPRINTHOOK;
1403#endif
1404 prt_dlg.Flags |= stored_nFlags;
1405 }
1406
1407 /*
1408 * If bang present, return default printer setup with no dialog
1409 * never show dialog if we are running over telnet
1410 */
1411 if (forceit
1412#ifndef FEAT_GUI
1413 || !term_console
1414#endif
1415 )
1416 {
1417 prt_dlg.Flags |= PD_RETURNDEFAULT;
1418#ifdef WIN3264
1419 /*
1420 * MSDN suggests setting the first parameter to WINSPOOL for
1421 * NT, but NULL appears to work just as well.
1422 */
1423 if (*p_pdev != NUL)
1424 prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL);
1425 else
1426#endif
1427 {
1428 prt_dlg.Flags |= PD_RETURNDEFAULT;
1429 if (PrintDlg(&prt_dlg) == 0)
1430 goto init_fail_dlg;
1431 }
1432 }
1433 else if (PrintDlg(&prt_dlg) == 0)
1434 goto init_fail_dlg;
1435 else
1436 {
1437 /*
1438 * keep the previous driver context
1439 */
1440 stored_dm = prt_dlg.hDevMode;
1441 stored_devn = prt_dlg.hDevNames;
1442 stored_nFlags = prt_dlg.Flags;
1443 stored_nCopies = prt_dlg.nCopies;
1444 }
1445
1446 if (prt_dlg.hDC == NULL)
1447 {
1448 EMSG(_("E237: Printer selection failed"));
1449 mch_print_cleanup();
1450 return FALSE;
1451 }
1452
1453 /* Not all printer drivers report the support of color (or grey) in the
1454 * same way. Let's set has_color if there appears to be some way to print
1455 * more than B&W. */
1456 i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS);
1457 psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1
1458 || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1
1459 || i > 2 || i == -1);
1460
1461 /* Ensure all font styles are baseline aligned */
1462 SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT);
1463
1464 /*
1465 * On some windows systems the nCopies parameter is not
1466 * passed back correctly. It must be retrieved from the
1467 * hDevMode struct.
1468 */
1469 mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode);
1470 if (mem != NULL)
1471 {
1472#ifdef WIN3264
1473 if (mem->dmCopies != 1)
1474 stored_nCopies = mem->dmCopies;
1475#endif
1476 if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX))
1477 psettings->duplex = TRUE;
1478 if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR))
1479 psettings->has_color = TRUE;
1480 }
1481 GlobalUnlock(prt_dlg.hDevMode);
1482
1483 devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames);
1484 if (devname != 0)
1485 {
1486 char_u *printer_name = (char_u *)devname + devname->wDeviceOffset;
1487 char_u *port_name = (char_u *)devname +devname->wOutputOffset;
1488 char_u *text = _("to %s on %s");
1489
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00001490 prt_name = alloc((unsigned)(STRLEN(printer_name) + STRLEN(port_name)
1491 + STRLEN(text)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001492 if (prt_name != NULL)
1493 wsprintf(prt_name, text, printer_name, port_name);
1494 }
1495 GlobalUnlock(prt_dlg.hDevNames);
1496
1497 /*
1498 * Initialise the font according to 'printfont'
1499 */
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02001500 vim_memset(&fLogFont, 0, sizeof(fLogFont));
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00001501 if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001502 {
1503 EMSG2(_("E613: Unknown printer font: %s"), p_pfn);
1504 mch_print_cleanup();
1505 return FALSE;
1506 }
1507
1508 for (pifBold = 0; pifBold <= 1; pifBold++)
1509 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1510 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1511 {
1512 fLogFont.lfWeight = boldface[pifBold];
1513 fLogFont.lfItalic = pifItalic;
1514 fLogFont.lfUnderline = pifUnderline;
1515 prt_font_handles[pifBold][pifItalic][pifUnderline]
1516 = CreateFontIndirect(&fLogFont);
1517 }
1518
1519 SetBkMode(prt_dlg.hDC, OPAQUE);
1520 SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]);
1521
1522 /*
1523 * Fill in the settings struct
1524 */
1525 psettings->chars_per_line = prt_get_cpl();
1526 psettings->lines_per_page = prt_get_lpp();
1527 psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE)
1528 ? prt_dlg.nCopies : 1;
1529 psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE)
1530 ? 1 : prt_dlg.nCopies;
1531
1532 if (psettings->n_collated_copies == 0)
1533 psettings->n_collated_copies = 1;
1534
1535 if (psettings->n_uncollated_copies == 0)
1536 psettings->n_uncollated_copies = 1;
1537
1538 psettings->jobname = jobname;
1539
1540 return TRUE;
1541
1542init_fail_dlg:
1543 {
1544 DWORD err = CommDlgExtendedError();
1545
1546 if (err)
1547 {
1548#ifdef WIN16
1549 char buf[20];
1550
1551 sprintf(buf, "%ld", err);
1552 EMSG2(_("E238: Print error: %s"), buf);
1553#else
1554 char_u *buf;
1555
1556 /* I suspect FormatMessage() doesn't work for values returned by
1557 * CommDlgExtendedError(). What does? */
1558 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
1559 FORMAT_MESSAGE_FROM_SYSTEM |
1560 FORMAT_MESSAGE_IGNORE_INSERTS,
1561 NULL, err, 0, (LPTSTR)(&buf), 0, NULL);
1562 EMSG2(_("E238: Print error: %s"),
1563 buf == NULL ? (char_u *)_("Unknown") : buf);
1564 LocalFree((LPVOID)(buf));
1565#endif
1566 }
1567 else
1568 msg_clr_eos(); /* Maybe canceled */
1569
1570 mch_print_cleanup();
1571 return FALSE;
1572 }
1573}
1574
1575
1576 int
1577mch_print_begin(prt_settings_T *psettings)
1578{
1579 int ret;
1580 static DOCINFO di;
1581 char szBuffer[300];
1582
1583 hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"),
1584 prt_dlg.hwndOwner, PrintDlgProc);
1585#ifdef WIN16
1586 Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL);
1587#else
1588 SetAbortProc(prt_dlg.hDC, AbortProc);
1589#endif
1590 wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname));
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001591 vimSetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02001593 vim_memset(&di, 0, sizeof(DOCINFO));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001594 di.cbSize = sizeof(DOCINFO);
1595 di.lpszDocName = psettings->jobname;
1596 ret = StartDoc(prt_dlg.hDC, &di);
1597
1598#ifdef FEAT_GUI
1599 /* Give focus back to main window (when using MDI). */
1600 SetFocus(s_hwnd);
1601#endif
1602
1603 return (ret > 0);
1604}
1605
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001606/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 void
1608mch_print_end(prt_settings_T *psettings)
1609{
1610 EndDoc(prt_dlg.hDC);
1611 if (!*bUserAbort)
1612 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1613}
1614
1615 int
1616mch_print_end_page(void)
1617{
1618 return (EndPage(prt_dlg.hDC) > 0);
1619}
1620
1621 int
1622mch_print_begin_page(char_u *msg)
1623{
1624 if (msg != NULL)
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001625 vimSetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001626 return (StartPage(prt_dlg.hDC) > 0);
1627}
1628
1629 int
1630mch_print_blank_page(void)
1631{
1632 return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
1633}
1634
1635static int prt_pos_x = 0;
1636static int prt_pos_y = 0;
1637
1638 void
1639mch_print_start_line(margin, page_line)
1640 int margin;
1641 int page_line;
1642{
1643 if (margin)
1644 prt_pos_x = -prt_number_width;
1645 else
1646 prt_pos_x = 0;
1647 prt_pos_y = page_line * prt_line_height
1648 + prt_tm.tmAscent + prt_tm.tmExternalLeading;
1649}
1650
1651 int
1652mch_print_text_out(char_u *p, int len)
1653{
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001654#if defined(FEAT_PROPORTIONAL_FONTS) || (defined(FEAT_MBYTE) && !defined(WIN16))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001655 SIZE sz;
1656#endif
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001657#if defined(FEAT_MBYTE) && !defined(WIN16)
1658 WCHAR *wp = NULL;
1659 int wlen = len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001660
Bram Moolenaar5246cd72013-06-16 16:41:47 +02001661 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1662 {
1663 wp = enc_to_utf16(p, &wlen);
1664 }
1665 if (wp != NULL)
1666 {
1667 int ret = FALSE;
1668
1669 TextOutW(prt_dlg.hDC, prt_pos_x + prt_left_margin,
1670 prt_pos_y + prt_top_margin, wp, wlen);
1671 GetTextExtentPoint32W(prt_dlg.hDC, wp, wlen, &sz);
1672 vim_free(wp);
1673 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
1674 /* This is wrong when printing spaces for a TAB. */
1675 if (p[len] != NUL)
1676 {
1677 wlen = MB_PTR2LEN(p + len);
1678 wp = enc_to_utf16(p + len, &wlen);
1679 if (wp != NULL)
1680 {
1681 GetTextExtentPoint32W(prt_dlg.hDC, wp, 1, &sz);
1682 ret = (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
1683 vim_free(wp);
1684 }
1685 }
1686 return ret;
1687 }
1688#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001689 TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin,
1690 prt_pos_y + prt_top_margin, p, len);
1691#ifndef FEAT_PROPORTIONAL_FONTS
1692 prt_pos_x += len * prt_tm.tmAveCharWidth;
1693 return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth
1694 + prt_tm.tmOverhang > prt_right_margin);
1695#else
1696# ifdef WIN16
1697 GetTextExtentPoint(prt_dlg.hDC, p, len, &sz);
1698# else
1699 GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz);
1700# endif
1701 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
1702 /* This is wrong when printing spaces for a TAB. */
1703 if (p[len] == NUL)
1704 return FALSE;
1705# ifdef WIN16
1706 GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz);
1707# else
1708 GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz);
1709# endif
1710 return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
1711#endif
1712}
1713
1714 void
1715mch_print_set_font(int iBold, int iItalic, int iUnderline)
1716{
1717 SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]);
1718}
1719
1720 void
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001721mch_print_set_bg(long_u bgcol)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001722{
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001723 SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
1724 swap_me((COLORREF)bgcol)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001725 /*
1726 * With a white background we can draw characters transparent, which is
1727 * good for italic characters that overlap to the next char cell.
1728 */
1729 if (bgcol == 0xffffffUL)
1730 SetBkMode(prt_dlg.hDC, TRANSPARENT);
1731 else
1732 SetBkMode(prt_dlg.hDC, OPAQUE);
1733}
1734
1735 void
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001736mch_print_set_fg(long_u fgcol)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001737{
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00001738 SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
1739 swap_me((COLORREF)fgcol)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001740}
1741
1742#endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
1743
Bram Moolenaar58d98232005-07-23 22:25:46 +00001744
1745
Bram Moolenaar071d4272004-06-13 20:20:40 +00001746#if defined(FEAT_SHORTCUT) || defined(PROTO)
Bram Moolenaar82881492012-11-20 16:53:39 +01001747# ifndef PROTO
1748# include <shlobj.h>
1749# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001750
1751/*
1752 * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
1753 * to and return that name in allocated memory.
1754 * Otherwise NULL is returned.
1755 */
1756 char_u *
1757mch_resolve_shortcut(char_u *fname)
1758{
1759 HRESULT hr;
1760 IShellLink *psl = NULL;
1761 IPersistFile *ppf = NULL;
1762 OLECHAR wsz[MAX_PATH];
1763 WIN32_FIND_DATA ffd; // we get those free of charge
Bram Moolenaar604729e2013-08-30 16:44:19 +02001764 CHAR buf[MAX_PATH]; // could have simply reused 'wsz'...
Bram Moolenaar071d4272004-06-13 20:20:40 +00001765 char_u *rfname = NULL;
1766 int len;
Bram Moolenaar604729e2013-08-30 16:44:19 +02001767# ifdef FEAT_MBYTE
1768 IShellLinkW *pslw = NULL;
1769 WIN32_FIND_DATAW ffdw; // we get those free of charge
1770# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001771
1772 /* Check if the file name ends in ".lnk". Avoid calling
1773 * CoCreateInstance(), it's quite slow. */
1774 if (fname == NULL)
1775 return rfname;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001776 len = (int)STRLEN(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001777 if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
1778 return rfname;
1779
1780 CoInitialize(NULL);
1781
Bram Moolenaar604729e2013-08-30 16:44:19 +02001782# ifdef FEAT_MBYTE
1783 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
1784 {
1785 // create a link manager object and request its interface
1786 hr = CoCreateInstance(
1787 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1788 &IID_IShellLinkW, (void**)&pslw);
1789 if (hr == S_OK)
1790 {
1791 WCHAR *p = enc_to_utf16(fname, NULL);
1792
1793 if (p != NULL)
1794 {
1795 // Get a pointer to the IPersistFile interface.
1796 hr = pslw->lpVtbl->QueryInterface(
1797 pslw, &IID_IPersistFile, (void**)&ppf);
1798 if (hr != S_OK)
1799 goto shortcut_errorw;
1800
1801 // "load" the name and resolve the link
1802 hr = ppf->lpVtbl->Load(ppf, p, STGM_READ);
1803 if (hr != S_OK)
1804 goto shortcut_errorw;
1805# if 0 // This makes Vim wait a long time if the target does not exist.
1806 hr = pslw->lpVtbl->Resolve(pslw, NULL, SLR_NO_UI);
1807 if (hr != S_OK)
1808 goto shortcut_errorw;
1809# endif
1810
1811 // Get the path to the link target.
1812 ZeroMemory(wsz, MAX_PATH * sizeof(WCHAR));
1813 hr = pslw->lpVtbl->GetPath(pslw, wsz, MAX_PATH, &ffdw, 0);
1814 if (hr == S_OK && wsz[0] != NUL)
1815 rfname = utf16_to_enc(wsz, NULL);
1816
1817shortcut_errorw:
1818 vim_free(p);
1819 if (hr == S_OK)
1820 goto shortcut_end;
1821 }
1822 }
1823 /* Retry with non-wide function (for Windows 98). */
1824 }
1825# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001826 // create a link manager object and request its interface
1827 hr = CoCreateInstance(
1828 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1829 &IID_IShellLink, (void**)&psl);
1830 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001831 goto shortcut_end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001832
1833 // Get a pointer to the IPersistFile interface.
1834 hr = psl->lpVtbl->QueryInterface(
1835 psl, &IID_IPersistFile, (void**)&ppf);
1836 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001837 goto shortcut_end;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001838
1839 // full path string must be in Unicode.
1840 MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
1841
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00001842 // "load" the name and resolve the link
Bram Moolenaar071d4272004-06-13 20:20:40 +00001843 hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
1844 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001845 goto shortcut_end;
1846# if 0 // This makes Vim wait a long time if the target doesn't exist.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001847 hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
1848 if (hr != S_OK)
Bram Moolenaar604729e2013-08-30 16:44:19 +02001849 goto shortcut_end;
1850# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001851
1852 // Get the path to the link target.
1853 ZeroMemory(buf, MAX_PATH);
1854 hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
1855 if (hr == S_OK && buf[0] != NUL)
1856 rfname = vim_strsave(buf);
1857
Bram Moolenaar604729e2013-08-30 16:44:19 +02001858shortcut_end:
Bram Moolenaar071d4272004-06-13 20:20:40 +00001859 // Release all interface pointers (both belong to the same object)
1860 if (ppf != NULL)
1861 ppf->lpVtbl->Release(ppf);
1862 if (psl != NULL)
1863 psl->lpVtbl->Release(psl);
Bram Moolenaar604729e2013-08-30 16:44:19 +02001864# ifdef FEAT_MBYTE
1865 if (pslw != NULL)
1866 pslw->lpVtbl->Release(pslw);
1867# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868
1869 CoUninitialize();
1870 return rfname;
1871}
1872#endif
1873
1874#if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
1875/*
1876 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
1877 */
1878 void
1879win32_set_foreground()
1880{
1881# ifndef FEAT_GUI
1882 GetConsoleHwnd(); /* get value of s_hwnd */
1883# endif
1884 if (s_hwnd != 0)
1885 SetForegroundWindow(s_hwnd);
1886}
1887#endif
1888
1889#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
1890/*
1891 * Client-server code for Vim
1892 *
1893 * Originally written by Paul Moore
1894 */
1895
1896/* In order to handle inter-process messages, we need to have a window. But
1897 * the functions in this module can be called before the main GUI window is
1898 * created (and may also be called in the console version, where there is no
1899 * GUI window at all).
1900 *
1901 * So we create a hidden window, and arrange to destroy it on exit.
1902 */
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001903HWND message_window = 0; /* window that's handling messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001904
1905#define VIM_CLASSNAME "VIM_MESSAGES"
1906#define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
1907
1908/* Communication is via WM_COPYDATA messages. The message type is send in
1909 * the dwData parameter. Types are defined here. */
1910#define COPYDATA_KEYS 0
1911#define COPYDATA_REPLY 1
1912#define COPYDATA_EXPR 10
1913#define COPYDATA_RESULT 11
1914#define COPYDATA_ERROR_RESULT 12
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001915#define COPYDATA_ENCODING 20
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916
1917/* This is a structure containing a server HWND and its name. */
1918struct server_id
1919{
1920 HWND hwnd;
1921 char_u *name;
1922};
1923
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001924/* Last received 'encoding' that the client uses. */
1925static char_u *client_enc = NULL;
1926
1927/*
1928 * Tell the other side what encoding we are using.
1929 * Errors are ignored.
1930 */
1931 static void
1932serverSendEnc(HWND target)
1933{
1934 COPYDATASTRUCT data;
1935
1936 data.dwData = COPYDATA_ENCODING;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001937#ifdef FEAT_MBYTE
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001938 data.cbData = (DWORD)STRLEN(p_enc) + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001939 data.lpData = p_enc;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001940#else
Bram Moolenaar8765a4a2010-07-27 22:41:43 +02001941 data.cbData = (DWORD)STRLEN("latin1") + 1;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001942 data.lpData = "latin1";
1943#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001944 (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
1945 (LPARAM)(&data));
1946}
1947
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948/*
1949 * Clean up on exit. This destroys the hidden message window.
1950 */
1951 static void
1952#ifdef __BORLANDC__
1953 _RTLENTRYF
1954#endif
1955CleanUpMessaging(void)
1956{
1957 if (message_window != 0)
1958 {
1959 DestroyWindow(message_window);
1960 message_window = 0;
1961 }
1962}
1963
1964static int save_reply(HWND server, char_u *reply, int expr);
1965
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001966/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001967 * The window procedure for the hidden message window.
1968 * It handles callback messages and notifications from servers.
1969 * In order to process these messages, it is necessary to run a
1970 * message loop. Code which may run before the main message loop
1971 * is started (in the GUI) is careful to pump messages when it needs
1972 * to. Features which require message delivery during normal use will
1973 * not work in the console version - this basically means those
1974 * features which allow Vim to act as a server, rather than a client.
1975 */
1976 static LRESULT CALLBACK
1977Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1978{
1979 if (msg == WM_COPYDATA)
1980 {
1981 /* This is a message from another Vim. The dwData member of the
1982 * COPYDATASTRUCT determines the type of message:
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001983 * COPYDATA_ENCODING:
1984 * The encoding that the client uses. Following messages will
1985 * use this encoding, convert if needed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001986 * COPYDATA_KEYS:
1987 * A key sequence. We are a server, and a client wants these keys
1988 * adding to the input queue.
1989 * COPYDATA_REPLY:
1990 * A reply. We are a client, and a server has sent this message
1991 * in response to a request. (server2client())
1992 * COPYDATA_EXPR:
1993 * An expression. We are a server, and a client wants us to
1994 * evaluate this expression.
1995 * COPYDATA_RESULT:
1996 * A reply. We are a client, and a server has sent this message
1997 * in response to a COPYDATA_EXPR.
1998 * COPYDATA_ERROR_RESULT:
1999 * A reply. We are a client, and a server has sent this message
2000 * in response to a COPYDATA_EXPR that failed to evaluate.
2001 */
2002 COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam;
2003 HWND sender = (HWND)wParam;
2004 COPYDATASTRUCT reply;
2005 char_u *res;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006 int retval;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002007 char_u *str;
2008 char_u *tofree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002009
2010 switch (data->dwData)
2011 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002012 case COPYDATA_ENCODING:
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002013# ifdef FEAT_MBYTE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002014 /* Remember the encoding that the client uses. */
2015 vim_free(client_enc);
2016 client_enc = enc_canonize((char_u *)data->lpData);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002017# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002018 return 1;
2019
Bram Moolenaar071d4272004-06-13 20:20:40 +00002020 case COPYDATA_KEYS:
2021 /* Remember who sent this, for <client> */
2022 clientWindow = sender;
2023
2024 /* Add the received keys to the input buffer. The loop waiting
2025 * for the user to do something should check the input buffer. */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002026 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2027 server_to_input_buf(str);
2028 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002029
2030# ifdef FEAT_GUI
2031 /* Wake up the main GUI loop. */
2032 if (s_hwnd != 0)
2033 PostMessage(s_hwnd, WM_NULL, 0, 0);
2034# endif
2035 return 1;
2036
2037 case COPYDATA_EXPR:
2038 /* Remember who sent this, for <client> */
2039 clientWindow = sender;
2040
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002041 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2042 res = eval_client_expr_to_string(str);
2043 vim_free(tofree);
2044
Bram Moolenaar071d4272004-06-13 20:20:40 +00002045 if (res == NULL)
2046 {
2047 res = vim_strsave(_(e_invexprmsg));
2048 reply.dwData = COPYDATA_ERROR_RESULT;
2049 }
2050 else
2051 reply.dwData = COPYDATA_RESULT;
2052 reply.lpData = res;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002053 reply.cbData = (DWORD)STRLEN(res) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002055 serverSendEnc(sender);
Bram Moolenaar5246cd72013-06-16 16:41:47 +02002056 retval = (int)SendMessage(sender, WM_COPYDATA,
2057 (WPARAM)message_window, (LPARAM)(&reply));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002058 vim_free(res);
2059 return retval;
2060
2061 case COPYDATA_REPLY:
2062 case COPYDATA_RESULT:
2063 case COPYDATA_ERROR_RESULT:
2064 if (data->lpData != NULL)
2065 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002066 str = serverConvert(client_enc, (char_u *)data->lpData,
2067 &tofree);
2068 if (tofree == NULL)
2069 str = vim_strsave(str);
2070 if (save_reply(sender, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 (data->dwData == COPYDATA_REPLY ? 0 :
2072 (data->dwData == COPYDATA_RESULT ? 1 :
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002073 2))) == FAIL)
2074 vim_free(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075#ifdef FEAT_AUTOCMD
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002076 else if (data->dwData == COPYDATA_REPLY)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077 {
Bram Moolenaar427d51c2013-06-16 16:01:25 +02002078 char_u winstr[30];
2079
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002080 sprintf((char *)winstr, PRINTF_HEX_LONG_U, (long_u)sender);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002081 apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002082 TRUE, curbuf);
2083 }
2084#endif
2085 }
2086 return 1;
2087 }
2088
2089 return 0;
2090 }
2091
2092 else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2093 {
2094 /* When the message window is activated (brought to the foreground),
2095 * this actually applies to the text window. */
2096#ifndef FEAT_GUI
2097 GetConsoleHwnd(); /* get value of s_hwnd */
2098#endif
2099 if (s_hwnd != 0)
2100 {
2101 SetForegroundWindow(s_hwnd);
2102 return 0;
2103 }
2104 }
2105
2106 return DefWindowProc(hwnd, msg, wParam, lParam);
2107}
2108
2109/*
2110 * Initialise the message handling process. This involves creating a window
2111 * to handle messages - the window will not be visible.
2112 */
2113 void
2114serverInitMessaging(void)
2115{
2116 WNDCLASS wndclass;
2117 HINSTANCE s_hinst;
2118
2119 /* Clean up on exit */
2120 atexit(CleanUpMessaging);
2121
2122 /* Register a window class - we only really care
2123 * about the window procedure
2124 */
2125 s_hinst = (HINSTANCE)GetModuleHandle(0);
2126 wndclass.style = 0;
2127 wndclass.lpfnWndProc = Messaging_WndProc;
2128 wndclass.cbClsExtra = 0;
2129 wndclass.cbWndExtra = 0;
2130 wndclass.hInstance = s_hinst;
2131 wndclass.hIcon = NULL;
2132 wndclass.hCursor = NULL;
2133 wndclass.hbrBackground = NULL;
2134 wndclass.lpszMenuName = NULL;
2135 wndclass.lpszClassName = VIM_CLASSNAME;
2136 RegisterClass(&wndclass);
2137
2138 /* Create the message window. It will be hidden, so the details don't
2139 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2140 * focus from gvim. */
2141 message_window = CreateWindow(VIM_CLASSNAME, "",
2142 WS_POPUPWINDOW | WS_CAPTION,
2143 CW_USEDEFAULT, CW_USEDEFAULT,
2144 100, 100, NULL, NULL,
2145 s_hinst, NULL);
2146}
2147
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002148/* Used by serverSendToVim() to find an alternate server name. */
2149static char_u *altname_buf_ptr = NULL;
2150
Bram Moolenaar071d4272004-06-13 20:20:40 +00002151/*
2152 * Get the title of the window "hwnd", which is the Vim server name, in
2153 * "name[namelen]" and return the length.
2154 * Returns zero if window "hwnd" is not a Vim server.
2155 */
2156 static int
2157getVimServerName(HWND hwnd, char *name, int namelen)
2158{
2159 int len;
2160 char buffer[VIM_CLASSNAME_LEN + 1];
2161
2162 /* Ignore windows which aren't Vim message windows */
2163 len = GetClassName(hwnd, buffer, sizeof(buffer));
2164 if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2165 return 0;
2166
2167 /* Get the title of the window */
2168 return GetWindowText(hwnd, name, namelen);
2169}
2170
2171 static BOOL CALLBACK
2172enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2173{
2174 struct server_id *id = (struct server_id *)lparam;
2175 char server[MAX_PATH];
2176
2177 /* Get the title of the window */
2178 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2179 return TRUE;
2180
2181 /* If this is the server we're looking for, return its HWND */
2182 if (STRICMP(server, id->name) == 0)
2183 {
2184 id->hwnd = hwnd;
2185 return FALSE;
2186 }
2187
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002188 /* If we are looking for an alternate server, remember this name. */
2189 if (altname_buf_ptr != NULL
2190 && STRNICMP(server, id->name, STRLEN(id->name)) == 0
2191 && vim_isdigit(server[STRLEN(id->name)]))
2192 {
2193 STRCPY(altname_buf_ptr, server);
2194 altname_buf_ptr = NULL; /* don't use another name */
2195 }
2196
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197 /* Otherwise, keep looking */
2198 return TRUE;
2199}
2200
2201 static BOOL CALLBACK
2202enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2203{
2204 garray_T *ga = (garray_T *)lparam;
2205 char server[MAX_PATH];
2206
2207 /* Get the title of the window */
2208 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2209 return TRUE;
2210
2211 /* Add the name to the list */
2212 ga_concat(ga, server);
2213 ga_concat(ga, "\n");
2214 return TRUE;
2215}
2216
2217 static HWND
2218findServer(char_u *name)
2219{
2220 struct server_id id;
2221
2222 id.name = name;
2223 id.hwnd = 0;
2224
2225 EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2226
2227 return id.hwnd;
2228}
2229
2230 void
2231serverSetName(char_u *name)
2232{
2233 char_u *ok_name;
2234 HWND hwnd = 0;
2235 int i = 0;
2236 char_u *p;
2237
2238 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002239 ok_name = alloc((unsigned)STRLEN(name) + 10);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240
2241 STRCPY(ok_name, name);
2242 p = ok_name + STRLEN(name);
2243
2244 for (;;)
2245 {
2246 /* This is inefficient - we're doing an EnumWindows loop for each
2247 * possible name. It would be better to grab all names in one go,
2248 * and scan the list each time...
2249 */
2250 hwnd = findServer(ok_name);
2251 if (hwnd == 0)
2252 break;
2253
2254 ++i;
2255 if (i >= 1000)
2256 break;
2257
2258 sprintf((char *)p, "%d", i);
2259 }
2260
2261 if (hwnd != 0)
2262 vim_free(ok_name);
2263 else
2264 {
2265 /* Remember the name */
2266 serverName = ok_name;
2267#ifdef FEAT_TITLE
2268 need_maketitle = TRUE; /* update Vim window title later */
2269#endif
2270
2271 /* Update the message window title */
2272 SetWindowText(message_window, ok_name);
2273
2274#ifdef FEAT_EVAL
2275 /* Set the servername variable */
2276 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2277#endif
2278 }
2279}
2280
2281 char_u *
2282serverGetVimNames(void)
2283{
2284 garray_T ga;
2285
2286 ga_init2(&ga, 1, 100);
2287
2288 EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
Bram Moolenaar269ec652004-07-29 08:43:53 +00002289 ga_append(&ga, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002290
2291 return ga.ga_data;
2292}
2293
2294 int
2295serverSendReply(name, reply)
2296 char_u *name; /* Where to send. */
2297 char_u *reply; /* What to send. */
2298{
2299 HWND target;
2300 COPYDATASTRUCT data;
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002301 long_u n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302
2303 /* The "name" argument is a magic cookie obtained from expand("<client>").
2304 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2305 * value of the client's message window HWND.
2306 */
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002307 sscanf((char *)name, SCANF_HEX_LONG_U, &n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 if (n == 0)
2309 return -1;
2310
2311 target = (HWND)n;
2312 if (!IsWindow(target))
2313 return -1;
2314
2315 data.dwData = COPYDATA_REPLY;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002316 data.cbData = (DWORD)STRLEN(reply) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317 data.lpData = reply;
2318
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002319 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2321 (LPARAM)(&data)))
2322 return 0;
2323
2324 return -1;
2325}
2326
2327 int
2328serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2329 char_u *name; /* Where to send. */
2330 char_u *cmd; /* What to send. */
2331 char_u **result; /* Result of eval'ed expression */
2332 void *ptarget; /* HWND of server */
2333 int asExpr; /* Expression or keys? */
2334 int silent; /* don't complain about no server */
2335{
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002336 HWND target;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 COPYDATASTRUCT data;
2338 char_u *retval = NULL;
2339 int retcode = 0;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002340 char_u altname_buf[MAX_PATH];
2341
2342 /* If the server name does not end in a digit then we look for an
2343 * alternate name. e.g. when "name" is GVIM the we may find GVIM2. */
2344 if (STRLEN(name) > 1 && !vim_isdigit(name[STRLEN(name) - 1]))
2345 altname_buf_ptr = altname_buf;
2346 altname_buf[0] = NUL;
2347 target = findServer(name);
2348 altname_buf_ptr = NULL;
2349 if (target == 0 && altname_buf[0] != NUL)
2350 /* Use another server name we found. */
2351 target = findServer(altname_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002352
2353 if (target == 0)
2354 {
2355 if (!silent)
2356 EMSG2(_(e_noserver), name);
2357 return -1;
2358 }
2359
2360 if (ptarget)
2361 *(HWND *)ptarget = target;
2362
2363 data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002364 data.cbData = (DWORD)STRLEN(cmd) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002365 data.lpData = cmd;
2366
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002367 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002368 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2369 (LPARAM)(&data)) == 0)
2370 return -1;
2371
2372 if (asExpr)
2373 retval = serverGetReply(target, &retcode, TRUE, TRUE);
2374
2375 if (result == NULL)
2376 vim_free(retval);
2377 else
2378 *result = retval; /* Caller assumes responsibility for freeing */
2379
2380 return retcode;
2381}
2382
2383/*
2384 * Bring the server to the foreground.
2385 */
2386 void
2387serverForeground(name)
2388 char_u *name;
2389{
2390 HWND target = findServer(name);
2391
2392 if (target != 0)
2393 SetForegroundWindow(target);
2394}
2395
2396/* Replies from server need to be stored until the client picks them up via
2397 * remote_read(). So we maintain a list of server-id/reply pairs.
2398 * Note that there could be multiple replies from one server pending if the
2399 * client is slow picking them up.
2400 * We just store the replies in a simple list. When we remove an entry, we
2401 * move list entries down to fill the gap.
2402 * The server ID is simply the HWND.
2403 */
2404typedef struct
2405{
2406 HWND server; /* server window */
2407 char_u *reply; /* reply string */
2408 int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002409} reply_T;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002410
2411static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
2412
2413#define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
2414#define REPLY_COUNT (reply_list.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415
2416/* Flag which is used to wait for a reply */
2417static int reply_received = 0;
2418
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002419/*
2420 * Store a reply. "reply" must be allocated memory (or NULL).
2421 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002422 static int
2423save_reply(HWND server, char_u *reply, int expr)
2424{
2425 reply_T *rep;
2426
2427 if (ga_grow(&reply_list, 1) == FAIL)
2428 return FAIL;
2429
2430 rep = REPLY_ITEM(REPLY_COUNT);
2431 rep->server = server;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002432 rep->reply = reply;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002433 rep->expr_result = expr;
2434 if (rep->reply == NULL)
2435 return FAIL;
2436
2437 ++REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002438 reply_received = 1;
2439 return OK;
2440}
2441
2442/*
2443 * Get a reply from server "server".
2444 * When "expr_res" is non NULL, get the result of an expression, otherwise a
2445 * server2client() message.
2446 * When non NULL, point to return code. 0 => OK, -1 => ERROR
2447 * If "remove" is TRUE, consume the message, the caller must free it then.
2448 * if "wait" is TRUE block until a message arrives (or the server exits).
2449 */
2450 char_u *
2451serverGetReply(HWND server, int *expr_res, int remove, int wait)
2452{
2453 int i;
2454 char_u *reply;
2455 reply_T *rep;
2456
2457 /* When waiting, loop until the message waiting for is received. */
2458 for (;;)
2459 {
2460 /* Reset this here, in case a message arrives while we are going
2461 * through the already received messages. */
2462 reply_received = 0;
2463
2464 for (i = 0; i < REPLY_COUNT; ++i)
2465 {
2466 rep = REPLY_ITEM(i);
2467 if (rep->server == server
2468 && ((rep->expr_result != 0) == (expr_res != NULL)))
2469 {
2470 /* Save the values we've found for later */
2471 reply = rep->reply;
2472 if (expr_res != NULL)
2473 *expr_res = rep->expr_result == 1 ? 0 : -1;
2474
2475 if (remove)
2476 {
2477 /* Move the rest of the list down to fill the gap */
2478 mch_memmove(rep, rep + 1,
2479 (REPLY_COUNT - i - 1) * sizeof(reply_T));
2480 --REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481 }
2482
2483 /* Return the reply to the caller, who takes on responsibility
2484 * for freeing it if "remove" is TRUE. */
2485 return reply;
2486 }
2487 }
2488
2489 /* If we got here, we didn't find a reply. Return immediately if the
2490 * "wait" parameter isn't set. */
2491 if (!wait)
2492 break;
2493
2494 /* We need to wait for a reply. Enter a message loop until the
2495 * "reply_received" flag gets set. */
2496
2497 /* Loop until we receive a reply */
2498 while (reply_received == 0)
2499 {
2500 /* Wait for a SendMessage() call to us. This could be the reply
2501 * we are waiting for. Use a timeout of a second, to catch the
2502 * situation that the server died unexpectedly. */
2503 MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
2504
2505 /* If the server has died, give up */
2506 if (!IsWindow(server))
2507 return NULL;
2508
2509 serverProcessPendingMessages();
2510 }
2511 }
2512
2513 return NULL;
2514}
2515
2516/*
2517 * Process any messages in the Windows message queue.
2518 */
2519 void
2520serverProcessPendingMessages(void)
2521{
2522 MSG msg;
2523
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02002524 while (pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002525 {
2526 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02002527 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002528 }
2529}
2530
2531#endif /* FEAT_CLIENTSERVER */
2532
2533#if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
2534 || defined(PROTO)
2535
2536struct charset_pair
2537{
2538 char *name;
2539 BYTE charset;
2540};
2541
2542static struct charset_pair
2543charset_pairs[] =
2544{
2545 {"ANSI", ANSI_CHARSET},
2546 {"CHINESEBIG5", CHINESEBIG5_CHARSET},
2547 {"DEFAULT", DEFAULT_CHARSET},
2548 {"HANGEUL", HANGEUL_CHARSET},
2549 {"OEM", OEM_CHARSET},
2550 {"SHIFTJIS", SHIFTJIS_CHARSET},
2551 {"SYMBOL", SYMBOL_CHARSET},
2552#ifdef WIN3264
2553 {"ARABIC", ARABIC_CHARSET},
2554 {"BALTIC", BALTIC_CHARSET},
2555 {"EASTEUROPE", EASTEUROPE_CHARSET},
2556 {"GB2312", GB2312_CHARSET},
2557 {"GREEK", GREEK_CHARSET},
2558 {"HEBREW", HEBREW_CHARSET},
2559 {"JOHAB", JOHAB_CHARSET},
2560 {"MAC", MAC_CHARSET},
2561 {"RUSSIAN", RUSSIAN_CHARSET},
2562 {"THAI", THAI_CHARSET},
2563 {"TURKISH", TURKISH_CHARSET},
2564# if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
2565 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
2566 {"VIETNAMESE", VIETNAMESE_CHARSET},
2567# endif
2568#endif
2569 {NULL, 0}
2570};
2571
2572/*
2573 * Convert a charset ID to a name.
2574 * Return NULL when not recognized.
2575 */
2576 char *
2577charset_id2name(int id)
2578{
2579 struct charset_pair *cp;
2580
2581 for (cp = charset_pairs; cp->name != NULL; ++cp)
2582 if ((BYTE)id == cp->charset)
2583 break;
2584 return cp->name;
2585}
2586
2587static const LOGFONT s_lfDefault =
2588{
2589 -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2590 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2591 PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
2592 "Fixedsys" /* see _ReadVimIni */
2593};
2594
2595/* Initialise the "current height" to -12 (same as s_lfDefault) just
2596 * in case the user specifies a font in "guifont" with no size before a font
2597 * with an explicit size has been set. This defaults the size to this value
2598 * (-12 equates to roughly 9pt).
2599 */
2600int current_font_height = -12; /* also used in gui_w48.c */
2601
2602/* Convert a string representing a point size into pixels. The string should
2603 * be a positive decimal number, with an optional decimal point (eg, "12", or
2604 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
2605 * character is stored in *end. The flag "vertical" says whether this
2606 * calculation is for a vertical (height) size or a horizontal (width) one.
2607 */
2608 static int
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002609points_to_pixels(char_u *str, char_u **end, int vertical, long_i pprinter_dc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002610{
2611 int pixels;
2612 int points = 0;
2613 int divisor = 0;
2614 HWND hwnd = (HWND)0;
2615 HDC hdc;
2616 HDC printer_dc = (HDC)pprinter_dc;
2617
2618 while (*str != NUL)
2619 {
2620 if (*str == '.' && divisor == 0)
2621 {
2622 /* Start keeping a divisor, for later */
2623 divisor = 1;
2624 }
2625 else
2626 {
2627 if (!VIM_ISDIGIT(*str))
2628 break;
2629
2630 points *= 10;
2631 points += *str - '0';
2632 divisor *= 10;
2633 }
2634 ++str;
2635 }
2636
2637 if (divisor == 0)
2638 divisor = 1;
2639
2640 if (printer_dc == NULL)
2641 {
2642 hwnd = GetDesktopWindow();
2643 hdc = GetWindowDC(hwnd);
2644 }
2645 else
2646 hdc = printer_dc;
2647
2648 pixels = MulDiv(points,
2649 GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
2650 72 * divisor);
2651
2652 if (printer_dc == NULL)
2653 ReleaseDC(hwnd, hdc);
2654
2655 *end = str;
2656 return pixels;
2657}
2658
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002659/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002660 static int CALLBACK
2661font_enumproc(
2662 ENUMLOGFONT *elf,
2663 NEWTEXTMETRIC *ntm,
2664 int type,
2665 LPARAM lparam)
2666{
2667 /* Return value:
2668 * 0 = terminate now (monospace & ANSI)
2669 * 1 = continue, still no luck...
2670 * 2 = continue, but we have an acceptable LOGFONT
2671 * (monospace, not ANSI)
2672 * We use these values, as EnumFontFamilies returns 1 if the
2673 * callback function is never called. So, we check the return as
2674 * 0 = perfect, 2 = OK, 1 = no good...
2675 * It's not pretty, but it works!
2676 */
2677
2678 LOGFONT *lf = (LOGFONT *)(lparam);
2679
2680#ifndef FEAT_PROPORTIONAL_FONTS
2681 /* Ignore non-monospace fonts without further ado */
2682 if ((ntm->tmPitchAndFamily & 1) != 0)
2683 return 1;
2684#endif
2685
2686 /* Remember this LOGFONT as a "possible" */
2687 *lf = elf->elfLogFont;
2688
2689 /* Terminate the scan as soon as we find an ANSI font */
2690 if (lf->lfCharSet == ANSI_CHARSET
2691 || lf->lfCharSet == OEM_CHARSET
2692 || lf->lfCharSet == DEFAULT_CHARSET)
2693 return 0;
2694
2695 /* Continue the scan - we have a non-ANSI font */
2696 return 2;
2697}
2698
2699 static int
2700init_logfont(LOGFONT *lf)
2701{
2702 int n;
2703 HWND hwnd = GetDesktopWindow();
2704 HDC hdc = GetWindowDC(hwnd);
2705
2706 n = EnumFontFamilies(hdc,
2707 (LPCSTR)lf->lfFaceName,
2708 (FONTENUMPROC)font_enumproc,
2709 (LPARAM)lf);
2710
2711 ReleaseDC(hwnd, hdc);
2712
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002713 /* If we couldn't find a usable font, return failure */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002714 if (n == 1)
2715 return FAIL;
2716
2717 /* Tidy up the rest of the LOGFONT structure. We set to a basic
2718 * font - get_logfont() sets bold, italic, etc based on the user's
2719 * input.
2720 */
2721 lf->lfHeight = current_font_height;
2722 lf->lfWidth = 0;
2723 lf->lfItalic = FALSE;
2724 lf->lfUnderline = FALSE;
2725 lf->lfStrikeOut = FALSE;
2726 lf->lfWeight = FW_NORMAL;
2727
2728 /* Return success */
2729 return OK;
2730}
2731
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002732/*
2733 * Get font info from "name" into logfont "lf".
2734 * Return OK for a valid name, FAIL otherwise.
2735 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002736 int
2737get_logfont(
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002738 LOGFONT *lf,
2739 char_u *name,
2740 HDC printer_dc,
2741 int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002742{
2743 char_u *p;
2744 int i;
2745 static LOGFONT *lastlf = NULL;
2746
2747 *lf = s_lfDefault;
2748 if (name == NULL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002749 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002750
2751 if (STRCMP(name, "*") == 0)
2752 {
2753#if defined(FEAT_GUI_W32)
2754 CHOOSEFONT cf;
2755 /* if name is "*", bring up std font dialog: */
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02002756 vim_memset(&cf, 0, sizeof(cf));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002757 cf.lStructSize = sizeof(cf);
2758 cf.hwndOwner = s_hwnd;
2759 cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
2760 if (lastlf != NULL)
2761 *lf = *lastlf;
2762 cf.lpLogFont = lf;
2763 cf.nFontType = 0 ; //REGULAR_FONTTYPE;
2764 if (ChooseFont(&cf))
2765 goto theend;
2766#else
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002767 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002768#endif
2769 }
2770
2771 /*
2772 * Split name up, it could be <name>:h<height>:w<width> etc.
2773 */
2774 for (p = name; *p && *p != ':'; p++)
2775 {
2776 if (p - name + 1 > LF_FACESIZE)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002777 return FAIL; /* Name too long */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002778 lf->lfFaceName[p - name] = *p;
2779 }
2780 if (p != name)
2781 lf->lfFaceName[p - name] = NUL;
2782
2783 /* First set defaults */
2784 lf->lfHeight = -12;
2785 lf->lfWidth = 0;
2786 lf->lfWeight = FW_NORMAL;
2787 lf->lfItalic = FALSE;
2788 lf->lfUnderline = FALSE;
2789 lf->lfStrikeOut = FALSE;
2790
2791 /*
2792 * If the font can't be found, try replacing '_' by ' '.
2793 */
2794 if (init_logfont(lf) == FAIL)
2795 {
2796 int did_replace = FALSE;
2797
2798 for (i = 0; lf->lfFaceName[i]; ++i)
2799 if (lf->lfFaceName[i] == '_')
2800 {
2801 lf->lfFaceName[i] = ' ';
2802 did_replace = TRUE;
2803 }
2804 if (!did_replace || init_logfont(lf) == FAIL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002805 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002806 }
2807
2808 while (*p == ':')
2809 p++;
2810
2811 /* Set the values found after ':' */
2812 while (*p)
2813 {
2814 switch (*p++)
2815 {
2816 case 'h':
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002817 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (long_i)printer_dc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002818 break;
2819 case 'w':
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002820 lf->lfWidth = points_to_pixels(p, &p, FALSE, (long_i)printer_dc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002821 break;
2822 case 'b':
2823#ifndef MSWIN16_FASTTEXT
2824 lf->lfWeight = FW_BOLD;
2825#endif
2826 break;
2827 case 'i':
2828#ifndef MSWIN16_FASTTEXT
2829 lf->lfItalic = TRUE;
2830#endif
2831 break;
2832 case 'u':
2833 lf->lfUnderline = TRUE;
2834 break;
2835 case 's':
2836 lf->lfStrikeOut = TRUE;
2837 break;
2838 case 'c':
2839 {
2840 struct charset_pair *cp;
2841
2842 for (cp = charset_pairs; cp->name != NULL; ++cp)
2843 if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
2844 {
2845 lf->lfCharSet = cp->charset;
2846 p += strlen(cp->name);
2847 break;
2848 }
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002849 if (cp->name == NULL && verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002850 {
Bram Moolenaar051b7822005-05-19 21:00:46 +00002851 vim_snprintf((char *)IObuff, IOSIZE,
2852 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853 EMSG(IObuff);
2854 break;
2855 }
2856 break;
2857 }
2858 default:
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002859 if (verbose)
2860 {
Bram Moolenaar051b7822005-05-19 21:00:46 +00002861 vim_snprintf((char *)IObuff, IOSIZE,
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002862 _("E245: Illegal char '%c' in font name \"%s\""),
2863 p[-1], name);
2864 EMSG(IObuff);
2865 }
2866 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002867 }
2868 while (*p == ':')
2869 p++;
2870 }
2871
2872#if defined(FEAT_GUI_W32)
2873theend:
2874#endif
2875 /* ron: init lastlf */
2876 if (printer_dc == NULL)
2877 {
2878 vim_free(lastlf);
2879 lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
2880 if (lastlf != NULL)
2881 mch_memmove(lastlf, lf, sizeof(LOGFONT));
2882 }
2883
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002884 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885}
2886
2887#endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */