blob: 5d45d7bfb910a93bcf7186eb896858e71707c4a8 [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
25#include <io.h>
26#include "vim.h"
27
28#ifdef HAVE_FCNTL_H
29# include <fcntl.h>
30#endif
31#ifdef WIN16
32# define SHORT_FNAME /* always 8.3 file name */
33# include <dos.h>
34# include <string.h>
35#endif
36#include <sys/types.h>
37#include <errno.h>
38#include <signal.h>
39#include <limits.h>
40#include <process.h>
41
42#undef chdir
43#ifdef __GNUC__
44# ifndef __MINGW32__
45# include <dirent.h>
46# endif
47#else
48# include <direct.h>
49#endif
50
51#if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
52# include <shellapi.h>
53#endif
54
55#if defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)
56# include <dlgs.h>
57# ifdef WIN3264
58# include <winspool.h>
59# else
60# include <print.h>
61# endif
62# include <commdlg.h>
63#endif
64
65#ifdef __MINGW32__
66# ifndef FROM_LEFT_1ST_BUTTON_PRESSED
67# define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
68# endif
69# ifndef RIGHTMOST_BUTTON_PRESSED
70# define RIGHTMOST_BUTTON_PRESSED 0x0002
71# endif
72# ifndef FROM_LEFT_2ND_BUTTON_PRESSED
73# define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
74# endif
75# ifndef FROM_LEFT_3RD_BUTTON_PRESSED
76# define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
77# endif
78# ifndef FROM_LEFT_4TH_BUTTON_PRESSED
79# define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
80# endif
81
82/*
83 * EventFlags
84 */
85# ifndef MOUSE_MOVED
86# define MOUSE_MOVED 0x0001
87# endif
88# ifndef DOUBLE_CLICK
89# define DOUBLE_CLICK 0x0002
90# endif
91#endif
92
93/*
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
96 */
97#ifdef PROTO
98#define WINAPI
99#define WINBASEAPI
100typedef int BOOL;
101typedef int CALLBACK;
102typedef int COLORREF;
103typedef int CONSOLE_CURSOR_INFO;
104typedef int COORD;
105typedef int DWORD;
106typedef int ENUMLOGFONT;
107typedef int HANDLE;
108typedef int HDC;
109typedef int HFONT;
110typedef int HICON;
111typedef int HWND;
112typedef int INPUT_RECORD;
113typedef int KEY_EVENT_RECORD;
114typedef int LOGFONT;
115typedef int LPARAM;
116typedef int LPBOOL;
117typedef int LPCSTR;
118typedef int LPCWSTR;
119typedef int LPSTR;
120typedef int LPTSTR;
121typedef int LPWSTR;
122typedef int LRESULT;
123typedef int MOUSE_EVENT_RECORD;
124typedef int NEWTEXTMETRIC;
125typedef int PACL;
126typedef int PRINTDLG;
127typedef int PSECURITY_DESCRIPTOR;
128typedef int PSID;
129typedef int SECURITY_INFORMATION;
130typedef int SHORT;
131typedef int SMALL_RECT;
132typedef int TEXTMETRIC;
133typedef int UINT;
134typedef int WCHAR;
135typedef int WORD;
136typedef int WPARAM;
137typedef void VOID;
138#endif
139
140/* Record all output and all keyboard & mouse input */
141/* #define MCH_WRITE_DUMP */
142
143#ifdef MCH_WRITE_DUMP
144FILE* fdDump = NULL;
145#endif
146
147#ifdef WIN3264
148extern DWORD g_PlatformId;
149#endif
150
151#ifndef FEAT_GUI_MSWIN
152extern char g_szOrigTitle[];
153#endif
154
155#ifdef FEAT_GUI
156extern HWND s_hwnd;
157#else
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158static HWND s_hwnd = 0; /* console window handle, set by GetConsoleHwnd() */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000159#endif
160
161extern int WSInitialized;
162
163/* Don't generate prototypes here, because some systems do have these
164 * functions. */
165#if defined(__GNUC__) && !defined(PROTO)
166# ifndef __MINGW32__
167int _stricoll(char *a, char *b)
168{
169 // the ANSI-ish correct way is to use strxfrm():
170 char a_buff[512], b_buff[512]; // file names, so this is enough on Win32
171 strxfrm(a_buff, a, 512);
172 strxfrm(b_buff, b, 512);
173 return strcoll(a_buff, b_buff);
174}
175
176char * _fullpath(char *buf, char *fname, int len)
177{
178 LPTSTR toss;
179
180 return (char *)GetFullPathName(fname, len, buf, &toss);
181}
182# endif
183
184int _chdrive(int drive)
185{
186 char temp [3] = "-:";
187 temp[0] = drive + 'A' - 1;
188 return !SetCurrentDirectory(temp);
189}
190#else
191# ifdef __BORLANDC__
192/* being a more ANSI compliant compiler, BorlandC doesn't define _stricoll:
193 * but it does in BC 5.02! */
194# if __BORLANDC__ < 0x502
195int _stricoll(char *a, char *b)
196{
197# if 1
198 // this is fast but not correct:
199 return stricmp(a, b);
200# else
201 // the ANSI-ish correct way is to use strxfrm():
202 char a_buff[512], b_buff[512]; // file names, so this is enough on Win32
203 strxfrm(a_buff, a, 512);
204 strxfrm(b_buff, b, 512);
205 return strcoll(a_buff, b_buff);
206# endif
207}
208# endif
209# endif
210#endif
211
212
213#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
214/*
215 * GUI version of mch_exit().
216 * Shut down and exit with status `r'
217 * Careful: mch_exit() may be called before mch_init()!
218 */
219 void
220mch_exit(int r)
221{
222 display_errors();
223
224 ml_close_all(TRUE); /* remove all memfiles */
225
226# ifdef FEAT_OLE
227 UninitOLE();
228# endif
229# ifdef FEAT_NETBEANS_INTG
230 if (WSInitialized)
231 {
232 WSInitialized = FALSE;
233 WSACleanup();
234 }
235# endif
236#ifdef DYNAMIC_GETTEXT
237 dyn_libintl_end();
238#endif
239
240 if (gui.in_use)
241 gui_exit(r);
242 exit(r);
243}
244
245#endif /* FEAT_GUI_MSWIN */
246
247
248/*
249 * Init the tables for toupper() and tolower().
250 */
251 void
252mch_early_init(void)
253{
254 int i;
255
256#ifdef WIN3264
257 PlatformId();
258#endif
259
260 /* Init the tables for toupper() and tolower() */
261 for (i = 0; i < 256; ++i)
262 toupper_tab[i] = tolower_tab[i] = i;
263#ifdef WIN3264
264 CharUpperBuff(toupper_tab, 256);
265 CharLowerBuff(tolower_tab, 256);
266#else
267 AnsiUpperBuff(toupper_tab, 256);
268 AnsiLowerBuff(tolower_tab, 256);
269#endif
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000270
271#if defined(FEAT_MBYTE) && !defined(FEAT_GUI)
272 (void)get_cmd_argsW(NULL);
273#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000274}
275
276
277/*
278 * Return TRUE if the input comes from a terminal, FALSE otherwise.
279 */
280 int
281mch_input_isatty()
282{
283#ifdef FEAT_GUI_MSWIN
284 return OK; /* GUI always has a tty */
285#else
286 if (isatty(read_cmd_fd))
287 return TRUE;
288 return FALSE;
289#endif
290}
291
292#ifdef FEAT_TITLE
293/*
294 * mch_settitle(): set titlebar of our window
295 */
296 void
297mch_settitle(
298 char_u *title,
299 char_u *icon)
300{
301# ifdef FEAT_GUI_MSWIN
302 gui_mch_settitle(title, icon);
303# else
304 if (title != NULL)
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000305 {
306# ifdef FEAT_MBYTE
307 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
308 {
309 /* Convert the title from 'encoding' to the active codepage. */
310 WCHAR *wp = enc_to_ucs2(title, NULL);
311 int n;
312
313 if (wp != NULL)
314 {
315 n = SetConsoleTitleW(wp);
316 vim_free(wp);
317 if (n != 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
318 return;
319 }
320 }
321# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000322 SetConsoleTitle(title);
Bram Moolenaar3fdfa4a2004-10-07 21:02:47 +0000323 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324# endif
325}
326
327
328/*
329 * Restore the window/icon title.
330 * which is one of:
331 * 1: Just restore title
332 * 2: Just restore icon (which we don't have)
333 * 3: Restore title and icon (which we don't have)
334 */
335 void
336mch_restore_title(
337 int which)
338{
339#ifndef FEAT_GUI_MSWIN
340 mch_settitle((which & 1) ? g_szOrigTitle : NULL, NULL);
341#endif
342}
343
344
345/*
346 * Return TRUE if we can restore the title (we can)
347 */
348 int
349mch_can_restore_title()
350{
351 return TRUE;
352}
353
354
355/*
356 * Return TRUE if we can restore the icon title (we can't)
357 */
358 int
359mch_can_restore_icon()
360{
361 return FALSE;
362}
363#endif /* FEAT_TITLE */
364
365
366/*
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000367 * Get absolute file name into buffer "buf" of length "len" bytes,
368 * turning all '/'s into '\\'s and getting the correct case of each component
369 * of the file name. Append a (back)slash to a directory name.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000370 * When 'shellslash' set do it the other way around.
371 * Return OK or FAIL.
372 */
373 int
374mch_FullName(
375 char_u *fname,
376 char_u *buf,
377 int len,
378 int force)
379{
380 int nResult = FAIL;
381
382#ifdef __BORLANDC__
383 if (*fname == NUL) /* Borland behaves badly here - make it consistent */
384 nResult = mch_dirname(buf, len);
385 else
386#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000387 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000388 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
389# ifdef __BORLANDC__
390 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
391 && g_PlatformId == VER_PLATFORM_WIN32_NT
392# endif
393 )
394 {
395 WCHAR *wname;
396 WCHAR wbuf[MAX_PATH];
397 char_u *cname = NULL;
398
399 /* Use the wide function:
400 * - convert the fname from 'encoding' to UCS2.
401 * - invoke _wfullpath()
402 * - convert the result from UCS2 to 'encoding'.
403 */
404 wname = enc_to_ucs2(fname, NULL);
405 if (wname != NULL && _wfullpath(wbuf, wname, MAX_PATH - 1) != NULL)
406 {
407 cname = ucs2_to_enc((short_u *)wbuf, NULL);
408 if (cname != NULL)
409 {
410 STRNCPY(buf, cname, len);
411 buf[len - 1] = NUL;
412 nResult = OK;
413 }
414 }
415 vim_free(wname);
416 vim_free(cname);
417 }
418#ifdef FEAT_MBYTE
419 if (nResult == FAIL) /* fall back to non-wide function */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000420#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000421 {
422 if (_fullpath(buf, fname, len - 1) == NULL)
423 {
424 STRNCPY(buf, fname, len); /* failed, use relative path name */
425 buf[len - 1] = NUL;
426 }
427 else
428 nResult = OK;
429 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000431
432#ifdef USE_FNAME_CASE
433 fname_case(buf, len);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000434#else
435 slash_adjust(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436#endif
437
438 return nResult;
439}
440
441
442/*
443 * Return TRUE if "fname" does not depend on the current directory.
444 */
445 int
446mch_isFullName(char_u *fname)
447{
448 char szName[_MAX_PATH + 1];
449
450 /* A name like "d:/foo" and "//server/share" is absolute */
451 if ((fname[0] && fname[1] == ':' && (fname[2] == '/' || fname[2] == '\\'))
452 || (fname[0] == fname[1] && (fname[0] == '/' || fname[0] == '\\')))
453 return TRUE;
454
455 /* A name that can't be made absolute probably isn't absolute. */
456 if (mch_FullName(fname, szName, _MAX_PATH, FALSE) == FAIL)
457 return FALSE;
458
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000459 return pathcmp(fname, szName, -1) == 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000460}
461
462/*
463 * Replace all slashes by backslashes.
464 * This used to be the other way around, but MS-DOS sometimes has problems
465 * with slashes (e.g. in a command name). We can't have mixed slashes and
466 * backslashes, because comparing file names will not work correctly. The
467 * commands that use a file name should try to avoid the need to type a
468 * backslash twice.
469 * When 'shellslash' set do it the other way around.
470 */
471 void
472slash_adjust(p)
473 char_u *p;
474{
475 if (p != NULL)
476 while (*p)
477 {
478 if (*p == psepcN)
479 *p = psepc;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000480 mb_ptr_adv(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000481 }
482}
483
484
485/*
486 * stat() can't handle a trailing '/' or '\', remove it first.
487 */
488 int
489vim_stat(const char *name, struct stat *stp)
490{
491 char buf[_MAX_PATH + 1];
492 char *p;
493
494 STRNCPY(buf, name, _MAX_PATH);
495 buf[_MAX_PATH] = NUL;
496 p = buf + strlen(buf);
497 if (p > buf)
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000498 mb_ptr_back(buf, p);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000499 if (p > buf && (*p == '\\' || *p == '/') && p[-1] != ':')
500 *p = NUL;
501#ifdef FEAT_MBYTE
502 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
503# ifdef __BORLANDC__
504 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
505 && g_PlatformId == VER_PLATFORM_WIN32_NT
506# endif
507 )
508 {
509 WCHAR *wp = enc_to_ucs2(buf, NULL);
510 int n;
511
512 if (wp != NULL)
513 {
514 n = _wstat(wp, (struct _stat *)stp);
515 vim_free(wp);
516 if (n >= 0)
517 return n;
518 /* Retry with non-wide function (for Windows 98). Can't use
519 * GetLastError() here and it's unclear what errno gets set to if
520 * the _wstat() fails for missing wide functions. */
521 }
522 }
523#endif
524 return stat(buf, stp);
525}
526
527#if defined(FEAT_GUI_MSWIN) || defined(PROTO)
528 void
529mch_settmode(int tmode)
530{
531 /* nothing to do */
532}
533
534 int
535mch_get_shellsize(void)
536{
537 /* never used */
538 return OK;
539}
540
541 void
542mch_set_shellsize(void)
543{
544 /* never used */
545}
546
547/*
548 * Rows and/or Columns has changed.
549 */
550 void
551mch_new_shellsize(void)
552{
553 /* never used */
554}
555
556#endif
557
558/*
559 * We have no job control, so fake it by starting a new shell.
560 */
561 void
562mch_suspend()
563{
564 suspend_shell();
565}
566
567#if defined(USE_MCH_ERRMSG) || defined(PROTO)
568
569#ifdef display_errors
570# undef display_errors
571#endif
572
573/*
574 * Display the saved error message(s).
575 */
576 void
577display_errors()
578{
579 char *p;
580
581 if (error_ga.ga_data != NULL)
582 {
583 /* avoid putting up a message box with blanks only */
584 for (p = (char *)error_ga.ga_data; *p; ++p)
585 if (!isspace(*p))
586 {
Bram Moolenaar8089cae2005-02-05 21:35:05 +0000587#if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +0000588 /* Truncate a very long message, it will go off-screen. */
589 if (STRLEN(p) > 2000)
590 {
591 char_u *s = p + 2000 - 14;
592
593#ifdef FEAT_MBYTE
594 if (has_mbyte)
595 s -= (*mb_head_off)(p, s);
596#endif
597 STRCPY(s, _("...(truncated)"));
598 }
Bram Moolenaar8089cae2005-02-05 21:35:05 +0000599#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +0000600
601 (void)gui_mch_dialog(VIM_ERROR, (char_u *)_("Error"),
602 p, (char_u *)_("&Ok"), 1, NULL);
603#if 0
Bram Moolenaar071d4272004-06-13 20:20:40 +0000604#ifdef WIN3264
605 MessageBox(NULL, p, "Vim", MB_TASKMODAL|MB_SETFOREGROUND);
606#else
607 MessageBox(NULL, p, "Vim", MB_TASKMODAL);
608#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +0000609#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 break;
611 }
612 ga_clear(&error_ga);
613 }
614}
615#endif
616
617
618/*
619 * Return TRUE if "p" contain a wildcard that can be expanded by
620 * dos_expandpath().
621 */
622 int
623mch_has_exp_wildcard(char_u *p)
624{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000625 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626 {
627 if (vim_strchr((char_u *)"?*[", *p) != NULL
628 || (*p == '~' && p[1] != NUL))
629 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000630 }
631 return FALSE;
632}
633
634/*
635 * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a
636 * shortened file name).
637 */
638 int
639mch_has_wildcard(char_u *p)
640{
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000641 for ( ; *p; mb_ptr_adv(p))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000642 {
643 if (vim_strchr((char_u *)
644# ifdef VIM_BACKTICK
645 "?*$[`"
646# else
647 "?*$["
648# endif
649 , *p) != NULL
650 || (*p == '~' && p[1] != NUL))
651 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000652 }
653 return FALSE;
654}
655
656
657/*
658 * The normal _chdir() does not change the default drive. This one does.
659 * Returning 0 implies success; -1 implies failure.
660 */
661 int
662mch_chdir(char *path)
663{
664 if (path[0] == NUL) /* just checking... */
665 return -1;
666
667 if (isalpha(path[0]) && path[1] == ':') /* has a drive name */
668 {
669 /* If we can change to the drive, skip that part of the path. If we
670 * can't then the current directory may be invalid, try using chdir()
671 * with the whole path. */
672 if (_chdrive(TOLOWER_ASC(path[0]) - 'a' + 1) == 0)
673 path += 2;
674 }
675
676 if (*path == NUL) /* drive name only */
677 return 0;
678
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000679#ifdef FEAT_MBYTE
680 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
681 {
682 WCHAR *p = enc_to_ucs2(path, NULL);
683 int n;
684
685 if (p != NULL)
686 {
687 n = _wchdir(p);
688 vim_free(p);
689 if (n == 0)
690 return 0;
691 /* Retry with non-wide function (for Windows 98). */
692 }
693 }
694#endif
695
Bram Moolenaar071d4272004-06-13 20:20:40 +0000696 return chdir(path); /* let the normal chdir() do the rest */
697}
698
699
700/*
701 * Switching off termcap mode is only allowed when Columns is 80, otherwise a
702 * crash may result. It's always allowed on NT or when running the GUI.
703 */
704 int
705can_end_termcap_mode(
706 int give_msg)
707{
708#ifdef FEAT_GUI_MSWIN
709 return TRUE; /* GUI starts a new console anyway */
710#else
711 if (g_PlatformId == VER_PLATFORM_WIN32_NT || Columns == 80)
712 return TRUE;
713 if (give_msg)
714 msg(_("'columns' is not 80, cannot execute external commands"));
715 return FALSE;
716#endif
717}
718
719#ifdef FEAT_GUI_MSWIN
720/*
721 * return non-zero if a character is available
722 */
723 int
724mch_char_avail()
725{
726 /* never used */
727 return TRUE;
728}
729#endif
730
731
732/*
733 * set screen mode, always fails.
734 */
735 int
736mch_screenmode(
737 char_u *arg)
738{
739 EMSG(_(e_screenmode));
740 return FAIL;
741}
742
743
744#if defined(FEAT_LIBCALL) || defined(PROTO)
745/*
746 * Call a DLL routine which takes either a string or int param
747 * and returns an allocated string.
748 * Return OK if it worked, FAIL if not.
749 */
750# ifdef WIN3264
751typedef LPTSTR (*MYSTRPROCSTR)(LPTSTR);
752typedef LPTSTR (*MYINTPROCSTR)(int);
753typedef int (*MYSTRPROCINT)(LPTSTR);
754typedef int (*MYINTPROCINT)(int);
755# else
756typedef LPSTR (*MYSTRPROCSTR)(LPSTR);
757typedef LPSTR (*MYINTPROCSTR)(int);
758typedef int (*MYSTRPROCINT)(LPSTR);
759typedef int (*MYINTPROCINT)(int);
760# endif
761
762# ifndef WIN16
763/*
764 * Check if a pointer points to a valid NUL terminated string.
765 * Return the length of the string, including terminating NUL.
766 * Returns 0 for an invalid pointer, 1 for an empty string.
767 */
768 static size_t
769check_str_len(char_u *str)
770{
771 SYSTEM_INFO si;
772 MEMORY_BASIC_INFORMATION mbi;
773 size_t length = 0;
774 size_t i;
775 const char *p;
776
777 /* get page size */
778 GetSystemInfo(&si);
779
780 /* get memory information */
781 if (VirtualQuery(str, &mbi, sizeof(mbi)))
782 {
783 /* pre cast these (typing savers) */
784 DWORD dwStr = (DWORD)str;
785 DWORD dwBaseAddress = (DWORD)mbi.BaseAddress;
786
787 /* get start address of page that str is on */
788 DWORD strPage = dwStr - (dwStr - dwBaseAddress) % si.dwPageSize;
789
790 /* get length from str to end of page */
791 DWORD pageLength = si.dwPageSize - (dwStr - strPage);
792
793 for (p = str; !IsBadReadPtr(p, pageLength);
794 p += pageLength, pageLength = si.dwPageSize)
795 for (i = 0; i < pageLength; ++i, ++length)
796 if (p[i] == NUL)
797 return length + 1;
798 }
799
800 return 0;
801}
802# endif
803
804 int
805mch_libcall(
806 char_u *libname,
807 char_u *funcname,
808 char_u *argstring, /* NULL when using a argint */
809 int argint,
810 char_u **string_result,/* NULL when using number_result */
811 int *number_result)
812{
813 HINSTANCE hinstLib;
814 MYSTRPROCSTR ProcAdd;
815 MYINTPROCSTR ProcAddI;
816 char_u *retval_str = NULL;
817 int retval_int = 0;
818 size_t len;
819
820 BOOL fRunTimeLinkSuccess = FALSE;
821
822 // Get a handle to the DLL module.
823 hinstLib = LoadLibrary(libname);
824
825 // If the handle is valid, try to get the function address.
826 if (hinstLib != NULL)
827 {
828#ifdef HAVE_TRY_EXCEPT
829 __try
830 {
831#endif
832 if (argstring != NULL)
833 {
834 /* Call with string argument */
835 ProcAdd = (MYSTRPROCSTR) GetProcAddress(hinstLib, funcname);
836 if ((fRunTimeLinkSuccess = (ProcAdd != NULL)) != 0)
837 {
838 if (string_result == NULL)
839 retval_int = ((MYSTRPROCINT)ProcAdd)(argstring);
840 else
841 retval_str = (ProcAdd)(argstring);
842 }
843 }
844 else
845 {
846 /* Call with number argument */
847 ProcAddI = (MYINTPROCSTR) GetProcAddress(hinstLib, funcname);
848 if ((fRunTimeLinkSuccess = (ProcAddI != NULL)) != 0)
849 {
850 if (string_result == NULL)
851 retval_int = ((MYINTPROCINT)ProcAddI)(argint);
852 else
853 retval_str = (ProcAddI)(argint);
854 }
855 }
856
857 // Save the string before we free the library.
858 // Assume that a "1" result is an illegal pointer.
859 if (string_result == NULL)
860 *number_result = retval_int;
861 else if (retval_str != NULL
862# ifdef WIN16
863 && retval_str != (char_u *)1
864 && retval_str != (char_u *)-1
865 && !IsBadStringPtr(retval_str, INT_MAX)
866 && (len = strlen(retval_str) + 1) > 0
867# else
868 && (len = check_str_len(retval_str)) > 0
869# endif
870 )
871 {
872 *string_result = lalloc((long_u)len, TRUE);
873 if (*string_result != NULL)
874 mch_memmove(*string_result, retval_str, len);
875 }
876
877#ifdef HAVE_TRY_EXCEPT
878 }
879 __except(EXCEPTION_EXECUTE_HANDLER)
880 {
881 if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW)
882 RESETSTKOFLW();
883 fRunTimeLinkSuccess = 0;
884 }
885#endif
886
887 // Free the DLL module.
888 (void)FreeLibrary(hinstLib);
889 }
890
891 if (!fRunTimeLinkSuccess)
892 {
893 EMSG2(_(e_libcall), funcname);
894 return FAIL;
895 }
896
897 return OK;
898}
899#endif
900
901#if defined(FEAT_MBYTE) || defined(PROTO)
902/*
903 * Convert an UTF-8 string to UCS-2.
904 * "instr[inlen]" is the input. "inlen" is in bytes.
905 * When "outstr" is NULL only return the number of UCS-2 words produced.
906 * Otherwise "outstr" must be a buffer of sufficient size.
907 * Returns the number of UCS-2 words produced.
908 */
909 int
910utf8_to_ucs2(char_u *instr, int inlen, short_u *outstr, int *unconvlenp)
911{
912 int outlen = 0;
913 char_u *p = instr;
914 int todo = inlen;
915 int l;
916
917 while (todo > 0)
918 {
919 /* Only convert if we have a complete sequence. */
920 l = utf_ptr2len_check_len(p, todo);
921 if (l > todo)
922 {
923 /* Return length of incomplete sequence. */
924 if (unconvlenp != NULL)
925 *unconvlenp = todo;
926 break;
927 }
928
929 if (outstr != NULL)
930 *outstr++ = utf_ptr2char(p);
931 ++outlen;
932 p += l;
933 todo -= l;
934 }
935
936 return outlen;
937}
938
939/*
940 * Convert an UCS-2 string to UTF-8.
941 * The input is "instr[inlen]" with "inlen" in number of ucs-2 words.
942 * When "outstr" is NULL only return the required number of bytes.
943 * Otherwise "outstr" must be a buffer of sufficient size.
944 * Return the number of bytes produced.
945 */
946 int
947ucs2_to_utf8(short_u *instr, int inlen, char_u *outstr)
948{
949 int outlen = 0;
950 int todo = inlen;
951 short_u *p = instr;
952 int l;
953
954 while (todo > 0)
955 {
956 if (outstr != NULL)
957 {
958 l = utf_char2bytes(*p, outstr);
959 outstr += l;
960 }
961 else
962 l = utf_char2len(*p);
963 ++p;
964 outlen += l;
965 --todo;
966 }
967
968 return outlen;
969}
970
971/*
972 * Call MultiByteToWideChar() and allocate memory for the result.
973 * Returns the result in "*out[*outlen]" with an extra zero appended.
974 * "outlen" is in words.
975 */
976 void
977MultiByteToWideChar_alloc(UINT cp, DWORD flags,
978 LPCSTR in, int inlen,
979 LPWSTR *out, int *outlen)
980{
981 *outlen = MultiByteToWideChar(cp, flags, in, inlen, 0, 0);
982 /* Add one one word to avoid a zero-length alloc(). */
983 *out = (LPWSTR)alloc(sizeof(WCHAR) * (*outlen + 1));
984 if (*out != NULL)
985 {
986 MultiByteToWideChar(cp, flags, in, inlen, *out, *outlen);
987 (*out)[*outlen] = 0;
988 }
989}
990
991/*
992 * Call WideCharToMultiByte() and allocate memory for the result.
993 * Returns the result in "*out[*outlen]" with an extra NUL appended.
994 */
995 void
996WideCharToMultiByte_alloc(UINT cp, DWORD flags,
997 LPCWSTR in, int inlen,
998 LPSTR *out, int *outlen,
999 LPCSTR def, LPBOOL useddef)
1000{
1001 *outlen = WideCharToMultiByte(cp, flags, in, inlen, NULL, 0, def, useddef);
1002 /* Add one one byte to avoid a zero-length alloc(). */
1003 *out = alloc((unsigned)*outlen + 1);
1004 if (*out != NULL)
1005 {
1006 WideCharToMultiByte(cp, flags, in, inlen, *out, *outlen, def, useddef);
1007 (*out)[*outlen] = 0;
1008 }
1009}
1010
1011#endif /* FEAT_MBYTE */
1012
1013#ifdef FEAT_CLIPBOARD
1014/*
1015 * Clipboard stuff, for cutting and pasting text to other windows.
1016 */
1017
1018/* Type used for the clipboard type of Vim's data. */
1019typedef struct
1020{
1021 int type; /* MCHAR, MBLOCK or MLINE */
1022 int txtlen; /* length of CF_TEXT in bytes */
1023 int ucslen; /* length of CF_UNICODETEXT in words */
1024 int rawlen; /* length of clip_star.format_raw, including encoding,
1025 excluding terminating NUL */
1026} VimClipType_t;
1027
1028/*
1029 * Make vim the owner of the current selection. Return OK upon success.
1030 */
1031 int
1032clip_mch_own_selection(VimClipboard *cbd)
1033{
1034 /*
1035 * Never actually own the clipboard. If another application sets the
1036 * clipboard, we don't want to think that we still own it.
1037 */
1038 return FAIL;
1039}
1040
1041/*
1042 * Make vim NOT the owner of the current selection.
1043 */
1044 void
1045clip_mch_lose_selection(VimClipboard *cbd)
1046{
1047 /* Nothing needs to be done here */
1048}
1049
1050/*
1051 * Copy "str[*size]" into allocated memory, changing CR-NL to NL.
1052 * Return the allocated result and the size in "*size".
1053 * Returns NULL when out of memory.
1054 */
1055 static char_u *
1056crnl_to_nl(const char_u *str, int *size)
1057{
1058 int pos = 0;
1059 int str_len = *size;
1060 char_u *ret;
1061 char_u *retp;
1062
1063 /* Avoid allocating zero bytes, it generates an error message. */
1064 ret = lalloc((long_u)(str_len == 0 ? 1 : str_len), TRUE);
1065 if (ret != NULL)
1066 {
1067 retp = ret;
1068 for (pos = 0; pos < str_len; ++pos)
1069 {
1070 if (str[pos] == '\r' && str[pos + 1] == '\n')
1071 {
1072 ++pos;
1073 --(*size);
1074 }
1075 *retp++ = str[pos];
1076 }
1077 }
1078
1079 return ret;
1080}
1081
1082#if defined(FEAT_MBYTE) || defined(PROTO)
1083/*
1084 * Note: the following two functions are only guaranteed to work when using
1085 * valid MS-Windows codepages or when iconv() is available.
1086 */
1087
1088/*
1089 * Convert "str" from 'encoding' to UCS-2.
1090 * Input in "str" with length "*lenp". When "lenp" is NULL, use strlen().
1091 * Output is returned as an allocated string. "*lenp" is set to the length of
1092 * the result. A trailing NUL is always added.
1093 * Returns NULL when out of memory.
1094 */
1095 short_u *
1096enc_to_ucs2(char_u *str, int *lenp)
1097{
1098 vimconv_T conv;
1099 WCHAR *ret;
1100 char_u *allocbuf = NULL;
1101 int len_loc;
1102 int length;
1103
1104 if (lenp == NULL)
1105 {
1106 len_loc = STRLEN(str) + 1;
1107 lenp = &len_loc;
1108 }
1109
1110 if (enc_codepage > 0)
1111 {
1112 /* We can do any CP### -> UCS-2 in one pass, and we can do it
1113 * without iconv() (convert_* may need iconv). */
1114 MultiByteToWideChar_alloc(enc_codepage, 0, str, *lenp, &ret, &length);
1115 }
1116 else
1117 {
1118 /* Use "latin1" by default, we might be called before we have p_enc
1119 * set up. Convert to utf-8 first, works better with iconv(). Does
1120 * nothing if 'encoding' is "utf-8". */
1121 conv.vc_type = CONV_NONE;
1122 if (convert_setup(&conv, p_enc ? p_enc : (char_u *)"latin1",
1123 (char_u *)"utf-8") == FAIL)
1124 return NULL;
1125 if (conv.vc_type != CONV_NONE)
1126 {
1127 str = allocbuf = string_convert(&conv, str, lenp);
1128 if (str == NULL)
1129 return NULL;
1130 }
1131 convert_setup(&conv, NULL, NULL);
1132
1133 length = utf8_to_ucs2(str, *lenp, NULL, NULL);
1134 ret = (WCHAR *)alloc((unsigned)((length + 1) * sizeof(WCHAR)));
1135 if (ret != NULL)
1136 {
1137 utf8_to_ucs2(str, *lenp, (short_u *)ret, NULL);
1138 ret[length] = 0;
1139 }
1140
1141 vim_free(allocbuf);
1142 }
1143
1144 *lenp = length;
1145 return (short_u *)ret;
1146}
1147
1148/*
1149 * Convert an UCS-2 string to 'encoding'.
1150 * Input in "str" with length (counted in wide characters) "*lenp". When
1151 * "lenp" is NULL, use wcslen().
1152 * Output is returned as an allocated string. If "*lenp" is not NULL it is
1153 * set to the length of the result.
1154 * Returns NULL when out of memory.
1155 */
1156 char_u *
1157ucs2_to_enc(short_u *str, int *lenp)
1158{
1159 vimconv_T conv;
1160 char_u *utf8_str = NULL, *enc_str = NULL;
1161 int len_loc;
1162
1163 if (lenp == NULL)
1164 {
1165 len_loc = wcslen(str) + 1;
1166 lenp = &len_loc;
1167 }
1168
1169 if (enc_codepage > 0)
1170 {
1171 /* We can do any UCS-2 -> CP### in one pass. */
1172 int length;
1173
1174 WideCharToMultiByte_alloc(enc_codepage, 0, str, *lenp,
1175 (LPSTR *)&enc_str, &length, 0, 0);
1176 *lenp = length;
1177 return enc_str;
1178 }
1179
1180 /* Avoid allocating zero bytes, it generates an error message. */
1181 utf8_str = alloc(ucs2_to_utf8(str, *lenp == 0 ? 1 : *lenp, NULL));
1182 if (utf8_str != NULL)
1183 {
1184 *lenp = ucs2_to_utf8(str, *lenp, utf8_str);
1185
1186 /* We might be called before we have p_enc set up. */
1187 conv.vc_type = CONV_NONE;
1188 convert_setup(&conv, (char_u *)"utf-8",
1189 p_enc? p_enc: (char_u *)"latin1");
1190 if (conv.vc_type == CONV_NONE)
1191 {
1192 /* p_enc is utf-8, so we're done. */
1193 enc_str = utf8_str;
1194 }
1195 else
1196 {
1197 enc_str = string_convert(&conv, utf8_str, lenp);
1198 vim_free(utf8_str);
1199 }
1200
1201 convert_setup(&conv, NULL, NULL);
1202 }
1203
1204 return enc_str;
1205}
1206#endif /* FEAT_MBYTE */
1207
1208/*
1209 * Get the current selection and put it in the clipboard register.
1210 *
1211 * NOTE: Must use GlobalLock/Unlock here to ensure Win32s compatibility.
1212 * On NT/W95 the clipboard data is a fixed global memory object and
1213 * so its handle = its pointer.
1214 * On Win32s, however, co-operation with the Win16 system means that
1215 * the clipboard data is moveable and its handle is not a pointer at all,
1216 * so we can't just cast the return value of GetClipboardData to (char_u*).
1217 * <VN>
1218 */
1219 void
1220clip_mch_request_selection(VimClipboard *cbd)
1221{
1222 VimClipType_t metadata = { -1, -1, -1, -1 };
1223 HGLOBAL hMem = NULL;
1224 char_u *str = NULL;
1225#if defined(FEAT_MBYTE) && defined(WIN3264)
1226 char_u *to_free = NULL;
1227#endif
1228#ifdef FEAT_MBYTE
1229 HGLOBAL rawh = NULL;
1230#endif
1231 char_u *hMemStr = NULL;
1232 int str_size = 0;
1233 int maxlen;
1234 size_t n;
1235
1236 /*
1237 * Don't pass GetActiveWindow() as an argument to OpenClipboard() because
1238 * then we can't paste back into the same window for some reason - webb.
1239 */
1240 if (!OpenClipboard(NULL))
1241 return;
1242
1243 /* Check for vim's own clipboard format first. This only gets the type of
1244 * the data, still need to use CF_UNICODETEXT or CF_TEXT for the text. */
1245 if (IsClipboardFormatAvailable(cbd->format))
1246 {
1247 VimClipType_t *meta_p;
1248 HGLOBAL meta_h;
1249
1250 /* We have metadata on the clipboard; try to get it. */
1251 if ((meta_h = GetClipboardData(cbd->format)) != NULL
1252 && (meta_p = (VimClipType_t *)GlobalLock(meta_h)) != NULL)
1253 {
1254 /* The size of "VimClipType_t" changed, "rawlen" was added later.
1255 * Only copy what is available for backwards compatibility. */
1256 n = sizeof(VimClipType_t);
1257 if (GlobalSize(meta_h) < n)
1258 n = GlobalSize(meta_h);
1259 memcpy(&metadata, meta_p, n);
1260 GlobalUnlock(meta_h);
1261 }
1262 }
1263
1264#ifdef FEAT_MBYTE
1265 /* Check for Vim's raw clipboard format first. This is used without
1266 * conversion, but only if 'encoding' matches. */
1267 if (IsClipboardFormatAvailable(cbd->format_raw)
1268 && metadata.rawlen > (int)STRLEN(p_enc))
1269 {
1270 /* We have raw data on the clipboard; try to get it. */
1271 if ((rawh = GetClipboardData(cbd->format_raw)) != NULL)
1272 {
1273 char_u *rawp;
1274
1275 rawp = (char_u *)GlobalLock(rawh);
1276 if (rawp != NULL && STRCMP(p_enc, rawp) == 0)
1277 {
1278 n = STRLEN(p_enc) + 1;
1279 str = rawp + n;
1280 str_size = metadata.rawlen - n;
1281 }
1282 else
1283 {
1284 GlobalUnlock(rawh);
1285 rawh = NULL;
1286 }
1287 }
1288 }
1289 if (str == NULL)
1290 {
1291#endif
1292
1293#if defined(FEAT_MBYTE) && defined(WIN3264)
1294 /* Try to get the clipboard in Unicode if it's not an empty string. */
1295 if (IsClipboardFormatAvailable(CF_UNICODETEXT) && metadata.ucslen != 0)
1296 {
1297 HGLOBAL hMemW;
1298
1299 if ((hMemW = GetClipboardData(CF_UNICODETEXT)) != NULL)
1300 {
1301 WCHAR *hMemWstr = (WCHAR *)GlobalLock(hMemW);
1302
1303 /* Use the length of our metadata if possible, but limit it to the
1304 * GlobalSize() for safety. */
1305 maxlen = GlobalSize(hMemW) / sizeof(WCHAR);
1306 if (metadata.ucslen >= 0)
1307 {
1308 if (metadata.ucslen > maxlen)
1309 str_size = maxlen;
1310 else
1311 str_size = metadata.ucslen;
1312 }
1313 else
1314 {
1315 for (str_size = 0; str_size < maxlen; ++str_size)
1316 if (hMemWstr[str_size] == NUL)
1317 break;
1318 }
1319 to_free = str = ucs2_to_enc((short_u *)hMemWstr, &str_size);
1320 GlobalUnlock(hMemW);
1321 }
1322 }
1323 else
1324#endif
1325 /* Get the clipboard in the Active codepage. */
1326 if (IsClipboardFormatAvailable(CF_TEXT))
1327 {
1328 if ((hMem = GetClipboardData(CF_TEXT)) != NULL)
1329 {
1330 str = hMemStr = (char_u *)GlobalLock(hMem);
1331
1332 /* The length is either what our metadata says or the strlen().
1333 * But limit it to the GlobalSize() for safety. */
1334 maxlen = GlobalSize(hMem);
1335 if (metadata.txtlen >= 0)
1336 {
1337 if (metadata.txtlen > maxlen)
1338 str_size = maxlen;
1339 else
1340 str_size = metadata.txtlen;
1341 }
1342 else
1343 {
1344 for (str_size = 0; str_size < maxlen; ++str_size)
1345 if (str[str_size] == NUL)
1346 break;
1347 }
1348
1349#if defined(FEAT_MBYTE) && defined(WIN3264)
1350 /* The text is in the active codepage. Convert to 'encoding',
1351 * going through UCS-2. */
1352 MultiByteToWideChar_alloc(GetACP(), 0, str, str_size,
1353 (LPWSTR *)&to_free, &maxlen);
1354 if (to_free != NULL)
1355 {
1356 str_size = maxlen;
1357 str = ucs2_to_enc((short_u *)to_free, &str_size);
1358 if (str != NULL)
1359 {
1360 vim_free(to_free);
1361 to_free = str;
1362 }
1363 }
1364#endif
1365 }
1366 }
1367#ifdef FEAT_MBYTE
1368 }
1369#endif
1370
1371 if (str != NULL && *str != NUL)
1372 {
1373 char_u *temp_clipboard;
1374
1375 /* If the type is not known guess it. */
1376 if (metadata.type == -1)
1377 metadata.type = (vim_strchr(str, '\n') == NULL) ? MCHAR : MLINE;
1378
1379 /* Translate <CR><NL> into <NL>. */
1380 temp_clipboard = crnl_to_nl(str, &str_size);
1381 if (temp_clipboard != NULL)
1382 {
1383 clip_yank_selection(metadata.type, temp_clipboard, str_size, cbd);
1384 vim_free(temp_clipboard);
1385 }
1386 }
1387
1388 /* unlock the global object */
1389 if (hMem != NULL)
1390 GlobalUnlock(hMem);
1391#ifdef FEAT_MBYTE
1392 if (rawh != NULL)
1393 GlobalUnlock(rawh);
1394#endif
1395 CloseClipboard();
1396#if defined(FEAT_MBYTE) && defined(WIN3264)
1397 vim_free(to_free);
1398#endif
1399}
1400
1401/*
1402 * Send the current selection to the clipboard.
1403 */
1404 void
1405clip_mch_set_selection(VimClipboard *cbd)
1406{
1407 char_u *str = NULL;
1408 VimClipType_t metadata;
1409 long_u txtlen;
1410 HGLOBAL hMemRaw = NULL;
1411 HGLOBAL hMem = NULL;
1412 HGLOBAL hMemVim = NULL;
1413# if defined(FEAT_MBYTE) && defined(WIN3264)
1414 HGLOBAL hMemW = NULL;
1415# endif
1416
1417 /* If the '*' register isn't already filled in, fill it in now */
1418 cbd->owned = TRUE;
1419 clip_get_selection(cbd);
1420 cbd->owned = FALSE;
1421
1422 /* Get the text to be put on the clipboard, with CR-LF. */
1423 metadata.type = clip_convert_selection(&str, &txtlen, cbd);
1424 if (metadata.type < 0)
1425 return;
1426 metadata.txtlen = (int)txtlen;
1427 metadata.ucslen = 0;
1428 metadata.rawlen = 0;
1429
1430#ifdef FEAT_MBYTE
1431 /* Always set the raw bytes: 'encoding', NUL and the text. This is used
1432 * when copy/paste from/to Vim with the same 'encoding', so that illegal
1433 * bytes can also be copied and no conversion is needed. */
1434 {
1435 LPSTR lpszMemRaw;
1436
1437 metadata.rawlen = txtlen + STRLEN(p_enc) + 1;
1438 hMemRaw = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1439 metadata.rawlen + 1);
1440 lpszMemRaw = (LPSTR)GlobalLock(hMemRaw);
1441 if (lpszMemRaw != NULL)
1442 {
1443 STRCPY(lpszMemRaw, p_enc);
1444 memcpy(lpszMemRaw + STRLEN(p_enc) + 1, str, txtlen + 1);
1445 GlobalUnlock(hMemRaw);
1446 }
1447 else
1448 metadata.rawlen = 0;
1449 }
1450#endif
1451
1452# if defined(FEAT_MBYTE) && defined(WIN3264)
1453 {
1454 WCHAR *out;
1455 int len = metadata.txtlen;
1456
1457 /* Convert the text to UCS-2. This is put on the clipboard as
1458 * CF_UNICODETEXT. */
1459 out = (WCHAR *)enc_to_ucs2(str, &len);
1460 if (out != NULL)
1461 {
1462 WCHAR *lpszMemW;
1463
1464 /* Convert the text for CF_TEXT to Active codepage. Otherwise it's
1465 * p_enc, which has no relation to the Active codepage. */
1466 metadata.txtlen = WideCharToMultiByte(GetACP(), 0, out, len,
1467 NULL, 0, 0, 0);
1468 vim_free(str);
1469 str = (char_u *)alloc((unsigned)(metadata.txtlen == 0 ? 1
1470 : metadata.txtlen));
1471 if (str == NULL)
1472 {
1473 vim_free(out);
1474 return; /* out of memory */
1475 }
1476 WideCharToMultiByte(GetACP(), 0, out, len,
1477 str, metadata.txtlen, 0, 0);
1478
1479 /* Allocate memory for the UCS-2 text, add one NUL word to
1480 * terminate the string. */
1481 hMemW = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1482 (len + 1) * sizeof(WCHAR));
1483 lpszMemW = (WCHAR *)GlobalLock(hMemW);
1484 if (lpszMemW != NULL)
1485 {
1486 memcpy(lpszMemW, out, len * sizeof(WCHAR));
1487 lpszMemW[len] = NUL;
1488 GlobalUnlock(hMemW);
1489 }
1490 vim_free(out);
1491 metadata.ucslen = len;
1492 }
1493 }
1494# endif
1495
1496 /* Allocate memory for the text, add one NUL byte to terminate the string.
1497 */
1498 hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, metadata.txtlen + 1);
1499 {
1500 LPSTR lpszMem = (LPSTR)GlobalLock(hMem);
1501
1502 if (lpszMem)
1503 {
1504 STRNCPY(lpszMem, str, metadata.txtlen);
1505 lpszMem[metadata.txtlen] = NUL;
1506 GlobalUnlock(hMem);
1507 }
1508 }
1509
1510 /* Set up metadata: */
1511 {
1512 VimClipType_t *lpszMemVim = NULL;
1513
1514 hMemVim = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,
1515 sizeof(VimClipType_t));
1516 lpszMemVim = (VimClipType_t *)GlobalLock(hMemVim);
1517 memcpy(lpszMemVim, &metadata, sizeof(metadata));
1518 GlobalUnlock(hMemVim);
1519 }
1520
1521 /*
1522 * Open the clipboard, clear it and put our text on it.
1523 * Always set our Vim format. Put Unicode and plain text on it.
1524 *
1525 * Don't pass GetActiveWindow() as an argument to OpenClipboard()
1526 * because then we can't paste back into the same window for some
1527 * reason - webb.
1528 */
1529 if (OpenClipboard(NULL))
1530 {
1531 if (EmptyClipboard())
1532 {
1533 SetClipboardData(cbd->format, hMemVim);
1534 hMemVim = 0;
1535# if defined(FEAT_MBYTE) && defined(WIN3264)
1536 if (hMemW != NULL)
1537 {
1538 if (SetClipboardData(CF_UNICODETEXT, hMemW) != NULL)
1539 hMemW = NULL;
1540 }
1541# endif
1542 /* Always use CF_TEXT. On Win98 Notepad won't obtain the
1543 * CF_UNICODETEXT text, only CF_TEXT. */
1544 SetClipboardData(CF_TEXT, hMem);
1545 hMem = 0;
1546 }
1547 CloseClipboard();
1548 }
1549
1550 vim_free(str);
1551 /* Free any allocations we didn't give to the clipboard: */
1552 if (hMemRaw)
1553 GlobalFree(hMemRaw);
1554 if (hMem)
1555 GlobalFree(hMem);
1556# if defined(FEAT_MBYTE) && defined(WIN3264)
1557 if (hMemW)
1558 GlobalFree(hMemW);
1559# endif
1560 if (hMemVim)
1561 GlobalFree(hMemVim);
1562}
1563
1564#endif /* FEAT_CLIPBOARD */
1565
1566
1567/*
1568 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
1569 */
1570 void
1571DumpPutS(
1572 const char *psz)
1573{
1574# ifdef MCH_WRITE_DUMP
1575 if (fdDump)
1576 {
1577 fputs(psz, fdDump);
1578 if (psz[strlen(psz) - 1] != '\n')
1579 fputc('\n', fdDump);
1580 fflush(fdDump);
1581 }
1582# endif
1583}
1584
1585#ifdef _DEBUG
1586
1587void __cdecl
1588Trace(
1589 char *pszFormat,
1590 ...)
1591{
1592 CHAR szBuff[2048];
1593 va_list args;
1594
1595 va_start(args, pszFormat);
1596 vsprintf(szBuff, pszFormat, args);
1597 va_end(args);
1598
1599 OutputDebugString(szBuff);
1600}
1601
1602#endif //_DEBUG
1603
Bram Moolenaar843ee412004-06-30 16:16:41 +00001604#if !defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605# if defined(FEAT_TITLE) && defined(WIN3264)
1606extern HWND g_hWnd; /* This is in os_win32.c. */
1607# endif
1608
1609/*
1610 * Showing the printer dialog is tricky since we have no GUI
1611 * window to parent it. The following routines are needed to
1612 * get the window parenting and Z-order to work properly.
1613 */
1614 static void
1615GetConsoleHwnd(void)
1616{
1617# define MY_BUFSIZE 1024 // Buffer size for console window titles.
1618
1619 char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
1620 char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
1621
1622 /* Skip if it's already set. */
1623 if (s_hwnd != 0)
1624 return;
1625
1626# if defined(FEAT_TITLE) && defined(WIN3264)
1627 /* Window handle may have been found by init code (Windows NT only) */
1628 if (g_hWnd != 0)
1629 {
1630 s_hwnd = g_hWnd;
1631 return;
1632 }
1633# endif
1634
1635 GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
1636
1637 wsprintf(pszNewWindowTitle, "%s/%d/%d",
1638 pszOldWindowTitle,
1639 GetTickCount(),
1640 GetCurrentProcessId());
1641 SetConsoleTitle(pszNewWindowTitle);
1642 Sleep(40);
1643 s_hwnd = FindWindow(NULL, pszNewWindowTitle);
1644
1645 SetConsoleTitle(pszOldWindowTitle);
1646}
Bram Moolenaar843ee412004-06-30 16:16:41 +00001647
1648/*
1649 * Console implementation of ":winpos".
1650 */
1651 int
1652mch_get_winpos(int *x, int *y)
1653{
1654 RECT rect;
1655
1656 GetConsoleHwnd();
1657 GetWindowRect(s_hwnd, &rect);
1658 *x = rect.left;
1659 *y = rect.top;
1660 return OK;
1661}
1662
1663/*
1664 * Console implementation of ":winpos x y".
1665 */
1666 void
1667mch_set_winpos(int x, int y)
1668{
1669 GetConsoleHwnd();
1670 SetWindowPos(s_hwnd, NULL, x, y, 0, 0,
1671 SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1672}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001673#endif
1674
1675#if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1676
1677# ifdef WIN16
1678# define TEXT(a) a
1679# endif
1680/*=================================================================
1681 * Win32 printer stuff
1682 */
1683
1684static HFONT prt_font_handles[2][2][2];
1685static PRINTDLG prt_dlg;
1686static const int boldface[2] = {FW_REGULAR, FW_BOLD};
1687static TEXTMETRIC prt_tm;
1688static int prt_line_height;
1689static int prt_number_width;
1690static int prt_left_margin;
1691static int prt_right_margin;
1692static int prt_top_margin;
1693static char_u szAppName[] = TEXT("VIM");
1694static HWND hDlgPrint;
1695static int *bUserAbort = NULL;
1696static char_u *prt_name = NULL;
1697
1698/* Defines which are also in vim.rc. */
1699#define IDC_BOX1 400
1700#define IDC_PRINTTEXT1 401
1701#define IDC_PRINTTEXT2 402
1702#define IDC_PROGRESS 403
1703
1704/*
1705 * Convert BGR to RGB for Windows GDI calls
1706 */
1707 static COLORREF
1708swap_me(COLORREF colorref)
1709{
1710 int temp;
1711 char *ptr = (char *)&colorref;
1712
1713 temp = *(ptr);
1714 *(ptr ) = *(ptr + 2);
1715 *(ptr + 2) = temp;
1716 return colorref;
1717}
1718
1719 static BOOL CALLBACK
1720PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
1721{
1722#ifdef FEAT_GETTEXT
1723 NONCLIENTMETRICS nm;
1724 static HFONT hfont;
1725#endif
1726
1727 switch (message)
1728 {
1729 case WM_INITDIALOG:
1730#ifdef FEAT_GETTEXT
1731 nm.cbSize = sizeof(NONCLIENTMETRICS);
1732 if (SystemParametersInfo(
1733 SPI_GETNONCLIENTMETRICS,
1734 sizeof(NONCLIENTMETRICS),
1735 &nm,
1736 0))
1737 {
1738 char buff[MAX_PATH];
1739 int i;
1740
1741 /* Translate the dialog texts */
1742 hfont = CreateFontIndirect(&nm.lfMessageFont);
1743 for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++)
1744 {
1745 SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1);
1746 if (GetDlgItemText(hDlg,i, buff, sizeof(buff)))
1747 SetDlgItemText(hDlg,i, _(buff));
1748 }
1749 SendDlgItemMessage(hDlg, IDCANCEL,
1750 WM_SETFONT, (WPARAM)hfont, 1);
1751 if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff)))
1752 SetDlgItemText(hDlg,IDCANCEL, _(buff));
1753 }
1754#endif
1755 SetWindowText(hDlg, szAppName);
1756 if (prt_name != NULL)
1757 {
1758 SetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name);
1759 vim_free(prt_name);
1760 prt_name = NULL;
1761 }
1762 EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED);
1763#ifndef FEAT_GUI
1764 BringWindowToTop(s_hwnd);
1765#endif
1766 return TRUE;
1767
1768 case WM_COMMAND:
1769 *bUserAbort = TRUE;
1770 EnableWindow(GetParent(hDlg), TRUE);
1771 DestroyWindow(hDlg);
1772 hDlgPrint = NULL;
1773#ifdef FEAT_GETTEXT
1774 DeleteObject(hfont);
1775#endif
1776 return TRUE;
1777 }
1778 return FALSE;
1779}
1780
1781 static BOOL CALLBACK
1782AbortProc(HDC hdcPrn, int iCode)
1783{
1784 MSG msg;
1785
1786 while (!*bUserAbort && PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1787 {
1788 if (!hDlgPrint || !IsDialogMessage(hDlgPrint, &msg))
1789 {
1790 TranslateMessage(&msg);
1791 DispatchMessage(&msg);
1792 }
1793 }
1794 return !*bUserAbort;
1795}
1796
1797#ifndef FEAT_GUI
1798
1799 static UINT CALLBACK
1800PrintHookProc(
1801 HWND hDlg, // handle to dialog box
1802 UINT uiMsg, // message identifier
1803 WPARAM wParam, // message parameter
1804 LPARAM lParam // message parameter
1805 )
1806{
1807 HWND hwndOwner;
1808 RECT rc, rcDlg, rcOwner;
1809 PRINTDLG *pPD;
1810
1811 if (uiMsg == WM_INITDIALOG)
1812 {
1813 // Get the owner window and dialog box rectangles.
1814 if ((hwndOwner = GetParent(hDlg)) == NULL)
1815 hwndOwner = GetDesktopWindow();
1816
1817 GetWindowRect(hwndOwner, &rcOwner);
1818 GetWindowRect(hDlg, &rcDlg);
1819 CopyRect(&rc, &rcOwner);
1820
1821 // Offset the owner and dialog box rectangles so that
1822 // right and bottom values represent the width and
1823 // height, and then offset the owner again to discard
1824 // space taken up by the dialog box.
1825
1826 OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
1827 OffsetRect(&rc, -rc.left, -rc.top);
1828 OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
1829
1830 // The new position is the sum of half the remaining
1831 // space and the owner's original position.
1832
1833 SetWindowPos(hDlg,
1834 HWND_TOP,
1835 rcOwner.left + (rc.right / 2),
1836 rcOwner.top + (rc.bottom / 2),
1837 0, 0, // ignores size arguments
1838 SWP_NOSIZE);
1839
1840 /* tackle the printdlg copiesctrl problem */
1841 pPD = (PRINTDLG *)lParam;
1842 pPD->nCopies = (WORD)pPD->lCustData;
1843 SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE );
1844 /* Bring the window to top */
1845 BringWindowToTop(GetParent(hDlg));
1846 SetForegroundWindow(hDlg);
1847 }
1848
1849 return FALSE;
1850}
1851#endif
1852
1853 void
1854mch_print_cleanup(void)
1855{
1856 int pifItalic;
1857 int pifBold;
1858 int pifUnderline;
1859
1860 for (pifBold = 0; pifBold <= 1; pifBold++)
1861 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1862 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1863 DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]);
1864
1865 if (prt_dlg.hDC != NULL)
1866 DeleteDC(prt_dlg.hDC);
1867 if (!*bUserAbort)
1868 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1869}
1870
1871 static int
1872to_device_units(int idx, int dpi, int physsize, int offset, int def_number)
1873{
1874 int ret = 0;
1875 int u;
1876 int nr;
1877
1878 u = prt_get_unit(idx);
1879 if (u == PRT_UNIT_NONE)
1880 {
1881 u = PRT_UNIT_PERC;
1882 nr = def_number;
1883 }
1884 else
1885 nr = printer_opts[idx].number;
1886
1887 switch (u)
1888 {
1889 case PRT_UNIT_PERC:
1890 ret = (physsize * nr) / 100;
1891 break;
1892 case PRT_UNIT_INCH:
1893 ret = (nr * dpi);
1894 break;
1895 case PRT_UNIT_MM:
1896 ret = (nr * 10 * dpi) / 254;
1897 break;
1898 case PRT_UNIT_POINT:
1899 ret = (nr * 10 * dpi) / 720;
1900 break;
1901 }
1902
1903 if (ret < offset)
1904 return 0;
1905 else
1906 return ret - offset;
1907}
1908
1909 static int
1910prt_get_cpl(void)
1911{
1912 int hr;
1913 int phyw;
1914 int dvoff;
1915 int rev_offset;
1916 int dpi;
1917#ifdef WIN16
1918 POINT pagesize;
1919#endif
1920
1921 GetTextMetrics(prt_dlg.hDC, &prt_tm);
1922 prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading;
1923
1924 hr = GetDeviceCaps(prt_dlg.hDC, HORZRES);
1925#ifdef WIN16
1926 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1927 phyw = pagesize.x;
1928 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1929 dvoff = pagesize.x;
1930#else
1931 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH);
1932 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX);
1933#endif
1934 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX);
1935
1936 rev_offset = phyw - (dvoff + hr);
1937
1938 prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10);
1939 if (prt_use_number())
1940 {
1941 prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth;
1942 prt_left_margin += prt_number_width;
1943 }
1944 else
1945 prt_number_width = 0;
1946
1947 prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw,
1948 rev_offset, 5);
1949
1950 return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth;
1951}
1952
1953 static int
1954prt_get_lpp(void)
1955{
1956 int vr;
1957 int phyw;
1958 int dvoff;
1959 int rev_offset;
1960 int bottom_margin;
1961 int dpi;
1962#ifdef WIN16
1963 POINT pagesize;
1964#endif
1965
1966 vr = GetDeviceCaps(prt_dlg.hDC, VERTRES);
1967#ifdef WIN16
1968 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1969 phyw = pagesize.y;
1970 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1971 dvoff = pagesize.y;
1972#else
1973 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT);
1974 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY);
1975#endif
1976 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY);
1977
1978 rev_offset = phyw - (dvoff + vr);
1979
1980 prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5);
1981
1982 /* adjust top margin if there is a header */
1983 prt_top_margin += prt_line_height * prt_header_height();
1984
1985 bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw,
1986 rev_offset, 5);
1987
1988 return (bottom_margin - prt_top_margin) / prt_line_height;
1989}
1990
1991 int
1992mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
1993{
1994 static HGLOBAL stored_dm = NULL;
1995 static HGLOBAL stored_devn = NULL;
1996 static int stored_nCopies = 1;
1997 static int stored_nFlags = 0;
1998
1999 LOGFONT fLogFont;
2000 int pifItalic;
2001 int pifBold;
2002 int pifUnderline;
2003
2004 DEVMODE *mem;
2005 DEVNAMES *devname;
2006 int i;
2007
2008 bUserAbort = &(psettings->user_abort);
2009 memset(&prt_dlg, 0, sizeof(PRINTDLG));
2010 prt_dlg.lStructSize = sizeof(PRINTDLG);
2011#ifndef FEAT_GUI
2012 GetConsoleHwnd(); /* get value of s_hwnd */
2013#endif
2014 prt_dlg.hwndOwner = s_hwnd;
2015 prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
2016 if (!forceit)
2017 {
2018 prt_dlg.hDevMode = stored_dm;
2019 prt_dlg.hDevNames = stored_devn;
2020 prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog
2021#ifndef FEAT_GUI
2022 /*
2023 * Use hook to prevent console window being sent to back
2024 */
2025 prt_dlg.lpfnPrintHook = PrintHookProc;
2026 prt_dlg.Flags |= PD_ENABLEPRINTHOOK;
2027#endif
2028 prt_dlg.Flags |= stored_nFlags;
2029 }
2030
2031 /*
2032 * If bang present, return default printer setup with no dialog
2033 * never show dialog if we are running over telnet
2034 */
2035 if (forceit
2036#ifndef FEAT_GUI
2037 || !term_console
2038#endif
2039 )
2040 {
2041 prt_dlg.Flags |= PD_RETURNDEFAULT;
2042#ifdef WIN3264
2043 /*
2044 * MSDN suggests setting the first parameter to WINSPOOL for
2045 * NT, but NULL appears to work just as well.
2046 */
2047 if (*p_pdev != NUL)
2048 prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL);
2049 else
2050#endif
2051 {
2052 prt_dlg.Flags |= PD_RETURNDEFAULT;
2053 if (PrintDlg(&prt_dlg) == 0)
2054 goto init_fail_dlg;
2055 }
2056 }
2057 else if (PrintDlg(&prt_dlg) == 0)
2058 goto init_fail_dlg;
2059 else
2060 {
2061 /*
2062 * keep the previous driver context
2063 */
2064 stored_dm = prt_dlg.hDevMode;
2065 stored_devn = prt_dlg.hDevNames;
2066 stored_nFlags = prt_dlg.Flags;
2067 stored_nCopies = prt_dlg.nCopies;
2068 }
2069
2070 if (prt_dlg.hDC == NULL)
2071 {
2072 EMSG(_("E237: Printer selection failed"));
2073 mch_print_cleanup();
2074 return FALSE;
2075 }
2076
2077 /* Not all printer drivers report the support of color (or grey) in the
2078 * same way. Let's set has_color if there appears to be some way to print
2079 * more than B&W. */
2080 i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS);
2081 psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1
2082 || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1
2083 || i > 2 || i == -1);
2084
2085 /* Ensure all font styles are baseline aligned */
2086 SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT);
2087
2088 /*
2089 * On some windows systems the nCopies parameter is not
2090 * passed back correctly. It must be retrieved from the
2091 * hDevMode struct.
2092 */
2093 mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode);
2094 if (mem != NULL)
2095 {
2096#ifdef WIN3264
2097 if (mem->dmCopies != 1)
2098 stored_nCopies = mem->dmCopies;
2099#endif
2100 if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX))
2101 psettings->duplex = TRUE;
2102 if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR))
2103 psettings->has_color = TRUE;
2104 }
2105 GlobalUnlock(prt_dlg.hDevMode);
2106
2107 devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames);
2108 if (devname != 0)
2109 {
2110 char_u *printer_name = (char_u *)devname + devname->wDeviceOffset;
2111 char_u *port_name = (char_u *)devname +devname->wOutputOffset;
2112 char_u *text = _("to %s on %s");
2113
2114 prt_name = alloc(STRLEN(printer_name) + STRLEN(port_name)
2115 + STRLEN(text));
2116 if (prt_name != NULL)
2117 wsprintf(prt_name, text, printer_name, port_name);
2118 }
2119 GlobalUnlock(prt_dlg.hDevNames);
2120
2121 /*
2122 * Initialise the font according to 'printfont'
2123 */
2124 memset(&fLogFont, 0, sizeof(fLogFont));
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002125 if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 {
2127 EMSG2(_("E613: Unknown printer font: %s"), p_pfn);
2128 mch_print_cleanup();
2129 return FALSE;
2130 }
2131
2132 for (pifBold = 0; pifBold <= 1; pifBold++)
2133 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
2134 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
2135 {
2136 fLogFont.lfWeight = boldface[pifBold];
2137 fLogFont.lfItalic = pifItalic;
2138 fLogFont.lfUnderline = pifUnderline;
2139 prt_font_handles[pifBold][pifItalic][pifUnderline]
2140 = CreateFontIndirect(&fLogFont);
2141 }
2142
2143 SetBkMode(prt_dlg.hDC, OPAQUE);
2144 SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]);
2145
2146 /*
2147 * Fill in the settings struct
2148 */
2149 psettings->chars_per_line = prt_get_cpl();
2150 psettings->lines_per_page = prt_get_lpp();
2151 psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE)
2152 ? prt_dlg.nCopies : 1;
2153 psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE)
2154 ? 1 : prt_dlg.nCopies;
2155
2156 if (psettings->n_collated_copies == 0)
2157 psettings->n_collated_copies = 1;
2158
2159 if (psettings->n_uncollated_copies == 0)
2160 psettings->n_uncollated_copies = 1;
2161
2162 psettings->jobname = jobname;
2163
2164 return TRUE;
2165
2166init_fail_dlg:
2167 {
2168 DWORD err = CommDlgExtendedError();
2169
2170 if (err)
2171 {
2172#ifdef WIN16
2173 char buf[20];
2174
2175 sprintf(buf, "%ld", err);
2176 EMSG2(_("E238: Print error: %s"), buf);
2177#else
2178 char_u *buf;
2179
2180 /* I suspect FormatMessage() doesn't work for values returned by
2181 * CommDlgExtendedError(). What does? */
2182 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2183 FORMAT_MESSAGE_FROM_SYSTEM |
2184 FORMAT_MESSAGE_IGNORE_INSERTS,
2185 NULL, err, 0, (LPTSTR)(&buf), 0, NULL);
2186 EMSG2(_("E238: Print error: %s"),
2187 buf == NULL ? (char_u *)_("Unknown") : buf);
2188 LocalFree((LPVOID)(buf));
2189#endif
2190 }
2191 else
2192 msg_clr_eos(); /* Maybe canceled */
2193
2194 mch_print_cleanup();
2195 return FALSE;
2196 }
2197}
2198
2199
2200 int
2201mch_print_begin(prt_settings_T *psettings)
2202{
2203 int ret;
2204 static DOCINFO di;
2205 char szBuffer[300];
2206
2207 hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"),
2208 prt_dlg.hwndOwner, PrintDlgProc);
2209#ifdef WIN16
2210 Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL);
2211#else
2212 SetAbortProc(prt_dlg.hDC, AbortProc);
2213#endif
2214 wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname));
2215 SetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer);
2216
2217 memset(&di, 0, sizeof(DOCINFO));
2218 di.cbSize = sizeof(DOCINFO);
2219 di.lpszDocName = psettings->jobname;
2220 ret = StartDoc(prt_dlg.hDC, &di);
2221
2222#ifdef FEAT_GUI
2223 /* Give focus back to main window (when using MDI). */
2224 SetFocus(s_hwnd);
2225#endif
2226
2227 return (ret > 0);
2228}
2229
2230 void
2231mch_print_end(prt_settings_T *psettings)
2232{
2233 EndDoc(prt_dlg.hDC);
2234 if (!*bUserAbort)
2235 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
2236}
2237
2238 int
2239mch_print_end_page(void)
2240{
2241 return (EndPage(prt_dlg.hDC) > 0);
2242}
2243
2244 int
2245mch_print_begin_page(char_u *msg)
2246{
2247 if (msg != NULL)
2248 SetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg);
2249 return (StartPage(prt_dlg.hDC) > 0);
2250}
2251
2252 int
2253mch_print_blank_page(void)
2254{
2255 return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
2256}
2257
2258static int prt_pos_x = 0;
2259static int prt_pos_y = 0;
2260
2261 void
2262mch_print_start_line(margin, page_line)
2263 int margin;
2264 int page_line;
2265{
2266 if (margin)
2267 prt_pos_x = -prt_number_width;
2268 else
2269 prt_pos_x = 0;
2270 prt_pos_y = page_line * prt_line_height
2271 + prt_tm.tmAscent + prt_tm.tmExternalLeading;
2272}
2273
2274 int
2275mch_print_text_out(char_u *p, int len)
2276{
2277#ifdef FEAT_PROPORTIONAL_FONTS
2278 SIZE sz;
2279#endif
2280
2281 TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin,
2282 prt_pos_y + prt_top_margin, p, len);
2283#ifndef FEAT_PROPORTIONAL_FONTS
2284 prt_pos_x += len * prt_tm.tmAveCharWidth;
2285 return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth
2286 + prt_tm.tmOverhang > prt_right_margin);
2287#else
2288# ifdef WIN16
2289 GetTextExtentPoint(prt_dlg.hDC, p, len, &sz);
2290# else
2291 GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz);
2292# endif
2293 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
2294 /* This is wrong when printing spaces for a TAB. */
2295 if (p[len] == NUL)
2296 return FALSE;
2297# ifdef WIN16
2298 GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz);
2299# else
2300 GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz);
2301# endif
2302 return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
2303#endif
2304}
2305
2306 void
2307mch_print_set_font(int iBold, int iItalic, int iUnderline)
2308{
2309 SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]);
2310}
2311
2312 void
2313mch_print_set_bg(unsigned long bgcol)
2314{
2315 SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC, swap_me(bgcol)));
2316 /*
2317 * With a white background we can draw characters transparent, which is
2318 * good for italic characters that overlap to the next char cell.
2319 */
2320 if (bgcol == 0xffffffUL)
2321 SetBkMode(prt_dlg.hDC, TRANSPARENT);
2322 else
2323 SetBkMode(prt_dlg.hDC, OPAQUE);
2324}
2325
2326 void
2327mch_print_set_fg(unsigned long fgcol)
2328{
2329 SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC, swap_me(fgcol)));
2330}
2331
2332#endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
2333
2334#if defined(FEAT_SHORTCUT) || defined(PROTO)
2335# include <shlobj.h>
2336
2337/*
2338 * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
2339 * to and return that name in allocated memory.
2340 * Otherwise NULL is returned.
2341 */
2342 char_u *
2343mch_resolve_shortcut(char_u *fname)
2344{
2345 HRESULT hr;
2346 IShellLink *psl = NULL;
2347 IPersistFile *ppf = NULL;
2348 OLECHAR wsz[MAX_PATH];
2349 WIN32_FIND_DATA ffd; // we get those free of charge
2350 TCHAR buf[MAX_PATH]; // could have simply reused 'wsz'...
2351 char_u *rfname = NULL;
2352 int len;
2353
2354 /* Check if the file name ends in ".lnk". Avoid calling
2355 * CoCreateInstance(), it's quite slow. */
2356 if (fname == NULL)
2357 return rfname;
2358 len = STRLEN(fname);
2359 if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
2360 return rfname;
2361
2362 CoInitialize(NULL);
2363
2364 // create a link manager object and request its interface
2365 hr = CoCreateInstance(
2366 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2367 &IID_IShellLink, (void**)&psl);
2368 if (hr != S_OK)
2369 goto shortcut_error;
2370
2371 // Get a pointer to the IPersistFile interface.
2372 hr = psl->lpVtbl->QueryInterface(
2373 psl, &IID_IPersistFile, (void**)&ppf);
2374 if (hr != S_OK)
2375 goto shortcut_error;
2376
2377 // full path string must be in Unicode.
2378 MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
2379
2380 // "load" the name and resove the link
2381 hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
2382 if (hr != S_OK)
2383 goto shortcut_error;
2384#if 0 // This makes Vim wait a long time if the target doesn't exist.
2385 hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
2386 if (hr != S_OK)
2387 goto shortcut_error;
2388#endif
2389
2390 // Get the path to the link target.
2391 ZeroMemory(buf, MAX_PATH);
2392 hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
2393 if (hr == S_OK && buf[0] != NUL)
2394 rfname = vim_strsave(buf);
2395
2396shortcut_error:
2397 // Release all interface pointers (both belong to the same object)
2398 if (ppf != NULL)
2399 ppf->lpVtbl->Release(ppf);
2400 if (psl != NULL)
2401 psl->lpVtbl->Release(psl);
2402
2403 CoUninitialize();
2404 return rfname;
2405}
2406#endif
2407
2408#if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
2409/*
2410 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
2411 */
2412 void
2413win32_set_foreground()
2414{
2415# ifndef FEAT_GUI
2416 GetConsoleHwnd(); /* get value of s_hwnd */
2417# endif
2418 if (s_hwnd != 0)
2419 SetForegroundWindow(s_hwnd);
2420}
2421#endif
2422
2423#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
2424/*
2425 * Client-server code for Vim
2426 *
2427 * Originally written by Paul Moore
2428 */
2429
2430/* In order to handle inter-process messages, we need to have a window. But
2431 * the functions in this module can be called before the main GUI window is
2432 * created (and may also be called in the console version, where there is no
2433 * GUI window at all).
2434 *
2435 * So we create a hidden window, and arrange to destroy it on exit.
2436 */
2437HWND message_window = 0; /* window that's handling messsages */
2438
2439#define VIM_CLASSNAME "VIM_MESSAGES"
2440#define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
2441
2442/* Communication is via WM_COPYDATA messages. The message type is send in
2443 * the dwData parameter. Types are defined here. */
2444#define COPYDATA_KEYS 0
2445#define COPYDATA_REPLY 1
2446#define COPYDATA_EXPR 10
2447#define COPYDATA_RESULT 11
2448#define COPYDATA_ERROR_RESULT 12
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002449#define COPYDATA_ENCODING 20
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450
2451/* This is a structure containing a server HWND and its name. */
2452struct server_id
2453{
2454 HWND hwnd;
2455 char_u *name;
2456};
2457
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002458/* Last received 'encoding' that the client uses. */
2459static char_u *client_enc = NULL;
2460
2461/*
2462 * Tell the other side what encoding we are using.
2463 * Errors are ignored.
2464 */
2465 static void
2466serverSendEnc(HWND target)
2467{
2468 COPYDATASTRUCT data;
2469
2470 data.dwData = COPYDATA_ENCODING;
2471 data.cbData = STRLEN(p_enc) + 1;
2472 data.lpData = p_enc;
2473 (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2474 (LPARAM)(&data));
2475}
2476
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477/*
2478 * Clean up on exit. This destroys the hidden message window.
2479 */
2480 static void
2481#ifdef __BORLANDC__
2482 _RTLENTRYF
2483#endif
2484CleanUpMessaging(void)
2485{
2486 if (message_window != 0)
2487 {
2488 DestroyWindow(message_window);
2489 message_window = 0;
2490 }
2491}
2492
2493static int save_reply(HWND server, char_u *reply, int expr);
2494
2495/*s
2496 * The window procedure for the hidden message window.
2497 * It handles callback messages and notifications from servers.
2498 * In order to process these messages, it is necessary to run a
2499 * message loop. Code which may run before the main message loop
2500 * is started (in the GUI) is careful to pump messages when it needs
2501 * to. Features which require message delivery during normal use will
2502 * not work in the console version - this basically means those
2503 * features which allow Vim to act as a server, rather than a client.
2504 */
2505 static LRESULT CALLBACK
2506Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2507{
2508 if (msg == WM_COPYDATA)
2509 {
2510 /* This is a message from another Vim. The dwData member of the
2511 * COPYDATASTRUCT determines the type of message:
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002512 * COPYDATA_ENCODING:
2513 * The encoding that the client uses. Following messages will
2514 * use this encoding, convert if needed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002515 * COPYDATA_KEYS:
2516 * A key sequence. We are a server, and a client wants these keys
2517 * adding to the input queue.
2518 * COPYDATA_REPLY:
2519 * A reply. We are a client, and a server has sent this message
2520 * in response to a request. (server2client())
2521 * COPYDATA_EXPR:
2522 * An expression. We are a server, and a client wants us to
2523 * evaluate this expression.
2524 * COPYDATA_RESULT:
2525 * A reply. We are a client, and a server has sent this message
2526 * in response to a COPYDATA_EXPR.
2527 * COPYDATA_ERROR_RESULT:
2528 * A reply. We are a client, and a server has sent this message
2529 * in response to a COPYDATA_EXPR that failed to evaluate.
2530 */
2531 COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam;
2532 HWND sender = (HWND)wParam;
2533 COPYDATASTRUCT reply;
2534 char_u *res;
2535 char_u winstr[30];
2536 int retval;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002537 char_u *str;
2538 char_u *tofree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002539
2540 switch (data->dwData)
2541 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002542 case COPYDATA_ENCODING:
2543 /* Remember the encoding that the client uses. */
2544 vim_free(client_enc);
2545 client_enc = enc_canonize((char_u *)data->lpData);
2546 return 1;
2547
Bram Moolenaar071d4272004-06-13 20:20:40 +00002548 case COPYDATA_KEYS:
2549 /* Remember who sent this, for <client> */
2550 clientWindow = sender;
2551
2552 /* Add the received keys to the input buffer. The loop waiting
2553 * for the user to do something should check the input buffer. */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002554 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2555 server_to_input_buf(str);
2556 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557
2558# ifdef FEAT_GUI
2559 /* Wake up the main GUI loop. */
2560 if (s_hwnd != 0)
2561 PostMessage(s_hwnd, WM_NULL, 0, 0);
2562# endif
2563 return 1;
2564
2565 case COPYDATA_EXPR:
2566 /* Remember who sent this, for <client> */
2567 clientWindow = sender;
2568
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002569 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2570 res = eval_client_expr_to_string(str);
2571 vim_free(tofree);
2572
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573 if (res == NULL)
2574 {
2575 res = vim_strsave(_(e_invexprmsg));
2576 reply.dwData = COPYDATA_ERROR_RESULT;
2577 }
2578 else
2579 reply.dwData = COPYDATA_RESULT;
2580 reply.lpData = res;
2581 reply.cbData = STRLEN(res) + 1;
2582
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002583 serverSendEnc(sender);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584 retval = SendMessage(sender, WM_COPYDATA, (WPARAM)message_window,
2585 (LPARAM)(&reply));
2586 vim_free(res);
2587 return retval;
2588
2589 case COPYDATA_REPLY:
2590 case COPYDATA_RESULT:
2591 case COPYDATA_ERROR_RESULT:
2592 if (data->lpData != NULL)
2593 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002594 str = serverConvert(client_enc, (char_u *)data->lpData,
2595 &tofree);
2596 if (tofree == NULL)
2597 str = vim_strsave(str);
2598 if (save_reply(sender, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002599 (data->dwData == COPYDATA_REPLY ? 0 :
2600 (data->dwData == COPYDATA_RESULT ? 1 :
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002601 2))) == FAIL)
2602 vim_free(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002603#ifdef FEAT_AUTOCMD
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002604 else if (data->dwData == COPYDATA_REPLY)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605 {
2606 sprintf((char *)winstr, "0x%x", (unsigned)sender);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002607 apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608 TRUE, curbuf);
2609 }
2610#endif
2611 }
2612 return 1;
2613 }
2614
2615 return 0;
2616 }
2617
2618 else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2619 {
2620 /* When the message window is activated (brought to the foreground),
2621 * this actually applies to the text window. */
2622#ifndef FEAT_GUI
2623 GetConsoleHwnd(); /* get value of s_hwnd */
2624#endif
2625 if (s_hwnd != 0)
2626 {
2627 SetForegroundWindow(s_hwnd);
2628 return 0;
2629 }
2630 }
2631
2632 return DefWindowProc(hwnd, msg, wParam, lParam);
2633}
2634
2635/*
2636 * Initialise the message handling process. This involves creating a window
2637 * to handle messages - the window will not be visible.
2638 */
2639 void
2640serverInitMessaging(void)
2641{
2642 WNDCLASS wndclass;
2643 HINSTANCE s_hinst;
2644
2645 /* Clean up on exit */
2646 atexit(CleanUpMessaging);
2647
2648 /* Register a window class - we only really care
2649 * about the window procedure
2650 */
2651 s_hinst = (HINSTANCE)GetModuleHandle(0);
2652 wndclass.style = 0;
2653 wndclass.lpfnWndProc = Messaging_WndProc;
2654 wndclass.cbClsExtra = 0;
2655 wndclass.cbWndExtra = 0;
2656 wndclass.hInstance = s_hinst;
2657 wndclass.hIcon = NULL;
2658 wndclass.hCursor = NULL;
2659 wndclass.hbrBackground = NULL;
2660 wndclass.lpszMenuName = NULL;
2661 wndclass.lpszClassName = VIM_CLASSNAME;
2662 RegisterClass(&wndclass);
2663
2664 /* Create the message window. It will be hidden, so the details don't
2665 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2666 * focus from gvim. */
2667 message_window = CreateWindow(VIM_CLASSNAME, "",
2668 WS_POPUPWINDOW | WS_CAPTION,
2669 CW_USEDEFAULT, CW_USEDEFAULT,
2670 100, 100, NULL, NULL,
2671 s_hinst, NULL);
2672}
2673
2674/*
2675 * Get the title of the window "hwnd", which is the Vim server name, in
2676 * "name[namelen]" and return the length.
2677 * Returns zero if window "hwnd" is not a Vim server.
2678 */
2679 static int
2680getVimServerName(HWND hwnd, char *name, int namelen)
2681{
2682 int len;
2683 char buffer[VIM_CLASSNAME_LEN + 1];
2684
2685 /* Ignore windows which aren't Vim message windows */
2686 len = GetClassName(hwnd, buffer, sizeof(buffer));
2687 if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2688 return 0;
2689
2690 /* Get the title of the window */
2691 return GetWindowText(hwnd, name, namelen);
2692}
2693
2694 static BOOL CALLBACK
2695enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2696{
2697 struct server_id *id = (struct server_id *)lparam;
2698 char server[MAX_PATH];
2699
2700 /* Get the title of the window */
2701 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2702 return TRUE;
2703
2704 /* If this is the server we're looking for, return its HWND */
2705 if (STRICMP(server, id->name) == 0)
2706 {
2707 id->hwnd = hwnd;
2708 return FALSE;
2709 }
2710
2711 /* Otherwise, keep looking */
2712 return TRUE;
2713}
2714
2715 static BOOL CALLBACK
2716enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2717{
2718 garray_T *ga = (garray_T *)lparam;
2719 char server[MAX_PATH];
2720
2721 /* Get the title of the window */
2722 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2723 return TRUE;
2724
2725 /* Add the name to the list */
2726 ga_concat(ga, server);
2727 ga_concat(ga, "\n");
2728 return TRUE;
2729}
2730
2731 static HWND
2732findServer(char_u *name)
2733{
2734 struct server_id id;
2735
2736 id.name = name;
2737 id.hwnd = 0;
2738
2739 EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2740
2741 return id.hwnd;
2742}
2743
2744 void
2745serverSetName(char_u *name)
2746{
2747 char_u *ok_name;
2748 HWND hwnd = 0;
2749 int i = 0;
2750 char_u *p;
2751
2752 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
2753 ok_name = alloc(STRLEN(name) + 10);
2754
2755 STRCPY(ok_name, name);
2756 p = ok_name + STRLEN(name);
2757
2758 for (;;)
2759 {
2760 /* This is inefficient - we're doing an EnumWindows loop for each
2761 * possible name. It would be better to grab all names in one go,
2762 * and scan the list each time...
2763 */
2764 hwnd = findServer(ok_name);
2765 if (hwnd == 0)
2766 break;
2767
2768 ++i;
2769 if (i >= 1000)
2770 break;
2771
2772 sprintf((char *)p, "%d", i);
2773 }
2774
2775 if (hwnd != 0)
2776 vim_free(ok_name);
2777 else
2778 {
2779 /* Remember the name */
2780 serverName = ok_name;
2781#ifdef FEAT_TITLE
2782 need_maketitle = TRUE; /* update Vim window title later */
2783#endif
2784
2785 /* Update the message window title */
2786 SetWindowText(message_window, ok_name);
2787
2788#ifdef FEAT_EVAL
2789 /* Set the servername variable */
2790 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2791#endif
2792 }
2793}
2794
2795 char_u *
2796serverGetVimNames(void)
2797{
2798 garray_T ga;
2799
2800 ga_init2(&ga, 1, 100);
2801
2802 EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
Bram Moolenaar269ec652004-07-29 08:43:53 +00002803 ga_append(&ga, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002804
2805 return ga.ga_data;
2806}
2807
2808 int
2809serverSendReply(name, reply)
2810 char_u *name; /* Where to send. */
2811 char_u *reply; /* What to send. */
2812{
2813 HWND target;
2814 COPYDATASTRUCT data;
2815 int n = 0;
2816
2817 /* The "name" argument is a magic cookie obtained from expand("<client>").
2818 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2819 * value of the client's message window HWND.
2820 */
2821 sscanf((char *)name, "%x", &n);
2822 if (n == 0)
2823 return -1;
2824
2825 target = (HWND)n;
2826 if (!IsWindow(target))
2827 return -1;
2828
2829 data.dwData = COPYDATA_REPLY;
2830 data.cbData = STRLEN(reply) + 1;
2831 data.lpData = reply;
2832
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002833 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2835 (LPARAM)(&data)))
2836 return 0;
2837
2838 return -1;
2839}
2840
2841 int
2842serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2843 char_u *name; /* Where to send. */
2844 char_u *cmd; /* What to send. */
2845 char_u **result; /* Result of eval'ed expression */
2846 void *ptarget; /* HWND of server */
2847 int asExpr; /* Expression or keys? */
2848 int silent; /* don't complain about no server */
2849{
2850 HWND target = findServer(name);
2851 COPYDATASTRUCT data;
2852 char_u *retval = NULL;
2853 int retcode = 0;
2854
2855 if (target == 0)
2856 {
2857 if (!silent)
2858 EMSG2(_(e_noserver), name);
2859 return -1;
2860 }
2861
2862 if (ptarget)
2863 *(HWND *)ptarget = target;
2864
2865 data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
2866 data.cbData = STRLEN(cmd) + 1;
2867 data.lpData = cmd;
2868
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002869 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2871 (LPARAM)(&data)) == 0)
2872 return -1;
2873
2874 if (asExpr)
2875 retval = serverGetReply(target, &retcode, TRUE, TRUE);
2876
2877 if (result == NULL)
2878 vim_free(retval);
2879 else
2880 *result = retval; /* Caller assumes responsibility for freeing */
2881
2882 return retcode;
2883}
2884
2885/*
2886 * Bring the server to the foreground.
2887 */
2888 void
2889serverForeground(name)
2890 char_u *name;
2891{
2892 HWND target = findServer(name);
2893
2894 if (target != 0)
2895 SetForegroundWindow(target);
2896}
2897
2898/* Replies from server need to be stored until the client picks them up via
2899 * remote_read(). So we maintain a list of server-id/reply pairs.
2900 * Note that there could be multiple replies from one server pending if the
2901 * client is slow picking them up.
2902 * We just store the replies in a simple list. When we remove an entry, we
2903 * move list entries down to fill the gap.
2904 * The server ID is simply the HWND.
2905 */
2906typedef struct
2907{
2908 HWND server; /* server window */
2909 char_u *reply; /* reply string */
2910 int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */
2911}
2912reply_T;
2913
2914static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
2915
2916#define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
2917#define REPLY_COUNT (reply_list.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918
2919/* Flag which is used to wait for a reply */
2920static int reply_received = 0;
2921
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002922/*
2923 * Store a reply. "reply" must be allocated memory (or NULL).
2924 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002925 static int
2926save_reply(HWND server, char_u *reply, int expr)
2927{
2928 reply_T *rep;
2929
2930 if (ga_grow(&reply_list, 1) == FAIL)
2931 return FAIL;
2932
2933 rep = REPLY_ITEM(REPLY_COUNT);
2934 rep->server = server;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002935 rep->reply = reply;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002936 rep->expr_result = expr;
2937 if (rep->reply == NULL)
2938 return FAIL;
2939
2940 ++REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002941 reply_received = 1;
2942 return OK;
2943}
2944
2945/*
2946 * Get a reply from server "server".
2947 * When "expr_res" is non NULL, get the result of an expression, otherwise a
2948 * server2client() message.
2949 * When non NULL, point to return code. 0 => OK, -1 => ERROR
2950 * If "remove" is TRUE, consume the message, the caller must free it then.
2951 * if "wait" is TRUE block until a message arrives (or the server exits).
2952 */
2953 char_u *
2954serverGetReply(HWND server, int *expr_res, int remove, int wait)
2955{
2956 int i;
2957 char_u *reply;
2958 reply_T *rep;
2959
2960 /* When waiting, loop until the message waiting for is received. */
2961 for (;;)
2962 {
2963 /* Reset this here, in case a message arrives while we are going
2964 * through the already received messages. */
2965 reply_received = 0;
2966
2967 for (i = 0; i < REPLY_COUNT; ++i)
2968 {
2969 rep = REPLY_ITEM(i);
2970 if (rep->server == server
2971 && ((rep->expr_result != 0) == (expr_res != NULL)))
2972 {
2973 /* Save the values we've found for later */
2974 reply = rep->reply;
2975 if (expr_res != NULL)
2976 *expr_res = rep->expr_result == 1 ? 0 : -1;
2977
2978 if (remove)
2979 {
2980 /* Move the rest of the list down to fill the gap */
2981 mch_memmove(rep, rep + 1,
2982 (REPLY_COUNT - i - 1) * sizeof(reply_T));
2983 --REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984 }
2985
2986 /* Return the reply to the caller, who takes on responsibility
2987 * for freeing it if "remove" is TRUE. */
2988 return reply;
2989 }
2990 }
2991
2992 /* If we got here, we didn't find a reply. Return immediately if the
2993 * "wait" parameter isn't set. */
2994 if (!wait)
2995 break;
2996
2997 /* We need to wait for a reply. Enter a message loop until the
2998 * "reply_received" flag gets set. */
2999
3000 /* Loop until we receive a reply */
3001 while (reply_received == 0)
3002 {
3003 /* Wait for a SendMessage() call to us. This could be the reply
3004 * we are waiting for. Use a timeout of a second, to catch the
3005 * situation that the server died unexpectedly. */
3006 MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
3007
3008 /* If the server has died, give up */
3009 if (!IsWindow(server))
3010 return NULL;
3011
3012 serverProcessPendingMessages();
3013 }
3014 }
3015
3016 return NULL;
3017}
3018
3019/*
3020 * Process any messages in the Windows message queue.
3021 */
3022 void
3023serverProcessPendingMessages(void)
3024{
3025 MSG msg;
3026
3027 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
3028 {
3029 TranslateMessage(&msg);
3030 DispatchMessage(&msg);
3031 }
3032}
3033
3034#endif /* FEAT_CLIENTSERVER */
3035
3036#if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
3037 || defined(PROTO)
3038
3039struct charset_pair
3040{
3041 char *name;
3042 BYTE charset;
3043};
3044
3045static struct charset_pair
3046charset_pairs[] =
3047{
3048 {"ANSI", ANSI_CHARSET},
3049 {"CHINESEBIG5", CHINESEBIG5_CHARSET},
3050 {"DEFAULT", DEFAULT_CHARSET},
3051 {"HANGEUL", HANGEUL_CHARSET},
3052 {"OEM", OEM_CHARSET},
3053 {"SHIFTJIS", SHIFTJIS_CHARSET},
3054 {"SYMBOL", SYMBOL_CHARSET},
3055#ifdef WIN3264
3056 {"ARABIC", ARABIC_CHARSET},
3057 {"BALTIC", BALTIC_CHARSET},
3058 {"EASTEUROPE", EASTEUROPE_CHARSET},
3059 {"GB2312", GB2312_CHARSET},
3060 {"GREEK", GREEK_CHARSET},
3061 {"HEBREW", HEBREW_CHARSET},
3062 {"JOHAB", JOHAB_CHARSET},
3063 {"MAC", MAC_CHARSET},
3064 {"RUSSIAN", RUSSIAN_CHARSET},
3065 {"THAI", THAI_CHARSET},
3066 {"TURKISH", TURKISH_CHARSET},
3067# if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
3068 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
3069 {"VIETNAMESE", VIETNAMESE_CHARSET},
3070# endif
3071#endif
3072 {NULL, 0}
3073};
3074
3075/*
3076 * Convert a charset ID to a name.
3077 * Return NULL when not recognized.
3078 */
3079 char *
3080charset_id2name(int id)
3081{
3082 struct charset_pair *cp;
3083
3084 for (cp = charset_pairs; cp->name != NULL; ++cp)
3085 if ((BYTE)id == cp->charset)
3086 break;
3087 return cp->name;
3088}
3089
3090static const LOGFONT s_lfDefault =
3091{
3092 -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
3093 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
3094 PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
3095 "Fixedsys" /* see _ReadVimIni */
3096};
3097
3098/* Initialise the "current height" to -12 (same as s_lfDefault) just
3099 * in case the user specifies a font in "guifont" with no size before a font
3100 * with an explicit size has been set. This defaults the size to this value
3101 * (-12 equates to roughly 9pt).
3102 */
3103int current_font_height = -12; /* also used in gui_w48.c */
3104
3105/* Convert a string representing a point size into pixels. The string should
3106 * be a positive decimal number, with an optional decimal point (eg, "12", or
3107 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
3108 * character is stored in *end. The flag "vertical" says whether this
3109 * calculation is for a vertical (height) size or a horizontal (width) one.
3110 */
3111 static int
3112points_to_pixels(char_u *str, char_u **end, int vertical, int pprinter_dc)
3113{
3114 int pixels;
3115 int points = 0;
3116 int divisor = 0;
3117 HWND hwnd = (HWND)0;
3118 HDC hdc;
3119 HDC printer_dc = (HDC)pprinter_dc;
3120
3121 while (*str != NUL)
3122 {
3123 if (*str == '.' && divisor == 0)
3124 {
3125 /* Start keeping a divisor, for later */
3126 divisor = 1;
3127 }
3128 else
3129 {
3130 if (!VIM_ISDIGIT(*str))
3131 break;
3132
3133 points *= 10;
3134 points += *str - '0';
3135 divisor *= 10;
3136 }
3137 ++str;
3138 }
3139
3140 if (divisor == 0)
3141 divisor = 1;
3142
3143 if (printer_dc == NULL)
3144 {
3145 hwnd = GetDesktopWindow();
3146 hdc = GetWindowDC(hwnd);
3147 }
3148 else
3149 hdc = printer_dc;
3150
3151 pixels = MulDiv(points,
3152 GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
3153 72 * divisor);
3154
3155 if (printer_dc == NULL)
3156 ReleaseDC(hwnd, hdc);
3157
3158 *end = str;
3159 return pixels;
3160}
3161
3162 static int CALLBACK
3163font_enumproc(
3164 ENUMLOGFONT *elf,
3165 NEWTEXTMETRIC *ntm,
3166 int type,
3167 LPARAM lparam)
3168{
3169 /* Return value:
3170 * 0 = terminate now (monospace & ANSI)
3171 * 1 = continue, still no luck...
3172 * 2 = continue, but we have an acceptable LOGFONT
3173 * (monospace, not ANSI)
3174 * We use these values, as EnumFontFamilies returns 1 if the
3175 * callback function is never called. So, we check the return as
3176 * 0 = perfect, 2 = OK, 1 = no good...
3177 * It's not pretty, but it works!
3178 */
3179
3180 LOGFONT *lf = (LOGFONT *)(lparam);
3181
3182#ifndef FEAT_PROPORTIONAL_FONTS
3183 /* Ignore non-monospace fonts without further ado */
3184 if ((ntm->tmPitchAndFamily & 1) != 0)
3185 return 1;
3186#endif
3187
3188 /* Remember this LOGFONT as a "possible" */
3189 *lf = elf->elfLogFont;
3190
3191 /* Terminate the scan as soon as we find an ANSI font */
3192 if (lf->lfCharSet == ANSI_CHARSET
3193 || lf->lfCharSet == OEM_CHARSET
3194 || lf->lfCharSet == DEFAULT_CHARSET)
3195 return 0;
3196
3197 /* Continue the scan - we have a non-ANSI font */
3198 return 2;
3199}
3200
3201 static int
3202init_logfont(LOGFONT *lf)
3203{
3204 int n;
3205 HWND hwnd = GetDesktopWindow();
3206 HDC hdc = GetWindowDC(hwnd);
3207
3208 n = EnumFontFamilies(hdc,
3209 (LPCSTR)lf->lfFaceName,
3210 (FONTENUMPROC)font_enumproc,
3211 (LPARAM)lf);
3212
3213 ReleaseDC(hwnd, hdc);
3214
3215 /* If we couldn't find a useable font, return failure */
3216 if (n == 1)
3217 return FAIL;
3218
3219 /* Tidy up the rest of the LOGFONT structure. We set to a basic
3220 * font - get_logfont() sets bold, italic, etc based on the user's
3221 * input.
3222 */
3223 lf->lfHeight = current_font_height;
3224 lf->lfWidth = 0;
3225 lf->lfItalic = FALSE;
3226 lf->lfUnderline = FALSE;
3227 lf->lfStrikeOut = FALSE;
3228 lf->lfWeight = FW_NORMAL;
3229
3230 /* Return success */
3231 return OK;
3232}
3233
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003234/*
3235 * Get font info from "name" into logfont "lf".
3236 * Return OK for a valid name, FAIL otherwise.
3237 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003238 int
3239get_logfont(
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003240 LOGFONT *lf,
3241 char_u *name,
3242 HDC printer_dc,
3243 int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003244{
3245 char_u *p;
3246 int i;
3247 static LOGFONT *lastlf = NULL;
3248
3249 *lf = s_lfDefault;
3250 if (name == NULL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003251 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003252
3253 if (STRCMP(name, "*") == 0)
3254 {
3255#if defined(FEAT_GUI_W32)
3256 CHOOSEFONT cf;
3257 /* if name is "*", bring up std font dialog: */
3258 memset(&cf, 0, sizeof(cf));
3259 cf.lStructSize = sizeof(cf);
3260 cf.hwndOwner = s_hwnd;
3261 cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
3262 if (lastlf != NULL)
3263 *lf = *lastlf;
3264 cf.lpLogFont = lf;
3265 cf.nFontType = 0 ; //REGULAR_FONTTYPE;
3266 if (ChooseFont(&cf))
3267 goto theend;
3268#else
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003269 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003270#endif
3271 }
3272
3273 /*
3274 * Split name up, it could be <name>:h<height>:w<width> etc.
3275 */
3276 for (p = name; *p && *p != ':'; p++)
3277 {
3278 if (p - name + 1 > LF_FACESIZE)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003279 return FAIL; /* Name too long */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280 lf->lfFaceName[p - name] = *p;
3281 }
3282 if (p != name)
3283 lf->lfFaceName[p - name] = NUL;
3284
3285 /* First set defaults */
3286 lf->lfHeight = -12;
3287 lf->lfWidth = 0;
3288 lf->lfWeight = FW_NORMAL;
3289 lf->lfItalic = FALSE;
3290 lf->lfUnderline = FALSE;
3291 lf->lfStrikeOut = FALSE;
3292
3293 /*
3294 * If the font can't be found, try replacing '_' by ' '.
3295 */
3296 if (init_logfont(lf) == FAIL)
3297 {
3298 int did_replace = FALSE;
3299
3300 for (i = 0; lf->lfFaceName[i]; ++i)
3301 if (lf->lfFaceName[i] == '_')
3302 {
3303 lf->lfFaceName[i] = ' ';
3304 did_replace = TRUE;
3305 }
3306 if (!did_replace || init_logfont(lf) == FAIL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003307 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003308 }
3309
3310 while (*p == ':')
3311 p++;
3312
3313 /* Set the values found after ':' */
3314 while (*p)
3315 {
3316 switch (*p++)
3317 {
3318 case 'h':
3319 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (int)printer_dc);
3320 break;
3321 case 'w':
3322 lf->lfWidth = points_to_pixels(p, &p, FALSE, (int)printer_dc);
3323 break;
3324 case 'b':
3325#ifndef MSWIN16_FASTTEXT
3326 lf->lfWeight = FW_BOLD;
3327#endif
3328 break;
3329 case 'i':
3330#ifndef MSWIN16_FASTTEXT
3331 lf->lfItalic = TRUE;
3332#endif
3333 break;
3334 case 'u':
3335 lf->lfUnderline = TRUE;
3336 break;
3337 case 's':
3338 lf->lfStrikeOut = TRUE;
3339 break;
3340 case 'c':
3341 {
3342 struct charset_pair *cp;
3343
3344 for (cp = charset_pairs; cp->name != NULL; ++cp)
3345 if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
3346 {
3347 lf->lfCharSet = cp->charset;
3348 p += strlen(cp->name);
3349 break;
3350 }
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003351 if (cp->name == NULL && verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352 {
3353 sprintf((char *)IObuff, _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
3354 EMSG(IObuff);
3355 break;
3356 }
3357 break;
3358 }
3359 default:
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003360 if (verbose)
3361 {
3362 sprintf((char *)IObuff,
3363 _("E245: Illegal char '%c' in font name \"%s\""),
3364 p[-1], name);
3365 EMSG(IObuff);
3366 }
3367 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003368 }
3369 while (*p == ':')
3370 p++;
3371 }
3372
3373#if defined(FEAT_GUI_W32)
3374theend:
3375#endif
3376 /* ron: init lastlf */
3377 if (printer_dc == NULL)
3378 {
3379 vim_free(lastlf);
3380 lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
3381 if (lastlf != NULL)
3382 mch_memmove(lastlf, lf, sizeof(LOGFONT));
3383 }
3384
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003385 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003386}
3387
3388#endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */