Merged from the latest developing branch.
[MacVim/KaoriYa.git] / src / os_mswin.c
blob537568956b4b02d84e541729af183a76bdedd3e2
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);
243 #ifdef EXITFREE
244 free_all_mem();
245 #endif
247 exit(r);
250 #endif /* FEAT_GUI_MSWIN */
254 * Init the tables for toupper() and tolower().
256 void
257 mch_early_init(void)
259 int i;
261 #ifdef WIN3264
262 PlatformId();
263 #endif
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
276 #if defined(FEAT_MBYTE) && !defined(FEAT_GUI)
277 (void)get_cmd_argsW(NULL);
278 #endif
283 * Return TRUE if the input comes from a terminal, FALSE otherwise.
286 mch_input_isatty()
288 #ifdef FEAT_GUI_MSWIN
289 return OK; /* GUI always has a tty */
290 #else
291 if (isatty(read_cmd_fd))
292 return TRUE;
293 return FALSE;
294 #endif
297 #ifdef FEAT_TITLE
299 * mch_settitle(): set titlebar of our window
301 void
302 mch_settitle(
303 char_u *title,
304 char_u *icon)
306 # ifdef FEAT_GUI_MSWIN
307 gui_mch_settitle(title, icon);
308 # else
309 if (title != NULL)
311 # ifdef FEAT_MBYTE
312 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
314 /* Convert the title from 'encoding' to the active codepage. */
315 WCHAR *wp = enc_to_ucs2(title, NULL);
316 int n;
318 if (wp != NULL)
320 n = SetConsoleTitleW(wp);
321 vim_free(wp);
322 if (n != 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
323 return;
326 # endif
327 SetConsoleTitle(title);
329 # endif
334 * Restore the window/icon title.
335 * which is one of:
336 * 1: Just restore title
337 * 2: Just restore icon (which we don't have)
338 * 3: Restore title and icon (which we don't have)
340 /*ARGSUSED*/
341 void
342 mch_restore_title(
343 int which)
345 #ifndef FEAT_GUI_MSWIN
346 mch_settitle((which & 1) ? g_szOrigTitle : NULL, NULL);
347 #endif
352 * Return TRUE if we can restore the title (we can)
355 mch_can_restore_title()
357 return TRUE;
362 * Return TRUE if we can restore the icon title (we can't)
365 mch_can_restore_icon()
367 return FALSE;
369 #endif /* FEAT_TITLE */
373 * Get absolute file name into buffer "buf" of length "len" bytes,
374 * turning all '/'s into '\\'s and getting the correct case of each component
375 * of the file name. Append a (back)slash to a directory name.
376 * When 'shellslash' set do it the other way around.
377 * Return OK or FAIL.
379 /*ARGSUSED*/
381 mch_FullName(
382 char_u *fname,
383 char_u *buf,
384 int len,
385 int force)
387 int nResult = FAIL;
389 #ifdef __BORLANDC__
390 if (*fname == NUL) /* Borland behaves badly here - make it consistent */
391 nResult = mch_dirname(buf, len);
392 else
393 #endif
395 #ifdef FEAT_MBYTE
396 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
397 # ifdef __BORLANDC__
398 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
399 && g_PlatformId == VER_PLATFORM_WIN32_NT
400 # endif
403 WCHAR *wname;
404 WCHAR wbuf[MAX_PATH];
405 char_u *cname = NULL;
407 /* Use the wide function:
408 * - convert the fname from 'encoding' to UCS2.
409 * - invoke _wfullpath()
410 * - convert the result from UCS2 to 'encoding'.
412 wname = enc_to_ucs2(fname, NULL);
413 if (wname != NULL && _wfullpath(wbuf, wname, MAX_PATH - 1) != NULL)
415 cname = ucs2_to_enc((short_u *)wbuf, NULL);
416 if (cname != NULL)
418 vim_strncpy(buf, cname, len - 1);
419 nResult = OK;
422 vim_free(wname);
423 vim_free(cname);
425 if (nResult == FAIL) /* fall back to non-wide function */
426 #endif
428 if (_fullpath(buf, fname, len - 1) == NULL)
430 /* failed, use relative path name */
431 vim_strncpy(buf, fname, len - 1);
433 else
434 nResult = OK;
438 #ifdef USE_FNAME_CASE
439 fname_case(buf, len);
440 #else
441 slash_adjust(buf);
442 #endif
444 return nResult;
449 * Return TRUE if "fname" does not depend on the current directory.
452 mch_isFullName(char_u *fname)
454 char szName[_MAX_PATH + 1];
456 /* A name like "d:/foo" and "//server/share" is absolute */
457 if ((fname[0] && fname[1] == ':' && (fname[2] == '/' || fname[2] == '\\'))
458 || (fname[0] == fname[1] && (fname[0] == '/' || fname[0] == '\\')))
459 return TRUE;
461 /* A name that can't be made absolute probably isn't absolute. */
462 if (mch_FullName(fname, szName, _MAX_PATH, FALSE) == FAIL)
463 return FALSE;
465 return pathcmp(fname, szName, -1) == 0;
469 * Replace all slashes by backslashes.
470 * This used to be the other way around, but MS-DOS sometimes has problems
471 * with slashes (e.g. in a command name). We can't have mixed slashes and
472 * backslashes, because comparing file names will not work correctly. The
473 * commands that use a file name should try to avoid the need to type a
474 * backslash twice.
475 * When 'shellslash' set do it the other way around.
477 void
478 slash_adjust(p)
479 char_u *p;
481 while (*p)
483 if (*p == psepcN)
484 *p = psepc;
485 mb_ptr_adv(p);
491 * stat() can't handle a trailing '/' or '\', remove it first.
494 vim_stat(const char *name, struct stat *stp)
496 char buf[_MAX_PATH + 1];
497 char *p;
499 vim_strncpy((char_u *)buf, (char_u *)name, _MAX_PATH);
500 p = buf + strlen(buf);
501 if (p > buf)
502 mb_ptr_back(buf, p);
503 if (p > buf && (*p == '\\' || *p == '/') && p[-1] != ':')
504 *p = NUL;
505 #ifdef FEAT_MBYTE
506 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
507 # ifdef __BORLANDC__
508 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
509 && g_PlatformId == VER_PLATFORM_WIN32_NT
510 # endif
513 WCHAR *wp = enc_to_ucs2(buf, NULL);
514 int n;
516 if (wp != NULL)
518 n = _wstat(wp, (struct _stat *)stp);
519 vim_free(wp);
520 if (n >= 0)
521 return n;
522 /* Retry with non-wide function (for Windows 98). Can't use
523 * GetLastError() here and it's unclear what errno gets set to if
524 * the _wstat() fails for missing wide functions. */
527 #endif
528 return stat(buf, stp);
531 #if defined(FEAT_GUI_MSWIN) || defined(PROTO)
532 /*ARGSUSED*/
533 void
534 mch_settmode(int tmode)
536 /* nothing to do */
540 mch_get_shellsize(void)
542 /* never used */
543 return OK;
546 void
547 mch_set_shellsize(void)
549 /* never used */
553 * Rows and/or Columns has changed.
555 void
556 mch_new_shellsize(void)
558 /* never used */
561 #endif
564 * We have no job control, so fake it by starting a new shell.
566 void
567 mch_suspend()
569 suspend_shell();
572 #if defined(USE_MCH_ERRMSG) || defined(PROTO)
574 #ifdef display_errors
575 # undef display_errors
576 #endif
579 * Display the saved error message(s).
581 void
582 display_errors()
584 char *p;
586 if (error_ga.ga_data != NULL)
588 /* avoid putting up a message box with blanks only */
589 for (p = (char *)error_ga.ga_data; *p; ++p)
590 if (!isspace(*p))
592 (void)gui_mch_dialog(
593 #ifdef FEAT_GUI
594 gui.starting ? VIM_INFO :
595 #endif
596 VIM_ERROR,
597 #ifdef FEAT_GUI
598 gui.starting ? (char_u *)_("Message") :
599 #endif
600 (char_u *)_("Error"),
601 p, (char_u *)_("&Ok"), 1, NULL);
602 break;
604 ga_clear(&error_ga);
607 #endif
611 * Return TRUE if "p" contain a wildcard that can be expanded by
612 * dos_expandpath().
615 mch_has_exp_wildcard(char_u *p)
617 for ( ; *p; mb_ptr_adv(p))
619 if (vim_strchr((char_u *)"?*[", *p) != NULL
620 || (*p == '~' && p[1] != NUL))
621 return TRUE;
623 return FALSE;
627 * Return TRUE if "p" contain a wildcard or a "~1" kind of thing (could be a
628 * shortened file name).
631 mch_has_wildcard(char_u *p)
633 for ( ; *p; mb_ptr_adv(p))
635 if (vim_strchr((char_u *)
636 # ifdef VIM_BACKTICK
637 "?*$[`"
638 # else
639 "?*$["
640 # endif
641 , *p) != NULL
642 || (*p == '~' && p[1] != NUL))
643 return TRUE;
645 return FALSE;
650 * The normal _chdir() does not change the default drive. This one does.
651 * Returning 0 implies success; -1 implies failure.
654 mch_chdir(char *path)
656 if (path[0] == NUL) /* just checking... */
657 return -1;
659 if (isalpha(path[0]) && path[1] == ':') /* has a drive name */
661 /* If we can change to the drive, skip that part of the path. If we
662 * can't then the current directory may be invalid, try using chdir()
663 * with the whole path. */
664 if (_chdrive(TOLOWER_ASC(path[0]) - 'a' + 1) == 0)
665 path += 2;
668 if (*path == NUL) /* drive name only */
669 return 0;
671 #ifdef FEAT_MBYTE
672 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
674 WCHAR *p = enc_to_ucs2(path, NULL);
675 int n;
677 if (p != NULL)
679 n = _wchdir(p);
680 vim_free(p);
681 if (n == 0)
682 return 0;
683 /* Retry with non-wide function (for Windows 98). */
686 #endif
688 return chdir(path); /* let the normal chdir() do the rest */
693 * Switching off termcap mode is only allowed when Columns is 80, otherwise a
694 * crash may result. It's always allowed on NT or when running the GUI.
696 /*ARGSUSED*/
698 can_end_termcap_mode(
699 int give_msg)
701 #ifdef FEAT_GUI_MSWIN
702 return TRUE; /* GUI starts a new console anyway */
703 #else
704 if (g_PlatformId == VER_PLATFORM_WIN32_NT || Columns == 80)
705 return TRUE;
706 if (give_msg)
707 msg(_("'columns' is not 80, cannot execute external commands"));
708 return FALSE;
709 #endif
712 #ifdef FEAT_GUI_MSWIN
714 * return non-zero if a character is available
717 mch_char_avail()
719 /* never used */
720 return TRUE;
722 #endif
726 * set screen mode, always fails.
728 /*ARGSUSED*/
730 mch_screenmode(
731 char_u *arg)
733 EMSG(_(e_screenmode));
734 return FAIL;
738 #if defined(FEAT_LIBCALL) || defined(PROTO)
740 * Call a DLL routine which takes either a string or int param
741 * and returns an allocated string.
742 * Return OK if it worked, FAIL if not.
744 # ifdef WIN3264
745 typedef LPTSTR (*MYSTRPROCSTR)(LPTSTR);
746 typedef LPTSTR (*MYINTPROCSTR)(int);
747 typedef int (*MYSTRPROCINT)(LPTSTR);
748 typedef int (*MYINTPROCINT)(int);
749 # else
750 typedef LPSTR (*MYSTRPROCSTR)(LPSTR);
751 typedef LPSTR (*MYINTPROCSTR)(int);
752 typedef int (*MYSTRPROCINT)(LPSTR);
753 typedef int (*MYINTPROCINT)(int);
754 # endif
756 # ifndef WIN16
758 * Check if a pointer points to a valid NUL terminated string.
759 * Return the length of the string, including terminating NUL.
760 * Returns 0 for an invalid pointer, 1 for an empty string.
762 static size_t
763 check_str_len(char_u *str)
765 SYSTEM_INFO si;
766 MEMORY_BASIC_INFORMATION mbi;
767 size_t length = 0;
768 size_t i;
769 const char *p;
771 /* get page size */
772 GetSystemInfo(&si);
774 /* get memory information */
775 if (VirtualQuery(str, &mbi, sizeof(mbi)))
777 /* pre cast these (typing savers) */
778 long_u dwStr = (long_u)str;
779 long_u dwBaseAddress = (long_u)mbi.BaseAddress;
781 /* get start address of page that str is on */
782 long_u strPage = dwStr - (dwStr - dwBaseAddress) % si.dwPageSize;
784 /* get length from str to end of page */
785 long_u pageLength = si.dwPageSize - (dwStr - strPage);
787 for (p = str; !IsBadReadPtr(p, pageLength);
788 p += pageLength, pageLength = si.dwPageSize)
789 for (i = 0; i < pageLength; ++i, ++length)
790 if (p[i] == NUL)
791 return length + 1;
794 return 0;
796 # endif
799 mch_libcall(
800 char_u *libname,
801 char_u *funcname,
802 char_u *argstring, /* NULL when using a argint */
803 int argint,
804 char_u **string_result,/* NULL when using number_result */
805 int *number_result)
807 HINSTANCE hinstLib;
808 MYSTRPROCSTR ProcAdd;
809 MYINTPROCSTR ProcAddI;
810 char_u *retval_str = NULL;
811 int retval_int = 0;
812 size_t len;
814 BOOL fRunTimeLinkSuccess = FALSE;
816 // Get a handle to the DLL module.
817 hinstLib = LoadLibrary(libname);
819 // If the handle is valid, try to get the function address.
820 if (hinstLib != NULL)
822 #ifdef HAVE_TRY_EXCEPT
823 __try
825 #endif
826 if (argstring != NULL)
828 /* Call with string argument */
829 ProcAdd = (MYSTRPROCSTR) GetProcAddress(hinstLib, funcname);
830 if ((fRunTimeLinkSuccess = (ProcAdd != NULL)) != 0)
832 if (string_result == NULL)
833 retval_int = ((MYSTRPROCINT)ProcAdd)(argstring);
834 else
835 retval_str = (ProcAdd)(argstring);
838 else
840 /* Call with number argument */
841 ProcAddI = (MYINTPROCSTR) GetProcAddress(hinstLib, funcname);
842 if ((fRunTimeLinkSuccess = (ProcAddI != NULL)) != 0)
844 if (string_result == NULL)
845 retval_int = ((MYINTPROCINT)ProcAddI)(argint);
846 else
847 retval_str = (ProcAddI)(argint);
851 // Save the string before we free the library.
852 // Assume that a "1" result is an illegal pointer.
853 if (string_result == NULL)
854 *number_result = retval_int;
855 else if (retval_str != NULL
856 # ifdef WIN16
857 && retval_str != (char_u *)1
858 && retval_str != (char_u *)-1
859 && !IsBadStringPtr(retval_str, INT_MAX)
860 && (len = strlen(retval_str) + 1) > 0
861 # else
862 && (len = check_str_len(retval_str)) > 0
863 # endif
866 *string_result = lalloc((long_u)len, TRUE);
867 if (*string_result != NULL)
868 mch_memmove(*string_result, retval_str, len);
871 #ifdef HAVE_TRY_EXCEPT
873 __except(EXCEPTION_EXECUTE_HANDLER)
875 if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW)
876 RESETSTKOFLW();
877 fRunTimeLinkSuccess = 0;
879 #endif
881 // Free the DLL module.
882 (void)FreeLibrary(hinstLib);
885 if (!fRunTimeLinkSuccess)
887 EMSG2(_(e_libcall), funcname);
888 return FAIL;
891 return OK;
893 #endif
895 #if defined(FEAT_MBYTE) || defined(PROTO)
897 * Convert an UTF-8 string to UCS-2.
898 * "instr[inlen]" is the input. "inlen" is in bytes.
899 * When "outstr" is NULL only return the number of UCS-2 words produced.
900 * Otherwise "outstr" must be a buffer of sufficient size.
901 * Returns the number of UCS-2 words produced.
904 utf8_to_ucs2(char_u *instr, int inlen, short_u *outstr, int *unconvlenp)
906 int outlen = 0;
907 char_u *p = instr;
908 int todo = inlen;
909 int l;
911 while (todo > 0)
913 /* Only convert if we have a complete sequence. */
914 l = utf_ptr2len_len(p, todo);
915 if (l > todo)
917 /* Return length of incomplete sequence. */
918 if (unconvlenp != NULL)
919 *unconvlenp = todo;
920 break;
923 if (outstr != NULL)
924 *outstr++ = utf_ptr2char(p);
925 ++outlen;
926 p += l;
927 todo -= l;
930 return outlen;
934 * Convert an UCS-2 string to UTF-8.
935 * The input is "instr[inlen]" with "inlen" in number of ucs-2 words.
936 * When "outstr" is NULL only return the required number of bytes.
937 * Otherwise "outstr" must be a buffer of sufficient size.
938 * Return the number of bytes produced.
941 ucs2_to_utf8(short_u *instr, int inlen, char_u *outstr)
943 int outlen = 0;
944 int todo = inlen;
945 short_u *p = instr;
946 int l;
948 while (todo > 0)
950 if (outstr != NULL)
952 l = utf_char2bytes(*p, outstr);
953 outstr += l;
955 else
956 l = utf_char2len(*p);
957 ++p;
958 outlen += l;
959 --todo;
962 return outlen;
966 * Call MultiByteToWideChar() and allocate memory for the result.
967 * Returns the result in "*out[*outlen]" with an extra zero appended.
968 * "outlen" is in words.
970 void
971 MultiByteToWideChar_alloc(UINT cp, DWORD flags,
972 LPCSTR in, int inlen,
973 LPWSTR *out, int *outlen)
975 *outlen = MultiByteToWideChar(cp, flags, in, inlen, 0, 0);
976 /* Add one one word to avoid a zero-length alloc(). */
977 *out = (LPWSTR)alloc(sizeof(WCHAR) * (*outlen + 1));
978 if (*out != NULL)
980 MultiByteToWideChar(cp, flags, in, inlen, *out, *outlen);
981 (*out)[*outlen] = 0;
986 * Call WideCharToMultiByte() and allocate memory for the result.
987 * Returns the result in "*out[*outlen]" with an extra NUL appended.
989 void
990 WideCharToMultiByte_alloc(UINT cp, DWORD flags,
991 LPCWSTR in, int inlen,
992 LPSTR *out, int *outlen,
993 LPCSTR def, LPBOOL useddef)
995 *outlen = WideCharToMultiByte(cp, flags, in, inlen, NULL, 0, def, useddef);
996 /* Add one one byte to avoid a zero-length alloc(). */
997 *out = alloc((unsigned)*outlen + 1);
998 if (*out != NULL)
1000 WideCharToMultiByte(cp, flags, in, inlen, *out, *outlen, def, useddef);
1001 (*out)[*outlen] = 0;
1005 #endif /* FEAT_MBYTE */
1007 #ifdef FEAT_CLIPBOARD
1009 * Clipboard stuff, for cutting and pasting text to other windows.
1012 /* Type used for the clipboard type of Vim's data. */
1013 typedef struct
1015 int type; /* MCHAR, MBLOCK or MLINE */
1016 int txtlen; /* length of CF_TEXT in bytes */
1017 int ucslen; /* length of CF_UNICODETEXT in words */
1018 int rawlen; /* length of clip_star.format_raw, including encoding,
1019 excluding terminating NUL */
1020 } VimClipType_t;
1023 * Make vim the owner of the current selection. Return OK upon success.
1025 /*ARGSUSED*/
1027 clip_mch_own_selection(VimClipboard *cbd)
1030 * Never actually own the clipboard. If another application sets the
1031 * clipboard, we don't want to think that we still own it.
1033 return FAIL;
1037 * Make vim NOT the owner of the current selection.
1039 /*ARGSUSED*/
1040 void
1041 clip_mch_lose_selection(VimClipboard *cbd)
1043 /* Nothing needs to be done here */
1047 * Copy "str[*size]" into allocated memory, changing CR-NL to NL.
1048 * Return the allocated result and the size in "*size".
1049 * Returns NULL when out of memory.
1051 static char_u *
1052 crnl_to_nl(const char_u *str, int *size)
1054 int pos = 0;
1055 int str_len = *size;
1056 char_u *ret;
1057 char_u *retp;
1059 /* Avoid allocating zero bytes, it generates an error message. */
1060 ret = lalloc((long_u)(str_len == 0 ? 1 : str_len), TRUE);
1061 if (ret != NULL)
1063 retp = ret;
1064 for (pos = 0; pos < str_len; ++pos)
1066 if (str[pos] == '\r' && str[pos + 1] == '\n')
1068 ++pos;
1069 --(*size);
1071 *retp++ = str[pos];
1075 return ret;
1078 #if defined(FEAT_MBYTE) || defined(PROTO)
1080 * Note: the following two functions are only guaranteed to work when using
1081 * valid MS-Windows codepages or when iconv() is available.
1085 * Convert "str" from 'encoding' to UCS-2.
1086 * Input in "str" with length "*lenp". When "lenp" is NULL, use strlen().
1087 * Output is returned as an allocated string. "*lenp" is set to the length of
1088 * the result. A trailing NUL is always added.
1089 * Returns NULL when out of memory.
1091 short_u *
1092 enc_to_ucs2(char_u *str, int *lenp)
1094 vimconv_T conv;
1095 WCHAR *ret;
1096 char_u *allocbuf = NULL;
1097 int len_loc;
1098 int length;
1100 if (lenp == NULL)
1102 len_loc = (int)STRLEN(str) + 1;
1103 lenp = &len_loc;
1106 if (enc_codepage > 0)
1108 /* We can do any CP### -> UCS-2 in one pass, and we can do it
1109 * without iconv() (convert_* may need iconv). */
1110 MultiByteToWideChar_alloc(enc_codepage, 0, str, *lenp, &ret, &length);
1112 else
1114 /* Use "latin1" by default, we might be called before we have p_enc
1115 * set up. Convert to utf-8 first, works better with iconv(). Does
1116 * nothing if 'encoding' is "utf-8". */
1117 conv.vc_type = CONV_NONE;
1118 if (convert_setup(&conv, p_enc ? p_enc : (char_u *)"latin1",
1119 (char_u *)"utf-8") == FAIL)
1120 return NULL;
1121 if (conv.vc_type != CONV_NONE)
1123 str = allocbuf = string_convert(&conv, str, lenp);
1124 if (str == NULL)
1125 return NULL;
1127 convert_setup(&conv, NULL, NULL);
1129 length = utf8_to_ucs2(str, *lenp, NULL, NULL);
1130 ret = (WCHAR *)alloc((unsigned)((length + 1) * sizeof(WCHAR)));
1131 if (ret != NULL)
1133 utf8_to_ucs2(str, *lenp, (short_u *)ret, NULL);
1134 ret[length] = 0;
1137 vim_free(allocbuf);
1140 *lenp = length;
1141 return (short_u *)ret;
1145 * Convert an UCS-2 string to 'encoding'.
1146 * Input in "str" with length (counted in wide characters) "*lenp". When
1147 * "lenp" is NULL, use wcslen().
1148 * Output is returned as an allocated string. If "*lenp" is not NULL it is
1149 * set to the length of the result.
1150 * Returns NULL when out of memory.
1152 char_u *
1153 ucs2_to_enc(short_u *str, int *lenp)
1155 vimconv_T conv;
1156 char_u *utf8_str = NULL, *enc_str = NULL;
1157 int len_loc;
1159 if (lenp == NULL)
1161 len_loc = (int)wcslen(str) + 1;
1162 lenp = &len_loc;
1165 if (enc_codepage > 0)
1167 /* We can do any UCS-2 -> CP### in one pass. */
1168 int length;
1170 WideCharToMultiByte_alloc(enc_codepage, 0, str, *lenp,
1171 (LPSTR *)&enc_str, &length, 0, 0);
1172 *lenp = length;
1173 return enc_str;
1176 /* Avoid allocating zero bytes, it generates an error message. */
1177 utf8_str = alloc(ucs2_to_utf8(str, *lenp == 0 ? 1 : *lenp, NULL));
1178 if (utf8_str != NULL)
1180 *lenp = ucs2_to_utf8(str, *lenp, utf8_str);
1182 /* We might be called before we have p_enc set up. */
1183 conv.vc_type = CONV_NONE;
1184 convert_setup(&conv, (char_u *)"utf-8",
1185 p_enc? p_enc: (char_u *)"latin1");
1186 if (conv.vc_type == CONV_NONE)
1188 /* p_enc is utf-8, so we're done. */
1189 enc_str = utf8_str;
1191 else
1193 enc_str = string_convert(&conv, utf8_str, lenp);
1194 vim_free(utf8_str);
1197 convert_setup(&conv, NULL, NULL);
1200 return enc_str;
1202 #endif /* FEAT_MBYTE */
1205 * Get the current selection and put it in the clipboard register.
1207 * NOTE: Must use GlobalLock/Unlock here to ensure Win32s compatibility.
1208 * On NT/W95 the clipboard data is a fixed global memory object and
1209 * so its handle = its pointer.
1210 * On Win32s, however, co-operation with the Win16 system means that
1211 * the clipboard data is moveable and its handle is not a pointer at all,
1212 * so we can't just cast the return value of GetClipboardData to (char_u*).
1213 * <VN>
1215 void
1216 clip_mch_request_selection(VimClipboard *cbd)
1218 VimClipType_t metadata = { -1, -1, -1, -1 };
1219 HGLOBAL hMem = NULL;
1220 char_u *str = NULL;
1221 #if defined(FEAT_MBYTE) && defined(WIN3264)
1222 char_u *to_free = NULL;
1223 #endif
1224 #ifdef FEAT_MBYTE
1225 HGLOBAL rawh = NULL;
1226 #endif
1227 int str_size = 0;
1228 int maxlen;
1229 size_t n;
1232 * Don't pass GetActiveWindow() as an argument to OpenClipboard() because
1233 * then we can't paste back into the same window for some reason - webb.
1235 if (!OpenClipboard(NULL))
1236 return;
1238 /* Check for vim's own clipboard format first. This only gets the type of
1239 * the data, still need to use CF_UNICODETEXT or CF_TEXT for the text. */
1240 if (IsClipboardFormatAvailable(cbd->format))
1242 VimClipType_t *meta_p;
1243 HGLOBAL meta_h;
1245 /* We have metadata on the clipboard; try to get it. */
1246 if ((meta_h = GetClipboardData(cbd->format)) != NULL
1247 && (meta_p = (VimClipType_t *)GlobalLock(meta_h)) != NULL)
1249 /* The size of "VimClipType_t" changed, "rawlen" was added later.
1250 * Only copy what is available for backwards compatibility. */
1251 n = sizeof(VimClipType_t);
1252 if (GlobalSize(meta_h) < n)
1253 n = GlobalSize(meta_h);
1254 memcpy(&metadata, meta_p, n);
1255 GlobalUnlock(meta_h);
1259 #ifdef FEAT_MBYTE
1260 /* Check for Vim's raw clipboard format first. This is used without
1261 * conversion, but only if 'encoding' matches. */
1262 if (IsClipboardFormatAvailable(cbd->format_raw)
1263 && metadata.rawlen > (int)STRLEN(p_enc))
1265 /* We have raw data on the clipboard; try to get it. */
1266 if ((rawh = GetClipboardData(cbd->format_raw)) != NULL)
1268 char_u *rawp;
1270 rawp = (char_u *)GlobalLock(rawh);
1271 if (rawp != NULL && STRCMP(p_enc, rawp) == 0)
1273 n = STRLEN(p_enc) + 1;
1274 str = rawp + n;
1275 str_size = (int)(metadata.rawlen - n);
1277 else
1279 GlobalUnlock(rawh);
1280 rawh = NULL;
1284 if (str == NULL)
1286 #endif
1288 #if defined(FEAT_MBYTE) && defined(WIN3264)
1289 /* Try to get the clipboard in Unicode if it's not an empty string. */
1290 if (IsClipboardFormatAvailable(CF_UNICODETEXT) && metadata.ucslen != 0)
1292 HGLOBAL hMemW;
1294 if ((hMemW = GetClipboardData(CF_UNICODETEXT)) != NULL)
1296 WCHAR *hMemWstr = (WCHAR *)GlobalLock(hMemW);
1298 /* Use the length of our metadata if possible, but limit it to the
1299 * GlobalSize() for safety. */
1300 maxlen = (int)(GlobalSize(hMemW) / sizeof(WCHAR));
1301 if (metadata.ucslen >= 0)
1303 if (metadata.ucslen > maxlen)
1304 str_size = maxlen;
1305 else
1306 str_size = metadata.ucslen;
1308 else
1310 for (str_size = 0; str_size < maxlen; ++str_size)
1311 if (hMemWstr[str_size] == NUL)
1312 break;
1314 to_free = str = ucs2_to_enc((short_u *)hMemWstr, &str_size);
1315 GlobalUnlock(hMemW);
1318 else
1319 #endif
1320 /* Get the clipboard in the Active codepage. */
1321 if (IsClipboardFormatAvailable(CF_TEXT))
1323 if ((hMem = GetClipboardData(CF_TEXT)) != NULL)
1325 str = (char_u *)GlobalLock(hMem);
1327 /* The length is either what our metadata says or the strlen().
1328 * But limit it to the GlobalSize() for safety. */
1329 maxlen = (int)GlobalSize(hMem);
1330 if (metadata.txtlen >= 0)
1332 if (metadata.txtlen > maxlen)
1333 str_size = maxlen;
1334 else
1335 str_size = metadata.txtlen;
1337 else
1339 for (str_size = 0; str_size < maxlen; ++str_size)
1340 if (str[str_size] == NUL)
1341 break;
1344 # if defined(FEAT_MBYTE) && defined(WIN3264)
1345 /* The text is in the active codepage. Convert to 'encoding',
1346 * going through UCS-2. */
1347 acp_to_enc(str, str_size, &to_free, &maxlen);
1348 if (to_free != NULL)
1350 str_size = maxlen;
1351 str = to_free;
1353 # endif
1356 #ifdef FEAT_MBYTE
1358 #endif
1360 if (str != NULL && *str != NUL)
1362 char_u *temp_clipboard;
1364 /* If the type is not known guess it. */
1365 if (metadata.type == -1)
1366 metadata.type = (vim_strchr(str, '\n') == NULL) ? MCHAR : MLINE;
1368 /* Translate <CR><NL> into <NL>. */
1369 temp_clipboard = crnl_to_nl(str, &str_size);
1370 if (temp_clipboard != NULL)
1372 clip_yank_selection(metadata.type, temp_clipboard, str_size, cbd);
1373 vim_free(temp_clipboard);
1377 /* unlock the global object */
1378 if (hMem != NULL)
1379 GlobalUnlock(hMem);
1380 #ifdef FEAT_MBYTE
1381 if (rawh != NULL)
1382 GlobalUnlock(rawh);
1383 #endif
1384 CloseClipboard();
1385 #if defined(FEAT_MBYTE) && defined(WIN3264)
1386 vim_free(to_free);
1387 #endif
1390 #if (defined(FEAT_MBYTE) && defined(WIN3264)) || defined(PROTO)
1392 * Convert from the active codepage to 'encoding'.
1393 * Input is "str[str_size]".
1394 * The result is in allocated memory: "out[outlen]". With terminating NUL.
1396 void
1397 acp_to_enc(str, str_size, out, outlen)
1398 char_u *str;
1399 int str_size;
1400 char_u **out;
1401 int *outlen;
1404 LPWSTR widestr;
1406 MultiByteToWideChar_alloc(GetACP(), 0, str, str_size, &widestr, outlen);
1407 if (widestr != NULL)
1409 ++*outlen; /* Include the 0 after the string */
1410 *out = ucs2_to_enc((short_u *)widestr, outlen);
1411 vim_free(widestr);
1414 #endif
1417 * Send the current selection to the clipboard.
1419 void
1420 clip_mch_set_selection(VimClipboard *cbd)
1422 char_u *str = NULL;
1423 VimClipType_t metadata;
1424 long_u txtlen;
1425 HGLOBAL hMemRaw = NULL;
1426 HGLOBAL hMem = NULL;
1427 HGLOBAL hMemVim = NULL;
1428 # if defined(FEAT_MBYTE) && defined(WIN3264)
1429 HGLOBAL hMemW = NULL;
1430 # endif
1432 /* If the '*' register isn't already filled in, fill it in now */
1433 cbd->owned = TRUE;
1434 clip_get_selection(cbd);
1435 cbd->owned = FALSE;
1437 /* Get the text to be put on the clipboard, with CR-LF. */
1438 metadata.type = clip_convert_selection(&str, &txtlen, cbd);
1439 if (metadata.type < 0)
1440 return;
1441 metadata.txtlen = (int)txtlen;
1442 metadata.ucslen = 0;
1443 metadata.rawlen = 0;
1445 #ifdef FEAT_MBYTE
1446 /* Always set the raw bytes: 'encoding', NUL and the text. This is used
1447 * when copy/paste from/to Vim with the same 'encoding', so that illegal
1448 * bytes can also be copied and no conversion is needed. */
1450 LPSTR lpszMemRaw;
1452 metadata.rawlen = (int)(txtlen + STRLEN(p_enc) + 1);
1453 hMemRaw = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1454 metadata.rawlen + 1);
1455 lpszMemRaw = (LPSTR)GlobalLock(hMemRaw);
1456 if (lpszMemRaw != NULL)
1458 STRCPY(lpszMemRaw, p_enc);
1459 memcpy(lpszMemRaw + STRLEN(p_enc) + 1, str, txtlen + 1);
1460 GlobalUnlock(hMemRaw);
1462 else
1463 metadata.rawlen = 0;
1465 #endif
1467 # if defined(FEAT_MBYTE) && defined(WIN3264)
1469 WCHAR *out;
1470 int len = metadata.txtlen;
1472 /* Convert the text to UCS-2. This is put on the clipboard as
1473 * CF_UNICODETEXT. */
1474 out = (WCHAR *)enc_to_ucs2(str, &len);
1475 if (out != NULL)
1477 WCHAR *lpszMemW;
1479 /* Convert the text for CF_TEXT to Active codepage. Otherwise it's
1480 * p_enc, which has no relation to the Active codepage. */
1481 metadata.txtlen = WideCharToMultiByte(GetACP(), 0, out, len,
1482 NULL, 0, 0, 0);
1483 vim_free(str);
1484 str = (char_u *)alloc((unsigned)(metadata.txtlen == 0 ? 1
1485 : metadata.txtlen));
1486 if (str == NULL)
1488 vim_free(out);
1489 return; /* out of memory */
1491 WideCharToMultiByte(GetACP(), 0, out, len,
1492 str, metadata.txtlen, 0, 0);
1494 /* Allocate memory for the UCS-2 text, add one NUL word to
1495 * terminate the string. */
1496 hMemW = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1497 (len + 1) * sizeof(WCHAR));
1498 lpszMemW = (WCHAR *)GlobalLock(hMemW);
1499 if (lpszMemW != NULL)
1501 memcpy(lpszMemW, out, len * sizeof(WCHAR));
1502 lpszMemW[len] = NUL;
1503 GlobalUnlock(hMemW);
1505 vim_free(out);
1506 metadata.ucslen = len;
1509 # endif
1511 /* Allocate memory for the text, add one NUL byte to terminate the string.
1513 hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, metadata.txtlen + 1);
1515 LPSTR lpszMem = (LPSTR)GlobalLock(hMem);
1517 if (lpszMem)
1519 vim_strncpy(lpszMem, str, metadata.txtlen);
1520 GlobalUnlock(hMem);
1524 /* Set up metadata: */
1526 VimClipType_t *lpszMemVim = NULL;
1528 hMemVim = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,
1529 sizeof(VimClipType_t));
1530 lpszMemVim = (VimClipType_t *)GlobalLock(hMemVim);
1531 memcpy(lpszMemVim, &metadata, sizeof(metadata));
1532 GlobalUnlock(hMemVim);
1536 * Open the clipboard, clear it and put our text on it.
1537 * Always set our Vim format. Put Unicode and plain text on it.
1539 * Don't pass GetActiveWindow() as an argument to OpenClipboard()
1540 * because then we can't paste back into the same window for some
1541 * reason - webb.
1543 if (OpenClipboard(NULL))
1545 if (EmptyClipboard())
1547 SetClipboardData(cbd->format, hMemVim);
1548 hMemVim = 0;
1549 # if defined(FEAT_MBYTE) && defined(WIN3264)
1550 if (hMemW != NULL)
1552 if (SetClipboardData(CF_UNICODETEXT, hMemW) != NULL)
1553 hMemW = NULL;
1555 # endif
1556 /* Always use CF_TEXT. On Win98 Notepad won't obtain the
1557 * CF_UNICODETEXT text, only CF_TEXT. */
1558 SetClipboardData(CF_TEXT, hMem);
1559 hMem = 0;
1561 CloseClipboard();
1564 vim_free(str);
1565 /* Free any allocations we didn't give to the clipboard: */
1566 if (hMemRaw)
1567 GlobalFree(hMemRaw);
1568 if (hMem)
1569 GlobalFree(hMem);
1570 # if defined(FEAT_MBYTE) && defined(WIN3264)
1571 if (hMemW)
1572 GlobalFree(hMemW);
1573 # endif
1574 if (hMemVim)
1575 GlobalFree(hMemVim);
1578 #endif /* FEAT_CLIPBOARD */
1582 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
1584 /*ARGSUSED*/
1585 void
1586 DumpPutS(
1587 const char *psz)
1589 # ifdef MCH_WRITE_DUMP
1590 if (fdDump)
1592 fputs(psz, fdDump);
1593 if (psz[strlen(psz) - 1] != '\n')
1594 fputc('\n', fdDump);
1595 fflush(fdDump);
1597 # endif
1600 #ifdef _DEBUG
1602 void __cdecl
1603 Trace(
1604 char *pszFormat,
1605 ...)
1607 CHAR szBuff[2048];
1608 va_list args;
1610 va_start(args, pszFormat);
1611 vsprintf(szBuff, pszFormat, args);
1612 va_end(args);
1614 OutputDebugString(szBuff);
1617 #endif //_DEBUG
1619 #if !defined(FEAT_GUI) || defined(PROTO)
1620 # if defined(FEAT_TITLE) && defined(WIN3264)
1621 extern HWND g_hWnd; /* This is in os_win32.c. */
1622 # endif
1625 * Showing the printer dialog is tricky since we have no GUI
1626 * window to parent it. The following routines are needed to
1627 * get the window parenting and Z-order to work properly.
1629 static void
1630 GetConsoleHwnd(void)
1632 # define MY_BUFSIZE 1024 // Buffer size for console window titles.
1634 char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
1635 char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
1637 /* Skip if it's already set. */
1638 if (s_hwnd != 0)
1639 return;
1641 # if defined(FEAT_TITLE) && defined(WIN3264)
1642 /* Window handle may have been found by init code (Windows NT only) */
1643 if (g_hWnd != 0)
1645 s_hwnd = g_hWnd;
1646 return;
1648 # endif
1650 GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
1652 wsprintf(pszNewWindowTitle, "%s/%d/%d",
1653 pszOldWindowTitle,
1654 GetTickCount(),
1655 GetCurrentProcessId());
1656 SetConsoleTitle(pszNewWindowTitle);
1657 Sleep(40);
1658 s_hwnd = FindWindow(NULL, pszNewWindowTitle);
1660 SetConsoleTitle(pszOldWindowTitle);
1664 * Console implementation of ":winpos".
1667 mch_get_winpos(int *x, int *y)
1669 RECT rect;
1671 GetConsoleHwnd();
1672 GetWindowRect(s_hwnd, &rect);
1673 *x = rect.left;
1674 *y = rect.top;
1675 return OK;
1679 * Console implementation of ":winpos x y".
1681 void
1682 mch_set_winpos(int x, int y)
1684 GetConsoleHwnd();
1685 SetWindowPos(s_hwnd, NULL, x, y, 0, 0,
1686 SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1688 #endif
1690 #if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1692 # ifdef WIN16
1693 # define TEXT(a) a
1694 # endif
1695 /*=================================================================
1696 * Win32 printer stuff
1699 static HFONT prt_font_handles[2][2][2];
1700 static PRINTDLG prt_dlg;
1701 static const int boldface[2] = {FW_REGULAR, FW_BOLD};
1702 static TEXTMETRIC prt_tm;
1703 static int prt_line_height;
1704 static int prt_number_width;
1705 static int prt_left_margin;
1706 static int prt_right_margin;
1707 static int prt_top_margin;
1708 static char_u szAppName[] = TEXT("VIM");
1709 static HWND hDlgPrint;
1710 static int *bUserAbort = NULL;
1711 static char_u *prt_name = NULL;
1713 /* Defines which are also in vim.rc. */
1714 #define IDC_BOX1 400
1715 #define IDC_PRINTTEXT1 401
1716 #define IDC_PRINTTEXT2 402
1717 #define IDC_PROGRESS 403
1720 * Convert BGR to RGB for Windows GDI calls
1722 static COLORREF
1723 swap_me(COLORREF colorref)
1725 int temp;
1726 char *ptr = (char *)&colorref;
1728 temp = *(ptr);
1729 *(ptr ) = *(ptr + 2);
1730 *(ptr + 2) = temp;
1731 return colorref;
1734 /*ARGSUSED*/
1735 static BOOL CALLBACK
1736 PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
1738 #ifdef FEAT_GETTEXT
1739 NONCLIENTMETRICS nm;
1740 static HFONT hfont;
1741 #endif
1743 switch (message)
1745 case WM_INITDIALOG:
1746 #ifdef FEAT_GETTEXT
1747 nm.cbSize = sizeof(NONCLIENTMETRICS);
1748 if (SystemParametersInfo(
1749 SPI_GETNONCLIENTMETRICS,
1750 sizeof(NONCLIENTMETRICS),
1751 &nm,
1754 char buff[MAX_PATH];
1755 int i;
1757 /* Translate the dialog texts */
1758 hfont = CreateFontIndirect(&nm.lfMessageFont);
1759 for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++)
1761 SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1);
1762 if (GetDlgItemText(hDlg,i, buff, sizeof(buff)))
1763 SetDlgItemText(hDlg,i, _(buff));
1765 SendDlgItemMessage(hDlg, IDCANCEL,
1766 WM_SETFONT, (WPARAM)hfont, 1);
1767 if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff)))
1768 SetDlgItemText(hDlg,IDCANCEL, _(buff));
1770 #endif
1771 SetWindowText(hDlg, szAppName);
1772 if (prt_name != NULL)
1774 SetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name);
1775 vim_free(prt_name);
1776 prt_name = NULL;
1778 EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED);
1779 #ifndef FEAT_GUI
1780 BringWindowToTop(s_hwnd);
1781 #endif
1782 return TRUE;
1784 case WM_COMMAND:
1785 *bUserAbort = TRUE;
1786 EnableWindow(GetParent(hDlg), TRUE);
1787 DestroyWindow(hDlg);
1788 hDlgPrint = NULL;
1789 #ifdef FEAT_GETTEXT
1790 DeleteObject(hfont);
1791 #endif
1792 return TRUE;
1794 return FALSE;
1797 /*ARGSUSED*/
1798 static BOOL CALLBACK
1799 AbortProc(HDC hdcPrn, int iCode)
1801 MSG msg;
1803 while (!*bUserAbort && PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1805 if (!hDlgPrint || !IsDialogMessage(hDlgPrint, &msg))
1807 TranslateMessage(&msg);
1808 DispatchMessage(&msg);
1811 return !*bUserAbort;
1814 #ifndef FEAT_GUI
1816 static UINT CALLBACK
1817 PrintHookProc(
1818 HWND hDlg, // handle to dialog box
1819 UINT uiMsg, // message identifier
1820 WPARAM wParam, // message parameter
1821 LPARAM lParam // message parameter
1824 HWND hwndOwner;
1825 RECT rc, rcDlg, rcOwner;
1826 PRINTDLG *pPD;
1828 if (uiMsg == WM_INITDIALOG)
1830 // Get the owner window and dialog box rectangles.
1831 if ((hwndOwner = GetParent(hDlg)) == NULL)
1832 hwndOwner = GetDesktopWindow();
1834 GetWindowRect(hwndOwner, &rcOwner);
1835 GetWindowRect(hDlg, &rcDlg);
1836 CopyRect(&rc, &rcOwner);
1838 // Offset the owner and dialog box rectangles so that
1839 // right and bottom values represent the width and
1840 // height, and then offset the owner again to discard
1841 // space taken up by the dialog box.
1843 OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
1844 OffsetRect(&rc, -rc.left, -rc.top);
1845 OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
1847 // The new position is the sum of half the remaining
1848 // space and the owner's original position.
1850 SetWindowPos(hDlg,
1851 HWND_TOP,
1852 rcOwner.left + (rc.right / 2),
1853 rcOwner.top + (rc.bottom / 2),
1854 0, 0, // ignores size arguments
1855 SWP_NOSIZE);
1857 /* tackle the printdlg copiesctrl problem */
1858 pPD = (PRINTDLG *)lParam;
1859 pPD->nCopies = (WORD)pPD->lCustData;
1860 SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE );
1861 /* Bring the window to top */
1862 BringWindowToTop(GetParent(hDlg));
1863 SetForegroundWindow(hDlg);
1866 return FALSE;
1868 #endif
1870 void
1871 mch_print_cleanup(void)
1873 int pifItalic;
1874 int pifBold;
1875 int pifUnderline;
1877 for (pifBold = 0; pifBold <= 1; pifBold++)
1878 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1879 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1880 DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]);
1882 if (prt_dlg.hDC != NULL)
1883 DeleteDC(prt_dlg.hDC);
1884 if (!*bUserAbort)
1885 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1888 static int
1889 to_device_units(int idx, int dpi, int physsize, int offset, int def_number)
1891 int ret = 0;
1892 int u;
1893 int nr;
1895 u = prt_get_unit(idx);
1896 if (u == PRT_UNIT_NONE)
1898 u = PRT_UNIT_PERC;
1899 nr = def_number;
1901 else
1902 nr = printer_opts[idx].number;
1904 switch (u)
1906 case PRT_UNIT_PERC:
1907 ret = (physsize * nr) / 100;
1908 break;
1909 case PRT_UNIT_INCH:
1910 ret = (nr * dpi);
1911 break;
1912 case PRT_UNIT_MM:
1913 ret = (nr * 10 * dpi) / 254;
1914 break;
1915 case PRT_UNIT_POINT:
1916 ret = (nr * 10 * dpi) / 720;
1917 break;
1920 if (ret < offset)
1921 return 0;
1922 else
1923 return ret - offset;
1926 static int
1927 prt_get_cpl(void)
1929 int hr;
1930 int phyw;
1931 int dvoff;
1932 int rev_offset;
1933 int dpi;
1934 #ifdef WIN16
1935 POINT pagesize;
1936 #endif
1938 GetTextMetrics(prt_dlg.hDC, &prt_tm);
1939 prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading;
1941 hr = GetDeviceCaps(prt_dlg.hDC, HORZRES);
1942 #ifdef WIN16
1943 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1944 phyw = pagesize.x;
1945 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1946 dvoff = pagesize.x;
1947 #else
1948 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH);
1949 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX);
1950 #endif
1951 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX);
1953 rev_offset = phyw - (dvoff + hr);
1955 prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10);
1956 if (prt_use_number())
1958 prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth;
1959 prt_left_margin += prt_number_width;
1961 else
1962 prt_number_width = 0;
1964 prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw,
1965 rev_offset, 5);
1967 return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth;
1970 static int
1971 prt_get_lpp(void)
1973 int vr;
1974 int phyw;
1975 int dvoff;
1976 int rev_offset;
1977 int bottom_margin;
1978 int dpi;
1979 #ifdef WIN16
1980 POINT pagesize;
1981 #endif
1983 vr = GetDeviceCaps(prt_dlg.hDC, VERTRES);
1984 #ifdef WIN16
1985 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
1986 phyw = pagesize.y;
1987 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
1988 dvoff = pagesize.y;
1989 #else
1990 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT);
1991 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY);
1992 #endif
1993 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY);
1995 rev_offset = phyw - (dvoff + vr);
1997 prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5);
1999 /* adjust top margin if there is a header */
2000 prt_top_margin += prt_line_height * prt_header_height();
2002 bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw,
2003 rev_offset, 5);
2005 return (bottom_margin - prt_top_margin) / prt_line_height;
2009 mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
2011 static HGLOBAL stored_dm = NULL;
2012 static HGLOBAL stored_devn = NULL;
2013 static int stored_nCopies = 1;
2014 static int stored_nFlags = 0;
2016 LOGFONT fLogFont;
2017 int pifItalic;
2018 int pifBold;
2019 int pifUnderline;
2021 DEVMODE *mem;
2022 DEVNAMES *devname;
2023 int i;
2025 bUserAbort = &(psettings->user_abort);
2026 memset(&prt_dlg, 0, sizeof(PRINTDLG));
2027 prt_dlg.lStructSize = sizeof(PRINTDLG);
2028 #ifndef FEAT_GUI
2029 GetConsoleHwnd(); /* get value of s_hwnd */
2030 #endif
2031 prt_dlg.hwndOwner = s_hwnd;
2032 prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
2033 if (!forceit)
2035 prt_dlg.hDevMode = stored_dm;
2036 prt_dlg.hDevNames = stored_devn;
2037 prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog
2038 #ifndef FEAT_GUI
2040 * Use hook to prevent console window being sent to back
2042 prt_dlg.lpfnPrintHook = PrintHookProc;
2043 prt_dlg.Flags |= PD_ENABLEPRINTHOOK;
2044 #endif
2045 prt_dlg.Flags |= stored_nFlags;
2049 * If bang present, return default printer setup with no dialog
2050 * never show dialog if we are running over telnet
2052 if (forceit
2053 #ifndef FEAT_GUI
2054 || !term_console
2055 #endif
2058 prt_dlg.Flags |= PD_RETURNDEFAULT;
2059 #ifdef WIN3264
2061 * MSDN suggests setting the first parameter to WINSPOOL for
2062 * NT, but NULL appears to work just as well.
2064 if (*p_pdev != NUL)
2065 prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL);
2066 else
2067 #endif
2069 prt_dlg.Flags |= PD_RETURNDEFAULT;
2070 if (PrintDlg(&prt_dlg) == 0)
2071 goto init_fail_dlg;
2074 else if (PrintDlg(&prt_dlg) == 0)
2075 goto init_fail_dlg;
2076 else
2079 * keep the previous driver context
2081 stored_dm = prt_dlg.hDevMode;
2082 stored_devn = prt_dlg.hDevNames;
2083 stored_nFlags = prt_dlg.Flags;
2084 stored_nCopies = prt_dlg.nCopies;
2087 if (prt_dlg.hDC == NULL)
2089 EMSG(_("E237: Printer selection failed"));
2090 mch_print_cleanup();
2091 return FALSE;
2094 /* Not all printer drivers report the support of color (or grey) in the
2095 * same way. Let's set has_color if there appears to be some way to print
2096 * more than B&W. */
2097 i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS);
2098 psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1
2099 || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1
2100 || i > 2 || i == -1);
2102 /* Ensure all font styles are baseline aligned */
2103 SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT);
2106 * On some windows systems the nCopies parameter is not
2107 * passed back correctly. It must be retrieved from the
2108 * hDevMode struct.
2110 mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode);
2111 if (mem != NULL)
2113 #ifdef WIN3264
2114 if (mem->dmCopies != 1)
2115 stored_nCopies = mem->dmCopies;
2116 #endif
2117 if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX))
2118 psettings->duplex = TRUE;
2119 if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR))
2120 psettings->has_color = TRUE;
2122 GlobalUnlock(prt_dlg.hDevMode);
2124 devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames);
2125 if (devname != 0)
2127 char_u *printer_name = (char_u *)devname + devname->wDeviceOffset;
2128 char_u *port_name = (char_u *)devname +devname->wOutputOffset;
2129 char_u *text = _("to %s on %s");
2131 prt_name = alloc(STRLEN(printer_name) + STRLEN(port_name)
2132 + STRLEN(text));
2133 if (prt_name != NULL)
2134 wsprintf(prt_name, text, printer_name, port_name);
2136 GlobalUnlock(prt_dlg.hDevNames);
2139 * Initialise the font according to 'printfont'
2141 memset(&fLogFont, 0, sizeof(fLogFont));
2142 if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL)
2144 EMSG2(_("E613: Unknown printer font: %s"), p_pfn);
2145 mch_print_cleanup();
2146 return FALSE;
2149 for (pifBold = 0; pifBold <= 1; pifBold++)
2150 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
2151 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
2153 fLogFont.lfWeight = boldface[pifBold];
2154 fLogFont.lfItalic = pifItalic;
2155 fLogFont.lfUnderline = pifUnderline;
2156 prt_font_handles[pifBold][pifItalic][pifUnderline]
2157 = CreateFontIndirect(&fLogFont);
2160 SetBkMode(prt_dlg.hDC, OPAQUE);
2161 SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]);
2164 * Fill in the settings struct
2166 psettings->chars_per_line = prt_get_cpl();
2167 psettings->lines_per_page = prt_get_lpp();
2168 psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE)
2169 ? prt_dlg.nCopies : 1;
2170 psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE)
2171 ? 1 : prt_dlg.nCopies;
2173 if (psettings->n_collated_copies == 0)
2174 psettings->n_collated_copies = 1;
2176 if (psettings->n_uncollated_copies == 0)
2177 psettings->n_uncollated_copies = 1;
2179 psettings->jobname = jobname;
2181 return TRUE;
2183 init_fail_dlg:
2185 DWORD err = CommDlgExtendedError();
2187 if (err)
2189 #ifdef WIN16
2190 char buf[20];
2192 sprintf(buf, "%ld", err);
2193 EMSG2(_("E238: Print error: %s"), buf);
2194 #else
2195 char_u *buf;
2197 /* I suspect FormatMessage() doesn't work for values returned by
2198 * CommDlgExtendedError(). What does? */
2199 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2200 FORMAT_MESSAGE_FROM_SYSTEM |
2201 FORMAT_MESSAGE_IGNORE_INSERTS,
2202 NULL, err, 0, (LPTSTR)(&buf), 0, NULL);
2203 EMSG2(_("E238: Print error: %s"),
2204 buf == NULL ? (char_u *)_("Unknown") : buf);
2205 LocalFree((LPVOID)(buf));
2206 #endif
2208 else
2209 msg_clr_eos(); /* Maybe canceled */
2211 mch_print_cleanup();
2212 return FALSE;
2218 mch_print_begin(prt_settings_T *psettings)
2220 int ret;
2221 static DOCINFO di;
2222 char szBuffer[300];
2224 hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"),
2225 prt_dlg.hwndOwner, PrintDlgProc);
2226 #ifdef WIN16
2227 Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL);
2228 #else
2229 SetAbortProc(prt_dlg.hDC, AbortProc);
2230 #endif
2231 wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname));
2232 SetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer);
2234 memset(&di, 0, sizeof(DOCINFO));
2235 di.cbSize = sizeof(DOCINFO);
2236 di.lpszDocName = psettings->jobname;
2237 ret = StartDoc(prt_dlg.hDC, &di);
2239 #ifdef FEAT_GUI
2240 /* Give focus back to main window (when using MDI). */
2241 SetFocus(s_hwnd);
2242 #endif
2244 return (ret > 0);
2247 /*ARGSUSED*/
2248 void
2249 mch_print_end(prt_settings_T *psettings)
2251 EndDoc(prt_dlg.hDC);
2252 if (!*bUserAbort)
2253 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
2257 mch_print_end_page(void)
2259 return (EndPage(prt_dlg.hDC) > 0);
2263 mch_print_begin_page(char_u *msg)
2265 if (msg != NULL)
2266 SetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg);
2267 return (StartPage(prt_dlg.hDC) > 0);
2271 mch_print_blank_page(void)
2273 return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
2276 static int prt_pos_x = 0;
2277 static int prt_pos_y = 0;
2279 void
2280 mch_print_start_line(margin, page_line)
2281 int margin;
2282 int page_line;
2284 if (margin)
2285 prt_pos_x = -prt_number_width;
2286 else
2287 prt_pos_x = 0;
2288 prt_pos_y = page_line * prt_line_height
2289 + prt_tm.tmAscent + prt_tm.tmExternalLeading;
2293 mch_print_text_out(char_u *p, int len)
2295 #ifdef FEAT_PROPORTIONAL_FONTS
2296 SIZE sz;
2297 #endif
2299 TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin,
2300 prt_pos_y + prt_top_margin, p, len);
2301 #ifndef FEAT_PROPORTIONAL_FONTS
2302 prt_pos_x += len * prt_tm.tmAveCharWidth;
2303 return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth
2304 + prt_tm.tmOverhang > prt_right_margin);
2305 #else
2306 # ifdef WIN16
2307 GetTextExtentPoint(prt_dlg.hDC, p, len, &sz);
2308 # else
2309 GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz);
2310 # endif
2311 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
2312 /* This is wrong when printing spaces for a TAB. */
2313 if (p[len] == NUL)
2314 return FALSE;
2315 # ifdef WIN16
2316 GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz);
2317 # else
2318 GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz);
2319 # endif
2320 return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
2321 #endif
2324 void
2325 mch_print_set_font(int iBold, int iItalic, int iUnderline)
2327 SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]);
2330 void
2331 mch_print_set_bg(long_u bgcol)
2333 SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
2334 swap_me((COLORREF)bgcol)));
2336 * With a white background we can draw characters transparent, which is
2337 * good for italic characters that overlap to the next char cell.
2339 if (bgcol == 0xffffffUL)
2340 SetBkMode(prt_dlg.hDC, TRANSPARENT);
2341 else
2342 SetBkMode(prt_dlg.hDC, OPAQUE);
2345 void
2346 mch_print_set_fg(long_u fgcol)
2348 SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
2349 swap_me((COLORREF)fgcol)));
2352 #endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
2356 #if defined(FEAT_SHORTCUT) || defined(PROTO)
2357 # include <shlobj.h>
2360 * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
2361 * to and return that name in allocated memory.
2362 * Otherwise NULL is returned.
2364 char_u *
2365 mch_resolve_shortcut(char_u *fname)
2367 HRESULT hr;
2368 IShellLink *psl = NULL;
2369 IPersistFile *ppf = NULL;
2370 OLECHAR wsz[MAX_PATH];
2371 WIN32_FIND_DATA ffd; // we get those free of charge
2372 TCHAR buf[MAX_PATH]; // could have simply reused 'wsz'...
2373 char_u *rfname = NULL;
2374 int len;
2376 /* Check if the file name ends in ".lnk". Avoid calling
2377 * CoCreateInstance(), it's quite slow. */
2378 if (fname == NULL)
2379 return rfname;
2380 len = (int)STRLEN(fname);
2381 if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
2382 return rfname;
2384 CoInitialize(NULL);
2386 // create a link manager object and request its interface
2387 hr = CoCreateInstance(
2388 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2389 &IID_IShellLink, (void**)&psl);
2390 if (hr != S_OK)
2391 goto shortcut_error;
2393 // Get a pointer to the IPersistFile interface.
2394 hr = psl->lpVtbl->QueryInterface(
2395 psl, &IID_IPersistFile, (void**)&ppf);
2396 if (hr != S_OK)
2397 goto shortcut_error;
2399 // full path string must be in Unicode.
2400 MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
2402 // "load" the name and resolve the link
2403 hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
2404 if (hr != S_OK)
2405 goto shortcut_error;
2406 #if 0 // This makes Vim wait a long time if the target doesn't exist.
2407 hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
2408 if (hr != S_OK)
2409 goto shortcut_error;
2410 #endif
2412 // Get the path to the link target.
2413 ZeroMemory(buf, MAX_PATH);
2414 hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
2415 if (hr == S_OK && buf[0] != NUL)
2416 rfname = vim_strsave(buf);
2418 shortcut_error:
2419 // Release all interface pointers (both belong to the same object)
2420 if (ppf != NULL)
2421 ppf->lpVtbl->Release(ppf);
2422 if (psl != NULL)
2423 psl->lpVtbl->Release(psl);
2425 CoUninitialize();
2426 return rfname;
2428 #endif
2430 #if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
2432 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
2434 void
2435 win32_set_foreground()
2437 # ifndef FEAT_GUI
2438 GetConsoleHwnd(); /* get value of s_hwnd */
2439 # endif
2440 if (s_hwnd != 0)
2441 SetForegroundWindow(s_hwnd);
2443 #endif
2445 #if defined(FEAT_CLIENTSERVER) || defined(PROTO)
2447 * Client-server code for Vim
2449 * Originally written by Paul Moore
2452 /* In order to handle inter-process messages, we need to have a window. But
2453 * the functions in this module can be called before the main GUI window is
2454 * created (and may also be called in the console version, where there is no
2455 * GUI window at all).
2457 * So we create a hidden window, and arrange to destroy it on exit.
2459 HWND message_window = 0; /* window that's handling messsages */
2461 #define VIM_CLASSNAME "VIM_MESSAGES"
2462 #define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
2464 /* Communication is via WM_COPYDATA messages. The message type is send in
2465 * the dwData parameter. Types are defined here. */
2466 #define COPYDATA_KEYS 0
2467 #define COPYDATA_REPLY 1
2468 #define COPYDATA_EXPR 10
2469 #define COPYDATA_RESULT 11
2470 #define COPYDATA_ERROR_RESULT 12
2471 #define COPYDATA_ENCODING 20
2473 /* This is a structure containing a server HWND and its name. */
2474 struct server_id
2476 HWND hwnd;
2477 char_u *name;
2480 /* Last received 'encoding' that the client uses. */
2481 static char_u *client_enc = NULL;
2484 * Tell the other side what encoding we are using.
2485 * Errors are ignored.
2487 static void
2488 serverSendEnc(HWND target)
2490 COPYDATASTRUCT data;
2492 data.dwData = COPYDATA_ENCODING;
2493 #ifdef FEAT_MBYTE
2494 data.cbData = (DWORD)STRLEN(p_enc) + 1;
2495 data.lpData = p_enc;
2496 #else
2497 data.cbData = STRLEN("latin1") + 1;
2498 data.lpData = "latin1";
2499 #endif
2500 (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2501 (LPARAM)(&data));
2505 * Clean up on exit. This destroys the hidden message window.
2507 static void
2508 #ifdef __BORLANDC__
2509 _RTLENTRYF
2510 #endif
2511 CleanUpMessaging(void)
2513 if (message_window != 0)
2515 DestroyWindow(message_window);
2516 message_window = 0;
2520 static int save_reply(HWND server, char_u *reply, int expr);
2523 * The window procedure for the hidden message window.
2524 * It handles callback messages and notifications from servers.
2525 * In order to process these messages, it is necessary to run a
2526 * message loop. Code which may run before the main message loop
2527 * is started (in the GUI) is careful to pump messages when it needs
2528 * to. Features which require message delivery during normal use will
2529 * not work in the console version - this basically means those
2530 * features which allow Vim to act as a server, rather than a client.
2532 static LRESULT CALLBACK
2533 Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2535 if (msg == WM_COPYDATA)
2537 /* This is a message from another Vim. The dwData member of the
2538 * COPYDATASTRUCT determines the type of message:
2539 * COPYDATA_ENCODING:
2540 * The encoding that the client uses. Following messages will
2541 * use this encoding, convert if needed.
2542 * COPYDATA_KEYS:
2543 * A key sequence. We are a server, and a client wants these keys
2544 * adding to the input queue.
2545 * COPYDATA_REPLY:
2546 * A reply. We are a client, and a server has sent this message
2547 * in response to a request. (server2client())
2548 * COPYDATA_EXPR:
2549 * An expression. We are a server, and a client wants us to
2550 * evaluate this expression.
2551 * COPYDATA_RESULT:
2552 * A reply. We are a client, and a server has sent this message
2553 * in response to a COPYDATA_EXPR.
2554 * COPYDATA_ERROR_RESULT:
2555 * A reply. We are a client, and a server has sent this message
2556 * in response to a COPYDATA_EXPR that failed to evaluate.
2558 COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam;
2559 HWND sender = (HWND)wParam;
2560 COPYDATASTRUCT reply;
2561 char_u *res;
2562 char_u winstr[30];
2563 int retval;
2564 char_u *str;
2565 char_u *tofree;
2567 switch (data->dwData)
2569 case COPYDATA_ENCODING:
2570 # ifdef FEAT_MBYTE
2571 /* Remember the encoding that the client uses. */
2572 vim_free(client_enc);
2573 client_enc = enc_canonize((char_u *)data->lpData);
2574 # endif
2575 return 1;
2577 case COPYDATA_KEYS:
2578 /* Remember who sent this, for <client> */
2579 clientWindow = sender;
2581 /* Add the received keys to the input buffer. The loop waiting
2582 * for the user to do something should check the input buffer. */
2583 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2584 server_to_input_buf(str);
2585 vim_free(tofree);
2587 # ifdef FEAT_GUI
2588 /* Wake up the main GUI loop. */
2589 if (s_hwnd != 0)
2590 PostMessage(s_hwnd, WM_NULL, 0, 0);
2591 # endif
2592 return 1;
2594 case COPYDATA_EXPR:
2595 /* Remember who sent this, for <client> */
2596 clientWindow = sender;
2598 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2599 res = eval_client_expr_to_string(str);
2600 vim_free(tofree);
2602 if (res == NULL)
2604 res = vim_strsave(_(e_invexprmsg));
2605 reply.dwData = COPYDATA_ERROR_RESULT;
2607 else
2608 reply.dwData = COPYDATA_RESULT;
2609 reply.lpData = res;
2610 reply.cbData = (DWORD)STRLEN(res) + 1;
2612 serverSendEnc(sender);
2613 retval = (int)SendMessage(sender, WM_COPYDATA, (WPARAM)message_window,
2614 (LPARAM)(&reply));
2615 vim_free(res);
2616 return retval;
2618 case COPYDATA_REPLY:
2619 case COPYDATA_RESULT:
2620 case COPYDATA_ERROR_RESULT:
2621 if (data->lpData != NULL)
2623 str = serverConvert(client_enc, (char_u *)data->lpData,
2624 &tofree);
2625 if (tofree == NULL)
2626 str = vim_strsave(str);
2627 if (save_reply(sender, str,
2628 (data->dwData == COPYDATA_REPLY ? 0 :
2629 (data->dwData == COPYDATA_RESULT ? 1 :
2630 2))) == FAIL)
2631 vim_free(str);
2632 #ifdef FEAT_AUTOCMD
2633 else if (data->dwData == COPYDATA_REPLY)
2635 sprintf((char *)winstr, PRINTF_HEX_LONG_U, (long_u)sender);
2636 apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
2637 TRUE, curbuf);
2639 #endif
2641 return 1;
2644 return 0;
2647 else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2649 /* When the message window is activated (brought to the foreground),
2650 * this actually applies to the text window. */
2651 #ifndef FEAT_GUI
2652 GetConsoleHwnd(); /* get value of s_hwnd */
2653 #endif
2654 if (s_hwnd != 0)
2656 SetForegroundWindow(s_hwnd);
2657 return 0;
2661 return DefWindowProc(hwnd, msg, wParam, lParam);
2665 * Initialise the message handling process. This involves creating a window
2666 * to handle messages - the window will not be visible.
2668 void
2669 serverInitMessaging(void)
2671 WNDCLASS wndclass;
2672 HINSTANCE s_hinst;
2674 /* Clean up on exit */
2675 atexit(CleanUpMessaging);
2677 /* Register a window class - we only really care
2678 * about the window procedure
2680 s_hinst = (HINSTANCE)GetModuleHandle(0);
2681 wndclass.style = 0;
2682 wndclass.lpfnWndProc = Messaging_WndProc;
2683 wndclass.cbClsExtra = 0;
2684 wndclass.cbWndExtra = 0;
2685 wndclass.hInstance = s_hinst;
2686 wndclass.hIcon = NULL;
2687 wndclass.hCursor = NULL;
2688 wndclass.hbrBackground = NULL;
2689 wndclass.lpszMenuName = NULL;
2690 wndclass.lpszClassName = VIM_CLASSNAME;
2691 RegisterClass(&wndclass);
2693 /* Create the message window. It will be hidden, so the details don't
2694 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2695 * focus from gvim. */
2696 message_window = CreateWindow(VIM_CLASSNAME, "",
2697 WS_POPUPWINDOW | WS_CAPTION,
2698 CW_USEDEFAULT, CW_USEDEFAULT,
2699 100, 100, NULL, NULL,
2700 s_hinst, NULL);
2703 /* Used by serverSendToVim() to find an alternate server name. */
2704 static char_u *altname_buf_ptr = NULL;
2707 * Get the title of the window "hwnd", which is the Vim server name, in
2708 * "name[namelen]" and return the length.
2709 * Returns zero if window "hwnd" is not a Vim server.
2711 static int
2712 getVimServerName(HWND hwnd, char *name, int namelen)
2714 int len;
2715 char buffer[VIM_CLASSNAME_LEN + 1];
2717 /* Ignore windows which aren't Vim message windows */
2718 len = GetClassName(hwnd, buffer, sizeof(buffer));
2719 if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2720 return 0;
2722 /* Get the title of the window */
2723 return GetWindowText(hwnd, name, namelen);
2726 static BOOL CALLBACK
2727 enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2729 struct server_id *id = (struct server_id *)lparam;
2730 char server[MAX_PATH];
2732 /* Get the title of the window */
2733 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2734 return TRUE;
2736 /* If this is the server we're looking for, return its HWND */
2737 if (STRICMP(server, id->name) == 0)
2739 id->hwnd = hwnd;
2740 return FALSE;
2743 /* If we are looking for an alternate server, remember this name. */
2744 if (altname_buf_ptr != NULL
2745 && STRNICMP(server, id->name, STRLEN(id->name)) == 0
2746 && vim_isdigit(server[STRLEN(id->name)]))
2748 STRCPY(altname_buf_ptr, server);
2749 altname_buf_ptr = NULL; /* don't use another name */
2752 /* Otherwise, keep looking */
2753 return TRUE;
2756 static BOOL CALLBACK
2757 enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2759 garray_T *ga = (garray_T *)lparam;
2760 char server[MAX_PATH];
2762 /* Get the title of the window */
2763 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2764 return TRUE;
2766 /* Add the name to the list */
2767 ga_concat(ga, server);
2768 ga_concat(ga, "\n");
2769 return TRUE;
2772 static HWND
2773 findServer(char_u *name)
2775 struct server_id id;
2777 id.name = name;
2778 id.hwnd = 0;
2780 EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2782 return id.hwnd;
2785 void
2786 serverSetName(char_u *name)
2788 char_u *ok_name;
2789 HWND hwnd = 0;
2790 int i = 0;
2791 char_u *p;
2793 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
2794 ok_name = alloc((unsigned)STRLEN(name) + 10);
2796 STRCPY(ok_name, name);
2797 p = ok_name + STRLEN(name);
2799 for (;;)
2801 /* This is inefficient - we're doing an EnumWindows loop for each
2802 * possible name. It would be better to grab all names in one go,
2803 * and scan the list each time...
2805 hwnd = findServer(ok_name);
2806 if (hwnd == 0)
2807 break;
2809 ++i;
2810 if (i >= 1000)
2811 break;
2813 sprintf((char *)p, "%d", i);
2816 if (hwnd != 0)
2817 vim_free(ok_name);
2818 else
2820 /* Remember the name */
2821 serverName = ok_name;
2822 #ifdef FEAT_TITLE
2823 need_maketitle = TRUE; /* update Vim window title later */
2824 #endif
2826 /* Update the message window title */
2827 SetWindowText(message_window, ok_name);
2829 #ifdef FEAT_EVAL
2830 /* Set the servername variable */
2831 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2832 #endif
2836 char_u *
2837 serverGetVimNames(void)
2839 garray_T ga;
2841 ga_init2(&ga, 1, 100);
2843 EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
2844 ga_append(&ga, NUL);
2846 return ga.ga_data;
2850 serverSendReply(name, reply)
2851 char_u *name; /* Where to send. */
2852 char_u *reply; /* What to send. */
2854 HWND target;
2855 COPYDATASTRUCT data;
2856 long_u n = 0;
2858 /* The "name" argument is a magic cookie obtained from expand("<client>").
2859 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2860 * value of the client's message window HWND.
2862 sscanf((char *)name, SCANF_HEX_LONG_U, &n);
2863 if (n == 0)
2864 return -1;
2866 target = (HWND)n;
2867 if (!IsWindow(target))
2868 return -1;
2870 data.dwData = COPYDATA_REPLY;
2871 data.cbData = (DWORD)STRLEN(reply) + 1;
2872 data.lpData = reply;
2874 serverSendEnc(target);
2875 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2876 (LPARAM)(&data)))
2877 return 0;
2879 return -1;
2883 serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2884 char_u *name; /* Where to send. */
2885 char_u *cmd; /* What to send. */
2886 char_u **result; /* Result of eval'ed expression */
2887 void *ptarget; /* HWND of server */
2888 int asExpr; /* Expression or keys? */
2889 int silent; /* don't complain about no server */
2891 HWND target;
2892 COPYDATASTRUCT data;
2893 char_u *retval = NULL;
2894 int retcode = 0;
2895 char_u altname_buf[MAX_PATH];
2897 /* If the server name does not end in a digit then we look for an
2898 * alternate name. e.g. when "name" is GVIM the we may find GVIM2. */
2899 if (STRLEN(name) > 1 && !vim_isdigit(name[STRLEN(name) - 1]))
2900 altname_buf_ptr = altname_buf;
2901 altname_buf[0] = NUL;
2902 target = findServer(name);
2903 altname_buf_ptr = NULL;
2904 if (target == 0 && altname_buf[0] != NUL)
2905 /* Use another server name we found. */
2906 target = findServer(altname_buf);
2908 if (target == 0)
2910 if (!silent)
2911 EMSG2(_(e_noserver), name);
2912 return -1;
2915 if (ptarget)
2916 *(HWND *)ptarget = target;
2918 data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
2919 data.cbData = (DWORD)STRLEN(cmd) + 1;
2920 data.lpData = cmd;
2922 serverSendEnc(target);
2923 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2924 (LPARAM)(&data)) == 0)
2925 return -1;
2927 if (asExpr)
2928 retval = serverGetReply(target, &retcode, TRUE, TRUE);
2930 if (result == NULL)
2931 vim_free(retval);
2932 else
2933 *result = retval; /* Caller assumes responsibility for freeing */
2935 return retcode;
2939 * Bring the server to the foreground.
2941 void
2942 serverForeground(name)
2943 char_u *name;
2945 HWND target = findServer(name);
2947 if (target != 0)
2948 SetForegroundWindow(target);
2951 /* Replies from server need to be stored until the client picks them up via
2952 * remote_read(). So we maintain a list of server-id/reply pairs.
2953 * Note that there could be multiple replies from one server pending if the
2954 * client is slow picking them up.
2955 * We just store the replies in a simple list. When we remove an entry, we
2956 * move list entries down to fill the gap.
2957 * The server ID is simply the HWND.
2959 typedef struct
2961 HWND server; /* server window */
2962 char_u *reply; /* reply string */
2963 int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */
2964 } reply_T;
2966 static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
2968 #define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
2969 #define REPLY_COUNT (reply_list.ga_len)
2971 /* Flag which is used to wait for a reply */
2972 static int reply_received = 0;
2975 * Store a reply. "reply" must be allocated memory (or NULL).
2977 static int
2978 save_reply(HWND server, char_u *reply, int expr)
2980 reply_T *rep;
2982 if (ga_grow(&reply_list, 1) == FAIL)
2983 return FAIL;
2985 rep = REPLY_ITEM(REPLY_COUNT);
2986 rep->server = server;
2987 rep->reply = reply;
2988 rep->expr_result = expr;
2989 if (rep->reply == NULL)
2990 return FAIL;
2992 ++REPLY_COUNT;
2993 reply_received = 1;
2994 return OK;
2998 * Get a reply from server "server".
2999 * When "expr_res" is non NULL, get the result of an expression, otherwise a
3000 * server2client() message.
3001 * When non NULL, point to return code. 0 => OK, -1 => ERROR
3002 * If "remove" is TRUE, consume the message, the caller must free it then.
3003 * if "wait" is TRUE block until a message arrives (or the server exits).
3005 char_u *
3006 serverGetReply(HWND server, int *expr_res, int remove, int wait)
3008 int i;
3009 char_u *reply;
3010 reply_T *rep;
3012 /* When waiting, loop until the message waiting for is received. */
3013 for (;;)
3015 /* Reset this here, in case a message arrives while we are going
3016 * through the already received messages. */
3017 reply_received = 0;
3019 for (i = 0; i < REPLY_COUNT; ++i)
3021 rep = REPLY_ITEM(i);
3022 if (rep->server == server
3023 && ((rep->expr_result != 0) == (expr_res != NULL)))
3025 /* Save the values we've found for later */
3026 reply = rep->reply;
3027 if (expr_res != NULL)
3028 *expr_res = rep->expr_result == 1 ? 0 : -1;
3030 if (remove)
3032 /* Move the rest of the list down to fill the gap */
3033 mch_memmove(rep, rep + 1,
3034 (REPLY_COUNT - i - 1) * sizeof(reply_T));
3035 --REPLY_COUNT;
3038 /* Return the reply to the caller, who takes on responsibility
3039 * for freeing it if "remove" is TRUE. */
3040 return reply;
3044 /* If we got here, we didn't find a reply. Return immediately if the
3045 * "wait" parameter isn't set. */
3046 if (!wait)
3047 break;
3049 /* We need to wait for a reply. Enter a message loop until the
3050 * "reply_received" flag gets set. */
3052 /* Loop until we receive a reply */
3053 while (reply_received == 0)
3055 /* Wait for a SendMessage() call to us. This could be the reply
3056 * we are waiting for. Use a timeout of a second, to catch the
3057 * situation that the server died unexpectedly. */
3058 MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
3060 /* If the server has died, give up */
3061 if (!IsWindow(server))
3062 return NULL;
3064 serverProcessPendingMessages();
3068 return NULL;
3072 * Process any messages in the Windows message queue.
3074 void
3075 serverProcessPendingMessages(void)
3077 MSG msg;
3079 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
3081 TranslateMessage(&msg);
3082 DispatchMessage(&msg);
3086 #endif /* FEAT_CLIENTSERVER */
3088 #if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
3089 || defined(PROTO)
3091 struct charset_pair
3093 char *name;
3094 BYTE charset;
3097 static struct charset_pair
3098 charset_pairs[] =
3100 {"ANSI", ANSI_CHARSET},
3101 {"CHINESEBIG5", CHINESEBIG5_CHARSET},
3102 {"DEFAULT", DEFAULT_CHARSET},
3103 {"HANGEUL", HANGEUL_CHARSET},
3104 {"OEM", OEM_CHARSET},
3105 {"SHIFTJIS", SHIFTJIS_CHARSET},
3106 {"SYMBOL", SYMBOL_CHARSET},
3107 #ifdef WIN3264
3108 {"ARABIC", ARABIC_CHARSET},
3109 {"BALTIC", BALTIC_CHARSET},
3110 {"EASTEUROPE", EASTEUROPE_CHARSET},
3111 {"GB2312", GB2312_CHARSET},
3112 {"GREEK", GREEK_CHARSET},
3113 {"HEBREW", HEBREW_CHARSET},
3114 {"JOHAB", JOHAB_CHARSET},
3115 {"MAC", MAC_CHARSET},
3116 {"RUSSIAN", RUSSIAN_CHARSET},
3117 {"THAI", THAI_CHARSET},
3118 {"TURKISH", TURKISH_CHARSET},
3119 # if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
3120 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
3121 {"VIETNAMESE", VIETNAMESE_CHARSET},
3122 # endif
3123 #endif
3124 {NULL, 0}
3128 * Convert a charset ID to a name.
3129 * Return NULL when not recognized.
3131 char *
3132 charset_id2name(int id)
3134 struct charset_pair *cp;
3136 for (cp = charset_pairs; cp->name != NULL; ++cp)
3137 if ((BYTE)id == cp->charset)
3138 break;
3139 return cp->name;
3142 static const LOGFONT s_lfDefault =
3144 -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
3145 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
3146 PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
3147 "Fixedsys" /* see _ReadVimIni */
3150 /* Initialise the "current height" to -12 (same as s_lfDefault) just
3151 * in case the user specifies a font in "guifont" with no size before a font
3152 * with an explicit size has been set. This defaults the size to this value
3153 * (-12 equates to roughly 9pt).
3155 int current_font_height = -12; /* also used in gui_w48.c */
3157 /* Convert a string representing a point size into pixels. The string should
3158 * be a positive decimal number, with an optional decimal point (eg, "12", or
3159 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
3160 * character is stored in *end. The flag "vertical" says whether this
3161 * calculation is for a vertical (height) size or a horizontal (width) one.
3163 static int
3164 points_to_pixels(char_u *str, char_u **end, int vertical, long_i pprinter_dc)
3166 int pixels;
3167 int points = 0;
3168 int divisor = 0;
3169 HWND hwnd = (HWND)0;
3170 HDC hdc;
3171 HDC printer_dc = (HDC)pprinter_dc;
3173 while (*str != NUL)
3175 if (*str == '.' && divisor == 0)
3177 /* Start keeping a divisor, for later */
3178 divisor = 1;
3180 else
3182 if (!VIM_ISDIGIT(*str))
3183 break;
3185 points *= 10;
3186 points += *str - '0';
3187 divisor *= 10;
3189 ++str;
3192 if (divisor == 0)
3193 divisor = 1;
3195 if (printer_dc == NULL)
3197 hwnd = GetDesktopWindow();
3198 hdc = GetWindowDC(hwnd);
3200 else
3201 hdc = printer_dc;
3203 pixels = MulDiv(points,
3204 GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
3205 72 * divisor);
3207 if (printer_dc == NULL)
3208 ReleaseDC(hwnd, hdc);
3210 *end = str;
3211 return pixels;
3214 /*ARGSUSED*/
3215 static int CALLBACK
3216 font_enumproc(
3217 ENUMLOGFONT *elf,
3218 NEWTEXTMETRIC *ntm,
3219 int type,
3220 LPARAM lparam)
3222 /* Return value:
3223 * 0 = terminate now (monospace & ANSI)
3224 * 1 = continue, still no luck...
3225 * 2 = continue, but we have an acceptable LOGFONT
3226 * (monospace, not ANSI)
3227 * We use these values, as EnumFontFamilies returns 1 if the
3228 * callback function is never called. So, we check the return as
3229 * 0 = perfect, 2 = OK, 1 = no good...
3230 * It's not pretty, but it works!
3233 LOGFONT *lf = (LOGFONT *)(lparam);
3235 #ifndef FEAT_PROPORTIONAL_FONTS
3236 /* Ignore non-monospace fonts without further ado */
3237 if ((ntm->tmPitchAndFamily & 1) != 0)
3238 return 1;
3239 #endif
3241 /* Remember this LOGFONT as a "possible" */
3242 *lf = elf->elfLogFont;
3244 /* Terminate the scan as soon as we find an ANSI font */
3245 if (lf->lfCharSet == ANSI_CHARSET
3246 || lf->lfCharSet == OEM_CHARSET
3247 || lf->lfCharSet == DEFAULT_CHARSET)
3248 return 0;
3250 /* Continue the scan - we have a non-ANSI font */
3251 return 2;
3254 static int
3255 init_logfont(LOGFONT *lf)
3257 int n;
3258 HWND hwnd = GetDesktopWindow();
3259 HDC hdc = GetWindowDC(hwnd);
3261 n = EnumFontFamilies(hdc,
3262 (LPCSTR)lf->lfFaceName,
3263 (FONTENUMPROC)font_enumproc,
3264 (LPARAM)lf);
3266 ReleaseDC(hwnd, hdc);
3268 /* If we couldn't find a useable font, return failure */
3269 if (n == 1)
3270 return FAIL;
3272 /* Tidy up the rest of the LOGFONT structure. We set to a basic
3273 * font - get_logfont() sets bold, italic, etc based on the user's
3274 * input.
3276 lf->lfHeight = current_font_height;
3277 lf->lfWidth = 0;
3278 lf->lfItalic = FALSE;
3279 lf->lfUnderline = FALSE;
3280 lf->lfStrikeOut = FALSE;
3281 lf->lfWeight = FW_NORMAL;
3283 /* Return success */
3284 return OK;
3288 * Get font info from "name" into logfont "lf".
3289 * Return OK for a valid name, FAIL otherwise.
3292 get_logfont(
3293 LOGFONT *lf,
3294 char_u *name,
3295 HDC printer_dc,
3296 int verbose)
3298 char_u *p;
3299 int i;
3300 static LOGFONT *lastlf = NULL;
3302 *lf = s_lfDefault;
3303 if (name == NULL)
3304 return OK;
3306 if (STRCMP(name, "*") == 0)
3308 #if defined(FEAT_GUI_W32)
3309 CHOOSEFONT cf;
3310 /* if name is "*", bring up std font dialog: */
3311 memset(&cf, 0, sizeof(cf));
3312 cf.lStructSize = sizeof(cf);
3313 cf.hwndOwner = s_hwnd;
3314 cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
3315 if (lastlf != NULL)
3316 *lf = *lastlf;
3317 cf.lpLogFont = lf;
3318 cf.nFontType = 0 ; //REGULAR_FONTTYPE;
3319 if (ChooseFont(&cf))
3320 goto theend;
3321 #else
3322 return FAIL;
3323 #endif
3327 * Split name up, it could be <name>:h<height>:w<width> etc.
3329 for (p = name; *p && *p != ':'; p++)
3331 if (p - name + 1 > LF_FACESIZE)
3332 return FAIL; /* Name too long */
3333 lf->lfFaceName[p - name] = *p;
3335 if (p != name)
3336 lf->lfFaceName[p - name] = NUL;
3338 /* First set defaults */
3339 lf->lfHeight = -12;
3340 lf->lfWidth = 0;
3341 lf->lfWeight = FW_NORMAL;
3342 lf->lfItalic = FALSE;
3343 lf->lfUnderline = FALSE;
3344 lf->lfStrikeOut = FALSE;
3347 * If the font can't be found, try replacing '_' by ' '.
3349 if (init_logfont(lf) == FAIL)
3351 int did_replace = FALSE;
3353 for (i = 0; lf->lfFaceName[i]; ++i)
3354 if (lf->lfFaceName[i] == '_')
3356 lf->lfFaceName[i] = ' ';
3357 did_replace = TRUE;
3359 if (!did_replace || init_logfont(lf) == FAIL)
3360 return FAIL;
3363 while (*p == ':')
3364 p++;
3366 /* Set the values found after ':' */
3367 while (*p)
3369 switch (*p++)
3371 case 'h':
3372 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (long_i)printer_dc);
3373 break;
3374 case 'w':
3375 lf->lfWidth = points_to_pixels(p, &p, FALSE, (long_i)printer_dc);
3376 break;
3377 case 'b':
3378 #ifndef MSWIN16_FASTTEXT
3379 lf->lfWeight = FW_BOLD;
3380 #endif
3381 break;
3382 case 'i':
3383 #ifndef MSWIN16_FASTTEXT
3384 lf->lfItalic = TRUE;
3385 #endif
3386 break;
3387 case 'u':
3388 lf->lfUnderline = TRUE;
3389 break;
3390 case 's':
3391 lf->lfStrikeOut = TRUE;
3392 break;
3393 case 'c':
3395 struct charset_pair *cp;
3397 for (cp = charset_pairs; cp->name != NULL; ++cp)
3398 if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
3400 lf->lfCharSet = cp->charset;
3401 p += strlen(cp->name);
3402 break;
3404 if (cp->name == NULL && verbose)
3406 vim_snprintf((char *)IObuff, IOSIZE,
3407 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
3408 EMSG(IObuff);
3409 break;
3411 break;
3413 default:
3414 if (verbose)
3416 vim_snprintf((char *)IObuff, IOSIZE,
3417 _("E245: Illegal char '%c' in font name \"%s\""),
3418 p[-1], name);
3419 EMSG(IObuff);
3421 return FAIL;
3423 while (*p == ':')
3424 p++;
3427 #if defined(FEAT_GUI_W32)
3428 theend:
3429 #endif
3430 /* ron: init lastlf */
3431 if (printer_dc == NULL)
3433 vim_free(lastlf);
3434 lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
3435 if (lastlf != NULL)
3436 mch_memmove(lastlf, lf, sizeof(LOGFONT));
3439 return OK;
3442 #endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */