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.
32 # define SHORT_FNAME /* always 8.3 file name */
36 #include <sys/types.h>
51 #if defined(FEAT_TITLE) && !defined(FEAT_GUI_W32)
52 # include <shellapi.h>
55 #if defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)
58 # include <winspool.h>
66 # ifndef FROM_LEFT_1ST_BUTTON_PRESSED
67 # define FROM_LEFT_1ST_BUTTON_PRESSED 0x0001
69 # ifndef RIGHTMOST_BUTTON_PRESSED
70 # define RIGHTMOST_BUTTON_PRESSED 0x0002
72 # ifndef FROM_LEFT_2ND_BUTTON_PRESSED
73 # define FROM_LEFT_2ND_BUTTON_PRESSED 0x0004
75 # ifndef FROM_LEFT_3RD_BUTTON_PRESSED
76 # define FROM_LEFT_3RD_BUTTON_PRESSED 0x0008
78 # ifndef FROM_LEFT_4TH_BUTTON_PRESSED
79 # define FROM_LEFT_4TH_BUTTON_PRESSED 0x0010
86 # define MOUSE_MOVED 0x0001
89 # define DOUBLE_CLICK 0x0002
94 * When generating prototypes for Win32 on Unix, these lines make the syntax
95 * errors disappear. They do not need to be correct.
101 typedef int CALLBACK
;
102 typedef int COLORREF
;
103 typedef int CONSOLE_CURSOR_INFO
;
106 typedef int ENUMLOGFONT
;
112 typedef int INPUT_RECORD
;
113 typedef int KEY_EVENT_RECORD
;
123 typedef int MOUSE_EVENT_RECORD
;
124 typedef int NEWTEXTMETRIC
;
126 typedef int PRINTDLG
;
127 typedef int PSECURITY_DESCRIPTOR
;
129 typedef int SECURITY_INFORMATION
;
131 typedef int SMALL_RECT
;
132 typedef int TEXTMETRIC
;
140 /* Record all output and all keyboard & mouse input */
141 /* #define MCH_WRITE_DUMP */
143 #ifdef MCH_WRITE_DUMP
148 extern DWORD g_PlatformId
;
151 #ifndef FEAT_GUI_MSWIN
152 extern char g_szOrigTitle
[];
158 static HWND s_hwnd
= 0; /* console window handle, set by GetConsoleHwnd() */
161 extern int WSInitialized
;
163 /* Don't generate prototypes here, because some systems do have these
165 #if defined(__GNUC__) && !defined(PROTO)
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
)
180 return (char *)GetFullPathName(fname
, len
, buf
, &toss
);
184 int _chdrive(int drive
)
186 char temp
[3] = "-:";
187 temp
[0] = drive
+ 'A' - 1;
188 return !SetCurrentDirectory(temp
);
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
)
198 // this is fast but not correct:
199 return stricmp(a
, b
);
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
);
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()!
224 ml_close_all(TRUE
); /* remove all memfiles */
229 # ifdef FEAT_NETBEANS_INTG
232 WSInitialized
= FALSE
;
236 #ifdef DYNAMIC_GETTEXT
250 #endif /* FEAT_GUI_MSWIN */
254 * Init the tables for toupper() and tolower().
265 /* Init the tables for toupper() and tolower() */
266 for (i
= 0; i
< 256; ++i
)
267 toupper_tab
[i
] = tolower_tab
[i
] = i
;
269 CharUpperBuff(toupper_tab
, 256);
270 CharLowerBuff(tolower_tab
, 256);
272 AnsiUpperBuff(toupper_tab
, 256);
273 AnsiLowerBuff(tolower_tab
, 256);
276 #if defined(FEAT_MBYTE) && !defined(FEAT_GUI)
277 (void)get_cmd_argsW(NULL
);
283 * Return TRUE if the input comes from a terminal, FALSE otherwise.
288 #ifdef FEAT_GUI_MSWIN
289 return OK
; /* GUI always has a tty */
291 if (isatty(read_cmd_fd
))
299 * mch_settitle(): set titlebar of our window
306 # ifdef FEAT_GUI_MSWIN
307 gui_mch_settitle(title
, icon
);
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
);
320 n
= SetConsoleTitleW(wp
);
322 if (n
!= 0 || GetLastError() != ERROR_CALL_NOT_IMPLEMENTED
)
327 SetConsoleTitle(title
);
334 * Restore the window/icon title.
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)
345 #ifndef FEAT_GUI_MSWIN
346 mch_settitle((which
& 1) ? g_szOrigTitle
: NULL
, NULL
);
352 * Return TRUE if we can restore the title (we can)
355 mch_can_restore_title()
362 * Return TRUE if we can restore the icon title (we can't)
365 mch_can_restore_icon()
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.
390 if (*fname
== NUL
) /* Borland behaves badly here - make it consistent */
391 nResult
= mch_dirname(buf
, len
);
396 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
398 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
399 && g_PlatformId
== VER_PLATFORM_WIN32_NT
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
);
418 vim_strncpy(buf
, cname
, len
- 1);
425 if (nResult
== FAIL
) /* fall back to non-wide function */
428 if (_fullpath(buf
, fname
, len
- 1) == NULL
)
430 /* failed, use relative path name */
431 vim_strncpy(buf
, fname
, len
- 1);
438 #ifdef USE_FNAME_CASE
439 fname_case(buf
, len
);
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] == '\\')))
461 /* A name that can't be made absolute probably isn't absolute. */
462 if (mch_FullName(fname
, szName
, _MAX_PATH
, FALSE
) == FAIL
)
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
475 * When 'shellslash' set do it the other way around.
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];
499 vim_strncpy((char_u
*)buf
, (char_u
*)name
, _MAX_PATH
);
500 p
= buf
+ strlen(buf
);
503 if (p
> buf
&& (*p
== '\\' || *p
== '/') && p
[-1] != ':')
506 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
508 /* Wide functions of Borland C 5.5 do not work on Windows 98. */
509 && g_PlatformId
== VER_PLATFORM_WIN32_NT
513 WCHAR
*wp
= enc_to_ucs2(buf
, NULL
);
518 n
= _wstat(wp
, (struct _stat
*)stp
);
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. */
528 return stat(buf
, stp
);
531 #if defined(FEAT_GUI_MSWIN) || defined(PROTO)
534 mch_settmode(int tmode
)
540 mch_get_shellsize(void)
547 mch_set_shellsize(void)
553 * Rows and/or Columns has changed.
556 mch_new_shellsize(void)
564 * We have no job control, so fake it by starting a new shell.
572 #if defined(USE_MCH_ERRMSG) || defined(PROTO)
574 #ifdef display_errors
575 # undef display_errors
579 * Display the saved error message(s).
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
)
592 (void)gui_mch_dialog(
594 gui
.starting
? VIM_INFO
:
598 gui
.starting
? (char_u
*)_("Message") :
600 (char_u
*)_("Error"),
601 p
, (char_u
*)_("&Ok"), 1, NULL
);
611 * Return TRUE if "p" contain a wildcard that can be expanded by
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
))
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
*)
642 || (*p
== '~' && p
[1] != NUL
))
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... */
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)
668 if (*path
== NUL
) /* drive name only */
672 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
674 WCHAR
*p
= enc_to_ucs2(path
, NULL
);
683 /* Retry with non-wide function (for Windows 98). */
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.
698 can_end_termcap_mode(
701 #ifdef FEAT_GUI_MSWIN
702 return TRUE
; /* GUI starts a new console anyway */
704 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
|| Columns
== 80)
707 msg(_("'columns' is not 80, cannot execute external commands"));
712 #ifdef FEAT_GUI_MSWIN
714 * return non-zero if a character is available
726 * set screen mode, always fails.
733 EMSG(_(e_screenmode
));
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.
745 typedef LPTSTR (*MYSTRPROCSTR
)(LPTSTR
);
746 typedef LPTSTR (*MYINTPROCSTR
)(int);
747 typedef int (*MYSTRPROCINT
)(LPTSTR
);
748 typedef int (*MYINTPROCINT
)(int);
750 typedef LPSTR (*MYSTRPROCSTR
)(LPSTR
);
751 typedef LPSTR (*MYINTPROCSTR
)(int);
752 typedef int (*MYSTRPROCINT
)(LPSTR
);
753 typedef int (*MYINTPROCINT
)(int);
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.
763 check_str_len(char_u
*str
)
766 MEMORY_BASIC_INFORMATION mbi
;
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
)
802 char_u
*argstring
, /* NULL when using a argint */
804 char_u
**string_result
,/* NULL when using number_result */
808 MYSTRPROCSTR ProcAdd
;
809 MYINTPROCSTR ProcAddI
;
810 char_u
*retval_str
= NULL
;
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
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
);
835 retval_str
= (ProcAdd
)(argstring
);
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
);
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
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
862 && (len
= check_str_len(retval_str
)) > 0
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
)
877 fRunTimeLinkSuccess
= 0;
881 // Free the DLL module.
882 (void)FreeLibrary(hinstLib
);
885 if (!fRunTimeLinkSuccess
)
887 EMSG2(_(e_libcall
), funcname
);
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
)
913 /* Only convert if we have a complete sequence. */
914 l
= utf_ptr2len_len(p
, todo
);
917 /* Return length of incomplete sequence. */
918 if (unconvlenp
!= NULL
)
924 *outstr
++ = utf_ptr2char(p
);
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
)
952 l
= utf_char2bytes(*p
, outstr
);
956 l
= utf_char2len(*p
);
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.
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));
980 MultiByteToWideChar(cp
, flags
, in
, inlen
, *out
, *outlen
);
986 * Call WideCharToMultiByte() and allocate memory for the result.
987 * Returns the result in "*out[*outlen]" with an extra NUL appended.
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);
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. */
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 */
1023 * Make vim the owner of the current selection. Return OK upon success.
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.
1037 * Make vim NOT the owner of the current selection.
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.
1052 crnl_to_nl(const char_u
*str
, int *size
)
1055 int str_len
= *size
;
1059 /* Avoid allocating zero bytes, it generates an error message. */
1060 ret
= lalloc((long_u
)(str_len
== 0 ? 1 : str_len
), TRUE
);
1064 for (pos
= 0; pos
< str_len
; ++pos
)
1066 if (str
[pos
] == '\r' && str
[pos
+ 1] == '\n')
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.
1092 enc_to_ucs2(char_u
*str
, int *lenp
)
1096 char_u
*allocbuf
= NULL
;
1102 len_loc
= (int)STRLEN(str
) + 1;
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
);
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
)
1121 if (conv
.vc_type
!= CONV_NONE
)
1123 str
= allocbuf
= string_convert(&conv
, str
, lenp
);
1127 convert_setup(&conv
, NULL
, NULL
);
1129 length
= utf8_to_ucs2(str
, *lenp
, NULL
, NULL
);
1130 ret
= (WCHAR
*)alloc((unsigned)((length
+ 1) * sizeof(WCHAR
)));
1133 utf8_to_ucs2(str
, *lenp
, (short_u
*)ret
, NULL
);
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.
1153 ucs2_to_enc(short_u
*str
, int *lenp
)
1156 char_u
*utf8_str
= NULL
, *enc_str
= NULL
;
1161 len_loc
= (int)wcslen(str
) + 1;
1165 if (enc_codepage
> 0)
1167 /* We can do any UCS-2 -> CP### in one pass. */
1170 WideCharToMultiByte_alloc(enc_codepage
, 0, str
, *lenp
,
1171 (LPSTR
*)&enc_str
, &length
, 0, 0);
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. */
1193 enc_str
= string_convert(&conv
, utf8_str
, lenp
);
1197 convert_setup(&conv
, NULL
, NULL
);
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*).
1216 clip_mch_request_selection(VimClipboard
*cbd
)
1218 VimClipType_t metadata
= { -1, -1, -1, -1 };
1219 HGLOBAL hMem
= NULL
;
1221 #if defined(FEAT_MBYTE) && defined(WIN3264)
1222 char_u
*to_free
= NULL
;
1225 HGLOBAL rawh
= NULL
;
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
))
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
;
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
);
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
)
1270 rawp
= (char_u
*)GlobalLock(rawh
);
1271 if (rawp
!= NULL
&& STRCMP(p_enc
, rawp
) == 0)
1273 n
= STRLEN(p_enc
) + 1;
1275 str_size
= (int)(metadata
.rawlen
- n
);
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)
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
)
1306 str_size
= metadata
.ucslen
;
1310 for (str_size
= 0; str_size
< maxlen
; ++str_size
)
1311 if (hMemWstr
[str_size
] == NUL
)
1314 to_free
= str
= ucs2_to_enc((short_u
*)hMemWstr
, &str_size
);
1315 GlobalUnlock(hMemW
);
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
)
1335 str_size
= metadata
.txtlen
;
1339 for (str_size
= 0; str_size
< maxlen
; ++str_size
)
1340 if (str
[str_size
] == NUL
)
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
)
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 */
1385 #if defined(FEAT_MBYTE) && defined(WIN3264)
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.
1397 acp_to_enc(str
, str_size
, out
, outlen
)
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
);
1417 * Send the current selection to the clipboard.
1420 clip_mch_set_selection(VimClipboard
*cbd
)
1423 VimClipType_t metadata
;
1425 HGLOBAL hMemRaw
= NULL
;
1426 HGLOBAL hMem
= NULL
;
1427 HGLOBAL hMemVim
= NULL
;
1428 # if defined(FEAT_MBYTE) && defined(WIN3264)
1429 HGLOBAL hMemW
= NULL
;
1432 /* If the '*' register isn't already filled in, fill it in now */
1434 clip_get_selection(cbd
);
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)
1441 metadata
.txtlen
= (int)txtlen
;
1442 metadata
.ucslen
= 0;
1443 metadata
.rawlen
= 0;
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. */
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
);
1463 metadata
.rawlen
= 0;
1467 # if defined(FEAT_MBYTE) && defined(WIN3264)
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
);
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
,
1484 str
= (char_u
*)alloc((unsigned)(metadata
.txtlen
== 0 ? 1
1485 : metadata
.txtlen
));
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
);
1506 metadata
.ucslen
= len
;
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
);
1519 vim_strncpy(lpszMem
, str
, metadata
.txtlen
);
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
1543 if (OpenClipboard(NULL
))
1545 if (EmptyClipboard())
1547 SetClipboardData(cbd
->format
, hMemVim
);
1549 # if defined(FEAT_MBYTE) && defined(WIN3264)
1552 if (SetClipboardData(CF_UNICODETEXT
, hMemW
) != NULL
)
1556 /* Always use CF_TEXT. On Win98 Notepad won't obtain the
1557 * CF_UNICODETEXT text, only CF_TEXT. */
1558 SetClipboardData(CF_TEXT
, hMem
);
1565 /* Free any allocations we didn't give to the clipboard: */
1567 GlobalFree(hMemRaw
);
1570 # if defined(FEAT_MBYTE) && defined(WIN3264)
1575 GlobalFree(hMemVim
);
1578 #endif /* FEAT_CLIPBOARD */
1582 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
1589 # ifdef MCH_WRITE_DUMP
1593 if (psz
[strlen(psz
) - 1] != '\n')
1594 fputc('\n', fdDump
);
1610 va_start(args
, pszFormat
);
1611 vsprintf(szBuff
, pszFormat
, args
);
1614 OutputDebugString(szBuff
);
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. */
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.
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. */
1641 # if defined(FEAT_TITLE) && defined(WIN3264)
1642 /* Window handle may have been found by init code (Windows NT only) */
1650 GetConsoleTitle(pszOldWindowTitle
, MY_BUFSIZE
);
1652 wsprintf(pszNewWindowTitle
, "%s/%d/%d",
1655 GetCurrentProcessId());
1656 SetConsoleTitle(pszNewWindowTitle
);
1658 s_hwnd
= FindWindow(NULL
, pszNewWindowTitle
);
1660 SetConsoleTitle(pszOldWindowTitle
);
1664 * Console implementation of ":winpos".
1667 mch_get_winpos(int *x
, int *y
)
1672 GetWindowRect(s_hwnd
, &rect
);
1679 * Console implementation of ":winpos x y".
1682 mch_set_winpos(int x
, int y
)
1685 SetWindowPos(s_hwnd
, NULL
, x
, y
, 0, 0,
1686 SWP_NOZORDER
| SWP_NOSIZE
| SWP_NOACTIVATE
);
1690 #if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
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
1723 swap_me(COLORREF colorref
)
1726 char *ptr
= (char *)&colorref
;
1729 *(ptr
) = *(ptr
+ 2);
1735 static BOOL CALLBACK
1736 PrintDlgProc(HWND hDlg
, UINT message
, WPARAM wParam
, LPARAM lParam
)
1739 NONCLIENTMETRICS nm
;
1747 nm
.cbSize
= sizeof(NONCLIENTMETRICS
);
1748 if (SystemParametersInfo(
1749 SPI_GETNONCLIENTMETRICS
,
1750 sizeof(NONCLIENTMETRICS
),
1754 char buff
[MAX_PATH
];
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
));
1771 SetWindowText(hDlg
, szAppName
);
1772 if (prt_name
!= NULL
)
1774 SetDlgItemText(hDlg
, IDC_PRINTTEXT2
, (LPSTR
)prt_name
);
1778 EnableMenuItem(GetSystemMenu(hDlg
, FALSE
), SC_CLOSE
, MF_GRAYED
);
1780 BringWindowToTop(s_hwnd
);
1786 EnableWindow(GetParent(hDlg
), TRUE
);
1787 DestroyWindow(hDlg
);
1790 DeleteObject(hfont
);
1798 static BOOL CALLBACK
1799 AbortProc(HDC hdcPrn
, int iCode
)
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
;
1816 static UINT CALLBACK
1818 HWND hDlg
, // handle to dialog box
1819 UINT uiMsg
, // message identifier
1820 WPARAM wParam
, // message parameter
1821 LPARAM lParam
// message parameter
1825 RECT rc
, rcDlg
, rcOwner
;
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.
1852 rcOwner
.left
+ (rc
.right
/ 2),
1853 rcOwner
.top
+ (rc
.bottom
/ 2),
1854 0, 0, // ignores size arguments
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
);
1871 mch_print_cleanup(void)
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
);
1885 SendMessage(hDlgPrint
, WM_COMMAND
, 0, 0);
1889 to_device_units(int idx
, int dpi
, int physsize
, int offset
, int def_number
)
1895 u
= prt_get_unit(idx
);
1896 if (u
== PRT_UNIT_NONE
)
1902 nr
= printer_opts
[idx
].number
;
1907 ret
= (physsize
* nr
) / 100;
1913 ret
= (nr
* 10 * dpi
) / 254;
1915 case PRT_UNIT_POINT
:
1916 ret
= (nr
* 10 * dpi
) / 720;
1923 return ret
- offset
;
1938 GetTextMetrics(prt_dlg
.hDC
, &prt_tm
);
1939 prt_line_height
= prt_tm
.tmHeight
+ prt_tm
.tmExternalLeading
;
1941 hr
= GetDeviceCaps(prt_dlg
.hDC
, HORZRES
);
1943 Escape(prt_dlg
.hDC
, GETPHYSPAGESIZE
, NULL
, NULL
, &pagesize
);
1945 Escape(prt_dlg
.hDC
, GETPRINTINGOFFSET
, NULL
, NULL
, &pagesize
);
1948 phyw
= GetDeviceCaps(prt_dlg
.hDC
, PHYSICALWIDTH
);
1949 dvoff
= GetDeviceCaps(prt_dlg
.hDC
, PHYSICALOFFSETX
);
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
;
1962 prt_number_width
= 0;
1964 prt_right_margin
= hr
- to_device_units(OPT_PRINT_RIGHT
, dpi
, phyw
,
1967 return (prt_right_margin
- prt_left_margin
) / prt_tm
.tmAveCharWidth
;
1983 vr
= GetDeviceCaps(prt_dlg
.hDC
, VERTRES
);
1985 Escape(prt_dlg
.hDC
, GETPHYSPAGESIZE
, NULL
, NULL
, &pagesize
);
1987 Escape(prt_dlg
.hDC
, GETPRINTINGOFFSET
, NULL
, NULL
, &pagesize
);
1990 phyw
= GetDeviceCaps(prt_dlg
.hDC
, PHYSICALHEIGHT
);
1991 dvoff
= GetDeviceCaps(prt_dlg
.hDC
, PHYSICALOFFSETY
);
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
,
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;
2025 bUserAbort
= &(psettings
->user_abort
);
2026 memset(&prt_dlg
, 0, sizeof(PRINTDLG
));
2027 prt_dlg
.lStructSize
= sizeof(PRINTDLG
);
2029 GetConsoleHwnd(); /* get value of s_hwnd */
2031 prt_dlg
.hwndOwner
= s_hwnd
;
2032 prt_dlg
.Flags
= PD_NOPAGENUMS
| PD_NOSELECTION
| PD_RETURNDC
;
2035 prt_dlg
.hDevMode
= stored_dm
;
2036 prt_dlg
.hDevNames
= stored_devn
;
2037 prt_dlg
.lCustData
= stored_nCopies
; // work around bug in print dialog
2040 * Use hook to prevent console window being sent to back
2042 prt_dlg
.lpfnPrintHook
= PrintHookProc
;
2043 prt_dlg
.Flags
|= PD_ENABLEPRINTHOOK
;
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
2058 prt_dlg
.Flags
|= PD_RETURNDEFAULT
;
2061 * MSDN suggests setting the first parameter to WINSPOOL for
2062 * NT, but NULL appears to work just as well.
2065 prt_dlg
.hDC
= CreateDC(NULL
, p_pdev
, NULL
, NULL
);
2069 prt_dlg
.Flags
|= PD_RETURNDEFAULT
;
2070 if (PrintDlg(&prt_dlg
) == 0)
2074 else if (PrintDlg(&prt_dlg
) == 0)
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();
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
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
2110 mem
= (DEVMODE
*)GlobalLock(prt_dlg
.hDevMode
);
2114 if (mem
->dmCopies
!= 1)
2115 stored_nCopies
= mem
->dmCopies
;
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
);
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
)
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();
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
;
2185 DWORD err
= CommDlgExtendedError();
2192 sprintf(buf
, "%ld", err
);
2193 EMSG2(_("E238: Print error: %s"), 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
));
2209 msg_clr_eos(); /* Maybe canceled */
2211 mch_print_cleanup();
2218 mch_print_begin(prt_settings_T
*psettings
)
2224 hDlgPrint
= CreateDialog(GetModuleHandle(NULL
), TEXT("PrintDlgBox"),
2225 prt_dlg
.hwndOwner
, PrintDlgProc
);
2227 Escape(prt_dlg
.hDC
, SETABORTPROC
, 0, (LPSTR
)AbortProc
, NULL
);
2229 SetAbortProc(prt_dlg
.hDC
, AbortProc
);
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
);
2240 /* Give focus back to main window (when using MDI). */
2249 mch_print_end(prt_settings_T
*psettings
)
2251 EndDoc(prt_dlg
.hDC
);
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
)
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;
2280 mch_print_start_line(margin
, page_line
)
2285 prt_pos_x
= -prt_number_width
;
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
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
);
2307 GetTextExtentPoint(prt_dlg
.hDC
, p
, len
, &sz
);
2309 GetTextExtentPoint32(prt_dlg
.hDC
, p
, len
, &sz
);
2311 prt_pos_x
+= (sz
.cx
- prt_tm
.tmOverhang
);
2312 /* This is wrong when printing spaces for a TAB. */
2316 GetTextExtentPoint(prt_dlg
.hDC
, p
+ len
, 1, &sz
);
2318 GetTextExtentPoint32(prt_dlg
.hDC
, p
+ len
, 1, &sz
);
2320 return (prt_pos_x
+ prt_left_margin
+ sz
.cx
> prt_right_margin
);
2325 mch_print_set_font(int iBold
, int iItalic
, int iUnderline
)
2327 SelectObject(prt_dlg
.hDC
, prt_font_handles
[iBold
][iItalic
][iUnderline
]);
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
);
2342 SetBkMode(prt_dlg
.hDC
, OPAQUE
);
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.
2365 mch_resolve_shortcut(char_u
*fname
)
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
;
2376 /* Check if the file name ends in ".lnk". Avoid calling
2377 * CoCreateInstance(), it's quite slow. */
2380 len
= (int)STRLEN(fname
);
2381 if (len
<= 4 || STRNICMP(fname
+ len
- 4, ".lnk", 4) != 0)
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
);
2391 goto shortcut_error
;
2393 // Get a pointer to the IPersistFile interface.
2394 hr
= psl
->lpVtbl
->QueryInterface(
2395 psl
, &IID_IPersistFile
, (void**)&ppf
);
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
);
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
);
2409 goto shortcut_error
;
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
);
2419 // Release all interface pointers (both belong to the same object)
2421 ppf
->lpVtbl
->Release(ppf
);
2423 psl
->lpVtbl
->Release(psl
);
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.
2435 win32_set_foreground()
2438 GetConsoleHwnd(); /* get value of s_hwnd */
2441 SetForegroundWindow(s_hwnd
);
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. */
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.
2488 serverSendEnc(HWND target
)
2490 COPYDATASTRUCT data
;
2492 data
.dwData
= COPYDATA_ENCODING
;
2494 data
.cbData
= (DWORD
)STRLEN(p_enc
) + 1;
2495 data
.lpData
= p_enc
;
2497 data
.cbData
= STRLEN("latin1") + 1;
2498 data
.lpData
= "latin1";
2500 (void)SendMessage(target
, WM_COPYDATA
, (WPARAM
)message_window
,
2505 * Clean up on exit. This destroys the hidden message window.
2511 CleanUpMessaging(void)
2513 if (message_window
!= 0)
2515 DestroyWindow(message_window
);
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.
2543 * A key sequence. We are a server, and a client wants these keys
2544 * adding to the input queue.
2546 * A reply. We are a client, and a server has sent this message
2547 * in response to a request. (server2client())
2549 * An expression. We are a server, and a client wants us to
2550 * evaluate this expression.
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
;
2567 switch (data
->dwData
)
2569 case COPYDATA_ENCODING
:
2571 /* Remember the encoding that the client uses. */
2572 vim_free(client_enc
);
2573 client_enc
= enc_canonize((char_u
*)data
->lpData
);
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
);
2588 /* Wake up the main GUI loop. */
2590 PostMessage(s_hwnd
, WM_NULL
, 0, 0);
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
);
2604 res
= vim_strsave(_(e_invexprmsg
));
2605 reply
.dwData
= COPYDATA_ERROR_RESULT
;
2608 reply
.dwData
= COPYDATA_RESULT
;
2610 reply
.cbData
= (DWORD
)STRLEN(res
) + 1;
2612 serverSendEnc(sender
);
2613 retval
= (int)SendMessage(sender
, WM_COPYDATA
, (WPARAM
)message_window
,
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
,
2626 str
= vim_strsave(str
);
2627 if (save_reply(sender
, str
,
2628 (data
->dwData
== COPYDATA_REPLY
? 0 :
2629 (data
->dwData
== COPYDATA_RESULT
? 1 :
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
,
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. */
2652 GetConsoleHwnd(); /* get value of s_hwnd */
2656 SetForegroundWindow(s_hwnd
);
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.
2669 serverInitMessaging(void)
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);
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
,
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.
2712 getVimServerName(HWND hwnd
, char *name
, int namelen
)
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)
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)
2736 /* If this is the server we're looking for, return its HWND */
2737 if (STRICMP(server
, id
->name
) == 0)
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 */
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)
2766 /* Add the name to the list */
2767 ga_concat(ga
, server
);
2768 ga_concat(ga
, "\n");
2773 findServer(char_u
*name
)
2775 struct server_id id
;
2780 EnumWindows(enumWindowsGetServer
, (LPARAM
)(&id
));
2786 serverSetName(char_u
*name
)
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
);
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
);
2813 sprintf((char *)p
, "%d", i
);
2820 /* Remember the name */
2821 serverName
= ok_name
;
2823 need_maketitle
= TRUE
; /* update Vim window title later */
2826 /* Update the message window title */
2827 SetWindowText(message_window
, ok_name
);
2830 /* Set the servername variable */
2831 set_vim_var_string(VV_SEND_SERVER
, serverName
, -1);
2837 serverGetVimNames(void)
2841 ga_init2(&ga
, 1, 100);
2843 EnumWindows(enumWindowsGetNames
, (LPARAM
)(&ga
));
2844 ga_append(&ga
, NUL
);
2850 serverSendReply(name
, reply
)
2851 char_u
*name
; /* Where to send. */
2852 char_u
*reply
; /* What to send. */
2855 COPYDATASTRUCT data
;
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
);
2867 if (!IsWindow(target
))
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
,
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 */
2892 COPYDATASTRUCT data
;
2893 char_u
*retval
= NULL
;
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
);
2911 EMSG2(_(e_noserver
), name
);
2916 *(HWND
*)ptarget
= target
;
2918 data
.dwData
= asExpr
? COPYDATA_EXPR
: COPYDATA_KEYS
;
2919 data
.cbData
= (DWORD
)STRLEN(cmd
) + 1;
2922 serverSendEnc(target
);
2923 if (SendMessage(target
, WM_COPYDATA
, (WPARAM
)message_window
,
2924 (LPARAM
)(&data
)) == 0)
2928 retval
= serverGetReply(target
, &retcode
, TRUE
, TRUE
);
2933 *result
= retval
; /* Caller assumes responsibility for freeing */
2939 * Bring the server to the foreground.
2942 serverForeground(name
)
2945 HWND target
= findServer(name
);
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.
2961 HWND server
; /* server window */
2962 char_u
*reply
; /* reply string */
2963 int expr_result
; /* 0 for REPLY, 1 for RESULT 2 for error */
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).
2978 save_reply(HWND server
, char_u
*reply
, int expr
)
2982 if (ga_grow(&reply_list
, 1) == FAIL
)
2985 rep
= REPLY_ITEM(REPLY_COUNT
);
2986 rep
->server
= server
;
2988 rep
->expr_result
= expr
;
2989 if (rep
->reply
== NULL
)
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).
3006 serverGetReply(HWND server
, int *expr_res
, int remove
, int wait
)
3012 /* When waiting, loop until the message waiting for is received. */
3015 /* Reset this here, in case a message arrives while we are going
3016 * through the already received messages. */
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 */
3027 if (expr_res
!= NULL
)
3028 *expr_res
= rep
->expr_result
== 1 ? 0 : -1;
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
));
3038 /* Return the reply to the caller, who takes on responsibility
3039 * for freeing it if "remove" is TRUE. */
3044 /* If we got here, we didn't find a reply. Return immediately if the
3045 * "wait" parameter isn't set. */
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
))
3064 serverProcessPendingMessages();
3072 * Process any messages in the Windows message queue.
3075 serverProcessPendingMessages(void)
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)) \
3097 static struct charset_pair
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
},
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
},
3128 * Convert a charset ID to a name.
3129 * Return NULL when not recognized.
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
)
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.
3164 points_to_pixels(char_u
*str
, char_u
**end
, int vertical
, long_i pprinter_dc
)
3169 HWND hwnd
= (HWND
)0;
3171 HDC printer_dc
= (HDC
)pprinter_dc
;
3175 if (*str
== '.' && divisor
== 0)
3177 /* Start keeping a divisor, for later */
3182 if (!VIM_ISDIGIT(*str
))
3186 points
+= *str
- '0';
3195 if (printer_dc
== NULL
)
3197 hwnd
= GetDesktopWindow();
3198 hdc
= GetWindowDC(hwnd
);
3203 pixels
= MulDiv(points
,
3204 GetDeviceCaps(hdc
, vertical
? LOGPIXELSY
: LOGPIXELSX
),
3207 if (printer_dc
== NULL
)
3208 ReleaseDC(hwnd
, hdc
);
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)
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
)
3250 /* Continue the scan - we have a non-ANSI font */
3255 init_logfont(LOGFONT
*lf
)
3258 HWND hwnd
= GetDesktopWindow();
3259 HDC hdc
= GetWindowDC(hwnd
);
3261 n
= EnumFontFamilies(hdc
,
3262 (LPCSTR
)lf
->lfFaceName
,
3263 (FONTENUMPROC
)font_enumproc
,
3266 ReleaseDC(hwnd
, hdc
);
3268 /* If we couldn't find a useable font, return failure */
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
3276 lf
->lfHeight
= current_font_height
;
3278 lf
->lfItalic
= FALSE
;
3279 lf
->lfUnderline
= FALSE
;
3280 lf
->lfStrikeOut
= FALSE
;
3281 lf
->lfWeight
= FW_NORMAL
;
3283 /* Return success */
3288 * Get font info from "name" into logfont "lf".
3289 * Return OK for a valid name, FAIL otherwise.
3300 static LOGFONT
*lastlf
= NULL
;
3306 if (STRCMP(name
, "*") == 0)
3308 #if defined(FEAT_GUI_W32)
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
;
3318 cf
.nFontType
= 0 ; //REGULAR_FONTTYPE;
3319 if (ChooseFont(&cf
))
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
;
3336 lf
->lfFaceName
[p
- name
] = NUL
;
3338 /* First set defaults */
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
] = ' ';
3359 if (!did_replace
|| init_logfont(lf
) == FAIL
)
3366 /* Set the values found after ':' */
3372 lf
->lfHeight
= - points_to_pixels(p
, &p
, TRUE
, (long_i
)printer_dc
);
3375 lf
->lfWidth
= points_to_pixels(p
, &p
, FALSE
, (long_i
)printer_dc
);
3378 #ifndef MSWIN16_FASTTEXT
3379 lf
->lfWeight
= FW_BOLD
;
3383 #ifndef MSWIN16_FASTTEXT
3384 lf
->lfItalic
= TRUE
;
3388 lf
->lfUnderline
= TRUE
;
3391 lf
->lfStrikeOut
= TRUE
;
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
);
3404 if (cp
->name
== NULL
&& verbose
)
3406 vim_snprintf((char *)IObuff
, IOSIZE
,
3407 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p
, name
);
3416 vim_snprintf((char *)IObuff
, IOSIZE
,
3417 _("E245: Illegal char '%c' in font name \"%s\""),
3427 #if defined(FEAT_GUI_W32)
3430 /* ron: init lastlf */
3431 if (printer_dc
== NULL
)
3434 lastlf
= (LOGFONT
*)alloc(sizeof(LOGFONT
));
3436 mch_memmove(lastlf
, lf
, sizeof(LOGFONT
));
3442 #endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */