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