comparison src/os_mswin.c @ 7:3fc0f57ecb91 v7.0001

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