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