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