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.
13 * Routines common to both Win16 and Win32.
28 # define SHORT_FNAME /* always 8.3 file name */
32 #include <sys/types.h>
46 #if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
47 # include <shellapi.h>
50 #if defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)
53 # include <winspool.h>
61 # ifndef FROM_LEFT_1ST_BUTTON_PRESSED
62 # define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
64 # ifndef RIGHTMOST_BUTTON_PRESSED
65 # define RIGHTMOST_BUTTON_PRESSED 0x0002
67 # ifndef FROM_LEFT_2ND_BUTTON_PRESSED
68 # define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
70 # ifndef FROM_LEFT_3RD_BUTTON_PRESSED
71 # define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
73 # ifndef FROM_LEFT_4TH_BUTTON_PRESSED
74 # define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
81 # define MOUSE_MOVED 0x0001
84 # define DOUBLE_CLICK 0x0002
89 * When generating prototypes for Win32 on Unix, these lines make the syntax
90 * errors disappear. They do not need to be correct.
98 typedef int CONSOLE_CURSOR_INFO;
101 typedef int ENUMLOGFONT;
107 typedef int INPUT_RECORD;
108 typedef int KEY_EVENT_RECORD;
118 typedef int MOUSE_EVENT_RECORD;
119 typedef int NEWTEXTMETRIC;
121 typedef int PRINTDLG;
122 typedef int PSECURITY_DESCRIPTOR;
124 typedef int SECURITY_INFORMATION;
126 typedef int SMALL_RECT;
127 typedef int TEXTMETRIC;
135 /* Record all output and all keyboard & mouse input */
136 /* #define MCH_WRITE_DUMP */
138 #ifdef MCH_WRITE_DUMP
143 extern DWORD g_PlatformId;
146 #ifndef FEAT_GUI_MSWIN
147 extern char g_szOrigTitle[];
153 static HWND s_hwnd = 0; /* console window handle, set by GetConsoleHwnd() */
156 extern int WSInitialized;
158 /* Don't generate prototypes here, because some systems do have these
160 #if defined(__GNUC__) && !defined(PROTO)
162 int _stricoll(char *a, char *b)
164 // the ANSI-ish correct way is to use strxfrm():
165 char a_buff[512], b_buff[512]; // file names, so this is enough on Win32
166 strxfrm(a_buff, a, 512);
167 strxfrm(b_buff, b, 512);
168 return strcoll(a_buff, b_buff);
171 char * _fullpath(char *buf, char *fname, int len)
175 return (char *)GetFullPathName(fname, len, buf, &toss);
179 int _chdrive(int drive)
181 char temp [3] = "-:";
182 temp[0] = drive + 'A' - 1;
183 return !SetCurrentDirectory(temp);
187 /* being a more ANSI compliant compiler, BorlandC doesn't define _stricoll:
188 * but it does in BC 5.02! */
189 # if __BORLANDC__ < 0x502
190 int _stricoll(char *a, char *b)
193 // this is fast but not correct:
194 return stricmp(a, b);
196 // the ANSI-ish correct way is to use strxfrm():
197 char a_buff[512], b_buff[512]; // file names, so this is enough on Win32
198 strxfrm(a_buff, a, 512);
199 strxfrm(b_buff, b, 512);
200 return strcoll(a_buff, b_buff);
208 #if defined(FEAT_GUI_MSWIN) || defined(PROTO)
210 * GUI version of mch_exit().
211 * Shut down and exit with status `r'
212 * Careful: mch_exit() may be called before mch_init()!
219 ml_close_all(TRUE); /* remove all memfiles */
224 # ifdef FEAT_NETBEANS_INTG
227 WSInitialized = FALSE;
231 #ifdef DYNAMIC_GETTEXT
245 #endif /* FEAT_GUI_MSWIN */
249 * Init the tables for toupper() and tolower().
260 /* Init the tables for toupper() and tolower() */
261 for (i = 0; i < 256; ++i)
262 toupper_tab[i] = tolower_tab[i] = i;
264 CharUpperBuff(toupper_tab, 256);
265 CharLowerBuff(tolower_tab, 256);
267 AnsiUpperBuff(toupper_tab, 256);
268 AnsiLowerBuff(tolower_tab, 256);
271 #if defined(FEAT_MBYTE) && !defined(FEAT_GUI)
272 (void)get_cmd_argsW(NULL);
278 * Return TRUE if the input comes from a terminal, FALSE otherwise.
283 #ifdef FEAT_GUI_MSWIN
284 return OK; /* GUI always has a tty */
286 if (isatty(read_cmd_fd))
294 * mch_settitle(): set titlebar of our window
301 # ifdef FEAT_GUI_MSWIN
302 gui_mch_settitle(title, icon);
307 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
309 /* Convert the title from 'encoding' to the active codepage. */
310 WCHAR *wp = enc_to_utf16(title, NULL);
315 n = SetConsoleTitleW(wp);
317 if (n != 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
322 SetConsoleTitle(title);
329 * Restore the window/icon title.
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)
340 #ifndef FEAT_GUI_MSWIN
341 mch_settitle((which & 1) ? g_szOrigTitle : NULL, NULL);
347 * Return TRUE if we can restore the title (we can)
350 mch_can_restore_title()
357 * Return TRUE if we can restore the icon title (we can't)
360 mch_can_restore_icon()
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.
385 if (*fname == NUL) /* Borland behaves badly here - make it consistent */
386 nResult = mch_dirname(buf, len);
391 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
393 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
394 && g_PlatformId == VER_PLATFORM_WIN32_NT
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_utf16(fname, NULL);
408 if (wname != NULL && _wfullpath(wbuf, wname, MAX_PATH - 1) != NULL)
410 cname = utf16_to_enc((short_u *)wbuf, NULL);
413 vim_strncpy(buf, cname, len - 1);
420 if (nResult == FAIL) /* fall back to non-wide function */
423 if (_fullpath(buf, fname, len - 1) == NULL)
425 /* failed, use relative path name */
426 vim_strncpy(buf, fname, len - 1);
433 #ifdef USE_FNAME_CASE
434 fname_case(buf, len);
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] == '\\')))
456 /* A name that can't be made absolute probably isn't absolute. */
457 if (mch_FullName(fname, szName, _MAX_PATH, FALSE) == FAIL)
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
470 * When 'shellslash' set do it the other way around.
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];
494 vim_strncpy((char_u *)buf, (char_u *)name, _MAX_PATH);
495 p = buf + strlen(buf);
498 if (p > buf && (*p == '\\' || *p == '/') && p[-1] != ':')
501 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage
503 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
504 && g_PlatformId == VER_PLATFORM_WIN32_NT
508 WCHAR *wp = enc_to_utf16(buf, NULL);
513 n = _wstat(wp, (struct _stat *)stp);
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. */
523 return stat(buf, stp);
526 #if defined(FEAT_GUI_MSWIN) || defined(PROTO)
529 mch_settmode(int tmode)
535 mch_get_shellsize(void)
542 mch_set_shellsize(void)
548 * Rows and/or Columns has changed.
551 mch_new_shellsize(void)
559 * We have no job control, so fake it by starting a new shell.
567 #if defined(USE_MCH_ERRMSG) || defined(PROTO)
569 #ifdef display_errors
570 # undef display_errors
574 * Display the saved error message(s).
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)
587 (void)gui_mch_dialog(
589 gui.starting ? VIM_INFO :
593 gui.starting ? (char_u *)_("Message") :
595 (char_u *)_("Error"),
596 p, (char_u *)_("&Ok"), 1, NULL, FALSE);
606 * Return TRUE if "p" contain a wildcard that can be expanded by
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))
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 *)
637 || (*p == '~' && p[1] != NUL))
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... */
657 smsg((char_u *)"chdir(%s)", path);
660 if (isalpha(path[0]) && path[1] == ':') /* has a drive name */
662 /* If we can change to the drive, skip that part of the path. If we
663 * can't then the current directory may be invalid, try using chdir()
664 * with the whole path. */
665 if (_chdrive(TOLOWER_ASC(path[0]) - 'a' + 1) == 0)
669 if (*path == NUL) /* drive name only */
673 if (enc_codepage >= 0 && (int)GetACP() != enc_codepage)
675 WCHAR *p = enc_to_utf16(path, NULL);
684 /* Retry with non-wide function (for Windows 98). */
689 return chdir(path); /* let the normal chdir() do the rest */
694 * Switching off termcap mode is only allowed when Columns is 80, otherwise a
695 * crash may result. It's always allowed on NT or when running the GUI.
699 can_end_termcap_mode(
702 #ifdef FEAT_GUI_MSWIN
703 return TRUE; /* GUI starts a new console anyway */
705 if (g_PlatformId == VER_PLATFORM_WIN32_NT || Columns == 80)
708 msg(_("'columns' is not 80, cannot execute external commands"));
713 #ifdef FEAT_GUI_MSWIN
715 * return non-zero if a character is available
727 * set screen mode, always fails.
734 EMSG(_(e_screenmode));
739 #if defined(FEAT_LIBCALL) || defined(PROTO)
741 * Call a DLL routine which takes either a string or int param
742 * and returns an allocated string.
743 * Return OK if it worked, FAIL if not.
746 typedef LPTSTR (*MYSTRPROCSTR)(LPTSTR);
747 typedef LPTSTR (*MYINTPROCSTR)(int);
748 typedef int (*MYSTRPROCINT)(LPTSTR);
749 typedef int (*MYINTPROCINT)(int);
751 typedef LPSTR (*MYSTRPROCSTR)(LPSTR);
752 typedef LPSTR (*MYINTPROCSTR)(int);
753 typedef int (*MYSTRPROCINT)(LPSTR);
754 typedef int (*MYINTPROCINT)(int);
759 * Check if a pointer points to a valid NUL terminated string.
760 * Return the length of the string, including terminating NUL.
761 * Returns 0 for an invalid pointer, 1 for an empty string.
764 check_str_len(char_u *str)
767 MEMORY_BASIC_INFORMATION mbi;
775 /* get memory information */
776 if (VirtualQuery(str, &mbi, sizeof(mbi)))
778 /* pre cast these (typing savers) */
779 long_u dwStr = (long_u)str;
780 long_u dwBaseAddress = (long_u)mbi.BaseAddress;
782 /* get start address of page that str is on */
783 long_u strPage = dwStr - (dwStr - dwBaseAddress) % si.dwPageSize;
785 /* get length from str to end of page */
786 long_u pageLength = si.dwPageSize - (dwStr - strPage);
788 for (p = str; !IsBadReadPtr(p, (UINT)pageLength);
789 p += pageLength, pageLength = si.dwPageSize)
790 for (i = 0; i < pageLength; ++i, ++length)
803 char_u *argstring, /* NULL when using a argint */
805 char_u **string_result,/* NULL when using number_result */
809 MYSTRPROCSTR ProcAdd;
810 MYINTPROCSTR ProcAddI;
811 char_u *retval_str = NULL;
815 BOOL fRunTimeLinkSuccess = FALSE;
817 // Get a handle to the DLL module.
819 hinstLib = LoadLibrary(libname);
821 hinstLib = vimLoadLib(libname);
824 // If the handle is valid, try to get the function address.
825 if (hinstLib != NULL)
827 #ifdef HAVE_TRY_EXCEPT
831 if (argstring != NULL)
833 /* Call with string argument */
834 ProcAdd = (MYSTRPROCSTR) GetProcAddress(hinstLib, funcname);
835 if ((fRunTimeLinkSuccess = (ProcAdd != NULL)) != 0)
837 if (string_result == NULL)
838 retval_int = ((MYSTRPROCINT)ProcAdd)(argstring);
840 retval_str = (ProcAdd)(argstring);
845 /* Call with number argument */
846 ProcAddI = (MYINTPROCSTR) GetProcAddress(hinstLib, funcname);
847 if ((fRunTimeLinkSuccess = (ProcAddI != NULL)) != 0)
849 if (string_result == NULL)
850 retval_int = ((MYINTPROCINT)ProcAddI)(argint);
852 retval_str = (ProcAddI)(argint);
856 // Save the string before we free the library.
857 // Assume that a "1" result is an illegal pointer.
858 if (string_result == NULL)
859 *number_result = retval_int;
860 else if (retval_str != NULL
862 && retval_str != (char_u *)1
863 && retval_str != (char_u *)-1
864 && !IsBadStringPtr(retval_str, INT_MAX)
865 && (len = strlen(retval_str) + 1) > 0
867 && (len = check_str_len(retval_str)) > 0
871 *string_result = lalloc((long_u)len, TRUE);
872 if (*string_result != NULL)
873 mch_memmove(*string_result, retval_str, len);
876 #ifdef HAVE_TRY_EXCEPT
878 __except(EXCEPTION_EXECUTE_HANDLER)
880 if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW)
882 fRunTimeLinkSuccess = 0;
886 // Free the DLL module.
887 (void)FreeLibrary(hinstLib);
890 if (!fRunTimeLinkSuccess)
892 EMSG2(_(e_libcall), funcname);
900 #if defined(FEAT_MBYTE) || defined(PROTO)
902 * Convert an UTF-8 string to UTF-16.
903 * "instr[inlen]" is the input. "inlen" is in bytes.
904 * When "outstr" is NULL only return the number of UTF-16 words produced.
905 * Otherwise "outstr" must be a buffer of sufficient size.
906 * Returns the number of UTF-16 words produced.
909 utf8_to_utf16(char_u *instr, int inlen, short_u *outstr, int *unconvlenp)
919 /* Only convert if we have a complete sequence. */
920 l = utf_ptr2len_len(p, todo);
923 /* Return length of incomplete sequence. */
924 if (unconvlenp != NULL)
929 ch = utf_ptr2char(p);
932 /* non-BMP character, encoding with surrogate pairs */
936 *outstr++ = (0xD800 - (0x10000 >> 10)) + (ch >> 10);
937 *outstr++ = 0xDC00 | (ch & 0x3FF);
940 else if (outstr != NULL)
951 * Convert an UTF-16 string to UTF-8.
952 * The input is "instr[inlen]" with "inlen" in number of UTF-16 words.
953 * When "outstr" is NULL only return the required number of bytes.
954 * Otherwise "outstr" must be a buffer of sufficient size.
955 * Return the number of bytes produced.
958 utf16_to_utf8(short_u *instr, int inlen, char_u *outstr)
969 if (ch >= 0xD800 && ch <= 0xDBFF && todo > 1)
971 /* surrogate pairs handling */
973 if (ch2 >= 0xDC00 && ch2 <= 0xDFFF)
975 ch = ((ch - 0xD800) << 10) + (ch2 & 0x3FF) + 0x10000;
982 l = utf_char2bytes(ch, outstr);
986 l = utf_char2len(ch);
996 * Call MultiByteToWideChar() and allocate memory for the result.
997 * Returns the result in "*out[*outlen]" with an extra zero appended.
998 * "outlen" is in words.
1001 MultiByteToWideChar_alloc(UINT cp, DWORD flags,
1002 LPCSTR in, int inlen,
1003 LPWSTR *out, int *outlen)
1005 *outlen = MultiByteToWideChar(cp, flags, in, inlen, 0, 0);
1006 /* Add one one word to avoid a zero-length alloc(). */
1007 *out = (LPWSTR)alloc(sizeof(WCHAR) * (*outlen + 1));
1010 MultiByteToWideChar(cp, flags, in, inlen, *out, *outlen);
1011 (*out)[*outlen] = 0;
1016 * Call WideCharToMultiByte() and allocate memory for the result.
1017 * Returns the result in "*out[*outlen]" with an extra NUL appended.
1020 WideCharToMultiByte_alloc(UINT cp, DWORD flags,
1021 LPCWSTR in, int inlen,
1022 LPSTR *out, int *outlen,
1023 LPCSTR def, LPBOOL useddef)
1025 *outlen = WideCharToMultiByte(cp, flags, in, inlen, NULL, 0, def, useddef);
1026 /* Add one one byte to avoid a zero-length alloc(). */
1027 *out = alloc((unsigned)*outlen + 1);
1030 WideCharToMultiByte(cp, flags, in, inlen, *out, *outlen, def, useddef);
1031 (*out)[*outlen] = 0;
1035 #endif /* FEAT_MBYTE */
1037 #ifdef FEAT_CLIPBOARD
1039 * Clipboard stuff, for cutting and pasting text to other windows.
1042 /* Type used for the clipboard type of Vim's data. */
1045 int type; /* MCHAR, MBLOCK or MLINE */
1046 int txtlen; /* length of CF_TEXT in bytes */
1047 int ucslen; /* length of CF_UNICODETEXT in words */
1048 int rawlen; /* length of clip_star.format_raw, including encoding,
1049 excluding terminating NUL */
1053 * Make vim the owner of the current selection. Return OK upon success.
1057 clip_mch_own_selection(VimClipboard *cbd)
1060 * Never actually own the clipboard. If another application sets the
1061 * clipboard, we don't want to think that we still own it.
1067 * Make vim NOT the owner of the current selection.
1071 clip_mch_lose_selection(VimClipboard *cbd)
1073 /* Nothing needs to be done here */
1077 * Copy "str[*size]" into allocated memory, changing CR-NL to NL.
1078 * Return the allocated result and the size in "*size".
1079 * Returns NULL when out of memory.
1082 crnl_to_nl(const char_u *str, int *size)
1085 int str_len = *size;
1089 /* Avoid allocating zero bytes, it generates an error message. */
1090 ret = lalloc((long_u)(str_len == 0 ? 1 : str_len), TRUE);
1094 for (pos = 0; pos < str_len; ++pos)
1096 if (str[pos] == '\r' && str[pos + 1] == '\n')
1109 * Wait for another process to Close the Clipboard.
1110 * Returns TRUE for success.
1113 vim_open_clipboard(void)
1117 while (!OpenClipboard(NULL))
1120 return FALSE; /* waited too long, give up */
1122 delay *= 2; /* wait for 10, 20, 40, 80, etc. msec */
1128 * Get the current selection and put it in the clipboard register.
1130 * NOTE: Must use GlobalLock/Unlock here to ensure Win32s compatibility.
1131 * On NT/W95 the clipboard data is a fixed global memory object and
1132 * so its handle = its pointer.
1133 * On Win32s, however, co-operation with the Win16 system means that
1134 * the clipboard data is moveable and its handle is not a pointer at all,
1135 * so we can't just cast the return value of GetClipboardData to (char_u*).
1139 clip_mch_request_selection(VimClipboard *cbd)
1141 VimClipType_t metadata = { -1, -1, -1, -1 };
1142 HGLOBAL hMem = NULL;
1144 #if defined(FEAT_MBYTE) && defined(WIN3264)
1145 char_u *to_free = NULL;
1148 HGLOBAL rawh = NULL;
1155 * Don't pass GetActiveWindow() as an argument to OpenClipboard() because
1156 * then we can't paste back into the same window for some reason - webb.
1158 if (!vim_open_clipboard())
1161 /* Check for vim's own clipboard format first. This only gets the type of
1162 * the data, still need to use CF_UNICODETEXT or CF_TEXT for the text. */
1163 if (IsClipboardFormatAvailable(cbd->format))
1165 VimClipType_t *meta_p;
1168 /* We have metadata on the clipboard; try to get it. */
1169 if ((meta_h = GetClipboardData(cbd->format)) != NULL
1170 && (meta_p = (VimClipType_t *)GlobalLock(meta_h)) != NULL)
1172 /* The size of "VimClipType_t" changed, "rawlen" was added later.
1173 * Only copy what is available for backwards compatibility. */
1174 n = sizeof(VimClipType_t);
1175 if (GlobalSize(meta_h) < n)
1176 n = GlobalSize(meta_h);
1177 memcpy(&metadata, meta_p, n);
1178 GlobalUnlock(meta_h);
1183 /* Check for Vim's raw clipboard format first. This is used without
1184 * conversion, but only if 'encoding' matches. */
1185 if (IsClipboardFormatAvailable(cbd->format_raw)
1186 && metadata.rawlen > (int)STRLEN(p_enc))
1188 /* We have raw data on the clipboard; try to get it. */
1189 if ((rawh = GetClipboardData(cbd->format_raw)) != NULL)
1193 rawp = (char_u *)GlobalLock(rawh);
1194 if (rawp != NULL && STRCMP(p_enc, rawp) == 0)
1196 n = STRLEN(p_enc) + 1;
1198 str_size = (int)(metadata.rawlen - n);
1211 #if defined(FEAT_MBYTE) && defined(WIN3264)
1212 /* Try to get the clipboard in Unicode if it's not an empty string. */
1213 if (IsClipboardFormatAvailable(CF_UNICODETEXT) && metadata.ucslen != 0)
1217 if ((hMemW = GetClipboardData(CF_UNICODETEXT)) != NULL)
1219 WCHAR *hMemWstr = (WCHAR *)GlobalLock(hMemW);
1221 /* Use the length of our metadata if possible, but limit it to the
1222 * GlobalSize() for safety. */
1223 maxlen = (int)(GlobalSize(hMemW) / sizeof(WCHAR));
1224 if (metadata.ucslen >= 0)
1226 if (metadata.ucslen > maxlen)
1229 str_size = metadata.ucslen;
1233 for (str_size = 0; str_size < maxlen; ++str_size)
1234 if (hMemWstr[str_size] == NUL)
1237 to_free = str = utf16_to_enc((short_u *)hMemWstr, &str_size);
1238 GlobalUnlock(hMemW);
1243 /* Get the clipboard in the Active codepage. */
1244 if (IsClipboardFormatAvailable(CF_TEXT))
1246 if ((hMem = GetClipboardData(CF_TEXT)) != NULL)
1248 str = (char_u *)GlobalLock(hMem);
1250 /* The length is either what our metadata says or the strlen().
1251 * But limit it to the GlobalSize() for safety. */
1252 maxlen = (int)GlobalSize(hMem);
1253 if (metadata.txtlen >= 0)
1255 if (metadata.txtlen > maxlen)
1258 str_size = metadata.txtlen;
1262 for (str_size = 0; str_size < maxlen; ++str_size)
1263 if (str[str_size] == NUL)
1267 # if defined(FEAT_MBYTE) && defined(WIN3264)
1268 /* The text is in the active codepage. Convert to 'encoding',
1269 * going through UTF-16. */
1270 acp_to_enc(str, str_size, &to_free, &maxlen);
1271 if (to_free != NULL)
1283 if (str != NULL && *str != NUL)
1285 char_u *temp_clipboard;
1287 /* If the type is not known detect it. */
1288 if (metadata.type == -1)
1289 metadata.type = MAUTO;
1291 /* Translate <CR><NL> into <NL>. */
1292 temp_clipboard = crnl_to_nl(str, &str_size);
1293 if (temp_clipboard != NULL)
1295 clip_yank_selection(metadata.type, temp_clipboard, str_size, cbd);
1296 vim_free(temp_clipboard);
1300 /* unlock the global object */
1308 #if defined(FEAT_MBYTE) && defined(WIN3264)
1314 * Send the current selection to the clipboard.
1317 clip_mch_set_selection(VimClipboard *cbd)
1320 VimClipType_t metadata;
1322 HGLOBAL hMemRaw = NULL;
1323 HGLOBAL hMem = NULL;
1324 HGLOBAL hMemVim = NULL;
1325 # if defined(FEAT_MBYTE) && defined(WIN3264)
1326 HGLOBAL hMemW = NULL;
1329 /* If the '*' register isn't already filled in, fill it in now */
1331 clip_get_selection(cbd);
1334 /* Get the text to be put on the clipboard, with CR-LF. */
1335 metadata.type = clip_convert_selection(&str, &txtlen, cbd);
1336 if (metadata.type < 0)
1338 metadata.txtlen = (int)txtlen;
1339 metadata.ucslen = 0;
1340 metadata.rawlen = 0;
1343 /* Always set the raw bytes: 'encoding', NUL and the text. This is used
1344 * when copy/paste from/to Vim with the same 'encoding', so that illegal
1345 * bytes can also be copied and no conversion is needed. */
1349 metadata.rawlen = (int)(txtlen + STRLEN(p_enc) + 1);
1350 hMemRaw = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1351 metadata.rawlen + 1);
1352 lpszMemRaw = (LPSTR)GlobalLock(hMemRaw);
1353 if (lpszMemRaw != NULL)
1355 STRCPY(lpszMemRaw, p_enc);
1356 memcpy(lpszMemRaw + STRLEN(p_enc) + 1, str, txtlen + 1);
1357 GlobalUnlock(hMemRaw);
1360 metadata.rawlen = 0;
1364 # if defined(FEAT_MBYTE) && defined(WIN3264)
1367 int len = metadata.txtlen;
1369 /* Convert the text to UTF-16. This is put on the clipboard as
1370 * CF_UNICODETEXT. */
1371 out = (WCHAR *)enc_to_utf16(str, &len);
1376 /* Convert the text for CF_TEXT to Active codepage. Otherwise it's
1377 * p_enc, which has no relation to the Active codepage. */
1378 metadata.txtlen = WideCharToMultiByte(GetACP(), 0, out, len,
1381 str = (char_u *)alloc((unsigned)(metadata.txtlen == 0 ? 1
1382 : metadata.txtlen));
1386 return; /* out of memory */
1388 WideCharToMultiByte(GetACP(), 0, out, len,
1389 str, metadata.txtlen, 0, 0);
1391 /* Allocate memory for the UTF-16 text, add one NUL word to
1392 * terminate the string. */
1393 hMemW = (LPSTR)GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE,
1394 (len + 1) * sizeof(WCHAR));
1395 lpszMemW = (WCHAR *)GlobalLock(hMemW);
1396 if (lpszMemW != NULL)
1398 memcpy(lpszMemW, out, len * sizeof(WCHAR));
1399 lpszMemW[len] = NUL;
1400 GlobalUnlock(hMemW);
1403 metadata.ucslen = len;
1408 /* Allocate memory for the text, add one NUL byte to terminate the string.
1410 hMem = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, metadata.txtlen + 1);
1412 LPSTR lpszMem = (LPSTR)GlobalLock(hMem);
1416 vim_strncpy(lpszMem, str, metadata.txtlen);
1421 /* Set up metadata: */
1423 VimClipType_t *lpszMemVim = NULL;
1425 hMemVim = GlobalAlloc(GMEM_MOVEABLE|GMEM_DDESHARE,
1426 sizeof(VimClipType_t));
1427 lpszMemVim = (VimClipType_t *)GlobalLock(hMemVim);
1428 memcpy(lpszMemVim, &metadata, sizeof(metadata));
1429 GlobalUnlock(hMemVim);
1433 * Open the clipboard, clear it and put our text on it.
1434 * Always set our Vim format. Put Unicode and plain text on it.
1436 * Don't pass GetActiveWindow() as an argument to OpenClipboard()
1437 * because then we can't paste back into the same window for some
1440 if (vim_open_clipboard())
1442 if (EmptyClipboard())
1444 SetClipboardData(cbd->format, hMemVim);
1446 # if defined(FEAT_MBYTE) && defined(WIN3264)
1449 if (SetClipboardData(CF_UNICODETEXT, hMemW) != NULL)
1453 /* Always use CF_TEXT. On Win98 Notepad won't obtain the
1454 * CF_UNICODETEXT text, only CF_TEXT. */
1455 SetClipboardData(CF_TEXT, hMem);
1462 /* Free any allocations we didn't give to the clipboard: */
1464 GlobalFree(hMemRaw);
1467 # if defined(FEAT_MBYTE) && defined(WIN3264)
1472 GlobalFree(hMemVim);
1475 #endif /* FEAT_CLIPBOARD */
1477 #if defined(FEAT_MBYTE) || defined(PROTO)
1479 * Note: the following two functions are only guaranteed to work when using
1480 * valid MS-Windows codepages or when iconv() is available.
1484 * Convert "str" from 'encoding' to UTF-16.
1485 * Input in "str" with length "*lenp". When "lenp" is NULL, use strlen().
1486 * Output is returned as an allocated string. "*lenp" is set to the length of
1487 * the result. A trailing NUL is always added.
1488 * Returns NULL when out of memory.
1491 enc_to_utf16(char_u *str, int *lenp)
1495 char_u *allocbuf = NULL;
1501 len_loc = (int)STRLEN(str) + 1;
1505 if (enc_codepage > 0)
1507 /* We can do any CP### -> UTF-16 in one pass, and we can do it
1508 * without iconv() (convert_* may need iconv). */
1509 MultiByteToWideChar_alloc(enc_codepage, 0, str, *lenp, &ret, &length);
1513 /* Use "latin1" by default, we might be called before we have p_enc
1514 * set up. Convert to utf-8 first, works better with iconv(). Does
1515 * nothing if 'encoding' is "utf-8". */
1516 conv.vc_type = CONV_NONE;
1517 if (convert_setup(&conv, p_enc ? p_enc : (char_u *)"latin1",
1518 (char_u *)"utf-8") == FAIL)
1520 if (conv.vc_type != CONV_NONE)
1522 str = allocbuf = string_convert(&conv, str, lenp);
1526 convert_setup(&conv, NULL, NULL);
1528 length = utf8_to_utf16(str, *lenp, NULL, NULL);
1529 ret = (WCHAR *)alloc((unsigned)((length + 1) * sizeof(WCHAR)));
1532 utf8_to_utf16(str, *lenp, (short_u *)ret, NULL);
1540 return (short_u *)ret;
1544 * Convert an UTF-16 string to 'encoding'.
1545 * Input in "str" with length (counted in wide characters) "*lenp". When
1546 * "lenp" is NULL, use wcslen().
1547 * Output is returned as an allocated string. If "*lenp" is not NULL it is
1548 * set to the length of the result.
1549 * Returns NULL when out of memory.
1552 utf16_to_enc(short_u *str, int *lenp)
1555 char_u *utf8_str = NULL, *enc_str = NULL;
1560 len_loc = (int)wcslen(str) + 1;
1564 if (enc_codepage > 0)
1566 /* We can do any UTF-16 -> CP### in one pass. */
1569 WideCharToMultiByte_alloc(enc_codepage, 0, str, *lenp,
1570 (LPSTR *)&enc_str, &length, 0, 0);
1575 /* Avoid allocating zero bytes, it generates an error message. */
1576 utf8_str = alloc(utf16_to_utf8(str, *lenp == 0 ? 1 : *lenp, NULL));
1577 if (utf8_str != NULL)
1579 *lenp = utf16_to_utf8(str, *lenp, utf8_str);
1581 /* We might be called before we have p_enc set up. */
1582 conv.vc_type = CONV_NONE;
1583 convert_setup(&conv, (char_u *)"utf-8",
1584 p_enc? p_enc: (char_u *)"latin1");
1585 if (conv.vc_type == CONV_NONE)
1587 /* p_enc is utf-8, so we're done. */
1592 enc_str = string_convert(&conv, utf8_str, lenp);
1596 convert_setup(&conv, NULL, NULL);
1601 #endif /* FEAT_MBYTE */
1603 #if (defined(FEAT_MBYTE) && defined(WIN3264)) || defined(PROTO)
1605 * Convert from the active codepage to 'encoding'.
1606 * Input is "str[str_size]".
1607 * The result is in allocated memory: "out[outlen]". With terminating NUL.
1610 acp_to_enc(str, str_size, out, outlen)
1619 MultiByteToWideChar_alloc(GetACP(), 0, str, str_size, &widestr, outlen);
1620 if (widestr != NULL)
1622 ++*outlen; /* Include the 0 after the string */
1623 *out = utf16_to_enc((short_u *)widestr, outlen);
1631 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
1638 # ifdef MCH_WRITE_DUMP
1642 if (psz[strlen(psz) - 1] != '\n')
1643 fputc('\n', fdDump);
1659 va_start(args, pszFormat);
1660 vsprintf(szBuff, pszFormat, args);
1663 OutputDebugString(szBuff);
1668 #if !defined(FEAT_GUI) || defined(PROTO)
1669 # if defined(FEAT_TITLE) && defined(WIN3264)
1670 extern HWND g_hWnd; /* This is in os_win32.c. */
1674 * Showing the printer dialog is tricky since we have no GUI
1675 * window to parent it. The following routines are needed to
1676 * get the window parenting and Z-order to work properly.
1679 GetConsoleHwnd(void)
1681 # define MY_BUFSIZE 1024 // Buffer size for console window titles.
1683 char pszNewWindowTitle[MY_BUFSIZE]; // Contains fabricated WindowTitle.
1684 char pszOldWindowTitle[MY_BUFSIZE]; // Contains original WindowTitle.
1686 /* Skip if it's already set. */
1690 # if defined(FEAT_TITLE) && defined(WIN3264)
1691 /* Window handle may have been found by init code (Windows NT only) */
1699 GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
1701 wsprintf(pszNewWindowTitle, "%s/%d/%d",
1704 GetCurrentProcessId());
1705 SetConsoleTitle(pszNewWindowTitle);
1707 s_hwnd = FindWindow(NULL, pszNewWindowTitle);
1709 SetConsoleTitle(pszOldWindowTitle);
1713 * Console implementation of ":winpos".
1716 mch_get_winpos(int *x, int *y)
1721 GetWindowRect(s_hwnd, &rect);
1728 * Console implementation of ":winpos x y".
1731 mch_set_winpos(int x, int y)
1734 SetWindowPos(s_hwnd, NULL, x, y, 0, 0,
1735 SWP_NOZORDER | SWP_NOSIZE | SWP_NOACTIVATE);
1739 #if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1744 /*=================================================================
1745 * Win32 printer stuff
1748 static HFONT prt_font_handles[2][2][2];
1749 static PRINTDLG prt_dlg;
1750 static const int boldface[2] = {FW_REGULAR, FW_BOLD};
1751 static TEXTMETRIC prt_tm;
1752 static int prt_line_height;
1753 static int prt_number_width;
1754 static int prt_left_margin;
1755 static int prt_right_margin;
1756 static int prt_top_margin;
1757 static char_u szAppName[] = TEXT("VIM");
1758 static HWND hDlgPrint;
1759 static int *bUserAbort = NULL;
1760 static char_u *prt_name = NULL;
1762 /* Defines which are also in vim.rc. */
1763 #define IDC_BOX1 400
1764 #define IDC_PRINTTEXT1 401
1765 #define IDC_PRINTTEXT2 402
1766 #define IDC_PROGRESS 403
1769 * Convert BGR to RGB for Windows GDI calls
1772 swap_me(COLORREF colorref)
1775 char *ptr = (char *)&colorref;
1778 *(ptr ) = *(ptr + 2);
1783 /* Attempt to make this work for old and new compilers */
1784 #if !defined(_WIN64) && (!defined(_MSC_VER) || _MSC_VER < 1300)
1785 # define PDP_RETVAL BOOL
1787 # define PDP_RETVAL INT_PTR
1791 static PDP_RETVAL CALLBACK
1792 PrintDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
1795 NONCLIENTMETRICS nm;
1803 nm.cbSize = sizeof(NONCLIENTMETRICS);
1804 if (SystemParametersInfo(
1805 SPI_GETNONCLIENTMETRICS,
1806 sizeof(NONCLIENTMETRICS),
1810 char buff[MAX_PATH];
1813 /* Translate the dialog texts */
1814 hfont = CreateFontIndirect(&nm.lfMessageFont);
1815 for (i = IDC_PRINTTEXT1; i <= IDC_PROGRESS; i++)
1817 SendDlgItemMessage(hDlg, i, WM_SETFONT, (WPARAM)hfont, 1);
1818 if (GetDlgItemText(hDlg,i, buff, sizeof(buff)))
1819 SetDlgItemText(hDlg,i, _(buff));
1821 SendDlgItemMessage(hDlg, IDCANCEL,
1822 WM_SETFONT, (WPARAM)hfont, 1);
1823 if (GetDlgItemText(hDlg,IDCANCEL, buff, sizeof(buff)))
1824 SetDlgItemText(hDlg,IDCANCEL, _(buff));
1827 SetWindowText(hDlg, szAppName);
1828 if (prt_name != NULL)
1830 SetDlgItemText(hDlg, IDC_PRINTTEXT2, (LPSTR)prt_name);
1834 EnableMenuItem(GetSystemMenu(hDlg, FALSE), SC_CLOSE, MF_GRAYED);
1836 BringWindowToTop(s_hwnd);
1842 EnableWindow(GetParent(hDlg), TRUE);
1843 DestroyWindow(hDlg);
1846 DeleteObject(hfont);
1854 static BOOL CALLBACK
1855 AbortProc(HDC hdcPrn, int iCode)
1859 while (!*bUserAbort && pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1861 if (!hDlgPrint || !pIsDialogMessage(hDlgPrint, &msg))
1863 TranslateMessage(&msg);
1864 pDispatchMessage(&msg);
1867 return !*bUserAbort;
1872 static UINT_PTR CALLBACK
1874 HWND hDlg, // handle to dialog box
1875 UINT uiMsg, // message identifier
1876 WPARAM wParam, // message parameter
1877 LPARAM lParam // message parameter
1881 RECT rc, rcDlg, rcOwner;
1884 if (uiMsg == WM_INITDIALOG)
1886 // Get the owner window and dialog box rectangles.
1887 if ((hwndOwner = GetParent(hDlg)) == NULL)
1888 hwndOwner = GetDesktopWindow();
1890 GetWindowRect(hwndOwner, &rcOwner);
1891 GetWindowRect(hDlg, &rcDlg);
1892 CopyRect(&rc, &rcOwner);
1894 // Offset the owner and dialog box rectangles so that
1895 // right and bottom values represent the width and
1896 // height, and then offset the owner again to discard
1897 // space taken up by the dialog box.
1899 OffsetRect(&rcDlg, -rcDlg.left, -rcDlg.top);
1900 OffsetRect(&rc, -rc.left, -rc.top);
1901 OffsetRect(&rc, -rcDlg.right, -rcDlg.bottom);
1903 // The new position is the sum of half the remaining
1904 // space and the owner's original position.
1908 rcOwner.left + (rc.right / 2),
1909 rcOwner.top + (rc.bottom / 2),
1910 0, 0, // ignores size arguments
1913 /* tackle the printdlg copiesctrl problem */
1914 pPD = (PRINTDLG *)lParam;
1915 pPD->nCopies = (WORD)pPD->lCustData;
1916 SetDlgItemInt( hDlg, edt3, pPD->nCopies, FALSE );
1917 /* Bring the window to top */
1918 BringWindowToTop(GetParent(hDlg));
1919 SetForegroundWindow(hDlg);
1927 mch_print_cleanup(void)
1933 for (pifBold = 0; pifBold <= 1; pifBold++)
1934 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
1935 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
1936 DeleteObject(prt_font_handles[pifBold][pifItalic][pifUnderline]);
1938 if (prt_dlg.hDC != NULL)
1939 DeleteDC(prt_dlg.hDC);
1941 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
1945 to_device_units(int idx, int dpi, int physsize, int offset, int def_number)
1951 u = prt_get_unit(idx);
1952 if (u == PRT_UNIT_NONE)
1958 nr = printer_opts[idx].number;
1963 ret = (physsize * nr) / 100;
1969 ret = (nr * 10 * dpi) / 254;
1971 case PRT_UNIT_POINT:
1972 ret = (nr * 10 * dpi) / 720;
1979 return ret - offset;
1994 GetTextMetrics(prt_dlg.hDC, &prt_tm);
1995 prt_line_height = prt_tm.tmHeight + prt_tm.tmExternalLeading;
1997 hr = GetDeviceCaps(prt_dlg.hDC, HORZRES);
1999 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
2001 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
2004 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALWIDTH);
2005 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETX);
2007 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSX);
2009 rev_offset = phyw - (dvoff + hr);
2011 prt_left_margin = to_device_units(OPT_PRINT_LEFT, dpi, phyw, dvoff, 10);
2012 if (prt_use_number())
2014 prt_number_width = PRINT_NUMBER_WIDTH * prt_tm.tmAveCharWidth;
2015 prt_left_margin += prt_number_width;
2018 prt_number_width = 0;
2020 prt_right_margin = hr - to_device_units(OPT_PRINT_RIGHT, dpi, phyw,
2023 return (prt_right_margin - prt_left_margin) / prt_tm.tmAveCharWidth;
2039 vr = GetDeviceCaps(prt_dlg.hDC, VERTRES);
2041 Escape(prt_dlg.hDC, GETPHYSPAGESIZE, NULL, NULL, &pagesize);
2043 Escape(prt_dlg.hDC, GETPRINTINGOFFSET, NULL, NULL, &pagesize);
2046 phyw = GetDeviceCaps(prt_dlg.hDC, PHYSICALHEIGHT);
2047 dvoff = GetDeviceCaps(prt_dlg.hDC, PHYSICALOFFSETY);
2049 dpi = GetDeviceCaps(prt_dlg.hDC, LOGPIXELSY);
2051 rev_offset = phyw - (dvoff + vr);
2053 prt_top_margin = to_device_units(OPT_PRINT_TOP, dpi, phyw, dvoff, 5);
2055 /* adjust top margin if there is a header */
2056 prt_top_margin += prt_line_height * prt_header_height();
2058 bottom_margin = vr - to_device_units(OPT_PRINT_BOT, dpi, phyw,
2061 return (bottom_margin - prt_top_margin) / prt_line_height;
2065 mch_print_init(prt_settings_T *psettings, char_u *jobname, int forceit)
2067 static HGLOBAL stored_dm = NULL;
2068 static HGLOBAL stored_devn = NULL;
2069 static int stored_nCopies = 1;
2070 static int stored_nFlags = 0;
2081 bUserAbort = &(psettings->user_abort);
2082 vim_memset(&prt_dlg, 0, sizeof(PRINTDLG));
2083 prt_dlg.lStructSize = sizeof(PRINTDLG);
2085 GetConsoleHwnd(); /* get value of s_hwnd */
2087 prt_dlg.hwndOwner = s_hwnd;
2088 prt_dlg.Flags = PD_NOPAGENUMS | PD_NOSELECTION | PD_RETURNDC;
2091 prt_dlg.hDevMode = stored_dm;
2092 prt_dlg.hDevNames = stored_devn;
2093 prt_dlg.lCustData = stored_nCopies; // work around bug in print dialog
2096 * Use hook to prevent console window being sent to back
2098 prt_dlg.lpfnPrintHook = PrintHookProc;
2099 prt_dlg.Flags |= PD_ENABLEPRINTHOOK;
2101 prt_dlg.Flags |= stored_nFlags;
2105 * If bang present, return default printer setup with no dialog
2106 * never show dialog if we are running over telnet
2114 prt_dlg.Flags |= PD_RETURNDEFAULT;
2117 * MSDN suggests setting the first parameter to WINSPOOL for
2118 * NT, but NULL appears to work just as well.
2121 prt_dlg.hDC = CreateDC(NULL, p_pdev, NULL, NULL);
2125 prt_dlg.Flags |= PD_RETURNDEFAULT;
2126 if (PrintDlg(&prt_dlg) == 0)
2130 else if (PrintDlg(&prt_dlg) == 0)
2135 * keep the previous driver context
2137 stored_dm = prt_dlg.hDevMode;
2138 stored_devn = prt_dlg.hDevNames;
2139 stored_nFlags = prt_dlg.Flags;
2140 stored_nCopies = prt_dlg.nCopies;
2143 if (prt_dlg.hDC == NULL)
2145 EMSG(_("E237: Printer selection failed"));
2146 mch_print_cleanup();
2150 /* Not all printer drivers report the support of color (or grey) in the
2151 * same way. Let's set has_color if there appears to be some way to print
2153 i = GetDeviceCaps(prt_dlg.hDC, NUMCOLORS);
2154 psettings->has_color = (GetDeviceCaps(prt_dlg.hDC, BITSPIXEL) > 1
2155 || GetDeviceCaps(prt_dlg.hDC, PLANES) > 1
2156 || i > 2 || i == -1);
2158 /* Ensure all font styles are baseline aligned */
2159 SetTextAlign(prt_dlg.hDC, TA_BASELINE|TA_LEFT);
2162 * On some windows systems the nCopies parameter is not
2163 * passed back correctly. It must be retrieved from the
2166 mem = (DEVMODE *)GlobalLock(prt_dlg.hDevMode);
2170 if (mem->dmCopies != 1)
2171 stored_nCopies = mem->dmCopies;
2173 if ((mem->dmFields & DM_DUPLEX) && (mem->dmDuplex & ~DMDUP_SIMPLEX))
2174 psettings->duplex = TRUE;
2175 if ((mem->dmFields & DM_COLOR) && (mem->dmColor & DMCOLOR_COLOR))
2176 psettings->has_color = TRUE;
2178 GlobalUnlock(prt_dlg.hDevMode);
2180 devname = (DEVNAMES *)GlobalLock(prt_dlg.hDevNames);
2183 char_u *printer_name = (char_u *)devname + devname->wDeviceOffset;
2184 char_u *port_name = (char_u *)devname +devname->wOutputOffset;
2185 char_u *text = _("to %s on %s");
2187 prt_name = alloc((unsigned)(STRLEN(printer_name) + STRLEN(port_name)
2189 if (prt_name != NULL)
2190 wsprintf(prt_name, text, printer_name, port_name);
2192 GlobalUnlock(prt_dlg.hDevNames);
2195 * Initialise the font according to 'printfont'
2197 vim_memset(&fLogFont, 0, sizeof(fLogFont));
2198 if (get_logfont(&fLogFont, p_pfn, prt_dlg.hDC, TRUE) == FAIL)
2200 EMSG2(_("E613: Unknown printer font: %s"), p_pfn);
2201 mch_print_cleanup();
2205 for (pifBold = 0; pifBold <= 1; pifBold++)
2206 for (pifItalic = 0; pifItalic <= 1; pifItalic++)
2207 for (pifUnderline = 0; pifUnderline <= 1; pifUnderline++)
2209 fLogFont.lfWeight = boldface[pifBold];
2210 fLogFont.lfItalic = pifItalic;
2211 fLogFont.lfUnderline = pifUnderline;
2212 prt_font_handles[pifBold][pifItalic][pifUnderline]
2213 = CreateFontIndirect(&fLogFont);
2216 SetBkMode(prt_dlg.hDC, OPAQUE);
2217 SelectObject(prt_dlg.hDC, prt_font_handles[0][0][0]);
2220 * Fill in the settings struct
2222 psettings->chars_per_line = prt_get_cpl();
2223 psettings->lines_per_page = prt_get_lpp();
2224 psettings->n_collated_copies = (prt_dlg.Flags & PD_COLLATE)
2225 ? prt_dlg.nCopies : 1;
2226 psettings->n_uncollated_copies = (prt_dlg.Flags & PD_COLLATE)
2227 ? 1 : prt_dlg.nCopies;
2229 if (psettings->n_collated_copies == 0)
2230 psettings->n_collated_copies = 1;
2232 if (psettings->n_uncollated_copies == 0)
2233 psettings->n_uncollated_copies = 1;
2235 psettings->jobname = jobname;
2241 DWORD err = CommDlgExtendedError();
2248 sprintf(buf, "%ld", err);
2249 EMSG2(_("E238: Print error: %s"), buf);
2253 /* I suspect FormatMessage() doesn't work for values returned by
2254 * CommDlgExtendedError(). What does? */
2255 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
2256 FORMAT_MESSAGE_FROM_SYSTEM |
2257 FORMAT_MESSAGE_IGNORE_INSERTS,
2258 NULL, err, 0, (LPTSTR)(&buf), 0, NULL);
2259 EMSG2(_("E238: Print error: %s"),
2260 buf == NULL ? (char_u *)_("Unknown") : buf);
2261 LocalFree((LPVOID)(buf));
2265 msg_clr_eos(); /* Maybe canceled */
2267 mch_print_cleanup();
2274 mch_print_begin(prt_settings_T *psettings)
2280 hDlgPrint = CreateDialog(GetModuleHandle(NULL), TEXT("PrintDlgBox"),
2281 prt_dlg.hwndOwner, PrintDlgProc);
2283 Escape(prt_dlg.hDC, SETABORTPROC, 0, (LPSTR)AbortProc, NULL);
2285 SetAbortProc(prt_dlg.hDC, AbortProc);
2287 wsprintf(szBuffer, _("Printing '%s'"), gettail(psettings->jobname));
2288 SetDlgItemText(hDlgPrint, IDC_PRINTTEXT1, (LPSTR)szBuffer);
2290 vim_memset(&di, 0, sizeof(DOCINFO));
2291 di.cbSize = sizeof(DOCINFO);
2292 di.lpszDocName = psettings->jobname;
2293 ret = StartDoc(prt_dlg.hDC, &di);
2296 /* Give focus back to main window (when using MDI). */
2305 mch_print_end(prt_settings_T *psettings)
2307 EndDoc(prt_dlg.hDC);
2309 SendMessage(hDlgPrint, WM_COMMAND, 0, 0);
2313 mch_print_end_page(void)
2315 return (EndPage(prt_dlg.hDC) > 0);
2319 mch_print_begin_page(char_u *msg)
2322 SetDlgItemText(hDlgPrint, IDC_PROGRESS, (LPSTR)msg);
2323 return (StartPage(prt_dlg.hDC) > 0);
2327 mch_print_blank_page(void)
2329 return (mch_print_begin_page(NULL) ? (mch_print_end_page()) : FALSE);
2332 static int prt_pos_x = 0;
2333 static int prt_pos_y = 0;
2336 mch_print_start_line(margin, page_line)
2341 prt_pos_x = -prt_number_width;
2344 prt_pos_y = page_line * prt_line_height
2345 + prt_tm.tmAscent + prt_tm.tmExternalLeading;
2349 mch_print_text_out(char_u *p, int len)
2351 #ifdef FEAT_PROPORTIONAL_FONTS
2355 TextOut(prt_dlg.hDC, prt_pos_x + prt_left_margin,
2356 prt_pos_y + prt_top_margin, p, len);
2357 #ifndef FEAT_PROPORTIONAL_FONTS
2358 prt_pos_x += len * prt_tm.tmAveCharWidth;
2359 return (prt_pos_x + prt_left_margin + prt_tm.tmAveCharWidth
2360 + prt_tm.tmOverhang > prt_right_margin);
2363 GetTextExtentPoint(prt_dlg.hDC, p, len, &sz);
2365 GetTextExtentPoint32(prt_dlg.hDC, p, len, &sz);
2367 prt_pos_x += (sz.cx - prt_tm.tmOverhang);
2368 /* This is wrong when printing spaces for a TAB. */
2372 GetTextExtentPoint(prt_dlg.hDC, p + len, 1, &sz);
2374 GetTextExtentPoint32(prt_dlg.hDC, p + len, 1, &sz);
2376 return (prt_pos_x + prt_left_margin + sz.cx > prt_right_margin);
2381 mch_print_set_font(int iBold, int iItalic, int iUnderline)
2383 SelectObject(prt_dlg.hDC, prt_font_handles[iBold][iItalic][iUnderline]);
2387 mch_print_set_bg(long_u bgcol)
2389 SetBkColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
2390 swap_me((COLORREF)bgcol)));
2392 * With a white background we can draw characters transparent, which is
2393 * good for italic characters that overlap to the next char cell.
2395 if (bgcol == 0xffffffUL)
2396 SetBkMode(prt_dlg.hDC, TRANSPARENT);
2398 SetBkMode(prt_dlg.hDC, OPAQUE);
2402 mch_print_set_fg(long_u fgcol)
2404 SetTextColor(prt_dlg.hDC, GetNearestColor(prt_dlg.hDC,
2405 swap_me((COLORREF)fgcol)));
2408 #endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
2412 #if defined(FEAT_SHORTCUT) || defined(PROTO)
2413 # include <shlobj.h>
2416 * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
2417 * to and return that name in allocated memory.
2418 * Otherwise NULL is returned.
2421 mch_resolve_shortcut(char_u *fname)
2424 IShellLink *psl = NULL;
2425 IPersistFile *ppf = NULL;
2426 OLECHAR wsz[MAX_PATH];
2427 WIN32_FIND_DATA ffd; // we get those free of charge
2428 TCHAR buf[MAX_PATH]; // could have simply reused 'wsz'...
2429 char_u *rfname = NULL;
2432 /* Check if the file name ends in ".lnk". Avoid calling
2433 * CoCreateInstance(), it's quite slow. */
2436 len = (int)STRLEN(fname);
2437 if (len <= 4 || STRNICMP(fname + len - 4, ".lnk", 4) != 0)
2442 // create a link manager object and request its interface
2443 hr = CoCreateInstance(
2444 &CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER,
2445 &IID_IShellLink, (void**)&psl);
2447 goto shortcut_error;
2449 // Get a pointer to the IPersistFile interface.
2450 hr = psl->lpVtbl->QueryInterface(
2451 psl, &IID_IPersistFile, (void**)&ppf);
2453 goto shortcut_error;
2455 // full path string must be in Unicode.
2456 MultiByteToWideChar(CP_ACP, 0, fname, -1, wsz, MAX_PATH);
2458 // "load" the name and resolve the link
2459 hr = ppf->lpVtbl->Load(ppf, wsz, STGM_READ);
2461 goto shortcut_error;
2462 #if 0 // This makes Vim wait a long time if the target doesn't exist.
2463 hr = psl->lpVtbl->Resolve(psl, NULL, SLR_NO_UI);
2465 goto shortcut_error;
2468 // Get the path to the link target.
2469 ZeroMemory(buf, MAX_PATH);
2470 hr = psl->lpVtbl->GetPath(psl, buf, MAX_PATH, &ffd, 0);
2471 if (hr == S_OK && buf[0] != NUL)
2472 rfname = vim_strsave(buf);
2475 // Release all interface pointers (both belong to the same object)
2477 ppf->lpVtbl->Release(ppf);
2479 psl->lpVtbl->Release(psl);
2486 #if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
2488 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
2491 win32_set_foreground()
2494 GetConsoleHwnd(); /* get value of s_hwnd */
2497 SetForegroundWindow(s_hwnd);
2501 #if defined(FEAT_CLIENTSERVER) || defined(PROTO)
2503 * Client-server code for Vim
2505 * Originally written by Paul Moore
2508 /* In order to handle inter-process messages, we need to have a window. But
2509 * the functions in this module can be called before the main GUI window is
2510 * created (and may also be called in the console version, where there is no
2511 * GUI window at all).
2513 * So we create a hidden window, and arrange to destroy it on exit.
2515 HWND message_window = 0; /* window that's handling messsages */
2517 #define VIM_CLASSNAME "VIM_MESSAGES"
2518 #define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
2520 /* Communication is via WM_COPYDATA messages. The message type is send in
2521 * the dwData parameter. Types are defined here. */
2522 #define COPYDATA_KEYS 0
2523 #define COPYDATA_REPLY 1
2524 #define COPYDATA_EXPR 10
2525 #define COPYDATA_RESULT 11
2526 #define COPYDATA_ERROR_RESULT 12
2527 #define COPYDATA_ENCODING 20
2529 /* This is a structure containing a server HWND and its name. */
2536 /* Last received 'encoding' that the client uses. */
2537 static char_u *client_enc = NULL;
2540 * Tell the other side what encoding we are using.
2541 * Errors are ignored.
2544 serverSendEnc(HWND target)
2546 COPYDATASTRUCT data;
2548 data.dwData = COPYDATA_ENCODING;
2550 data.cbData = (DWORD)STRLEN(p_enc) + 1;
2551 data.lpData = p_enc;
2553 data.cbData = (DWORD)STRLEN("latin1") + 1;
2554 data.lpData = "latin1";
2556 (void)SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2561 * Clean up on exit. This destroys the hidden message window.
2567 CleanUpMessaging(void)
2569 if (message_window != 0)
2571 DestroyWindow(message_window);
2576 static int save_reply(HWND server, char_u *reply, int expr);
2579 * The window procedure for the hidden message window.
2580 * It handles callback messages and notifications from servers.
2581 * In order to process these messages, it is necessary to run a
2582 * message loop. Code which may run before the main message loop
2583 * is started (in the GUI) is careful to pump messages when it needs
2584 * to. Features which require message delivery during normal use will
2585 * not work in the console version - this basically means those
2586 * features which allow Vim to act as a server, rather than a client.
2588 static LRESULT CALLBACK
2589 Messaging_WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
2591 if (msg == WM_COPYDATA)
2593 /* This is a message from another Vim. The dwData member of the
2594 * COPYDATASTRUCT determines the type of message:
2595 * COPYDATA_ENCODING:
2596 * The encoding that the client uses. Following messages will
2597 * use this encoding, convert if needed.
2599 * A key sequence. We are a server, and a client wants these keys
2600 * adding to the input queue.
2602 * A reply. We are a client, and a server has sent this message
2603 * in response to a request. (server2client())
2605 * An expression. We are a server, and a client wants us to
2606 * evaluate this expression.
2608 * A reply. We are a client, and a server has sent this message
2609 * in response to a COPYDATA_EXPR.
2610 * COPYDATA_ERROR_RESULT:
2611 * A reply. We are a client, and a server has sent this message
2612 * in response to a COPYDATA_EXPR that failed to evaluate.
2614 COPYDATASTRUCT *data = (COPYDATASTRUCT*)lParam;
2615 HWND sender = (HWND)wParam;
2616 COPYDATASTRUCT reply;
2623 switch (data->dwData)
2625 case COPYDATA_ENCODING:
2627 /* Remember the encoding that the client uses. */
2628 vim_free(client_enc);
2629 client_enc = enc_canonize((char_u *)data->lpData);
2634 /* Remember who sent this, for <client> */
2635 clientWindow = sender;
2637 /* Add the received keys to the input buffer. The loop waiting
2638 * for the user to do something should check the input buffer. */
2639 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2640 server_to_input_buf(str);
2644 /* Wake up the main GUI loop. */
2646 PostMessage(s_hwnd, WM_NULL, 0, 0);
2651 /* Remember who sent this, for <client> */
2652 clientWindow = sender;
2654 str = serverConvert(client_enc, (char_u *)data->lpData, &tofree);
2655 res = eval_client_expr_to_string(str);
2660 res = vim_strsave(_(e_invexprmsg));
2661 reply.dwData = COPYDATA_ERROR_RESULT;
2664 reply.dwData = COPYDATA_RESULT;
2666 reply.cbData = (DWORD)STRLEN(res) + 1;
2668 serverSendEnc(sender);
2669 retval = (int)SendMessage(sender, WM_COPYDATA, (WPARAM)message_window,
2674 case COPYDATA_REPLY:
2675 case COPYDATA_RESULT:
2676 case COPYDATA_ERROR_RESULT:
2677 if (data->lpData != NULL)
2679 str = serverConvert(client_enc, (char_u *)data->lpData,
2682 str = vim_strsave(str);
2683 if (save_reply(sender, str,
2684 (data->dwData == COPYDATA_REPLY ? 0 :
2685 (data->dwData == COPYDATA_RESULT ? 1 :
2689 else if (data->dwData == COPYDATA_REPLY)
2691 sprintf((char *)winstr, PRINTF_HEX_LONG_U, (long_u)sender);
2692 apply_autocmds(EVENT_REMOTEREPLY, winstr, str,
2703 else if (msg == WM_ACTIVATE && wParam == WA_ACTIVE)
2705 /* When the message window is activated (brought to the foreground),
2706 * this actually applies to the text window. */
2708 GetConsoleHwnd(); /* get value of s_hwnd */
2712 SetForegroundWindow(s_hwnd);
2717 return DefWindowProc(hwnd, msg, wParam, lParam);
2721 * Initialise the message handling process. This involves creating a window
2722 * to handle messages - the window will not be visible.
2725 serverInitMessaging(void)
2730 /* Clean up on exit */
2731 atexit(CleanUpMessaging);
2733 /* Register a window class - we only really care
2734 * about the window procedure
2736 s_hinst = (HINSTANCE)GetModuleHandle(0);
2738 wndclass.lpfnWndProc = Messaging_WndProc;
2739 wndclass.cbClsExtra = 0;
2740 wndclass.cbWndExtra = 0;
2741 wndclass.hInstance = s_hinst;
2742 wndclass.hIcon = NULL;
2743 wndclass.hCursor = NULL;
2744 wndclass.hbrBackground = NULL;
2745 wndclass.lpszMenuName = NULL;
2746 wndclass.lpszClassName = VIM_CLASSNAME;
2747 RegisterClass(&wndclass);
2749 /* Create the message window. It will be hidden, so the details don't
2750 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2751 * focus from gvim. */
2752 message_window = CreateWindow(VIM_CLASSNAME, "",
2753 WS_POPUPWINDOW | WS_CAPTION,
2754 CW_USEDEFAULT, CW_USEDEFAULT,
2755 100, 100, NULL, NULL,
2759 /* Used by serverSendToVim() to find an alternate server name. */
2760 static char_u *altname_buf_ptr = NULL;
2763 * Get the title of the window "hwnd", which is the Vim server name, in
2764 * "name[namelen]" and return the length.
2765 * Returns zero if window "hwnd" is not a Vim server.
2768 getVimServerName(HWND hwnd, char *name, int namelen)
2771 char buffer[VIM_CLASSNAME_LEN + 1];
2773 /* Ignore windows which aren't Vim message windows */
2774 len = GetClassName(hwnd, buffer, sizeof(buffer));
2775 if (len != VIM_CLASSNAME_LEN || STRCMP(buffer, VIM_CLASSNAME) != 0)
2778 /* Get the title of the window */
2779 return GetWindowText(hwnd, name, namelen);
2782 static BOOL CALLBACK
2783 enumWindowsGetServer(HWND hwnd, LPARAM lparam)
2785 struct server_id *id = (struct server_id *)lparam;
2786 char server[MAX_PATH];
2788 /* Get the title of the window */
2789 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2792 /* If this is the server we're looking for, return its HWND */
2793 if (STRICMP(server, id->name) == 0)
2799 /* If we are looking for an alternate server, remember this name. */
2800 if (altname_buf_ptr != NULL
2801 && STRNICMP(server, id->name, STRLEN(id->name)) == 0
2802 && vim_isdigit(server[STRLEN(id->name)]))
2804 STRCPY(altname_buf_ptr, server);
2805 altname_buf_ptr = NULL; /* don't use another name */
2808 /* Otherwise, keep looking */
2812 static BOOL CALLBACK
2813 enumWindowsGetNames(HWND hwnd, LPARAM lparam)
2815 garray_T *ga = (garray_T *)lparam;
2816 char server[MAX_PATH];
2818 /* Get the title of the window */
2819 if (getVimServerName(hwnd, server, sizeof(server)) == 0)
2822 /* Add the name to the list */
2823 ga_concat(ga, server);
2824 ga_concat(ga, "\n");
2829 findServer(char_u *name)
2831 struct server_id id;
2836 EnumWindows(enumWindowsGetServer, (LPARAM)(&id));
2842 serverSetName(char_u *name)
2849 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
2850 ok_name = alloc((unsigned)STRLEN(name) + 10);
2852 STRCPY(ok_name, name);
2853 p = ok_name + STRLEN(name);
2857 /* This is inefficient - we're doing an EnumWindows loop for each
2858 * possible name. It would be better to grab all names in one go,
2859 * and scan the list each time...
2861 hwnd = findServer(ok_name);
2869 sprintf((char *)p, "%d", i);
2876 /* Remember the name */
2877 serverName = ok_name;
2879 need_maketitle = TRUE; /* update Vim window title later */
2882 /* Update the message window title */
2883 SetWindowText(message_window, ok_name);
2886 /* Set the servername variable */
2887 set_vim_var_string(VV_SEND_SERVER, serverName, -1);
2893 serverGetVimNames(void)
2897 ga_init2(&ga, 1, 100);
2899 EnumWindows(enumWindowsGetNames, (LPARAM)(&ga));
2900 ga_append(&ga, NUL);
2906 serverSendReply(name, reply)
2907 char_u *name; /* Where to send. */
2908 char_u *reply; /* What to send. */
2911 COPYDATASTRUCT data;
2914 /* The "name" argument is a magic cookie obtained from expand("<client>").
2915 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2916 * value of the client's message window HWND.
2918 sscanf((char *)name, SCANF_HEX_LONG_U, &n);
2923 if (!IsWindow(target))
2926 data.dwData = COPYDATA_REPLY;
2927 data.cbData = (DWORD)STRLEN(reply) + 1;
2928 data.lpData = reply;
2930 serverSendEnc(target);
2931 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2939 serverSendToVim(name, cmd, result, ptarget, asExpr, silent)
2940 char_u *name; /* Where to send. */
2941 char_u *cmd; /* What to send. */
2942 char_u **result; /* Result of eval'ed expression */
2943 void *ptarget; /* HWND of server */
2944 int asExpr; /* Expression or keys? */
2945 int silent; /* don't complain about no server */
2948 COPYDATASTRUCT data;
2949 char_u *retval = NULL;
2951 char_u altname_buf[MAX_PATH];
2953 /* If the server name does not end in a digit then we look for an
2954 * alternate name. e.g. when "name" is GVIM the we may find GVIM2. */
2955 if (STRLEN(name) > 1 && !vim_isdigit(name[STRLEN(name) - 1]))
2956 altname_buf_ptr = altname_buf;
2957 altname_buf[0] = NUL;
2958 target = findServer(name);
2959 altname_buf_ptr = NULL;
2960 if (target == 0 && altname_buf[0] != NUL)
2961 /* Use another server name we found. */
2962 target = findServer(altname_buf);
2967 EMSG2(_(e_noserver), name);
2972 *(HWND *)ptarget = target;
2974 data.dwData = asExpr ? COPYDATA_EXPR : COPYDATA_KEYS;
2975 data.cbData = (DWORD)STRLEN(cmd) + 1;
2978 serverSendEnc(target);
2979 if (SendMessage(target, WM_COPYDATA, (WPARAM)message_window,
2980 (LPARAM)(&data)) == 0)
2984 retval = serverGetReply(target, &retcode, TRUE, TRUE);
2989 *result = retval; /* Caller assumes responsibility for freeing */
2995 * Bring the server to the foreground.
2998 serverForeground(name)
3001 HWND target = findServer(name);
3004 SetForegroundWindow(target);
3007 /* Replies from server need to be stored until the client picks them up via
3008 * remote_read(). So we maintain a list of server-id/reply pairs.
3009 * Note that there could be multiple replies from one server pending if the
3010 * client is slow picking them up.
3011 * We just store the replies in a simple list. When we remove an entry, we
3012 * move list entries down to fill the gap.
3013 * The server ID is simply the HWND.
3017 HWND server; /* server window */
3018 char_u *reply; /* reply string */
3019 int expr_result; /* 0 for REPLY, 1 for RESULT 2 for error */
3022 static garray_T reply_list = {0, 0, sizeof(reply_T), 5, 0};
3024 #define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
3025 #define REPLY_COUNT (reply_list.ga_len)
3027 /* Flag which is used to wait for a reply */
3028 static int reply_received = 0;
3031 * Store a reply. "reply" must be allocated memory (or NULL).
3034 save_reply(HWND server, char_u *reply, int expr)
3038 if (ga_grow(&reply_list, 1) == FAIL)
3041 rep = REPLY_ITEM(REPLY_COUNT);
3042 rep->server = server;
3044 rep->expr_result = expr;
3045 if (rep->reply == NULL)
3054 * Get a reply from server "server".
3055 * When "expr_res" is non NULL, get the result of an expression, otherwise a
3056 * server2client() message.
3057 * When non NULL, point to return code. 0 => OK, -1 => ERROR
3058 * If "remove" is TRUE, consume the message, the caller must free it then.
3059 * if "wait" is TRUE block until a message arrives (or the server exits).
3062 serverGetReply(HWND server, int *expr_res, int remove, int wait)
3068 /* When waiting, loop until the message waiting for is received. */
3071 /* Reset this here, in case a message arrives while we are going
3072 * through the already received messages. */
3075 for (i = 0; i < REPLY_COUNT; ++i)
3077 rep = REPLY_ITEM(i);
3078 if (rep->server == server
3079 && ((rep->expr_result != 0) == (expr_res != NULL)))
3081 /* Save the values we've found for later */
3083 if (expr_res != NULL)
3084 *expr_res = rep->expr_result == 1 ? 0 : -1;
3088 /* Move the rest of the list down to fill the gap */
3089 mch_memmove(rep, rep + 1,
3090 (REPLY_COUNT - i - 1) * sizeof(reply_T));
3094 /* Return the reply to the caller, who takes on responsibility
3095 * for freeing it if "remove" is TRUE. */
3100 /* If we got here, we didn't find a reply. Return immediately if the
3101 * "wait" parameter isn't set. */
3105 /* We need to wait for a reply. Enter a message loop until the
3106 * "reply_received" flag gets set. */
3108 /* Loop until we receive a reply */
3109 while (reply_received == 0)
3111 /* Wait for a SendMessage() call to us. This could be the reply
3112 * we are waiting for. Use a timeout of a second, to catch the
3113 * situation that the server died unexpectedly. */
3114 MsgWaitForMultipleObjects(0, NULL, TRUE, 1000, QS_ALLINPUT);
3116 /* If the server has died, give up */
3117 if (!IsWindow(server))
3120 serverProcessPendingMessages();
3128 * Process any messages in the Windows message queue.
3131 serverProcessPendingMessages(void)
3135 while (pPeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
3137 TranslateMessage(&msg);
3138 pDispatchMessage(&msg);
3142 #endif /* FEAT_CLIENTSERVER */
3144 #if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
3153 static struct charset_pair
3156 {"ANSI", ANSI_CHARSET},
3157 {"CHINESEBIG5", CHINESEBIG5_CHARSET},
3158 {"DEFAULT", DEFAULT_CHARSET},
3159 {"HANGEUL", HANGEUL_CHARSET},
3160 {"OEM", OEM_CHARSET},
3161 {"SHIFTJIS", SHIFTJIS_CHARSET},
3162 {"SYMBOL", SYMBOL_CHARSET},
3164 {"ARABIC", ARABIC_CHARSET},
3165 {"BALTIC", BALTIC_CHARSET},
3166 {"EASTEUROPE", EASTEUROPE_CHARSET},
3167 {"GB2312", GB2312_CHARSET},
3168 {"GREEK", GREEK_CHARSET},
3169 {"HEBREW", HEBREW_CHARSET},
3170 {"JOHAB", JOHAB_CHARSET},
3171 {"MAC", MAC_CHARSET},
3172 {"RUSSIAN", RUSSIAN_CHARSET},
3173 {"THAI", THAI_CHARSET},
3174 {"TURKISH", TURKISH_CHARSET},
3175 # if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
3176 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
3177 {"VIETNAMESE", VIETNAMESE_CHARSET},
3184 * Convert a charset ID to a name.
3185 * Return NULL when not recognized.
3188 charset_id2name(int id)
3190 struct charset_pair *cp;
3192 for (cp = charset_pairs; cp->name != NULL; ++cp)
3193 if ((BYTE)id == cp->charset)
3198 static const LOGFONT s_lfDefault =
3200 -12, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
3201 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
3202 PROOF_QUALITY, FIXED_PITCH | FF_DONTCARE,
3203 "Fixedsys" /* see _ReadVimIni */
3206 /* Initialise the "current height" to -12 (same as s_lfDefault) just
3207 * in case the user specifies a font in "guifont" with no size before a font
3208 * with an explicit size has been set. This defaults the size to this value
3209 * (-12 equates to roughly 9pt).
3211 int current_font_height = -12; /* also used in gui_w48.c */
3213 /* Convert a string representing a point size into pixels. The string should
3214 * be a positive decimal number, with an optional decimal point (eg, "12", or
3215 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
3216 * character is stored in *end. The flag "vertical" says whether this
3217 * calculation is for a vertical (height) size or a horizontal (width) one.
3220 points_to_pixels(char_u *str, char_u **end, int vertical, long_i pprinter_dc)
3225 HWND hwnd = (HWND)0;
3227 HDC printer_dc = (HDC)pprinter_dc;
3231 if (*str == '.' && divisor == 0)
3233 /* Start keeping a divisor, for later */
3238 if (!VIM_ISDIGIT(*str))
3242 points += *str - '0';
3251 if (printer_dc == NULL)
3253 hwnd = GetDesktopWindow();
3254 hdc = GetWindowDC(hwnd);
3259 pixels = MulDiv(points,
3260 GetDeviceCaps(hdc, vertical ? LOGPIXELSY : LOGPIXELSX),
3263 if (printer_dc == NULL)
3264 ReleaseDC(hwnd, hdc);
3279 * 0 = terminate now (monospace & ANSI)
3280 * 1 = continue, still no luck...
3281 * 2 = continue, but we have an acceptable LOGFONT
3282 * (monospace, not ANSI)
3283 * We use these values, as EnumFontFamilies returns 1 if the
3284 * callback function is never called. So, we check the return as
3285 * 0 = perfect, 2 = OK, 1 = no good...
3286 * It's not pretty, but it works!
3289 LOGFONT *lf = (LOGFONT *)(lparam);
3291 #ifndef FEAT_PROPORTIONAL_FONTS
3292 /* Ignore non-monospace fonts without further ado */
3293 if ((ntm->tmPitchAndFamily & 1) != 0)
3297 /* Remember this LOGFONT as a "possible" */
3298 *lf = elf->elfLogFont;
3300 /* Terminate the scan as soon as we find an ANSI font */
3301 if (lf->lfCharSet == ANSI_CHARSET
3302 || lf->lfCharSet == OEM_CHARSET
3303 || lf->lfCharSet == DEFAULT_CHARSET)
3306 /* Continue the scan - we have a non-ANSI font */
3311 init_logfont(LOGFONT *lf)
3314 HWND hwnd = GetDesktopWindow();
3315 HDC hdc = GetWindowDC(hwnd);
3317 n = EnumFontFamilies(hdc,
3318 (LPCSTR)lf->lfFaceName,
3319 (FONTENUMPROC)font_enumproc,
3322 ReleaseDC(hwnd, hdc);
3324 /* If we couldn't find a useable font, return failure */
3328 /* Tidy up the rest of the LOGFONT structure. We set to a basic
3329 * font - get_logfont() sets bold, italic, etc based on the user's
3332 lf->lfHeight = current_font_height;
3334 lf->lfItalic = FALSE;
3335 lf->lfUnderline = FALSE;
3336 lf->lfStrikeOut = FALSE;
3337 lf->lfWeight = FW_NORMAL;
3339 /* Return success */
3344 * Get font info from "name" into logfont "lf".
3345 * Return OK for a valid name, FAIL otherwise.
3356 static LOGFONT *lastlf = NULL;
3362 if (STRCMP(name, "*") == 0)
3364 #if defined(FEAT_GUI_W32)
3366 /* if name is "*", bring up std font dialog: */
3367 vim_memset(&cf, 0, sizeof(cf));
3368 cf.lStructSize = sizeof(cf);
3369 cf.hwndOwner = s_hwnd;
3370 cf.Flags = CF_SCREENFONTS | CF_FIXEDPITCHONLY | CF_INITTOLOGFONTSTRUCT;
3374 cf.nFontType = 0 ; //REGULAR_FONTTYPE;
3375 if (ChooseFont(&cf))
3383 * Split name up, it could be <name>:h<height>:w<width> etc.
3385 for (p = name; *p && *p != ':'; p++)
3387 if (p - name + 1 > LF_FACESIZE)
3388 return FAIL; /* Name too long */
3389 lf->lfFaceName[p - name] = *p;
3392 lf->lfFaceName[p - name] = NUL;
3394 /* First set defaults */
3397 lf->lfWeight = FW_NORMAL;
3398 lf->lfItalic = FALSE;
3399 lf->lfUnderline = FALSE;
3400 lf->lfStrikeOut = FALSE;
3403 * If the font can't be found, try replacing '_' by ' '.
3405 if (init_logfont(lf) == FAIL)
3407 int did_replace = FALSE;
3409 for (i = 0; lf->lfFaceName[i]; ++i)
3410 if (lf->lfFaceName[i] == '_')
3412 lf->lfFaceName[i] = ' ';
3415 if (!did_replace || init_logfont(lf) == FAIL)
3422 /* Set the values found after ':' */
3428 lf->lfHeight = - points_to_pixels(p, &p, TRUE, (long_i)printer_dc);
3431 lf->lfWidth = points_to_pixels(p, &p, FALSE, (long_i)printer_dc);
3434 #ifndef MSWIN16_FASTTEXT
3435 lf->lfWeight = FW_BOLD;
3439 #ifndef MSWIN16_FASTTEXT
3440 lf->lfItalic = TRUE;
3444 lf->lfUnderline = TRUE;
3447 lf->lfStrikeOut = TRUE;
3451 struct charset_pair *cp;
3453 for (cp = charset_pairs; cp->name != NULL; ++cp)
3454 if (STRNCMP(p, cp->name, strlen(cp->name)) == 0)
3456 lf->lfCharSet = cp->charset;
3457 p += strlen(cp->name);
3460 if (cp->name == NULL && verbose)
3462 vim_snprintf((char *)IObuff, IOSIZE,
3463 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p, name);
3472 vim_snprintf((char *)IObuff, IOSIZE,
3473 _("E245: Illegal char '%c' in font name \"%s\""),
3483 #if defined(FEAT_GUI_W32)
3486 /* ron: init lastlf */
3487 if (printer_dc == NULL)
3490 lastlf = (LOGFONT *)alloc(sizeof(LOGFONT));
3492 mch_memmove(lastlf, lf, sizeof(LOGFONT));
3498 #endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */