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