blob: c833113db50b1201e397bf92c9d038f7d4a710ff [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 {
Bram Moolenaar44ecf652005-03-07 23:09:59 +00001414 ++*outlen; /* Include the 0 after the string */
Bram Moolenaar05159a02005-02-26 23:04:13 +00001415 *out = ucs2_to_enc((short_u *)widestr, outlen);
1416 vim_free(widestr);
1417 }
1418}
1419#endif
1420
Bram Moolenaar071d4272004-06-13 20:20:40 +00001421/*
1422 * Send the current selection to the clipboard.
1423 */
1424 void
1425clip_mch_set_selection(VimClipboard *cbd)
1426{
1427 char_u *str = NULL;
1428 VimClipType_t metadata;
1429 long_u txtlen;
1430 HGLOBAL hMemRaw = NULL;
1431 HGLOBAL hMem = NULL;
1432 HGLOBAL hMemVim = NULL;
1433# if defined(FEAT_MBYTE) && defined(WIN3264)
1434 HGLOBAL hMemW = NULL;
1435# endif
1436
1437 /* If the '*' register isn't already filled in, fill it in now */
1438 cbd->owned = TRUE;
1439 clip_get_selection(cbd);
1440 cbd->owned = FALSE;
1441
1442 /* Get the text to be put on the clipboard, with CR-LF. */
1443 metadata.type = clip_convert_selection(&str, &txtlen, cbd);
1444 if (metadata.type < 0)
1445 return;
1446 metadata.txtlen = (int)txtlen;
1447 metadata.ucslen = 0;
1448 metadata.rawlen = 0;
1449
1450#ifdef FEAT_MBYTE
1451 /* Always set the raw bytes: 'encoding', NUL and the text. This is used
1452 * when copy/paste from/to Vim with the same 'encoding', so that illegal
1453 * bytes can also be copied and no conversion is needed. */
1454 {
1455 LPSTR lpszMemRaw;
1456
1457 metadata.rawlen = txtlen + STRLEN(p_enc) + 1;
1458 hMemRaw = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1459 metadata.rawlen + 1);
1460 lpszMemRaw = (LPSTR)GlobalLock(hMemRaw);
1461 if (lpszMemRaw != NULL)
1462 {
1463 STRCPY(lpszMemRaw, p_enc);
1464 memcpy(lpszMemRaw + STRLEN(p_enc) + 1, str, txtlen + 1);
1465 GlobalUnlock(hMemRaw);
1466 }
1467 else
1468 metadata.rawlen = 0;
1469 }
1470#endif
1471
1472# if defined(FEAT_MBYTE) && defined(WIN3264)
1473 {
1474 WCHAR *out;
1475 int len = metadata.txtlen;
1476
1477 /* Convert the text to UCS-2. This is put on the clipboard as
1478 * CF_UNICODETEXT. */
1479 out = (WCHAR *)enc_to_ucs2(str, &len);
1480 if (out != NULL)
1481 {
1482 WCHAR *lpszMemW;
1483
1484 /* Convert the text for CF_TEXT to Active codepage. Otherwise it's
1485 * p_enc, which has no relation to the Active codepage. */
1486 metadata.txtlen = WideCharToMultiByte(GetACP(), 0, out, len,
1487 NULL, 0, 0, 0);
1488 vim_free(str);
1489 str = (char_u *)alloc((unsigned)(metadata.txtlen == 0 ? 1
1490 : metadata.txtlen));
1491 if (str == NULL)
1492 {
1493 vim_free(out);
1494 return; /* out of memory */
1495 }
1496 WideCharToMultiByte(GetACP(), 0, out, len,
1497 str, metadata.txtlen, 0, 0);
1498
1499 /* Allocate memory for the UCS-2 text, add one NUL word to
1500 * terminate the string. */
1501 hMemW = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1502 (len + 1) * sizeof(WCHAR));
1503 lpszMemW = (WCHAR *)GlobalLock(hMemW);
1504 if (lpszMemW != NULL)
1505 {
1506 memcpy(lpszMemW, out, len * sizeof(WCHAR));
1507 lpszMemW[len] = NUL;
1508 GlobalUnlock(hMemW);
1509 }
1510 vim_free(out);
1511 metadata.ucslen = len;
1512 }
1513 }
1514# endif
1515
1516 /* Allocate memory for the text, add one NUL byte to terminate the string.
1517 */
1518 hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, metadata.txtlen + 1);
1519 {
1520 LPSTR lpszMem = (LPSTR)GlobalLock(hMem);
1521
1522 if (lpszMem)
1523 {
1524 STRNCPY(lpszMem, str, metadata.txtlen);
1525 lpszMem[metadata.txtlen] = NUL;
1526 GlobalUnlock(hMem);
1527 }
1528 }
1529
1530 /* Set up metadata: */
1531 {
1532 VimClipType_t *lpszMemVim = NULL;
1533
1534 hMemVim = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,
1535 sizeof(VimClipType_t));
1536 lpszMemVim = (VimClipType_t *)GlobalLock(hMemVim);
1537 memcpy(lpszMemVim, &metadata, sizeof(metadata));
1538 GlobalUnlock(hMemVim);
1539 }
1540
1541 /*
1542 * Open the clipboard, clear it and put our text on it.
1543 * Always set our Vim format. Put Unicode and plain text on it.
1544 *
1545 * Don't pass GetActiveWindow() as an argument to OpenClipboard()
1546 * because then we can't paste back into the same window for some
1547 * reason - webb.
1548 */
1549 if (OpenClipboard(NULL))
1550 {
1551 if (EmptyClipboard())
1552 {
1553 SetClipboardData(cbd->format, hMemVim);
1554 hMemVim = 0;
1555# if defined(FEAT_MBYTE) && defined(WIN3264)
1556 if (hMemW != NULL)
1557 {
1558 if (SetClipboardData(CF_UNICODETEXT, hMemW) != NULL)
1559 hMemW = NULL;
1560 }
1561# endif
1562 /* Always use CF_TEXT. On Win98 Notepad won't obtain the
1563 * CF_UNICODETEXT text, only CF_TEXT. */
1564 SetClipboardData(CF_TEXT, hMem);
1565 hMem = 0;
1566 }
1567 CloseClipboard();
1568 }
1569
1570 vim_free(str);
1571 /* Free any allocations we didn't give to the clipboard: */
1572 if (hMemRaw)
1573 GlobalFree(hMemRaw);
1574 if (hMem)
1575 GlobalFree(hMem);
1576# if defined(FEAT_MBYTE) && defined(WIN3264)
1577 if (hMemW)
1578 GlobalFree(hMemW);
1579# endif
1580 if (hMemVim)
1581 GlobalFree(hMemVim);
1582}
1583
1584#endif /* FEAT_CLIPBOARD */
1585
1586
1587/*
1588 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
1589 */
1590 void
1591DumpPutS(
1592 const char *psz)
1593{
1594# ifdef MCH_WRITE_DUMP
1595 if (fdDump)
1596 {
1597 fputs(psz, fdDump);
1598 if (psz[strlen(psz) - 1] != '\n')
1599 fputc('\n', fdDump);
1600 fflush(fdDump);
1601 }
1602# endif
1603}
1604
1605#ifdef _DEBUG
1606
1607void __cdecl
1608Trace(
1609 char *pszFormat,
1610 ...)
1611{
1612 CHAR szBuff[2048];
1613 va_list args;
1614
1615 va_start(args, pszFormat);
1616 vsprintf(szBuff, pszFormat, args);
1617 va_end(args);
1618
1619 OutputDebugString(szBuff);
1620}
1621
1622#endif //_DEBUG
1623
Bram Moolenaar843ee412004-06-30 16:16:41 +00001624#if !defined(FEAT_GUI) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625# if defined(FEAT_TITLE) && defined(WIN3264)
1626extern HWND g_hWnd; /* This is in os_win32.c. */
1627# endif
1628
1629/*
1630 * Showing the printer dialog is tricky since we have no GUI
1631 * window to parent it. The following routines are needed to
1632 * get the window parenting and Z-order to work properly.
1633 */
1634 static void
1635GetConsoleHwnd(void)
1636{
1637# define MY_BUFSIZE 1024 // Buffer size for console window titles.
1638
1639 char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
1640 char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
1641
1642 /* Skip if it's already set. */
1643 if (s_hwnd != 0)
1644 return;
1645
1646# if defined(FEAT_TITLE) && defined(WIN3264)
1647 /* Window handle may have been found by init code (Windows NT only) */
1648 if (g_hWnd != 0)
1649 {
1650 s_hwnd = g_hWnd;
1651 return;
1652 }
1653# endif
1654
1655 GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
1656
1657 wsprintf(pszNewWindowTitle, "%s/%d/%d",
1658 pszOldWindowTitle,
1659 GetTickCount(),
1660 GetCurrentProcessId());
1661 SetConsoleTitle(pszNewWindowTitle);
1662 Sleep(40);
1663 s_hwnd = FindWindow(NULL, pszNewWindowTitle);
1664
1665 SetConsoleTitle(pszOldWindowTitle);
1666}
Bram Moolenaar843ee412004-06-30 16:16:41 +00001667
1668/*
1669 * Console implementation of ":winpos".
1670 */
1671 int
1672mch_get_winpos(int *x, int *y)
1673{
1674 RECT rect;
1675
1676 GetConsoleHwnd();
1677 GetWindowRect(s_hwnd, &rect);
1678 *x = rect.left;
1679 *y = rect.top;
1680 return OK;
1681}
1682
1683/*
1684 * Console implementation of ":winpos x y".
1685 */
1686 void
1687mch_set_winpos(int x, int y)
1688{
1689 GetConsoleHwnd();
1690 SetWindowPos(s_hwnd, NULL, x, y, 0, 0,
1691 SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1692}
Bram Moolenaar071d4272004-06-13 20:20:40 +00001693#endif
1694
1695#if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1696
1697# ifdef WIN16
1698# define TEXT(a) a
1699# endif
1700/*=================================================================
1701 * Win32 printer stuff
1702 */
1703
1704static HFONT prt_font_handles[2][2][2];
1705static PRINTDLG prt_dlg;
1706static const int boldface[2] = {FW_REGULAR, FW_BOLD};
1707static TEXTMETRIC prt_tm;
1708static int prt_line_height;
1709static int prt_number_width;
1710static int prt_left_margin;
1711static int prt_right_margin;
1712static int prt_top_margin;
1713static char_u szAppName[] = TEXT("VIM");
1714static HWND hDlgPrint;
1715static int *bUserAbort = NULL;
1716static char_u *prt_name = NULL;
1717
1718/* Defines which are also in vim.rc. */
1719#define IDC_BOX1 400
1720#define IDC_PRINTTEXT1 401
1721#define IDC_PRINTTEXT2 402
1722#define IDC_PROGRESS 403
1723
1724/*
1725 * Convert BGR to RGB for Windows GDI calls
1726 */
1727 static COLORREF
1728swap_me(COLORREF colorref)
1729{
1730 int temp;
1731 char *ptr = (char *)&colorref;
1732
1733 temp = *(ptr);
1734 *(ptr ) = *(ptr + 2);
1735 *(ptr + 2) = temp;
1736 return colorref;
1737}
1738
1739 static BOOL CALLBACK
1740PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
1741{
1742#ifdef FEAT_GETTEXT
1743 NONCLIENTMETRICS nm;
1744 static HFONT hfont;
1745#endif
1746
1747 switch (message)
1748 {
1749 case WM_INITDIALOG:
1750#ifdef FEAT_GETTEXT
1751 nm.cbSize = sizeof(NONCLIENTMETRICS);
1752 if (SystemParametersInfo(
1753 SPI_GETNONCLIENTMETRICS,
1754 sizeof(NONCLIENTMETRICS),
1755 &nm,
1756 0))
1757 {
1758 char buff[MAX_PATH];
1759 int i;
1760
1761 /* Translate the dialog texts */
1762 hfont = CreateFontIndirect(&nm.lfMessageFont);
1763 for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++)
1764 {
1765 SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1);
1766 if (GetDlgItemText(hDlg,i, buff, sizeof(buff)))
1767 SetDlgItemText(hDlg,i, _(buff));
1768 }
1769 SendDlgItemMessage(hDlg, IDCANCEL,
1770 WM_SETFONT, (WPARAM)hfont, 1);
1771 if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff)))
1772 SetDlgItemText(hDlg,IDCANCEL, _(buff));
1773 }
1774#endif
1775 SetWindowText(hDlg, szAppName);
1776 if (prt_name != NULL)
1777 {
1778 SetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name);
1779 vim_free(prt_name);
1780 prt_name = NULL;
1781 }
1782 EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED);
1783#ifndef FEAT_GUI
1784 BringWindowToTop(s_hwnd);
1785#endif
1786 return TRUE;
1787
1788 case WM_COMMAND:
1789 *bUserAbort = TRUE;
1790 EnableWindow(GetParent(hDlg), TRUE);
1791 DestroyWindow(hDlg);
1792 hDlgPrint = NULL;
1793#ifdef FEAT_GETTEXT
1794 DeleteObject(hfont);
1795#endif
1796 return TRUE;
1797 }
1798 return FALSE;
1799}
1800
1801 static BOOL CALLBACK
1802AbortProc(HDC hdcPrn, int iCode)
1803{
1804 MSG msg;
1805
1806 while (!*bUserAbort && PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1807 {
1808 if (!hDlgPrint || !IsDialogMessage(hDlgPrint, &msg))
1809 {
1810 TranslateMessage(&msg);
1811 DispatchMessage(&msg);
1812 }
1813 }
1814 return !*bUserAbort;
1815}
1816
1817#ifndef FEAT_GUI
1818
1819 static UINT CALLBACK
1820PrintHookProc(
1821 HWND hDlg, // handle to dialog box
1822 UINT uiMsg, // message identifier
1823 WPARAM wParam, // message parameter
1824 LPARAM lParam // message parameter
1825 )
1826{
1827 HWND hwndOwner;
1828 RECT rc, rcDlg, rcOwner;
1829 PRINTDLG *pPD;
1830
1831 if (uiMsg == WM_INITDIALOG)
1832 {
1833 // Get the owner window and dialog box rectangles.
1834 if ((hwndOwner = GetParent(hDlg)) == NULL)
1835 hwndOwner = GetDesktopWindow();
1836
1837 GetWindowRect(hwndOwner, &rcOwner);
1838 GetWindowRect(hDlg, &rcDlg);
1839 CopyRect(&rc, &rcOwner);
1840
1841 // Offset the owner and dialog box rectangles so that
1842 // right and bottom values represent the width and
1843 // height, and then offset the owner again to discard
1844 // space taken up by the dialog box.
1845
1846 OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
1847 OffsetRect(&rc, -rc.left, -rc.top);
1848 OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
1849
1850 // The new position is the sum of half the remaining
1851 // space and the owner's original position.
1852
1853 SetWindowPos(hDlg,
1854 HWND_TOP,
1855 rcOwner.left + (rc.right / 2),
1856 rcOwner.top + (rc.bottom / 2),
1857 0, 0, // ignores size arguments
1858 SWP_NOSIZE);
1859
1860 /* tackle the printdlg copiesctrl problem */
1861 pPD = (PRINTDLG *)lParam;
1862 pPD->nCopies = (WORD)pPD->lCustData;
1863 SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE );
1864 /* Bring the window to top */
1865 BringWindowToTop(GetParent(hDlg));
1866 SetForegroundWindow(hDlg);
1867 }
1868
1869 return FALSE;
1870}
1871#endif
1872
1873 void
1874mch_print_cleanup(void)
1875{
1876 int pifItalic;
1877 int pifBold;
1878 int pifUnderline;
1879
1880 for (pifBold = 0; pifBold <= 1; pifBold++)
1881 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1882 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1883 DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]);
1884
1885 if (prt_dlg.hDC != NULL)
1886 DeleteDC(prt_dlg.hDC);
1887 if (!*bUserAbort)
1888 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1889}
1890
1891 static int
1892to_device_units(int idx, int dpi, int physsize, int offset, int def_number)
1893{
1894 int ret = 0;
1895 int u;
1896 int nr;
1897
1898 u = prt_get_unit(idx);
1899 if (u == PRT_UNIT_NONE)
1900 {
1901 u = PRT_UNIT_PERC;
1902 nr = def_number;
1903 }
1904 else
1905 nr = printer_opts[idx].number;
1906
1907 switch (u)
1908 {
1909 case PRT_UNIT_PERC:
1910 ret = (physsize * nr) / 100;
1911 break;
1912 case PRT_UNIT_INCH:
1913 ret = (nr * dpi);
1914 break;
1915 case PRT_UNIT_MM:
1916 ret = (nr * 10 * dpi) / 254;
1917 break;
1918 case PRT_UNIT_POINT:
1919 ret = (nr * 10 * dpi) / 720;
1920 break;
1921 }
1922
1923 if (ret < offset)
1924 return 0;
1925 else
1926 return ret - offset;
1927}
1928
1929 static int
1930prt_get_cpl(void)
1931{
1932 int hr;
1933 int phyw;
1934 int dvoff;
1935 int rev_offset;
1936 int dpi;
1937#ifdef WIN16
1938 POINT pagesize;
1939#endif
1940
1941 GetTextMetrics(prt_dlg.hDC, &prt_tm);
1942 prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading;
1943
1944 hr = GetDeviceCaps(prt_dlg.hDC, HORZRES);
1945#ifdef WIN16
1946 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1947 phyw = pagesize.x;
1948 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1949 dvoff = pagesize.x;
1950#else
1951 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH);
1952 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX);
1953#endif
1954 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX);
1955
1956 rev_offset = phyw - (dvoff + hr);
1957
1958 prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10);
1959 if (prt_use_number())
1960 {
1961 prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth;
1962 prt_left_margin += prt_number_width;
1963 }
1964 else
1965 prt_number_width = 0;
1966
1967 prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw,
1968 rev_offset, 5);
1969
1970 return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth;
1971}
1972
1973 static int
1974prt_get_lpp(void)
1975{
1976 int vr;
1977 int phyw;
1978 int dvoff;
1979 int rev_offset;
1980 int bottom_margin;
1981 int dpi;
1982#ifdef WIN16
1983 POINT pagesize;
1984#endif
1985
1986 vr = GetDeviceCaps(prt_dlg.hDC, VERTRES);
1987#ifdef WIN16
1988 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1989 phyw = pagesize.y;
1990 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1991 dvoff = pagesize.y;
1992#else
1993 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT);
1994 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY);
1995#endif
1996 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY);
1997
1998 rev_offset = phyw - (dvoff + vr);
1999
2000 prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5);
2001
2002 /* adjust top margin if there is a header */
2003 prt_top_margin += prt_line_height * prt_header_height();
2004
2005 bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw,
2006 rev_offset, 5);
2007
2008 return (bottom_margin - prt_top_margin) / prt_line_height;
2009}
2010
2011 int
2012mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
2013{
2014 static HGLOBAL stored_dm = NULL;
2015 static HGLOBAL stored_devn = NULL;
2016 static int stored_nCopies = 1;
2017 static int stored_nFlags = 0;
2018
2019 LOGFONT fLogFont;
2020 int pifItalic;
2021 int pifBold;
2022 int pifUnderline;
2023
2024 DEVMODE *mem;
2025 DEVNAMES *devname;
2026 int i;
2027
2028 bUserAbort = &(psettings->user_abort);
2029 memset(&prt_dlg, 0, sizeof(PRINTDLG));
2030 prt_dlg.lStructSize = sizeof(PRINTDLG);
2031#ifndef FEAT_GUI
2032 GetConsoleHwnd(); /* get value of s_hwnd */
2033#endif
2034 prt_dlg.hwndOwner = s_hwnd;
2035 prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
2036 if (!forceit)
2037 {
2038 prt_dlg.hDevMode = stored_dm;
2039 prt_dlg.hDevNames = stored_devn;
2040 prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog
2041#ifndef FEAT_GUI
2042 /*
2043 * Use hook to prevent console window being sent to back
2044 */
2045 prt_dlg.lpfnPrintHook = PrintHookProc;
2046 prt_dlg.Flags |= PD_ENABLEPRINTHOOK;
2047#endif
2048 prt_dlg.Flags |= stored_nFlags;
2049 }
2050
2051 /*
2052 * If bang present, return default printer setup with no dialog
2053 * never show dialog if we are running over telnet
2054 */
2055 if (forceit
2056#ifndef FEAT_GUI
2057 || !term_console
2058#endif
2059 )
2060 {
2061 prt_dlg.Flags |= PD_RETURNDEFAULT;
2062#ifdef WIN3264
2063 /*
2064 * MSDN suggests setting the first parameter to WINSPOOL for
2065 * NT, but NULL appears to work just as well.
2066 */
2067 if (*p_pdev != NUL)
2068 prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL);
2069 else
2070#endif
2071 {
2072 prt_dlg.Flags |= PD_RETURNDEFAULT;
2073 if (PrintDlg(&prt_dlg) == 0)
2074 goto init_fail_dlg;
2075 }
2076 }
2077 else if (PrintDlg(&prt_dlg) == 0)
2078 goto init_fail_dlg;
2079 else
2080 {
2081 /*
2082 * keep the previous driver context
2083 */
2084 stored_dm = prt_dlg.hDevMode;
2085 stored_devn = prt_dlg.hDevNames;
2086 stored_nFlags = prt_dlg.Flags;
2087 stored_nCopies = prt_dlg.nCopies;
2088 }
2089
2090 if (prt_dlg.hDC == NULL)
2091 {
2092 EMSG(_("E237: Printer selection failed"));
2093 mch_print_cleanup();
2094 return FALSE;
2095 }
2096
2097 /* Not all printer drivers report the support of color (or grey) in the
2098 * same way. Let's set has_color if there appears to be some way to print
2099 * more than B&W. */
2100 i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS);
2101 psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1
2102 || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1
2103 || i > 2 || i == -1);
2104
2105 /* Ensure all font styles are baseline aligned */
2106 SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT);
2107
2108 /*
2109 * On some windows systems the nCopies parameter is not
2110 * passed back correctly. It must be retrieved from the
2111 * hDevMode struct.
2112 */
2113 mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode);
2114 if (mem != NULL)
2115 {
2116#ifdef WIN3264
2117 if (mem->dmCopies != 1)
2118 stored_nCopies = mem->dmCopies;
2119#endif
2120 if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX))
2121 psettings->duplex = TRUE;
2122 if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR))
2123 psettings->has_color = TRUE;
2124 }
2125 GlobalUnlock(prt_dlg.hDevMode);
2126
2127 devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames);
2128 if (devname != 0)
2129 {
2130 char_u *printer_name = (char_u *)devname + devname->wDeviceOffset;
2131 char_u *port_name = (char_u *)devname +devname->wOutputOffset;
2132 char_u *text = _("to %s on %s");
2133
2134 prt_name = alloc(STRLEN(printer_name) + STRLEN(port_name)
2135 + STRLEN(text));
2136 if (prt_name != NULL)
2137 wsprintf(prt_name, text, printer_name, port_name);
2138 }
2139 GlobalUnlock(prt_dlg.hDevNames);
2140
2141 /*
2142 * Initialise the font according to 'printfont'
2143 */
2144 memset(&fLogFont, 0, sizeof(fLogFont));
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00002145 if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002146 {
2147 EMSG2(_("E613: Unknown printer font: %s"), p_pfn);
2148 mch_print_cleanup();
2149 return FALSE;
2150 }
2151
2152 for (pifBold = 0; pifBold <= 1; pifBold++)
2153 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
2154 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
2155 {
2156 fLogFont.lfWeight = boldface[pifBold];
2157 fLogFont.lfItalic = pifItalic;
2158 fLogFont.lfUnderline = pifUnderline;
2159 prt_font_handles[pifBold][pifItalic][pifUnderline]
2160 = CreateFontIndirect(&fLogFont);
2161 }
2162
2163 SetBkMode(prt_dlg.hDC, OPAQUE);
2164 SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]);
2165
2166 /*
2167 * Fill in the settings struct
2168 */
2169 psettings->chars_per_line = prt_get_cpl();
2170 psettings->lines_per_page = prt_get_lpp();
2171 psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE)
2172 ? prt_dlg.nCopies : 1;
2173 psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE)
2174 ? 1 : prt_dlg.nCopies;
2175
2176 if (psettings->n_collated_copies == 0)
2177 psettings->n_collated_copies = 1;
2178
2179 if (psettings->n_uncollated_copies == 0)
2180 psettings->n_uncollated_copies = 1;
2181
2182 psettings->jobname = jobname;
2183
2184 return TRUE;
2185
2186init_fail_dlg:
2187 {
2188 DWORD err = CommDlgExtendedError();
2189
2190 if (err)
2191 {
2192#ifdef WIN16
2193 char buf[20];
2194
2195 sprintf(buf, "%ld", err);
2196 EMSG2(_("E238: Print error: %s"), buf);
2197#else
2198 char_u *buf;
2199
2200 /* I suspect FormatMessage() doesn't work for values returned by
2201 * CommDlgExtendedError(). What does? */
2202 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2203 FORMAT_MESSAGE_FROM_SYSTEM |
2204 FORMAT_MESSAGE_IGNORE_INSERTS,
2205 NULL, err, 0, (LPTSTR)(&buf), 0, NULL);
2206 EMSG2(_("E238: Print error: %s"),
2207 buf == NULL ? (char_u *)_("Unknown") : buf);
2208 LocalFree((LPVOID)(buf));
2209#endif
2210 }
2211 else
2212 msg_clr_eos(); /* Maybe canceled */
2213
2214 mch_print_cleanup();
2215 return FALSE;
2216 }
2217}
2218
2219
2220 int
2221mch_print_begin(prt_settings_T *psettings)
2222{
2223 int ret;
2224 static DOCINFO di;
2225 char szBuffer[300];
2226
2227 hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"),
2228 prt_dlg.hwndOwner, PrintDlgProc);
2229#ifdef WIN16
2230 Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL);
2231#else
2232 SetAbortProc(prt_dlg.hDC, AbortProc);
2233#endif
2234 wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname));
2235 SetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer);
2236
2237 memset(&di, 0, sizeof(DOCINFO));
2238 di.cbSize = sizeof(DOCINFO);
2239 di.lpszDocName = psettings->jobname;
2240 ret = StartDoc(prt_dlg.hDC, &di);
2241
2242#ifdef FEAT_GUI
2243 /* Give focus back to main window (when using MDI). */
2244 SetFocus(s_hwnd);
2245#endif
2246
2247 return (ret > 0);
2248}
2249
2250 void
2251mch_print_end(prt_settings_T *psettings)
2252{
2253 EndDoc(prt_dlg.hDC);
2254 if (!*bUserAbort)
2255 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
2256}
2257
2258 int
2259mch_print_end_page(void)
2260{
2261 return (EndPage(prt_dlg.hDC) > 0);
2262}
2263
2264 int
2265mch_print_begin_page(char_u *msg)
2266{
2267 if (msg != NULL)
2268 SetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg);
2269 return (StartPage(prt_dlg.hDC) > 0);
2270}
2271
2272 int
2273mch_print_blank_page(void)
2274{
2275 return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
2276}
2277
2278static int prt_pos_x = 0;
2279static int prt_pos_y = 0;
2280
2281 void
2282mch_print_start_line(margin, page_line)
2283 int margin;
2284 int page_line;
2285{
2286 if (margin)
2287 prt_pos_x = -prt_number_width;
2288 else
2289 prt_pos_x = 0;
2290 prt_pos_y = page_line * prt_line_height
2291 + prt_tm.tmAscent + prt_tm.tmExternalLeading;
2292}
2293
2294 int
2295mch_print_text_out(char_u *p, int len)
2296{
2297#ifdef FEAT_PROPORTIONAL_FONTS
2298 SIZE sz;
2299#endif
2300
2301 TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin,
2302 prt_pos_y + prt_top_margin, p, len);
2303#ifndef FEAT_PROPORTIONAL_FONTS
2304 prt_pos_x += len * prt_tm.tmAveCharWidth;
2305 return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth
2306 + prt_tm.tmOverhang > prt_right_margin);
2307#else
2308# ifdef WIN16
2309 GetTextExtentPoint(prt_dlg.hDC, p, len, &sz);
2310# else
2311 GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz);
2312# endif
2313 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
2314 /* This is wrong when printing spaces for a TAB. */
2315 if (p[len] == NUL)
2316 return FALSE;
2317# ifdef WIN16
2318 GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz);
2319# else
2320 GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz);
2321# endif
2322 return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
2323#endif
2324}
2325
2326 void
2327mch_print_set_font(int iBold, int iItalic, int iUnderline)
2328{
2329 SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]);
2330}
2331
2332 void
2333mch_print_set_bg(unsigned long bgcol)
2334{
2335 SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC, swap_me(bgcol)));
2336 /*
2337 * With a white background we can draw characters transparent, which is
2338 * good for italic characters that overlap to the next char cell.
2339 */
2340 if (bgcol == 0xffffffUL)
2341 SetBkMode(prt_dlg.hDC, TRANSPARENT);
2342 else
2343 SetBkMode(prt_dlg.hDC, OPAQUE);
2344}
2345
2346 void
2347mch_print_set_fg(unsigned long fgcol)
2348{
2349 SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC, swap_me(fgcol)));
2350}
2351
2352#endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
2353
2354#if defined(FEAT_SHORTCUT) || defined(PROTO)
2355# include <shlobj.h>
2356
2357/*
2358 * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
2359 * to and return that name in allocated memory.
2360 * Otherwise NULL is returned.
2361 */
2362 char_u *
2363mch_resolve_shortcut(char_u *fname)
2364{
2365 HRESULT hr;
2366 IShellLink *psl = NULL;
2367 IPersistFile *ppf = NULL;
2368 OLECHAR wsz[MAX_PATH];
2369 WIN32_FIND_DATA ffd; // we get those free of charge
2370 TCHAR buf[MAX_PATH]; // could have simply reused 'wsz'...
2371 char_u *rfname = NULL;
2372 int len;
2373
2374 /* Check if the file name ends in ".lnk". Avoid calling
2375 * CoCreateInstance(), it's quite slow. */
2376 if (fname == NULL)
2377 return rfname;
2378 len = STRLEN(fname);
2379 if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
2380 return rfname;
2381
2382 CoInitialize(NULL);
2383
2384 // create a link manager object and request its interface
2385 hr = CoCreateInstance(
2386 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2387 &IID_IShellLink, (void**)&psl);
2388 if (hr != S_OK)
2389 goto shortcut_error;
2390
2391 // Get a pointer to the IPersistFile interface.
2392 hr = psl->lpVtbl->QueryInterface(
2393 psl, &IID_IPersistFile, (void**)&ppf);
2394 if (hr != S_OK)
2395 goto shortcut_error;
2396
2397 // full path string must be in Unicode.
2398 MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
2399
2400 // "load" the name and resove the link
2401 hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
2402 if (hr != S_OK)
2403 goto shortcut_error;
2404#if 0 // This makes Vim wait a long time if the target doesn't exist.
2405 hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
2406 if (hr != S_OK)
2407 goto shortcut_error;
2408#endif
2409
2410 // Get the path to the link target.
2411 ZeroMemory(buf, MAX_PATH);
2412 hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
2413 if (hr == S_OK && buf[0] != NUL)
2414 rfname = vim_strsave(buf);
2415
2416shortcut_error:
2417 // Release all interface pointers (both belong to the same object)
2418 if (ppf != NULL)
2419 ppf->lpVtbl->Release(ppf);
2420 if (psl != NULL)
2421 psl->lpVtbl->Release(psl);
2422
2423 CoUninitialize();
2424 return rfname;
2425}
2426#endif
2427
2428#if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
2429/*
2430 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
2431 */
2432 void
2433win32_set_foreground()
2434{
2435# ifndef FEAT_GUI
2436 GetConsoleHwnd(); /* get value of s_hwnd */
2437# endif
2438 if (s_hwnd != 0)
2439 SetForegroundWindow(s_hwnd);
2440}
2441#endif
2442
2443#if defined(FEAT_CLIENTSERVER) || defined(PROTO)
2444/*
2445 * Client-server code for Vim
2446 *
2447 * Originally written by Paul Moore
2448 */
2449
2450/* In order to handle inter-process messages, we need to have a window. But
2451 * the functions in this module can be called before the main GUI window is
2452 * created (and may also be called in the console version, where there is no
2453 * GUI window at all).
2454 *
2455 * So we create a hidden window, and arrange to destroy it on exit.
2456 */
2457HWND message_window = 0; /* window that's handling messsages */
2458
2459#define VIM_CLASSNAME "VIM_MESSAGES"
2460#define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
2461
2462/* Communication is via WM_COPYDATA messages. The message type is send in
2463 * the dwData parameter. Types are defined here. */
2464#define COPYDATA_KEYS 0
2465#define COPYDATA_REPLY 1
2466#define COPYDATA_EXPR 10
2467#define COPYDATA_RESULT 11
2468#define COPYDATA_ERROR_RESULT 12
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002469#define COPYDATA_ENCODING 20
Bram Moolenaar071d4272004-06-13 20:20:40 +00002470
2471/* This is a structure containing a server HWND and its name. */
2472struct server_id
2473{
2474 HWND hwnd;
2475 char_u *name;
2476};
2477
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002478/* Last received 'encoding' that the client uses. */
2479static char_u *client_enc = NULL;
2480
2481/*
2482 * Tell the other side what encoding we are using.
2483 * Errors are ignored.
2484 */
2485 static void
2486serverSendEnc(HWND target)
2487{
2488 COPYDATASTRUCT data;
2489
2490 data.dwData = COPYDATA_ENCODING;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002491#ifdef FEAT_MBYTE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002492 data.cbData = STRLEN(p_enc) + 1;
2493 data.lpData = p_enc;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00002494#else
2495 data.cbData = STRLEN("latin1") + 1;
2496 data.lpData = "latin1";
2497#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002498 (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2499 (LPARAM)(&data));
2500}
2501
Bram Moolenaar071d4272004-06-13 20:20:40 +00002502/*
2503 * Clean up on exit. This destroys the hidden message window.
2504 */
2505 static void
2506#ifdef __BORLANDC__
2507 _RTLENTRYF
2508#endif
2509CleanUpMessaging(void)
2510{
2511 if (message_window != 0)
2512 {
2513 DestroyWindow(message_window);
2514 message_window = 0;
2515 }
2516}
2517
2518static int save_reply(HWND server, char_u *reply, int expr);
2519
2520/*s
2521 * The window procedure for the hidden message window.
2522 * It handles callback messages and notifications from servers.
2523 * In order to process these messages, it is necessary to run a
2524 * message loop. Code which may run before the main message loop
2525 * is started (in the GUI) is careful to pump messages when it needs
2526 * to. Features which require message delivery during normal use will
2527 * not work in the console version - this basically means those
2528 * features which allow Vim to act as a server, rather than a client.
2529 */
2530 static LRESULT CALLBACK
2531Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2532{
2533 if (msg == WM_COPYDATA)
2534 {
2535 /* This is a message from another Vim. The dwData member of the
2536 * COPYDATASTRUCT determines the type of message:
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002537 * COPYDATA_ENCODING:
2538 * The encoding that the client uses. Following messages will
2539 * use this encoding, convert if needed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002540 * COPYDATA_KEYS:
2541 * A key sequence. We are a server, and a client wants these keys
2542 * adding to the input queue.
2543 * COPYDATA_REPLY:
2544 * A reply. We are a client, and a server has sent this message
2545 * in response to a request. (server2client())
2546 * COPYDATA_EXPR:
2547 * An expression. We are a server, and a client wants us to
2548 * evaluate this expression.
2549 * COPYDATA_RESULT:
2550 * A reply. We are a client, and a server has sent this message
2551 * in response to a COPYDATA_EXPR.
2552 * COPYDATA_ERROR_RESULT:
2553 * A reply. We are a client, and a server has sent this message
2554 * in response to a COPYDATA_EXPR that failed to evaluate.
2555 */
2556 COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam;
2557 HWND sender = (HWND)wParam;
2558 COPYDATASTRUCT reply;
2559 char_u *res;
2560 char_u winstr[30];
2561 int retval;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002562 char_u *str;
2563 char_u *tofree;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564
2565 switch (data->dwData)
2566 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002567 case COPYDATA_ENCODING:
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002568# ifdef FEAT_MBYTE
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002569 /* Remember the encoding that the client uses. */
2570 vim_free(client_enc);
2571 client_enc = enc_canonize((char_u *)data->lpData);
Bram Moolenaarbc7aa852005-03-06 23:38:09 +00002572# endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002573 return 1;
2574
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 case COPYDATA_KEYS:
2576 /* Remember who sent this, for <client> */
2577 clientWindow = sender;
2578
2579 /* Add the received keys to the input buffer. The loop waiting
2580 * for the user to do something should check the input buffer. */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002581 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2582 server_to_input_buf(str);
2583 vim_free(tofree);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002584
2585# ifdef FEAT_GUI
2586 /* Wake up the main GUI loop. */
2587 if (s_hwnd != 0)
2588 PostMessage(s_hwnd, WM_NULL, 0, 0);
2589# endif
2590 return 1;
2591
2592 case COPYDATA_EXPR:
2593 /* Remember who sent this, for <client> */
2594 clientWindow = sender;
2595
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002596 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2597 res = eval_client_expr_to_string(str);
2598 vim_free(tofree);
2599
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600 if (res == NULL)
2601 {
2602 res = vim_strsave(_(e_invexprmsg));
2603 reply.dwData = COPYDATA_ERROR_RESULT;
2604 }
2605 else
2606 reply.dwData = COPYDATA_RESULT;
2607 reply.lpData = res;
2608 reply.cbData = STRLEN(res) + 1;
2609
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002610 serverSendEnc(sender);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002611 retval = SendMessage(sender, WM_COPYDATA, (WPARAM)message_window,
2612 (LPARAM)(&reply));
2613 vim_free(res);
2614 return retval;
2615
2616 case COPYDATA_REPLY:
2617 case COPYDATA_RESULT:
2618 case COPYDATA_ERROR_RESULT:
2619 if (data->lpData != NULL)
2620 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002621 str = serverConvert(client_enc, (char_u *)data->lpData,
2622 &tofree);
2623 if (tofree == NULL)
2624 str = vim_strsave(str);
2625 if (save_reply(sender, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 (data->dwData == COPYDATA_REPLY ? 0 :
2627 (data->dwData == COPYDATA_RESULT ? 1 :
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002628 2))) == FAIL)
2629 vim_free(str);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002630#ifdef FEAT_AUTOCMD
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002631 else if (data->dwData == COPYDATA_REPLY)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632 {
2633 sprintf((char *)winstr, "0x%x", (unsigned)sender);
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002634 apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635 TRUE, curbuf);
2636 }
2637#endif
2638 }
2639 return 1;
2640 }
2641
2642 return 0;
2643 }
2644
2645 else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2646 {
2647 /* When the message window is activated (brought to the foreground),
2648 * this actually applies to the text window. */
2649#ifndef FEAT_GUI
2650 GetConsoleHwnd(); /* get value of s_hwnd */
2651#endif
2652 if (s_hwnd != 0)
2653 {
2654 SetForegroundWindow(s_hwnd);
2655 return 0;
2656 }
2657 }
2658
2659 return DefWindowProc(hwnd, msg, wParam, lParam);
2660}
2661
2662/*
2663 * Initialise the message handling process. This involves creating a window
2664 * to handle messages - the window will not be visible.
2665 */
2666 void
2667serverInitMessaging(void)
2668{
2669 WNDCLASS wndclass;
2670 HINSTANCE s_hinst;
2671
2672 /* Clean up on exit */
2673 atexit(CleanUpMessaging);
2674
2675 /* Register a window class - we only really care
2676 * about the window procedure
2677 */
2678 s_hinst = (HINSTANCE)GetModuleHandle(0);
2679 wndclass.style = 0;
2680 wndclass.lpfnWndProc = Messaging_WndProc;
2681 wndclass.cbClsExtra = 0;
2682 wndclass.cbWndExtra = 0;
2683 wndclass.hInstance = s_hinst;
2684 wndclass.hIcon = NULL;
2685 wndclass.hCursor = NULL;
2686 wndclass.hbrBackground = NULL;
2687 wndclass.lpszMenuName = NULL;
2688 wndclass.lpszClassName = VIM_CLASSNAME;
2689 RegisterClass(&wndclass);
2690
2691 /* Create the message window. It will be hidden, so the details don't
2692 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2693 * focus from gvim. */
2694 message_window = CreateWindow(VIM_CLASSNAME, "",
2695 WS_POPUPWINDOW | WS_CAPTION,
2696 CW_USEDEFAULT, CW_USEDEFAULT,
2697 100, 100, NULL, NULL,
2698 s_hinst, NULL);
2699}
2700
2701/*
2702 * Get the title of the window "hwnd", which is the Vim server name, in
2703 * "name[namelen]" and return the length.
2704 * Returns zero if window "hwnd" is not a Vim server.
2705 */
2706 static int
2707getVimServerName(HWND hwnd, char *name, int namelen)
2708{
2709 int len;
2710 char buffer[VIM_CLASSNAME_LEN + 1];
2711
2712 /* Ignore windows which aren't Vim message windows */
2713 len = GetClassName(hwnd, buffer, sizeof(buffer));
2714 if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2715 return 0;
2716
2717 /* Get the title of the window */
2718 return GetWindowText(hwnd, name, namelen);
2719}
2720
2721 static BOOL CALLBACK
2722enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2723{
2724 struct server_id *id = (struct server_id *)lparam;
2725 char server[MAX_PATH];
2726
2727 /* Get the title of the window */
2728 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2729 return TRUE;
2730
2731 /* If this is the server we're looking for, return its HWND */
2732 if (STRICMP(server, id->name) == 0)
2733 {
2734 id->hwnd = hwnd;
2735 return FALSE;
2736 }
2737
2738 /* Otherwise, keep looking */
2739 return TRUE;
2740}
2741
2742 static BOOL CALLBACK
2743enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2744{
2745 garray_T *ga = (garray_T *)lparam;
2746 char server[MAX_PATH];
2747
2748 /* Get the title of the window */
2749 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2750 return TRUE;
2751
2752 /* Add the name to the list */
2753 ga_concat(ga, server);
2754 ga_concat(ga, "\n");
2755 return TRUE;
2756}
2757
2758 static HWND
2759findServer(char_u *name)
2760{
2761 struct server_id id;
2762
2763 id.name = name;
2764 id.hwnd = 0;
2765
2766 EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2767
2768 return id.hwnd;
2769}
2770
2771 void
2772serverSetName(char_u *name)
2773{
2774 char_u *ok_name;
2775 HWND hwnd = 0;
2776 int i = 0;
2777 char_u *p;
2778
2779 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
2780 ok_name = alloc(STRLEN(name) + 10);
2781
2782 STRCPY(ok_name, name);
2783 p = ok_name + STRLEN(name);
2784
2785 for (;;)
2786 {
2787 /* This is inefficient - we're doing an EnumWindows loop for each
2788 * possible name. It would be better to grab all names in one go,
2789 * and scan the list each time...
2790 */
2791 hwnd = findServer(ok_name);
2792 if (hwnd == 0)
2793 break;
2794
2795 ++i;
2796 if (i >= 1000)
2797 break;
2798
2799 sprintf((char *)p, "%d", i);
2800 }
2801
2802 if (hwnd != 0)
2803 vim_free(ok_name);
2804 else
2805 {
2806 /* Remember the name */
2807 serverName = ok_name;
2808#ifdef FEAT_TITLE
2809 need_maketitle = TRUE; /* update Vim window title later */
2810#endif
2811
2812 /* Update the message window title */
2813 SetWindowText(message_window, ok_name);
2814
2815#ifdef FEAT_EVAL
2816 /* Set the servername variable */
2817 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2818#endif
2819 }
2820}
2821
2822 char_u *
2823serverGetVimNames(void)
2824{
2825 garray_T ga;
2826
2827 ga_init2(&ga, 1, 100);
2828
2829 EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
Bram Moolenaar269ec652004-07-29 08:43:53 +00002830 ga_append(&ga, NUL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831
2832 return ga.ga_data;
2833}
2834
2835 int
2836serverSendReply(name, reply)
2837 char_u *name; /* Where to send. */
2838 char_u *reply; /* What to send. */
2839{
2840 HWND target;
2841 COPYDATASTRUCT data;
2842 int n = 0;
2843
2844 /* The "name" argument is a magic cookie obtained from expand("<client>").
2845 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2846 * value of the client's message window HWND.
2847 */
2848 sscanf((char *)name, "%x", &n);
2849 if (n == 0)
2850 return -1;
2851
2852 target = (HWND)n;
2853 if (!IsWindow(target))
2854 return -1;
2855
2856 data.dwData = COPYDATA_REPLY;
2857 data.cbData = STRLEN(reply) + 1;
2858 data.lpData = reply;
2859
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002860 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2862 (LPARAM)(&data)))
2863 return 0;
2864
2865 return -1;
2866}
2867
2868 int
2869serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2870 char_u *name; /* Where to send. */
2871 char_u *cmd; /* What to send. */
2872 char_u **result; /* Result of eval'ed expression */
2873 void *ptarget; /* HWND of server */
2874 int asExpr; /* Expression or keys? */
2875 int silent; /* don't complain about no server */
2876{
2877 HWND target = findServer(name);
2878 COPYDATASTRUCT data;
2879 char_u *retval = NULL;
2880 int retcode = 0;
2881
2882 if (target == 0)
2883 {
2884 if (!silent)
2885 EMSG2(_(e_noserver), name);
2886 return -1;
2887 }
2888
2889 if (ptarget)
2890 *(HWND *)ptarget = target;
2891
2892 data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
2893 data.cbData = STRLEN(cmd) + 1;
2894 data.lpData = cmd;
2895
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002896 serverSendEnc(target);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002897 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2898 (LPARAM)(&data)) == 0)
2899 return -1;
2900
2901 if (asExpr)
2902 retval = serverGetReply(target, &retcode, TRUE, TRUE);
2903
2904 if (result == NULL)
2905 vim_free(retval);
2906 else
2907 *result = retval; /* Caller assumes responsibility for freeing */
2908
2909 return retcode;
2910}
2911
2912/*
2913 * Bring the server to the foreground.
2914 */
2915 void
2916serverForeground(name)
2917 char_u *name;
2918{
2919 HWND target = findServer(name);
2920
2921 if (target != 0)
2922 SetForegroundWindow(target);
2923}
2924
2925/* Replies from server need to be stored until the client picks them up via
2926 * remote_read(). So we maintain a list of server-id/reply pairs.
2927 * Note that there could be multiple replies from one server pending if the
2928 * client is slow picking them up.
2929 * We just store the replies in a simple list. When we remove an entry, we
2930 * move list entries down to fill the gap.
2931 * The server ID is simply the HWND.
2932 */
2933typedef struct
2934{
2935 HWND server; /* server window */
2936 char_u *reply; /* reply string */
2937 int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */
2938}
2939reply_T;
2940
2941static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
2942
2943#define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
2944#define REPLY_COUNT (reply_list.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002945
2946/* Flag which is used to wait for a reply */
2947static int reply_received = 0;
2948
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002949/*
2950 * Store a reply. "reply" must be allocated memory (or NULL).
2951 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002952 static int
2953save_reply(HWND server, char_u *reply, int expr)
2954{
2955 reply_T *rep;
2956
2957 if (ga_grow(&reply_list, 1) == FAIL)
2958 return FAIL;
2959
2960 rep = REPLY_ITEM(REPLY_COUNT);
2961 rep->server = server;
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00002962 rep->reply = reply;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002963 rep->expr_result = expr;
2964 if (rep->reply == NULL)
2965 return FAIL;
2966
2967 ++REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002968 reply_received = 1;
2969 return OK;
2970}
2971
2972/*
2973 * Get a reply from server "server".
2974 * When "expr_res" is non NULL, get the result of an expression, otherwise a
2975 * server2client() message.
2976 * When non NULL, point to return code. 0 => OK, -1 => ERROR
2977 * If "remove" is TRUE, consume the message, the caller must free it then.
2978 * if "wait" is TRUE block until a message arrives (or the server exits).
2979 */
2980 char_u *
2981serverGetReply(HWND server, int *expr_res, int remove, int wait)
2982{
2983 int i;
2984 char_u *reply;
2985 reply_T *rep;
2986
2987 /* When waiting, loop until the message waiting for is received. */
2988 for (;;)
2989 {
2990 /* Reset this here, in case a message arrives while we are going
2991 * through the already received messages. */
2992 reply_received = 0;
2993
2994 for (i = 0; i < REPLY_COUNT; ++i)
2995 {
2996 rep = REPLY_ITEM(i);
2997 if (rep->server == server
2998 && ((rep->expr_result != 0) == (expr_res != NULL)))
2999 {
3000 /* Save the values we've found for later */
3001 reply = rep->reply;
3002 if (expr_res != NULL)
3003 *expr_res = rep->expr_result == 1 ? 0 : -1;
3004
3005 if (remove)
3006 {
3007 /* Move the rest of the list down to fill the gap */
3008 mch_memmove(rep, rep + 1,
3009 (REPLY_COUNT - i - 1) * sizeof(reply_T));
3010 --REPLY_COUNT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003011 }
3012
3013 /* Return the reply to the caller, who takes on responsibility
3014 * for freeing it if "remove" is TRUE. */
3015 return reply;
3016 }
3017 }
3018
3019 /* If we got here, we didn't find a reply. Return immediately if the
3020 * "wait" parameter isn't set. */
3021 if (!wait)
3022 break;
3023
3024 /* We need to wait for a reply. Enter a message loop until the
3025 * "reply_received" flag gets set. */
3026
3027 /* Loop until we receive a reply */
3028 while (reply_received == 0)
3029 {
3030 /* Wait for a SendMessage() call to us. This could be the reply
3031 * we are waiting for. Use a timeout of a second, to catch the
3032 * situation that the server died unexpectedly. */
3033 MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
3034
3035 /* If the server has died, give up */
3036 if (!IsWindow(server))
3037 return NULL;
3038
3039 serverProcessPendingMessages();
3040 }
3041 }
3042
3043 return NULL;
3044}
3045
3046/*
3047 * Process any messages in the Windows message queue.
3048 */
3049 void
3050serverProcessPendingMessages(void)
3051{
3052 MSG msg;
3053
3054 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
3055 {
3056 TranslateMessage(&msg);
3057 DispatchMessage(&msg);
3058 }
3059}
3060
3061#endif /* FEAT_CLIENTSERVER */
3062
3063#if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
3064 || defined(PROTO)
3065
3066struct charset_pair
3067{
3068 char *name;
3069 BYTE charset;
3070};
3071
3072static struct charset_pair
3073charset_pairs[] =
3074{
3075 {"ANSI", ANSI_CHARSET},
3076 {"CHINESEBIG5", CHINESEBIG5_CHARSET},
3077 {"DEFAULT", DEFAULT_CHARSET},
3078 {"HANGEUL", HANGEUL_CHARSET},
3079 {"OEM", OEM_CHARSET},
3080 {"SHIFTJIS", SHIFTJIS_CHARSET},
3081 {"SYMBOL", SYMBOL_CHARSET},
3082#ifdef WIN3264
3083 {"ARABIC", ARABIC_CHARSET},
3084 {"BALTIC", BALTIC_CHARSET},
3085 {"EASTEUROPE", EASTEUROPE_CHARSET},
3086 {"GB2312", GB2312_CHARSET},
3087 {"GREEK", GREEK_CHARSET},
3088 {"HEBREW", HEBREW_CHARSET},
3089 {"JOHAB", JOHAB_CHARSET},
3090 {"MAC", MAC_CHARSET},
3091 {"RUSSIAN", RUSSIAN_CHARSET},
3092 {"THAI", THAI_CHARSET},
3093 {"TURKISH", TURKISH_CHARSET},
3094# if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
3095 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
3096 {"VIETNAMESE", VIETNAMESE_CHARSET},
3097# endif
3098#endif
3099 {NULL, 0}
3100};
3101
3102/*
3103 * Convert a charset ID to a name.
3104 * Return NULL when not recognized.
3105 */
3106 char *
3107charset_id2name(int id)
3108{
3109 struct charset_pair *cp;
3110
3111 for (cp = charset_pairs; cp->name != NULL; ++cp)
3112 if ((BYTE)id == cp->charset)
3113 break;
3114 return cp->name;
3115}
3116
3117static const LOGFONT s_lfDefault =
3118{
3119 -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
3120 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
3121 PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
3122 "Fixedsys" /* see _ReadVimIni */
3123};
3124
3125/* Initialise the "current height" to -12 (same as s_lfDefault) just
3126 * in case the user specifies a font in "guifont" with no size before a font
3127 * with an explicit size has been set. This defaults the size to this value
3128 * (-12 equates to roughly 9pt).
3129 */
3130int current_font_height = -12; /* also used in gui_w48.c */
3131
3132/* Convert a string representing a point size into pixels. The string should
3133 * be a positive decimal number, with an optional decimal point (eg, "12", or
3134 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
3135 * character is stored in *end. The flag "vertical" says whether this
3136 * calculation is for a vertical (height) size or a horizontal (width) one.
3137 */
3138 static int
3139points_to_pixels(char_u *str, char_u **end, int vertical, int pprinter_dc)
3140{
3141 int pixels;
3142 int points = 0;
3143 int divisor = 0;
3144 HWND hwnd = (HWND)0;
3145 HDC hdc;
3146 HDC printer_dc = (HDC)pprinter_dc;
3147
3148 while (*str != NUL)
3149 {
3150 if (*str == '.' && divisor == 0)
3151 {
3152 /* Start keeping a divisor, for later */
3153 divisor = 1;
3154 }
3155 else
3156 {
3157 if (!VIM_ISDIGIT(*str))
3158 break;
3159
3160 points *= 10;
3161 points += *str - '0';
3162 divisor *= 10;
3163 }
3164 ++str;
3165 }
3166
3167 if (divisor == 0)
3168 divisor = 1;
3169
3170 if (printer_dc == NULL)
3171 {
3172 hwnd = GetDesktopWindow();
3173 hdc = GetWindowDC(hwnd);
3174 }
3175 else
3176 hdc = printer_dc;
3177
3178 pixels = MulDiv(points,
3179 GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
3180 72 * divisor);
3181
3182 if (printer_dc == NULL)
3183 ReleaseDC(hwnd, hdc);
3184
3185 *end = str;
3186 return pixels;
3187}
3188
3189 static int CALLBACK
3190font_enumproc(
3191 ENUMLOGFONT *elf,
3192 NEWTEXTMETRIC *ntm,
3193 int type,
3194 LPARAM lparam)
3195{
3196 /* Return value:
3197 * 0 = terminate now (monospace & ANSI)
3198 * 1 = continue, still no luck...
3199 * 2 = continue, but we have an acceptable LOGFONT
3200 * (monospace, not ANSI)
3201 * We use these values, as EnumFontFamilies returns 1 if the
3202 * callback function is never called. So, we check the return as
3203 * 0 = perfect, 2 = OK, 1 = no good...
3204 * It's not pretty, but it works!
3205 */
3206
3207 LOGFONT *lf = (LOGFONT *)(lparam);
3208
3209#ifndef FEAT_PROPORTIONAL_FONTS
3210 /* Ignore non-monospace fonts without further ado */
3211 if ((ntm->tmPitchAndFamily & 1) != 0)
3212 return 1;
3213#endif
3214
3215 /* Remember this LOGFONT as a "possible" */
3216 *lf = elf->elfLogFont;
3217
3218 /* Terminate the scan as soon as we find an ANSI font */
3219 if (lf->lfCharSet == ANSI_CHARSET
3220 || lf->lfCharSet == OEM_CHARSET
3221 || lf->lfCharSet == DEFAULT_CHARSET)
3222 return 0;
3223
3224 /* Continue the scan - we have a non-ANSI font */
3225 return 2;
3226}
3227
3228 static int
3229init_logfont(LOGFONT *lf)
3230{
3231 int n;
3232 HWND hwnd = GetDesktopWindow();
3233 HDC hdc = GetWindowDC(hwnd);
3234
3235 n = EnumFontFamilies(hdc,
3236 (LPCSTR)lf->lfFaceName,
3237 (FONTENUMPROC)font_enumproc,
3238 (LPARAM)lf);
3239
3240 ReleaseDC(hwnd, hdc);
3241
3242 /* If we couldn't find a useable font, return failure */
3243 if (n == 1)
3244 return FAIL;
3245
3246 /* Tidy up the rest of the LOGFONT structure. We set to a basic
3247 * font - get_logfont() sets bold, italic, etc based on the user's
3248 * input.
3249 */
3250 lf->lfHeight = current_font_height;
3251 lf->lfWidth = 0;
3252 lf->lfItalic = FALSE;
3253 lf->lfUnderline = FALSE;
3254 lf->lfStrikeOut = FALSE;
3255 lf->lfWeight = FW_NORMAL;
3256
3257 /* Return success */
3258 return OK;
3259}
3260
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003261/*
3262 * Get font info from "name" into logfont "lf".
3263 * Return OK for a valid name, FAIL otherwise.
3264 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265 int
3266get_logfont(
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003267 LOGFONT *lf,
3268 char_u *name,
3269 HDC printer_dc,
3270 int verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003271{
3272 char_u *p;
3273 int i;
3274 static LOGFONT *lastlf = NULL;
3275
3276 *lf = s_lfDefault;
3277 if (name == NULL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003278 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003279
3280 if (STRCMP(name, "*") == 0)
3281 {
3282#if defined(FEAT_GUI_W32)
3283 CHOOSEFONT cf;
3284 /* if name is "*", bring up std font dialog: */
3285 memset(&cf, 0, sizeof(cf));
3286 cf.lStructSize = sizeof(cf);
3287 cf.hwndOwner = s_hwnd;
3288 cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
3289 if (lastlf != NULL)
3290 *lf = *lastlf;
3291 cf.lpLogFont = lf;
3292 cf.nFontType = 0 ; //REGULAR_FONTTYPE;
3293 if (ChooseFont(&cf))
3294 goto theend;
3295#else
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003296 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003297#endif
3298 }
3299
3300 /*
3301 * Split name up, it could be <name>:h<height>:w<width> etc.
3302 */
3303 for (p = name; *p && *p != ':'; p++)
3304 {
3305 if (p - name + 1 > LF_FACESIZE)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003306 return FAIL; /* Name too long */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003307 lf->lfFaceName[p - name] = *p;
3308 }
3309 if (p != name)
3310 lf->lfFaceName[p - name] = NUL;
3311
3312 /* First set defaults */
3313 lf->lfHeight = -12;
3314 lf->lfWidth = 0;
3315 lf->lfWeight = FW_NORMAL;
3316 lf->lfItalic = FALSE;
3317 lf->lfUnderline = FALSE;
3318 lf->lfStrikeOut = FALSE;
3319
3320 /*
3321 * If the font can't be found, try replacing '_' by ' '.
3322 */
3323 if (init_logfont(lf) == FAIL)
3324 {
3325 int did_replace = FALSE;
3326
3327 for (i = 0; lf->lfFaceName[i]; ++i)
3328 if (lf->lfFaceName[i] == '_')
3329 {
3330 lf->lfFaceName[i] = ' ';
3331 did_replace = TRUE;
3332 }
3333 if (!did_replace || init_logfont(lf) == FAIL)
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003334 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003335 }
3336
3337 while (*p == ':')
3338 p++;
3339
3340 /* Set the values found after ':' */
3341 while (*p)
3342 {
3343 switch (*p++)
3344 {
3345 case 'h':
3346 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (int)printer_dc);
3347 break;
3348 case 'w':
3349 lf->lfWidth = points_to_pixels(p, &p, FALSE, (int)printer_dc);
3350 break;
3351 case 'b':
3352#ifndef MSWIN16_FASTTEXT
3353 lf->lfWeight = FW_BOLD;
3354#endif
3355 break;
3356 case 'i':
3357#ifndef MSWIN16_FASTTEXT
3358 lf->lfItalic = TRUE;
3359#endif
3360 break;
3361 case 'u':
3362 lf->lfUnderline = TRUE;
3363 break;
3364 case 's':
3365 lf->lfStrikeOut = TRUE;
3366 break;
3367 case 'c':
3368 {
3369 struct charset_pair *cp;
3370
3371 for (cp = charset_pairs; cp->name != NULL; ++cp)
3372 if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
3373 {
3374 lf->lfCharSet = cp->charset;
3375 p += strlen(cp->name);
3376 break;
3377 }
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003378 if (cp->name == NULL && verbose)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 {
3380 sprintf((char *)IObuff, _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
3381 EMSG(IObuff);
3382 break;
3383 }
3384 break;
3385 }
3386 default:
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003387 if (verbose)
3388 {
3389 sprintf((char *)IObuff,
3390 _("E245: Illegal char '%c' in font name \"%s\""),
3391 p[-1], name);
3392 EMSG(IObuff);
3393 }
3394 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395 }
3396 while (*p == ':')
3397 p++;
3398 }
3399
3400#if defined(FEAT_GUI_W32)
3401theend:
3402#endif
3403 /* ron: init lastlf */
3404 if (printer_dc == NULL)
3405 {
3406 vim_free(lastlf);
3407 lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
3408 if (lastlf != NULL)
3409 mch_memmove(lastlf, lf, sizeof(LOGFONT));
3410 }
3411
Bram Moolenaard8b0cf12004-12-12 11:33:30 +00003412 return OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003413}
3414
3415#endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */