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
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_ucs2(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_ucs2(fname
, NULL
);
408 if (wname
!= NULL
&& _wfullpath(wbuf
, wname
, MAX_PATH
- 1) != NULL
)
410 cname
= ucs2_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_ucs2(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
);
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... */
654 if (isalpha(path
[0]) && path
[1] == ':') /* has a drive name */
656 /* If we can change to the drive, skip that part of the path. If we
657 * can't then the current directory may be invalid, try using chdir()
658 * with the whole path. */
659 if (_chdrive(TOLOWER_ASC(path
[0]) - 'a' + 1) == 0)
663 if (*path
== NUL
) /* drive name only */
667 if (enc_codepage
>= 0 && (int)GetACP() != enc_codepage
)
669 WCHAR
*p
= enc_to_ucs2(path
, NULL
);
678 /* Retry with non-wide function (for Windows 98). */
683 return chdir(path
); /* let the normal chdir() do the rest */
688 * Switching off termcap mode is only allowed when Columns is 80, otherwise a
689 * crash may result. It's always allowed on NT or when running the GUI.
693 can_end_termcap_mode(
696 #ifdef FEAT_GUI_MSWIN
697 return TRUE
; /* GUI starts a new console anyway */
699 if (g_PlatformId
== VER_PLATFORM_WIN32_NT
|| Columns
== 80)
702 msg(_("'columns' is not 80, cannot execute external commands"));
707 #ifdef FEAT_GUI_MSWIN
709 * return non-zero if a character is available
721 * set screen mode, always fails.
728 EMSG(_(e_screenmode
));
733 #if defined(FEAT_LIBCALL) || defined(PROTO)
735 * Call a DLL routine which takes either a string or int param
736 * and returns an allocated string.
737 * Return OK if it worked, FAIL if not.
740 typedef LPTSTR (*MYSTRPROCSTR
)(LPTSTR
);
741 typedef LPTSTR (*MYINTPROCSTR
)(int);
742 typedef int (*MYSTRPROCINT
)(LPTSTR
);
743 typedef int (*MYINTPROCINT
)(int);
745 typedef LPSTR (*MYSTRPROCSTR
)(LPSTR
);
746 typedef LPSTR (*MYINTPROCSTR
)(int);
747 typedef int (*MYSTRPROCINT
)(LPSTR
);
748 typedef int (*MYINTPROCINT
)(int);
753 * Check if a pointer points to a valid NUL terminated string.
754 * Return the length of the string, including terminating NUL.
755 * Returns 0 for an invalid pointer, 1 for an empty string.
758 check_str_len(char_u
*str
)
761 MEMORY_BASIC_INFORMATION mbi
;
769 /* get memory information */
770 if (VirtualQuery(str
, &mbi
, sizeof(mbi
)))
772 /* pre cast these (typing savers) */
773 DWORD dwStr
= (DWORD
)str
;
774 DWORD dwBaseAddress
= (DWORD
)mbi
.BaseAddress
;
776 /* get start address of page that str is on */
777 DWORD strPage
= dwStr
- (dwStr
- dwBaseAddress
) % si
.dwPageSize
;
779 /* get length from str to end of page */
780 DWORD pageLength
= si
.dwPageSize
- (dwStr
- strPage
);
782 for (p
= str
; !IsBadReadPtr(p
, pageLength
);
783 p
+= pageLength
, pageLength
= si
.dwPageSize
)
784 for (i
= 0; i
< pageLength
; ++i
, ++length
)
797 char_u
*argstring
, /* NULL when using a argint */
799 char_u
**string_result
,/* NULL when using number_result */
803 MYSTRPROCSTR ProcAdd
;
804 MYINTPROCSTR ProcAddI
;
805 char_u
*retval_str
= NULL
;
809 BOOL fRunTimeLinkSuccess
= FALSE
;
811 // Get a handle to the DLL module.
812 hinstLib
= LoadLibrary(libname
);
814 // If the handle is valid, try to get the function address.
815 if (hinstLib
!= NULL
)
817 #ifdef HAVE_TRY_EXCEPT
821 if (argstring
!= NULL
)
823 /* Call with string argument */
824 ProcAdd
= (MYSTRPROCSTR
) GetProcAddress(hinstLib
, funcname
);
825 if ((fRunTimeLinkSuccess
= (ProcAdd
!= NULL
)) != 0)
827 if (string_result
== NULL
)
828 retval_int
= ((MYSTRPROCINT
)ProcAdd
)(argstring
);
830 retval_str
= (ProcAdd
)(argstring
);
835 /* Call with number argument */
836 ProcAddI
= (MYINTPROCSTR
) GetProcAddress(hinstLib
, funcname
);
837 if ((fRunTimeLinkSuccess
= (ProcAddI
!= NULL
)) != 0)
839 if (string_result
== NULL
)
840 retval_int
= ((MYINTPROCINT
)ProcAddI
)(argint
);
842 retval_str
= (ProcAddI
)(argint
);
846 // Save the string before we free the library.
847 // Assume that a "1" result is an illegal pointer.
848 if (string_result
== NULL
)
849 *number_result
= retval_int
;
850 else if (retval_str
!= NULL
852 && retval_str
!= (char_u
*)1
853 && retval_str
!= (char_u
*)-1
854 && !IsBadStringPtr(retval_str
, INT_MAX
)
855 && (len
= strlen(retval_str
) + 1) > 0
857 && (len
= check_str_len(retval_str
)) > 0
861 *string_result
= lalloc((long_u
)len
, TRUE
);
862 if (*string_result
!= NULL
)
863 mch_memmove(*string_result
, retval_str
, len
);
866 #ifdef HAVE_TRY_EXCEPT
868 __except(EXCEPTION_EXECUTE_HANDLER
)
870 if (GetExceptionCode() == EXCEPTION_STACK_OVERFLOW
)
872 fRunTimeLinkSuccess
= 0;
876 // Free the DLL module.
877 (void)FreeLibrary(hinstLib
);
880 if (!fRunTimeLinkSuccess
)
882 EMSG2(_(e_libcall
), funcname
);
890 #if defined(FEAT_MBYTE) || defined(PROTO)
892 * Convert an UTF-8 string to UCS-2.
893 * "instr[inlen]" is the input. "inlen" is in bytes.
894 * When "outstr" is NULL only return the number of UCS-2 words produced.
895 * Otherwise "outstr" must be a buffer of sufficient size.
896 * Returns the number of UCS-2 words produced.
899 utf8_to_ucs2(char_u
*instr
, int inlen
, short_u
*outstr
, int *unconvlenp
)
908 /* Only convert if we have a complete sequence. */
909 l
= utf_ptr2len_len(p
, todo
);
912 /* Return length of incomplete sequence. */
913 if (unconvlenp
!= NULL
)
919 *outstr
++ = utf_ptr2char(p
);
929 * Convert an UCS-2 string to UTF-8.
930 * The input is "instr[inlen]" with "inlen" in number of ucs-2 words.
931 * When "outstr" is NULL only return the required number of bytes.
932 * Otherwise "outstr" must be a buffer of sufficient size.
933 * Return the number of bytes produced.
936 ucs2_to_utf8(short_u
*instr
, int inlen
, char_u
*outstr
)
947 l
= utf_char2bytes(*p
, outstr
);
951 l
= utf_char2len(*p
);
961 * Call MultiByteToWideChar() and allocate memory for the result.
962 * Returns the result in "*out[*outlen]" with an extra zero appended.
963 * "outlen" is in words.
966 MultiByteToWideChar_alloc(UINT cp
, DWORD flags
,
967 LPCSTR in
, int inlen
,
968 LPWSTR
*out
, int *outlen
)
970 *outlen
= MultiByteToWideChar(cp
, flags
, in
, inlen
, 0, 0);
971 /* Add one one word to avoid a zero-length alloc(). */
972 *out
= (LPWSTR
)alloc(sizeof(WCHAR
) * (*outlen
+ 1));
975 MultiByteToWideChar(cp
, flags
, in
, inlen
, *out
, *outlen
);
981 * Call WideCharToMultiByte() and allocate memory for the result.
982 * Returns the result in "*out[*outlen]" with an extra NUL appended.
985 WideCharToMultiByte_alloc(UINT cp
, DWORD flags
,
986 LPCWSTR in
, int inlen
,
987 LPSTR
*out
, int *outlen
,
988 LPCSTR def
, LPBOOL useddef
)
990 *outlen
= WideCharToMultiByte(cp
, flags
, in
, inlen
, NULL
, 0, def
, useddef
);
991 /* Add one one byte to avoid a zero-length alloc(). */
992 *out
= alloc((unsigned)*outlen
+ 1);
995 WideCharToMultiByte(cp
, flags
, in
, inlen
, *out
, *outlen
, def
, useddef
);
1000 #endif /* FEAT_MBYTE */
1002 #ifdef FEAT_CLIPBOARD
1004 * Clipboard stuff, for cutting and pasting text to other windows.
1007 /* Type used for the clipboard type of Vim's data. */
1010 int type
; /* MCHAR, MBLOCK or MLINE */
1011 int txtlen
; /* length of CF_TEXT in bytes */
1012 int ucslen
; /* length of CF_UNICODETEXT in words */
1013 int rawlen
; /* length of clip_star.format_raw, including encoding,
1014 excluding terminating NUL */
1018 * Make vim the owner of the current selection. Return OK upon success.
1022 clip_mch_own_selection(VimClipboard
*cbd
)
1025 * Never actually own the clipboard. If another application sets the
1026 * clipboard, we don't want to think that we still own it.
1032 * Make vim NOT the owner of the current selection.
1036 clip_mch_lose_selection(VimClipboard
*cbd
)
1038 /* Nothing needs to be done here */
1042 * Copy "str[*size]" into allocated memory, changing CR-NL to NL.
1043 * Return the allocated result and the size in "*size".
1044 * Returns NULL when out of memory.
1047 crnl_to_nl(const char_u
*str
, int *size
)
1050 int str_len
= *size
;
1054 /* Avoid allocating zero bytes, it generates an error message. */
1055 ret
= lalloc((long_u
)(str_len
== 0 ? 1 : str_len
), TRUE
);
1059 for (pos
= 0; pos
< str_len
; ++pos
)
1061 if (str
[pos
] == '\r' && str
[pos
+ 1] == '\n')
1073 #if defined(FEAT_MBYTE) || defined(PROTO)
1075 * Note: the following two functions are only guaranteed to work when using
1076 * valid MS-Windows codepages or when iconv() is available.
1080 * Convert "str" from 'encoding' to UCS-2.
1081 * Input in "str" with length "*lenp". When "lenp" is NULL, use strlen().
1082 * Output is returned as an allocated string. "*lenp" is set to the length of
1083 * the result. A trailing NUL is always added.
1084 * Returns NULL when out of memory.
1087 enc_to_ucs2(char_u
*str
, int *lenp
)
1091 char_u
*allocbuf
= NULL
;
1097 len_loc
= (int)STRLEN(str
) + 1;
1101 if (enc_codepage
> 0)
1103 /* We can do any CP### -> UCS-2 in one pass, and we can do it
1104 * without iconv() (convert_* may need iconv). */
1105 MultiByteToWideChar_alloc(enc_codepage
, 0, str
, *lenp
, &ret
, &length
);
1109 /* Use "latin1" by default, we might be called before we have p_enc
1110 * set up. Convert to utf-8 first, works better with iconv(). Does
1111 * nothing if 'encoding' is "utf-8". */
1112 conv
.vc_type
= CONV_NONE
;
1113 if (convert_setup(&conv
, p_enc
? p_enc
: (char_u
*)"latin1",
1114 (char_u
*)"utf-8") == FAIL
)
1116 if (conv
.vc_type
!= CONV_NONE
)
1118 str
= allocbuf
= string_convert(&conv
, str
, lenp
);
1122 convert_setup(&conv
, NULL
, NULL
);
1124 length
= utf8_to_ucs2(str
, *lenp
, NULL
, NULL
);
1125 ret
= (WCHAR
*)alloc((unsigned)((length
+ 1) * sizeof(WCHAR
)));
1128 utf8_to_ucs2(str
, *lenp
, (short_u
*)ret
, NULL
);
1136 return (short_u
*)ret
;
1140 * Convert an UCS-2 string to 'encoding'.
1141 * Input in "str" with length (counted in wide characters) "*lenp". When
1142 * "lenp" is NULL, use wcslen().
1143 * Output is returned as an allocated string. If "*lenp" is not NULL it is
1144 * set to the length of the result.
1145 * Returns NULL when out of memory.
1148 ucs2_to_enc(short_u
*str
, int *lenp
)
1151 char_u
*utf8_str
= NULL
, *enc_str
= NULL
;
1156 len_loc
= (int)wcslen(str
) + 1;
1160 if (enc_codepage
> 0)
1162 /* We can do any UCS-2 -> CP### in one pass. */
1165 WideCharToMultiByte_alloc(enc_codepage
, 0, str
, *lenp
,
1166 (LPSTR
*)&enc_str
, &length
, 0, 0);
1171 /* Avoid allocating zero bytes, it generates an error message. */
1172 utf8_str
= alloc(ucs2_to_utf8(str
, *lenp
== 0 ? 1 : *lenp
, NULL
));
1173 if (utf8_str
!= NULL
)
1175 *lenp
= ucs2_to_utf8(str
, *lenp
, utf8_str
);
1177 /* We might be called before we have p_enc set up. */
1178 conv
.vc_type
= CONV_NONE
;
1179 convert_setup(&conv
, (char_u
*)"utf-8",
1180 p_enc
? p_enc
: (char_u
*)"latin1");
1181 if (conv
.vc_type
== CONV_NONE
)
1183 /* p_enc is utf-8, so we're done. */
1188 enc_str
= string_convert(&conv
, utf8_str
, lenp
);
1192 convert_setup(&conv
, NULL
, NULL
);
1197 #endif /* FEAT_MBYTE */
1200 * Get the current selection and put it in the clipboard register.
1202 * NOTE: Must use GlobalLock/Unlock here to ensure Win32s compatibility.
1203 * On NT/W95 the clipboard data is a fixed global memory object and
1204 * so its handle = its pointer.
1205 * On Win32s, however, co-operation with the Win16 system means that
1206 * the clipboard data is moveable and its handle is not a pointer at all,
1207 * so we can't just cast the return value of GetClipboardData to (char_u*).
1211 clip_mch_request_selection(VimClipboard
*cbd
)
1213 VimClipType_t metadata
= { -1, -1, -1, -1 };
1214 HGLOBAL hMem
= NULL
;
1216 #if defined(FEAT_MBYTE) && defined(WIN3264)
1217 char_u
*to_free
= NULL
;
1220 HGLOBAL rawh
= NULL
;
1227 * Don't pass GetActiveWindow() as an argument to OpenClipboard() because
1228 * then we can't paste back into the same window for some reason - webb.
1230 if (!OpenClipboard(NULL
))
1233 /* Check for vim's own clipboard format first. This only gets the type of
1234 * the data, still need to use CF_UNICODETEXT or CF_TEXT for the text. */
1235 if (IsClipboardFormatAvailable(cbd
->format
))
1237 VimClipType_t
*meta_p
;
1240 /* We have metadata on the clipboard; try to get it. */
1241 if ((meta_h
= GetClipboardData(cbd
->format
)) != NULL
1242 && (meta_p
= (VimClipType_t
*)GlobalLock(meta_h
)) != NULL
)
1244 /* The size of "VimClipType_t" changed, "rawlen" was added later.
1245 * Only copy what is available for backwards compatibility. */
1246 n
= sizeof(VimClipType_t
);
1247 if (GlobalSize(meta_h
) < n
)
1248 n
= GlobalSize(meta_h
);
1249 memcpy(&metadata
, meta_p
, n
);
1250 GlobalUnlock(meta_h
);
1255 /* Check for Vim's raw clipboard format first. This is used without
1256 * conversion, but only if 'encoding' matches. */
1257 if (IsClipboardFormatAvailable(cbd
->format_raw
)
1258 && metadata
.rawlen
> (int)STRLEN(p_enc
))
1260 /* We have raw data on the clipboard; try to get it. */
1261 if ((rawh
= GetClipboardData(cbd
->format_raw
)) != NULL
)
1265 rawp
= (char_u
*)GlobalLock(rawh
);
1266 if (rawp
!= NULL
&& STRCMP(p_enc
, rawp
) == 0)
1268 n
= STRLEN(p_enc
) + 1;
1270 str_size
= (int)(metadata
.rawlen
- n
);
1283 #if defined(FEAT_MBYTE) && defined(WIN3264)
1284 /* Try to get the clipboard in Unicode if it's not an empty string. */
1285 if (IsClipboardFormatAvailable(CF_UNICODETEXT
) && metadata
.ucslen
!= 0)
1289 if ((hMemW
= GetClipboardData(CF_UNICODETEXT
)) != NULL
)
1291 WCHAR
*hMemWstr
= (WCHAR
*)GlobalLock(hMemW
);
1293 /* Use the length of our metadata if possible, but limit it to the
1294 * GlobalSize() for safety. */
1295 maxlen
= (int)(GlobalSize(hMemW
) / sizeof(WCHAR
));
1296 if (metadata
.ucslen
>= 0)
1298 if (metadata
.ucslen
> maxlen
)
1301 str_size
= metadata
.ucslen
;
1305 for (str_size
= 0; str_size
< maxlen
; ++str_size
)
1306 if (hMemWstr
[str_size
] == NUL
)
1309 to_free
= str
= ucs2_to_enc((short_u
*)hMemWstr
, &str_size
);
1310 GlobalUnlock(hMemW
);
1315 /* Get the clipboard in the Active codepage. */
1316 if (IsClipboardFormatAvailable(CF_TEXT
))
1318 if ((hMem
= GetClipboardData(CF_TEXT
)) != NULL
)
1320 str
= (char_u
*)GlobalLock(hMem
);
1322 /* The length is either what our metadata says or the strlen().
1323 * But limit it to the GlobalSize() for safety. */
1324 maxlen
= (int)GlobalSize(hMem
);
1325 if (metadata
.txtlen
>= 0)
1327 if (metadata
.txtlen
> maxlen
)
1330 str_size
= metadata
.txtlen
;
1334 for (str_size
= 0; str_size
< maxlen
; ++str_size
)
1335 if (str
[str_size
] == NUL
)
1339 # if defined(FEAT_MBYTE) && defined(WIN3264)
1340 /* The text is in the active codepage. Convert to 'encoding',
1341 * going through UCS-2. */
1342 acp_to_enc(str
, str_size
, &to_free
, &maxlen
);
1343 if (to_free
!= NULL
)
1355 if (str
!= NULL
&& *str
!= NUL
)
1357 char_u
*temp_clipboard
;
1359 /* If the type is not known guess it. */
1360 if (metadata
.type
== -1)
1361 metadata
.type
= (vim_strchr(str
, '\n') == NULL
) ? MCHAR
: MLINE
;
1363 /* Translate <CR><NL> into <NL>. */
1364 temp_clipboard
= crnl_to_nl(str
, &str_size
);
1365 if (temp_clipboard
!= NULL
)
1367 clip_yank_selection(metadata
.type
, temp_clipboard
, str_size
, cbd
);
1368 vim_free(temp_clipboard
);
1372 /* unlock the global object */
1380 #if defined(FEAT_MBYTE) && defined(WIN3264)
1385 #if (defined(FEAT_MBYTE) && defined(WIN3264)) || defined(PROTO)
1387 * Convert from the active codepage to 'encoding'.
1388 * Input is "str[str_size]".
1389 * The result is in allocated memory: "out[outlen]". With terminating NUL.
1392 acp_to_enc(str
, str_size
, out
, outlen
)
1401 MultiByteToWideChar_alloc(GetACP(), 0, str
, str_size
, &widestr
, outlen
);
1402 if (widestr
!= NULL
)
1404 ++*outlen
; /* Include the 0 after the string */
1405 *out
= ucs2_to_enc((short_u
*)widestr
, outlen
);
1412 * Send the current selection to the clipboard.
1415 clip_mch_set_selection(VimClipboard
*cbd
)
1418 VimClipType_t metadata
;
1420 HGLOBAL hMemRaw
= NULL
;
1421 HGLOBAL hMem
= NULL
;
1422 HGLOBAL hMemVim
= NULL
;
1423 # if defined(FEAT_MBYTE) && defined(WIN3264)
1424 HGLOBAL hMemW
= NULL
;
1427 /* If the '*' register isn't already filled in, fill it in now */
1429 clip_get_selection(cbd
);
1432 /* Get the text to be put on the clipboard, with CR-LF. */
1433 metadata
.type
= clip_convert_selection(&str
, &txtlen
, cbd
);
1434 if (metadata
.type
< 0)
1436 metadata
.txtlen
= (int)txtlen
;
1437 metadata
.ucslen
= 0;
1438 metadata
.rawlen
= 0;
1441 /* Always set the raw bytes: 'encoding', NUL and the text. This is used
1442 * when copy/paste from/to Vim with the same 'encoding', so that illegal
1443 * bytes can also be copied and no conversion is needed. */
1447 metadata
.rawlen
= (int)(txtlen
+ STRLEN(p_enc
) + 1);
1448 hMemRaw
= (LPSTR
)GlobalAlloc(GMEM_MOVEABLE
| GMEM_DDESHARE
,
1449 metadata
.rawlen
+ 1);
1450 lpszMemRaw
= (LPSTR
)GlobalLock(hMemRaw
);
1451 if (lpszMemRaw
!= NULL
)
1453 STRCPY(lpszMemRaw
, p_enc
);
1454 memcpy(lpszMemRaw
+ STRLEN(p_enc
) + 1, str
, txtlen
+ 1);
1455 GlobalUnlock(hMemRaw
);
1458 metadata
.rawlen
= 0;
1462 # if defined(FEAT_MBYTE) && defined(WIN3264)
1465 int len
= metadata
.txtlen
;
1467 /* Convert the text to UCS-2. This is put on the clipboard as
1468 * CF_UNICODETEXT. */
1469 out
= (WCHAR
*)enc_to_ucs2(str
, &len
);
1474 /* Convert the text for CF_TEXT to Active codepage. Otherwise it's
1475 * p_enc, which has no relation to the Active codepage. */
1476 metadata
.txtlen
= WideCharToMultiByte(GetACP(), 0, out
, len
,
1479 str
= (char_u
*)alloc((unsigned)(metadata
.txtlen
== 0 ? 1
1480 : metadata
.txtlen
));
1484 return; /* out of memory */
1486 WideCharToMultiByte(GetACP(), 0, out
, len
,
1487 str
, metadata
.txtlen
, 0, 0);
1489 /* Allocate memory for the UCS-2 text, add one NUL word to
1490 * terminate the string. */
1491 hMemW
= (LPSTR
)GlobalAlloc(GMEM_MOVEABLE
| GMEM_DDESHARE
,
1492 (len
+ 1) * sizeof(WCHAR
));
1493 lpszMemW
= (WCHAR
*)GlobalLock(hMemW
);
1494 if (lpszMemW
!= NULL
)
1496 memcpy(lpszMemW
, out
, len
* sizeof(WCHAR
));
1497 lpszMemW
[len
] = NUL
;
1498 GlobalUnlock(hMemW
);
1501 metadata
.ucslen
= len
;
1506 /* Allocate memory for the text, add one NUL byte to terminate the string.
1508 hMem
= GlobalAlloc(GMEM_MOVEABLE
| GMEM_DDESHARE
, metadata
.txtlen
+ 1);
1510 LPSTR lpszMem
= (LPSTR
)GlobalLock(hMem
);
1514 vim_strncpy(lpszMem
, str
, metadata
.txtlen
);
1519 /* Set up metadata: */
1521 VimClipType_t
*lpszMemVim
= NULL
;
1523 hMemVim
= GlobalAlloc(GMEM_MOVEABLE
|GMEM_DDESHARE
,
1524 sizeof(VimClipType_t
));
1525 lpszMemVim
= (VimClipType_t
*)GlobalLock(hMemVim
);
1526 memcpy(lpszMemVim
, &metadata
, sizeof(metadata
));
1527 GlobalUnlock(hMemVim
);
1531 * Open the clipboard, clear it and put our text on it.
1532 * Always set our Vim format. Put Unicode and plain text on it.
1534 * Don't pass GetActiveWindow() as an argument to OpenClipboard()
1535 * because then we can't paste back into the same window for some
1538 if (OpenClipboard(NULL
))
1540 if (EmptyClipboard())
1542 SetClipboardData(cbd
->format
, hMemVim
);
1544 # if defined(FEAT_MBYTE) && defined(WIN3264)
1547 if (SetClipboardData(CF_UNICODETEXT
, hMemW
) != NULL
)
1551 /* Always use CF_TEXT. On Win98 Notepad won't obtain the
1552 * CF_UNICODETEXT text, only CF_TEXT. */
1553 SetClipboardData(CF_TEXT
, hMem
);
1560 /* Free any allocations we didn't give to the clipboard: */
1562 GlobalFree(hMemRaw
);
1565 # if defined(FEAT_MBYTE) && defined(WIN3264)
1570 GlobalFree(hMemVim
);
1573 #endif /* FEAT_CLIPBOARD */
1577 * Debugging helper: expose the MCH_WRITE_DUMP stuff to other modules
1584 # ifdef MCH_WRITE_DUMP
1588 if (psz
[strlen(psz
) - 1] != '\n')
1589 fputc('\n', fdDump
);
1605 va_start(args
, pszFormat
);
1606 vsprintf(szBuff
, pszFormat
, args
);
1609 OutputDebugString(szBuff
);
1614 #if !defined(FEAT_GUI) || defined(PROTO)
1615 # if defined(FEAT_TITLE) && defined(WIN3264)
1616 extern HWND g_hWnd
; /* This is in os_win32.c. */
1620 * Showing the printer dialog is tricky since we have no GUI
1621 * window to parent it. The following routines are needed to
1622 * get the window parenting and Z-order to work properly.
1625 GetConsoleHwnd(void)
1627 # define MY_BUFSIZE 1024 // Buffer size for console window titles.
1629 char pszNewWindowTitle
[MY_BUFSIZE
]; // Contains fabricated WindowTitle.
1630 char pszOldWindowTitle
[MY_BUFSIZE
]; // Contains original WindowTitle.
1632 /* Skip if it's already set. */
1636 # if defined(FEAT_TITLE) && defined(WIN3264)
1637 /* Window handle may have been found by init code (Windows NT only) */
1645 GetConsoleTitle(pszOldWindowTitle
, MY_BUFSIZE
);
1647 wsprintf(pszNewWindowTitle
, "%s/%d/%d",
1650 GetCurrentProcessId());
1651 SetConsoleTitle(pszNewWindowTitle
);
1653 s_hwnd
= FindWindow(NULL
, pszNewWindowTitle
);
1655 SetConsoleTitle(pszOldWindowTitle
);
1659 * Console implementation of ":winpos".
1662 mch_get_winpos(int *x
, int *y
)
1667 GetWindowRect(s_hwnd
, &rect
);
1674 * Console implementation of ":winpos x y".
1677 mch_set_winpos(int x
, int y
)
1680 SetWindowPos(s_hwnd
, NULL
, x
, y
, 0, 0,
1681 SWP_NOZORDER
| SWP_NOSIZE
| SWP_NOACTIVATE
);
1685 #if (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) || defined(PROTO)
1690 /*=================================================================
1691 * Win32 printer stuff
1694 static HFONT prt_font_handles
[2][2][2];
1695 static PRINTDLG prt_dlg
;
1696 static const int boldface
[2] = {FW_REGULAR
, FW_BOLD
};
1697 static TEXTMETRIC prt_tm
;
1698 static int prt_line_height
;
1699 static int prt_number_width
;
1700 static int prt_left_margin
;
1701 static int prt_right_margin
;
1702 static int prt_top_margin
;
1703 static char_u szAppName
[] = TEXT("VIM");
1704 static HWND hDlgPrint
;
1705 static int *bUserAbort
= NULL
;
1706 static char_u
*prt_name
= NULL
;
1708 /* Defines which are also in vim.rc. */
1709 #define IDC_BOX1 400
1710 #define IDC_PRINTTEXT1 401
1711 #define IDC_PRINTTEXT2 402
1712 #define IDC_PROGRESS 403
1715 * Convert BGR to RGB for Windows GDI calls
1718 swap_me(COLORREF colorref
)
1721 char *ptr
= (char *)&colorref
;
1724 *(ptr
) = *(ptr
+ 2);
1730 static BOOL CALLBACK
1731 PrintDlgProc(HWND hDlg
, UINT message
, WPARAM wParam
, LPARAM lParam
)
1734 NONCLIENTMETRICS nm
;
1742 nm
.cbSize
= sizeof(NONCLIENTMETRICS
);
1743 if (SystemParametersInfo(
1744 SPI_GETNONCLIENTMETRICS
,
1745 sizeof(NONCLIENTMETRICS
),
1749 char buff
[MAX_PATH
];
1752 /* Translate the dialog texts */
1753 hfont
= CreateFontIndirect(&nm
.lfMessageFont
);
1754 for (i
= IDC_PRINTTEXT1
; i
<= IDC_PROGRESS
; i
++)
1756 SendDlgItemMessage(hDlg
, i
, WM_SETFONT
, (WPARAM
)hfont
, 1);
1757 if (GetDlgItemText(hDlg
,i
, buff
, sizeof(buff
)))
1758 SetDlgItemText(hDlg
,i
, _(buff
));
1760 SendDlgItemMessage(hDlg
, IDCANCEL
,
1761 WM_SETFONT
, (WPARAM
)hfont
, 1);
1762 if (GetDlgItemText(hDlg
,IDCANCEL
, buff
, sizeof(buff
)))
1763 SetDlgItemText(hDlg
,IDCANCEL
, _(buff
));
1766 SetWindowText(hDlg
, szAppName
);
1767 if (prt_name
!= NULL
)
1769 SetDlgItemText(hDlg
, IDC_PRINTTEXT2
, (LPSTR
)prt_name
);
1773 EnableMenuItem(GetSystemMenu(hDlg
, FALSE
), SC_CLOSE
, MF_GRAYED
);
1775 BringWindowToTop(s_hwnd
);
1781 EnableWindow(GetParent(hDlg
), TRUE
);
1782 DestroyWindow(hDlg
);
1785 DeleteObject(hfont
);
1793 static BOOL CALLBACK
1794 AbortProc(HDC hdcPrn
, int iCode
)
1798 while (!*bUserAbort
&& PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
))
1800 if (!hDlgPrint
|| !IsDialogMessage(hDlgPrint
, &msg
))
1802 TranslateMessage(&msg
);
1803 DispatchMessage(&msg
);
1806 return !*bUserAbort
;
1811 static UINT CALLBACK
1813 HWND hDlg
, // handle to dialog box
1814 UINT uiMsg
, // message identifier
1815 WPARAM wParam
, // message parameter
1816 LPARAM lParam
// message parameter
1820 RECT rc
, rcDlg
, rcOwner
;
1823 if (uiMsg
== WM_INITDIALOG
)
1825 // Get the owner window and dialog box rectangles.
1826 if ((hwndOwner
= GetParent(hDlg
)) == NULL
)
1827 hwndOwner
= GetDesktopWindow();
1829 GetWindowRect(hwndOwner
, &rcOwner
);
1830 GetWindowRect(hDlg
, &rcDlg
);
1831 CopyRect(&rc
, &rcOwner
);
1833 // Offset the owner and dialog box rectangles so that
1834 // right and bottom values represent the width and
1835 // height, and then offset the owner again to discard
1836 // space taken up by the dialog box.
1838 OffsetRect(&rcDlg
, -rcDlg
.left
, -rcDlg
.top
);
1839 OffsetRect(&rc
, -rc
.left
, -rc
.top
);
1840 OffsetRect(&rc
, -rcDlg
.right
, -rcDlg
.bottom
);
1842 // The new position is the sum of half the remaining
1843 // space and the owner's original position.
1847 rcOwner
.left
+ (rc
.right
/ 2),
1848 rcOwner
.top
+ (rc
.bottom
/ 2),
1849 0, 0, // ignores size arguments
1852 /* tackle the printdlg copiesctrl problem */
1853 pPD
= (PRINTDLG
*)lParam
;
1854 pPD
->nCopies
= (WORD
)pPD
->lCustData
;
1855 SetDlgItemInt( hDlg
, edt3
, pPD
->nCopies
, FALSE
);
1856 /* Bring the window to top */
1857 BringWindowToTop(GetParent(hDlg
));
1858 SetForegroundWindow(hDlg
);
1866 mch_print_cleanup(void)
1872 for (pifBold
= 0; pifBold
<= 1; pifBold
++)
1873 for (pifItalic
= 0; pifItalic
<= 1; pifItalic
++)
1874 for (pifUnderline
= 0; pifUnderline
<= 1; pifUnderline
++)
1875 DeleteObject(prt_font_handles
[pifBold
][pifItalic
][pifUnderline
]);
1877 if (prt_dlg
.hDC
!= NULL
)
1878 DeleteDC(prt_dlg
.hDC
);
1880 SendMessage(hDlgPrint
, WM_COMMAND
, 0, 0);
1884 to_device_units(int idx
, int dpi
, int physsize
, int offset
, int def_number
)
1890 u
= prt_get_unit(idx
);
1891 if (u
== PRT_UNIT_NONE
)
1897 nr
= printer_opts
[idx
].number
;
1902 ret
= (physsize
* nr
) / 100;
1908 ret
= (nr
* 10 * dpi
) / 254;
1910 case PRT_UNIT_POINT
:
1911 ret
= (nr
* 10 * dpi
) / 720;
1918 return ret
- offset
;
1933 GetTextMetrics(prt_dlg
.hDC
, &prt_tm
);
1934 prt_line_height
= prt_tm
.tmHeight
+ prt_tm
.tmExternalLeading
;
1936 hr
= GetDeviceCaps(prt_dlg
.hDC
, HORZRES
);
1938 Escape(prt_dlg
.hDC
, GETPHYSPAGESIZE
, NULL
, NULL
, &pagesize
);
1940 Escape(prt_dlg
.hDC
, GETPRINTINGOFFSET
, NULL
, NULL
, &pagesize
);
1943 phyw
= GetDeviceCaps(prt_dlg
.hDC
, PHYSICALWIDTH
);
1944 dvoff
= GetDeviceCaps(prt_dlg
.hDC
, PHYSICALOFFSETX
);
1946 dpi
= GetDeviceCaps(prt_dlg
.hDC
, LOGPIXELSX
);
1948 rev_offset
= phyw
- (dvoff
+ hr
);
1950 prt_left_margin
= to_device_units(OPT_PRINT_LEFT
, dpi
, phyw
, dvoff
, 10);
1951 if (prt_use_number())
1953 prt_number_width
= PRINT_NUMBER_WIDTH
* prt_tm
.tmAveCharWidth
;
1954 prt_left_margin
+= prt_number_width
;
1957 prt_number_width
= 0;
1959 prt_right_margin
= hr
- to_device_units(OPT_PRINT_RIGHT
, dpi
, phyw
,
1962 return (prt_right_margin
- prt_left_margin
) / prt_tm
.tmAveCharWidth
;
1978 vr
= GetDeviceCaps(prt_dlg
.hDC
, VERTRES
);
1980 Escape(prt_dlg
.hDC
, GETPHYSPAGESIZE
, NULL
, NULL
, &pagesize
);
1982 Escape(prt_dlg
.hDC
, GETPRINTINGOFFSET
, NULL
, NULL
, &pagesize
);
1985 phyw
= GetDeviceCaps(prt_dlg
.hDC
, PHYSICALHEIGHT
);
1986 dvoff
= GetDeviceCaps(prt_dlg
.hDC
, PHYSICALOFFSETY
);
1988 dpi
= GetDeviceCaps(prt_dlg
.hDC
, LOGPIXELSY
);
1990 rev_offset
= phyw
- (dvoff
+ vr
);
1992 prt_top_margin
= to_device_units(OPT_PRINT_TOP
, dpi
, phyw
, dvoff
, 5);
1994 /* adjust top margin if there is a header */
1995 prt_top_margin
+= prt_line_height
* prt_header_height();
1997 bottom_margin
= vr
- to_device_units(OPT_PRINT_BOT
, dpi
, phyw
,
2000 return (bottom_margin
- prt_top_margin
) / prt_line_height
;
2004 mch_print_init(prt_settings_T
*psettings
, char_u
*jobname
, int forceit
)
2006 static HGLOBAL stored_dm
= NULL
;
2007 static HGLOBAL stored_devn
= NULL
;
2008 static int stored_nCopies
= 1;
2009 static int stored_nFlags
= 0;
2020 bUserAbort
= &(psettings
->user_abort
);
2021 memset(&prt_dlg
, 0, sizeof(PRINTDLG
));
2022 prt_dlg
.lStructSize
= sizeof(PRINTDLG
);
2024 GetConsoleHwnd(); /* get value of s_hwnd */
2026 prt_dlg
.hwndOwner
= s_hwnd
;
2027 prt_dlg
.Flags
= PD_NOPAGENUMS
| PD_NOSELECTION
| PD_RETURNDC
;
2030 prt_dlg
.hDevMode
= stored_dm
;
2031 prt_dlg
.hDevNames
= stored_devn
;
2032 prt_dlg
.lCustData
= stored_nCopies
; // work around bug in print dialog
2035 * Use hook to prevent console window being sent to back
2037 prt_dlg
.lpfnPrintHook
= PrintHookProc
;
2038 prt_dlg
.Flags
|= PD_ENABLEPRINTHOOK
;
2040 prt_dlg
.Flags
|= stored_nFlags
;
2044 * If bang present, return default printer setup with no dialog
2045 * never show dialog if we are running over telnet
2053 prt_dlg
.Flags
|= PD_RETURNDEFAULT
;
2056 * MSDN suggests setting the first parameter to WINSPOOL for
2057 * NT, but NULL appears to work just as well.
2060 prt_dlg
.hDC
= CreateDC(NULL
, p_pdev
, NULL
, NULL
);
2064 prt_dlg
.Flags
|= PD_RETURNDEFAULT
;
2065 if (PrintDlg(&prt_dlg
) == 0)
2069 else if (PrintDlg(&prt_dlg
) == 0)
2074 * keep the previous driver context
2076 stored_dm
= prt_dlg
.hDevMode
;
2077 stored_devn
= prt_dlg
.hDevNames
;
2078 stored_nFlags
= prt_dlg
.Flags
;
2079 stored_nCopies
= prt_dlg
.nCopies
;
2082 if (prt_dlg
.hDC
== NULL
)
2084 EMSG(_("E237: Printer selection failed"));
2085 mch_print_cleanup();
2089 /* Not all printer drivers report the support of color (or grey) in the
2090 * same way. Let's set has_color if there appears to be some way to print
2092 i
= GetDeviceCaps(prt_dlg
.hDC
, NUMCOLORS
);
2093 psettings
->has_color
= (GetDeviceCaps(prt_dlg
.hDC
, BITSPIXEL
) > 1
2094 || GetDeviceCaps(prt_dlg
.hDC
, PLANES
) > 1
2095 || i
> 2 || i
== -1);
2097 /* Ensure all font styles are baseline aligned */
2098 SetTextAlign(prt_dlg
.hDC
, TA_BASELINE
|TA_LEFT
);
2101 * On some windows systems the nCopies parameter is not
2102 * passed back correctly. It must be retrieved from the
2105 mem
= (DEVMODE
*)GlobalLock(prt_dlg
.hDevMode
);
2109 if (mem
->dmCopies
!= 1)
2110 stored_nCopies
= mem
->dmCopies
;
2112 if ((mem
->dmFields
& DM_DUPLEX
) && (mem
->dmDuplex
& ~DMDUP_SIMPLEX
))
2113 psettings
->duplex
= TRUE
;
2114 if ((mem
->dmFields
& DM_COLOR
) && (mem
->dmColor
& DMCOLOR_COLOR
))
2115 psettings
->has_color
= TRUE
;
2117 GlobalUnlock(prt_dlg
.hDevMode
);
2119 devname
= (DEVNAMES
*)GlobalLock(prt_dlg
.hDevNames
);
2122 char_u
*printer_name
= (char_u
*)devname
+ devname
->wDeviceOffset
;
2123 char_u
*port_name
= (char_u
*)devname
+devname
->wOutputOffset
;
2124 char_u
*text
= _("to %s on %s");
2126 prt_name
= alloc(STRLEN(printer_name
) + STRLEN(port_name
)
2128 if (prt_name
!= NULL
)
2129 wsprintf(prt_name
, text
, printer_name
, port_name
);
2131 GlobalUnlock(prt_dlg
.hDevNames
);
2134 * Initialise the font according to 'printfont'
2136 memset(&fLogFont
, 0, sizeof(fLogFont
));
2137 if (get_logfont(&fLogFont
, p_pfn
, prt_dlg
.hDC
, TRUE
) == FAIL
)
2139 EMSG2(_("E613: Unknown printer font: %s"), p_pfn
);
2140 mch_print_cleanup();
2144 for (pifBold
= 0; pifBold
<= 1; pifBold
++)
2145 for (pifItalic
= 0; pifItalic
<= 1; pifItalic
++)
2146 for (pifUnderline
= 0; pifUnderline
<= 1; pifUnderline
++)
2148 fLogFont
.lfWeight
= boldface
[pifBold
];
2149 fLogFont
.lfItalic
= pifItalic
;
2150 fLogFont
.lfUnderline
= pifUnderline
;
2151 prt_font_handles
[pifBold
][pifItalic
][pifUnderline
]
2152 = CreateFontIndirect(&fLogFont
);
2155 SetBkMode(prt_dlg
.hDC
, OPAQUE
);
2156 SelectObject(prt_dlg
.hDC
, prt_font_handles
[0][0][0]);
2159 * Fill in the settings struct
2161 psettings
->chars_per_line
= prt_get_cpl();
2162 psettings
->lines_per_page
= prt_get_lpp();
2163 psettings
->n_collated_copies
= (prt_dlg
.Flags
& PD_COLLATE
)
2164 ? prt_dlg
.nCopies
: 1;
2165 psettings
->n_uncollated_copies
= (prt_dlg
.Flags
& PD_COLLATE
)
2166 ? 1 : prt_dlg
.nCopies
;
2168 if (psettings
->n_collated_copies
== 0)
2169 psettings
->n_collated_copies
= 1;
2171 if (psettings
->n_uncollated_copies
== 0)
2172 psettings
->n_uncollated_copies
= 1;
2174 psettings
->jobname
= jobname
;
2180 DWORD err
= CommDlgExtendedError();
2187 sprintf(buf
, "%ld", err
);
2188 EMSG2(_("E238: Print error: %s"), buf
);
2192 /* I suspect FormatMessage() doesn't work for values returned by
2193 * CommDlgExtendedError(). What does? */
2194 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|
2195 FORMAT_MESSAGE_FROM_SYSTEM
|
2196 FORMAT_MESSAGE_IGNORE_INSERTS
,
2197 NULL
, err
, 0, (LPTSTR
)(&buf
), 0, NULL
);
2198 EMSG2(_("E238: Print error: %s"),
2199 buf
== NULL
? (char_u
*)_("Unknown") : buf
);
2200 LocalFree((LPVOID
)(buf
));
2204 msg_clr_eos(); /* Maybe canceled */
2206 mch_print_cleanup();
2213 mch_print_begin(prt_settings_T
*psettings
)
2219 hDlgPrint
= CreateDialog(GetModuleHandle(NULL
), TEXT("PrintDlgBox"),
2220 prt_dlg
.hwndOwner
, PrintDlgProc
);
2222 Escape(prt_dlg
.hDC
, SETABORTPROC
, 0, (LPSTR
)AbortProc
, NULL
);
2224 SetAbortProc(prt_dlg
.hDC
, AbortProc
);
2226 wsprintf(szBuffer
, _("Printing '%s'"), gettail(psettings
->jobname
));
2227 SetDlgItemText(hDlgPrint
, IDC_PRINTTEXT1
, (LPSTR
)szBuffer
);
2229 memset(&di
, 0, sizeof(DOCINFO
));
2230 di
.cbSize
= sizeof(DOCINFO
);
2231 di
.lpszDocName
= psettings
->jobname
;
2232 ret
= StartDoc(prt_dlg
.hDC
, &di
);
2235 /* Give focus back to main window (when using MDI). */
2244 mch_print_end(prt_settings_T
*psettings
)
2246 EndDoc(prt_dlg
.hDC
);
2248 SendMessage(hDlgPrint
, WM_COMMAND
, 0, 0);
2252 mch_print_end_page(void)
2254 return (EndPage(prt_dlg
.hDC
) > 0);
2258 mch_print_begin_page(char_u
*msg
)
2261 SetDlgItemText(hDlgPrint
, IDC_PROGRESS
, (LPSTR
)msg
);
2262 return (StartPage(prt_dlg
.hDC
) > 0);
2266 mch_print_blank_page(void)
2268 return (mch_print_begin_page(NULL
) ? (mch_print_end_page()) : FALSE
);
2271 static int prt_pos_x
= 0;
2272 static int prt_pos_y
= 0;
2275 mch_print_start_line(margin
, page_line
)
2280 prt_pos_x
= -prt_number_width
;
2283 prt_pos_y
= page_line
* prt_line_height
2284 + prt_tm
.tmAscent
+ prt_tm
.tmExternalLeading
;
2288 mch_print_text_out(char_u
*p
, int len
)
2290 #ifdef FEAT_PROPORTIONAL_FONTS
2294 TextOut(prt_dlg
.hDC
, prt_pos_x
+ prt_left_margin
,
2295 prt_pos_y
+ prt_top_margin
, p
, len
);
2296 #ifndef FEAT_PROPORTIONAL_FONTS
2297 prt_pos_x
+= len
* prt_tm
.tmAveCharWidth
;
2298 return (prt_pos_x
+ prt_left_margin
+ prt_tm
.tmAveCharWidth
2299 + prt_tm
.tmOverhang
> prt_right_margin
);
2302 GetTextExtentPoint(prt_dlg
.hDC
, p
, len
, &sz
);
2304 GetTextExtentPoint32(prt_dlg
.hDC
, p
, len
, &sz
);
2306 prt_pos_x
+= (sz
.cx
- prt_tm
.tmOverhang
);
2307 /* This is wrong when printing spaces for a TAB. */
2311 GetTextExtentPoint(prt_dlg
.hDC
, p
+ len
, 1, &sz
);
2313 GetTextExtentPoint32(prt_dlg
.hDC
, p
+ len
, 1, &sz
);
2315 return (prt_pos_x
+ prt_left_margin
+ sz
.cx
> prt_right_margin
);
2320 mch_print_set_font(int iBold
, int iItalic
, int iUnderline
)
2322 SelectObject(prt_dlg
.hDC
, prt_font_handles
[iBold
][iItalic
][iUnderline
]);
2326 mch_print_set_bg(unsigned long bgcol
)
2328 SetBkColor(prt_dlg
.hDC
, GetNearestColor(prt_dlg
.hDC
, swap_me(bgcol
)));
2330 * With a white background we can draw characters transparent, which is
2331 * good for italic characters that overlap to the next char cell.
2333 if (bgcol
== 0xffffffUL
)
2334 SetBkMode(prt_dlg
.hDC
, TRANSPARENT
);
2336 SetBkMode(prt_dlg
.hDC
, OPAQUE
);
2340 mch_print_set_fg(unsigned long fgcol
)
2342 SetTextColor(prt_dlg
.hDC
, GetNearestColor(prt_dlg
.hDC
, swap_me(fgcol
)));
2345 #endif /*FEAT_PRINTER && !FEAT_POSTSCRIPT*/
2349 #if defined(FEAT_SHORTCUT) || defined(PROTO)
2350 # include <shlobj.h>
2353 * When "fname" is the name of a shortcut (*.lnk) resolve the file it points
2354 * to and return that name in allocated memory.
2355 * Otherwise NULL is returned.
2358 mch_resolve_shortcut(char_u
*fname
)
2361 IShellLink
*psl
= NULL
;
2362 IPersistFile
*ppf
= NULL
;
2363 OLECHAR wsz
[MAX_PATH
];
2364 WIN32_FIND_DATA ffd
; // we get those free of charge
2365 TCHAR buf
[MAX_PATH
]; // could have simply reused 'wsz'...
2366 char_u
*rfname
= NULL
;
2369 /* Check if the file name ends in ".lnk". Avoid calling
2370 * CoCreateInstance(), it's quite slow. */
2373 len
= (int)STRLEN(fname
);
2374 if (len
<= 4 || STRNICMP(fname
+ len
- 4, ".lnk", 4) != 0)
2379 // create a link manager object and request its interface
2380 hr
= CoCreateInstance(
2381 &CLSID_ShellLink
, NULL
, CLSCTX_INPROC_SERVER
,
2382 &IID_IShellLink
, (void**)&psl
);
2384 goto shortcut_error
;
2386 // Get a pointer to the IPersistFile interface.
2387 hr
= psl
->lpVtbl
->QueryInterface(
2388 psl
, &IID_IPersistFile
, (void**)&ppf
);
2390 goto shortcut_error
;
2392 // full path string must be in Unicode.
2393 MultiByteToWideChar(CP_ACP
, 0, fname
, -1, wsz
, MAX_PATH
);
2395 // "load" the name and resove the link
2396 hr
= ppf
->lpVtbl
->Load(ppf
, wsz
, STGM_READ
);
2398 goto shortcut_error
;
2399 #if 0 // This makes Vim wait a long time if the target doesn't exist.
2400 hr
= psl
->lpVtbl
->Resolve(psl
, NULL
, SLR_NO_UI
);
2402 goto shortcut_error
;
2405 // Get the path to the link target.
2406 ZeroMemory(buf
, MAX_PATH
);
2407 hr
= psl
->lpVtbl
->GetPath(psl
, buf
, MAX_PATH
, &ffd
, 0);
2408 if (hr
== S_OK
&& buf
[0] != NUL
)
2409 rfname
= vim_strsave(buf
);
2412 // Release all interface pointers (both belong to the same object)
2414 ppf
->lpVtbl
->Release(ppf
);
2416 psl
->lpVtbl
->Release(psl
);
2423 #if (defined(FEAT_EVAL) && !defined(FEAT_GUI)) || defined(PROTO)
2425 * Bring ourselves to the foreground. Does work if the OS doesn't allow it.
2428 win32_set_foreground()
2431 GetConsoleHwnd(); /* get value of s_hwnd */
2434 SetForegroundWindow(s_hwnd
);
2438 #if defined(FEAT_CLIENTSERVER) || defined(PROTO)
2440 * Client-server code for Vim
2442 * Originally written by Paul Moore
2445 /* In order to handle inter-process messages, we need to have a window. But
2446 * the functions in this module can be called before the main GUI window is
2447 * created (and may also be called in the console version, where there is no
2448 * GUI window at all).
2450 * So we create a hidden window, and arrange to destroy it on exit.
2452 HWND message_window
= 0; /* window that's handling messsages */
2454 #define VIM_CLASSNAME "VIM_MESSAGES"
2455 #define VIM_CLASSNAME_LEN (sizeof(VIM_CLASSNAME) - 1)
2457 /* Communication is via WM_COPYDATA messages. The message type is send in
2458 * the dwData parameter. Types are defined here. */
2459 #define COPYDATA_KEYS 0
2460 #define COPYDATA_REPLY 1
2461 #define COPYDATA_EXPR 10
2462 #define COPYDATA_RESULT 11
2463 #define COPYDATA_ERROR_RESULT 12
2464 #define COPYDATA_ENCODING 20
2466 /* This is a structure containing a server HWND and its name. */
2473 /* Last received 'encoding' that the client uses. */
2474 static char_u
*client_enc
= NULL
;
2477 * Tell the other side what encoding we are using.
2478 * Errors are ignored.
2481 serverSendEnc(HWND target
)
2483 COPYDATASTRUCT data
;
2485 data
.dwData
= COPYDATA_ENCODING
;
2487 data
.cbData
= (DWORD
)STRLEN(p_enc
) + 1;
2488 data
.lpData
= p_enc
;
2490 data
.cbData
= STRLEN("latin1") + 1;
2491 data
.lpData
= "latin1";
2493 (void)SendMessage(target
, WM_COPYDATA
, (WPARAM
)message_window
,
2498 * Clean up on exit. This destroys the hidden message window.
2504 CleanUpMessaging(void)
2506 if (message_window
!= 0)
2508 DestroyWindow(message_window
);
2513 static int save_reply(HWND server
, char_u
*reply
, int expr
);
2516 * The window procedure for the hidden message window.
2517 * It handles callback messages and notifications from servers.
2518 * In order to process these messages, it is necessary to run a
2519 * message loop. Code which may run before the main message loop
2520 * is started (in the GUI) is careful to pump messages when it needs
2521 * to. Features which require message delivery during normal use will
2522 * not work in the console version - this basically means those
2523 * features which allow Vim to act as a server, rather than a client.
2525 static LRESULT CALLBACK
2526 Messaging_WndProc(HWND hwnd
, UINT msg
, WPARAM wParam
, LPARAM lParam
)
2528 if (msg
== WM_COPYDATA
)
2530 /* This is a message from another Vim. The dwData member of the
2531 * COPYDATASTRUCT determines the type of message:
2532 * COPYDATA_ENCODING:
2533 * The encoding that the client uses. Following messages will
2534 * use this encoding, convert if needed.
2536 * A key sequence. We are a server, and a client wants these keys
2537 * adding to the input queue.
2539 * A reply. We are a client, and a server has sent this message
2540 * in response to a request. (server2client())
2542 * An expression. We are a server, and a client wants us to
2543 * evaluate this expression.
2545 * A reply. We are a client, and a server has sent this message
2546 * in response to a COPYDATA_EXPR.
2547 * COPYDATA_ERROR_RESULT:
2548 * A reply. We are a client, and a server has sent this message
2549 * in response to a COPYDATA_EXPR that failed to evaluate.
2551 COPYDATASTRUCT
*data
= (COPYDATASTRUCT
*)lParam
;
2552 HWND sender
= (HWND
)wParam
;
2553 COPYDATASTRUCT reply
;
2560 switch (data
->dwData
)
2562 case COPYDATA_ENCODING
:
2564 /* Remember the encoding that the client uses. */
2565 vim_free(client_enc
);
2566 client_enc
= enc_canonize((char_u
*)data
->lpData
);
2571 /* Remember who sent this, for <client> */
2572 clientWindow
= sender
;
2574 /* Add the received keys to the input buffer. The loop waiting
2575 * for the user to do something should check the input buffer. */
2576 str
= serverConvert(client_enc
, (char_u
*)data
->lpData
, &tofree
);
2577 server_to_input_buf(str
);
2581 /* Wake up the main GUI loop. */
2583 PostMessage(s_hwnd
, WM_NULL
, 0, 0);
2588 /* Remember who sent this, for <client> */
2589 clientWindow
= sender
;
2591 str
= serverConvert(client_enc
, (char_u
*)data
->lpData
, &tofree
);
2592 res
= eval_client_expr_to_string(str
);
2597 res
= vim_strsave(_(e_invexprmsg
));
2598 reply
.dwData
= COPYDATA_ERROR_RESULT
;
2601 reply
.dwData
= COPYDATA_RESULT
;
2603 reply
.cbData
= (DWORD
)STRLEN(res
) + 1;
2605 serverSendEnc(sender
);
2606 retval
= (int)SendMessage(sender
, WM_COPYDATA
, (WPARAM
)message_window
,
2611 case COPYDATA_REPLY
:
2612 case COPYDATA_RESULT
:
2613 case COPYDATA_ERROR_RESULT
:
2614 if (data
->lpData
!= NULL
)
2616 str
= serverConvert(client_enc
, (char_u
*)data
->lpData
,
2619 str
= vim_strsave(str
);
2620 if (save_reply(sender
, str
,
2621 (data
->dwData
== COPYDATA_REPLY
? 0 :
2622 (data
->dwData
== COPYDATA_RESULT
? 1 :
2626 else if (data
->dwData
== COPYDATA_REPLY
)
2628 sprintf((char *)winstr
, "0x%x", (unsigned)sender
);
2629 apply_autocmds(EVENT_REMOTEREPLY
, winstr
, str
,
2640 else if (msg
== WM_ACTIVATE
&& wParam
== WA_ACTIVE
)
2642 /* When the message window is activated (brought to the foreground),
2643 * this actually applies to the text window. */
2645 GetConsoleHwnd(); /* get value of s_hwnd */
2649 SetForegroundWindow(s_hwnd
);
2654 return DefWindowProc(hwnd
, msg
, wParam
, lParam
);
2658 * Initialise the message handling process. This involves creating a window
2659 * to handle messages - the window will not be visible.
2662 serverInitMessaging(void)
2667 /* Clean up on exit */
2668 atexit(CleanUpMessaging
);
2670 /* Register a window class - we only really care
2671 * about the window procedure
2673 s_hinst
= (HINSTANCE
)GetModuleHandle(0);
2675 wndclass
.lpfnWndProc
= Messaging_WndProc
;
2676 wndclass
.cbClsExtra
= 0;
2677 wndclass
.cbWndExtra
= 0;
2678 wndclass
.hInstance
= s_hinst
;
2679 wndclass
.hIcon
= NULL
;
2680 wndclass
.hCursor
= NULL
;
2681 wndclass
.hbrBackground
= NULL
;
2682 wndclass
.lpszMenuName
= NULL
;
2683 wndclass
.lpszClassName
= VIM_CLASSNAME
;
2684 RegisterClass(&wndclass
);
2686 /* Create the message window. It will be hidden, so the details don't
2687 * matter. Don't use WS_OVERLAPPEDWINDOW, it will make a shortcut remove
2688 * focus from gvim. */
2689 message_window
= CreateWindow(VIM_CLASSNAME
, "",
2690 WS_POPUPWINDOW
| WS_CAPTION
,
2691 CW_USEDEFAULT
, CW_USEDEFAULT
,
2692 100, 100, NULL
, NULL
,
2697 * Get the title of the window "hwnd", which is the Vim server name, in
2698 * "name[namelen]" and return the length.
2699 * Returns zero if window "hwnd" is not a Vim server.
2702 getVimServerName(HWND hwnd
, char *name
, int namelen
)
2705 char buffer
[VIM_CLASSNAME_LEN
+ 1];
2707 /* Ignore windows which aren't Vim message windows */
2708 len
= GetClassName(hwnd
, buffer
, sizeof(buffer
));
2709 if (len
!= VIM_CLASSNAME_LEN
|| STRCMP(buffer
, VIM_CLASSNAME
) != 0)
2712 /* Get the title of the window */
2713 return GetWindowText(hwnd
, name
, namelen
);
2716 static BOOL CALLBACK
2717 enumWindowsGetServer(HWND hwnd
, LPARAM lparam
)
2719 struct server_id
*id
= (struct server_id
*)lparam
;
2720 char server
[MAX_PATH
];
2722 /* Get the title of the window */
2723 if (getVimServerName(hwnd
, server
, sizeof(server
)) == 0)
2726 /* If this is the server we're looking for, return its HWND */
2727 if (STRICMP(server
, id
->name
) == 0)
2733 /* Otherwise, keep looking */
2737 static BOOL CALLBACK
2738 enumWindowsGetNames(HWND hwnd
, LPARAM lparam
)
2740 garray_T
*ga
= (garray_T
*)lparam
;
2741 char server
[MAX_PATH
];
2743 /* Get the title of the window */
2744 if (getVimServerName(hwnd
, server
, sizeof(server
)) == 0)
2747 /* Add the name to the list */
2748 ga_concat(ga
, server
);
2749 ga_concat(ga
, "\n");
2754 findServer(char_u
*name
)
2756 struct server_id id
;
2761 EnumWindows(enumWindowsGetServer
, (LPARAM
)(&id
));
2767 serverSetName(char_u
*name
)
2774 /* Leave enough space for a 9-digit suffix to ensure uniqueness! */
2775 ok_name
= alloc((unsigned)STRLEN(name
) + 10);
2777 STRCPY(ok_name
, name
);
2778 p
= ok_name
+ STRLEN(name
);
2782 /* This is inefficient - we're doing an EnumWindows loop for each
2783 * possible name. It would be better to grab all names in one go,
2784 * and scan the list each time...
2786 hwnd
= findServer(ok_name
);
2794 sprintf((char *)p
, "%d", i
);
2801 /* Remember the name */
2802 serverName
= ok_name
;
2804 need_maketitle
= TRUE
; /* update Vim window title later */
2807 /* Update the message window title */
2808 SetWindowText(message_window
, ok_name
);
2811 /* Set the servername variable */
2812 set_vim_var_string(VV_SEND_SERVER
, serverName
, -1);
2818 serverGetVimNames(void)
2822 ga_init2(&ga
, 1, 100);
2824 EnumWindows(enumWindowsGetNames
, (LPARAM
)(&ga
));
2825 ga_append(&ga
, NUL
);
2831 serverSendReply(name
, reply
)
2832 char_u
*name
; /* Where to send. */
2833 char_u
*reply
; /* What to send. */
2836 COPYDATASTRUCT data
;
2839 /* The "name" argument is a magic cookie obtained from expand("<client>").
2840 * It should be of the form 0xXXXXX - i.e. a C hex literal, which is the
2841 * value of the client's message window HWND.
2843 sscanf((char *)name
, "%x", &n
);
2848 if (!IsWindow(target
))
2851 data
.dwData
= COPYDATA_REPLY
;
2852 data
.cbData
= (DWORD
)STRLEN(reply
) + 1;
2853 data
.lpData
= reply
;
2855 serverSendEnc(target
);
2856 if (SendMessage(target
, WM_COPYDATA
, (WPARAM
)message_window
,
2864 serverSendToVim(name
, cmd
, result
, ptarget
, asExpr
, silent
)
2865 char_u
*name
; /* Where to send. */
2866 char_u
*cmd
; /* What to send. */
2867 char_u
**result
; /* Result of eval'ed expression */
2868 void *ptarget
; /* HWND of server */
2869 int asExpr
; /* Expression or keys? */
2870 int silent
; /* don't complain about no server */
2872 HWND target
= findServer(name
);
2873 COPYDATASTRUCT data
;
2874 char_u
*retval
= NULL
;
2880 EMSG2(_(e_noserver
), name
);
2885 *(HWND
*)ptarget
= target
;
2887 data
.dwData
= asExpr
? COPYDATA_EXPR
: COPYDATA_KEYS
;
2888 data
.cbData
= (DWORD
)STRLEN(cmd
) + 1;
2891 serverSendEnc(target
);
2892 if (SendMessage(target
, WM_COPYDATA
, (WPARAM
)message_window
,
2893 (LPARAM
)(&data
)) == 0)
2897 retval
= serverGetReply(target
, &retcode
, TRUE
, TRUE
);
2902 *result
= retval
; /* Caller assumes responsibility for freeing */
2908 * Bring the server to the foreground.
2911 serverForeground(name
)
2914 HWND target
= findServer(name
);
2917 SetForegroundWindow(target
);
2920 /* Replies from server need to be stored until the client picks them up via
2921 * remote_read(). So we maintain a list of server-id/reply pairs.
2922 * Note that there could be multiple replies from one server pending if the
2923 * client is slow picking them up.
2924 * We just store the replies in a simple list. When we remove an entry, we
2925 * move list entries down to fill the gap.
2926 * The server ID is simply the HWND.
2930 HWND server
; /* server window */
2931 char_u
*reply
; /* reply string */
2932 int expr_result
; /* 0 for REPLY, 1 for RESULT 2 for error */
2935 static garray_T reply_list
= {0, 0, sizeof(reply_T
), 5, 0};
2937 #define REPLY_ITEM(i) ((reply_T *)(reply_list.ga_data) + (i))
2938 #define REPLY_COUNT (reply_list.ga_len)
2940 /* Flag which is used to wait for a reply */
2941 static int reply_received
= 0;
2944 * Store a reply. "reply" must be allocated memory (or NULL).
2947 save_reply(HWND server
, char_u
*reply
, int expr
)
2951 if (ga_grow(&reply_list
, 1) == FAIL
)
2954 rep
= REPLY_ITEM(REPLY_COUNT
);
2955 rep
->server
= server
;
2957 rep
->expr_result
= expr
;
2958 if (rep
->reply
== NULL
)
2967 * Get a reply from server "server".
2968 * When "expr_res" is non NULL, get the result of an expression, otherwise a
2969 * server2client() message.
2970 * When non NULL, point to return code. 0 => OK, -1 => ERROR
2971 * If "remove" is TRUE, consume the message, the caller must free it then.
2972 * if "wait" is TRUE block until a message arrives (or the server exits).
2975 serverGetReply(HWND server
, int *expr_res
, int remove
, int wait
)
2981 /* When waiting, loop until the message waiting for is received. */
2984 /* Reset this here, in case a message arrives while we are going
2985 * through the already received messages. */
2988 for (i
= 0; i
< REPLY_COUNT
; ++i
)
2990 rep
= REPLY_ITEM(i
);
2991 if (rep
->server
== server
2992 && ((rep
->expr_result
!= 0) == (expr_res
!= NULL
)))
2994 /* Save the values we've found for later */
2996 if (expr_res
!= NULL
)
2997 *expr_res
= rep
->expr_result
== 1 ? 0 : -1;
3001 /* Move the rest of the list down to fill the gap */
3002 mch_memmove(rep
, rep
+ 1,
3003 (REPLY_COUNT
- i
- 1) * sizeof(reply_T
));
3007 /* Return the reply to the caller, who takes on responsibility
3008 * for freeing it if "remove" is TRUE. */
3013 /* If we got here, we didn't find a reply. Return immediately if the
3014 * "wait" parameter isn't set. */
3018 /* We need to wait for a reply. Enter a message loop until the
3019 * "reply_received" flag gets set. */
3021 /* Loop until we receive a reply */
3022 while (reply_received
== 0)
3024 /* Wait for a SendMessage() call to us. This could be the reply
3025 * we are waiting for. Use a timeout of a second, to catch the
3026 * situation that the server died unexpectedly. */
3027 MsgWaitForMultipleObjects(0, NULL
, TRUE
, 1000, QS_ALLINPUT
);
3029 /* If the server has died, give up */
3030 if (!IsWindow(server
))
3033 serverProcessPendingMessages();
3041 * Process any messages in the Windows message queue.
3044 serverProcessPendingMessages(void)
3048 while (PeekMessage(&msg
, NULL
, 0, 0, PM_REMOVE
))
3050 TranslateMessage(&msg
);
3051 DispatchMessage(&msg
);
3055 #endif /* FEAT_CLIENTSERVER */
3057 #if defined(FEAT_GUI) || (defined(FEAT_PRINTER) && !defined(FEAT_POSTSCRIPT)) \
3066 static struct charset_pair
3069 {"ANSI", ANSI_CHARSET
},
3070 {"CHINESEBIG5", CHINESEBIG5_CHARSET
},
3071 {"DEFAULT", DEFAULT_CHARSET
},
3072 {"HANGEUL", HANGEUL_CHARSET
},
3073 {"OEM", OEM_CHARSET
},
3074 {"SHIFTJIS", SHIFTJIS_CHARSET
},
3075 {"SYMBOL", SYMBOL_CHARSET
},
3077 {"ARABIC", ARABIC_CHARSET
},
3078 {"BALTIC", BALTIC_CHARSET
},
3079 {"EASTEUROPE", EASTEUROPE_CHARSET
},
3080 {"GB2312", GB2312_CHARSET
},
3081 {"GREEK", GREEK_CHARSET
},
3082 {"HEBREW", HEBREW_CHARSET
},
3083 {"JOHAB", JOHAB_CHARSET
},
3084 {"MAC", MAC_CHARSET
},
3085 {"RUSSIAN", RUSSIAN_CHARSET
},
3086 {"THAI", THAI_CHARSET
},
3087 {"TURKISH", TURKISH_CHARSET
},
3088 # if (!defined(_MSC_VER) || (_MSC_VER > 1010)) \
3089 && (!defined(__BORLANDC__) || (__BORLANDC__ > 0x0500))
3090 {"VIETNAMESE", VIETNAMESE_CHARSET
},
3097 * Convert a charset ID to a name.
3098 * Return NULL when not recognized.
3101 charset_id2name(int id
)
3103 struct charset_pair
*cp
;
3105 for (cp
= charset_pairs
; cp
->name
!= NULL
; ++cp
)
3106 if ((BYTE
)id
== cp
->charset
)
3111 static const LOGFONT s_lfDefault
=
3113 -12, 0, 0, 0, FW_NORMAL
, FALSE
, FALSE
, FALSE
, DEFAULT_CHARSET
,
3114 OUT_DEFAULT_PRECIS
, CLIP_DEFAULT_PRECIS
,
3115 PROOF_QUALITY
, FIXED_PITCH
| FF_DONTCARE
,
3116 "Fixedsys" /* see _ReadVimIni */
3119 /* Initialise the "current height" to -12 (same as s_lfDefault) just
3120 * in case the user specifies a font in "guifont" with no size before a font
3121 * with an explicit size has been set. This defaults the size to this value
3122 * (-12 equates to roughly 9pt).
3124 int current_font_height
= -12; /* also used in gui_w48.c */
3126 /* Convert a string representing a point size into pixels. The string should
3127 * be a positive decimal number, with an optional decimal point (eg, "12", or
3128 * "10.5"). The pixel value is returned, and a pointer to the next unconverted
3129 * character is stored in *end. The flag "vertical" says whether this
3130 * calculation is for a vertical (height) size or a horizontal (width) one.
3133 points_to_pixels(char_u
*str
, char_u
**end
, int vertical
, int pprinter_dc
)
3138 HWND hwnd
= (HWND
)0;
3140 HDC printer_dc
= (HDC
)pprinter_dc
;
3144 if (*str
== '.' && divisor
== 0)
3146 /* Start keeping a divisor, for later */
3151 if (!VIM_ISDIGIT(*str
))
3155 points
+= *str
- '0';
3164 if (printer_dc
== NULL
)
3166 hwnd
= GetDesktopWindow();
3167 hdc
= GetWindowDC(hwnd
);
3172 pixels
= MulDiv(points
,
3173 GetDeviceCaps(hdc
, vertical
? LOGPIXELSY
: LOGPIXELSX
),
3176 if (printer_dc
== NULL
)
3177 ReleaseDC(hwnd
, hdc
);
3192 * 0 = terminate now (monospace & ANSI)
3193 * 1 = continue, still no luck...
3194 * 2 = continue, but we have an acceptable LOGFONT
3195 * (monospace, not ANSI)
3196 * We use these values, as EnumFontFamilies returns 1 if the
3197 * callback function is never called. So, we check the return as
3198 * 0 = perfect, 2 = OK, 1 = no good...
3199 * It's not pretty, but it works!
3202 LOGFONT
*lf
= (LOGFONT
*)(lparam
);
3204 #ifndef FEAT_PROPORTIONAL_FONTS
3205 /* Ignore non-monospace fonts without further ado */
3206 if ((ntm
->tmPitchAndFamily
& 1) != 0)
3210 /* Remember this LOGFONT as a "possible" */
3211 *lf
= elf
->elfLogFont
;
3213 /* Terminate the scan as soon as we find an ANSI font */
3214 if (lf
->lfCharSet
== ANSI_CHARSET
3215 || lf
->lfCharSet
== OEM_CHARSET
3216 || lf
->lfCharSet
== DEFAULT_CHARSET
)
3219 /* Continue the scan - we have a non-ANSI font */
3224 init_logfont(LOGFONT
*lf
)
3227 HWND hwnd
= GetDesktopWindow();
3228 HDC hdc
= GetWindowDC(hwnd
);
3230 n
= EnumFontFamilies(hdc
,
3231 (LPCSTR
)lf
->lfFaceName
,
3232 (FONTENUMPROC
)font_enumproc
,
3235 ReleaseDC(hwnd
, hdc
);
3237 /* If we couldn't find a useable font, return failure */
3241 /* Tidy up the rest of the LOGFONT structure. We set to a basic
3242 * font - get_logfont() sets bold, italic, etc based on the user's
3245 lf
->lfHeight
= current_font_height
;
3247 lf
->lfItalic
= FALSE
;
3248 lf
->lfUnderline
= FALSE
;
3249 lf
->lfStrikeOut
= FALSE
;
3250 lf
->lfWeight
= FW_NORMAL
;
3252 /* Return success */
3257 * Get font info from "name" into logfont "lf".
3258 * Return OK for a valid name, FAIL otherwise.
3269 static LOGFONT
*lastlf
= NULL
;
3275 if (STRCMP(name
, "*") == 0)
3277 #if defined(FEAT_GUI_W32)
3279 /* if name is "*", bring up std font dialog: */
3280 memset(&cf
, 0, sizeof(cf
));
3281 cf
.lStructSize
= sizeof(cf
);
3282 cf
.hwndOwner
= s_hwnd
;
3283 cf
.Flags
= CF_SCREENFONTS
| CF_FIXEDPITCHONLY
| CF_INITTOLOGFONTSTRUCT
;
3287 cf
.nFontType
= 0 ; //REGULAR_FONTTYPE;
3288 if (ChooseFont(&cf
))
3296 * Split name up, it could be <name>:h<height>:w<width> etc.
3298 for (p
= name
; *p
&& *p
!= ':'; p
++)
3300 if (p
- name
+ 1 > LF_FACESIZE
)
3301 return FAIL
; /* Name too long */
3302 lf
->lfFaceName
[p
- name
] = *p
;
3305 lf
->lfFaceName
[p
- name
] = NUL
;
3307 /* First set defaults */
3310 lf
->lfWeight
= FW_NORMAL
;
3311 lf
->lfItalic
= FALSE
;
3312 lf
->lfUnderline
= FALSE
;
3313 lf
->lfStrikeOut
= FALSE
;
3316 * If the font can't be found, try replacing '_' by ' '.
3318 if (init_logfont(lf
) == FAIL
)
3320 int did_replace
= FALSE
;
3322 for (i
= 0; lf
->lfFaceName
[i
]; ++i
)
3323 if (lf
->lfFaceName
[i
] == '_')
3325 lf
->lfFaceName
[i
] = ' ';
3328 if (!did_replace
|| init_logfont(lf
) == FAIL
)
3335 /* Set the values found after ':' */
3341 lf
->lfHeight
= - points_to_pixels(p
, &p
, TRUE
, (int)printer_dc
);
3344 lf
->lfWidth
= points_to_pixels(p
, &p
, FALSE
, (int)printer_dc
);
3347 #ifndef MSWIN16_FASTTEXT
3348 lf
->lfWeight
= FW_BOLD
;
3352 #ifndef MSWIN16_FASTTEXT
3353 lf
->lfItalic
= TRUE
;
3357 lf
->lfUnderline
= TRUE
;
3360 lf
->lfStrikeOut
= TRUE
;
3364 struct charset_pair
*cp
;
3366 for (cp
= charset_pairs
; cp
->name
!= NULL
; ++cp
)
3367 if (STRNCMP(p
, cp
->name
, strlen(cp
->name
)) == 0)
3369 lf
->lfCharSet
= cp
->charset
;
3370 p
+= strlen(cp
->name
);
3373 if (cp
->name
== NULL
&& verbose
)
3375 vim_snprintf((char *)IObuff
, IOSIZE
,
3376 _("E244: Illegal charset name \"%s\" in font name \"%s\""), p
, name
);
3385 vim_snprintf((char *)IObuff
, IOSIZE
,
3386 _("E245: Illegal char '%c' in font name \"%s\""),
3396 #if defined(FEAT_GUI_W32)
3399 /* ron: init lastlf */
3400 if (printer_dc
== NULL
)
3403 lastlf
= (LOGFONT
*)alloc(sizeof(LOGFONT
));
3405 mch_memmove(lastlf
, lf
, sizeof(LOGFONT
));
3411 #endif /* defined(FEAT_GUI) || defined(FEAT_PRINTER) */