Sync with newest CVS repository.
[MacVim/jjgod.git] / src / os_mswin.c
blob642dc43b427e8bd1b75d9738b35ac8b90f6a18dc
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
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 */
11 * os_mswin.c
13 * Routines common to both Win16 and Win32.
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
25 #include "vimio.h"
26 #include "vim.h"
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>
42 #undef chdir
43 #ifdef __GNUC__
44 # ifndef __MINGW32__
45 # include <dirent.h>
46 # endif
47 #else
48 # include <direct.h>
49 #endif
51 #if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
52 # include <shellapi.h>
53 #endif
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
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
83 * EventFlags
85 # ifndef MOUSE_MOVED
86 # define MOUSE_MOVED 0x0001
87 # endif
88 # ifndef DOUBLE_CLICK
89 # define DOUBLE_CLICK 0x0002
90 # endif
91 #endif
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
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
140 /* Record all output and all keyboard & mouse input */
141 /* #define MCH_WRITE_DUMP */
143 #ifdef MCH_WRITE_DUMP
144 FILE* fdDump = NULL;
145 #endif
147 #ifdef WIN3264
148 extern DWORD g_PlatformId;
149 #endif
151 #ifndef FEAT_GUI_MSWIN
152 extern char g_szOrigTitle[];
153 #endif
155 #ifdef FEAT_GUI
156 extern HWND s_hwnd;
157 #else
158 static HWND s_hwnd = 0; /* console window handle, set by GetConsoleHwnd() */
159 #endif
161 extern int WSInitialized;
163 /* Don't generate prototypes here, because some systems do have these
164 * functions. */
165 #if defined(__GNUC__) && !defined(PROTO)
166 # ifndef __MINGW32__
167 int _stricoll(char *a, char *b)
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);
176 char * _fullpath(char *buf, char *fname, int len)
178 LPTSTR toss;
180 return (char *)GetFullPathName(fname, len, buf, &toss);
182 # endif
184 int _chdrive(int drive)
186 char temp [3] = "-:";
187 temp[0] = drive + 'A' - 1;
188 return !SetCurrentDirectory(temp);
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
195 int _stricoll(char *a, char *b)
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
208 # endif
209 # endif
210 #endif
213 #if defined(FEAT_GUI_MSWIN) || defined(PROTO)
215 * GUI version of mch_exit().
216 * Shut down and exit with status `r'
217 * Careful: mch_exit() may be called before mch_init()!
219 void
220 mch_exit(int r)
222 display_errors();
224 ml_close_all(TRUE); /* remove all memfiles */
226 # ifdef FEAT_OLE
227 UninitOLE();
228 # endif
229 # ifdef FEAT_NETBEANS_INTG
230 if (WSInitialized)
232 WSInitialized = FALSE;
233 WSACleanup();
235 # endif
236 #ifdef DYNAMIC_GETTEXT
237 dyn_libintl_end();
238 #endif
240 if (gui.in_use)
241 gui_exit(r);
242 exit(r);
245 #endif /* FEAT_GUI_MSWIN */
249 * Init the tables for toupper() and tolower().
251 void
252 mch_early_init(void)
254 int i;
256 #ifdef WIN3264
257 PlatformId();
258 #endif
260 /* Init the tables for toupper() and tolower() */
261 for (i = 0; i < 256; ++i)
262 toupper_tab[i] = tolower_tab[i] = i;
263 #ifdef WIN3264
264 CharUpperBuff(toupper_tab, 256);
265 CharLowerBuff(tolower_tab, 256);
266 #else
267 AnsiUpperBuff(toupper_tab, 256);
268 AnsiLowerBuff(tolower_tab, 256);
269 #endif
271 #if defined(FEAT_MBYTE) && !defined(FEAT_GUI)
272 (void)get_cmd_argsW(NULL);
273 #endif
278 * Return TRUE if the input comes from a terminal, FALSE otherwise.
281 mch_input_isatty()
283 #ifdef FEAT_GUI_MSWIN
284 return OK; /* GUI always has a tty */
285 #else
286 if (isatty(read_cmd_fd))
287 return TRUE;
288 return FALSE;
289 #endif
292 #ifdef FEAT_TITLE
294 * mch_settitle(): set titlebar of our window
296 void
297 mch_settitle(
298 char_u *title,
299 char_u *icon)
301 # ifdef FEAT_GUI_MSWIN
302 gui_mch_settitle(title, icon);
303 # else
304 if (title != NULL)
306 # ifdef FEAT_MBYTE
307 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
309 /* Convert the title from 'encoding' to the active codepage. */
310 WCHAR *wp = enc_to_ucs2(title, NULL);
311 int n;
313 if (wp != NULL)
315 n = SetConsoleTitleW(wp);
316 vim_free(wp);
317 if (n != 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
318 return;
321 # endif
322 SetConsoleTitle(title);
324 # endif
329 * Restore the window/icon title.
330 * which is one of:
331 * 1: Just restore title
332 * 2: Just restore icon (which we don't have)
333 * 3: Restore title and icon (which we don't have)
335 /*ARGSUSED*/
336 void
337 mch_restore_title(
338 int which)
340 #ifndef FEAT_GUI_MSWIN
341 mch_settitle((which & 1) ? g_szOrigTitle : NULL, NULL);
342 #endif
347 * Return TRUE if we can restore the title (we can)
350 mch_can_restore_title()
352 return TRUE;
357 * Return TRUE if we can restore the icon title (we can't)
360 mch_can_restore_icon()
362 return FALSE;
364 #endif /* FEAT_TITLE */
368 * Get absolute file name into buffer "buf" of length "len" bytes,
369 * turning all '/'s into '\\'s and getting the correct case of each component
370 * of the file name. Append a (back)slash to a directory name.
371 * When 'shellslash' set do it the other way around.
372 * Return OK or FAIL.
374 /*ARGSUSED*/
376 mch_FullName(
377 char_u *fname,
378 char_u *buf,
379 int len,
380 int force)
382 int nResult = FAIL;
384 #ifdef __BORLANDC__
385 if (*fname == NUL) /* Borland behaves badly here - make it consistent */
386 nResult = mch_dirname(buf, len);
387 else
388 #endif
390 #ifdef FEAT_MBYTE
391 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
392 # ifdef __BORLANDC__
393 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
394 && g_PlatformId == VER_PLATFORM_WIN32_NT
395 # endif
398 WCHAR *wname;
399 WCHAR wbuf[MAX_PATH];
400 char_u *cname = NULL;
402 /* Use the wide function:
403 * - convert the fname from 'encoding' to UCS2.
404 * - invoke _wfullpath()
405 * - convert the result from UCS2 to 'encoding'.
407 wname = enc_to_ucs2(fname, NULL);
408 if (wname != NULL && _wfullpath(wbuf, wname, MAX_PATH - 1) != NULL)
410 cname = ucs2_to_enc((short_u *)wbuf, NULL);
411 if (cname != NULL)
413 vim_strncpy(buf, cname, len - 1);
414 nResult = OK;
417 vim_free(wname);
418 vim_free(cname);
420 if (nResult == FAIL) /* fall back to non-wide function */
421 #endif
423 if (_fullpath(buf, fname, len - 1) == NULL)
425 /* failed, use relative path name */
426 vim_strncpy(buf, fname, len - 1);
428 else
429 nResult = OK;
433 #ifdef USE_FNAME_CASE
434 fname_case(buf, len);
435 #else
436 slash_adjust(buf);
437 #endif
439 return nResult;
444 * Return TRUE if "fname" does not depend on the current directory.
447 mch_isFullName(char_u *fname)
449 char szName[_MAX_PATH + 1];
451 /* A name like "d:/foo" and "//server/share" is absolute */
452 if ((fname[0] && fname[1] == ':' && (fname[2] == '/' || fname[2] == '\\'))
453 || (fname[0] == fname[1] && (fname[0] == '/' || fname[0] == '\\')))
454 return TRUE;
456 /* A name that can't be made absolute probably isn't absolute. */
457 if (mch_FullName(fname, szName, _MAX_PATH, FALSE) == FAIL)
458 return FALSE;
460 return pathcmp(fname, szName, -1) == 0;
464 * Replace all slashes by backslashes.
465 * This used to be the other way around, but MS-DOS sometimes has problems
466 * with slashes (e.g. in a command name). We can't have mixed slashes and
467 * backslashes, because comparing file names will not work correctly. The
468 * commands that use a file name should try to avoid the need to type a
469 * backslash twice.
470 * When 'shellslash' set do it the other way around.
472 void
473 slash_adjust(p)
474 char_u *p;
476 while (*p)
478 if (*p == psepcN)
479 *p = psepc;
480 mb_ptr_adv(p);
486 * stat() can't handle a trailing '/' or '\', remove it first.
489 vim_stat(const char *name, struct stat *stp)
491 char buf[_MAX_PATH + 1];
492 char *p;
494 vim_strncpy((char_u *)buf, (char_u *)name, _MAX_PATH);
495 p = buf + strlen(buf);
496 if (p > buf)
497 mb_ptr_back(buf, p);
498 if (p > buf && (*p == '\\' || *p == '/') && p[-1] != ':')
499 *p = NUL;
500 #ifdef FEAT_MBYTE
501 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
502 # ifdef __BORLANDC__
503 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
504 && g_PlatformId == VER_PLATFORM_WIN32_NT
505 # endif
508 WCHAR *wp = enc_to_ucs2(buf, NULL);
509 int n;
511 if (wp != NULL)
513 n = _wstat(wp, (struct _stat *)stp);
514 vim_free(wp);
515 if (n >= 0)
516 return n;
517 /* Retry with non-wide function (for Windows 98). Can't use
518 * GetLastError() here and it's unclear what errno gets set to if
519 * the _wstat() fails for missing wide functions. */
522 #endif
523 return stat(buf, stp);
526 #if defined(FEAT_GUI_MSWIN) || defined(PROTO)
527 /*ARGSUSED*/
528 void
529 mch_settmode(int tmode)
531 /* nothing to do */
535 mch_get_shellsize(void)
537 /* never used */
538 return OK;
541 void
542 mch_set_shellsize(void)
544 /* never used */
548 * Rows and/or Columns has changed.
550 void
551 mch_new_shellsize(void)
553 /* never used */
556 #endif
559 * We have no job control, so fake it by starting a new shell.
561 void
562 mch_suspend()
564 suspend_shell();
567 #if defined(USE_MCH_ERRMSG) || defined(PROTO)
569 #ifdef display_errors
570 # undef display_errors
571 #endif
574 * Display the saved error message(s).
576 void
577 display_errors()
579 char *p;
581 if (error_ga.ga_data != NULL)
583 /* avoid putting up a message box with blanks only */
584 for (p = (char *)error_ga.ga_data; *p; ++p)
585 if (!isspace(*p))
587 (void)gui_mch_dialog(
588 #ifdef FEAT_GUI
589 gui.starting ? VIM_INFO :
590 #endif
591 VIM_ERROR,
592 #ifdef FEAT_GUI
593 gui.starting ? (char_u *)_("Message") :
594 #endif
595 (char_u *)_("Error"),
596 p, (char_u *)_("&Ok"), 1, NULL);
597 break;
599 ga_clear(&error_ga);
602 #endif
606 * Return TRUE if "p" contain a wildcard that can be expanded by
607 * dos_expandpath().
610 mch_has_exp_wildcard(char_u *p)
612 for ( ; *p; mb_ptr_adv(p))
614 if (vim_strchr((char_u *)"?*[", *p) != NULL
615 || (*p == '~' && p[1] != NUL))
616 return TRUE;
618 return FALSE;
622 * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a
623 * shortened file name).
626 mch_has_wildcard(char_u *p)
628 for ( ; *p; mb_ptr_adv(p))
630 if (vim_strchr((char_u *)
631 # ifdef VIM_BACKTICK
632 "?*$[`"
633 # else
634 "?*$["
635 # endif
636 , *p) != NULL
637 || (*p == '~' && p[1] != NUL))
638 return TRUE;
640 return FALSE;
645 * The normal _chdir() does not change the default drive. This one does.
646 * Returning 0 implies success; -1 implies failure.
649 mch_chdir(char *path)
651 if (path[0] == NUL) /* just checking... */
652 return -1;
654 if (isalpha(path[0]) && path[1] == ':') /* has a drive name */
656 /* If we can change to the drive, skip that part of the path. If we
657 * can't then the current directory may be invalid, try using chdir()
658 * with the whole path. */
659 if (_chdrive(TOLOWER_ASC(path[0]) - 'a' + 1) == 0)
660 path += 2;
663 if (*path == NUL) /* drive name only */
664 return 0;
666 #ifdef FEAT_MBYTE
667 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
669 WCHAR *p = enc_to_ucs2(path, NULL);
670 int n;
672 if (p != NULL)
674 n = _wchdir(p);
675 vim_free(p);
676 if (n == 0)
677 return 0;
678 /* Retry with non-wide function (for Windows 98). */
681 #endif
683 return chdir(path); /* let the normal chdir() do the rest */
688 * Switching off termcap mode is only allowed when Columns is 80, otherwise a
689 * crash may result. It's always allowed on NT or when running the GUI.
691 /*ARGSUSED*/
693 can_end_termcap_mode(
694 int give_msg)
696 #ifdef FEAT_GUI_MSWIN
697 return TRUE; /* GUI starts a new console anyway */
698 #else
699 if (g_PlatformId == VER_PLATFORM_WIN32_NT || Columns == 80)
700 return TRUE;
701 if (give_msg)
702 msg(_("'columns' is not 80, cannot execute external commands"));
703 return FALSE;
704 #endif
707 #ifdef FEAT_GUI_MSWIN
709 * return non-zero if a character is available
712 mch_char_avail()
714 /* never used */
715 return TRUE;
717 #endif
721 * set screen mode, always fails.
723 /*ARGSUSED*/
725 mch_screenmode(
726 char_u *arg)
728 EMSG(_(e_screenmode));
729 return FAIL;
733 #if defined(FEAT_LIBCALL) || defined(PROTO)
735 * Call a DLL routine which takes either a string or int param
736 * and returns an allocated string.
737 * Return OK if it worked, FAIL if not.
739 # ifdef WIN3264
740 typedef LPTSTR (*MYSTRPROCSTR)(LPTSTR);
741 typedef LPTSTR (*MYINTPROCSTR)(int);
742 typedef int (*MYSTRPROCINT)(LPTSTR);
743 typedef int (*MYINTPROCINT)(int);
744 # else
745 typedef LPSTR (*MYSTRPROCSTR)(LPSTR);
746 typedef LPSTR (*MYINTPROCSTR)(int);
747 typedef int (*MYSTRPROCINT)(LPSTR);
748 typedef int (*MYINTPROCINT)(int);
749 # endif
751 # ifndef WIN16
753 * Check if a pointer points to a valid NUL terminated string.
754 * Return the length of the string, including terminating NUL.
755 * Returns 0 for an invalid pointer, 1 for an empty string.
757 static size_t
758 check_str_len(char_u *str)
760 SYSTEM_INFO si;
761 MEMORY_BASIC_INFORMATION mbi;
762 size_t length = 0;
763 size_t i;
764 const char *p;
766 /* get page size */
767 GetSystemInfo(&si);
769 /* get memory information */
770 if (VirtualQuery(str, &mbi, sizeof(mbi)))
772 /* pre cast these (typing savers) */
773 DWORD dwStr = (DWORD)str;
774 DWORD dwBaseAddress = (DWORD)mbi.BaseAddress;
776 /* get start address of page that str is on */
777 DWORD strPage = dwStr - (dwStr - dwBaseAddress) % si.dwPageSize;
779 /* get length from str to end of page */
780 DWORD pageLength = si.dwPageSize - (dwStr - strPage);
782 for (p = str; !IsBadReadPtr(p, pageLength);
783 p += pageLength, pageLength = si.dwPageSize)
784 for (i = 0; i < pageLength; ++i, ++length)
785 if (p[i] == NUL)
786 return length + 1;
789 return 0;
791 # endif
794 mch_libcall(
795 char_u *libname,
796 char_u *funcname,
797 char_u *argstring, /* NULL when using a argint */
798 int argint,
799 char_u **string_result,/* NULL when using number_result */
800 int *number_result)
802 HINSTANCE hinstLib;
803 MYSTRPROCSTR ProcAdd;
804 MYINTPROCSTR ProcAddI;
805 char_u *retval_str = NULL;
806 int retval_int = 0;
807 size_t len;
809 BOOL fRunTimeLinkSuccess = FALSE;
811 // Get a handle to the DLL module.
812 hinstLib = LoadLibrary(libname);
814 // If the handle is valid, try to get the function address.
815 if (hinstLib != NULL)
817 #ifdef HAVE_TRY_EXCEPT
818 __try
820 #endif
821 if (argstring != NULL)
823 /* Call with string argument */
824 ProcAdd = (MYSTRPROCSTR) GetProcAddress(hinstLib, funcname);
825 if ((fRunTimeLinkSuccess = (ProcAdd != NULL)) != 0)
827 if (string_result == NULL)
828 retval_int = ((MYSTRPROCINT)ProcAdd)(argstring);
829 else
830 retval_str = (ProcAdd)(argstring);
833 else
835 /* Call with number argument */
836 ProcAddI = (MYINTPROCSTR) GetProcAddress(hinstLib, funcname);
837 if ((fRunTimeLinkSuccess = (ProcAddI != NULL)) != 0)
839 if (string_result == NULL)
840 retval_int = ((MYINTPROCINT)ProcAddI)(argint);
841 else
842 retval_str = (ProcAddI)(argint);
846 // Save the string before we free the library.
847 // Assume that a "1" result is an illegal pointer.
848 if (string_result == NULL)
849 *number_result = retval_int;
850 else if (retval_str != NULL
851 # ifdef WIN16
852 && retval_str != (char_u *)1
853 && retval_str != (char_u *)-1
854 && !IsBadStringPtr(retval_str, INT_MAX)
855 && (len = strlen(retval_str) + 1) > 0
856 # else
857 && (len = check_str_len(retval_str)) > 0
858 # endif
861 *string_result = lalloc((long_u)len, TRUE);
862 if (*string_result != NULL)
863 mch_memmove(*string_result, retval_str, len);
866 #ifdef HAVE_TRY_EXCEPT
868 __except(EXCEPTION_EXECUTE_HANDLER)
870 if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW)
871 RESETSTKOFLW();
872 fRunTimeLinkSuccess = 0;
874 #endif
876 // Free the DLL module.
877 (void)FreeLibrary(hinstLib);
880 if (!fRunTimeLinkSuccess)
882 EMSG2(_(e_libcall), funcname);
883 return FAIL;
886 return OK;
888 #endif
890 #if defined(FEAT_MBYTE) || defined(PROTO)
892 * Convert an UTF-8 string to UCS-2.
893 * "instr[inlen]" is the input. "inlen" is in bytes.
894 * When "outstr" is NULL only return the number of UCS-2 words produced.
895 * Otherwise "outstr" must be a buffer of sufficient size.
896 * Returns the number of UCS-2 words produced.
899 utf8_to_ucs2(char_u *instr, int inlen, short_u *outstr, int *unconvlenp)
901 int outlen = 0;
902 char_u *p = instr;
903 int todo = inlen;
904 int l;
906 while (todo > 0)
908 /* Only convert if we have a complete sequence. */
909 l = utf_ptr2len_len(p, todo);
910 if (l > todo)
912 /* Return length of incomplete sequence. */
913 if (unconvlenp != NULL)
914 *unconvlenp = todo;
915 break;
918 if (outstr != NULL)
919 *outstr++ = utf_ptr2char(p);
920 ++outlen;
921 p += l;
922 todo -= l;
925 return outlen;
929 * Convert an UCS-2 string to UTF-8.
930 * The input is "instr[inlen]" with "inlen" in number of ucs-2 words.
931 * When "outstr" is NULL only return the required number of bytes.
932 * Otherwise "outstr" must be a buffer of sufficient size.
933 * Return the number of bytes produced.
936 ucs2_to_utf8(short_u *instr, int inlen, char_u *outstr)
938 int outlen = 0;
939 int todo = inlen;
940 short_u *p = instr;
941 int l;
943 while (todo > 0)
945 if (outstr != NULL)
947 l = utf_char2bytes(*p, outstr);
948 outstr += l;
950 else
951 l = utf_char2len(*p);
952 ++p;
953 outlen += l;
954 --todo;
957 return outlen;
961 * Call MultiByteToWideChar() and allocate memory for the result.
962 * Returns the result in "*out[*outlen]" with an extra zero appended.
963 * "outlen" is in words.
965 void
966 MultiByteToWideChar_alloc(UINT cp, DWORD flags,
967 LPCSTR in, int inlen,
968 LPWSTR *out, int *outlen)
970 *outlen = MultiByteToWideChar(cp, flags, in, inlen, 0, 0);
971 /* Add one one word to avoid a zero-length alloc(). */
972 *out = (LPWSTR)alloc(sizeof(WCHAR) * (*outlen + 1));
973 if (*out != NULL)
975 MultiByteToWideChar(cp, flags, in, inlen, *out, *outlen);
976 (*out)[*outlen] = 0;
981 * Call WideCharToMultiByte() and allocate memory for the result.
982 * Returns the result in "*out[*outlen]" with an extra NUL appended.
984 void
985 WideCharToMultiByte_alloc(UINT cp, DWORD flags,
986 LPCWSTR in, int inlen,
987 LPSTR *out, int *outlen,
988 LPCSTR def, LPBOOL useddef)
990 *outlen = WideCharToMultiByte(cp, flags, in, inlen, NULL, 0, def, useddef);
991 /* Add one one byte to avoid a zero-length alloc(). */
992 *out = alloc((unsigned)*outlen + 1);
993 if (*out != NULL)
995 WideCharToMultiByte(cp, flags, in, inlen, *out, *outlen, def, useddef);
996 (*out)[*outlen] = 0;
1000 #endif /* FEAT_MBYTE */
1002 #ifdef FEAT_CLIPBOARD
1004 * Clipboard stuff, for cutting and pasting text to other windows.
1007 /* Type used for the clipboard type of Vim's data. */
1008 typedef struct
1010 int type; /* MCHAR, MBLOCK or MLINE */
1011 int txtlen; /* length of CF_TEXT in bytes */
1012 int ucslen; /* length of CF_UNICODETEXT in words */
1013 int rawlen; /* length of clip_star.format_raw, including encoding,
1014 excluding terminating NUL */
1015 } VimClipType_t;
1018 * Make vim the owner of the current selection. Return OK upon success.
1020 /*ARGSUSED*/
1022 clip_mch_own_selection(VimClipboard *cbd)
1025 * Never actually own the clipboard. If another application sets the
1026 * clipboard, we don't want to think that we still own it.
1028 return FAIL;
1032 * Make vim NOT the owner of the current selection.
1034 /*ARGSUSED*/
1035 void
1036 clip_mch_lose_selection(VimClipboard *cbd)
1038 /* Nothing needs to be done here */
1042 * Copy "str[*size]" into allocated memory, changing CR-NL to NL.
1043 * Return the allocated result and the size in "*size".
1044 * Returns NULL when out of memory.
1046 static char_u *
1047 crnl_to_nl(const char_u *str, int *size)
1049 int pos = 0;
1050 int str_len = *size;
1051 char_u *ret;
1052 char_u *retp;
1054 /* Avoid allocating zero bytes, it generates an error message. */
1055 ret = lalloc((long_u)(str_len == 0 ? 1 : str_len), TRUE);
1056 if (ret != NULL)
1058 retp = ret;
1059 for (pos = 0; pos < str_len; ++pos)
1061 if (str[pos] == '\r' && str[pos + 1] == '\n')
1063 ++pos;
1064 --(*size);
1066 *retp++ = str[pos];
1070 return ret;
1073 #if defined(FEAT_MBYTE) || defined(PROTO)
1075 * Note: the following two functions are only guaranteed to work when using
1076 * valid MS-Windows codepages or when iconv() is available.
1080 * Convert "str" from 'encoding' to UCS-2.
1081 * Input in "str" with length "*lenp". When "lenp" is NULL, use strlen().
1082 * Output is returned as an allocated string. "*lenp" is set to the length of
1083 * the result. A trailing NUL is always added.
1084 * Returns NULL when out of memory.
1086 short_u *
1087 enc_to_ucs2(char_u *str, int *lenp)
1089 vimconv_T conv;
1090 WCHAR *ret;
1091 char_u *allocbuf = NULL;
1092 int len_loc;
1093 int length;
1095 if (lenp == NULL)
1097 len_loc = (int)STRLEN(str) + 1;
1098 lenp = &len_loc;
1101 if (enc_codepage > 0)
1103 /* We can do any CP### -> UCS-2 in one pass, and we can do it
1104 * without iconv() (convert_* may need iconv). */
1105 MultiByteToWideChar_alloc(enc_codepage, 0, str, *lenp, &ret, &length);
1107 else
1109 /* Use "latin1" by default, we might be called before we have p_enc
1110 * set up. Convert to utf-8 first, works better with iconv(). Does
1111 * nothing if 'encoding' is "utf-8". */
1112 conv.vc_type = CONV_NONE;
1113 if (convert_setup(&conv, p_enc ? p_enc : (char_u *)"latin1",
1114 (char_u *)"utf-8") == FAIL)
1115 return NULL;
1116 if (conv.vc_type != CONV_NONE)
1118 str = allocbuf = string_convert(&conv, str, lenp);
1119 if (str == NULL)
1120 return NULL;
1122 convert_setup(&conv, NULL, NULL);
1124 length = utf8_to_ucs2(str, *lenp, NULL, NULL);
1125 ret = (WCHAR *)alloc((unsigned)((length + 1) * sizeof(WCHAR)));
1126 if (ret != NULL)
1128 utf8_to_ucs2(str, *lenp, (short_u *)ret, NULL);
1129 ret[length] = 0;
1132 vim_free(allocbuf);
1135 *lenp = length;
1136 return (short_u *)ret;
1140 * Convert an UCS-2 string to 'encoding'.
1141 * Input in "str" with length (counted in wide characters) "*lenp". When
1142 * "lenp" is NULL, use wcslen().
1143 * Output is returned as an allocated string. If "*lenp" is not NULL it is
1144 * set to the length of the result.
1145 * Returns NULL when out of memory.
1147 char_u *
1148 ucs2_to_enc(short_u *str, int *lenp)
1150 vimconv_T conv;
1151 char_u *utf8_str = NULL, *enc_str = NULL;
1152 int len_loc;
1154 if (lenp == NULL)
1156 len_loc = (int)wcslen(str) + 1;
1157 lenp = &len_loc;
1160 if (enc_codepage > 0)
1162 /* We can do any UCS-2 -> CP### in one pass. */
1163 int length;
1165 WideCharToMultiByte_alloc(enc_codepage, 0, str, *lenp,
1166 (LPSTR *)&enc_str, &length, 0, 0);
1167 *lenp = length;
1168 return enc_str;
1171 /* Avoid allocating zero bytes, it generates an error message. */
1172 utf8_str = alloc(ucs2_to_utf8(str, *lenp == 0 ? 1 : *lenp, NULL));
1173 if (utf8_str != NULL)
1175 *lenp = ucs2_to_utf8(str, *lenp, utf8_str);
1177 /* We might be called before we have p_enc set up. */
1178 conv.vc_type = CONV_NONE;
1179 convert_setup(&conv, (char_u *)"utf-8",
1180 p_enc? p_enc: (char_u *)"latin1");
1181 if (conv.vc_type == CONV_NONE)
1183 /* p_enc is utf-8, so we're done. */
1184 enc_str = utf8_str;
1186 else
1188 enc_str = string_convert(&conv, utf8_str, lenp);
1189 vim_free(utf8_str);
1192 convert_setup(&conv, NULL, NULL);
1195 return enc_str;
1197 #endif /* FEAT_MBYTE */
1200 * Get the current selection and put it in the clipboard register.
1202 * NOTE: Must use GlobalLock/Unlock here to ensure Win32s compatibility.
1203 * On NT/W95 the clipboard data is a fixed global memory object and
1204 * so its handle = its pointer.
1205 * On Win32s, however, co-operation with the Win16 system means that
1206 * the clipboard data is moveable and its handle is not a pointer at all,
1207 * so we can't just cast the return value of GetClipboardData to (char_u*).
1208 * <VN>
1210 void
1211 clip_mch_request_selection(VimClipboard *cbd)
1213 VimClipType_t metadata = { -1, -1, -1, -1 };
1214 HGLOBAL hMem = NULL;
1215 char_u *str = NULL;
1216 #if defined(FEAT_MBYTE) && defined(WIN3264)
1217 char_u *to_free = NULL;
1218 #endif
1219 #ifdef FEAT_MBYTE
1220 HGLOBAL rawh = NULL;
1221 #endif
1222 int str_size = 0;
1223 int maxlen;
1224 size_t n;
1227 * Don't pass GetActiveWindow() as an argument to OpenClipboard() because
1228 * then we can't paste back into the same window for some reason - webb.
1230 if (!OpenClipboard(NULL))
1231 return;
1233 /* Check for vim's own clipboard format first. This only gets the type of
1234 * the data, still need to use CF_UNICODETEXT or CF_TEXT for the text. */
1235 if (IsClipboardFormatAvailable(cbd->format))
1237 VimClipType_t *meta_p;
1238 HGLOBAL meta_h;
1240 /* We have metadata on the clipboard; try to get it. */
1241 if ((meta_h = GetClipboardData(cbd->format)) != NULL
1242 && (meta_p = (VimClipType_t *)GlobalLock(meta_h)) != NULL)
1244 /* The size of "VimClipType_t" changed, "rawlen" was added later.
1245 * Only copy what is available for backwards compatibility. */
1246 n = sizeof(VimClipType_t);
1247 if (GlobalSize(meta_h) < n)
1248 n = GlobalSize(meta_h);
1249 memcpy(&metadata, meta_p, n);
1250 GlobalUnlock(meta_h);
1254 #ifdef FEAT_MBYTE
1255 /* Check for Vim's raw clipboard format first. This is used without
1256 * conversion, but only if 'encoding' matches. */
1257 if (IsClipboardFormatAvailable(cbd->format_raw)
1258 && metadata.rawlen > (int)STRLEN(p_enc))
1260 /* We have raw data on the clipboard; try to get it. */
1261 if ((rawh = GetClipboardData(cbd->format_raw)) != NULL)
1263 char_u *rawp;
1265 rawp = (char_u *)GlobalLock(rawh);
1266 if (rawp != NULL && STRCMP(p_enc, rawp) == 0)
1268 n = STRLEN(p_enc) + 1;
1269 str = rawp + n;
1270 str_size = (int)(metadata.rawlen - n);
1272 else
1274 GlobalUnlock(rawh);
1275 rawh = NULL;
1279 if (str == NULL)
1281 #endif
1283 #if defined(FEAT_MBYTE) && defined(WIN3264)
1284 /* Try to get the clipboard in Unicode if it's not an empty string. */
1285 if (IsClipboardFormatAvailable(CF_UNICODETEXT) && metadata.ucslen != 0)
1287 HGLOBAL hMemW;
1289 if ((hMemW = GetClipboardData(CF_UNICODETEXT)) != NULL)
1291 WCHAR *hMemWstr = (WCHAR *)GlobalLock(hMemW);
1293 /* Use the length of our metadata if possible, but limit it to the
1294 * GlobalSize() for safety. */
1295 maxlen = (int)(GlobalSize(hMemW) / sizeof(WCHAR));
1296 if (metadata.ucslen >= 0)
1298 if (metadata.ucslen > maxlen)
1299 str_size = maxlen;
1300 else
1301 str_size = metadata.ucslen;
1303 else
1305 for (str_size = 0; str_size < maxlen; ++str_size)
1306 if (hMemWstr[str_size] == NUL)
1307 break;
1309 to_free = str = ucs2_to_enc((short_u *)hMemWstr, &str_size);
1310 GlobalUnlock(hMemW);
1313 else
1314 #endif
1315 /* Get the clipboard in the Active codepage. */
1316 if (IsClipboardFormatAvailable(CF_TEXT))
1318 if ((hMem = GetClipboardData(CF_TEXT)) != NULL)
1320 str = (char_u *)GlobalLock(hMem);
1322 /* The length is either what our metadata says or the strlen().
1323 * But limit it to the GlobalSize() for safety. */
1324 maxlen = (int)GlobalSize(hMem);
1325 if (metadata.txtlen >= 0)
1327 if (metadata.txtlen > maxlen)
1328 str_size = maxlen;
1329 else
1330 str_size = metadata.txtlen;
1332 else
1334 for (str_size = 0; str_size < maxlen; ++str_size)
1335 if (str[str_size] == NUL)
1336 break;
1339 # if defined(FEAT_MBYTE) && defined(WIN3264)
1340 /* The text is in the active codepage. Convert to 'encoding',
1341 * going through UCS-2. */
1342 acp_to_enc(str, str_size, &to_free, &maxlen);
1343 if (to_free != NULL)
1345 str_size = maxlen;
1346 str = to_free;
1348 # endif
1351 #ifdef FEAT_MBYTE
1353 #endif
1355 if (str != NULL && *str != NUL)
1357 char_u *temp_clipboard;
1359 /* If the type is not known guess it. */
1360 if (metadata.type == -1)
1361 metadata.type = (vim_strchr(str, '\n') == NULL) ? MCHAR : MLINE;
1363 /* Translate <CR><NL> into <NL>. */
1364 temp_clipboard = crnl_to_nl(str, &str_size);
1365 if (temp_clipboard != NULL)
1367 clip_yank_selection(metadata.type, temp_clipboard, str_size, cbd);
1368 vim_free(temp_clipboard);
1372 /* unlock the global object */
1373 if (hMem != NULL)
1374 GlobalUnlock(hMem);
1375 #ifdef FEAT_MBYTE
1376 if (rawh != NULL)
1377 GlobalUnlock(rawh);
1378 #endif
1379 CloseClipboard();
1380 #if defined(FEAT_MBYTE) && defined(WIN3264)
1381 vim_free(to_free);
1382 #endif
1385 #if (defined(FEAT_MBYTE) && defined(WIN3264)) || defined(PROTO)
1387 * Convert from the active codepage to 'encoding'.
1388 * Input is "str[str_size]".
1389 * The result is in allocated memory: "out[outlen]". With terminating NUL.
1391 void
1392 acp_to_enc(str, str_size, out, outlen)
1393 char_u *str;
1394 int str_size;
1395 char_u **out;
1396 int *outlen;
1399 LPWSTR widestr;
1401 MultiByteToWideChar_alloc(GetACP(), 0, str, str_size, &widestr, outlen);
1402 if (widestr != NULL)
1404 ++*outlen; /* Include the 0 after the string */
1405 *out = ucs2_to_enc((short_u *)widestr, outlen);
1406 vim_free(widestr);
1409 #endif
1412 * Send the current selection to the clipboard.
1414 void
1415 clip_mch_set_selection(VimClipboard *cbd)
1417 char_u *str = NULL;
1418 VimClipType_t metadata;
1419 long_u txtlen;
1420 HGLOBAL hMemRaw = NULL;
1421 HGLOBAL hMem = NULL;
1422 HGLOBAL hMemVim = NULL;
1423 # if defined(FEAT_MBYTE) && defined(WIN3264)
1424 HGLOBAL hMemW = NULL;
1425 # endif
1427 /* If the '*' register isn't already filled in, fill it in now */
1428 cbd->owned = TRUE;
1429 clip_get_selection(cbd);
1430 cbd->owned = FALSE;
1432 /* Get the text to be put on the clipboard, with CR-LF. */
1433 metadata.type = clip_convert_selection(&str, &txtlen, cbd);
1434 if (metadata.type < 0)
1435 return;
1436 metadata.txtlen = (int)txtlen;
1437 metadata.ucslen = 0;
1438 metadata.rawlen = 0;
1440 #ifdef FEAT_MBYTE
1441 /* Always set the raw bytes: 'encoding', NUL and the text. This is used
1442 * when copy/paste from/to Vim with the same 'encoding', so that illegal
1443 * bytes can also be copied and no conversion is needed. */
1445 LPSTR lpszMemRaw;
1447 metadata.rawlen = (int)(txtlen + STRLEN(p_enc) + 1);
1448 hMemRaw = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1449 metadata.rawlen + 1);
1450 lpszMemRaw = (LPSTR)GlobalLock(hMemRaw);
1451 if (lpszMemRaw != NULL)
1453 STRCPY(lpszMemRaw, p_enc);
1454 memcpy(lpszMemRaw + STRLEN(p_enc) + 1, str, txtlen + 1);
1455 GlobalUnlock(hMemRaw);
1457 else
1458 metadata.rawlen = 0;
1460 #endif
1462 # if defined(FEAT_MBYTE) && defined(WIN3264)
1464 WCHAR *out;
1465 int len = metadata.txtlen;
1467 /* Convert the text to UCS-2. This is put on the clipboard as
1468 * CF_UNICODETEXT. */
1469 out = (WCHAR *)enc_to_ucs2(str, &len);
1470 if (out != NULL)
1472 WCHAR *lpszMemW;
1474 /* Convert the text for CF_TEXT to Active codepage. Otherwise it's
1475 * p_enc, which has no relation to the Active codepage. */
1476 metadata.txtlen = WideCharToMultiByte(GetACP(), 0, out, len,
1477 NULL, 0, 0, 0);
1478 vim_free(str);
1479 str = (char_u *)alloc((unsigned)(metadata.txtlen == 0 ? 1
1480 : metadata.txtlen));
1481 if (str == NULL)
1483 vim_free(out);
1484 return; /* out of memory */
1486 WideCharToMultiByte(GetACP(), 0, out, len,
1487 str, metadata.txtlen, 0, 0);
1489 /* Allocate memory for the UCS-2 text, add one NUL word to
1490 * terminate the string. */
1491 hMemW = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1492 (len + 1) * sizeof(WCHAR));
1493 lpszMemW = (WCHAR *)GlobalLock(hMemW);
1494 if (lpszMemW != NULL)
1496 memcpy(lpszMemW, out, len * sizeof(WCHAR));
1497 lpszMemW[len] = NUL;
1498 GlobalUnlock(hMemW);
1500 vim_free(out);
1501 metadata.ucslen = len;
1504 # endif
1506 /* Allocate memory for the text, add one NUL byte to terminate the string.
1508 hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, metadata.txtlen + 1);
1510 LPSTR lpszMem = (LPSTR)GlobalLock(hMem);
1512 if (lpszMem)
1514 vim_strncpy(lpszMem, str, metadata.txtlen);
1515 GlobalUnlock(hMem);
1519 /* Set up metadata: */
1521 VimClipType_t *lpszMemVim = NULL;
1523 hMemVim = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,
1524 sizeof(VimClipType_t));
1525 lpszMemVim = (VimClipType_t *)GlobalLock(hMemVim);
1526 memcpy(lpszMemVim, &metadata, sizeof(metadata));
1527 GlobalUnlock(hMemVim);
1531 * Open the clipboard, clear it and put our text on it.
1532 * Always set our Vim format. Put Unicode and plain text on it.
1534 * Don't pass GetActiveWindow() as an argument to OpenClipboard()
1535 * because then we can't paste back into the same window for some
1536 * reason - webb.
1538 if (OpenClipboard(NULL))
1540 if (EmptyClipboard())
1542 SetClipboardData(cbd->format, hMemVim);
1543 hMemVim = 0;
1544 # if defined(FEAT_MBYTE) && defined(WIN3264)
1545 if (hMemW != NULL)
1547 if (SetClipboardData(CF_UNICODETEXT, hMemW) != NULL)
1548 hMemW = NULL;
1550 # endif
1551 /* Always use CF_TEXT. On Win98 Notepad won't obtain the
1552 * CF_UNICODETEXT text, only CF_TEXT. */
1553 SetClipboardData(CF_TEXT, hMem);
1554 hMem = 0;
1556 CloseClipboard();
1559 vim_free(str);
1560 /* Free any allocations we didn't give to the clipboard: */
1561 if (hMemRaw)
1562 GlobalFree(hMemRaw);
1563 if (hMem)
1564 GlobalFree(hMem);
1565 # if defined(FEAT_MBYTE) && defined(WIN3264)
1566 if (hMemW)
1567 GlobalFree(hMemW);
1568 # endif
1569 if (hMemVim)
1570 GlobalFree(hMemVim);
1573 #endif /* FEAT_CLIPBOARD */
1577 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
1579 /*ARGSUSED*/
1580 void
1581 DumpPutS(
1582 const char *psz)
1584 # ifdef MCH_WRITE_DUMP
1585 if (fdDump)
1587 fputs(psz, fdDump);
1588 if (psz[strlen(psz) - 1] != '\n')
1589 fputc('\n', fdDump);
1590 fflush(fdDump);
1592 # endif
1595 #ifdef _DEBUG
1597 void __cdecl
1598 Trace(
1599 char *pszFormat,
1600 ...)
1602 CHAR szBuff[2048];
1603 va_list args;
1605 va_start(args, pszFormat);
1606 vsprintf(szBuff, pszFormat, args);
1607 va_end(args);
1609 OutputDebugString(szBuff);
1612 #endif //_DEBUG
1614 #if !defined(FEAT_GUI) || defined(PROTO)
1615 # if defined(FEAT_TITLE) && defined(WIN3264)
1616 extern HWND g_hWnd; /* This is in os_win32.c. */
1617 # endif
1620 * Showing the printer dialog is tricky since we have no GUI
1621 * window to parent it. The following routines are needed to
1622 * get the window parenting and Z-order to work properly.
1624 static void
1625 GetConsoleHwnd(void)
1627 # define MY_BUFSIZE 1024 // Buffer size for console window titles.
1629 char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
1630 char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
1632 /* Skip if it's already set. */
1633 if (s_hwnd != 0)
1634 return;
1636 # if defined(FEAT_TITLE) && defined(WIN3264)
1637 /* Window handle may have been found by init code (Windows NT only) */
1638 if (g_hWnd != 0)
1640 s_hwnd = g_hWnd;
1641 return;
1643 # endif
1645 GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
1647 wsprintf(pszNewWindowTitle, "%s/%d/%d",
1648 pszOldWindowTitle,
1649 GetTickCount(),
1650 GetCurrentProcessId());
1651 SetConsoleTitle(pszNewWindowTitle);
1652 Sleep(40);
1653 s_hwnd = FindWindow(NULL, pszNewWindowTitle);
1655 SetConsoleTitle(pszOldWindowTitle);
1659 * Console implementation of ":winpos".
1662 mch_get_winpos(int *x, int *y)
1664 RECT rect;
1666 GetConsoleHwnd();
1667 GetWindowRect(s_hwnd, &rect);
1668 *x = rect.left;
1669 *y = rect.top;
1670 return OK;
1674 * Console implementation of ":winpos x y".
1676 void
1677 mch_set_winpos(int x, int y)
1679 GetConsoleHwnd();
1680 SetWindowPos(s_hwnd, NULL, x, y, 0, 0,
1681 SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1683 #endif
1685 #if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1687 # ifdef WIN16
1688 # define TEXT(a) a
1689 # endif
1690 /*=================================================================
1691 * Win32 printer stuff
1694 static HFONT prt_font_handles[2][2][2];
1695 static PRINTDLG prt_dlg;
1696 static const int boldface[2] = {FW_REGULAR, FW_BOLD};
1697 static TEXTMETRIC prt_tm;
1698 static int prt_line_height;
1699 static int prt_number_width;
1700 static int prt_left_margin;
1701 static int prt_right_margin;
1702 static int prt_top_margin;
1703 static char_u szAppName[] = TEXT("VIM");
1704 static HWND hDlgPrint;
1705 static int *bUserAbort = NULL;
1706 static char_u *prt_name = NULL;
1708 /* Defines which are also in vim.rc. */
1709 #define IDC_BOX1 400
1710 #define IDC_PRINTTEXT1 401
1711 #define IDC_PRINTTEXT2 402
1712 #define IDC_PROGRESS 403
1715 * Convert BGR to RGB for Windows GDI calls
1717 static COLORREF
1718 swap_me(COLORREF colorref)
1720 int temp;
1721 char *ptr = (char *)&colorref;
1723 temp = *(ptr);
1724 *(ptr ) = *(ptr + 2);
1725 *(ptr + 2) = temp;
1726 return colorref;
1729 /*ARGSUSED*/
1730 static BOOL CALLBACK
1731 PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
1733 #ifdef FEAT_GETTEXT
1734 NONCLIENTMETRICS nm;
1735 static HFONT hfont;
1736 #endif
1738 switch (message)
1740 case WM_INITDIALOG:
1741 #ifdef FEAT_GETTEXT
1742 nm.cbSize = sizeof(NONCLIENTMETRICS);
1743 if (SystemParametersInfo(
1744 SPI_GETNONCLIENTMETRICS,
1745 sizeof(NONCLIENTMETRICS),
1746 &nm,
1749 char buff[MAX_PATH];
1750 int i;
1752 /* Translate the dialog texts */
1753 hfont = CreateFontIndirect(&nm.lfMessageFont);
1754 for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++)
1756 SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1);
1757 if (GetDlgItemText(hDlg,i, buff, sizeof(buff)))
1758 SetDlgItemText(hDlg,i, _(buff));
1760 SendDlgItemMessage(hDlg, IDCANCEL,
1761 WM_SETFONT, (WPARAM)hfont, 1);
1762 if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff)))
1763 SetDlgItemText(hDlg,IDCANCEL, _(buff));
1765 #endif
1766 SetWindowText(hDlg, szAppName);
1767 if (prt_name != NULL)
1769 SetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name);
1770 vim_free(prt_name);
1771 prt_name = NULL;
1773 EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED);
1774 #ifndef FEAT_GUI
1775 BringWindowToTop(s_hwnd);
1776 #endif
1777 return TRUE;
1779 case WM_COMMAND:
1780 *bUserAbort = TRUE;
1781 EnableWindow(GetParent(hDlg), TRUE);
1782 DestroyWindow(hDlg);
1783 hDlgPrint = NULL;
1784 #ifdef FEAT_GETTEXT
1785 DeleteObject(hfont);
1786 #endif
1787 return TRUE;
1789 return FALSE;
1792 /*ARGSUSED*/
1793 static BOOL CALLBACK
1794 AbortProc(HDC hdcPrn, int iCode)
1796 MSG msg;
1798 while (!*bUserAbort && PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1800 if (!hDlgPrint || !IsDialogMessage(hDlgPrint, &msg))
1802 TranslateMessage(&msg);
1803 DispatchMessage(&msg);
1806 return !*bUserAbort;
1809 #ifndef FEAT_GUI
1811 static UINT CALLBACK
1812 PrintHookProc(
1813 HWND hDlg, // handle to dialog box
1814 UINT uiMsg, // message identifier
1815 WPARAM wParam, // message parameter
1816 LPARAM lParam // message parameter
1819 HWND hwndOwner;
1820 RECT rc, rcDlg, rcOwner;
1821 PRINTDLG *pPD;
1823 if (uiMsg == WM_INITDIALOG)
1825 // Get the owner window and dialog box rectangles.
1826 if ((hwndOwner = GetParent(hDlg)) == NULL)
1827 hwndOwner = GetDesktopWindow();
1829 GetWindowRect(hwndOwner, &rcOwner);
1830 GetWindowRect(hDlg, &rcDlg);
1831 CopyRect(&rc, &rcOwner);
1833 // Offset the owner and dialog box rectangles so that
1834 // right and bottom values represent the width and
1835 // height, and then offset the owner again to discard
1836 // space taken up by the dialog box.
1838 OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
1839 OffsetRect(&rc, -rc.left, -rc.top);
1840 OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
1842 // The new position is the sum of half the remaining
1843 // space and the owner's original position.
1845 SetWindowPos(hDlg,
1846 HWND_TOP,
1847 rcOwner.left + (rc.right / 2),
1848 rcOwner.top + (rc.bottom / 2),
1849 0, 0, // ignores size arguments
1850 SWP_NOSIZE);
1852 /* tackle the printdlg copiesctrl problem */
1853 pPD = (PRINTDLG *)lParam;
1854 pPD->nCopies = (WORD)pPD->lCustData;
1855 SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE );
1856 /* Bring the window to top */
1857 BringWindowToTop(GetParent(hDlg));
1858 SetForegroundWindow(hDlg);
1861 return FALSE;
1863 #endif
1865 void
1866 mch_print_cleanup(void)
1868 int pifItalic;
1869 int pifBold;
1870 int pifUnderline;
1872 for (pifBold = 0; pifBold <= 1; pifBold++)
1873 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1874 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1875 DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]);
1877 if (prt_dlg.hDC != NULL)
1878 DeleteDC(prt_dlg.hDC);
1879 if (!*bUserAbort)
1880 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1883 static int
1884 to_device_units(int idx, int dpi, int physsize, int offset, int def_number)
1886 int ret = 0;
1887 int u;
1888 int nr;
1890 u = prt_get_unit(idx);
1891 if (u == PRT_UNIT_NONE)
1893 u = PRT_UNIT_PERC;
1894 nr = def_number;
1896 else
1897 nr = printer_opts[idx].number;
1899 switch (u)
1901 case PRT_UNIT_PERC:
1902 ret = (physsize * nr) / 100;
1903 break;
1904 case PRT_UNIT_INCH:
1905 ret = (nr * dpi);
1906 break;
1907 case PRT_UNIT_MM:
1908 ret = (nr * 10 * dpi) / 254;
1909 break;
1910 case PRT_UNIT_POINT:
1911 ret = (nr * 10 * dpi) / 720;
1912 break;
1915 if (ret < offset)
1916 return 0;
1917 else
1918 return ret - offset;
1921 static int
1922 prt_get_cpl(void)
1924 int hr;
1925 int phyw;
1926 int dvoff;
1927 int rev_offset;
1928 int dpi;
1929 #ifdef WIN16
1930 POINT pagesize;
1931 #endif
1933 GetTextMetrics(prt_dlg.hDC, &prt_tm);
1934 prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading;
1936 hr = GetDeviceCaps(prt_dlg.hDC, HORZRES);
1937 #ifdef WIN16
1938 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1939 phyw = pagesize.x;
1940 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1941 dvoff = pagesize.x;
1942 #else
1943 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH);
1944 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX);
1945 #endif
1946 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX);
1948 rev_offset = phyw - (dvoff + hr);
1950 prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10);
1951 if (prt_use_number())
1953 prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth;
1954 prt_left_margin += prt_number_width;
1956 else
1957 prt_number_width = 0;
1959 prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw,
1960 rev_offset, 5);
1962 return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth;
1965 static int
1966 prt_get_lpp(void)
1968 int vr;
1969 int phyw;
1970 int dvoff;
1971 int rev_offset;
1972 int bottom_margin;
1973 int dpi;
1974 #ifdef WIN16
1975 POINT pagesize;
1976 #endif
1978 vr = GetDeviceCaps(prt_dlg.hDC, VERTRES);
1979 #ifdef WIN16
1980 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1981 phyw = pagesize.y;
1982 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1983 dvoff = pagesize.y;
1984 #else
1985 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT);
1986 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY);
1987 #endif
1988 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY);
1990 rev_offset = phyw - (dvoff + vr);
1992 prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5);
1994 /* adjust top margin if there is a header */
1995 prt_top_margin += prt_line_height * prt_header_height();
1997 bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw,
1998 rev_offset, 5);
2000 return (bottom_margin - prt_top_margin) / prt_line_height;
2004 mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
2006 static HGLOBAL stored_dm = NULL;
2007 static HGLOBAL stored_devn = NULL;
2008 static int stored_nCopies = 1;
2009 static int stored_nFlags = 0;
2011 LOGFONT fLogFont;
2012 int pifItalic;
2013 int pifBold;
2014 int pifUnderline;
2016 DEVMODE *mem;
2017 DEVNAMES *devname;
2018 int i;
2020 bUserAbort = &(psettings->user_abort);
2021 memset(&prt_dlg, 0, sizeof(PRINTDLG));
2022 prt_dlg.lStructSize = sizeof(PRINTDLG);
2023 #ifndef FEAT_GUI
2024 GetConsoleHwnd(); /* get value of s_hwnd */
2025 #endif
2026 prt_dlg.hwndOwner = s_hwnd;
2027 prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
2028 if (!forceit)
2030 prt_dlg.hDevMode = stored_dm;
2031 prt_dlg.hDevNames = stored_devn;
2032 prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog
2033 #ifndef FEAT_GUI
2035 * Use hook to prevent console window being sent to back
2037 prt_dlg.lpfnPrintHook = PrintHookProc;
2038 prt_dlg.Flags |= PD_ENABLEPRINTHOOK;
2039 #endif
2040 prt_dlg.Flags |= stored_nFlags;
2044 * If bang present, return default printer setup with no dialog
2045 * never show dialog if we are running over telnet
2047 if (forceit
2048 #ifndef FEAT_GUI
2049 || !term_console
2050 #endif
2053 prt_dlg.Flags |= PD_RETURNDEFAULT;
2054 #ifdef WIN3264
2056 * MSDN suggests setting the first parameter to WINSPOOL for
2057 * NT, but NULL appears to work just as well.
2059 if (*p_pdev != NUL)
2060 prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL);
2061 else
2062 #endif
2064 prt_dlg.Flags |= PD_RETURNDEFAULT;
2065 if (PrintDlg(&prt_dlg) == 0)
2066 goto init_fail_dlg;
2069 else if (PrintDlg(&prt_dlg) == 0)
2070 goto init_fail_dlg;
2071 else
2074 * keep the previous driver context
2076 stored_dm = prt_dlg.hDevMode;
2077 stored_devn = prt_dlg.hDevNames;
2078 stored_nFlags = prt_dlg.Flags;
2079 stored_nCopies = prt_dlg.nCopies;
2082 if (prt_dlg.hDC == NULL)
2084 EMSG(_("E237: Printer selection failed"));
2085 mch_print_cleanup();
2086 return FALSE;
2089 /* Not all printer drivers report the support of color (or grey) in the
2090 * same way. Let's set has_color if there appears to be some way to print
2091 * more than B&W. */
2092 i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS);
2093 psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1
2094 || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1
2095 || i > 2 || i == -1);
2097 /* Ensure all font styles are baseline aligned */
2098 SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT);
2101 * On some windows systems the nCopies parameter is not
2102 * passed back correctly. It must be retrieved from the
2103 * hDevMode struct.
2105 mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode);
2106 if (mem != NULL)
2108 #ifdef WIN3264
2109 if (mem->dmCopies != 1)
2110 stored_nCopies = mem->dmCopies;
2111 #endif
2112 if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX))
2113 psettings->duplex = TRUE;
2114 if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR))
2115 psettings->has_color = TRUE;
2117 GlobalUnlock(prt_dlg.hDevMode);
2119 devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames);
2120 if (devname != 0)
2122 char_u *printer_name = (char_u *)devname + devname->wDeviceOffset;
2123 char_u *port_name = (char_u *)devname +devname->wOutputOffset;
2124 char_u *text = _("to %s on %s");
2126 prt_name = alloc(STRLEN(printer_name) + STRLEN(port_name)
2127 + STRLEN(text));
2128 if (prt_name != NULL)
2129 wsprintf(prt_name, text, printer_name, port_name);
2131 GlobalUnlock(prt_dlg.hDevNames);
2134 * Initialise the font according to 'printfont'
2136 memset(&fLogFont, 0, sizeof(fLogFont));
2137 if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL)
2139 EMSG2(_("E613: Unknown printer font: %s"), p_pfn);
2140 mch_print_cleanup();
2141 return FALSE;
2144 for (pifBold = 0; pifBold <= 1; pifBold++)
2145 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
2146 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
2148 fLogFont.lfWeight = boldface[pifBold];
2149 fLogFont.lfItalic = pifItalic;
2150 fLogFont.lfUnderline = pifUnderline;
2151 prt_font_handles[pifBold][pifItalic][pifUnderline]
2152 = CreateFontIndirect(&fLogFont);
2155 SetBkMode(prt_dlg.hDC, OPAQUE);
2156 SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]);
2159 * Fill in the settings struct
2161 psettings->chars_per_line = prt_get_cpl();
2162 psettings->lines_per_page = prt_get_lpp();
2163 psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE)
2164 ? prt_dlg.nCopies : 1;
2165 psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE)
2166 ? 1 : prt_dlg.nCopies;
2168 if (psettings->n_collated_copies == 0)
2169 psettings->n_collated_copies = 1;
2171 if (psettings->n_uncollated_copies == 0)
2172 psettings->n_uncollated_copies = 1;
2174 psettings->jobname = jobname;
2176 return TRUE;
2178 init_fail_dlg:
2180 DWORD err = CommDlgExtendedError();
2182 if (err)
2184 #ifdef WIN16
2185 char buf[20];
2187 sprintf(buf, "%ld", err);
2188 EMSG2(_("E238: Print error: %s"), buf);
2189 #else
2190 char_u *buf;
2192 /* I suspect FormatMessage() doesn't work for values returned by
2193 * CommDlgExtendedError(). What does? */
2194 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2195 FORMAT_MESSAGE_FROM_SYSTEM |
2196 FORMAT_MESSAGE_IGNORE_INSERTS,
2197 NULL, err, 0, (LPTSTR)(&buf), 0, NULL);
2198 EMSG2(_("E238: Print error: %s"),
2199 buf == NULL ? (char_u *)_("Unknown") : buf);
2200 LocalFree((LPVOID)(buf));
2201 #endif
2203 else
2204 msg_clr_eos(); /* Maybe canceled */
2206 mch_print_cleanup();
2207 return FALSE;
2213 mch_print_begin(prt_settings_T *psettings)
2215 int ret;
2216 static DOCINFO di;
2217 char szBuffer[300];
2219 hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"),
2220 prt_dlg.hwndOwner, PrintDlgProc);
2221 #ifdef WIN16
2222 Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL);
2223 #else
2224 SetAbortProc(prt_dlg.hDC, AbortProc);
2225 #endif
2226 wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname));
2227 SetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer);
2229 memset(&di, 0, sizeof(DOCINFO));
2230 di.cbSize = sizeof(DOCINFO);
2231 di.lpszDocName = psettings->jobname;
2232 ret = StartDoc(prt_dlg.hDC, &di);
2234 #ifdef FEAT_GUI
2235 /* Give focus back to main window (when using MDI). */
2236 SetFocus(s_hwnd);
2237 #endif
2239 return (ret > 0);
2242 /*ARGSUSED*/
2243 void
2244 mch_print_end(prt_settings_T *psettings)
2246 EndDoc(prt_dlg.hDC);
2247 if (!*bUserAbort)
2248 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
2252 mch_print_end_page(void)
2254 return (EndPage(prt_dlg.hDC) > 0);
2258 mch_print_begin_page(char_u *msg)
2260 if (msg != NULL)
2261 SetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg);
2262 return (StartPage(prt_dlg.hDC) > 0);
2266 mch_print_blank_page(void)
2268 return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
2271 static int prt_pos_x = 0;
2272 static int prt_pos_y = 0;
2274 void
2275 mch_print_start_line(margin, page_line)
2276 int margin;
2277 int page_line;
2279 if (margin)
2280 prt_pos_x = -prt_number_width;
2281 else
2282 prt_pos_x = 0;
2283 prt_pos_y = page_line * prt_line_height
2284 + prt_tm.tmAscent + prt_tm.tmExternalLeading;
2288 mch_print_text_out(char_u *p, int len)
2290 #ifdef FEAT_PROPORTIONAL_FONTS
2291 SIZE sz;
2292 #endif
2294 TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin,
2295 prt_pos_y + prt_top_margin, p, len);
2296 #ifndef FEAT_PROPORTIONAL_FONTS
2297 prt_pos_x += len * prt_tm.tmAveCharWidth;
2298 return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth
2299 + prt_tm.tmOverhang > prt_right_margin);
2300 #else
2301 # ifdef WIN16
2302 GetTextExtentPoint(prt_dlg.hDC, p, len, &sz);
2303 # else
2304 GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz);
2305 # endif
2306 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
2307 /* This is wrong when printing spaces for a TAB. */
2308 if (p[len] == NUL)
2309 return FALSE;
2310 # ifdef WIN16
2311 GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz);
2312 # else
2313 GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz);
2314 # endif
2315 return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
2316 #endif
2319 void
2320 mch_print_set_font(int iBold, int iItalic, int iUnderline)
2322 SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]);
2325 void
2326 mch_print_set_bg(unsigned long bgcol)
2328 SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC, swap_me(bgcol)));
2330 * With a white background we can draw characters transparent, which is
2331 * good for italic characters that overlap to the next char cell.
2333 if (bgcol == 0xffffffUL)
2334 SetBkMode(prt_dlg.hDC, TRANSPARENT);
2335 else
2336 SetBkMode(prt_dlg.hDC, OPAQUE);
2339 void
2340 mch_print_set_fg(unsigned long fgcol)
2342 SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC, swap_me(fgcol)));
2345 #endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
2349 #if defined(FEAT_SHORTCUT) || defined(PROTO)
2350 # include <shlobj.h>
2353 * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
2354 * to and return that name in allocated memory.
2355 * Otherwise NULL is returned.
2357 char_u *
2358 mch_resolve_shortcut(char_u *fname)
2360 HRESULT hr;
2361 IShellLink *psl = NULL;
2362 IPersistFile *ppf = NULL;
2363 OLECHAR wsz[MAX_PATH];
2364 WIN32_FIND_DATA ffd; // we get those free of charge
2365 TCHAR buf[MAX_PATH]; // could have simply reused 'wsz'...
2366 char_u *rfname = NULL;
2367 int len;
2369 /* Check if the file name ends in ".lnk". Avoid calling
2370 * CoCreateInstance(), it's quite slow. */
2371 if (fname == NULL)
2372 return rfname;
2373 len = (int)STRLEN(fname);
2374 if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
2375 return rfname;
2377 CoInitialize(NULL);
2379 // create a link manager object and request its interface
2380 hr = CoCreateInstance(
2381 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2382 &IID_IShellLink, (void**)&psl);
2383 if (hr != S_OK)
2384 goto shortcut_error;
2386 // Get a pointer to the IPersistFile interface.
2387 hr = psl->lpVtbl->QueryInterface(
2388 psl, &IID_IPersistFile, (void**)&ppf);
2389 if (hr != S_OK)
2390 goto shortcut_error;
2392 // full path string must be in Unicode.
2393 MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
2395 // "load" the name and resove the link
2396 hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
2397 if (hr != S_OK)
2398 goto shortcut_error;
2399 #if 0 // This makes Vim wait a long time if the target doesn't exist.
2400 hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
2401 if (hr != S_OK)
2402 goto shortcut_error;
2403 #endif
2405 // Get the path to the link target.
2406 ZeroMemory(buf, MAX_PATH);
2407 hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
2408 if (hr == S_OK && buf[0] != NUL)
2409 rfname = vim_strsave(buf);
2411 shortcut_error:
2412 // Release all interface pointers (both belong to the same object)
2413 if (ppf != NULL)
2414 ppf->lpVtbl->Release(ppf);
2415 if (psl != NULL)
2416 psl->lpVtbl->Release(psl);
2418 CoUninitialize();
2419 return rfname;
2421 #endif
2423 #if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
2425 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
2427 void
2428 win32_set_foreground()
2430 # ifndef FEAT_GUI
2431 GetConsoleHwnd(); /* get value of s_hwnd */
2432 # endif
2433 if (s_hwnd != 0)
2434 SetForegroundWindow(s_hwnd);
2436 #endif
2438 #if defined(FEAT_CLIENTSERVER) || defined(PROTO)
2440 * Client-server code for Vim
2442 * Originally written by Paul Moore
2445 /* In order to handle inter-process messages, we need to have a window. But
2446 * the functions in this module can be called before the main GUI window is
2447 * created (and may also be called in the console version, where there is no
2448 * GUI window at all).
2450 * So we create a hidden window, and arrange to destroy it on exit.
2452 HWND message_window = 0; /* window that's handling messsages */
2454 #define VIM_CLASSNAME "VIM_MESSAGES"
2455 #define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
2457 /* Communication is via WM_COPYDATA messages. The message type is send in
2458 * the dwData parameter. Types are defined here. */
2459 #define COPYDATA_KEYS 0
2460 #define COPYDATA_REPLY 1
2461 #define COPYDATA_EXPR 10
2462 #define COPYDATA_RESULT 11
2463 #define COPYDATA_ERROR_RESULT 12
2464 #define COPYDATA_ENCODING 20
2466 /* This is a structure containing a server HWND and its name. */
2467 struct server_id
2469 HWND hwnd;
2470 char_u *name;
2473 /* Last received 'encoding' that the client uses. */
2474 static char_u *client_enc = NULL;
2477 * Tell the other side what encoding we are using.
2478 * Errors are ignored.
2480 static void
2481 serverSendEnc(HWND target)
2483 COPYDATASTRUCT data;
2485 data.dwData = COPYDATA_ENCODING;
2486 #ifdef FEAT_MBYTE
2487 data.cbData = (DWORD)STRLEN(p_enc) + 1;
2488 data.lpData = p_enc;
2489 #else
2490 data.cbData = STRLEN("latin1") + 1;
2491 data.lpData = "latin1";
2492 #endif
2493 (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2494 (LPARAM)(&data));
2498 * Clean up on exit. This destroys the hidden message window.
2500 static void
2501 #ifdef __BORLANDC__
2502 _RTLENTRYF
2503 #endif
2504 CleanUpMessaging(void)
2506 if (message_window != 0)
2508 DestroyWindow(message_window);
2509 message_window = 0;
2513 static int save_reply(HWND server, char_u *reply, int expr);
2516 * The window procedure for the hidden message window.
2517 * It handles callback messages and notifications from servers.
2518 * In order to process these messages, it is necessary to run a
2519 * message loop. Code which may run before the main message loop
2520 * is started (in the GUI) is careful to pump messages when it needs
2521 * to. Features which require message delivery during normal use will
2522 * not work in the console version - this basically means those
2523 * features which allow Vim to act as a server, rather than a client.
2525 static LRESULT CALLBACK
2526 Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2528 if (msg == WM_COPYDATA)
2530 /* This is a message from another Vim. The dwData member of the
2531 * COPYDATASTRUCT determines the type of message:
2532 * COPYDATA_ENCODING:
2533 * The encoding that the client uses. Following messages will
2534 * use this encoding, convert if needed.
2535 * COPYDATA_KEYS:
2536 * A key sequence. We are a server, and a client wants these keys
2537 * adding to the input queue.
2538 * COPYDATA_REPLY:
2539 * A reply. We are a client, and a server has sent this message
2540 * in response to a request. (server2client())
2541 * COPYDATA_EXPR:
2542 * An expression. We are a server, and a client wants us to
2543 * evaluate this expression.
2544 * COPYDATA_RESULT:
2545 * A reply. We are a client, and a server has sent this message
2546 * in response to a COPYDATA_EXPR.
2547 * COPYDATA_ERROR_RESULT:
2548 * A reply. We are a client, and a server has sent this message
2549 * in response to a COPYDATA_EXPR that failed to evaluate.
2551 COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam;
2552 HWND sender = (HWND)wParam;
2553 COPYDATASTRUCT reply;
2554 char_u *res;
2555 char_u winstr[30];
2556 int retval;
2557 char_u *str;
2558 char_u *tofree;
2560 switch (data->dwData)
2562 case COPYDATA_ENCODING:
2563 # ifdef FEAT_MBYTE
2564 /* Remember the encoding that the client uses. */
2565 vim_free(client_enc);
2566 client_enc = enc_canonize((char_u *)data->lpData);
2567 # endif
2568 return 1;
2570 case COPYDATA_KEYS:
2571 /* Remember who sent this, for <client> */
2572 clientWindow = sender;
2574 /* Add the received keys to the input buffer. The loop waiting
2575 * for the user to do something should check the input buffer. */
2576 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2577 server_to_input_buf(str);
2578 vim_free(tofree);
2580 # ifdef FEAT_GUI
2581 /* Wake up the main GUI loop. */
2582 if (s_hwnd != 0)
2583 PostMessage(s_hwnd, WM_NULL, 0, 0);
2584 # endif
2585 return 1;
2587 case COPYDATA_EXPR:
2588 /* Remember who sent this, for <client> */
2589 clientWindow = sender;
2591 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2592 res = eval_client_expr_to_string(str);
2593 vim_free(tofree);
2595 if (res == NULL)
2597 res = vim_strsave(_(e_invexprmsg));
2598 reply.dwData = COPYDATA_ERROR_RESULT;
2600 else
2601 reply.dwData = COPYDATA_RESULT;
2602 reply.lpData = res;
2603 reply.cbData = (DWORD)STRLEN(res) + 1;
2605 serverSendEnc(sender);
2606 retval = (int)SendMessage(sender, WM_COPYDATA, (WPARAM)message_window,
2607 (LPARAM)(&reply));
2608 vim_free(res);
2609 return retval;
2611 case COPYDATA_REPLY:
2612 case COPYDATA_RESULT:
2613 case COPYDATA_ERROR_RESULT:
2614 if (data->lpData != NULL)
2616 str = serverConvert(client_enc, (char_u *)data->lpData,
2617 &tofree);
2618 if (tofree == NULL)
2619 str = vim_strsave(str);
2620 if (save_reply(sender, str,
2621 (data->dwData == COPYDATA_REPLY ? 0 :
2622 (data->dwData == COPYDATA_RESULT ? 1 :
2623 2))) == FAIL)
2624 vim_free(str);
2625 #ifdef FEAT_AUTOCMD
2626 else if (data->dwData == COPYDATA_REPLY)
2628 sprintf((char *)winstr, "0x%x", (unsigned)sender);
2629 apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
2630 TRUE, curbuf);
2632 #endif
2634 return 1;
2637 return 0;
2640 else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2642 /* When the message window is activated (brought to the foreground),
2643 * this actually applies to the text window. */
2644 #ifndef FEAT_GUI
2645 GetConsoleHwnd(); /* get value of s_hwnd */
2646 #endif
2647 if (s_hwnd != 0)
2649 SetForegroundWindow(s_hwnd);
2650 return 0;
2654 return DefWindowProc(hwnd, msg, wParam, lParam);
2658 * Initialise the message handling process. This involves creating a window
2659 * to handle messages - the window will not be visible.
2661 void
2662 serverInitMessaging(void)
2664 WNDCLASS wndclass;
2665 HINSTANCE s_hinst;
2667 /* Clean up on exit */
2668 atexit(CleanUpMessaging);
2670 /* Register a window class - we only really care
2671 * about the window procedure
2673 s_hinst = (HINSTANCE)GetModuleHandle(0);
2674 wndclass.style = 0;
2675 wndclass.lpfnWndProc = Messaging_WndProc;
2676 wndclass.cbClsExtra = 0;
2677 wndclass.cbWndExtra = 0;
2678 wndclass.hInstance = s_hinst;
2679 wndclass.hIcon = NULL;
2680 wndclass.hCursor = NULL;
2681 wndclass.hbrBackground = NULL;
2682 wndclass.lpszMenuName = NULL;
2683 wndclass.lpszClassName = VIM_CLASSNAME;
2684 RegisterClass(&wndclass);
2686 /* Create the message window. It will be hidden, so the details don't
2687 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2688 * focus from gvim. */
2689 message_window = CreateWindow(VIM_CLASSNAME, "",
2690 WS_POPUPWINDOW | WS_CAPTION,
2691 CW_USEDEFAULT, CW_USEDEFAULT,
2692 100, 100, NULL, NULL,
2693 s_hinst, NULL);
2697 * Get the title of the window "hwnd", which is the Vim server name, in
2698 * "name[namelen]" and return the length.
2699 * Returns zero if window "hwnd" is not a Vim server.
2701 static int
2702 getVimServerName(HWND hwnd, char *name, int namelen)
2704 int len;
2705 char buffer[VIM_CLASSNAME_LEN + 1];
2707 /* Ignore windows which aren't Vim message windows */
2708 len = GetClassName(hwnd, buffer, sizeof(buffer));
2709 if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2710 return 0;
2712 /* Get the title of the window */
2713 return GetWindowText(hwnd, name, namelen);
2716 static BOOL CALLBACK
2717 enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2719 struct server_id *id = (struct server_id *)lparam;
2720 char server[MAX_PATH];
2722 /* Get the title of the window */
2723 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2724 return TRUE;
2726 /* If this is the server we're looking for, return its HWND */
2727 if (STRICMP(server, id->name) == 0)
2729 id->hwnd = hwnd;
2730 return FALSE;
2733 /* Otherwise, keep looking */
2734 return TRUE;
2737 static BOOL CALLBACK
2738 enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2740 garray_T *ga = (garray_T *)lparam;
2741 char server[MAX_PATH];
2743 /* Get the title of the window */
2744 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2745 return TRUE;
2747 /* Add the name to the list */
2748 ga_concat(ga, server);
2749 ga_concat(ga, "\n");
2750 return TRUE;
2753 static HWND
2754 findServer(char_u *name)
2756 struct server_id id;
2758 id.name = name;
2759 id.hwnd = 0;
2761 EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2763 return id.hwnd;
2766 void
2767 serverSetName(char_u *name)
2769 char_u *ok_name;
2770 HWND hwnd = 0;
2771 int i = 0;
2772 char_u *p;
2774 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
2775 ok_name = alloc((unsigned)STRLEN(name) + 10);
2777 STRCPY(ok_name, name);
2778 p = ok_name + STRLEN(name);
2780 for (;;)
2782 /* This is inefficient - we're doing an EnumWindows loop for each
2783 * possible name. It would be better to grab all names in one go,
2784 * and scan the list each time...
2786 hwnd = findServer(ok_name);
2787 if (hwnd == 0)
2788 break;
2790 ++i;
2791 if (i >= 1000)
2792 break;
2794 sprintf((char *)p, "%d", i);
2797 if (hwnd != 0)
2798 vim_free(ok_name);
2799 else
2801 /* Remember the name */
2802 serverName = ok_name;
2803 #ifdef FEAT_TITLE
2804 need_maketitle = TRUE; /* update Vim window title later */
2805 #endif
2807 /* Update the message window title */
2808 SetWindowText(message_window, ok_name);
2810 #ifdef FEAT_EVAL
2811 /* Set the servername variable */
2812 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2813 #endif
2817 char_u *
2818 serverGetVimNames(void)
2820 garray_T ga;
2822 ga_init2(&ga, 1, 100);
2824 EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
2825 ga_append(&ga, NUL);
2827 return ga.ga_data;
2831 serverSendReply(name, reply)
2832 char_u *name; /* Where to send. */
2833 char_u *reply; /* What to send. */
2835 HWND target;
2836 COPYDATASTRUCT data;
2837 int n = 0;
2839 /* The "name" argument is a magic cookie obtained from expand("<client>").
2840 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2841 * value of the client's message window HWND.
2843 sscanf((char *)name, "%x", &n);
2844 if (n == 0)
2845 return -1;
2847 target = (HWND)n;
2848 if (!IsWindow(target))
2849 return -1;
2851 data.dwData = COPYDATA_REPLY;
2852 data.cbData = (DWORD)STRLEN(reply) + 1;
2853 data.lpData = reply;
2855 serverSendEnc(target);
2856 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2857 (LPARAM)(&data)))
2858 return 0;
2860 return -1;
2864 serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2865 char_u *name; /* Where to send. */
2866 char_u *cmd; /* What to send. */
2867 char_u **result; /* Result of eval'ed expression */
2868 void *ptarget; /* HWND of server */
2869 int asExpr; /* Expression or keys? */
2870 int silent; /* don't complain about no server */
2872 HWND target = findServer(name);
2873 COPYDATASTRUCT data;
2874 char_u *retval = NULL;
2875 int retcode = 0;
2877 if (target == 0)
2879 if (!silent)
2880 EMSG2(_(e_noserver), name);
2881 return -1;
2884 if (ptarget)
2885 *(HWND *)ptarget = target;
2887 data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
2888 data.cbData = (DWORD)STRLEN(cmd) + 1;
2889 data.lpData = cmd;
2891 serverSendEnc(target);
2892 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2893 (LPARAM)(&data)) == 0)
2894 return -1;
2896 if (asExpr)
2897 retval = serverGetReply(target, &retcode, TRUE, TRUE);
2899 if (result == NULL)
2900 vim_free(retval);
2901 else
2902 *result = retval; /* Caller assumes responsibility for freeing */
2904 return retcode;
2908 * Bring the server to the foreground.
2910 void
2911 serverForeground(name)
2912 char_u *name;
2914 HWND target = findServer(name);
2916 if (target != 0)
2917 SetForegroundWindow(target);
2920 /* Replies from server need to be stored until the client picks them up via
2921 * remote_read(). So we maintain a list of server-id/reply pairs.
2922 * Note that there could be multiple replies from one server pending if the
2923 * client is slow picking them up.
2924 * We just store the replies in a simple list. When we remove an entry, we
2925 * move list entries down to fill the gap.
2926 * The server ID is simply the HWND.
2928 typedef struct
2930 HWND server; /* server window */
2931 char_u *reply; /* reply string */
2932 int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */
2933 } reply_T;
2935 static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
2937 #define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
2938 #define REPLY_COUNT (reply_list.ga_len)
2940 /* Flag which is used to wait for a reply */
2941 static int reply_received = 0;
2944 * Store a reply. "reply" must be allocated memory (or NULL).
2946 static int
2947 save_reply(HWND server, char_u *reply, int expr)
2949 reply_T *rep;
2951 if (ga_grow(&reply_list, 1) == FAIL)
2952 return FAIL;
2954 rep = REPLY_ITEM(REPLY_COUNT);
2955 rep->server = server;
2956 rep->reply = reply;
2957 rep->expr_result = expr;
2958 if (rep->reply == NULL)
2959 return FAIL;
2961 ++REPLY_COUNT;
2962 reply_received = 1;
2963 return OK;
2967 * Get a reply from server "server".
2968 * When "expr_res" is non NULL, get the result of an expression, otherwise a
2969 * server2client() message.
2970 * When non NULL, point to return code. 0 => OK, -1 => ERROR
2971 * If "remove" is TRUE, consume the message, the caller must free it then.
2972 * if "wait" is TRUE block until a message arrives (or the server exits).
2974 char_u *
2975 serverGetReply(HWND server, int *expr_res, int remove, int wait)
2977 int i;
2978 char_u *reply;
2979 reply_T *rep;
2981 /* When waiting, loop until the message waiting for is received. */
2982 for (;;)
2984 /* Reset this here, in case a message arrives while we are going
2985 * through the already received messages. */
2986 reply_received = 0;
2988 for (i = 0; i < REPLY_COUNT; ++i)
2990 rep = REPLY_ITEM(i);
2991 if (rep->server == server
2992 && ((rep->expr_result != 0) == (expr_res != NULL)))
2994 /* Save the values we've found for later */
2995 reply = rep->reply;
2996 if (expr_res != NULL)
2997 *expr_res = rep->expr_result == 1 ? 0 : -1;
2999 if (remove)
3001 /* Move the rest of the list down to fill the gap */
3002 mch_memmove(rep, rep + 1,
3003 (REPLY_COUNT - i - 1) * sizeof(reply_T));
3004 --REPLY_COUNT;
3007 /* Return the reply to the caller, who takes on responsibility
3008 * for freeing it if "remove" is TRUE. */
3009 return reply;
3013 /* If we got here, we didn't find a reply. Return immediately if the
3014 * "wait" parameter isn't set. */
3015 if (!wait)
3016 break;
3018 /* We need to wait for a reply. Enter a message loop until the
3019 * "reply_received" flag gets set. */
3021 /* Loop until we receive a reply */
3022 while (reply_received == 0)
3024 /* Wait for a SendMessage() call to us. This could be the reply
3025 * we are waiting for. Use a timeout of a second, to catch the
3026 * situation that the server died unexpectedly. */
3027 MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
3029 /* If the server has died, give up */
3030 if (!IsWindow(server))
3031 return NULL;
3033 serverProcessPendingMessages();
3037 return NULL;
3041 * Process any messages in the Windows message queue.
3043 void
3044 serverProcessPendingMessages(void)
3046 MSG msg;
3048 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
3050 TranslateMessage(&msg);
3051 DispatchMessage(&msg);
3055 #endif /* FEAT_CLIENTSERVER */
3057 #if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
3058 || defined(PROTO)
3060 struct charset_pair
3062 char *name;
3063 BYTE charset;
3066 static struct charset_pair
3067 charset_pairs[] =
3069 {"ANSI", ANSI_CHARSET},
3070 {"CHINESEBIG5", CHINESEBIG5_CHARSET},
3071 {"DEFAULT", DEFAULT_CHARSET},
3072 {"HANGEUL", HANGEUL_CHARSET},
3073 {"OEM", OEM_CHARSET},
3074 {"SHIFTJIS", SHIFTJIS_CHARSET},
3075 {"SYMBOL", SYMBOL_CHARSET},
3076 #ifdef WIN3264
3077 {"ARABIC", ARABIC_CHARSET},
3078 {"BALTIC", BALTIC_CHARSET},
3079 {"EASTEUROPE", EASTEUROPE_CHARSET},
3080 {"GB2312", GB2312_CHARSET},
3081 {"GREEK", GREEK_CHARSET},
3082 {"HEBREW", HEBREW_CHARSET},
3083 {"JOHAB", JOHAB_CHARSET},
3084 {"MAC", MAC_CHARSET},
3085 {"RUSSIAN", RUSSIAN_CHARSET},
3086 {"THAI", THAI_CHARSET},
3087 {"TURKISH", TURKISH_CHARSET},
3088 # if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
3089 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
3090 {"VIETNAMESE", VIETNAMESE_CHARSET},
3091 # endif
3092 #endif
3093 {NULL, 0}
3097 * Convert a charset ID to a name.
3098 * Return NULL when not recognized.
3100 char *
3101 charset_id2name(int id)
3103 struct charset_pair *cp;
3105 for (cp = charset_pairs; cp->name != NULL; ++cp)
3106 if ((BYTE)id == cp->charset)
3107 break;
3108 return cp->name;
3111 static const LOGFONT s_lfDefault =
3113 -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
3114 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
3115 PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
3116 "Fixedsys" /* see _ReadVimIni */
3119 /* Initialise the "current height" to -12 (same as s_lfDefault) just
3120 * in case the user specifies a font in "guifont" with no size before a font
3121 * with an explicit size has been set. This defaults the size to this value
3122 * (-12 equates to roughly 9pt).
3124 int current_font_height = -12; /* also used in gui_w48.c */
3126 /* Convert a string representing a point size into pixels. The string should
3127 * be a positive decimal number, with an optional decimal point (eg, "12", or
3128 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
3129 * character is stored in *end. The flag "vertical" says whether this
3130 * calculation is for a vertical (height) size or a horizontal (width) one.
3132 static int
3133 points_to_pixels(char_u *str, char_u **end, int vertical, int pprinter_dc)
3135 int pixels;
3136 int points = 0;
3137 int divisor = 0;
3138 HWND hwnd = (HWND)0;
3139 HDC hdc;
3140 HDC printer_dc = (HDC)pprinter_dc;
3142 while (*str != NUL)
3144 if (*str == '.' && divisor == 0)
3146 /* Start keeping a divisor, for later */
3147 divisor = 1;
3149 else
3151 if (!VIM_ISDIGIT(*str))
3152 break;
3154 points *= 10;
3155 points += *str - '0';
3156 divisor *= 10;
3158 ++str;
3161 if (divisor == 0)
3162 divisor = 1;
3164 if (printer_dc == NULL)
3166 hwnd = GetDesktopWindow();
3167 hdc = GetWindowDC(hwnd);
3169 else
3170 hdc = printer_dc;
3172 pixels = MulDiv(points,
3173 GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
3174 72 * divisor);
3176 if (printer_dc == NULL)
3177 ReleaseDC(hwnd, hdc);
3179 *end = str;
3180 return pixels;
3183 /*ARGSUSED*/
3184 static int CALLBACK
3185 font_enumproc(
3186 ENUMLOGFONT *elf,
3187 NEWTEXTMETRIC *ntm,
3188 int type,
3189 LPARAM lparam)
3191 /* Return value:
3192 * 0 = terminate now (monospace & ANSI)
3193 * 1 = continue, still no luck...
3194 * 2 = continue, but we have an acceptable LOGFONT
3195 * (monospace, not ANSI)
3196 * We use these values, as EnumFontFamilies returns 1 if the
3197 * callback function is never called. So, we check the return as
3198 * 0 = perfect, 2 = OK, 1 = no good...
3199 * It's not pretty, but it works!
3202 LOGFONT *lf = (LOGFONT *)(lparam);
3204 #ifndef FEAT_PROPORTIONAL_FONTS
3205 /* Ignore non-monospace fonts without further ado */
3206 if ((ntm->tmPitchAndFamily & 1) != 0)
3207 return 1;
3208 #endif
3210 /* Remember this LOGFONT as a "possible" */
3211 *lf = elf->elfLogFont;
3213 /* Terminate the scan as soon as we find an ANSI font */
3214 if (lf->lfCharSet == ANSI_CHARSET
3215 || lf->lfCharSet == OEM_CHARSET
3216 || lf->lfCharSet == DEFAULT_CHARSET)
3217 return 0;
3219 /* Continue the scan - we have a non-ANSI font */
3220 return 2;
3223 static int
3224 init_logfont(LOGFONT *lf)
3226 int n;
3227 HWND hwnd = GetDesktopWindow();
3228 HDC hdc = GetWindowDC(hwnd);
3230 n = EnumFontFamilies(hdc,
3231 (LPCSTR)lf->lfFaceName,
3232 (FONTENUMPROC)font_enumproc,
3233 (LPARAM)lf);
3235 ReleaseDC(hwnd, hdc);
3237 /* If we couldn't find a useable font, return failure */
3238 if (n == 1)
3239 return FAIL;
3241 /* Tidy up the rest of the LOGFONT structure. We set to a basic
3242 * font - get_logfont() sets bold, italic, etc based on the user's
3243 * input.
3245 lf->lfHeight = current_font_height;
3246 lf->lfWidth = 0;
3247 lf->lfItalic = FALSE;
3248 lf->lfUnderline = FALSE;
3249 lf->lfStrikeOut = FALSE;
3250 lf->lfWeight = FW_NORMAL;
3252 /* Return success */
3253 return OK;
3257 * Get font info from "name" into logfont "lf".
3258 * Return OK for a valid name, FAIL otherwise.
3261 get_logfont(
3262 LOGFONT *lf,
3263 char_u *name,
3264 HDC printer_dc,
3265 int verbose)
3267 char_u *p;
3268 int i;
3269 static LOGFONT *lastlf = NULL;
3271 *lf = s_lfDefault;
3272 if (name == NULL)
3273 return OK;
3275 if (STRCMP(name, "*") == 0)
3277 #if defined(FEAT_GUI_W32)
3278 CHOOSEFONT cf;
3279 /* if name is "*", bring up std font dialog: */
3280 memset(&cf, 0, sizeof(cf));
3281 cf.lStructSize = sizeof(cf);
3282 cf.hwndOwner = s_hwnd;
3283 cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
3284 if (lastlf != NULL)
3285 *lf = *lastlf;
3286 cf.lpLogFont = lf;
3287 cf.nFontType = 0 ; //REGULAR_FONTTYPE;
3288 if (ChooseFont(&cf))
3289 goto theend;
3290 #else
3291 return FAIL;
3292 #endif
3296 * Split name up, it could be <name>:h<height>:w<width> etc.
3298 for (p = name; *p && *p != ':'; p++)
3300 if (p - name + 1 > LF_FACESIZE)
3301 return FAIL; /* Name too long */
3302 lf->lfFaceName[p - name] = *p;
3304 if (p != name)
3305 lf->lfFaceName[p - name] = NUL;
3307 /* First set defaults */
3308 lf->lfHeight = -12;
3309 lf->lfWidth = 0;
3310 lf->lfWeight = FW_NORMAL;
3311 lf->lfItalic = FALSE;
3312 lf->lfUnderline = FALSE;
3313 lf->lfStrikeOut = FALSE;
3316 * If the font can't be found, try replacing '_' by ' '.
3318 if (init_logfont(lf) == FAIL)
3320 int did_replace = FALSE;
3322 for (i = 0; lf->lfFaceName[i]; ++i)
3323 if (lf->lfFaceName[i] == '_')
3325 lf->lfFaceName[i] = ' ';
3326 did_replace = TRUE;
3328 if (!did_replace || init_logfont(lf) == FAIL)
3329 return FAIL;
3332 while (*p == ':')
3333 p++;
3335 /* Set the values found after ':' */
3336 while (*p)
3338 switch (*p++)
3340 case 'h':
3341 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (int)printer_dc);
3342 break;
3343 case 'w':
3344 lf->lfWidth = points_to_pixels(p, &p, FALSE, (int)printer_dc);
3345 break;
3346 case 'b':
3347 #ifndef MSWIN16_FASTTEXT
3348 lf->lfWeight = FW_BOLD;
3349 #endif
3350 break;
3351 case 'i':
3352 #ifndef MSWIN16_FASTTEXT
3353 lf->lfItalic = TRUE;
3354 #endif
3355 break;
3356 case 'u':
3357 lf->lfUnderline = TRUE;
3358 break;
3359 case 's':
3360 lf->lfStrikeOut = TRUE;
3361 break;
3362 case 'c':
3364 struct charset_pair *cp;
3366 for (cp = charset_pairs; cp->name != NULL; ++cp)
3367 if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
3369 lf->lfCharSet = cp->charset;
3370 p += strlen(cp->name);
3371 break;
3373 if (cp->name == NULL && verbose)
3375 vim_snprintf((char *)IObuff, IOSIZE,
3376 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
3377 EMSG(IObuff);
3378 break;
3380 break;
3382 default:
3383 if (verbose)
3385 vim_snprintf((char *)IObuff, IOSIZE,
3386 _("E245: Illegal char '%c' in font name \"%s\""),
3387 p[-1], name);
3388 EMSG(IObuff);
3390 return FAIL;
3392 while (*p == ':')
3393 p++;
3396 #if defined(FEAT_GUI_W32)
3397 theend:
3398 #endif
3399 /* ron: init lastlf */
3400 if (printer_dc == NULL)
3402 vim_free(lastlf);
3403 lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
3404 if (lastlf != NULL)
3405 mch_memmove(lastlf, lf, sizeof(LOGFONT));
3408 return OK;
3411 #endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */