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