blob: 96d3448c33677fbd004cea248578cddf723347a9 [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
1764 TCHAR buf[MAX_PATH]; // could have simply reused 'wsz'...
1765 char_u *rfname = NULL;
1766 int len;
1767
1768 /* Check if the file name ends in ".lnk". Avoid calling
1769 * CoCreateInstance(), it's quite slow. */
1770 if (fname == NULL)
1771 return rfname;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001772 len = (int)STRLEN(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
1774 return rfname;
1775
1776 CoInitialize(NULL);
1777
1778 // create a link manager object and request its interface
1779 hr = CoCreateInstance(
1780 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
1781 &IID_IShellLink, (void**)&psl);
1782 if (hr != S_OK)
1783 goto shortcut_error;
1784
1785 // Get a pointer to the IPersistFile interface.
1786 hr = psl->lpVtbl->QueryInterface(
1787 psl, &IID_IPersistFile, (void**)&ppf);
1788 if (hr != S_OK)
1789 goto shortcut_error;
1790
1791 // full path string must be in Unicode.
1792 MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
1793
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00001794 // "load" the name and resolve the link
Bram Moolenaar071d4272004-06-13 20:20:40 +00001795 hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
1796 if (hr != S_OK)
1797 goto shortcut_error;
1798#if 0 // This makes Vim wait a long time if the target doesn't exist.
1799 hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
1800 if (hr != S_OK)
1801 goto shortcut_error;
1802#endif
1803
1804 // Get the path to the link target.
1805 ZeroMemory(buf, MAX_PATH);
1806 hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
1807 if (hr == S_OK && buf[0] != NUL)
1808 rfname = vim_strsave(buf);
1809
1810shortcut_error:
1811 // Release all interface pointers (both belong to the same object)
1812 if (ppf != NULL)
1813 ppf->lpVtbl->Release(ppf);
1814 if (psl != NULL)
1815 psl->lpVtbl->Release(psl);
1816
1817 CoUninitialize();
1818 return rfname;
1819}
1820#endif
1821
1822#if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
1823/*
1824 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
1825 */
1826 void
1827win32_set_foreground()
1828{
1829# ifndef FEAT_GUI
1830 GetConsoleHwnd(); /* get value of s_hwnd */
1831# endif
1832 if (s_hwnd != 0)
1833 SetForegroundWindow(s_hwnd);
1834}
1835#endif
1836
1837#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
1838/*
1839 * Client-server code for Vim
1840 *
1841 * Originally written by Paul Moore
1842 */
1843
1844/* In order to handle inter-process messages, we need to have a window. But
1845 * the functions in this module can be called before the main GUI window is
1846 * created (and may also be called in the console version, where there is no
1847 * GUI window at all).
1848 *
1849 * So we create a hidden window, and arrange to destroy it on exit.
1850 */
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001851HWND message_window = 0; /* window that's handling messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001852
1853#define VIM_CLASSNAME "VIM_MESSAGES"
1854#define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
1855
1856/* Communication is via WM_COPYDATA messages. The message type is send in
1857 * the dwData parameter. Types are defined here. */
1858#define COPYDATA_KEYS 0
1859#define COPYDATA_REPLY 1
1860#define COPYDATA_EXPR 10
1861#define COPYDATA_RESULT 11
1862#define COPYDATA_ERROR_RESULT 12
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001863#define COPYDATA_ENCODING 20
Bram Moolenaar071d4272004-06-13 20:20:40 +00001864
1865/* This is a structure containing a server HWND and its name. */
1866struct server_id
1867{
1868 HWND hwnd;
1869 char_u *name;
1870};
1871
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001872/* Last received 'encoding' that the client uses. */
1873static char_u *client_enc = NULL;
1874
1875/*
1876 * Tell the other side what encoding we are using.
1877 * Errors are ignored.
1878 */
1879 static void
1880serverSendEnc(HWND target)
1881{
1882 COPYDATASTRUCT data;
1883
1884 data.dwData = COPYDATA_ENCODING;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001885#ifdef FEAT_MBYTE
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001886 data.cbData = (DWORD)STRLEN(p_enc) + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001887 data.lpData = p_enc;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001888#else
Bram Moolenaar8765a4a2010-07-27 22:41:43 +02001889 data.cbData = (DWORD)STRLEN("latin1") + 1;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001890 data.lpData = "latin1";
1891#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001892 (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
1893 (LPARAM)(&data));
1894}
1895
Bram Moolenaar071d4272004-06-13 20:20:40 +00001896/*
1897 * Clean up on exit. This destroys the hidden message window.
1898 */
1899 static void
1900#ifdef __BORLANDC__
1901 _RTLENTRYF
1902#endif
1903CleanUpMessaging(void)
1904{
1905 if (message_window != 0)
1906 {
1907 DestroyWindow(message_window);
1908 message_window = 0;
1909 }
1910}
1911
1912static int save_reply(HWND server, char_u *reply, int expr);
1913
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02001914/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915 * The window procedure for the hidden message window.
1916 * It handles callback messages and notifications from servers.
1917 * In order to process these messages, it is necessary to run a
1918 * message loop. Code which may run before the main message loop
1919 * is started (in the GUI) is careful to pump messages when it needs
1920 * to. Features which require message delivery during normal use will
1921 * not work in the console version - this basically means those
1922 * features which allow Vim to act as a server, rather than a client.
1923 */
1924 static LRESULT CALLBACK
1925Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
1926{
1927 if (msg == WM_COPYDATA)
1928 {
1929 /* This is a message from another Vim. The dwData member of the
1930 * COPYDATASTRUCT determines the type of message:
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001931 * COPYDATA_ENCODING:
1932 * The encoding that the client uses. Following messages will
1933 * use this encoding, convert if needed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934 * COPYDATA_KEYS:
1935 * A key sequence. We are a server, and a client wants these keys
1936 * adding to the input queue.
1937 * COPYDATA_REPLY:
1938 * A reply. We are a client, and a server has sent this message
1939 * in response to a request. (server2client())
1940 * COPYDATA_EXPR:
1941 * An expression. We are a server, and a client wants us to
1942 * evaluate this expression.
1943 * COPYDATA_RESULT:
1944 * A reply. We are a client, and a server has sent this message
1945 * in response to a COPYDATA_EXPR.
1946 * COPYDATA_ERROR_RESULT:
1947 * A reply. We are a client, and a server has sent this message
1948 * in response to a COPYDATA_EXPR that failed to evaluate.
1949 */
1950 COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam;
1951 HWND sender = (HWND)wParam;
1952 COPYDATASTRUCT reply;
1953 char_u *res;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001954 int retval;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001955 char_u *str;
1956 char_u *tofree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957
1958 switch (data->dwData)
1959 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001960 case COPYDATA_ENCODING:
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001961# ifdef FEAT_MBYTE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001962 /* Remember the encoding that the client uses. */
1963 vim_free(client_enc);
1964 client_enc = enc_canonize((char_u *)data->lpData);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00001965# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001966 return 1;
1967
Bram Moolenaar071d4272004-06-13 20:20:40 +00001968 case COPYDATA_KEYS:
1969 /* Remember who sent this, for <client> */
1970 clientWindow = sender;
1971
1972 /* Add the received keys to the input buffer. The loop waiting
1973 * for the user to do something should check the input buffer. */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001974 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
1975 server_to_input_buf(str);
1976 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001977
1978# ifdef FEAT_GUI
1979 /* Wake up the main GUI loop. */
1980 if (s_hwnd != 0)
1981 PostMessage(s_hwnd, WM_NULL, 0, 0);
1982# endif
1983 return 1;
1984
1985 case COPYDATA_EXPR:
1986 /* Remember who sent this, for <client> */
1987 clientWindow = sender;
1988
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00001989 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
1990 res = eval_client_expr_to_string(str);
1991 vim_free(tofree);
1992
Bram Moolenaar071d4272004-06-13 20:20:40 +00001993 if (res == NULL)
1994 {
1995 res = vim_strsave(_(e_invexprmsg));
1996 reply.dwData = COPYDATA_ERROR_RESULT;
1997 }
1998 else
1999 reply.dwData = COPYDATA_RESULT;
2000 reply.lpData = res;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002001 reply.cbData = (DWORD)STRLEN(res) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002003 serverSendEnc(sender);
Bram Moolenaar5246cd72013-06-16 16:41:47 +02002004 retval = (int)SendMessage(sender, WM_COPYDATA,
2005 (WPARAM)message_window, (LPARAM)(&reply));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002006 vim_free(res);
2007 return retval;
2008
2009 case COPYDATA_REPLY:
2010 case COPYDATA_RESULT:
2011 case COPYDATA_ERROR_RESULT:
2012 if (data->lpData != NULL)
2013 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002014 str = serverConvert(client_enc, (char_u *)data->lpData,
2015 &tofree);
2016 if (tofree == NULL)
2017 str = vim_strsave(str);
2018 if (save_reply(sender, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002019 (data->dwData == COPYDATA_REPLY ? 0 :
2020 (data->dwData == COPYDATA_RESULT ? 1 :
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002021 2))) == FAIL)
2022 vim_free(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023#ifdef FEAT_AUTOCMD
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002024 else if (data->dwData == COPYDATA_REPLY)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 {
Bram Moolenaar427d51c2013-06-16 16:01:25 +02002026 char_u winstr[30];
2027
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002028 sprintf((char *)winstr, PRINTF_HEX_LONG_U, (long_u)sender);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002029 apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002030 TRUE, curbuf);
2031 }
2032#endif
2033 }
2034 return 1;
2035 }
2036
2037 return 0;
2038 }
2039
2040 else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2041 {
2042 /* When the message window is activated (brought to the foreground),
2043 * this actually applies to the text window. */
2044#ifndef FEAT_GUI
2045 GetConsoleHwnd(); /* get value of s_hwnd */
2046#endif
2047 if (s_hwnd != 0)
2048 {
2049 SetForegroundWindow(s_hwnd);
2050 return 0;
2051 }
2052 }
2053
2054 return DefWindowProc(hwnd, msg, wParam, lParam);
2055}
2056
2057/*
2058 * Initialise the message handling process. This involves creating a window
2059 * to handle messages - the window will not be visible.
2060 */
2061 void
2062serverInitMessaging(void)
2063{
2064 WNDCLASS wndclass;
2065 HINSTANCE s_hinst;
2066
2067 /* Clean up on exit */
2068 atexit(CleanUpMessaging);
2069
2070 /* Register a window class - we only really care
2071 * about the window procedure
2072 */
2073 s_hinst = (HINSTANCE)GetModuleHandle(0);
2074 wndclass.style = 0;
2075 wndclass.lpfnWndProc = Messaging_WndProc;
2076 wndclass.cbClsExtra = 0;
2077 wndclass.cbWndExtra = 0;
2078 wndclass.hInstance = s_hinst;
2079 wndclass.hIcon = NULL;
2080 wndclass.hCursor = NULL;
2081 wndclass.hbrBackground = NULL;
2082 wndclass.lpszMenuName = NULL;
2083 wndclass.lpszClassName = VIM_CLASSNAME;
2084 RegisterClass(&wndclass);
2085
2086 /* Create the message window. It will be hidden, so the details don't
2087 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2088 * focus from gvim. */
2089 message_window = CreateWindow(VIM_CLASSNAME, "",
2090 WS_POPUPWINDOW | WS_CAPTION,
2091 CW_USEDEFAULT, CW_USEDEFAULT,
2092 100, 100, NULL, NULL,
2093 s_hinst, NULL);
2094}
2095
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002096/* Used by serverSendToVim() to find an alternate server name. */
2097static char_u *altname_buf_ptr = NULL;
2098
Bram Moolenaar071d4272004-06-13 20:20:40 +00002099/*
2100 * Get the title of the window "hwnd", which is the Vim server name, in
2101 * "name[namelen]" and return the length.
2102 * Returns zero if window "hwnd" is not a Vim server.
2103 */
2104 static int
2105getVimServerName(HWND hwnd, char *name, int namelen)
2106{
2107 int len;
2108 char buffer[VIM_CLASSNAME_LEN + 1];
2109
2110 /* Ignore windows which aren't Vim message windows */
2111 len = GetClassName(hwnd, buffer, sizeof(buffer));
2112 if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2113 return 0;
2114
2115 /* Get the title of the window */
2116 return GetWindowText(hwnd, name, namelen);
2117}
2118
2119 static BOOL CALLBACK
2120enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2121{
2122 struct server_id *id = (struct server_id *)lparam;
2123 char server[MAX_PATH];
2124
2125 /* Get the title of the window */
2126 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2127 return TRUE;
2128
2129 /* If this is the server we're looking for, return its HWND */
2130 if (STRICMP(server, id->name) == 0)
2131 {
2132 id->hwnd = hwnd;
2133 return FALSE;
2134 }
2135
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002136 /* If we are looking for an alternate server, remember this name. */
2137 if (altname_buf_ptr != NULL
2138 && STRNICMP(server, id->name, STRLEN(id->name)) == 0
2139 && vim_isdigit(server[STRLEN(id->name)]))
2140 {
2141 STRCPY(altname_buf_ptr, server);
2142 altname_buf_ptr = NULL; /* don't use another name */
2143 }
2144
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 /* Otherwise, keep looking */
2146 return TRUE;
2147}
2148
2149 static BOOL CALLBACK
2150enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2151{
2152 garray_T *ga = (garray_T *)lparam;
2153 char server[MAX_PATH];
2154
2155 /* Get the title of the window */
2156 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2157 return TRUE;
2158
2159 /* Add the name to the list */
2160 ga_concat(ga, server);
2161 ga_concat(ga, "\n");
2162 return TRUE;
2163}
2164
2165 static HWND
2166findServer(char_u *name)
2167{
2168 struct server_id id;
2169
2170 id.name = name;
2171 id.hwnd = 0;
2172
2173 EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2174
2175 return id.hwnd;
2176}
2177
2178 void
2179serverSetName(char_u *name)
2180{
2181 char_u *ok_name;
2182 HWND hwnd = 0;
2183 int i = 0;
2184 char_u *p;
2185
2186 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002187 ok_name = alloc((unsigned)STRLEN(name) + 10);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002188
2189 STRCPY(ok_name, name);
2190 p = ok_name + STRLEN(name);
2191
2192 for (;;)
2193 {
2194 /* This is inefficient - we're doing an EnumWindows loop for each
2195 * possible name. It would be better to grab all names in one go,
2196 * and scan the list each time...
2197 */
2198 hwnd = findServer(ok_name);
2199 if (hwnd == 0)
2200 break;
2201
2202 ++i;
2203 if (i >= 1000)
2204 break;
2205
2206 sprintf((char *)p, "%d", i);
2207 }
2208
2209 if (hwnd != 0)
2210 vim_free(ok_name);
2211 else
2212 {
2213 /* Remember the name */
2214 serverName = ok_name;
2215#ifdef FEAT_TITLE
2216 need_maketitle = TRUE; /* update Vim window title later */
2217#endif
2218
2219 /* Update the message window title */
2220 SetWindowText(message_window, ok_name);
2221
2222#ifdef FEAT_EVAL
2223 /* Set the servername variable */
2224 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2225#endif
2226 }
2227}
2228
2229 char_u *
2230serverGetVimNames(void)
2231{
2232 garray_T ga;
2233
2234 ga_init2(&ga, 1, 100);
2235
2236 EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
Bram Moolenaar269ec652004-07-29 08:43:53 +00002237 ga_append(&ga, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002238
2239 return ga.ga_data;
2240}
2241
2242 int
2243serverSendReply(name, reply)
2244 char_u *name; /* Where to send. */
2245 char_u *reply; /* What to send. */
2246{
2247 HWND target;
2248 COPYDATASTRUCT data;
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002249 long_u n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002250
2251 /* The "name" argument is a magic cookie obtained from expand("<client>").
2252 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2253 * value of the client's message window HWND.
2254 */
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002255 sscanf((char *)name, SCANF_HEX_LONG_U, &n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256 if (n == 0)
2257 return -1;
2258
2259 target = (HWND)n;
2260 if (!IsWindow(target))
2261 return -1;
2262
2263 data.dwData = COPYDATA_REPLY;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002264 data.cbData = (DWORD)STRLEN(reply) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002265 data.lpData = reply;
2266
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002267 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2269 (LPARAM)(&data)))
2270 return 0;
2271
2272 return -1;
2273}
2274
2275 int
2276serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2277 char_u *name; /* Where to send. */
2278 char_u *cmd; /* What to send. */
2279 char_u **result; /* Result of eval'ed expression */
2280 void *ptarget; /* HWND of server */
2281 int asExpr; /* Expression or keys? */
2282 int silent; /* don't complain about no server */
2283{
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002284 HWND target;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 COPYDATASTRUCT data;
2286 char_u *retval = NULL;
2287 int retcode = 0;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002288 char_u altname_buf[MAX_PATH];
2289
2290 /* If the server name does not end in a digit then we look for an
2291 * alternate name. e.g. when "name" is GVIM the we may find GVIM2. */
2292 if (STRLEN(name) > 1 && !vim_isdigit(name[STRLEN(name) - 1]))
2293 altname_buf_ptr = altname_buf;
2294 altname_buf[0] = NUL;
2295 target = findServer(name);
2296 altname_buf_ptr = NULL;
2297 if (target == 0 && altname_buf[0] != NUL)
2298 /* Use another server name we found. */
2299 target = findServer(altname_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300
2301 if (target == 0)
2302 {
2303 if (!silent)
2304 EMSG2(_(e_noserver), name);
2305 return -1;
2306 }
2307
2308 if (ptarget)
2309 *(HWND *)ptarget = target;
2310
2311 data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002312 data.cbData = (DWORD)STRLEN(cmd) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313 data.lpData = cmd;
2314
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002315 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2317 (LPARAM)(&data)) == 0)
2318 return -1;
2319
2320 if (asExpr)
2321 retval = serverGetReply(target, &retcode, TRUE, TRUE);
2322
2323 if (result == NULL)
2324 vim_free(retval);
2325 else
2326 *result = retval; /* Caller assumes responsibility for freeing */
2327
2328 return retcode;
2329}
2330
2331/*
2332 * Bring the server to the foreground.
2333 */
2334 void
2335serverForeground(name)
2336 char_u *name;
2337{
2338 HWND target = findServer(name);
2339
2340 if (target != 0)
2341 SetForegroundWindow(target);
2342}
2343
2344/* Replies from server need to be stored until the client picks them up via
2345 * remote_read(). So we maintain a list of server-id/reply pairs.
2346 * Note that there could be multiple replies from one server pending if the
2347 * client is slow picking them up.
2348 * We just store the replies in a simple list. When we remove an entry, we
2349 * move list entries down to fill the gap.
2350 * The server ID is simply the HWND.
2351 */
2352typedef struct
2353{
2354 HWND server; /* server window */
2355 char_u *reply; /* reply string */
2356 int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002357} reply_T;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002358
2359static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
2360
2361#define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
2362#define REPLY_COUNT (reply_list.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002363
2364/* Flag which is used to wait for a reply */
2365static int reply_received = 0;
2366
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002367/*
2368 * Store a reply. "reply" must be allocated memory (or NULL).
2369 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002370 static int
2371save_reply(HWND server, char_u *reply, int expr)
2372{
2373 reply_T *rep;
2374
2375 if (ga_grow(&reply_list, 1) == FAIL)
2376 return FAIL;
2377
2378 rep = REPLY_ITEM(REPLY_COUNT);
2379 rep->server = server;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002380 rep->reply = reply;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002381 rep->expr_result = expr;
2382 if (rep->reply == NULL)
2383 return FAIL;
2384
2385 ++REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386 reply_received = 1;
2387 return OK;
2388}
2389
2390/*
2391 * Get a reply from server "server".
2392 * When "expr_res" is non NULL, get the result of an expression, otherwise a
2393 * server2client() message.
2394 * When non NULL, point to return code. 0 => OK, -1 => ERROR
2395 * If "remove" is TRUE, consume the message, the caller must free it then.
2396 * if "wait" is TRUE block until a message arrives (or the server exits).
2397 */
2398 char_u *
2399serverGetReply(HWND server, int *expr_res, int remove, int wait)
2400{
2401 int i;
2402 char_u *reply;
2403 reply_T *rep;
2404
2405 /* When waiting, loop until the message waiting for is received. */
2406 for (;;)
2407 {
2408 /* Reset this here, in case a message arrives while we are going
2409 * through the already received messages. */
2410 reply_received = 0;
2411
2412 for (i = 0; i < REPLY_COUNT; ++i)
2413 {
2414 rep = REPLY_ITEM(i);
2415 if (rep->server == server
2416 && ((rep->expr_result != 0) == (expr_res != NULL)))
2417 {
2418 /* Save the values we've found for later */
2419 reply = rep->reply;
2420 if (expr_res != NULL)
2421 *expr_res = rep->expr_result == 1 ? 0 : -1;
2422
2423 if (remove)
2424 {
2425 /* Move the rest of the list down to fill the gap */
2426 mch_memmove(rep, rep + 1,
2427 (REPLY_COUNT - i - 1) * sizeof(reply_T));
2428 --REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002429 }
2430
2431 /* Return the reply to the caller, who takes on responsibility
2432 * for freeing it if "remove" is TRUE. */
2433 return reply;
2434 }
2435 }
2436
2437 /* If we got here, we didn't find a reply. Return immediately if the
2438 * "wait" parameter isn't set. */
2439 if (!wait)
2440 break;
2441
2442 /* We need to wait for a reply. Enter a message loop until the
2443 * "reply_received" flag gets set. */
2444
2445 /* Loop until we receive a reply */
2446 while (reply_received == 0)
2447 {
2448 /* Wait for a SendMessage() call to us. This could be the reply
2449 * we are waiting for. Use a timeout of a second, to catch the
2450 * situation that the server died unexpectedly. */
2451 MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
2452
2453 /* If the server has died, give up */
2454 if (!IsWindow(server))
2455 return NULL;
2456
2457 serverProcessPendingMessages();
2458 }
2459 }
2460
2461 return NULL;
2462}
2463
2464/*
2465 * Process any messages in the Windows message queue.
2466 */
2467 void
2468serverProcessPendingMessages(void)
2469{
2470 MSG msg;
2471
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02002472 while (pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 {
2474 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02002475 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002476 }
2477}
2478
2479#endif /* FEAT_CLIENTSERVER */
2480
2481#if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
2482 || defined(PROTO)
2483
2484struct charset_pair
2485{
2486 char *name;
2487 BYTE charset;
2488};
2489
2490static struct charset_pair
2491charset_pairs[] =
2492{
2493 {"ANSI", ANSI_CHARSET},
2494 {"CHINESEBIG5", CHINESEBIG5_CHARSET},
2495 {"DEFAULT", DEFAULT_CHARSET},
2496 {"HANGEUL", HANGEUL_CHARSET},
2497 {"OEM", OEM_CHARSET},
2498 {"SHIFTJIS", SHIFTJIS_CHARSET},
2499 {"SYMBOL", SYMBOL_CHARSET},
2500#ifdef WIN3264
2501 {"ARABIC", ARABIC_CHARSET},
2502 {"BALTIC", BALTIC_CHARSET},
2503 {"EASTEUROPE", EASTEUROPE_CHARSET},
2504 {"GB2312", GB2312_CHARSET},
2505 {"GREEK", GREEK_CHARSET},
2506 {"HEBREW", HEBREW_CHARSET},
2507 {"JOHAB", JOHAB_CHARSET},
2508 {"MAC", MAC_CHARSET},
2509 {"RUSSIAN", RUSSIAN_CHARSET},
2510 {"THAI", THAI_CHARSET},
2511 {"TURKISH", TURKISH_CHARSET},
2512# if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
2513 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
2514 {"VIETNAMESE", VIETNAMESE_CHARSET},
2515# endif
2516#endif
2517 {NULL, 0}
2518};
2519
2520/*
2521 * Convert a charset ID to a name.
2522 * Return NULL when not recognized.
2523 */
2524 char *
2525charset_id2name(int id)
2526{
2527 struct charset_pair *cp;
2528
2529 for (cp = charset_pairs; cp->name != NULL; ++cp)
2530 if ((BYTE)id == cp->charset)
2531 break;
2532 return cp->name;
2533}
2534
2535static const LOGFONT s_lfDefault =
2536{
2537 -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
2538 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
2539 PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
2540 "Fixedsys" /* see _ReadVimIni */
2541};
2542
2543/* Initialise the "current height" to -12 (same as s_lfDefault) just
2544 * in case the user specifies a font in "guifont" with no size before a font
2545 * with an explicit size has been set. This defaults the size to this value
2546 * (-12 equates to roughly 9pt).
2547 */
2548int current_font_height = -12; /* also used in gui_w48.c */
2549
2550/* Convert a string representing a point size into pixels. The string should
2551 * be a positive decimal number, with an optional decimal point (eg, "12", or
2552 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
2553 * character is stored in *end. The flag "vertical" says whether this
2554 * calculation is for a vertical (height) size or a horizontal (width) one.
2555 */
2556 static int
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002557points_to_pixels(char_u *str, char_u **end, int vertical, long_i pprinter_dc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558{
2559 int pixels;
2560 int points = 0;
2561 int divisor = 0;
2562 HWND hwnd = (HWND)0;
2563 HDC hdc;
2564 HDC printer_dc = (HDC)pprinter_dc;
2565
2566 while (*str != NUL)
2567 {
2568 if (*str == '.' && divisor == 0)
2569 {
2570 /* Start keeping a divisor, for later */
2571 divisor = 1;
2572 }
2573 else
2574 {
2575 if (!VIM_ISDIGIT(*str))
2576 break;
2577
2578 points *= 10;
2579 points += *str - '0';
2580 divisor *= 10;
2581 }
2582 ++str;
2583 }
2584
2585 if (divisor == 0)
2586 divisor = 1;
2587
2588 if (printer_dc == NULL)
2589 {
2590 hwnd = GetDesktopWindow();
2591 hdc = GetWindowDC(hwnd);
2592 }
2593 else
2594 hdc = printer_dc;
2595
2596 pixels = MulDiv(points,
2597 GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
2598 72 * divisor);
2599
2600 if (printer_dc == NULL)
2601 ReleaseDC(hwnd, hdc);
2602
2603 *end = str;
2604 return pixels;
2605}
2606
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002607/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608 static int CALLBACK
2609font_enumproc(
2610 ENUMLOGFONT *elf,
2611 NEWTEXTMETRIC *ntm,
2612 int type,
2613 LPARAM lparam)
2614{
2615 /* Return value:
2616 * 0 = terminate now (monospace & ANSI)
2617 * 1 = continue, still no luck...
2618 * 2 = continue, but we have an acceptable LOGFONT
2619 * (monospace, not ANSI)
2620 * We use these values, as EnumFontFamilies returns 1 if the
2621 * callback function is never called. So, we check the return as
2622 * 0 = perfect, 2 = OK, 1 = no good...
2623 * It's not pretty, but it works!
2624 */
2625
2626 LOGFONT *lf = (LOGFONT *)(lparam);
2627
2628#ifndef FEAT_PROPORTIONAL_FONTS
2629 /* Ignore non-monospace fonts without further ado */
2630 if ((ntm->tmPitchAndFamily & 1) != 0)
2631 return 1;
2632#endif
2633
2634 /* Remember this LOGFONT as a "possible" */
2635 *lf = elf->elfLogFont;
2636
2637 /* Terminate the scan as soon as we find an ANSI font */
2638 if (lf->lfCharSet == ANSI_CHARSET
2639 || lf->lfCharSet == OEM_CHARSET
2640 || lf->lfCharSet == DEFAULT_CHARSET)
2641 return 0;
2642
2643 /* Continue the scan - we have a non-ANSI font */
2644 return 2;
2645}
2646
2647 static int
2648init_logfont(LOGFONT *lf)
2649{
2650 int n;
2651 HWND hwnd = GetDesktopWindow();
2652 HDC hdc = GetWindowDC(hwnd);
2653
2654 n = EnumFontFamilies(hdc,
2655 (LPCSTR)lf->lfFaceName,
2656 (FONTENUMPROC)font_enumproc,
2657 (LPARAM)lf);
2658
2659 ReleaseDC(hwnd, hdc);
2660
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02002661 /* If we couldn't find a usable font, return failure */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002662 if (n == 1)
2663 return FAIL;
2664
2665 /* Tidy up the rest of the LOGFONT structure. We set to a basic
2666 * font - get_logfont() sets bold, italic, etc based on the user's
2667 * input.
2668 */
2669 lf->lfHeight = current_font_height;
2670 lf->lfWidth = 0;
2671 lf->lfItalic = FALSE;
2672 lf->lfUnderline = FALSE;
2673 lf->lfStrikeOut = FALSE;
2674 lf->lfWeight = FW_NORMAL;
2675
2676 /* Return success */
2677 return OK;
2678}
2679
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002680/*
2681 * Get font info from "name" into logfont "lf".
2682 * Return OK for a valid name, FAIL otherwise.
2683 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684 int
2685get_logfont(
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002686 LOGFONT *lf,
2687 char_u *name,
2688 HDC printer_dc,
2689 int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690{
2691 char_u *p;
2692 int i;
2693 static LOGFONT *lastlf = NULL;
2694
2695 *lf = s_lfDefault;
2696 if (name == NULL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002697 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002698
2699 if (STRCMP(name, "*") == 0)
2700 {
2701#if defined(FEAT_GUI_W32)
2702 CHOOSEFONT cf;
2703 /* if name is "*", bring up std font dialog: */
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02002704 vim_memset(&cf, 0, sizeof(cf));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002705 cf.lStructSize = sizeof(cf);
2706 cf.hwndOwner = s_hwnd;
2707 cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
2708 if (lastlf != NULL)
2709 *lf = *lastlf;
2710 cf.lpLogFont = lf;
2711 cf.nFontType = 0 ; //REGULAR_FONTTYPE;
2712 if (ChooseFont(&cf))
2713 goto theend;
2714#else
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002715 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716#endif
2717 }
2718
2719 /*
2720 * Split name up, it could be <name>:h<height>:w<width> etc.
2721 */
2722 for (p = name; *p && *p != ':'; p++)
2723 {
2724 if (p - name + 1 > LF_FACESIZE)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002725 return FAIL; /* Name too long */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002726 lf->lfFaceName[p - name] = *p;
2727 }
2728 if (p != name)
2729 lf->lfFaceName[p - name] = NUL;
2730
2731 /* First set defaults */
2732 lf->lfHeight = -12;
2733 lf->lfWidth = 0;
2734 lf->lfWeight = FW_NORMAL;
2735 lf->lfItalic = FALSE;
2736 lf->lfUnderline = FALSE;
2737 lf->lfStrikeOut = FALSE;
2738
2739 /*
2740 * If the font can't be found, try replacing '_' by ' '.
2741 */
2742 if (init_logfont(lf) == FAIL)
2743 {
2744 int did_replace = FALSE;
2745
2746 for (i = 0; lf->lfFaceName[i]; ++i)
2747 if (lf->lfFaceName[i] == '_')
2748 {
2749 lf->lfFaceName[i] = ' ';
2750 did_replace = TRUE;
2751 }
2752 if (!did_replace || init_logfont(lf) == FAIL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002753 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754 }
2755
2756 while (*p == ':')
2757 p++;
2758
2759 /* Set the values found after ':' */
2760 while (*p)
2761 {
2762 switch (*p++)
2763 {
2764 case 'h':
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002765 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (long_i)printer_dc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002766 break;
2767 case 'w':
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002768 lf->lfWidth = points_to_pixels(p, &p, FALSE, (long_i)printer_dc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002769 break;
2770 case 'b':
2771#ifndef MSWIN16_FASTTEXT
2772 lf->lfWeight = FW_BOLD;
2773#endif
2774 break;
2775 case 'i':
2776#ifndef MSWIN16_FASTTEXT
2777 lf->lfItalic = TRUE;
2778#endif
2779 break;
2780 case 'u':
2781 lf->lfUnderline = TRUE;
2782 break;
2783 case 's':
2784 lf->lfStrikeOut = TRUE;
2785 break;
2786 case 'c':
2787 {
2788 struct charset_pair *cp;
2789
2790 for (cp = charset_pairs; cp->name != NULL; ++cp)
2791 if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
2792 {
2793 lf->lfCharSet = cp->charset;
2794 p += strlen(cp->name);
2795 break;
2796 }
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002797 if (cp->name == NULL && verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002798 {
Bram Moolenaar051b7822005-05-19 21:00:46 +00002799 vim_snprintf((char *)IObuff, IOSIZE,
2800 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801 EMSG(IObuff);
2802 break;
2803 }
2804 break;
2805 }
2806 default:
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002807 if (verbose)
2808 {
Bram Moolenaar051b7822005-05-19 21:00:46 +00002809 vim_snprintf((char *)IObuff, IOSIZE,
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002810 _("E245: Illegal char '%c' in font name \"%s\""),
2811 p[-1], name);
2812 EMSG(IObuff);
2813 }
2814 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002815 }
2816 while (*p == ':')
2817 p++;
2818 }
2819
2820#if defined(FEAT_GUI_W32)
2821theend:
2822#endif
2823 /* ron: init lastlf */
2824 if (printer_dc == NULL)
2825 {
2826 vim_free(lastlf);
2827 lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
2828 if (lastlf != NULL)
2829 mch_memmove(lastlf, lf, sizeof(LOGFONT));
2830 }
2831
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002832 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833}
2834
2835#endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */