blob: 912864fd6bd9f47400faddc0e895e88a3bda8dfd [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
187int _chdrive(int drive)
188{
189 char temp [3] = "-:";
190 temp[0] = drive + 'A' - 1;
191 return !SetCurrentDirectory(temp);
192}
193#else
194# ifdef __BORLANDC__
195/* being a more ANSI compliant compiler, BorlandC doesn't define _stricoll:
196 * but it does in BC 5.02! */
197# if __BORLANDC__ < 0x502
198int _stricoll(char *a, char *b)
199{
200# if 1
201 // this is fast but not correct:
202 return stricmp(a, b);
203# else
204 // the ANSI-ish correct way is to use strxfrm():
205 char a_buff[512], b_buff[512]; // file names, so this is enough on Win32
206 strxfrm(a_buff, a, 512);
207 strxfrm(b_buff, b, 512);
208 return strcoll(a_buff, b_buff);
209# endif
210}
211# endif
212# endif
213#endif
214
215
216#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
217/*
218 * GUI version of mch_exit().
219 * Shut down and exit with status `r'
220 * Careful: mch_exit() may be called before mch_init()!
221 */
222 void
223mch_exit(int r)
224{
225 display_errors();
226
227 ml_close_all(TRUE); /* remove all memfiles */
228
229# ifdef FEAT_OLE
230 UninitOLE();
231# endif
232# ifdef FEAT_NETBEANS_INTG
233 if (WSInitialized)
234 {
235 WSInitialized = FALSE;
236 WSACleanup();
237 }
238# endif
239#ifdef DYNAMIC_GETTEXT
240 dyn_libintl_end();
241#endif
242
243 if (gui.in_use)
244 gui_exit(r);
Bram Moolenaar85c79d32007-02-20 01:59:20 +0000245
246#ifdef EXITFREE
247 free_all_mem();
248#endif
249
Bram Moolenaar071d4272004-06-13 20:20:40 +0000250 exit(r);
251}
252
253#endif /* FEAT_GUI_MSWIN */
254
255
256/*
257 * Init the tables for toupper() and tolower().
258 */
259 void
260mch_early_init(void)
261{
262 int i;
263
264#ifdef WIN3264
265 PlatformId();
266#endif
267
268 /* Init the tables for toupper() and tolower() */
269 for (i = 0; i < 256; ++i)
270 toupper_tab[i] = tolower_tab[i] = i;
271#ifdef WIN3264
272 CharUpperBuff(toupper_tab, 256);
273 CharLowerBuff(tolower_tab, 256);
274#else
275 AnsiUpperBuff(toupper_tab, 256);
276 AnsiLowerBuff(tolower_tab, 256);
277#endif
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000278
279#if defined(FEAT_MBYTE) && !defined(FEAT_GUI)
280 (void)get_cmd_argsW(NULL);
281#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000282}
283
284
285/*
286 * Return TRUE if the input comes from a terminal, FALSE otherwise.
287 */
288 int
289mch_input_isatty()
290{
291#ifdef FEAT_GUI_MSWIN
292 return OK; /* GUI always has a tty */
293#else
294 if (isatty(read_cmd_fd))
295 return TRUE;
296 return FALSE;
297#endif
298}
299
300#ifdef FEAT_TITLE
301/*
302 * mch_settitle(): set titlebar of our window
303 */
304 void
305mch_settitle(
306 char_u *title,
307 char_u *icon)
308{
309# ifdef FEAT_GUI_MSWIN
310 gui_mch_settitle(title, icon);
311# else
312 if (title != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000313 {
314# ifdef FEAT_MBYTE
315 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
316 {
317 /* Convert the title from 'encoding' to the active codepage. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000318 WCHAR *wp = enc_to_utf16(title, NULL);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000319 int n;
320
321 if (wp != NULL)
322 {
323 n = SetConsoleTitleW(wp);
324 vim_free(wp);
325 if (n != 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
326 return;
327 }
328 }
329# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000330 SetConsoleTitle(title);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000332# endif
333}
334
335
336/*
337 * Restore the window/icon title.
338 * which is one of:
339 * 1: Just restore title
340 * 2: Just restore icon (which we don't have)
341 * 3: Restore title and icon (which we don't have)
342 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000343/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 void
345mch_restore_title(
346 int which)
347{
348#ifndef FEAT_GUI_MSWIN
349 mch_settitle((which & 1) ? g_szOrigTitle : NULL, NULL);
350#endif
351}
352
353
354/*
355 * Return TRUE if we can restore the title (we can)
356 */
357 int
358mch_can_restore_title()
359{
360 return TRUE;
361}
362
363
364/*
365 * Return TRUE if we can restore the icon title (we can't)
366 */
367 int
368mch_can_restore_icon()
369{
370 return FALSE;
371}
372#endif /* FEAT_TITLE */
373
374
375/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000376 * Get absolute file name into buffer "buf" of length "len" bytes,
377 * turning all '/'s into '\\'s and getting the correct case of each component
378 * of the file name. Append a (back)slash to a directory name.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000379 * When 'shellslash' set do it the other way around.
380 * Return OK or FAIL.
381 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000382/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000383 int
384mch_FullName(
385 char_u *fname,
386 char_u *buf,
387 int len,
388 int force)
389{
390 int nResult = FAIL;
391
392#ifdef __BORLANDC__
393 if (*fname == NUL) /* Borland behaves badly here - make it consistent */
394 nResult = mch_dirname(buf, len);
395 else
396#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +0000398#ifdef FEAT_MBYTE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000399 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
400# ifdef __BORLANDC__
401 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
402 && g_PlatformId == VER_PLATFORM_WIN32_NT
403# endif
404 )
405 {
406 WCHAR *wname;
407 WCHAR wbuf[MAX_PATH];
408 char_u *cname = NULL;
409
410 /* Use the wide function:
411 * - convert the fname from 'encoding' to UCS2.
412 * - invoke _wfullpath()
413 * - convert the result from UCS2 to 'encoding'.
414 */
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000415 wname = enc_to_utf16(fname, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000416 if (wname != NULL && _wfullpath(wbuf, wname, MAX_PATH - 1) != NULL)
417 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000418 cname = utf16_to_enc((short_u *)wbuf, NULL);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000419 if (cname != NULL)
420 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +0000421 vim_strncpy(buf, cname, len - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000422 nResult = OK;
423 }
424 }
425 vim_free(wname);
426 vim_free(cname);
427 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000428 if (nResult == FAIL) /* fall back to non-wide function */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000429#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000430 {
431 if (_fullpath(buf, fname, len - 1) == NULL)
432 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +0000433 /* failed, use relative path name */
434 vim_strncpy(buf, fname, len - 1);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000435 }
436 else
437 nResult = OK;
438 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000439 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000440
441#ifdef USE_FNAME_CASE
442 fname_case(buf, len);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000443#else
444 slash_adjust(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445#endif
446
447 return nResult;
448}
449
450
451/*
452 * Return TRUE if "fname" does not depend on the current directory.
453 */
454 int
455mch_isFullName(char_u *fname)
456{
457 char szName[_MAX_PATH + 1];
458
459 /* A name like "d:/foo" and "//server/share" is absolute */
460 if ((fname[0] && fname[1] == ':' && (fname[2] == '/' || fname[2] == '\\'))
461 || (fname[0] == fname[1] && (fname[0] == '/' || fname[0] == '\\')))
462 return TRUE;
463
464 /* A name that can't be made absolute probably isn't absolute. */
465 if (mch_FullName(fname, szName, _MAX_PATH, FALSE) == FAIL)
466 return FALSE;
467
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000468 return pathcmp(fname, szName, -1) == 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000469}
470
471/*
472 * Replace all slashes by backslashes.
473 * This used to be the other way around, but MS-DOS sometimes has problems
474 * with slashes (e.g. in a command name). We can't have mixed slashes and
475 * backslashes, because comparing file names will not work correctly. The
476 * commands that use a file name should try to avoid the need to type a
477 * backslash twice.
478 * When 'shellslash' set do it the other way around.
479 */
480 void
481slash_adjust(p)
482 char_u *p;
483{
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +0000484 while (*p)
485 {
486 if (*p == psepcN)
487 *p = psepc;
488 mb_ptr_adv(p);
489 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000490}
491
492
493/*
494 * stat() can't handle a trailing '/' or '\', remove it first.
495 */
496 int
497vim_stat(const char *name, struct stat *stp)
498{
499 char buf[_MAX_PATH + 1];
500 char *p;
501
Bram Moolenaar84110ac2005-07-20 21:56:21 +0000502 vim_strncpy((char_u *)buf, (char_u *)name, _MAX_PATH);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000503 p = buf + strlen(buf);
504 if (p > buf)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000505 mb_ptr_back(buf, p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000506 if (p > buf && (*p == '\\' || *p == '/') && p[-1] != ':')
507 *p = NUL;
508#ifdef FEAT_MBYTE
509 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
510# ifdef __BORLANDC__
511 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
512 && g_PlatformId == VER_PLATFORM_WIN32_NT
513# endif
514 )
515 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000516 WCHAR *wp = enc_to_utf16(buf, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000517 int n;
518
519 if (wp != NULL)
520 {
521 n = _wstat(wp, (struct _stat *)stp);
522 vim_free(wp);
523 if (n >= 0)
524 return n;
525 /* Retry with non-wide function (for Windows 98). Can't use
526 * GetLastError() here and it's unclear what errno gets set to if
527 * the _wstat() fails for missing wide functions. */
528 }
529 }
530#endif
531 return stat(buf, stp);
532}
533
534#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000535/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000536 void
537mch_settmode(int tmode)
538{
539 /* nothing to do */
540}
541
542 int
543mch_get_shellsize(void)
544{
545 /* never used */
546 return OK;
547}
548
549 void
550mch_set_shellsize(void)
551{
552 /* never used */
553}
554
555/*
556 * Rows and/or Columns has changed.
557 */
558 void
559mch_new_shellsize(void)
560{
561 /* never used */
562}
563
564#endif
565
566/*
567 * We have no job control, so fake it by starting a new shell.
568 */
569 void
570mch_suspend()
571{
572 suspend_shell();
573}
574
575#if defined(USE_MCH_ERRMSG) || defined(PROTO)
576
577#ifdef display_errors
578# undef display_errors
579#endif
580
581/*
582 * Display the saved error message(s).
583 */
584 void
585display_errors()
586{
587 char *p;
588
589 if (error_ga.ga_data != NULL)
590 {
591 /* avoid putting up a message box with blanks only */
592 for (p = (char *)error_ga.ga_data; *p; ++p)
593 if (!isspace(*p))
594 {
Bram Moolenaarc17ef8e2006-03-25 21:48:58 +0000595 (void)gui_mch_dialog(
596#ifdef FEAT_GUI
597 gui.starting ? VIM_INFO :
598#endif
599 VIM_ERROR,
600#ifdef FEAT_GUI
601 gui.starting ? (char_u *)_("Message") :
602#endif
603 (char_u *)_("Error"),
Bram Moolenaard2c340a2011-01-17 20:08:11 +0100604 p, (char_u *)_("&Ok"), 1, NULL, FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000605 break;
606 }
607 ga_clear(&error_ga);
608 }
609}
610#endif
611
612
613/*
614 * Return TRUE if "p" contain a wildcard that can be expanded by
615 * dos_expandpath().
616 */
617 int
618mch_has_exp_wildcard(char_u *p)
619{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000620 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000621 {
622 if (vim_strchr((char_u *)"?*[", *p) != NULL
623 || (*p == '~' && p[1] != NUL))
624 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000625 }
626 return FALSE;
627}
628
629/*
630 * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a
631 * shortened file name).
632 */
633 int
634mch_has_wildcard(char_u *p)
635{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000636 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000637 {
638 if (vim_strchr((char_u *)
639# ifdef VIM_BACKTICK
640 "?*$[`"
641# else
642 "?*$["
643# endif
644 , *p) != NULL
645 || (*p == '~' && p[1] != NUL))
646 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000647 }
648 return FALSE;
649}
650
651
652/*
653 * The normal _chdir() does not change the default drive. This one does.
654 * Returning 0 implies success; -1 implies failure.
655 */
656 int
657mch_chdir(char *path)
658{
659 if (path[0] == NUL) /* just checking... */
660 return -1;
661
Bram Moolenaara2974d72009-07-14 16:38:36 +0000662 if (p_verbose >= 5)
663 {
664 verbose_enter();
665 smsg((char_u *)"chdir(%s)", path);
666 verbose_leave();
667 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000668 if (isalpha(path[0]) && path[1] == ':') /* has a drive name */
669 {
670 /* If we can change to the drive, skip that part of the path. If we
671 * can't then the current directory may be invalid, try using chdir()
672 * with the whole path. */
673 if (_chdrive(TOLOWER_ASC(path[0]) - 'a' + 1) == 0)
674 path += 2;
675 }
676
677 if (*path == NUL) /* drive name only */
678 return 0;
679
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000680#ifdef FEAT_MBYTE
681 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
682 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000683 WCHAR *p = enc_to_utf16(path, NULL);
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000684 int n;
685
686 if (p != NULL)
687 {
688 n = _wchdir(p);
689 vim_free(p);
690 if (n == 0)
691 return 0;
692 /* Retry with non-wide function (for Windows 98). */
693 }
694 }
695#endif
696
Bram Moolenaar071d4272004-06-13 20:20:40 +0000697 return chdir(path); /* let the normal chdir() do the rest */
698}
699
700
701/*
702 * Switching off termcap mode is only allowed when Columns is 80, otherwise a
703 * crash may result. It's always allowed on NT or when running the GUI.
704 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000705/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000706 int
707can_end_termcap_mode(
708 int give_msg)
709{
710#ifdef FEAT_GUI_MSWIN
711 return TRUE; /* GUI starts a new console anyway */
712#else
713 if (g_PlatformId == VER_PLATFORM_WIN32_NT || Columns == 80)
714 return TRUE;
715 if (give_msg)
716 msg(_("'columns' is not 80, cannot execute external commands"));
717 return FALSE;
718#endif
719}
720
721#ifdef FEAT_GUI_MSWIN
722/*
723 * return non-zero if a character is available
724 */
725 int
726mch_char_avail()
727{
728 /* never used */
729 return TRUE;
730}
731#endif
732
733
734/*
735 * set screen mode, always fails.
736 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +0000737/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738 int
739mch_screenmode(
740 char_u *arg)
741{
742 EMSG(_(e_screenmode));
743 return FAIL;
744}
745
746
747#if defined(FEAT_LIBCALL) || defined(PROTO)
748/*
749 * Call a DLL routine which takes either a string or int param
750 * and returns an allocated string.
751 * Return OK if it worked, FAIL if not.
752 */
753# ifdef WIN3264
754typedef LPTSTR (*MYSTRPROCSTR)(LPTSTR);
755typedef LPTSTR (*MYINTPROCSTR)(int);
756typedef int (*MYSTRPROCINT)(LPTSTR);
757typedef int (*MYINTPROCINT)(int);
758# else
759typedef LPSTR (*MYSTRPROCSTR)(LPSTR);
760typedef LPSTR (*MYINTPROCSTR)(int);
761typedef int (*MYSTRPROCINT)(LPSTR);
762typedef int (*MYINTPROCINT)(int);
763# endif
764
765# ifndef WIN16
766/*
767 * Check if a pointer points to a valid NUL terminated string.
768 * Return the length of the string, including terminating NUL.
769 * Returns 0 for an invalid pointer, 1 for an empty string.
770 */
771 static size_t
772check_str_len(char_u *str)
773{
774 SYSTEM_INFO si;
775 MEMORY_BASIC_INFORMATION mbi;
776 size_t length = 0;
777 size_t i;
778 const char *p;
779
780 /* get page size */
781 GetSystemInfo(&si);
782
783 /* get memory information */
784 if (VirtualQuery(str, &mbi, sizeof(mbi)))
785 {
786 /* pre cast these (typing savers) */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000787 long_u dwStr = (long_u)str;
788 long_u dwBaseAddress = (long_u)mbi.BaseAddress;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000789
790 /* get start address of page that str is on */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000791 long_u strPage = dwStr - (dwStr - dwBaseAddress) % si.dwPageSize;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792
793 /* get length from str to end of page */
Bram Moolenaareb3593b2006-04-22 22:33:57 +0000794 long_u pageLength = si.dwPageSize - (dwStr - strPage);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000795
Bram Moolenaar442b4222010-05-24 21:34:22 +0200796 for (p = str; !IsBadReadPtr(p, (UINT)pageLength);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000797 p += pageLength, pageLength = si.dwPageSize)
798 for (i = 0; i < pageLength; ++i, ++length)
799 if (p[i] == NUL)
800 return length + 1;
801 }
802
803 return 0;
804}
805# endif
806
807 int
808mch_libcall(
809 char_u *libname,
810 char_u *funcname,
811 char_u *argstring, /* NULL when using a argint */
812 int argint,
813 char_u **string_result,/* NULL when using number_result */
814 int *number_result)
815{
816 HINSTANCE hinstLib;
817 MYSTRPROCSTR ProcAdd;
818 MYINTPROCSTR ProcAddI;
819 char_u *retval_str = NULL;
820 int retval_int = 0;
821 size_t len;
822
823 BOOL fRunTimeLinkSuccess = FALSE;
824
825 // Get a handle to the DLL module.
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200826# ifdef WIN16
Bram Moolenaar071d4272004-06-13 20:20:40 +0000827 hinstLib = LoadLibrary(libname);
Bram Moolenaarebbcb822010-10-23 14:02:54 +0200828# else
829 hinstLib = vimLoadLib(libname);
830# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000831
832 // If the handle is valid, try to get the function address.
833 if (hinstLib != NULL)
834 {
835#ifdef HAVE_TRY_EXCEPT
836 __try
837 {
838#endif
839 if (argstring != NULL)
840 {
841 /* Call with string argument */
842 ProcAdd = (MYSTRPROCSTR) GetProcAddress(hinstLib, funcname);
843 if ((fRunTimeLinkSuccess = (ProcAdd != NULL)) != 0)
844 {
845 if (string_result == NULL)
846 retval_int = ((MYSTRPROCINT)ProcAdd)(argstring);
847 else
848 retval_str = (ProcAdd)(argstring);
849 }
850 }
851 else
852 {
853 /* Call with number argument */
854 ProcAddI = (MYINTPROCSTR) GetProcAddress(hinstLib, funcname);
855 if ((fRunTimeLinkSuccess = (ProcAddI != NULL)) != 0)
856 {
857 if (string_result == NULL)
858 retval_int = ((MYINTPROCINT)ProcAddI)(argint);
859 else
860 retval_str = (ProcAddI)(argint);
861 }
862 }
863
864 // Save the string before we free the library.
865 // Assume that a "1" result is an illegal pointer.
866 if (string_result == NULL)
867 *number_result = retval_int;
868 else if (retval_str != NULL
869# ifdef WIN16
870 && retval_str != (char_u *)1
871 && retval_str != (char_u *)-1
872 && !IsBadStringPtr(retval_str, INT_MAX)
873 && (len = strlen(retval_str) + 1) > 0
874# else
875 && (len = check_str_len(retval_str)) > 0
876# endif
877 )
878 {
879 *string_result = lalloc((long_u)len, TRUE);
880 if (*string_result != NULL)
881 mch_memmove(*string_result, retval_str, len);
882 }
883
884#ifdef HAVE_TRY_EXCEPT
885 }
886 __except(EXCEPTION_EXECUTE_HANDLER)
887 {
888 if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW)
889 RESETSTKOFLW();
890 fRunTimeLinkSuccess = 0;
891 }
892#endif
893
894 // Free the DLL module.
895 (void)FreeLibrary(hinstLib);
896 }
897
898 if (!fRunTimeLinkSuccess)
899 {
900 EMSG2(_(e_libcall), funcname);
901 return FAIL;
902 }
903
904 return OK;
905}
906#endif
907
908#if defined(FEAT_MBYTE) || defined(PROTO)
909/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000910 * Convert an UTF-8 string to UTF-16.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000911 * "instr[inlen]" is the input. "inlen" is in bytes.
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000912 * When "outstr" is NULL only return the number of UTF-16 words produced.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000913 * Otherwise "outstr" must be a buffer of sufficient size.
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000914 * Returns the number of UTF-16 words produced.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915 */
916 int
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000917utf8_to_utf16(char_u *instr, int inlen, short_u *outstr, int *unconvlenp)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000918{
919 int outlen = 0;
920 char_u *p = instr;
921 int todo = inlen;
922 int l;
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000923 int ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924
925 while (todo > 0)
926 {
927 /* Only convert if we have a complete sequence. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +0000928 l = utf_ptr2len_len(p, todo);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929 if (l > todo)
930 {
931 /* Return length of incomplete sequence. */
932 if (unconvlenp != NULL)
933 *unconvlenp = todo;
934 break;
935 }
936
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000937 ch = utf_ptr2char(p);
938 if (ch >= 0x10000)
939 {
940 /* non-BMP character, encoding with surrogate pairs */
941 ++outlen;
942 if (outstr != NULL)
943 {
944 *outstr++ = (0xD800 - (0x10000 >> 10)) + (ch >> 10);
945 *outstr++ = 0xDC00 | (ch & 0x3FF);
946 }
947 }
948 else if (outstr != NULL)
949 *outstr++ = ch;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 ++outlen;
951 p += l;
952 todo -= l;
953 }
954
955 return outlen;
956}
957
958/*
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000959 * Convert an UTF-16 string to UTF-8.
960 * The input is "instr[inlen]" with "inlen" in number of UTF-16 words.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961 * When "outstr" is NULL only return the required number of bytes.
962 * Otherwise "outstr" must be a buffer of sufficient size.
963 * Return the number of bytes produced.
964 */
965 int
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000966utf16_to_utf8(short_u *instr, int inlen, char_u *outstr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000967{
968 int outlen = 0;
969 int todo = inlen;
970 short_u *p = instr;
971 int l;
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000972 int ch, ch2;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973
974 while (todo > 0)
975 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000976 ch = *p;
977 if (ch >= 0xD800 && ch <= 0xDBFF && todo > 1)
978 {
979 /* surrogate pairs handling */
980 ch2 = p[1];
981 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF)
982 {
983 ch = ((ch - 0xD800) << 10) + (ch2 & 0x3FF) + 0x10000;
984 ++p;
985 --todo;
986 }
987 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000988 if (outstr != NULL)
989 {
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000990 l = utf_char2bytes(ch, outstr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991 outstr += l;
992 }
993 else
Bram Moolenaar36f692d2008-11-20 16:10:17 +0000994 l = utf_char2len(ch);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995 ++p;
996 outlen += l;
997 --todo;
998 }
999
1000 return outlen;
1001}
1002
1003/*
1004 * Call MultiByteToWideChar() and allocate memory for the result.
1005 * Returns the result in "*out[*outlen]" with an extra zero appended.
1006 * "outlen" is in words.
1007 */
1008 void
1009MultiByteToWideChar_alloc(UINT cp, DWORD flags,
1010 LPCSTR in, int inlen,
1011 LPWSTR *out, int *outlen)
1012{
1013 *outlen = MultiByteToWideChar(cp, flags, in, inlen, 0, 0);
1014 /* Add one one word to avoid a zero-length alloc(). */
1015 *out = (LPWSTR)alloc(sizeof(WCHAR) * (*outlen + 1));
1016 if (*out != NULL)
1017 {
1018 MultiByteToWideChar(cp, flags, in, inlen, *out, *outlen);
1019 (*out)[*outlen] = 0;
1020 }
1021}
1022
1023/*
1024 * Call WideCharToMultiByte() and allocate memory for the result.
1025 * Returns the result in "*out[*outlen]" with an extra NUL appended.
1026 */
1027 void
1028WideCharToMultiByte_alloc(UINT cp, DWORD flags,
1029 LPCWSTR in, int inlen,
1030 LPSTR *out, int *outlen,
1031 LPCSTR def, LPBOOL useddef)
1032{
1033 *outlen = WideCharToMultiByte(cp, flags, in, inlen, NULL, 0, def, useddef);
1034 /* Add one one byte to avoid a zero-length alloc(). */
1035 *out = alloc((unsigned)*outlen + 1);
1036 if (*out != NULL)
1037 {
1038 WideCharToMultiByte(cp, flags, in, inlen, *out, *outlen, def, useddef);
1039 (*out)[*outlen] = 0;
1040 }
1041}
1042
1043#endif /* FEAT_MBYTE */
1044
1045#ifdef FEAT_CLIPBOARD
1046/*
1047 * Clipboard stuff, for cutting and pasting text to other windows.
1048 */
1049
1050/* Type used for the clipboard type of Vim's data. */
1051typedef struct
1052{
1053 int type; /* MCHAR, MBLOCK or MLINE */
1054 int txtlen; /* length of CF_TEXT in bytes */
1055 int ucslen; /* length of CF_UNICODETEXT in words */
1056 int rawlen; /* length of clip_star.format_raw, including encoding,
1057 excluding terminating NUL */
1058} VimClipType_t;
1059
1060/*
1061 * Make vim the owner of the current selection. Return OK upon success.
1062 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001063/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001064 int
1065clip_mch_own_selection(VimClipboard *cbd)
1066{
1067 /*
1068 * Never actually own the clipboard. If another application sets the
1069 * clipboard, we don't want to think that we still own it.
1070 */
1071 return FAIL;
1072}
1073
1074/*
1075 * Make vim NOT the owner of the current selection.
1076 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001077/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001078 void
1079clip_mch_lose_selection(VimClipboard *cbd)
1080{
1081 /* Nothing needs to be done here */
1082}
1083
1084/*
1085 * Copy "str[*size]" into allocated memory, changing CR-NL to NL.
1086 * Return the allocated result and the size in "*size".
1087 * Returns NULL when out of memory.
1088 */
1089 static char_u *
1090crnl_to_nl(const char_u *str, int *size)
1091{
1092 int pos = 0;
1093 int str_len = *size;
1094 char_u *ret;
1095 char_u *retp;
1096
1097 /* Avoid allocating zero bytes, it generates an error message. */
1098 ret = lalloc((long_u)(str_len == 0 ? 1 : str_len), TRUE);
1099 if (ret != NULL)
1100 {
1101 retp = ret;
1102 for (pos = 0; pos < str_len; ++pos)
1103 {
1104 if (str[pos] == '\r' && str[pos + 1] == '\n')
1105 {
1106 ++pos;
1107 --(*size);
1108 }
1109 *retp++ = str[pos];
1110 }
1111 }
1112
1113 return ret;
1114}
1115
Bram Moolenaar071d4272004-06-13 20:20:40 +00001116/*
Bram Moolenaar282937b2009-01-22 20:50:10 +00001117 * Wait for another process to Close the Clipboard.
1118 * Returns TRUE for success.
1119 */
Bram Moolenaard30f9d92009-05-14 20:01:05 +00001120 static int
1121vim_open_clipboard(void)
Bram Moolenaar282937b2009-01-22 20:50:10 +00001122{
1123 int delay = 10;
1124
1125 while (!OpenClipboard(NULL))
1126 {
Bram Moolenaarcc448b32010-07-14 16:52:17 +02001127 if (delay > 500)
1128 return FALSE; /* waited too long, give up */
1129 Sleep(delay);
1130 delay *= 2; /* wait for 10, 20, 40, 80, etc. msec */
Bram Moolenaar282937b2009-01-22 20:50:10 +00001131 }
1132 return TRUE;
1133}
1134
1135/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00001136 * Get the current selection and put it in the clipboard register.
1137 *
1138 * NOTE: Must use GlobalLock/Unlock here to ensure Win32s compatibility.
1139 * On NT/W95 the clipboard data is a fixed global memory object and
1140 * so its handle = its pointer.
1141 * On Win32s, however, co-operation with the Win16 system means that
1142 * the clipboard data is moveable and its handle is not a pointer at all,
1143 * so we can't just cast the return value of GetClipboardData to (char_u*).
1144 * <VN>
1145 */
1146 void
1147clip_mch_request_selection(VimClipboard *cbd)
1148{
1149 VimClipType_t metadata = { -1, -1, -1, -1 };
1150 HGLOBAL hMem = NULL;
1151 char_u *str = NULL;
1152#if defined(FEAT_MBYTE) && defined(WIN3264)
1153 char_u *to_free = NULL;
1154#endif
1155#ifdef FEAT_MBYTE
1156 HGLOBAL rawh = NULL;
1157#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158 int str_size = 0;
1159 int maxlen;
1160 size_t n;
1161
1162 /*
1163 * Don't pass GetActiveWindow() as an argument to OpenClipboard() because
1164 * then we can't paste back into the same window for some reason - webb.
1165 */
Bram Moolenaar282937b2009-01-22 20:50:10 +00001166 if (!vim_open_clipboard())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 return;
1168
1169 /* Check for vim's own clipboard format first. This only gets the type of
1170 * the data, still need to use CF_UNICODETEXT or CF_TEXT for the text. */
1171 if (IsClipboardFormatAvailable(cbd->format))
1172 {
1173 VimClipType_t *meta_p;
1174 HGLOBAL meta_h;
1175
1176 /* We have metadata on the clipboard; try to get it. */
1177 if ((meta_h = GetClipboardData(cbd->format)) != NULL
1178 && (meta_p = (VimClipType_t *)GlobalLock(meta_h)) != NULL)
1179 {
1180 /* The size of "VimClipType_t" changed, "rawlen" was added later.
1181 * Only copy what is available for backwards compatibility. */
1182 n = sizeof(VimClipType_t);
1183 if (GlobalSize(meta_h) < n)
1184 n = GlobalSize(meta_h);
1185 memcpy(&metadata, meta_p, n);
1186 GlobalUnlock(meta_h);
1187 }
1188 }
1189
1190#ifdef FEAT_MBYTE
1191 /* Check for Vim's raw clipboard format first. This is used without
1192 * conversion, but only if 'encoding' matches. */
1193 if (IsClipboardFormatAvailable(cbd->format_raw)
1194 && metadata.rawlen > (int)STRLEN(p_enc))
1195 {
1196 /* We have raw data on the clipboard; try to get it. */
1197 if ((rawh = GetClipboardData(cbd->format_raw)) != NULL)
1198 {
1199 char_u *rawp;
1200
1201 rawp = (char_u *)GlobalLock(rawh);
1202 if (rawp != NULL && STRCMP(p_enc, rawp) == 0)
1203 {
1204 n = STRLEN(p_enc) + 1;
1205 str = rawp + n;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001206 str_size = (int)(metadata.rawlen - n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207 }
1208 else
1209 {
1210 GlobalUnlock(rawh);
1211 rawh = NULL;
1212 }
1213 }
1214 }
1215 if (str == NULL)
1216 {
1217#endif
1218
1219#if defined(FEAT_MBYTE) && defined(WIN3264)
1220 /* Try to get the clipboard in Unicode if it's not an empty string. */
1221 if (IsClipboardFormatAvailable(CF_UNICODETEXT) && metadata.ucslen != 0)
1222 {
1223 HGLOBAL hMemW;
1224
1225 if ((hMemW = GetClipboardData(CF_UNICODETEXT)) != NULL)
1226 {
1227 WCHAR *hMemWstr = (WCHAR *)GlobalLock(hMemW);
1228
1229 /* Use the length of our metadata if possible, but limit it to the
1230 * GlobalSize() for safety. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001231 maxlen = (int)(GlobalSize(hMemW) / sizeof(WCHAR));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001232 if (metadata.ucslen >= 0)
1233 {
1234 if (metadata.ucslen > maxlen)
1235 str_size = maxlen;
1236 else
1237 str_size = metadata.ucslen;
1238 }
1239 else
1240 {
1241 for (str_size = 0; str_size < maxlen; ++str_size)
1242 if (hMemWstr[str_size] == NUL)
1243 break;
1244 }
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001245 to_free = str = utf16_to_enc((short_u *)hMemWstr, &str_size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001246 GlobalUnlock(hMemW);
1247 }
1248 }
1249 else
1250#endif
1251 /* Get the clipboard in the Active codepage. */
1252 if (IsClipboardFormatAvailable(CF_TEXT))
1253 {
1254 if ((hMem = GetClipboardData(CF_TEXT)) != NULL)
1255 {
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001256 str = (char_u *)GlobalLock(hMem);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001257
1258 /* The length is either what our metadata says or the strlen().
1259 * But limit it to the GlobalSize() for safety. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001260 maxlen = (int)GlobalSize(hMem);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261 if (metadata.txtlen >= 0)
1262 {
1263 if (metadata.txtlen > maxlen)
1264 str_size = maxlen;
1265 else
1266 str_size = metadata.txtlen;
1267 }
1268 else
1269 {
1270 for (str_size = 0; str_size < maxlen; ++str_size)
1271 if (str[str_size] == NUL)
1272 break;
1273 }
1274
Bram Moolenaar05159a02005-02-26 23:04:13 +00001275# if defined(FEAT_MBYTE) && defined(WIN3264)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001276 /* The text is in the active codepage. Convert to 'encoding',
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001277 * going through UTF-16. */
Bram Moolenaar05159a02005-02-26 23:04:13 +00001278 acp_to_enc(str, str_size, &to_free, &maxlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001279 if (to_free != NULL)
1280 {
1281 str_size = maxlen;
Bram Moolenaar05159a02005-02-26 23:04:13 +00001282 str = to_free;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001283 }
Bram Moolenaar05159a02005-02-26 23:04:13 +00001284# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001285 }
1286 }
1287#ifdef FEAT_MBYTE
1288 }
1289#endif
1290
1291 if (str != NULL && *str != NUL)
1292 {
1293 char_u *temp_clipboard;
1294
Bram Moolenaard44347f2011-06-19 01:14:29 +02001295 /* If the type is not known detect it. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001296 if (metadata.type == -1)
Bram Moolenaard44347f2011-06-19 01:14:29 +02001297 metadata.type = MAUTO;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001298
1299 /* Translate <CR><NL> into <NL>. */
1300 temp_clipboard = crnl_to_nl(str, &str_size);
1301 if (temp_clipboard != NULL)
1302 {
1303 clip_yank_selection(metadata.type, temp_clipboard, str_size, cbd);
1304 vim_free(temp_clipboard);
1305 }
1306 }
1307
1308 /* unlock the global object */
1309 if (hMem != NULL)
1310 GlobalUnlock(hMem);
1311#ifdef FEAT_MBYTE
1312 if (rawh != NULL)
1313 GlobalUnlock(rawh);
1314#endif
1315 CloseClipboard();
1316#if defined(FEAT_MBYTE) && defined(WIN3264)
1317 vim_free(to_free);
1318#endif
1319}
1320
1321/*
1322 * Send the current selection to the clipboard.
1323 */
1324 void
1325clip_mch_set_selection(VimClipboard *cbd)
1326{
1327 char_u *str = NULL;
1328 VimClipType_t metadata;
1329 long_u txtlen;
1330 HGLOBAL hMemRaw = NULL;
1331 HGLOBAL hMem = NULL;
1332 HGLOBAL hMemVim = NULL;
1333# if defined(FEAT_MBYTE) && defined(WIN3264)
1334 HGLOBAL hMemW = NULL;
1335# endif
1336
1337 /* If the '*' register isn't already filled in, fill it in now */
1338 cbd->owned = TRUE;
1339 clip_get_selection(cbd);
1340 cbd->owned = FALSE;
1341
1342 /* Get the text to be put on the clipboard, with CR-LF. */
1343 metadata.type = clip_convert_selection(&str, &txtlen, cbd);
1344 if (metadata.type < 0)
1345 return;
1346 metadata.txtlen = (int)txtlen;
1347 metadata.ucslen = 0;
1348 metadata.rawlen = 0;
1349
1350#ifdef FEAT_MBYTE
1351 /* Always set the raw bytes: 'encoding', NUL and the text. This is used
1352 * when copy/paste from/to Vim with the same 'encoding', so that illegal
1353 * bytes can also be copied and no conversion is needed. */
1354 {
1355 LPSTR lpszMemRaw;
1356
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001357 metadata.rawlen = (int)(txtlen + STRLEN(p_enc) + 1);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001358 hMemRaw = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1359 metadata.rawlen + 1);
1360 lpszMemRaw = (LPSTR)GlobalLock(hMemRaw);
1361 if (lpszMemRaw != NULL)
1362 {
1363 STRCPY(lpszMemRaw, p_enc);
1364 memcpy(lpszMemRaw + STRLEN(p_enc) + 1, str, txtlen + 1);
1365 GlobalUnlock(hMemRaw);
1366 }
1367 else
1368 metadata.rawlen = 0;
1369 }
1370#endif
1371
1372# if defined(FEAT_MBYTE) && defined(WIN3264)
1373 {
1374 WCHAR *out;
1375 int len = metadata.txtlen;
1376
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001377 /* Convert the text to UTF-16. This is put on the clipboard as
Bram Moolenaar071d4272004-06-13 20:20:40 +00001378 * CF_UNICODETEXT. */
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001379 out = (WCHAR *)enc_to_utf16(str, &len);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001380 if (out != NULL)
1381 {
1382 WCHAR *lpszMemW;
1383
1384 /* Convert the text for CF_TEXT to Active codepage. Otherwise it's
1385 * p_enc, which has no relation to the Active codepage. */
1386 metadata.txtlen = WideCharToMultiByte(GetACP(), 0, out, len,
1387 NULL, 0, 0, 0);
1388 vim_free(str);
1389 str = (char_u *)alloc((unsigned)(metadata.txtlen == 0 ? 1
1390 : metadata.txtlen));
1391 if (str == NULL)
1392 {
1393 vim_free(out);
1394 return; /* out of memory */
1395 }
1396 WideCharToMultiByte(GetACP(), 0, out, len,
1397 str, metadata.txtlen, 0, 0);
1398
Bram Moolenaar36f692d2008-11-20 16:10:17 +00001399 /* Allocate memory for the UTF-16 text, add one NUL word to
Bram Moolenaar071d4272004-06-13 20:20:40 +00001400 * terminate the string. */
1401 hMemW = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1402 (len + 1) * sizeof(WCHAR));
1403 lpszMemW = (WCHAR *)GlobalLock(hMemW);
1404 if (lpszMemW != NULL)
1405 {
1406 memcpy(lpszMemW, out, len * sizeof(WCHAR));
1407 lpszMemW[len] = NUL;
1408 GlobalUnlock(hMemW);
1409 }
1410 vim_free(out);
1411 metadata.ucslen = len;
1412 }
1413 }
1414# endif
1415
1416 /* Allocate memory for the text, add one NUL byte to terminate the string.
1417 */
1418 hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, metadata.txtlen + 1);
1419 {
1420 LPSTR lpszMem = (LPSTR)GlobalLock(hMem);
1421
1422 if (lpszMem)
1423 {
Bram Moolenaarfe3ca8d2005-07-18 21:43:02 +00001424 vim_strncpy(lpszMem, str, metadata.txtlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001425 GlobalUnlock(hMem);
1426 }
1427 }
1428
1429 /* Set up metadata: */
1430 {
1431 VimClipType_t *lpszMemVim = NULL;
1432
1433 hMemVim = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,
1434 sizeof(VimClipType_t));
1435 lpszMemVim = (VimClipType_t *)GlobalLock(hMemVim);
1436 memcpy(lpszMemVim, &metadata, sizeof(metadata));
1437 GlobalUnlock(hMemVim);
1438 }
1439
1440 /*
1441 * Open the clipboard, clear it and put our text on it.
1442 * Always set our Vim format. Put Unicode and plain text on it.
1443 *
1444 * Don't pass GetActiveWindow() as an argument to OpenClipboard()
1445 * because then we can't paste back into the same window for some
1446 * reason - webb.
1447 */
Bram Moolenaar282937b2009-01-22 20:50:10 +00001448 if (vim_open_clipboard())
Bram Moolenaar071d4272004-06-13 20:20:40 +00001449 {
1450 if (EmptyClipboard())
1451 {
1452 SetClipboardData(cbd->format, hMemVim);
1453 hMemVim = 0;
1454# if defined(FEAT_MBYTE) && defined(WIN3264)
1455 if (hMemW != NULL)
1456 {
1457 if (SetClipboardData(CF_UNICODETEXT, hMemW) != NULL)
1458 hMemW = NULL;
1459 }
1460# endif
1461 /* Always use CF_TEXT. On Win98 Notepad won't obtain the
1462 * CF_UNICODETEXT text, only CF_TEXT. */
1463 SetClipboardData(CF_TEXT, hMem);
1464 hMem = 0;
1465 }
1466 CloseClipboard();
1467 }
1468
1469 vim_free(str);
1470 /* Free any allocations we didn't give to the clipboard: */
1471 if (hMemRaw)
1472 GlobalFree(hMemRaw);
1473 if (hMem)
1474 GlobalFree(hMem);
1475# if defined(FEAT_MBYTE) && defined(WIN3264)
1476 if (hMemW)
1477 GlobalFree(hMemW);
1478# endif
1479 if (hMemVim)
1480 GlobalFree(hMemVim);
1481}
1482
1483#endif /* FEAT_CLIPBOARD */
1484
Bram Moolenaarc16756d2011-06-19 01:30:07 +02001485#if defined(FEAT_MBYTE) || defined(PROTO)
1486/*
1487 * Note: the following two functions are only guaranteed to work when using
1488 * valid MS-Windows codepages or when iconv() is available.
1489 */
1490
1491/*
1492 * Convert "str" from 'encoding' to UTF-16.
1493 * Input in "str" with length "*lenp". When "lenp" is NULL, use strlen().
1494 * Output is returned as an allocated string. "*lenp" is set to the length of
1495 * the result. A trailing NUL is always added.
1496 * Returns NULL when out of memory.
1497 */
1498 short_u *
1499enc_to_utf16(char_u *str, int *lenp)
1500{
1501 vimconv_T conv;
1502 WCHAR *ret;
1503 char_u *allocbuf = NULL;
1504 int len_loc;
1505 int length;
1506
1507 if (lenp == NULL)
1508 {
1509 len_loc = (int)STRLEN(str) + 1;
1510 lenp = &len_loc;
1511 }
1512
1513 if (enc_codepage > 0)
1514 {
1515 /* We can do any CP### -> UTF-16 in one pass, and we can do it
1516 * without iconv() (convert_* may need iconv). */
1517 MultiByteToWideChar_alloc(enc_codepage, 0, str, *lenp, &ret, &length);
1518 }
1519 else
1520 {
1521 /* Use "latin1" by default, we might be called before we have p_enc
1522 * set up. Convert to utf-8 first, works better with iconv(). Does
1523 * nothing if 'encoding' is "utf-8". */
1524 conv.vc_type = CONV_NONE;
1525 if (convert_setup(&conv, p_enc ? p_enc : (char_u *)"latin1",
1526 (char_u *)"utf-8") == FAIL)
1527 return NULL;
1528 if (conv.vc_type != CONV_NONE)
1529 {
1530 str = allocbuf = string_convert(&conv, str, lenp);
1531 if (str == NULL)
1532 return NULL;
1533 }
1534 convert_setup(&conv, NULL, NULL);
1535
1536 length = utf8_to_utf16(str, *lenp, NULL, NULL);
1537 ret = (WCHAR *)alloc((unsigned)((length + 1) * sizeof(WCHAR)));
1538 if (ret != NULL)
1539 {
1540 utf8_to_utf16(str, *lenp, (short_u *)ret, NULL);
1541 ret[length] = 0;
1542 }
1543
1544 vim_free(allocbuf);
1545 }
1546
1547 *lenp = length;
1548 return (short_u *)ret;
1549}
1550
1551/*
1552 * Convert an UTF-16 string to 'encoding'.
1553 * Input in "str" with length (counted in wide characters) "*lenp". When
1554 * "lenp" is NULL, use wcslen().
1555 * Output is returned as an allocated string. If "*lenp" is not NULL it is
1556 * set to the length of the result.
1557 * Returns NULL when out of memory.
1558 */
1559 char_u *
1560utf16_to_enc(short_u *str, int *lenp)
1561{
1562 vimconv_T conv;
1563 char_u *utf8_str = NULL, *enc_str = NULL;
1564 int len_loc;
1565
1566 if (lenp == NULL)
1567 {
1568 len_loc = (int)wcslen(str) + 1;
1569 lenp = &len_loc;
1570 }
1571
1572 if (enc_codepage > 0)
1573 {
1574 /* We can do any UTF-16 -> CP### in one pass. */
1575 int length;
1576
1577 WideCharToMultiByte_alloc(enc_codepage, 0, str, *lenp,
1578 (LPSTR *)&enc_str, &length, 0, 0);
1579 *lenp = length;
1580 return enc_str;
1581 }
1582
1583 /* Avoid allocating zero bytes, it generates an error message. */
1584 utf8_str = alloc(utf16_to_utf8(str, *lenp == 0 ? 1 : *lenp, NULL));
1585 if (utf8_str != NULL)
1586 {
1587 *lenp = utf16_to_utf8(str, *lenp, utf8_str);
1588
1589 /* We might be called before we have p_enc set up. */
1590 conv.vc_type = CONV_NONE;
1591 convert_setup(&conv, (char_u *)"utf-8",
1592 p_enc? p_enc: (char_u *)"latin1");
1593 if (conv.vc_type == CONV_NONE)
1594 {
1595 /* p_enc is utf-8, so we're done. */
1596 enc_str = utf8_str;
1597 }
1598 else
1599 {
1600 enc_str = string_convert(&conv, utf8_str, lenp);
1601 vim_free(utf8_str);
1602 }
1603
1604 convert_setup(&conv, NULL, NULL);
1605 }
1606
1607 return enc_str;
1608}
1609#endif /* FEAT_MBYTE */
1610
1611#if (defined(FEAT_MBYTE) && defined(WIN3264)) || defined(PROTO)
1612/*
1613 * Convert from the active codepage to 'encoding'.
1614 * Input is "str[str_size]".
1615 * The result is in allocated memory: "out[outlen]". With terminating NUL.
1616 */
1617 void
1618acp_to_enc(str, str_size, out, outlen)
1619 char_u *str;
1620 int str_size;
1621 char_u **out;
1622 int *outlen;
1623
1624{
1625 LPWSTR widestr;
1626
1627 MultiByteToWideChar_alloc(GetACP(), 0, str, str_size, &widestr, outlen);
1628 if (widestr != NULL)
1629 {
1630 ++*outlen; /* Include the 0 after the string */
1631 *out = utf16_to_enc((short_u *)widestr, outlen);
1632 vim_free(widestr);
1633 }
1634}
1635#endif
1636
Bram Moolenaar071d4272004-06-13 20:20:40 +00001637
1638/*
1639 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
1640 */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001641/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001642 void
1643DumpPutS(
1644 const char *psz)
1645{
1646# ifdef MCH_WRITE_DUMP
1647 if (fdDump)
1648 {
1649 fputs(psz, fdDump);
1650 if (psz[strlen(psz) - 1] != '\n')
1651 fputc('\n', fdDump);
1652 fflush(fdDump);
1653 }
1654# endif
1655}
1656
1657#ifdef _DEBUG
1658
1659void __cdecl
1660Trace(
1661 char *pszFormat,
1662 ...)
1663{
1664 CHAR szBuff[2048];
1665 va_list args;
1666
1667 va_start(args, pszFormat);
1668 vsprintf(szBuff, pszFormat, args);
1669 va_end(args);
1670
1671 OutputDebugString(szBuff);
1672}
1673
1674#endif //_DEBUG
1675
Bram Moolenaar843ee412004-06-30 16:16:41 +00001676#if !defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001677# if defined(FEAT_TITLE) && defined(WIN3264)
1678extern HWND g_hWnd; /* This is in os_win32.c. */
1679# endif
1680
1681/*
1682 * Showing the printer dialog is tricky since we have no GUI
1683 * window to parent it. The following routines are needed to
1684 * get the window parenting and Z-order to work properly.
1685 */
1686 static void
1687GetConsoleHwnd(void)
1688{
1689# define MY_BUFSIZE 1024 // Buffer size for console window titles.
1690
1691 char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
1692 char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
1693
1694 /* Skip if it's already set. */
1695 if (s_hwnd != 0)
1696 return;
1697
1698# if defined(FEAT_TITLE) && defined(WIN3264)
1699 /* Window handle may have been found by init code (Windows NT only) */
1700 if (g_hWnd != 0)
1701 {
1702 s_hwnd = g_hWnd;
1703 return;
1704 }
1705# endif
1706
1707 GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
1708
1709 wsprintf(pszNewWindowTitle, "%s/%d/%d",
1710 pszOldWindowTitle,
1711 GetTickCount(),
1712 GetCurrentProcessId());
1713 SetConsoleTitle(pszNewWindowTitle);
1714 Sleep(40);
1715 s_hwnd = FindWindow(NULL, pszNewWindowTitle);
1716
1717 SetConsoleTitle(pszOldWindowTitle);
1718}
Bram Moolenaar843ee412004-06-30 16:16:41 +00001719
1720/*
1721 * Console implementation of ":winpos".
1722 */
1723 int
1724mch_get_winpos(int *x, int *y)
1725{
1726 RECT rect;
1727
1728 GetConsoleHwnd();
1729 GetWindowRect(s_hwnd, &rect);
1730 *x = rect.left;
1731 *y = rect.top;
1732 return OK;
1733}
1734
1735/*
1736 * Console implementation of ":winpos x y".
1737 */
1738 void
1739mch_set_winpos(int x, int y)
1740{
1741 GetConsoleHwnd();
1742 SetWindowPos(s_hwnd, NULL, x, y, 0, 0,
1743 SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1744}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745#endif
1746
1747#if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1748
1749# ifdef WIN16
1750# define TEXT(a) a
1751# endif
1752/*=================================================================
1753 * Win32 printer stuff
1754 */
1755
1756static HFONT prt_font_handles[2][2][2];
1757static PRINTDLG prt_dlg;
1758static const int boldface[2] = {FW_REGULAR, FW_BOLD};
1759static TEXTMETRIC prt_tm;
1760static int prt_line_height;
1761static int prt_number_width;
1762static int prt_left_margin;
1763static int prt_right_margin;
1764static int prt_top_margin;
1765static char_u szAppName[] = TEXT("VIM");
1766static HWND hDlgPrint;
1767static int *bUserAbort = NULL;
1768static char_u *prt_name = NULL;
1769
1770/* Defines which are also in vim.rc. */
1771#define IDC_BOX1 400
1772#define IDC_PRINTTEXT1 401
1773#define IDC_PRINTTEXT2 402
1774#define IDC_PROGRESS 403
1775
1776/*
1777 * Convert BGR to RGB for Windows GDI calls
1778 */
1779 static COLORREF
1780swap_me(COLORREF colorref)
1781{
1782 int temp;
1783 char *ptr = (char *)&colorref;
1784
1785 temp = *(ptr);
1786 *(ptr ) = *(ptr + 2);
1787 *(ptr + 2) = temp;
1788 return colorref;
1789}
1790
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001791/* Attempt to make this work for old and new compilers */
Bram Moolenaar9f733d12011-09-21 20:09:42 +02001792#if !defined(_WIN64) && (!defined(_MSC_VER) || _MSC_VER < 1300)
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001793# define PDP_RETVAL BOOL
1794#else
1795# define PDP_RETVAL INT_PTR
1796#endif
1797
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001798/*ARGSUSED*/
Bram Moolenaared39e1d2008-08-09 17:55:22 +00001799 static PDP_RETVAL CALLBACK
Bram Moolenaar071d4272004-06-13 20:20:40 +00001800PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
1801{
1802#ifdef FEAT_GETTEXT
1803 NONCLIENTMETRICS nm;
1804 static HFONT hfont;
1805#endif
1806
1807 switch (message)
1808 {
1809 case WM_INITDIALOG:
1810#ifdef FEAT_GETTEXT
1811 nm.cbSize = sizeof(NONCLIENTMETRICS);
1812 if (SystemParametersInfo(
1813 SPI_GETNONCLIENTMETRICS,
1814 sizeof(NONCLIENTMETRICS),
1815 &nm,
1816 0))
1817 {
1818 char buff[MAX_PATH];
1819 int i;
1820
1821 /* Translate the dialog texts */
1822 hfont = CreateFontIndirect(&nm.lfMessageFont);
1823 for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++)
1824 {
1825 SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1);
1826 if (GetDlgItemText(hDlg,i, buff, sizeof(buff)))
1827 SetDlgItemText(hDlg,i, _(buff));
1828 }
1829 SendDlgItemMessage(hDlg, IDCANCEL,
1830 WM_SETFONT, (WPARAM)hfont, 1);
1831 if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff)))
1832 SetDlgItemText(hDlg,IDCANCEL, _(buff));
1833 }
1834#endif
1835 SetWindowText(hDlg, szAppName);
1836 if (prt_name != NULL)
1837 {
1838 SetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name);
1839 vim_free(prt_name);
1840 prt_name = NULL;
1841 }
1842 EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED);
1843#ifndef FEAT_GUI
1844 BringWindowToTop(s_hwnd);
1845#endif
1846 return TRUE;
1847
1848 case WM_COMMAND:
1849 *bUserAbort = TRUE;
1850 EnableWindow(GetParent(hDlg), TRUE);
1851 DestroyWindow(hDlg);
1852 hDlgPrint = NULL;
1853#ifdef FEAT_GETTEXT
1854 DeleteObject(hfont);
1855#endif
1856 return TRUE;
1857 }
1858 return FALSE;
1859}
1860
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00001861/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00001862 static BOOL CALLBACK
1863AbortProc(HDC hdcPrn, int iCode)
1864{
1865 MSG msg;
1866
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001867 while (!*bUserAbort && pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001868 {
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001869 if (!hDlgPrint || !pIsDialogMessage(hDlgPrint, &msg))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870 {
1871 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02001872 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001873 }
1874 }
1875 return !*bUserAbort;
1876}
1877
1878#ifndef FEAT_GUI
1879
Bram Moolenaar26fdd7d2011-11-30 13:42:44 +01001880 static UINT_PTR CALLBACK
Bram Moolenaar071d4272004-06-13 20:20:40 +00001881PrintHookProc(
1882 HWND hDlg, // handle to dialog box
1883 UINT uiMsg, // message identifier
1884 WPARAM wParam, // message parameter
1885 LPARAM lParam // message parameter
1886 )
1887{
1888 HWND hwndOwner;
1889 RECT rc, rcDlg, rcOwner;
1890 PRINTDLG *pPD;
1891
1892 if (uiMsg == WM_INITDIALOG)
1893 {
1894 // Get the owner window and dialog box rectangles.
1895 if ((hwndOwner = GetParent(hDlg)) == NULL)
1896 hwndOwner = GetDesktopWindow();
1897
1898 GetWindowRect(hwndOwner, &rcOwner);
1899 GetWindowRect(hDlg, &rcDlg);
1900 CopyRect(&rc, &rcOwner);
1901
1902 // Offset the owner and dialog box rectangles so that
1903 // right and bottom values represent the width and
1904 // height, and then offset the owner again to discard
1905 // space taken up by the dialog box.
1906
1907 OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
1908 OffsetRect(&rc, -rc.left, -rc.top);
1909 OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
1910
1911 // The new position is the sum of half the remaining
1912 // space and the owner's original position.
1913
1914 SetWindowPos(hDlg,
1915 HWND_TOP,
1916 rcOwner.left + (rc.right / 2),
1917 rcOwner.top + (rc.bottom / 2),
1918 0, 0, // ignores size arguments
1919 SWP_NOSIZE);
1920
1921 /* tackle the printdlg copiesctrl problem */
1922 pPD = (PRINTDLG *)lParam;
1923 pPD->nCopies = (WORD)pPD->lCustData;
1924 SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE );
1925 /* Bring the window to top */
1926 BringWindowToTop(GetParent(hDlg));
1927 SetForegroundWindow(hDlg);
1928 }
1929
1930 return FALSE;
1931}
1932#endif
1933
1934 void
1935mch_print_cleanup(void)
1936{
1937 int pifItalic;
1938 int pifBold;
1939 int pifUnderline;
1940
1941 for (pifBold = 0; pifBold <= 1; pifBold++)
1942 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1943 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1944 DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]);
1945
1946 if (prt_dlg.hDC != NULL)
1947 DeleteDC(prt_dlg.hDC);
1948 if (!*bUserAbort)
1949 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1950}
1951
1952 static int
1953to_device_units(int idx, int dpi, int physsize, int offset, int def_number)
1954{
1955 int ret = 0;
1956 int u;
1957 int nr;
1958
1959 u = prt_get_unit(idx);
1960 if (u == PRT_UNIT_NONE)
1961 {
1962 u = PRT_UNIT_PERC;
1963 nr = def_number;
1964 }
1965 else
1966 nr = printer_opts[idx].number;
1967
1968 switch (u)
1969 {
1970 case PRT_UNIT_PERC:
1971 ret = (physsize * nr) / 100;
1972 break;
1973 case PRT_UNIT_INCH:
1974 ret = (nr * dpi);
1975 break;
1976 case PRT_UNIT_MM:
1977 ret = (nr * 10 * dpi) / 254;
1978 break;
1979 case PRT_UNIT_POINT:
1980 ret = (nr * 10 * dpi) / 720;
1981 break;
1982 }
1983
1984 if (ret < offset)
1985 return 0;
1986 else
1987 return ret - offset;
1988}
1989
1990 static int
1991prt_get_cpl(void)
1992{
1993 int hr;
1994 int phyw;
1995 int dvoff;
1996 int rev_offset;
1997 int dpi;
1998#ifdef WIN16
1999 POINT pagesize;
2000#endif
2001
2002 GetTextMetrics(prt_dlg.hDC, &prt_tm);
2003 prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading;
2004
2005 hr = GetDeviceCaps(prt_dlg.hDC, HORZRES);
2006#ifdef WIN16
2007 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
2008 phyw = pagesize.x;
2009 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
2010 dvoff = pagesize.x;
2011#else
2012 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH);
2013 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX);
2014#endif
2015 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX);
2016
2017 rev_offset = phyw - (dvoff + hr);
2018
2019 prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10);
2020 if (prt_use_number())
2021 {
2022 prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth;
2023 prt_left_margin += prt_number_width;
2024 }
2025 else
2026 prt_number_width = 0;
2027
2028 prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw,
2029 rev_offset, 5);
2030
2031 return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth;
2032}
2033
2034 static int
2035prt_get_lpp(void)
2036{
2037 int vr;
2038 int phyw;
2039 int dvoff;
2040 int rev_offset;
2041 int bottom_margin;
2042 int dpi;
2043#ifdef WIN16
2044 POINT pagesize;
2045#endif
2046
2047 vr = GetDeviceCaps(prt_dlg.hDC, VERTRES);
2048#ifdef WIN16
2049 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
2050 phyw = pagesize.y;
2051 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
2052 dvoff = pagesize.y;
2053#else
2054 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT);
2055 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY);
2056#endif
2057 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY);
2058
2059 rev_offset = phyw - (dvoff + vr);
2060
2061 prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5);
2062
2063 /* adjust top margin if there is a header */
2064 prt_top_margin += prt_line_height * prt_header_height();
2065
2066 bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw,
2067 rev_offset, 5);
2068
2069 return (bottom_margin - prt_top_margin) / prt_line_height;
2070}
2071
2072 int
2073mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
2074{
2075 static HGLOBAL stored_dm = NULL;
2076 static HGLOBAL stored_devn = NULL;
2077 static int stored_nCopies = 1;
2078 static int stored_nFlags = 0;
2079
2080 LOGFONT fLogFont;
2081 int pifItalic;
2082 int pifBold;
2083 int pifUnderline;
2084
2085 DEVMODE *mem;
2086 DEVNAMES *devname;
2087 int i;
2088
2089 bUserAbort = &(psettings->user_abort);
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02002090 vim_memset(&prt_dlg, 0, sizeof(PRINTDLG));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002091 prt_dlg.lStructSize = sizeof(PRINTDLG);
2092#ifndef FEAT_GUI
2093 GetConsoleHwnd(); /* get value of s_hwnd */
2094#endif
2095 prt_dlg.hwndOwner = s_hwnd;
2096 prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
2097 if (!forceit)
2098 {
2099 prt_dlg.hDevMode = stored_dm;
2100 prt_dlg.hDevNames = stored_devn;
2101 prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog
2102#ifndef FEAT_GUI
2103 /*
2104 * Use hook to prevent console window being sent to back
2105 */
2106 prt_dlg.lpfnPrintHook = PrintHookProc;
2107 prt_dlg.Flags |= PD_ENABLEPRINTHOOK;
2108#endif
2109 prt_dlg.Flags |= stored_nFlags;
2110 }
2111
2112 /*
2113 * If bang present, return default printer setup with no dialog
2114 * never show dialog if we are running over telnet
2115 */
2116 if (forceit
2117#ifndef FEAT_GUI
2118 || !term_console
2119#endif
2120 )
2121 {
2122 prt_dlg.Flags |= PD_RETURNDEFAULT;
2123#ifdef WIN3264
2124 /*
2125 * MSDN suggests setting the first parameter to WINSPOOL for
2126 * NT, but NULL appears to work just as well.
2127 */
2128 if (*p_pdev != NUL)
2129 prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL);
2130 else
2131#endif
2132 {
2133 prt_dlg.Flags |= PD_RETURNDEFAULT;
2134 if (PrintDlg(&prt_dlg) == 0)
2135 goto init_fail_dlg;
2136 }
2137 }
2138 else if (PrintDlg(&prt_dlg) == 0)
2139 goto init_fail_dlg;
2140 else
2141 {
2142 /*
2143 * keep the previous driver context
2144 */
2145 stored_dm = prt_dlg.hDevMode;
2146 stored_devn = prt_dlg.hDevNames;
2147 stored_nFlags = prt_dlg.Flags;
2148 stored_nCopies = prt_dlg.nCopies;
2149 }
2150
2151 if (prt_dlg.hDC == NULL)
2152 {
2153 EMSG(_("E237: Printer selection failed"));
2154 mch_print_cleanup();
2155 return FALSE;
2156 }
2157
2158 /* Not all printer drivers report the support of color (or grey) in the
2159 * same way. Let's set has_color if there appears to be some way to print
2160 * more than B&W. */
2161 i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS);
2162 psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1
2163 || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1
2164 || i > 2 || i == -1);
2165
2166 /* Ensure all font styles are baseline aligned */
2167 SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT);
2168
2169 /*
2170 * On some windows systems the nCopies parameter is not
2171 * passed back correctly. It must be retrieved from the
2172 * hDevMode struct.
2173 */
2174 mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode);
2175 if (mem != NULL)
2176 {
2177#ifdef WIN3264
2178 if (mem->dmCopies != 1)
2179 stored_nCopies = mem->dmCopies;
2180#endif
2181 if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX))
2182 psettings->duplex = TRUE;
2183 if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR))
2184 psettings->has_color = TRUE;
2185 }
2186 GlobalUnlock(prt_dlg.hDevMode);
2187
2188 devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames);
2189 if (devname != 0)
2190 {
2191 char_u *printer_name = (char_u *)devname + devname->wDeviceOffset;
2192 char_u *port_name = (char_u *)devname +devname->wOutputOffset;
2193 char_u *text = _("to %s on %s");
2194
Bram Moolenaare6a91fd2008-07-24 18:51:11 +00002195 prt_name = alloc((unsigned)(STRLEN(printer_name) + STRLEN(port_name)
2196 + STRLEN(text)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002197 if (prt_name != NULL)
2198 wsprintf(prt_name, text, printer_name, port_name);
2199 }
2200 GlobalUnlock(prt_dlg.hDevNames);
2201
2202 /*
2203 * Initialise the font according to 'printfont'
2204 */
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02002205 vim_memset(&fLogFont, 0, sizeof(fLogFont));
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002206 if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002207 {
2208 EMSG2(_("E613: Unknown printer font: %s"), p_pfn);
2209 mch_print_cleanup();
2210 return FALSE;
2211 }
2212
2213 for (pifBold = 0; pifBold <= 1; pifBold++)
2214 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
2215 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
2216 {
2217 fLogFont.lfWeight = boldface[pifBold];
2218 fLogFont.lfItalic = pifItalic;
2219 fLogFont.lfUnderline = pifUnderline;
2220 prt_font_handles[pifBold][pifItalic][pifUnderline]
2221 = CreateFontIndirect(&fLogFont);
2222 }
2223
2224 SetBkMode(prt_dlg.hDC, OPAQUE);
2225 SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]);
2226
2227 /*
2228 * Fill in the settings struct
2229 */
2230 psettings->chars_per_line = prt_get_cpl();
2231 psettings->lines_per_page = prt_get_lpp();
2232 psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE)
2233 ? prt_dlg.nCopies : 1;
2234 psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE)
2235 ? 1 : prt_dlg.nCopies;
2236
2237 if (psettings->n_collated_copies == 0)
2238 psettings->n_collated_copies = 1;
2239
2240 if (psettings->n_uncollated_copies == 0)
2241 psettings->n_uncollated_copies = 1;
2242
2243 psettings->jobname = jobname;
2244
2245 return TRUE;
2246
2247init_fail_dlg:
2248 {
2249 DWORD err = CommDlgExtendedError();
2250
2251 if (err)
2252 {
2253#ifdef WIN16
2254 char buf[20];
2255
2256 sprintf(buf, "%ld", err);
2257 EMSG2(_("E238: Print error: %s"), buf);
2258#else
2259 char_u *buf;
2260
2261 /* I suspect FormatMessage() doesn't work for values returned by
2262 * CommDlgExtendedError(). What does? */
2263 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2264 FORMAT_MESSAGE_FROM_SYSTEM |
2265 FORMAT_MESSAGE_IGNORE_INSERTS,
2266 NULL, err, 0, (LPTSTR)(&buf), 0, NULL);
2267 EMSG2(_("E238: Print error: %s"),
2268 buf == NULL ? (char_u *)_("Unknown") : buf);
2269 LocalFree((LPVOID)(buf));
2270#endif
2271 }
2272 else
2273 msg_clr_eos(); /* Maybe canceled */
2274
2275 mch_print_cleanup();
2276 return FALSE;
2277 }
2278}
2279
2280
2281 int
2282mch_print_begin(prt_settings_T *psettings)
2283{
2284 int ret;
2285 static DOCINFO di;
2286 char szBuffer[300];
2287
2288 hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"),
2289 prt_dlg.hwndOwner, PrintDlgProc);
2290#ifdef WIN16
2291 Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL);
2292#else
2293 SetAbortProc(prt_dlg.hDC, AbortProc);
2294#endif
2295 wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname));
2296 SetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer);
2297
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02002298 vim_memset(&di, 0, sizeof(DOCINFO));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002299 di.cbSize = sizeof(DOCINFO);
2300 di.lpszDocName = psettings->jobname;
2301 ret = StartDoc(prt_dlg.hDC, &di);
2302
2303#ifdef FEAT_GUI
2304 /* Give focus back to main window (when using MDI). */
2305 SetFocus(s_hwnd);
2306#endif
2307
2308 return (ret > 0);
2309}
2310
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00002311/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312 void
2313mch_print_end(prt_settings_T *psettings)
2314{
2315 EndDoc(prt_dlg.hDC);
2316 if (!*bUserAbort)
2317 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
2318}
2319
2320 int
2321mch_print_end_page(void)
2322{
2323 return (EndPage(prt_dlg.hDC) > 0);
2324}
2325
2326 int
2327mch_print_begin_page(char_u *msg)
2328{
2329 if (msg != NULL)
2330 SetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg);
2331 return (StartPage(prt_dlg.hDC) > 0);
2332}
2333
2334 int
2335mch_print_blank_page(void)
2336{
2337 return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
2338}
2339
2340static int prt_pos_x = 0;
2341static int prt_pos_y = 0;
2342
2343 void
2344mch_print_start_line(margin, page_line)
2345 int margin;
2346 int page_line;
2347{
2348 if (margin)
2349 prt_pos_x = -prt_number_width;
2350 else
2351 prt_pos_x = 0;
2352 prt_pos_y = page_line * prt_line_height
2353 + prt_tm.tmAscent + prt_tm.tmExternalLeading;
2354}
2355
2356 int
2357mch_print_text_out(char_u *p, int len)
2358{
2359#ifdef FEAT_PROPORTIONAL_FONTS
2360 SIZE sz;
2361#endif
2362
2363 TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin,
2364 prt_pos_y + prt_top_margin, p, len);
2365#ifndef FEAT_PROPORTIONAL_FONTS
2366 prt_pos_x += len * prt_tm.tmAveCharWidth;
2367 return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth
2368 + prt_tm.tmOverhang > prt_right_margin);
2369#else
2370# ifdef WIN16
2371 GetTextExtentPoint(prt_dlg.hDC, p, len, &sz);
2372# else
2373 GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz);
2374# endif
2375 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
2376 /* This is wrong when printing spaces for a TAB. */
2377 if (p[len] == NUL)
2378 return FALSE;
2379# ifdef WIN16
2380 GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz);
2381# else
2382 GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz);
2383# endif
2384 return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
2385#endif
2386}
2387
2388 void
2389mch_print_set_font(int iBold, int iItalic, int iUnderline)
2390{
2391 SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]);
2392}
2393
2394 void
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00002395mch_print_set_bg(long_u bgcol)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002396{
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00002397 SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
2398 swap_me((COLORREF)bgcol)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 /*
2400 * With a white background we can draw characters transparent, which is
2401 * good for italic characters that overlap to the next char cell.
2402 */
2403 if (bgcol == 0xffffffUL)
2404 SetBkMode(prt_dlg.hDC, TRANSPARENT);
2405 else
2406 SetBkMode(prt_dlg.hDC, OPAQUE);
2407}
2408
2409 void
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00002410mch_print_set_fg(long_u fgcol)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002411{
Bram Moolenaar551dbcc2006-04-25 22:13:59 +00002412 SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
2413 swap_me((COLORREF)fgcol)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414}
2415
2416#endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
2417
Bram Moolenaar58d98232005-07-23 22:25:46 +00002418
2419
Bram Moolenaar071d4272004-06-13 20:20:40 +00002420#if defined(FEAT_SHORTCUT) || defined(PROTO)
Bram Moolenaar82881492012-11-20 16:53:39 +01002421# ifndef PROTO
2422# include <shlobj.h>
2423# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002424
2425/*
2426 * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
2427 * to and return that name in allocated memory.
2428 * Otherwise NULL is returned.
2429 */
2430 char_u *
2431mch_resolve_shortcut(char_u *fname)
2432{
2433 HRESULT hr;
2434 IShellLink *psl = NULL;
2435 IPersistFile *ppf = NULL;
2436 OLECHAR wsz[MAX_PATH];
2437 WIN32_FIND_DATA ffd; // we get those free of charge
2438 TCHAR buf[MAX_PATH]; // could have simply reused 'wsz'...
2439 char_u *rfname = NULL;
2440 int len;
2441
2442 /* Check if the file name ends in ".lnk". Avoid calling
2443 * CoCreateInstance(), it's quite slow. */
2444 if (fname == NULL)
2445 return rfname;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002446 len = (int)STRLEN(fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002447 if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
2448 return rfname;
2449
2450 CoInitialize(NULL);
2451
2452 // create a link manager object and request its interface
2453 hr = CoCreateInstance(
2454 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2455 &IID_IShellLink, (void**)&psl);
2456 if (hr != S_OK)
2457 goto shortcut_error;
2458
2459 // Get a pointer to the IPersistFile interface.
2460 hr = psl->lpVtbl->QueryInterface(
2461 psl, &IID_IPersistFile, (void**)&ppf);
2462 if (hr != S_OK)
2463 goto shortcut_error;
2464
2465 // full path string must be in Unicode.
2466 MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
2467
Bram Moolenaarff1d0d42007-05-10 17:24:16 +00002468 // "load" the name and resolve the link
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469 hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
2470 if (hr != S_OK)
2471 goto shortcut_error;
2472#if 0 // This makes Vim wait a long time if the target doesn't exist.
2473 hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
2474 if (hr != S_OK)
2475 goto shortcut_error;
2476#endif
2477
2478 // Get the path to the link target.
2479 ZeroMemory(buf, MAX_PATH);
2480 hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
2481 if (hr == S_OK && buf[0] != NUL)
2482 rfname = vim_strsave(buf);
2483
2484shortcut_error:
2485 // Release all interface pointers (both belong to the same object)
2486 if (ppf != NULL)
2487 ppf->lpVtbl->Release(ppf);
2488 if (psl != NULL)
2489 psl->lpVtbl->Release(psl);
2490
2491 CoUninitialize();
2492 return rfname;
2493}
2494#endif
2495
2496#if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
2497/*
2498 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
2499 */
2500 void
2501win32_set_foreground()
2502{
2503# ifndef FEAT_GUI
2504 GetConsoleHwnd(); /* get value of s_hwnd */
2505# endif
2506 if (s_hwnd != 0)
2507 SetForegroundWindow(s_hwnd);
2508}
2509#endif
2510
2511#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
2512/*
2513 * Client-server code for Vim
2514 *
2515 * Originally written by Paul Moore
2516 */
2517
2518/* In order to handle inter-process messages, we need to have a window. But
2519 * the functions in this module can be called before the main GUI window is
2520 * created (and may also be called in the console version, where there is no
2521 * GUI window at all).
2522 *
2523 * So we create a hidden window, and arrange to destroy it on exit.
2524 */
2525HWND message_window = 0; /* window that's handling messsages */
2526
2527#define VIM_CLASSNAME "VIM_MESSAGES"
2528#define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
2529
2530/* Communication is via WM_COPYDATA messages. The message type is send in
2531 * the dwData parameter. Types are defined here. */
2532#define COPYDATA_KEYS 0
2533#define COPYDATA_REPLY 1
2534#define COPYDATA_EXPR 10
2535#define COPYDATA_RESULT 11
2536#define COPYDATA_ERROR_RESULT 12
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002537#define COPYDATA_ENCODING 20
Bram Moolenaar071d4272004-06-13 20:20:40 +00002538
2539/* This is a structure containing a server HWND and its name. */
2540struct server_id
2541{
2542 HWND hwnd;
2543 char_u *name;
2544};
2545
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002546/* Last received 'encoding' that the client uses. */
2547static char_u *client_enc = NULL;
2548
2549/*
2550 * Tell the other side what encoding we are using.
2551 * Errors are ignored.
2552 */
2553 static void
2554serverSendEnc(HWND target)
2555{
2556 COPYDATASTRUCT data;
2557
2558 data.dwData = COPYDATA_ENCODING;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002559#ifdef FEAT_MBYTE
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002560 data.cbData = (DWORD)STRLEN(p_enc) + 1;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002561 data.lpData = p_enc;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002562#else
Bram Moolenaar8765a4a2010-07-27 22:41:43 +02002563 data.cbData = (DWORD)STRLEN("latin1") + 1;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002564 data.lpData = "latin1";
2565#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002566 (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2567 (LPARAM)(&data));
2568}
2569
Bram Moolenaar071d4272004-06-13 20:20:40 +00002570/*
2571 * Clean up on exit. This destroys the hidden message window.
2572 */
2573 static void
2574#ifdef __BORLANDC__
2575 _RTLENTRYF
2576#endif
2577CleanUpMessaging(void)
2578{
2579 if (message_window != 0)
2580 {
2581 DestroyWindow(message_window);
2582 message_window = 0;
2583 }
2584}
2585
2586static int save_reply(HWND server, char_u *reply, int expr);
2587
2588/*s
2589 * The window procedure for the hidden message window.
2590 * It handles callback messages and notifications from servers.
2591 * In order to process these messages, it is necessary to run a
2592 * message loop. Code which may run before the main message loop
2593 * is started (in the GUI) is careful to pump messages when it needs
2594 * to. Features which require message delivery during normal use will
2595 * not work in the console version - this basically means those
2596 * features which allow Vim to act as a server, rather than a client.
2597 */
2598 static LRESULT CALLBACK
2599Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2600{
2601 if (msg == WM_COPYDATA)
2602 {
2603 /* This is a message from another Vim. The dwData member of the
2604 * COPYDATASTRUCT determines the type of message:
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002605 * COPYDATA_ENCODING:
2606 * The encoding that the client uses. Following messages will
2607 * use this encoding, convert if needed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608 * COPYDATA_KEYS:
2609 * A key sequence. We are a server, and a client wants these keys
2610 * adding to the input queue.
2611 * COPYDATA_REPLY:
2612 * A reply. We are a client, and a server has sent this message
2613 * in response to a request. (server2client())
2614 * COPYDATA_EXPR:
2615 * An expression. We are a server, and a client wants us to
2616 * evaluate this expression.
2617 * COPYDATA_RESULT:
2618 * A reply. We are a client, and a server has sent this message
2619 * in response to a COPYDATA_EXPR.
2620 * COPYDATA_ERROR_RESULT:
2621 * A reply. We are a client, and a server has sent this message
2622 * in response to a COPYDATA_EXPR that failed to evaluate.
2623 */
2624 COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam;
2625 HWND sender = (HWND)wParam;
2626 COPYDATASTRUCT reply;
2627 char_u *res;
2628 char_u winstr[30];
2629 int retval;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002630 char_u *str;
2631 char_u *tofree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632
2633 switch (data->dwData)
2634 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002635 case COPYDATA_ENCODING:
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002636# ifdef FEAT_MBYTE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002637 /* Remember the encoding that the client uses. */
2638 vim_free(client_enc);
2639 client_enc = enc_canonize((char_u *)data->lpData);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002640# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002641 return 1;
2642
Bram Moolenaar071d4272004-06-13 20:20:40 +00002643 case COPYDATA_KEYS:
2644 /* Remember who sent this, for <client> */
2645 clientWindow = sender;
2646
2647 /* Add the received keys to the input buffer. The loop waiting
2648 * for the user to do something should check the input buffer. */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002649 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2650 server_to_input_buf(str);
2651 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002652
2653# ifdef FEAT_GUI
2654 /* Wake up the main GUI loop. */
2655 if (s_hwnd != 0)
2656 PostMessage(s_hwnd, WM_NULL, 0, 0);
2657# endif
2658 return 1;
2659
2660 case COPYDATA_EXPR:
2661 /* Remember who sent this, for <client> */
2662 clientWindow = sender;
2663
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002664 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2665 res = eval_client_expr_to_string(str);
2666 vim_free(tofree);
2667
Bram Moolenaar071d4272004-06-13 20:20:40 +00002668 if (res == NULL)
2669 {
2670 res = vim_strsave(_(e_invexprmsg));
2671 reply.dwData = COPYDATA_ERROR_RESULT;
2672 }
2673 else
2674 reply.dwData = COPYDATA_RESULT;
2675 reply.lpData = res;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002676 reply.cbData = (DWORD)STRLEN(res) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002677
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002678 serverSendEnc(sender);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002679 retval = (int)SendMessage(sender, WM_COPYDATA, (WPARAM)message_window,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002680 (LPARAM)(&reply));
2681 vim_free(res);
2682 return retval;
2683
2684 case COPYDATA_REPLY:
2685 case COPYDATA_RESULT:
2686 case COPYDATA_ERROR_RESULT:
2687 if (data->lpData != NULL)
2688 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002689 str = serverConvert(client_enc, (char_u *)data->lpData,
2690 &tofree);
2691 if (tofree == NULL)
2692 str = vim_strsave(str);
2693 if (save_reply(sender, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694 (data->dwData == COPYDATA_REPLY ? 0 :
2695 (data->dwData == COPYDATA_RESULT ? 1 :
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002696 2))) == FAIL)
2697 vim_free(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002698#ifdef FEAT_AUTOCMD
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002699 else if (data->dwData == COPYDATA_REPLY)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700 {
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002701 sprintf((char *)winstr, PRINTF_HEX_LONG_U, (long_u)sender);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002702 apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002703 TRUE, curbuf);
2704 }
2705#endif
2706 }
2707 return 1;
2708 }
2709
2710 return 0;
2711 }
2712
2713 else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2714 {
2715 /* When the message window is activated (brought to the foreground),
2716 * this actually applies to the text window. */
2717#ifndef FEAT_GUI
2718 GetConsoleHwnd(); /* get value of s_hwnd */
2719#endif
2720 if (s_hwnd != 0)
2721 {
2722 SetForegroundWindow(s_hwnd);
2723 return 0;
2724 }
2725 }
2726
2727 return DefWindowProc(hwnd, msg, wParam, lParam);
2728}
2729
2730/*
2731 * Initialise the message handling process. This involves creating a window
2732 * to handle messages - the window will not be visible.
2733 */
2734 void
2735serverInitMessaging(void)
2736{
2737 WNDCLASS wndclass;
2738 HINSTANCE s_hinst;
2739
2740 /* Clean up on exit */
2741 atexit(CleanUpMessaging);
2742
2743 /* Register a window class - we only really care
2744 * about the window procedure
2745 */
2746 s_hinst = (HINSTANCE)GetModuleHandle(0);
2747 wndclass.style = 0;
2748 wndclass.lpfnWndProc = Messaging_WndProc;
2749 wndclass.cbClsExtra = 0;
2750 wndclass.cbWndExtra = 0;
2751 wndclass.hInstance = s_hinst;
2752 wndclass.hIcon = NULL;
2753 wndclass.hCursor = NULL;
2754 wndclass.hbrBackground = NULL;
2755 wndclass.lpszMenuName = NULL;
2756 wndclass.lpszClassName = VIM_CLASSNAME;
2757 RegisterClass(&wndclass);
2758
2759 /* Create the message window. It will be hidden, so the details don't
2760 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2761 * focus from gvim. */
2762 message_window = CreateWindow(VIM_CLASSNAME, "",
2763 WS_POPUPWINDOW | WS_CAPTION,
2764 CW_USEDEFAULT, CW_USEDEFAULT,
2765 100, 100, NULL, NULL,
2766 s_hinst, NULL);
2767}
2768
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002769/* Used by serverSendToVim() to find an alternate server name. */
2770static char_u *altname_buf_ptr = NULL;
2771
Bram Moolenaar071d4272004-06-13 20:20:40 +00002772/*
2773 * Get the title of the window "hwnd", which is the Vim server name, in
2774 * "name[namelen]" and return the length.
2775 * Returns zero if window "hwnd" is not a Vim server.
2776 */
2777 static int
2778getVimServerName(HWND hwnd, char *name, int namelen)
2779{
2780 int len;
2781 char buffer[VIM_CLASSNAME_LEN + 1];
2782
2783 /* Ignore windows which aren't Vim message windows */
2784 len = GetClassName(hwnd, buffer, sizeof(buffer));
2785 if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2786 return 0;
2787
2788 /* Get the title of the window */
2789 return GetWindowText(hwnd, name, namelen);
2790}
2791
2792 static BOOL CALLBACK
2793enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2794{
2795 struct server_id *id = (struct server_id *)lparam;
2796 char server[MAX_PATH];
2797
2798 /* Get the title of the window */
2799 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2800 return TRUE;
2801
2802 /* If this is the server we're looking for, return its HWND */
2803 if (STRICMP(server, id->name) == 0)
2804 {
2805 id->hwnd = hwnd;
2806 return FALSE;
2807 }
2808
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002809 /* If we are looking for an alternate server, remember this name. */
2810 if (altname_buf_ptr != NULL
2811 && STRNICMP(server, id->name, STRLEN(id->name)) == 0
2812 && vim_isdigit(server[STRLEN(id->name)]))
2813 {
2814 STRCPY(altname_buf_ptr, server);
2815 altname_buf_ptr = NULL; /* don't use another name */
2816 }
2817
Bram Moolenaar071d4272004-06-13 20:20:40 +00002818 /* Otherwise, keep looking */
2819 return TRUE;
2820}
2821
2822 static BOOL CALLBACK
2823enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2824{
2825 garray_T *ga = (garray_T *)lparam;
2826 char server[MAX_PATH];
2827
2828 /* Get the title of the window */
2829 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2830 return TRUE;
2831
2832 /* Add the name to the list */
2833 ga_concat(ga, server);
2834 ga_concat(ga, "\n");
2835 return TRUE;
2836}
2837
2838 static HWND
2839findServer(char_u *name)
2840{
2841 struct server_id id;
2842
2843 id.name = name;
2844 id.hwnd = 0;
2845
2846 EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2847
2848 return id.hwnd;
2849}
2850
2851 void
2852serverSetName(char_u *name)
2853{
2854 char_u *ok_name;
2855 HWND hwnd = 0;
2856 int i = 0;
2857 char_u *p;
2858
2859 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002860 ok_name = alloc((unsigned)STRLEN(name) + 10);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861
2862 STRCPY(ok_name, name);
2863 p = ok_name + STRLEN(name);
2864
2865 for (;;)
2866 {
2867 /* This is inefficient - we're doing an EnumWindows loop for each
2868 * possible name. It would be better to grab all names in one go,
2869 * and scan the list each time...
2870 */
2871 hwnd = findServer(ok_name);
2872 if (hwnd == 0)
2873 break;
2874
2875 ++i;
2876 if (i >= 1000)
2877 break;
2878
2879 sprintf((char *)p, "%d", i);
2880 }
2881
2882 if (hwnd != 0)
2883 vim_free(ok_name);
2884 else
2885 {
2886 /* Remember the name */
2887 serverName = ok_name;
2888#ifdef FEAT_TITLE
2889 need_maketitle = TRUE; /* update Vim window title later */
2890#endif
2891
2892 /* Update the message window title */
2893 SetWindowText(message_window, ok_name);
2894
2895#ifdef FEAT_EVAL
2896 /* Set the servername variable */
2897 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2898#endif
2899 }
2900}
2901
2902 char_u *
2903serverGetVimNames(void)
2904{
2905 garray_T ga;
2906
2907 ga_init2(&ga, 1, 100);
2908
2909 EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
Bram Moolenaar269ec652004-07-29 08:43:53 +00002910 ga_append(&ga, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911
2912 return ga.ga_data;
2913}
2914
2915 int
2916serverSendReply(name, reply)
2917 char_u *name; /* Where to send. */
2918 char_u *reply; /* What to send. */
2919{
2920 HWND target;
2921 COPYDATASTRUCT data;
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002922 long_u n = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923
2924 /* The "name" argument is a magic cookie obtained from expand("<client>").
2925 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2926 * value of the client's message window HWND.
2927 */
Bram Moolenaareb3593b2006-04-22 22:33:57 +00002928 sscanf((char *)name, SCANF_HEX_LONG_U, &n);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929 if (n == 0)
2930 return -1;
2931
2932 target = (HWND)n;
2933 if (!IsWindow(target))
2934 return -1;
2935
2936 data.dwData = COPYDATA_REPLY;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002937 data.cbData = (DWORD)STRLEN(reply) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002938 data.lpData = reply;
2939
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002940 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2942 (LPARAM)(&data)))
2943 return 0;
2944
2945 return -1;
2946}
2947
2948 int
2949serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2950 char_u *name; /* Where to send. */
2951 char_u *cmd; /* What to send. */
2952 char_u **result; /* Result of eval'ed expression */
2953 void *ptarget; /* HWND of server */
2954 int asExpr; /* Expression or keys? */
2955 int silent; /* don't complain about no server */
2956{
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002957 HWND target;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958 COPYDATASTRUCT data;
2959 char_u *retval = NULL;
2960 int retcode = 0;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00002961 char_u altname_buf[MAX_PATH];
2962
2963 /* If the server name does not end in a digit then we look for an
2964 * alternate name. e.g. when "name" is GVIM the we may find GVIM2. */
2965 if (STRLEN(name) > 1 && !vim_isdigit(name[STRLEN(name) - 1]))
2966 altname_buf_ptr = altname_buf;
2967 altname_buf[0] = NUL;
2968 target = findServer(name);
2969 altname_buf_ptr = NULL;
2970 if (target == 0 && altname_buf[0] != NUL)
2971 /* Use another server name we found. */
2972 target = findServer(altname_buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002973
2974 if (target == 0)
2975 {
2976 if (!silent)
2977 EMSG2(_(e_noserver), name);
2978 return -1;
2979 }
2980
2981 if (ptarget)
2982 *(HWND *)ptarget = target;
2983
2984 data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002985 data.cbData = (DWORD)STRLEN(cmd) + 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002986 data.lpData = cmd;
2987
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002988 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002989 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2990 (LPARAM)(&data)) == 0)
2991 return -1;
2992
2993 if (asExpr)
2994 retval = serverGetReply(target, &retcode, TRUE, TRUE);
2995
2996 if (result == NULL)
2997 vim_free(retval);
2998 else
2999 *result = retval; /* Caller assumes responsibility for freeing */
3000
3001 return retcode;
3002}
3003
3004/*
3005 * Bring the server to the foreground.
3006 */
3007 void
3008serverForeground(name)
3009 char_u *name;
3010{
3011 HWND target = findServer(name);
3012
3013 if (target != 0)
3014 SetForegroundWindow(target);
3015}
3016
3017/* Replies from server need to be stored until the client picks them up via
3018 * remote_read(). So we maintain a list of server-id/reply pairs.
3019 * Note that there could be multiple replies from one server pending if the
3020 * client is slow picking them up.
3021 * We just store the replies in a simple list. When we remove an entry, we
3022 * move list entries down to fill the gap.
3023 * The server ID is simply the HWND.
3024 */
3025typedef struct
3026{
3027 HWND server; /* server window */
3028 char_u *reply; /* reply string */
3029 int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003030} reply_T;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003031
3032static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
3033
3034#define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
3035#define REPLY_COUNT (reply_list.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036
3037/* Flag which is used to wait for a reply */
3038static int reply_received = 0;
3039
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003040/*
3041 * Store a reply. "reply" must be allocated memory (or NULL).
3042 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003043 static int
3044save_reply(HWND server, char_u *reply, int expr)
3045{
3046 reply_T *rep;
3047
3048 if (ga_grow(&reply_list, 1) == FAIL)
3049 return FAIL;
3050
3051 rep = REPLY_ITEM(REPLY_COUNT);
3052 rep->server = server;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003053 rep->reply = reply;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054 rep->expr_result = expr;
3055 if (rep->reply == NULL)
3056 return FAIL;
3057
3058 ++REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003059 reply_received = 1;
3060 return OK;
3061}
3062
3063/*
3064 * Get a reply from server "server".
3065 * When "expr_res" is non NULL, get the result of an expression, otherwise a
3066 * server2client() message.
3067 * When non NULL, point to return code. 0 => OK, -1 => ERROR
3068 * If "remove" is TRUE, consume the message, the caller must free it then.
3069 * if "wait" is TRUE block until a message arrives (or the server exits).
3070 */
3071 char_u *
3072serverGetReply(HWND server, int *expr_res, int remove, int wait)
3073{
3074 int i;
3075 char_u *reply;
3076 reply_T *rep;
3077
3078 /* When waiting, loop until the message waiting for is received. */
3079 for (;;)
3080 {
3081 /* Reset this here, in case a message arrives while we are going
3082 * through the already received messages. */
3083 reply_received = 0;
3084
3085 for (i = 0; i < REPLY_COUNT; ++i)
3086 {
3087 rep = REPLY_ITEM(i);
3088 if (rep->server == server
3089 && ((rep->expr_result != 0) == (expr_res != NULL)))
3090 {
3091 /* Save the values we've found for later */
3092 reply = rep->reply;
3093 if (expr_res != NULL)
3094 *expr_res = rep->expr_result == 1 ? 0 : -1;
3095
3096 if (remove)
3097 {
3098 /* Move the rest of the list down to fill the gap */
3099 mch_memmove(rep, rep + 1,
3100 (REPLY_COUNT - i - 1) * sizeof(reply_T));
3101 --REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003102 }
3103
3104 /* Return the reply to the caller, who takes on responsibility
3105 * for freeing it if "remove" is TRUE. */
3106 return reply;
3107 }
3108 }
3109
3110 /* If we got here, we didn't find a reply. Return immediately if the
3111 * "wait" parameter isn't set. */
3112 if (!wait)
3113 break;
3114
3115 /* We need to wait for a reply. Enter a message loop until the
3116 * "reply_received" flag gets set. */
3117
3118 /* Loop until we receive a reply */
3119 while (reply_received == 0)
3120 {
3121 /* Wait for a SendMessage() call to us. This could be the reply
3122 * we are waiting for. Use a timeout of a second, to catch the
3123 * situation that the server died unexpectedly. */
3124 MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
3125
3126 /* If the server has died, give up */
3127 if (!IsWindow(server))
3128 return NULL;
3129
3130 serverProcessPendingMessages();
3131 }
3132 }
3133
3134 return NULL;
3135}
3136
3137/*
3138 * Process any messages in the Windows message queue.
3139 */
3140 void
3141serverProcessPendingMessages(void)
3142{
3143 MSG msg;
3144
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003145 while (pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146 {
3147 TranslateMessage(&msg);
Bram Moolenaar8c85fa32011-08-10 17:08:03 +02003148 pDispatchMessage(&msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003149 }
3150}
3151
3152#endif /* FEAT_CLIENTSERVER */
3153
3154#if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
3155 || defined(PROTO)
3156
3157struct charset_pair
3158{
3159 char *name;
3160 BYTE charset;
3161};
3162
3163static struct charset_pair
3164charset_pairs[] =
3165{
3166 {"ANSI", ANSI_CHARSET},
3167 {"CHINESEBIG5", CHINESEBIG5_CHARSET},
3168 {"DEFAULT", DEFAULT_CHARSET},
3169 {"HANGEUL", HANGEUL_CHARSET},
3170 {"OEM", OEM_CHARSET},
3171 {"SHIFTJIS", SHIFTJIS_CHARSET},
3172 {"SYMBOL", SYMBOL_CHARSET},
3173#ifdef WIN3264
3174 {"ARABIC", ARABIC_CHARSET},
3175 {"BALTIC", BALTIC_CHARSET},
3176 {"EASTEUROPE", EASTEUROPE_CHARSET},
3177 {"GB2312", GB2312_CHARSET},
3178 {"GREEK", GREEK_CHARSET},
3179 {"HEBREW", HEBREW_CHARSET},
3180 {"JOHAB", JOHAB_CHARSET},
3181 {"MAC", MAC_CHARSET},
3182 {"RUSSIAN", RUSSIAN_CHARSET},
3183 {"THAI", THAI_CHARSET},
3184 {"TURKISH", TURKISH_CHARSET},
3185# if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
3186 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
3187 {"VIETNAMESE", VIETNAMESE_CHARSET},
3188# endif
3189#endif
3190 {NULL, 0}
3191};
3192
3193/*
3194 * Convert a charset ID to a name.
3195 * Return NULL when not recognized.
3196 */
3197 char *
3198charset_id2name(int id)
3199{
3200 struct charset_pair *cp;
3201
3202 for (cp = charset_pairs; cp->name != NULL; ++cp)
3203 if ((BYTE)id == cp->charset)
3204 break;
3205 return cp->name;
3206}
3207
3208static const LOGFONT s_lfDefault =
3209{
3210 -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
3211 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
3212 PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
3213 "Fixedsys" /* see _ReadVimIni */
3214};
3215
3216/* Initialise the "current height" to -12 (same as s_lfDefault) just
3217 * in case the user specifies a font in "guifont" with no size before a font
3218 * with an explicit size has been set. This defaults the size to this value
3219 * (-12 equates to roughly 9pt).
3220 */
3221int current_font_height = -12; /* also used in gui_w48.c */
3222
3223/* Convert a string representing a point size into pixels. The string should
3224 * be a positive decimal number, with an optional decimal point (eg, "12", or
3225 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
3226 * character is stored in *end. The flag "vertical" says whether this
3227 * calculation is for a vertical (height) size or a horizontal (width) one.
3228 */
3229 static int
Bram Moolenaareb3593b2006-04-22 22:33:57 +00003230points_to_pixels(char_u *str, char_u **end, int vertical, long_i pprinter_dc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231{
3232 int pixels;
3233 int points = 0;
3234 int divisor = 0;
3235 HWND hwnd = (HWND)0;
3236 HDC hdc;
3237 HDC printer_dc = (HDC)pprinter_dc;
3238
3239 while (*str != NUL)
3240 {
3241 if (*str == '.' && divisor == 0)
3242 {
3243 /* Start keeping a divisor, for later */
3244 divisor = 1;
3245 }
3246 else
3247 {
3248 if (!VIM_ISDIGIT(*str))
3249 break;
3250
3251 points *= 10;
3252 points += *str - '0';
3253 divisor *= 10;
3254 }
3255 ++str;
3256 }
3257
3258 if (divisor == 0)
3259 divisor = 1;
3260
3261 if (printer_dc == NULL)
3262 {
3263 hwnd = GetDesktopWindow();
3264 hdc = GetWindowDC(hwnd);
3265 }
3266 else
3267 hdc = printer_dc;
3268
3269 pixels = MulDiv(points,
3270 GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
3271 72 * divisor);
3272
3273 if (printer_dc == NULL)
3274 ReleaseDC(hwnd, hdc);
3275
3276 *end = str;
3277 return pixels;
3278}
3279
Bram Moolenaar9ba0eb82005-06-13 22:28:56 +00003280/*ARGSUSED*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00003281 static int CALLBACK
3282font_enumproc(
3283 ENUMLOGFONT *elf,
3284 NEWTEXTMETRIC *ntm,
3285 int type,
3286 LPARAM lparam)
3287{
3288 /* Return value:
3289 * 0 = terminate now (monospace & ANSI)
3290 * 1 = continue, still no luck...
3291 * 2 = continue, but we have an acceptable LOGFONT
3292 * (monospace, not ANSI)
3293 * We use these values, as EnumFontFamilies returns 1 if the
3294 * callback function is never called. So, we check the return as
3295 * 0 = perfect, 2 = OK, 1 = no good...
3296 * It's not pretty, but it works!
3297 */
3298
3299 LOGFONT *lf = (LOGFONT *)(lparam);
3300
3301#ifndef FEAT_PROPORTIONAL_FONTS
3302 /* Ignore non-monospace fonts without further ado */
3303 if ((ntm->tmPitchAndFamily & 1) != 0)
3304 return 1;
3305#endif
3306
3307 /* Remember this LOGFONT as a "possible" */
3308 *lf = elf->elfLogFont;
3309
3310 /* Terminate the scan as soon as we find an ANSI font */
3311 if (lf->lfCharSet == ANSI_CHARSET
3312 || lf->lfCharSet == OEM_CHARSET
3313 || lf->lfCharSet == DEFAULT_CHARSET)
3314 return 0;
3315
3316 /* Continue the scan - we have a non-ANSI font */
3317 return 2;
3318}
3319
3320 static int
3321init_logfont(LOGFONT *lf)
3322{
3323 int n;
3324 HWND hwnd = GetDesktopWindow();
3325 HDC hdc = GetWindowDC(hwnd);
3326
3327 n = EnumFontFamilies(hdc,
3328 (LPCSTR)lf->lfFaceName,
3329 (FONTENUMPROC)font_enumproc,
3330 (LPARAM)lf);
3331
3332 ReleaseDC(hwnd, hdc);
3333
3334 /* If we couldn't find a useable font, return failure */
3335 if (n == 1)
3336 return FAIL;
3337
3338 /* Tidy up the rest of the LOGFONT structure. We set to a basic
3339 * font - get_logfont() sets bold, italic, etc based on the user's
3340 * input.
3341 */
3342 lf->lfHeight = current_font_height;
3343 lf->lfWidth = 0;
3344 lf->lfItalic = FALSE;
3345 lf->lfUnderline = FALSE;
3346 lf->lfStrikeOut = FALSE;
3347 lf->lfWeight = FW_NORMAL;
3348
3349 /* Return success */
3350 return OK;
3351}
3352
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003353/*
3354 * Get font info from "name" into logfont "lf".
3355 * Return OK for a valid name, FAIL otherwise.
3356 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 int
3358get_logfont(
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003359 LOGFONT *lf,
3360 char_u *name,
3361 HDC printer_dc,
3362 int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363{
3364 char_u *p;
3365 int i;
3366 static LOGFONT *lastlf = NULL;
3367
3368 *lf = s_lfDefault;
3369 if (name == NULL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003370 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371
3372 if (STRCMP(name, "*") == 0)
3373 {
3374#if defined(FEAT_GUI_W32)
3375 CHOOSEFONT cf;
3376 /* if name is "*", bring up std font dialog: */
Bram Moolenaar7db5fc82010-05-24 11:59:29 +02003377 vim_memset(&cf, 0, sizeof(cf));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003378 cf.lStructSize = sizeof(cf);
3379 cf.hwndOwner = s_hwnd;
3380 cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
3381 if (lastlf != NULL)
3382 *lf = *lastlf;
3383 cf.lpLogFont = lf;
3384 cf.nFontType = 0 ; //REGULAR_FONTTYPE;
3385 if (ChooseFont(&cf))
3386 goto theend;
3387#else
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003388 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003389#endif
3390 }
3391
3392 /*
3393 * Split name up, it could be <name>:h<height>:w<width> etc.
3394 */
3395 for (p = name; *p && *p != ':'; p++)
3396 {
3397 if (p - name + 1 > LF_FACESIZE)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003398 return FAIL; /* Name too long */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003399 lf->lfFaceName[p - name] = *p;
3400 }
3401 if (p != name)
3402 lf->lfFaceName[p - name] = NUL;
3403
3404 /* First set defaults */
3405 lf->lfHeight = -12;
3406 lf->lfWidth = 0;
3407 lf->lfWeight = FW_NORMAL;
3408 lf->lfItalic = FALSE;
3409 lf->lfUnderline = FALSE;
3410 lf->lfStrikeOut = FALSE;
3411
3412 /*
3413 * If the font can't be found, try replacing '_' by ' '.
3414 */
3415 if (init_logfont(lf) == FAIL)
3416 {
3417 int did_replace = FALSE;
3418
3419 for (i = 0; lf->lfFaceName[i]; ++i)
3420 if (lf->lfFaceName[i] == '_')
3421 {
3422 lf->lfFaceName[i] = ' ';
3423 did_replace = TRUE;
3424 }
3425 if (!did_replace || init_logfont(lf) == FAIL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003426 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003427 }
3428
3429 while (*p == ':')
3430 p++;
3431
3432 /* Set the values found after ':' */
3433 while (*p)
3434 {
3435 switch (*p++)
3436 {
3437 case 'h':
Bram Moolenaareb3593b2006-04-22 22:33:57 +00003438 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (long_i)printer_dc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003439 break;
3440 case 'w':
Bram Moolenaareb3593b2006-04-22 22:33:57 +00003441 lf->lfWidth = points_to_pixels(p, &p, FALSE, (long_i)printer_dc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442 break;
3443 case 'b':
3444#ifndef MSWIN16_FASTTEXT
3445 lf->lfWeight = FW_BOLD;
3446#endif
3447 break;
3448 case 'i':
3449#ifndef MSWIN16_FASTTEXT
3450 lf->lfItalic = TRUE;
3451#endif
3452 break;
3453 case 'u':
3454 lf->lfUnderline = TRUE;
3455 break;
3456 case 's':
3457 lf->lfStrikeOut = TRUE;
3458 break;
3459 case 'c':
3460 {
3461 struct charset_pair *cp;
3462
3463 for (cp = charset_pairs; cp->name != NULL; ++cp)
3464 if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
3465 {
3466 lf->lfCharSet = cp->charset;
3467 p += strlen(cp->name);
3468 break;
3469 }
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003470 if (cp->name == NULL && verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003471 {
Bram Moolenaar051b7822005-05-19 21:00:46 +00003472 vim_snprintf((char *)IObuff, IOSIZE,
3473 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003474 EMSG(IObuff);
3475 break;
3476 }
3477 break;
3478 }
3479 default:
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003480 if (verbose)
3481 {
Bram Moolenaar051b7822005-05-19 21:00:46 +00003482 vim_snprintf((char *)IObuff, IOSIZE,
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003483 _("E245: Illegal char '%c' in font name \"%s\""),
3484 p[-1], name);
3485 EMSG(IObuff);
3486 }
3487 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488 }
3489 while (*p == ':')
3490 p++;
3491 }
3492
3493#if defined(FEAT_GUI_W32)
3494theend:
3495#endif
3496 /* ron: init lastlf */
3497 if (printer_dc == NULL)
3498 {
3499 vim_free(lastlf);
3500 lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
3501 if (lastlf != NULL)
3502 mch_memmove(lastlf, lf, sizeof(LOGFONT));
3503 }
3504
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003505 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003506}
3507
3508#endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */