2 * window.c - the PuTTY(tel) main program, which runs a PuTTY terminal
3 * emulator and backend in a window.
14 #define COMPILE_MULTIMON_STUBS
17 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
33 /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
34 * wParam are used by Windows, and should be masked off, so we shouldn't
35 * attempt to store information in them. Hence all these identifiers have
36 * the low 4 bits clear. Also, identifiers should < 0xF000. */
38 #define IDM_SHOWLOG 0x0010
39 #define IDM_NEWSESS 0x0020
40 #define IDM_DUPSESS 0x0030
41 #define IDM_RESTART 0x0040
42 #define IDM_RECONF 0x0050
43 #define IDM_CLRSB 0x0060
44 #define IDM_RESET 0x0070
45 #define IDM_HELP 0x0140
46 #define IDM_ABOUT 0x0150
47 #define IDM_SAVEDSESS 0x0160
48 #define IDM_COPYALL 0x0170
49 #define IDM_FULLSCREEN 0x0180
50 #define IDM_PASTE 0x0190
51 #define IDM_SPECIALSEP 0x0200
53 #define IDM_SPECIAL_MIN 0x0400
54 #define IDM_SPECIAL_MAX 0x0800
56 #define IDM_SAVED_MIN 0x1000
57 #define IDM_SAVED_MAX 0x5000
58 #define MENU_SAVED_STEP 16
59 /* Maximum number of sessions on saved-session submenu */
60 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
62 #define WM_IGNORE_CLIP (WM_APP + 2)
63 #define WM_FULLSCR_ON_MAX (WM_APP + 3)
64 #define WM_AGENT_CALLBACK (WM_APP + 4)
65 #define WM_GOT_CLIPDATA (WM_APP + 6)
67 /* Needed for Chinese support and apparently not always defined. */
69 #define VK_PROCESSKEY 0xE5
72 /* Mouse wheel support. */
74 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
77 #define WHEEL_DELTA 120
80 /* VK_PACKET, used to send Unicode characters in WM_KEYDOWNs */
82 #define VK_PACKET 0xE7
85 static Mouse_Button translate_button(Mouse_Button button);
86 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
87 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
88 unsigned char *output);
89 static void conftopalette(void);
90 static void systopalette(void);
91 static void init_palette(void);
92 static void init_fonts(int, int);
93 static void another_font(int);
94 static void deinit_fonts(void);
95 static void set_input_locale(HKL);
96 static void update_savedsess_menu(void);
97 static void init_winfuncs(void);
99 static int is_full_screen(void);
100 static void make_full_screen(void);
101 static void clear_full_screen(void);
102 static void flip_full_screen(void);
103 static int process_clipdata(HGLOBAL clipdata, int unicode);
105 /* Window layout information */
106 static void reset_window(int);
107 static int extra_width, extra_height;
108 static int font_width, font_height, font_dualwidth, font_varpitch;
109 static int offset_width, offset_height;
110 static int was_zoomed = 0;
111 static int prev_rows, prev_cols;
113 static void flash_window(int mode);
114 static void sys_cursor_update(void);
115 static int get_fullscreen_rect(RECT * ss);
117 static int caret_x = -1, caret_y = -1;
119 static int kbd_codepage;
122 static Backend *back;
123 static void *backhandle;
125 static struct unicode_data ucsdata;
126 static int session_closed;
127 static int reconfiguring = FALSE;
129 static const struct telnet_special *specials = NULL;
130 static HMENU specials_menu = NULL;
131 static int n_specials = 0;
133 static wchar_t *clipboard_contents;
134 static size_t clipboard_length;
136 #define TIMING_TIMER_ID 1234
137 static long timing_next_time;
142 enum { SYSMENU, CTXMENU };
143 static HMENU savedsess_menu;
145 struct wm_netevent_params {
146 /* Used to pass data to wm_netevent_callback */
151 Conf *conf; /* exported to windlg.c */
153 static void conf_cache_data(void);
157 static struct sesslist sesslist; /* for saved-session menu */
159 struct agent_callback {
160 void (*callback)(void *, void *, int);
166 #define FONT_NORMAL 0
168 #define FONT_UNDERLINE 2
169 #define FONT_BOLDUND 3
170 #define FONT_WIDE 0x04
171 #define FONT_HIGH 0x08
172 #define FONT_NARROW 0x10
174 #define FONT_OEM 0x20
175 #define FONT_OEMBOLD 0x21
176 #define FONT_OEMUND 0x22
177 #define FONT_OEMBOLDUND 0x23
179 #define FONT_MAXNO 0x40
181 static HFONT fonts[FONT_MAXNO];
182 static LOGFONT lfont;
183 static int fontflag[FONT_MAXNO];
185 BOLD_NONE, BOLD_SHADOW, BOLD_FONT
187 static int bold_colours;
193 #define NCFGCOLOURS 22
194 #define NEXTCOLOURS 240
195 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
196 static COLORREF colours[NALLCOLOURS];
198 static LPLOGPALETTE logpal;
199 static RGBTRIPLE defpal[NALLCOLOURS];
201 static HBITMAP caretbm;
203 static int dbltime, lasttime, lastact;
204 static Mouse_Button lastbtn;
206 /* this allows xterm-style mouse handling. */
207 static int send_raw_mouse = 0;
208 static int wheel_accumulator = 0;
210 static int busy_status = BUSY_NOT;
212 static char *window_name, *icon_name;
214 static int compose_state = 0;
216 static UINT wm_mousewheel = WM_MOUSEWHEEL;
218 #define IS_HIGH_VARSEL(wch1, wch2) \
219 ((wch1) == 0xDB40 && ((wch2) >= 0xDD00 && (wch2) <= 0xDDEF))
220 #define IS_LOW_VARSEL(wch) \
221 (((wch) >= 0x180B && (wch) <= 0x180D) || /* MONGOLIAN FREE VARIATION SELECTOR */ \
222 ((wch) >= 0xFE00 && (wch) <= 0xFE0F)) /* VARIATION SELECTOR 1-16 */
224 const int share_can_be_downstream = TRUE;
225 const int share_can_be_upstream = TRUE;
227 /* Dummy routine, only required in plink. */
228 void frontend_echoedit_update(void *frontend, int echo, int edit)
232 int frontend_is_utf8(void *frontend)
234 return ucsdata.line_codepage == CP_UTF8;
237 char *get_ttymode(void *frontend, const char *mode)
239 return term_get_ttymode(term, mode);
242 static void start_backend(void)
245 char msg[1024], *title;
250 * Select protocol. This is farmed out into a table in a
251 * separate file to enable an ssh-free variant.
253 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
255 char *str = dupprintf("%s Internal Error", appname);
256 MessageBox(NULL, "Unsupported protocol number found",
257 str, MB_OK | MB_ICONEXCLAMATION);
262 error = back->init(NULL, &backhandle, conf,
263 conf_get_str(conf, CONF_host),
264 conf_get_int(conf, CONF_port),
266 conf_get_int(conf, CONF_tcp_nodelay),
267 conf_get_int(conf, CONF_tcp_keepalives));
268 back->provide_logctx(backhandle, logctx);
270 char *str = dupprintf("%s Error", appname);
271 sprintf(msg, "Unable to open connection to\n"
272 "%.800s\n" "%s", conf_dest(conf), error);
273 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
277 window_name = icon_name = NULL;
278 title = conf_get_str(conf, CONF_wintitle);
280 sprintf(msg, "%s - %s", realhost, appname);
284 set_title(NULL, title);
285 set_icon(NULL, title);
288 * Connect the terminal to the backend for resize purposes.
290 term_provide_resize_fn(term, back->size, backhandle);
293 * Set up a line discipline.
295 ldisc = ldisc_create(conf, term, back, backhandle, NULL);
298 * Destroy the Restart Session menu item. (This will return
299 * failure if it's already absent, as it will be the very first
300 * time we call this function. We ignore that, because as long
301 * as the menu item ends up not being there, we don't care
302 * whether it was us who removed it or not!)
304 for (i = 0; i < lenof(popup_menus); i++) {
305 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
308 session_closed = FALSE;
311 static void close_session(void *ignored_context)
316 session_closed = TRUE;
317 sprintf(morestuff, "%.70s (inactive)", appname);
318 set_icon(NULL, morestuff);
319 set_title(NULL, morestuff);
326 back->free(backhandle);
329 term_provide_resize_fn(term, NULL, NULL);
330 update_specials_menu(NULL);
334 * Show the Restart Session menu item. Do a precautionary
335 * delete first to ensure we never end up with more than one.
337 for (i = 0; i < lenof(popup_menus); i++) {
338 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
339 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
340 IDM_RESTART, "&Restart Session");
344 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
348 int guess_width, guess_height;
350 dll_hijacking_protection();
354 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
358 InitCommonControls();
360 /* Set Explicit App User Model Id so that jump lists don't cause
361 PuTTY to hang on to removable media. */
363 set_explicit_app_user_model_id();
365 /* Ensure a Maximize setting in Explorer doesn't maximise the
371 char *str = dupprintf("%s Fatal Error", appname);
372 MessageBox(NULL, "Windows refuses to report a version",
373 str, MB_OK | MB_ICONEXCLAMATION);
379 * If we're running a version of Windows that doesn't support
380 * WM_MOUSEWHEEL, find out what message number we should be
383 if (osVersion.dwMajorVersion < 4 ||
384 (osVersion.dwMajorVersion == 4 &&
385 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
386 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
397 hr = CoInitialize(NULL);
398 if (hr != S_OK && hr != S_FALSE) {
399 char *str = dupprintf("%s Fatal Error", appname);
400 MessageBox(NULL, "Failed to initialize COM subsystem",
401 str, MB_OK | MB_ICONEXCLAMATION);
407 * Process the command line.
412 /* By default, we bring up the config dialog, rather than launching
413 * a session. This gets set to TRUE if something happens to change
414 * that (e.g., a hostname is specified on the command-line). */
415 int allow_launch = FALSE;
417 default_protocol = be_default_protocol;
418 /* Find the appropriate default port. */
420 Backend *b = backend_from_proto(default_protocol);
421 default_port = 0; /* illegal */
423 default_port = b->default_port;
425 conf_set_int(conf, CONF_logtype, LGTYP_NONE);
427 do_defaults(NULL, conf);
432 * Process a couple of command-line options which are more
433 * easily dealt with before the line is broken up into words.
434 * These are the old-fashioned but convenient @sessionname and
435 * the internal-use-only &sharedmemoryhandle, plus the &R
436 * prefix for -restrict-acl, all of which are used by PuTTYs
437 * auto-launching each other via System-menu options.
439 while (*p && isspace(*p))
441 if (*p == '&' && p[1] == 'R' &&
442 (!p[2] || p[2] == '@' || p[2] == '&')) {
443 /* &R restrict-acl prefix */
444 restrict_process_acl();
445 restricted_acl = TRUE;
451 * An initial @ means that the whole of the rest of the
452 * command line should be treated as the name of a saved
453 * session, with _no quoting or escaping_. This makes it a
454 * very convenient means of automated saved-session
455 * launching, via IDM_SAVEDSESS or Windows 7 jump lists.
458 while (i > 1 && isspace(p[i - 1]))
461 do_defaults(p + 1, conf);
462 if (!conf_launchable(conf) && !do_config()) {
465 allow_launch = TRUE; /* allow it to be launched directly */
466 } else if (*p == '&') {
468 * An initial & means we've been given a command line
469 * containing the hex value of a HANDLE for a file
470 * mapping object, which we must then interpret as a
476 if (sscanf(p + 1, "%p:%u", &filemap, &cpsize) == 2 &&
477 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
478 0, 0, cpsize)) != NULL) {
479 conf_deserialise(conf, cp, cpsize);
481 CloseHandle(filemap);
482 } else if (!do_config()) {
487 /* Do-nothing case for an empty command line - or rather,
488 * for a command line that's empty _after_ we strip off
492 * Otherwise, break up the command line and deal with
498 split_into_argv(cmdline, &argc, &argv, NULL);
500 for (i = 0; i < argc; i++) {
504 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
507 cmdline_error("option \"%s\" requires an argument", p);
508 } else if (ret == 2) {
509 i++; /* skip next argument */
510 } else if (ret == 1) {
511 continue; /* nothing further needs doing */
512 } else if (!strcmp(p, "-cleanup") ||
513 !strcmp(p, "-cleanup-during-uninstall")) {
515 * `putty -cleanup'. Remove all registry
516 * entries associated with PuTTY, and also find
517 * and delete the random seed file.
520 /* Are we being invoked from an uninstaller? */
521 if (!strcmp(p, "-cleanup-during-uninstall")) {
522 s1 = dupprintf("Remove saved sessions and random seed file?\n"
524 "If you hit Yes, ALL Registry entries associated\n"
525 "with %s will be removed, as well as the\n"
526 "random seed file. THIS PROCESS WILL\n"
527 "DESTROY YOUR SAVED SESSIONS.\n"
528 "(This only affects the currently logged-in user.)\n"
530 "If you hit No, uninstallation will proceed, but\n"
531 "saved sessions etc will be left on the machine.",
533 s2 = dupprintf("%s Uninstallation", appname);
535 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
536 "associated with %s, and will also remove\n"
537 "the random seed file. (This only affects the\n"
538 "currently logged-in user.)\n"
540 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
541 "Are you really sure you want to continue?",
543 s2 = dupprintf("%s Warning", appname);
545 if (message_box(s1, s2,
546 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
547 HELPCTXID(option_cleanup)) == IDYES) {
553 } else if (!strcmp(p, "-pgpfp")) {
556 } else if (*p != '-') {
560 * If we already have a host name, treat
561 * this argument as a port number. NB we
562 * have to treat this as a saved -P
563 * argument, so that it will be deferred
564 * until it's a good moment to run it.
566 int ret = cmdline_process_param("-P", p, 1, conf);
568 } else if (!strncmp(q, "telnet:", 7)) {
570 * If the hostname starts with "telnet:",
571 * set the protocol to Telnet and process
572 * the string as a Telnet URL.
577 if (q[0] == '/' && q[1] == '/')
579 conf_set_int(conf, CONF_protocol, PROT_TELNET);
581 p += host_strcspn(p, ":/");
586 conf_set_int(conf, CONF_port, atoi(p));
588 conf_set_int(conf, CONF_port, -1);
589 conf_set_str(conf, CONF_host, q);
593 * Otherwise, treat this argument as a host
596 while (*p && !isspace(*p))
600 conf_set_str(conf, CONF_host, q);
604 cmdline_error("unknown option \"%s\"", p);
609 cmdline_run_saved(conf);
611 if (loaded_session || got_host)
614 if ((!allow_launch || !conf_launchable(conf)) && !do_config()) {
619 * Muck about with the hostname in various ways.
622 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
623 char *host = hostbuf;
627 * Trim leading whitespace.
629 host += strspn(host, " \t");
632 * See if host is of the form user@host, and separate
633 * out the username if so.
635 if (host[0] != '\0') {
636 char *atsign = strrchr(host, '@');
639 conf_set_str(conf, CONF_username, host);
645 * Trim a colon suffix off the hostname if it's there. In
646 * order to protect unbracketed IPv6 address literals
647 * against this treatment, we do not do this if there's
648 * _more_ than one colon.
651 char *c = host_strchr(host, ':');
654 char *d = host_strchr(c+1, ':');
661 * Remove any remaining whitespace.
666 if (*q != ' ' && *q != '\t')
672 conf_set_str(conf, CONF_host, hostbuf);
681 wndclass.lpfnWndProc = WndProc;
682 wndclass.cbClsExtra = 0;
683 wndclass.cbWndExtra = 0;
684 wndclass.hInstance = inst;
685 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
686 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
687 wndclass.hbrBackground = NULL;
688 wndclass.lpszMenuName = NULL;
689 wndclass.lpszClassName = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
691 RegisterClassW(&wndclass);
694 memset(&ucsdata, 0, sizeof(ucsdata));
701 * Guess some defaults for the window size. This all gets
702 * updated later, so we don't really care too much. However, we
703 * do want the font width/height guesses to correspond to a
704 * large font rather than a small one...
711 guess_width = extra_width + font_width * conf_get_int(conf, CONF_width);
712 guess_height = extra_height + font_height*conf_get_int(conf, CONF_height);
715 get_fullscreen_rect(&r);
716 if (guess_width > r.right - r.left)
717 guess_width = r.right - r.left;
718 if (guess_height > r.bottom - r.top)
719 guess_height = r.bottom - r.top;
723 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
725 wchar_t *uappname = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
726 if (!conf_get_int(conf, CONF_scrollbar))
727 winmode &= ~(WS_VSCROLL);
728 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
729 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
730 if (conf_get_int(conf, CONF_alwaysontop))
731 exwinmode |= WS_EX_TOPMOST;
732 if (conf_get_int(conf, CONF_sunken_edge))
733 exwinmode |= WS_EX_CLIENTEDGE;
734 hwnd = CreateWindowExW(exwinmode, uappname, uappname,
735 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
736 guess_width, guess_height,
737 NULL, NULL, inst, NULL);
742 * Initialise the fonts, simultaneously correcting the guesses
743 * for font_{width,height}.
748 * Initialise the terminal. (We have to do this _after_
749 * creating the window, since the terminal is the first thing
750 * which will call schedule_timer(), which will in turn call
751 * timer_change_notify() which will expect hwnd to exist.)
753 term = term_init(conf, &ucsdata, NULL);
754 logctx = log_init(NULL, conf);
755 term_provide_logctx(term, logctx);
756 term_size(term, conf_get_int(conf, CONF_height),
757 conf_get_int(conf, CONF_width),
758 conf_get_int(conf, CONF_savelines));
761 * Correct the guesses for extra_{width,height}.
765 GetWindowRect(hwnd, &wr);
766 GetClientRect(hwnd, &cr);
767 offset_width = offset_height = conf_get_int(conf, CONF_window_border);
768 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
769 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
773 * Resize the window, now we know what size we _really_ want it
776 guess_width = extra_width + font_width * term->cols;
777 guess_height = extra_height + font_height * term->rows;
778 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
779 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
782 * Set up a caret bitmap, with no content.
786 int size = (font_width + 15) / 16 * 2 * font_height;
787 bits = snewn(size, char);
788 memset(bits, 0, size);
789 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
792 CreateCaret(hwnd, caretbm, font_width, font_height);
795 * Initialise the scroll bar.
800 si.cbSize = sizeof(si);
801 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
803 si.nMax = term->rows - 1;
804 si.nPage = term->rows;
806 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
810 * Prepare the mouse handler.
812 lastact = MA_NOTHING;
813 lastbtn = MBT_NOTHING;
814 dbltime = GetDoubleClickTime();
817 * Set up the session-control options on the system menu.
824 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
825 popup_menus[CTXMENU].menu = CreatePopupMenu();
826 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
828 savedsess_menu = CreateMenu();
829 get_sesslist(&sesslist, TRUE);
830 update_savedsess_menu();
832 for (j = 0; j < lenof(popup_menus); j++) {
833 m = popup_menus[j].menu;
835 AppendMenu(m, MF_SEPARATOR, 0, 0);
836 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
837 AppendMenu(m, MF_SEPARATOR, 0, 0);
838 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
839 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
840 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT_PTR) savedsess_menu,
842 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
843 AppendMenu(m, MF_SEPARATOR, 0, 0);
844 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
845 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
846 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
847 AppendMenu(m, MF_SEPARATOR, 0, 0);
848 AppendMenu(m, (conf_get_int(conf, CONF_resize_action)
849 == RESIZE_DISABLED) ? MF_GRAYED : MF_ENABLED,
850 IDM_FULLSCREEN, "&Full Screen");
851 AppendMenu(m, MF_SEPARATOR, 0, 0);
853 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
854 str = dupprintf("&About %s", appname);
855 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
863 * Set up the initial input locale.
865 set_input_locale(GetKeyboardLayout(0));
868 * Finally show the window!
870 ShowWindow(hwnd, show);
871 SetForegroundWindow(hwnd);
874 * Set the palette up.
880 term_set_focus(term, GetForegroundWindow() == hwnd);
888 if (toplevel_callback_pending() ||
889 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
891 * If we have anything we'd like to do immediately, set
892 * the timeout for MsgWaitForMultipleObjects to zero so
893 * that we'll only do a quick check of our handles and
894 * then get on with whatever that was.
896 * One such option is a pending toplevel callback. The
897 * other is a non-empty Windows message queue, which you'd
898 * think we could leave to MsgWaitForMultipleObjects to
899 * check for us along with all the handles, but in fact we
900 * can't because once PeekMessage in one iteration of this
901 * loop has removed a message from the queue, the whole
902 * queue is considered uninteresting by the next
903 * invocation of MWFMO. So we check ourselves whether the
904 * message queue is non-empty, and if so, set this timeout
905 * to zero to ensure MWFMO doesn't block.
910 /* The messages seem unreliable; especially if we're being tricky */
911 term_set_focus(term, GetForegroundWindow() == hwnd);
914 handles = handle_get_events(&nhandles);
916 n = MsgWaitForMultipleObjects(nhandles, handles, FALSE,
917 timeout, QS_ALLINPUT);
919 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
920 handle_got_event(handles[n - WAIT_OBJECT_0]);
925 while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
926 if (msg.message == WM_QUIT)
927 goto finished; /* two-level break */
929 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
930 DispatchMessageW(&msg);
933 * WM_NETEVENT messages seem to jump ahead of others in
934 * the message queue. I'm not sure why; the docs for
935 * PeekMessage mention that messages are prioritised in
936 * some way, but I'm unclear on which priorities go where.
938 * Anyway, in practice I observe that WM_NETEVENT seems to
939 * jump to the head of the queue, which means that if we
940 * were to only process one message every time round this
941 * loop, we'd get nothing but NETEVENTs if the server
942 * flooded us with data, and stop responding to any other
943 * kind of window message. So instead, we keep on round
944 * this loop until we've consumed at least one message
945 * that _isn't_ a NETEVENT, or run out of messages
946 * completely (whichever comes first). And we don't go to
947 * run_toplevel_callbacks (which is where the netevents
948 * are actually processed, causing fresh NETEVENT messages
949 * to appear) until we've done this.
951 if (msg.message != WM_NETEVENT)
955 run_toplevel_callbacks();
959 cleanup_exit(msg.wParam); /* this doesn't return... */
960 return msg.wParam; /* ... but optimiser doesn't know */
966 void cleanup_exit(int code)
977 if (conf_get_int(conf, CONF_protocol) == PROT_SSH) {
992 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
994 char *do_select(SOCKET skt, int startup)
999 events = (FD_CONNECT | FD_READ | FD_WRITE |
1000 FD_OOB | FD_CLOSE | FD_ACCEPT);
1005 return "do_select(): internal error (hwnd==NULL)";
1006 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
1007 switch (p_WSAGetLastError()) {
1009 return "Network is down";
1011 return "WSAAsyncSelect(): unknown error";
1018 * Refresh the saved-session submenu from `sesslist'.
1020 static void update_savedsess_menu(void)
1023 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
1024 /* skip sesslist.sessions[0] == Default Settings */
1026 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
1027 : MENU_SAVED_MAX+1);
1029 AppendMenu(savedsess_menu, MF_ENABLED,
1030 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
1031 sesslist.sessions[i]);
1032 if (sesslist.nsessions <= 1)
1033 AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)");
1037 * Update the Special Commands submenu.
1039 void update_specials_menu(void *frontend)
1045 specials = back->get_specials(backhandle);
1050 /* We can't use Windows to provide a stack for submenus, so
1051 * here's a lame "stack" that will do for now. */
1052 HMENU saved_menu = NULL;
1054 new_menu = CreatePopupMenu();
1055 for (i = 0; nesting > 0; i++) {
1056 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
1057 switch (specials[i].code) {
1059 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
1062 assert(nesting < 2);
1064 saved_menu = new_menu; /* XXX lame stacking */
1065 new_menu = CreatePopupMenu();
1066 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
1067 (UINT_PTR) new_menu, specials[i].name);
1072 new_menu = saved_menu; /* XXX lame stacking */
1077 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
1082 /* Squirrel the highest special. */
1089 for (j = 0; j < lenof(popup_menus); j++) {
1090 if (specials_menu) {
1091 /* XXX does this free up all submenus? */
1092 DeleteMenu(popup_menus[j].menu, (UINT_PTR)specials_menu,
1094 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
1097 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1098 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
1099 (UINT_PTR) new_menu, "S&pecial Command");
1100 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1101 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
1104 specials_menu = new_menu;
1107 static void update_mouse_pointer(void)
1110 int force_visible = FALSE;
1111 static int forced_visible = FALSE;
1112 switch (busy_status) {
1115 curstype = IDC_ARROW;
1117 curstype = IDC_IBEAM;
1120 curstype = IDC_APPSTARTING; /* this may be an abuse */
1121 force_visible = TRUE;
1124 curstype = IDC_WAIT;
1125 force_visible = TRUE;
1131 HCURSOR cursor = LoadCursor(NULL, curstype);
1132 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1133 SetCursor(cursor); /* force redraw of cursor at current posn */
1135 if (force_visible != forced_visible) {
1136 /* We want some cursor shapes to be visible always.
1137 * Along with show_mouseptr(), this manages the ShowCursor()
1138 * counter such that if we switch back to a non-force_visible
1139 * cursor, the previous visibility state is restored. */
1140 ShowCursor(force_visible);
1141 forced_visible = force_visible;
1145 void set_busy_status(void *frontend, int status)
1147 busy_status = status;
1148 update_mouse_pointer();
1152 * set or clear the "raw mouse message" mode
1154 void set_raw_mouse_mode(void *frontend, int activate)
1156 activate = activate && !conf_get_int(conf, CONF_no_mouse_rep);
1157 send_raw_mouse = activate;
1158 update_mouse_pointer();
1162 * Print a message box and close the connection.
1164 void connection_fatal(void *frontend, const char *fmt, ...)
1167 char *stuff, morestuff[100];
1170 stuff = dupvprintf(fmt, ap);
1172 sprintf(morestuff, "%.70s Fatal Error", appname);
1173 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1176 if (conf_get_int(conf, CONF_close_on_exit) == FORCE_ON)
1179 queue_toplevel_callback(close_session, NULL);
1184 * Report an error at the command-line parsing stage.
1186 void cmdline_error(const char *fmt, ...)
1189 char *stuff, morestuff[100];
1192 stuff = dupvprintf(fmt, ap);
1194 sprintf(morestuff, "%.70s Command Line Error", appname);
1195 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1201 * Actually do the job requested by a WM_NETEVENT
1203 static void wm_netevent_callback(void *vctx)
1205 struct wm_netevent_params *params = (struct wm_netevent_params *)vctx;
1206 select_result(params->wParam, params->lParam);
1211 * Copy the colour palette from the configuration data into defpal.
1212 * This is non-trivial because the colour indices are different.
1214 static void conftopalette(void)
1217 static const int ww[] = {
1218 256, 257, 258, 259, 260, 261,
1219 0, 8, 1, 9, 2, 10, 3, 11,
1220 4, 12, 5, 13, 6, 14, 7, 15
1223 for (i = 0; i < 22; i++) {
1225 defpal[w].rgbtRed = conf_get_int_int(conf, CONF_colours, i*3+0);
1226 defpal[w].rgbtGreen = conf_get_int_int(conf, CONF_colours, i*3+1);
1227 defpal[w].rgbtBlue = conf_get_int_int(conf, CONF_colours, i*3+2);
1229 for (i = 0; i < NEXTCOLOURS; i++) {
1231 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1232 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1233 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1234 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
1236 int shade = i - 216;
1237 shade = shade * 10 + 8;
1238 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1239 defpal[i+16].rgbtBlue = shade;
1243 /* Override with system colours if appropriate */
1244 if (conf_get_int(conf, CONF_system_colour))
1249 * Override bit of defpal with colours from the system.
1250 * (NB that this takes a copy the system colours at the time this is called,
1251 * so subsequent colour scheme changes don't take effect. To fix that we'd
1252 * probably want to be using GetSysColorBrush() and the like.)
1254 static void systopalette(void)
1257 static const struct { int nIndex; int norm; int bold; } or[] =
1259 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1260 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1261 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1262 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1265 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1266 COLORREF colour = GetSysColor(or[i].nIndex);
1267 defpal[or[i].norm].rgbtRed =
1268 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1269 defpal[or[i].norm].rgbtGreen =
1270 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1271 defpal[or[i].norm].rgbtBlue =
1272 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1277 * Set up the colour palette.
1279 static void init_palette(void)
1282 HDC hdc = GetDC(hwnd);
1284 if (conf_get_int(conf, CONF_try_palette) &&
1285 GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1287 * This is a genuine case where we must use smalloc
1288 * because the snew macros can't cope.
1290 logpal = smalloc(sizeof(*logpal)
1291 - sizeof(logpal->palPalEntry)
1292 + NALLCOLOURS * sizeof(PALETTEENTRY));
1293 logpal->palVersion = 0x300;
1294 logpal->palNumEntries = NALLCOLOURS;
1295 for (i = 0; i < NALLCOLOURS; i++) {
1296 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1297 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1298 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1299 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1301 pal = CreatePalette(logpal);
1303 SelectPalette(hdc, pal, FALSE);
1304 RealizePalette(hdc);
1305 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1308 ReleaseDC(hwnd, hdc);
1311 for (i = 0; i < NALLCOLOURS; i++)
1312 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1313 defpal[i].rgbtGreen,
1314 defpal[i].rgbtBlue);
1316 for (i = 0; i < NALLCOLOURS; i++)
1317 colours[i] = RGB(defpal[i].rgbtRed,
1318 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1322 * This is a wrapper to ExtTextOut() to force Windows to display
1323 * the precise glyphs we give it. Otherwise it would do its own
1324 * bidi and Arabic shaping, and we would end up uncertain which
1325 * characters it had put where.
1327 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1328 unsigned short *lpString, UINT cbCount,
1329 CONST INT *lpDx, int opaque)
1333 * The LCC include files apparently don't supply the
1334 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1335 * proper: the differences aren't important to us (the only
1336 * variable-width string parameter is one we don't use anyway).
1342 char *buffer = snewn(cbCount*2+2, char);
1343 char *classbuffer = snewn(cbCount, char);
1344 memset(&gcpr, 0, sizeof(gcpr));
1345 memset(buffer, 0, cbCount*2+2);
1346 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1348 gcpr.lStructSize = sizeof(gcpr);
1349 gcpr.lpGlyphs = (void *)buffer;
1350 gcpr.lpClass = (void *)classbuffer;
1351 gcpr.nGlyphs = cbCount;
1352 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1353 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1355 ExtTextOut(hdc, x, y,
1356 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1357 lprc, buffer, cbCount, lpDx);
1361 * The exact_textout() wrapper, unfortunately, destroys the useful
1362 * Windows `font linking' behaviour: automatic handling of Unicode
1363 * code points not supported in this font by falling back to a font
1364 * which does contain them. Therefore, we adopt a multi-layered
1365 * approach: for any potentially-bidi text, we use exact_textout(),
1366 * and for everything else we use a simple ExtTextOut as we did
1367 * before exact_textout() was introduced.
1369 static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1370 unsigned short *lpString, UINT cbCount,
1371 CONST INT *lpDx, int opaque)
1374 int bkmode = 0, got_bkmode = FALSE;
1378 for (i = 0; i < (int)cbCount ;) {
1379 int rtl = is_rtl(lpString[i]);
1383 for (j = i+1; j < (int)cbCount; j++) {
1384 if (rtl != is_rtl(lpString[j]))
1390 * Now [i,j) indicates a maximal substring of lpString
1391 * which should be displayed using the same textout
1395 exact_textout(hdc, xp, y, lprc, lpString+i, j-i,
1396 font_varpitch ? NULL : lpDx+i, opaque);
1398 ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1399 lprc, lpString+i, j-i,
1400 font_varpitch ? NULL : lpDx+i);
1406 bkmode = GetBkMode(hdc);
1408 SetBkMode(hdc, TRANSPARENT);
1413 SetBkMode(hdc, bkmode);
1416 static int get_font_width(HDC hdc, const TEXTMETRIC *tm)
1419 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1420 if (!(tm->tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1421 ret = tm->tmAveCharWidth;
1425 ABCFLOAT widths[LAST-FIRST + 1];
1428 font_varpitch = TRUE;
1429 font_dualwidth = TRUE;
1430 if (GetCharABCWidthsFloat(hdc, FIRST, LAST, widths)) {
1432 for (j = 0; j < lenof(widths); j++) {
1433 int width = (int)(0.5 + widths[j].abcfA +
1434 widths[j].abcfB + widths[j].abcfC);
1439 ret = tm->tmMaxCharWidth;
1448 * Initialise all the fonts we will need initially. There may be as many as
1449 * three or as few as one. The other (potentially) twenty-one fonts are done
1450 * if/when they are needed.
1454 * - check the font width and height, correcting our guesses if
1457 * - verify that the bold font is the same width as the ordinary
1458 * one, and engage shadow bolding if not.
1460 * - verify that the underlined font is the same width as the
1461 * ordinary one (manual underlining by means of line drawing can
1462 * be done in a pinch).
1464 static void init_fonts(int pick_width, int pick_height)
1473 int fw_dontcare, fw_bold;
1475 for (i = 0; i < FONT_MAXNO; i++)
1478 bold_font_mode = conf_get_int(conf, CONF_bold_style) & 1 ?
1479 BOLD_FONT : BOLD_NONE;
1480 bold_colours = conf_get_int(conf, CONF_bold_style) & 2 ? TRUE : FALSE;
1481 und_mode = UND_FONT;
1483 font = conf_get_fontspec(conf, CONF_font);
1485 fw_dontcare = FW_BOLD;
1488 fw_dontcare = FW_DONTCARE;
1495 font_height = pick_height;
1497 font_height = font->height;
1498 if (font_height > 0) {
1500 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1503 font_width = pick_width;
1505 quality = conf_get_int(conf, CONF_font_quality);
1506 #define f(i,c,w,u) \
1507 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1508 c, OUT_DEFAULT_PRECIS, \
1509 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), \
1510 FIXED_PITCH | FF_DONTCARE, font->name)
1512 f(FONT_NORMAL, font->charset, fw_dontcare, FALSE);
1514 SelectObject(hdc, fonts[FONT_NORMAL]);
1515 GetTextMetrics(hdc, &tm);
1517 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1519 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1520 if (!(tm.tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1521 font_varpitch = FALSE;
1522 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1524 font_varpitch = TRUE;
1525 font_dualwidth = TRUE;
1527 if (pick_width == 0 || pick_height == 0) {
1528 font_height = tm.tmHeight;
1529 font_width = get_font_width(hdc, &tm);
1532 #ifdef RDB_DEBUG_PATCH
1533 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1534 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1539 DWORD cset = tm.tmCharSet;
1540 memset(&info, 0xFF, sizeof(info));
1542 /* !!! Yes the next line is right */
1543 if (cset == OEM_CHARSET)
1544 ucsdata.font_codepage = GetOEMCP();
1546 if (TranslateCharsetInfo ((DWORD *)(ULONG_PTR)cset,
1547 &info, TCI_SRCCHARSET))
1548 ucsdata.font_codepage = info.ciACP;
1550 ucsdata.font_codepage = -1;
1552 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1553 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1556 f(FONT_UNDERLINE, font->charset, fw_dontcare, TRUE);
1559 * Some fonts, e.g. 9-pt Courier, draw their underlines
1560 * outside their character cell. We successfully prevent
1561 * screen corruption by clipping the text output, but then
1562 * we lose the underline completely. Here we try to work
1563 * out whether this is such a font, and if it is, we set a
1564 * flag that causes underlines to be drawn by hand.
1566 * Having tried other more sophisticated approaches (such
1567 * as examining the TEXTMETRIC structure or requesting the
1568 * height of a string), I think we'll do this the brute
1569 * force way: we create a small bitmap, draw an underlined
1570 * space on it, and test to see whether any pixels are
1571 * foreground-coloured. (Since we expect the underline to
1572 * go all the way across the character cell, we only search
1573 * down a single column of the bitmap, half way across.)
1577 HBITMAP und_bm, und_oldbm;
1581 und_dc = CreateCompatibleDC(hdc);
1582 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1583 und_oldbm = SelectObject(und_dc, und_bm);
1584 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1585 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1586 SetTextColor(und_dc, RGB(255, 255, 255));
1587 SetBkColor(und_dc, RGB(0, 0, 0));
1588 SetBkMode(und_dc, OPAQUE);
1589 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1591 for (i = 0; i < font_height; i++) {
1592 c = GetPixel(und_dc, font_width / 2, i);
1593 if (c != RGB(0, 0, 0))
1596 SelectObject(und_dc, und_oldbm);
1597 DeleteObject(und_bm);
1600 und_mode = UND_LINE;
1601 DeleteObject(fonts[FONT_UNDERLINE]);
1602 fonts[FONT_UNDERLINE] = 0;
1606 if (bold_font_mode == BOLD_FONT) {
1607 f(FONT_BOLD, font->charset, fw_bold, FALSE);
1611 descent = tm.tmAscent + 1;
1612 if (descent >= font_height)
1613 descent = font_height - 1;
1615 for (i = 0; i < 3; i++) {
1617 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1618 fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight;
1625 ReleaseDC(hwnd, hdc);
1627 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1628 und_mode = UND_LINE;
1629 DeleteObject(fonts[FONT_UNDERLINE]);
1630 fonts[FONT_UNDERLINE] = 0;
1633 if (bold_font_mode == BOLD_FONT &&
1634 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1635 bold_font_mode = BOLD_SHADOW;
1636 DeleteObject(fonts[FONT_BOLD]);
1637 fonts[FONT_BOLD] = 0;
1639 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1641 init_ucs(conf, &ucsdata);
1644 static void another_font(int fontno)
1647 int fw_dontcare, fw_bold, quality;
1652 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1655 basefont = (fontno & ~(FONT_BOLDUND));
1656 if (basefont != fontno && !fontflag[basefont])
1657 another_font(basefont);
1659 font = conf_get_fontspec(conf, CONF_font);
1662 fw_dontcare = FW_BOLD;
1665 fw_dontcare = FW_DONTCARE;
1675 if (fontno & FONT_WIDE)
1677 if (fontno & FONT_NARROW)
1679 if (fontno & FONT_OEM)
1681 if (fontno & FONT_BOLD)
1683 if (fontno & FONT_UNDERLINE)
1686 quality = conf_get_int(conf, CONF_font_quality);
1689 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1690 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1691 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality),
1692 DEFAULT_PITCH | FF_DONTCARE, s);
1694 fontflag[fontno] = 1;
1697 static void deinit_fonts(void)
1700 for (i = 0; i < FONT_MAXNO; i++) {
1702 DeleteObject(fonts[i]);
1708 void request_resize(void *frontend, int w, int h)
1712 /* If the window is maximized supress resizing attempts */
1713 if (IsZoomed(hwnd)) {
1714 if (conf_get_int(conf, CONF_resize_action) == RESIZE_TERM)
1718 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) return;
1719 if (h == term->rows && w == term->cols) return;
1721 /* Sanity checks ... */
1723 static int first_time = 1;
1726 switch (first_time) {
1728 /* Get the size of the screen */
1729 if (get_fullscreen_rect(&ss))
1730 /* first_time = 0 */ ;
1736 /* Make sure the values are sane */
1737 width = (ss.right - ss.left - extra_width) / 4;
1738 height = (ss.bottom - ss.top - extra_height) / 6;
1740 if (w > width || h > height)
1749 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
1751 if (conf_get_int(conf, CONF_resize_action) != RESIZE_FONT &&
1753 width = extra_width + font_width * w;
1754 height = extra_height + font_height * h;
1756 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1757 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1758 SWP_NOMOVE | SWP_NOZORDER);
1762 InvalidateRect(hwnd, NULL, TRUE);
1765 static void reset_window(int reinit) {
1767 * This function decides how to resize or redraw when the
1768 * user changes something.
1770 * This function doesn't like to change the terminal size but if the
1771 * font size is locked that may be it's only soluion.
1773 int win_width, win_height, resize_action, window_border;
1776 #ifdef RDB_DEBUG_PATCH
1777 debug((27, "reset_window()"));
1780 /* Current window sizes ... */
1781 GetWindowRect(hwnd, &wr);
1782 GetClientRect(hwnd, &cr);
1784 win_width = cr.right - cr.left;
1785 win_height = cr.bottom - cr.top;
1787 resize_action = conf_get_int(conf, CONF_resize_action);
1788 window_border = conf_get_int(conf, CONF_window_border);
1790 if (resize_action == RESIZE_DISABLED)
1793 /* Are we being forced to reload the fonts ? */
1795 #ifdef RDB_DEBUG_PATCH
1796 debug((27, "reset_window() -- Forced deinit"));
1802 /* Oh, looks like we're minimised */
1803 if (win_width == 0 || win_height == 0)
1806 /* Is the window out of position ? */
1808 (offset_width != (win_width-font_width*term->cols)/2 ||
1809 offset_height != (win_height-font_height*term->rows)/2) ){
1810 offset_width = (win_width-font_width*term->cols)/2;
1811 offset_height = (win_height-font_height*term->rows)/2;
1812 InvalidateRect(hwnd, NULL, TRUE);
1813 #ifdef RDB_DEBUG_PATCH
1814 debug((27, "reset_window() -> Reposition terminal"));
1818 if (IsZoomed(hwnd)) {
1819 /* We're fullscreen, this means we must not change the size of
1820 * the window so it's the font size or the terminal itself.
1823 extra_width = wr.right - wr.left - cr.right + cr.left;
1824 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1826 if (resize_action != RESIZE_TERM) {
1827 if (font_width != win_width/term->cols ||
1828 font_height != win_height/term->rows) {
1830 init_fonts(win_width/term->cols, win_height/term->rows);
1831 offset_width = (win_width-font_width*term->cols)/2;
1832 offset_height = (win_height-font_height*term->rows)/2;
1833 InvalidateRect(hwnd, NULL, TRUE);
1834 #ifdef RDB_DEBUG_PATCH
1835 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1836 font_width, font_height));
1840 if (font_width * term->cols != win_width ||
1841 font_height * term->rows != win_height) {
1842 /* Our only choice at this point is to change the
1843 * size of the terminal; Oh well.
1845 term_size(term, win_height/font_height, win_width/font_width,
1846 conf_get_int(conf, CONF_savelines));
1847 offset_width = (win_width-font_width*term->cols)/2;
1848 offset_height = (win_height-font_height*term->rows)/2;
1849 InvalidateRect(hwnd, NULL, TRUE);
1850 #ifdef RDB_DEBUG_PATCH
1851 debug((27, "reset_window() -> Zoomed term_size"));
1858 /* Hmm, a force re-init means we should ignore the current window
1859 * so we resize to the default font size.
1862 #ifdef RDB_DEBUG_PATCH
1863 debug((27, "reset_window() -> Forced re-init"));
1866 offset_width = offset_height = window_border;
1867 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1868 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1870 if (win_width != font_width*term->cols + offset_width*2 ||
1871 win_height != font_height*term->rows + offset_height*2) {
1873 /* If this is too large windows will resize it to the maximum
1874 * allowed window size, we will then be back in here and resize
1875 * the font or terminal to fit.
1877 SetWindowPos(hwnd, NULL, 0, 0,
1878 font_width*term->cols + extra_width,
1879 font_height*term->rows + extra_height,
1880 SWP_NOMOVE | SWP_NOZORDER);
1883 InvalidateRect(hwnd, NULL, TRUE);
1887 /* Okay the user doesn't want us to change the font so we try the
1888 * window. But that may be too big for the screen which forces us
1889 * to change the terminal.
1891 if ((resize_action == RESIZE_TERM && reinit<=0) ||
1892 (resize_action == RESIZE_EITHER && reinit<0) ||
1894 offset_width = offset_height = window_border;
1895 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1896 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1898 if (win_width != font_width*term->cols + offset_width*2 ||
1899 win_height != font_height*term->rows + offset_height*2) {
1904 get_fullscreen_rect(&ss);
1906 width = (ss.right - ss.left - extra_width) / font_width;
1907 height = (ss.bottom - ss.top - extra_height) / font_height;
1910 if ( term->rows > height || term->cols > width ) {
1911 if (resize_action == RESIZE_EITHER) {
1912 /* Make the font the biggest we can */
1913 if (term->cols > width)
1914 font_width = (ss.right - ss.left - extra_width)
1916 if (term->rows > height)
1917 font_height = (ss.bottom - ss.top - extra_height)
1921 init_fonts(font_width, font_height);
1923 width = (ss.right - ss.left - extra_width) / font_width;
1924 height = (ss.bottom - ss.top - extra_height) / font_height;
1926 if ( height > term->rows ) height = term->rows;
1927 if ( width > term->cols ) width = term->cols;
1928 term_size(term, height, width,
1929 conf_get_int(conf, CONF_savelines));
1930 #ifdef RDB_DEBUG_PATCH
1931 debug((27, "reset_window() -> term resize to (%d,%d)",
1937 SetWindowPos(hwnd, NULL, 0, 0,
1938 font_width*term->cols + extra_width,
1939 font_height*term->rows + extra_height,
1940 SWP_NOMOVE | SWP_NOZORDER);
1942 InvalidateRect(hwnd, NULL, TRUE);
1943 #ifdef RDB_DEBUG_PATCH
1944 debug((27, "reset_window() -> window resize to (%d,%d)",
1945 font_width*term->cols + extra_width,
1946 font_height*term->rows + extra_height));
1952 /* We're allowed to or must change the font but do we want to ? */
1954 if (font_width != (win_width-window_border*2)/term->cols ||
1955 font_height != (win_height-window_border*2)/term->rows) {
1958 init_fonts((win_width-window_border*2)/term->cols,
1959 (win_height-window_border*2)/term->rows);
1960 offset_width = (win_width-font_width*term->cols)/2;
1961 offset_height = (win_height-font_height*term->rows)/2;
1963 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1964 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1966 InvalidateRect(hwnd, NULL, TRUE);
1967 #ifdef RDB_DEBUG_PATCH
1968 debug((25, "reset_window() -> font resize to (%d,%d)",
1969 font_width, font_height));
1974 static void set_input_locale(HKL kl)
1978 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1979 lbuf, sizeof(lbuf));
1981 kbd_codepage = atoi(lbuf);
1984 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1986 int thistime = GetMessageTime();
1988 if (send_raw_mouse &&
1989 !(shift && conf_get_int(conf, CONF_mouse_override))) {
1990 lastbtn = MBT_NOTHING;
1991 term_mouse(term, b, translate_button(b), MA_CLICK,
1992 x, y, shift, ctrl, alt);
1996 if (lastbtn == b && thistime - lasttime < dbltime) {
1997 lastact = (lastact == MA_CLICK ? MA_2CLK :
1998 lastact == MA_2CLK ? MA_3CLK :
1999 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
2004 if (lastact != MA_NOTHING)
2005 term_mouse(term, b, translate_button(b), lastact,
2006 x, y, shift, ctrl, alt);
2007 lasttime = thistime;
2011 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
2012 * into a cooked one (SELECT, EXTEND, PASTE).
2014 static Mouse_Button translate_button(Mouse_Button button)
2016 if (button == MBT_LEFT)
2018 if (button == MBT_MIDDLE)
2019 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2020 MBT_PASTE : MBT_EXTEND;
2021 if (button == MBT_RIGHT)
2022 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2023 MBT_EXTEND : MBT_PASTE;
2024 return 0; /* shouldn't happen */
2027 static void show_mouseptr(int show)
2029 /* NB that the counter in ShowCursor() is also frobbed by
2030 * update_mouse_pointer() */
2031 static int cursor_visible = 1;
2032 if (!conf_get_int(conf, CONF_hide_mouseptr))
2033 show = 1; /* override if this feature disabled */
2034 if (cursor_visible && !show)
2036 else if (!cursor_visible && show)
2038 cursor_visible = show;
2041 static int is_alt_pressed(void)
2044 int r = GetKeyboardState(keystate);
2047 if (keystate[VK_MENU] & 0x80)
2049 if (keystate[VK_RMENU] & 0x80)
2054 static int resizing;
2056 void notify_remote_exit(void *fe)
2058 int exitcode, close_on_exit;
2060 if (!session_closed &&
2061 (exitcode = back->exitcode(backhandle)) >= 0) {
2062 close_on_exit = conf_get_int(conf, CONF_close_on_exit);
2063 /* Abnormal exits will already have set session_closed and taken
2064 * appropriate action. */
2065 if (close_on_exit == FORCE_ON ||
2066 (close_on_exit == AUTO && exitcode != INT_MAX)) {
2069 queue_toplevel_callback(close_session, NULL);
2070 session_closed = TRUE;
2071 /* exitcode == INT_MAX indicates that the connection was closed
2072 * by a fatal error, so an error box will be coming our way and
2073 * we should not generate this informational one. */
2074 if (exitcode != INT_MAX)
2075 MessageBox(hwnd, "Connection closed by remote host",
2076 appname, MB_OK | MB_ICONINFORMATION);
2081 void timer_change_notify(unsigned long next)
2083 unsigned long now = GETTICKCOUNT();
2085 if (now - next < INT_MAX)
2089 KillTimer(hwnd, TIMING_TIMER_ID);
2090 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
2091 timing_next_time = next;
2094 static void conf_cache_data(void)
2096 /* Cache some items from conf to speed lookups in very hot code */
2097 cursor_type = conf_get_int(conf, CONF_cursor_type);
2098 vtmode = conf_get_int(conf, CONF_vtmode);
2101 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2102 WPARAM wParam, LPARAM lParam)
2105 static int ignore_clip = FALSE;
2106 static int need_backend_resize = FALSE;
2107 static int fullscr_on_max = FALSE;
2108 static int processed_resize = FALSE;
2109 static UINT last_mousemove = 0;
2114 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
2117 KillTimer(hwnd, TIMING_TIMER_ID);
2118 if (run_timers(timing_next_time, &next)) {
2119 timer_change_notify(next);
2130 str = dupprintf("%s Exit Confirmation", appname);
2131 if (session_closed || !conf_get_int(conf, CONF_warn_on_close) ||
2133 "Are you sure you want to close this session?",
2134 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
2136 DestroyWindow(hwnd);
2144 case WM_INITMENUPOPUP:
2145 if ((HMENU)wParam == savedsess_menu) {
2146 /* About to pop up Saved Sessions sub-menu.
2147 * Refresh the session list. */
2148 get_sesslist(&sesslist, FALSE); /* free */
2149 get_sesslist(&sesslist, TRUE);
2150 update_savedsess_menu();
2156 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
2166 const char *argprefix;
2167 BOOL inherit_handles;
2169 PROCESS_INFORMATION pi;
2170 HANDLE filemap = NULL;
2177 if (wParam == IDM_DUPSESS) {
2179 * Allocate a file-mapping memory chunk for the
2182 SECURITY_ATTRIBUTES sa;
2186 size = conf_serialised_size(conf);
2188 sa.nLength = sizeof(sa);
2189 sa.lpSecurityDescriptor = NULL;
2190 sa.bInheritHandle = TRUE;
2191 filemap = CreateFileMapping(INVALID_HANDLE_VALUE,
2195 if (filemap && filemap != INVALID_HANDLE_VALUE) {
2196 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, size);
2198 conf_serialise(conf, p);
2202 inherit_handles = TRUE;
2203 cl = dupprintf("putty %s&%p:%u", argprefix,
2204 filemap, (unsigned)size);
2205 } else if (wParam == IDM_SAVEDSESS) {
2206 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
2207 / MENU_SAVED_STEP) + 1;
2208 if (sessno < (unsigned)sesslist.nsessions) {
2209 const char *session = sesslist.sessions[sessno];
2210 cl = dupprintf("putty %s@%s", argprefix, session);
2211 inherit_handles = FALSE;
2214 } else /* IDM_NEWSESS */ {
2215 cl = dupprintf("putty%s%s",
2216 *argprefix ? " " : "",
2218 inherit_handles = FALSE;
2221 GetModuleFileName(NULL, b, sizeof(b) - 1);
2223 si.lpReserved = NULL;
2224 si.lpDesktop = NULL;
2228 si.lpReserved2 = NULL;
2229 CreateProcess(b, cl, NULL, NULL, inherit_handles,
2230 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
2231 CloseHandle(pi.hProcess);
2232 CloseHandle(pi.hThread);
2235 CloseHandle(filemap);
2241 logevent(NULL, "----- Session restarted -----");
2242 term_pwron(term, FALSE);
2251 int reconfig_result;
2256 reconfiguring = TRUE;
2259 * Copy the current window title into the stored
2260 * previous configuration, so that doing nothing to
2261 * the window title field in the config box doesn't
2262 * reset the title to its startup state.
2264 conf_set_str(conf, CONF_wintitle, window_name);
2266 prev_conf = conf_copy(conf);
2269 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2270 reconfiguring = FALSE;
2271 if (!reconfig_result) {
2272 conf_free(prev_conf);
2278 resize_action = conf_get_int(conf, CONF_resize_action);
2280 /* Disable full-screen if resizing forbidden */
2282 for (i = 0; i < lenof(popup_menus); i++)
2283 EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN,
2285 (resize_action == RESIZE_DISABLED)
2286 ? MF_GRAYED : MF_ENABLED);
2287 /* Gracefully unzoom if necessary */
2288 if (IsZoomed(hwnd) && (resize_action == RESIZE_DISABLED))
2289 ShowWindow(hwnd, SW_RESTORE);
2292 /* Pass new config data to the logging module */
2293 log_reconfig(logctx, conf);
2297 * Flush the line discipline's edit buffer in the
2298 * case where local editing has just been disabled.
2301 ldisc_configure(ldisc, conf);
2302 ldisc_echoedit_update(ldisc);
2311 /* Pass new config data to the terminal */
2312 term_reconfig(term, conf);
2314 /* Pass new config data to the back end */
2316 back->reconfig(backhandle, conf);
2318 /* Screen size changed ? */
2319 if (conf_get_int(conf, CONF_height) !=
2320 conf_get_int(prev_conf, CONF_height) ||
2321 conf_get_int(conf, CONF_width) !=
2322 conf_get_int(prev_conf, CONF_width) ||
2323 conf_get_int(conf, CONF_savelines) !=
2324 conf_get_int(prev_conf, CONF_savelines) ||
2325 resize_action == RESIZE_FONT ||
2326 (resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2327 resize_action == RESIZE_DISABLED)
2328 term_size(term, conf_get_int(conf, CONF_height),
2329 conf_get_int(conf, CONF_width),
2330 conf_get_int(conf, CONF_savelines));
2332 /* Enable or disable the scroll bar, etc */
2334 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2335 LONG nexflag, exflag =
2336 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2339 if (conf_get_int(conf, CONF_alwaysontop) !=
2340 conf_get_int(prev_conf, CONF_alwaysontop)) {
2341 if (conf_get_int(conf, CONF_alwaysontop)) {
2342 nexflag |= WS_EX_TOPMOST;
2343 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2344 SWP_NOMOVE | SWP_NOSIZE);
2346 nexflag &= ~(WS_EX_TOPMOST);
2347 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2348 SWP_NOMOVE | SWP_NOSIZE);
2351 if (conf_get_int(conf, CONF_sunken_edge))
2352 nexflag |= WS_EX_CLIENTEDGE;
2354 nexflag &= ~(WS_EX_CLIENTEDGE);
2357 if (conf_get_int(conf, is_full_screen() ?
2358 CONF_scrollbar_in_fullscreen :
2362 nflg &= ~WS_VSCROLL;
2364 if (resize_action == RESIZE_DISABLED ||
2366 nflg &= ~WS_THICKFRAME;
2368 nflg |= WS_THICKFRAME;
2370 if (resize_action == RESIZE_DISABLED)
2371 nflg &= ~WS_MAXIMIZEBOX;
2373 nflg |= WS_MAXIMIZEBOX;
2375 if (nflg != flag || nexflag != exflag) {
2377 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2378 if (nexflag != exflag)
2379 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2381 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2382 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2383 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2391 if (resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2396 set_title(NULL, conf_get_str(conf, CONF_wintitle));
2397 if (IsIconic(hwnd)) {
2399 conf_get_int(conf, CONF_win_name_always) ?
2400 window_name : icon_name);
2404 FontSpec *font = conf_get_fontspec(conf, CONF_font);
2405 FontSpec *prev_font = conf_get_fontspec(prev_conf,
2408 if (!strcmp(font->name, prev_font->name) ||
2409 !strcmp(conf_get_str(conf, CONF_line_codepage),
2410 conf_get_str(prev_conf, CONF_line_codepage)) ||
2411 font->isbold != prev_font->isbold ||
2412 font->height != prev_font->height ||
2413 font->charset != prev_font->charset ||
2414 conf_get_int(conf, CONF_font_quality) !=
2415 conf_get_int(prev_conf, CONF_font_quality) ||
2416 conf_get_int(conf, CONF_vtmode) !=
2417 conf_get_int(prev_conf, CONF_vtmode) ||
2418 conf_get_int(conf, CONF_bold_style) !=
2419 conf_get_int(prev_conf, CONF_bold_style) ||
2420 resize_action == RESIZE_DISABLED ||
2421 resize_action == RESIZE_EITHER ||
2422 resize_action != conf_get_int(prev_conf,
2423 CONF_resize_action))
2427 InvalidateRect(hwnd, NULL, TRUE);
2428 reset_window(init_lvl);
2430 conf_free(prev_conf);
2437 request_paste(NULL);
2443 term_pwron(term, TRUE);
2445 ldisc_echoedit_update(ldisc);
2451 launch_help(hwnd, NULL);
2455 * We get this if the System menu has been activated
2462 * We get this if the System menu has been activated
2463 * using the keyboard. This might happen from within
2464 * TranslateKey, in which case it really wants to be
2465 * followed by a `space' character to actually _bring
2466 * the menu up_ rather than just sitting there in
2467 * `ready to appear' state.
2469 show_mouseptr(1); /* make sure pointer is visible */
2471 PostMessage(hwnd, WM_CHAR, ' ', 0);
2473 case IDM_FULLSCREEN:
2477 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2478 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2480 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2481 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2483 * Ensure we haven't been sent a bogus SYSCOMMAND
2484 * which would cause us to reference invalid memory
2485 * and crash. Perhaps I'm just too paranoid here.
2487 if (i >= n_specials)
2490 back->special(backhandle, specials[i].code);
2495 #define X_POS(l) ((int)(short)LOWORD(l))
2496 #define Y_POS(l) ((int)(short)HIWORD(l))
2498 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2499 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2500 case WM_LBUTTONDOWN:
2501 case WM_MBUTTONDOWN:
2502 case WM_RBUTTONDOWN:
2506 if (message == WM_RBUTTONDOWN &&
2507 ((wParam & MK_CONTROL) ||
2508 (conf_get_int(conf, CONF_mouse_is_xterm) == 2))) {
2511 show_mouseptr(1); /* make sure pointer is visible */
2512 GetCursorPos(&cursorpos);
2513 TrackPopupMenu(popup_menus[CTXMENU].menu,
2514 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2515 cursorpos.x, cursorpos.y,
2523 case WM_LBUTTONDOWN:
2525 wParam |= MK_LBUTTON;
2528 case WM_MBUTTONDOWN:
2529 button = MBT_MIDDLE;
2530 wParam |= MK_MBUTTON;
2533 case WM_RBUTTONDOWN:
2535 wParam |= MK_RBUTTON;
2540 wParam &= ~MK_LBUTTON;
2544 button = MBT_MIDDLE;
2545 wParam &= ~MK_MBUTTON;
2550 wParam &= ~MK_RBUTTON;
2554 button = press = 0; /* shouldn't happen */
2558 * Special case: in full-screen mode, if the left
2559 * button is clicked in the very top left corner of the
2560 * window, we put up the System menu instead of doing
2564 char mouse_on_hotspot = 0;
2573 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2576 mi.cbSize = sizeof(MONITORINFO);
2577 GetMonitorInfo(mon, &mi);
2579 if (mi.rcMonitor.left == pt.x &&
2580 mi.rcMonitor.top == pt.y) {
2581 mouse_on_hotspot = 1;
2586 if (pt.x == 0 && pt.y == 0) {
2587 mouse_on_hotspot = 1;
2590 if (is_full_screen() && press &&
2591 button == MBT_LEFT && mouse_on_hotspot) {
2592 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2593 MAKELPARAM(pt.x, pt.y));
2600 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2601 wParam & MK_SHIFT, wParam & MK_CONTROL,
2605 term_mouse(term, button, translate_button(button), MA_RELEASE,
2606 TO_CHR_X(X_POS(lParam)),
2607 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2608 wParam & MK_CONTROL, is_alt_pressed());
2609 if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)))
2617 * Windows seems to like to occasionally send MOUSEMOVE
2618 * events even if the mouse hasn't moved. Don't unhide
2619 * the mouse pointer in this case.
2621 static WPARAM wp = 0;
2622 static LPARAM lp = 0;
2623 if (wParam != wp || lParam != lp ||
2624 last_mousemove != WM_MOUSEMOVE) {
2626 wp = wParam; lp = lParam;
2627 last_mousemove = WM_MOUSEMOVE;
2631 * Add the mouse position and message time to the random
2634 noise_ultralight(lParam);
2636 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2637 GetCapture() == hwnd) {
2639 if (wParam & MK_LBUTTON)
2641 else if (wParam & MK_MBUTTON)
2645 term_mouse(term, b, translate_button(b), MA_DRAG,
2646 TO_CHR_X(X_POS(lParam)),
2647 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2648 wParam & MK_CONTROL, is_alt_pressed());
2651 case WM_NCMOUSEMOVE:
2653 static WPARAM wp = 0;
2654 static LPARAM lp = 0;
2655 if (wParam != wp || lParam != lp ||
2656 last_mousemove != WM_NCMOUSEMOVE) {
2658 wp = wParam; lp = lParam;
2659 last_mousemove = WM_NCMOUSEMOVE;
2662 noise_ultralight(lParam);
2664 case WM_IGNORE_CLIP:
2665 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2667 case WM_DESTROYCLIPBOARD:
2669 term_deselect(term);
2670 ignore_clip = FALSE;
2677 hdc = BeginPaint(hwnd, &p);
2679 SelectPalette(hdc, pal, TRUE);
2680 RealizePalette(hdc);
2684 * We have to be careful about term_paint(). It will
2685 * set a bunch of character cells to INVALID and then
2686 * call do_paint(), which will redraw those cells and
2687 * _then mark them as done_. This may not be accurate:
2688 * when painting in WM_PAINT context we are restricted
2689 * to the rectangle which has just been exposed - so if
2690 * that only covers _part_ of a character cell and the
2691 * rest of it was already visible, that remainder will
2692 * not be redrawn at all. Accordingly, we must not
2693 * paint any character cell in a WM_PAINT context which
2694 * already has a pending update due to terminal output.
2695 * The simplest solution to this - and many, many
2696 * thanks to Hung-Te Lin for working all this out - is
2697 * not to do any actual painting at _all_ if there's a
2698 * pending terminal update: just mark the relevant
2699 * character cells as INVALID and wait for the
2700 * scheduled full update to sort it out.
2702 * I have a suspicion this isn't the _right_ solution.
2703 * An alternative approach would be to have terminal.c
2704 * separately track what _should_ be on the terminal
2705 * screen and what _is_ on the terminal screen, and
2706 * have two completely different types of redraw (one
2707 * for full updates, which syncs the former with the
2708 * terminal itself, and one for WM_PAINT which syncs
2709 * the latter with the former); yet another possibility
2710 * would be to have the Windows front end do what the
2711 * GTK one already does, and maintain a bitmap of the
2712 * current terminal appearance so that WM_PAINT becomes
2713 * completely trivial. However, this should do for now.
2715 term_paint(term, hdc,
2716 (p.rcPaint.left-offset_width)/font_width,
2717 (p.rcPaint.top-offset_height)/font_height,
2718 (p.rcPaint.right-offset_width-1)/font_width,
2719 (p.rcPaint.bottom-offset_height-1)/font_height,
2720 !term->window_update_pending);
2723 p.rcPaint.left < offset_width ||
2724 p.rcPaint.top < offset_height ||
2725 p.rcPaint.right >= offset_width + font_width*term->cols ||
2726 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2728 HBRUSH fillcolour, oldbrush;
2730 fillcolour = CreateSolidBrush (
2731 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2732 oldbrush = SelectObject(hdc, fillcolour);
2733 edge = CreatePen(PS_SOLID, 0,
2734 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2735 oldpen = SelectObject(hdc, edge);
2738 * Jordan Russell reports that this apparently
2739 * ineffectual IntersectClipRect() call masks a
2740 * Windows NT/2K bug causing strange display
2741 * problems when the PuTTY window is taller than
2742 * the primary monitor. It seems harmless enough...
2744 IntersectClipRect(hdc,
2745 p.rcPaint.left, p.rcPaint.top,
2746 p.rcPaint.right, p.rcPaint.bottom);
2748 ExcludeClipRect(hdc,
2749 offset_width, offset_height,
2750 offset_width+font_width*term->cols,
2751 offset_height+font_height*term->rows);
2753 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2754 p.rcPaint.right, p.rcPaint.bottom);
2756 /* SelectClipRgn(hdc, NULL); */
2758 SelectObject(hdc, oldbrush);
2759 DeleteObject(fillcolour);
2760 SelectObject(hdc, oldpen);
2763 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2764 SelectObject(hdc, GetStockObject(WHITE_PEN));
2772 * To protect against re-entrancy when Windows's recv()
2773 * immediately triggers a new WSAAsyncSelect window
2774 * message, we don't call select_result directly from this
2775 * handler but instead wait until we're back out at the
2776 * top level of the message loop.
2778 struct wm_netevent_params *params =
2779 snew(struct wm_netevent_params);
2780 params->wParam = wParam;
2781 params->lParam = lParam;
2782 queue_toplevel_callback(wm_netevent_callback, params);
2786 term_set_focus(term, TRUE);
2787 CreateCaret(hwnd, caretbm, font_width, font_height);
2789 flash_window(0); /* stop */
2795 term_set_focus(term, FALSE);
2797 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2800 case WM_ENTERSIZEMOVE:
2801 #ifdef RDB_DEBUG_PATCH
2802 debug((27, "WM_ENTERSIZEMOVE"));
2806 need_backend_resize = FALSE;
2808 case WM_EXITSIZEMOVE:
2811 #ifdef RDB_DEBUG_PATCH
2812 debug((27, "WM_EXITSIZEMOVE"));
2814 if (need_backend_resize) {
2815 term_size(term, conf_get_int(conf, CONF_height),
2816 conf_get_int(conf, CONF_width),
2817 conf_get_int(conf, CONF_savelines));
2818 InvalidateRect(hwnd, NULL, TRUE);
2823 * This does two jobs:
2824 * 1) Keep the sizetip uptodate
2825 * 2) Make sure the window size is _stepped_ in units of the font size.
2827 resize_action = conf_get_int(conf, CONF_resize_action);
2828 if (resize_action == RESIZE_TERM ||
2829 (resize_action == RESIZE_EITHER && !is_alt_pressed())) {
2830 int width, height, w, h, ew, eh;
2831 LPRECT r = (LPRECT) lParam;
2833 if (!need_backend_resize && resize_action == RESIZE_EITHER &&
2834 (conf_get_int(conf, CONF_height) != term->rows ||
2835 conf_get_int(conf, CONF_width) != term->cols)) {
2837 * Great! It seems that both the terminal size and the
2838 * font size have been changed and the user is now dragging.
2840 * It will now be difficult to get back to the configured
2843 * This would be easier but it seems to be too confusing.
2845 conf_set_int(conf, CONF_height, term->rows);
2846 conf_set_int(conf, CONF_width, term->cols);
2848 InvalidateRect(hwnd, NULL, TRUE);
2849 need_backend_resize = TRUE;
2852 width = r->right - r->left - extra_width;
2853 height = r->bottom - r->top - extra_height;
2854 w = (width + font_width / 2) / font_width;
2857 h = (height + font_height / 2) / font_height;
2860 UpdateSizeTip(hwnd, w, h);
2861 ew = width - w * font_width;
2862 eh = height - h * font_height;
2864 if (wParam == WMSZ_LEFT ||
2865 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2871 if (wParam == WMSZ_TOP ||
2872 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2882 int width, height, w, h, rv = 0;
2883 int window_border = conf_get_int(conf, CONF_window_border);
2884 int ex_width = extra_width + (window_border - offset_width) * 2;
2885 int ex_height = extra_height + (window_border - offset_height) * 2;
2886 LPRECT r = (LPRECT) lParam;
2888 width = r->right - r->left - ex_width;
2889 height = r->bottom - r->top - ex_height;
2891 w = (width + term->cols/2)/term->cols;
2892 h = (height + term->rows/2)/term->rows;
2893 if ( r->right != r->left + w*term->cols + ex_width)
2896 if (wParam == WMSZ_LEFT ||
2897 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2898 r->left = r->right - w*term->cols - ex_width;
2900 r->right = r->left + w*term->cols + ex_width;
2902 if (r->bottom != r->top + h*term->rows + ex_height)
2905 if (wParam == WMSZ_TOP ||
2906 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2907 r->top = r->bottom - h*term->rows - ex_height;
2909 r->bottom = r->top + h*term->rows + ex_height;
2913 /* break; (never reached) */
2914 case WM_FULLSCR_ON_MAX:
2915 fullscr_on_max = TRUE;
2918 sys_cursor_update();
2921 resize_action = conf_get_int(conf, CONF_resize_action);
2922 #ifdef RDB_DEBUG_PATCH
2923 debug((27, "WM_SIZE %s (%d,%d)",
2924 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2925 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2926 (wParam == SIZE_RESTORED && resizing) ? "to":
2927 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2929 LOWORD(lParam), HIWORD(lParam)));
2931 if (wParam == SIZE_MINIMIZED)
2933 conf_get_int(conf, CONF_win_name_always) ?
2934 window_name : icon_name);
2935 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2936 SetWindowText(hwnd, window_name);
2937 if (wParam == SIZE_RESTORED) {
2938 processed_resize = FALSE;
2939 clear_full_screen();
2940 if (processed_resize) {
2942 * Inhibit normal processing of this WM_SIZE; a
2943 * secondary one was triggered just now by
2944 * clear_full_screen which contained the correct
2950 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2951 fullscr_on_max = FALSE;
2952 processed_resize = FALSE;
2954 if (processed_resize) {
2956 * Inhibit normal processing of this WM_SIZE; a
2957 * secondary one was triggered just now by
2958 * make_full_screen which contained the correct client
2965 processed_resize = TRUE;
2967 if (resize_action == RESIZE_DISABLED) {
2968 /* A resize, well it better be a minimize. */
2972 int width, height, w, h;
2973 int window_border = conf_get_int(conf, CONF_window_border);
2975 width = LOWORD(lParam);
2976 height = HIWORD(lParam);
2978 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2980 prev_rows = term->rows;
2981 prev_cols = term->cols;
2982 if (resize_action == RESIZE_TERM) {
2983 w = width / font_width;
2985 h = height / font_height;
2990 * As below, if we're in the middle of an
2991 * interactive resize we don't call
2992 * back->size. In Windows 7, this case can
2993 * arise in maximisation as well via the Aero
2996 need_backend_resize = TRUE;
2997 conf_set_int(conf, CONF_height, h);
2998 conf_set_int(conf, CONF_width, w);
3000 term_size(term, h, w,
3001 conf_get_int(conf, CONF_savelines));
3005 } else if (wParam == SIZE_RESTORED && was_zoomed) {
3007 if (resize_action == RESIZE_TERM) {
3008 w = (width-window_border*2) / font_width;
3010 h = (height-window_border*2) / font_height;
3012 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
3014 } else if (resize_action != RESIZE_FONT)
3018 } else if (wParam == SIZE_MINIMIZED) {
3020 } else if (resize_action == RESIZE_TERM ||
3021 (resize_action == RESIZE_EITHER &&
3022 !is_alt_pressed())) {
3023 w = (width-window_border*2) / font_width;
3025 h = (height-window_border*2) / font_height;
3030 * Don't call back->size in mid-resize. (To
3031 * prevent massive numbers of resize events
3032 * getting sent down the connection during an NT
3035 need_backend_resize = TRUE;
3036 conf_set_int(conf, CONF_height, h);
3037 conf_set_int(conf, CONF_width, w);
3039 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
3045 sys_cursor_update();
3048 switch (LOWORD(wParam)) {
3050 term_scroll(term, -1, 0);
3053 term_scroll(term, +1, 0);
3056 term_scroll(term, 0, +1);
3059 term_scroll(term, 0, -1);
3062 term_scroll(term, 0, +term->rows / 2);
3065 term_scroll(term, 0, -term->rows / 2);
3067 case SB_THUMBPOSITION:
3070 * Use GetScrollInfo instead of HIWORD(wParam) to get
3071 * 32-bit scroll position.
3076 si.cbSize = sizeof(si);
3077 si.fMask = SIF_TRACKPOS;
3078 if (GetScrollInfo(hwnd, SB_VERT, &si) == 0)
3079 si.nTrackPos = HIWORD(wParam);
3080 term_scroll(term, 1, si.nTrackPos);
3085 case WM_PALETTECHANGED:
3086 if ((HWND) wParam != hwnd && pal != NULL) {
3087 HDC hdc = get_ctx(NULL);
3089 if (RealizePalette(hdc) > 0)
3095 case WM_QUERYNEWPALETTE:
3097 HDC hdc = get_ctx(NULL);
3099 if (RealizePalette(hdc) > 0)
3111 * Add the scan code and keypress timing to the random
3114 noise_ultralight(lParam);
3117 * We don't do TranslateMessage since it disassociates the
3118 * resulting CHAR message from the KEYDOWN that sparked it,
3119 * which we occasionally don't want. Instead, we process
3120 * KEYDOWN, and call the Win32 translator functions so that
3121 * we get the translations under _our_ control.
3124 unsigned char buf[20];
3127 if (wParam == VK_PROCESSKEY || /* IME PROCESS key */
3128 wParam == VK_PACKET) { /* 'this key is a Unicode char' */
3129 if (message == WM_KEYDOWN) {
3132 m.message = WM_KEYDOWN;
3134 m.lParam = lParam & 0xdfff;
3135 TranslateMessage(&m);
3136 } else break; /* pass to Windows for default processing */
3138 len = TranslateKey(message, wParam, lParam, buf);
3140 return DefWindowProcW(hwnd, message, wParam, lParam);
3144 * We need not bother about stdin backlogs
3145 * here, because in GUI PuTTY we can't do
3146 * anything about it anyway; there's no means
3147 * of asking Windows to hold off on KEYDOWN
3148 * messages. We _have_ to buffer everything
3151 term_seen_key_event(term);
3153 ldisc_send(ldisc, (char *)buf, len, 1);
3159 case WM_INPUTLANGCHANGE:
3160 /* wParam == Font number */
3161 /* lParam == Locale */
3162 set_input_locale((HKL)lParam);
3163 sys_cursor_update();
3165 case WM_IME_STARTCOMPOSITION:
3167 HIMC hImc = ImmGetContext(hwnd);
3168 ImmSetCompositionFont(hImc, &lfont);
3169 ImmReleaseContext(hwnd, hImc);
3172 case WM_IME_COMPOSITION:
3178 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
3179 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
3181 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
3182 break; /* fall back to DefWindowProc */
3184 hIMC = ImmGetContext(hwnd);
3185 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3189 buff = snewn(n, char);
3190 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
3192 * Jaeyoun Chung reports that Korean character
3193 * input doesn't work correctly if we do a single
3194 * luni_send() covering the whole of buff. So
3195 * instead we luni_send the characters one by one.
3197 term_seen_key_event(term);
3198 /* don't divide SURROGATE PAIR */
3200 for (i = 0; i < n; i += 2) {
3201 WCHAR hs = *(unsigned short *)(buff+i);
3202 if (IS_HIGH_SURROGATE(hs) && i+2 < n) {
3203 WCHAR ls = *(unsigned short *)(buff+i+2);
3204 if (IS_LOW_SURROGATE(ls)) {
3205 luni_send(ldisc, (unsigned short *)(buff+i), 2, 1);
3210 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
3215 ImmReleaseContext(hwnd, hIMC);
3220 if (wParam & 0xFF00) {
3224 buf[0] = wParam >> 8;
3225 term_seen_key_event(term);
3227 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
3229 char c = (unsigned char) wParam;
3230 term_seen_key_event(term);
3232 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
3238 * Nevertheless, we are prepared to deal with WM_CHAR
3239 * messages, should they crop up. So if someone wants to
3240 * post the things to us as part of a macro manoeuvre,
3241 * we're ready to cope.
3244 static wchar_t pending_surrogate = 0;
3247 if (IS_HIGH_SURROGATE(c)) {
3248 pending_surrogate = c;
3249 } else if (IS_SURROGATE_PAIR(pending_surrogate, c)) {
3251 pair[0] = pending_surrogate;
3253 term_seen_key_event(term);
3254 luni_send(ldisc, pair, 2, 1);
3255 } else if (!IS_SURROGATE(c)) {
3256 term_seen_key_event(term);
3257 luni_send(ldisc, &c, 1, 1);
3261 case WM_SYSCOLORCHANGE:
3262 if (conf_get_int(conf, CONF_system_colour)) {
3263 /* Refresh palette from system colours. */
3264 /* XXX actually this zaps the entire palette. */
3267 /* Force a repaint of the terminal window. */
3268 term_invalidate(term);
3271 case WM_AGENT_CALLBACK:
3273 struct agent_callback *c = (struct agent_callback *)lParam;
3274 c->callback(c->callback_ctx, c->data, c->len);
3278 case WM_GOT_CLIPDATA:
3279 if (process_clipdata((HGLOBAL)lParam, wParam))
3280 term_do_paste(term);
3283 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
3284 int shift_pressed=0, control_pressed=0;
3286 if (message == WM_MOUSEWHEEL) {
3287 wheel_accumulator += (short)HIWORD(wParam);
3288 shift_pressed=LOWORD(wParam) & MK_SHIFT;
3289 control_pressed=LOWORD(wParam) & MK_CONTROL;
3292 wheel_accumulator += (int)wParam;
3293 if (GetKeyboardState(keys)!=0) {
3294 shift_pressed=keys[VK_SHIFT]&0x80;
3295 control_pressed=keys[VK_CONTROL]&0x80;
3299 /* process events when the threshold is reached */
3300 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
3303 /* reduce amount for next time */
3304 if (wheel_accumulator > 0) {
3306 wheel_accumulator -= WHEEL_DELTA;
3307 } else if (wheel_accumulator < 0) {
3309 wheel_accumulator += WHEEL_DELTA;
3313 if (send_raw_mouse &&
3314 !(conf_get_int(conf, CONF_mouse_override) &&
3316 /* Mouse wheel position is in screen coordinates for
3319 p.x = X_POS(lParam); p.y = Y_POS(lParam);
3320 if (ScreenToClient(hwnd, &p)) {
3321 /* send a mouse-down followed by a mouse up */
3322 term_mouse(term, b, translate_button(b),
3325 TO_CHR_Y(p.y), shift_pressed,
3326 control_pressed, is_alt_pressed());
3327 } /* else: not sure when this can fail */
3329 /* trigger a scroll */
3330 term_scroll(term, 0,
3332 -term->rows / 2 : term->rows / 2);
3340 * Any messages we don't process completely above are passed through to
3341 * DefWindowProc() for default processing.
3343 return DefWindowProcW(hwnd, message, wParam, lParam);
3347 * Move the system caret. (We maintain one, even though it's
3348 * invisible, for the benefit of blind people: apparently some
3349 * helper software tracks the system caret, so we should arrange to
3352 void sys_cursor(void *frontend, int x, int y)
3356 if (!term->has_focus) return;
3359 * Avoid gratuitously re-updating the cursor position and IMM
3360 * window if there's no actual change required.
3362 cx = x * font_width + offset_width;
3363 cy = y * font_height + offset_height;
3364 if (cx == caret_x && cy == caret_y)
3369 sys_cursor_update();
3372 static void sys_cursor_update(void)
3377 if (!term->has_focus) return;
3379 if (caret_x < 0 || caret_y < 0)
3382 SetCaretPos(caret_x, caret_y);
3384 /* IMM calls on Win98 and beyond only */
3385 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3387 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3388 osVersion.dwMinorVersion == 0) return; /* 95 */
3390 /* we should have the IMM functions */
3391 hIMC = ImmGetContext(hwnd);
3392 cf.dwStyle = CFS_POINT;
3393 cf.ptCurrentPos.x = caret_x;
3394 cf.ptCurrentPos.y = caret_y;
3395 ImmSetCompositionWindow(hIMC, &cf);
3397 ImmReleaseContext(hwnd, hIMC);
3401 * Draw a line of text in the window, at given character
3402 * coordinates, in given attributes.
3404 * We are allowed to fiddle with the contents of `text'.
3406 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3407 unsigned long attr, int lattr)
3410 int nfg, nbg, nfont;
3413 int force_manual_underline = 0;
3414 int fnt_width, char_width;
3415 int text_adjust = 0;
3417 int maxlen, remaining, opaque;
3418 int is_cursor = FALSE;
3419 static int *lpDx = NULL;
3420 static int lpDx_len = 0;
3422 int len2; /* for SURROGATE PAIR */
3424 lattr &= LATTR_MODE;
3426 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3428 if (attr & ATTR_WIDE)
3431 /* Only want the left half of double width lines */
3432 if (lattr != LATTR_NORM && x*2 >= term->cols)
3440 if ((attr & TATTR_ACTCURS) && (cursor_type == 0 || term->big_cursor)) {
3441 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3442 /* cursor fg and bg */
3443 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3448 if (vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3449 /* Assume a poorman font is borken in other ways too. */
3459 nfont |= FONT_WIDE + FONT_HIGH;
3462 if (attr & ATTR_NARROW)
3463 nfont |= FONT_NARROW;
3465 #ifdef USES_VTLINE_HACK
3466 /* Special hack for the VT100 linedraw glyphs. */
3467 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3468 switch ((unsigned char) (text[0])) {
3470 text_adjust = -2 * font_height / 5;
3473 text_adjust = -1 * font_height / 5;
3476 text_adjust = font_height / 5;
3479 text_adjust = 2 * font_height / 5;
3482 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3484 text[0] = ucsdata.unitab_xterm['q'];
3485 if (attr & ATTR_UNDER) {
3486 attr &= ~ATTR_UNDER;
3487 force_manual_underline = 1;
3492 /* Anything left as an original character set is unprintable. */
3493 if (DIRECT_CHAR(text[0]) &&
3494 (len < 2 || !IS_SURROGATE_PAIR(text[0], text[1]))) {
3496 for (i = 0; i < len; i++)
3501 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3504 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3505 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3506 if (bold_font_mode == BOLD_FONT && (attr & ATTR_BOLD))
3508 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3509 nfont |= FONT_UNDERLINE;
3510 another_font(nfont);
3511 if (!fonts[nfont]) {
3512 if (nfont & FONT_UNDERLINE)
3513 force_manual_underline = 1;
3514 /* Don't do the same for manual bold, it could be bad news. */
3516 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3518 another_font(nfont);
3520 nfont = FONT_NORMAL;
3521 if (attr & ATTR_REVERSE) {
3526 if (bold_colours && (attr & ATTR_BOLD) && !is_cursor) {
3527 if (nfg < 16) nfg |= 8;
3528 else if (nfg >= 256) nfg |= 1;
3530 if (bold_colours && (attr & ATTR_BLINK)) {
3531 if (nbg < 16) nbg |= 8;
3532 else if (nbg >= 256) nbg |= 1;
3536 SelectObject(hdc, fonts[nfont]);
3537 SetTextColor(hdc, fg);
3538 SetBkColor(hdc, bg);
3539 if (attr & TATTR_COMBINING)
3540 SetBkMode(hdc, TRANSPARENT);
3542 SetBkMode(hdc, OPAQUE);
3545 line_box.right = x + char_width * len;
3546 line_box.bottom = y + font_height;
3547 /* adjust line_box.right for SURROGATE PAIR & VARIATION SELECTOR */
3551 for (i = 0; i < len ; i++) {
3552 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3554 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i], text[i+1])) {
3555 rc_width += char_width;
3557 } else if (IS_LOW_VARSEL(text[i])) {
3560 rc_width += char_width;
3563 line_box.right = line_box.left + rc_width;
3566 /* Only want the left half of double width lines */
3567 if (line_box.right > font_width*term->cols+offset_width)
3568 line_box.right = font_width*term->cols+offset_width;
3570 if (font_varpitch) {
3572 * If we're using a variable-pitch font, we unconditionally
3573 * draw the glyphs one at a time and centre them in their
3574 * character cells (which means in particular that we must
3575 * disable the lpDx mechanism). This gives slightly odd but
3576 * generally reasonable results.
3578 xoffset = char_width / 2;
3579 SetTextAlign(hdc, TA_TOP | TA_CENTER | TA_NOUPDATECP);
3584 * In a fixed-pitch font, we draw the whole string in one go
3585 * in the normal way.
3588 SetTextAlign(hdc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
3593 opaque = TRUE; /* start by erasing the rectangle */
3594 for (remaining = len; remaining > 0;
3595 text += len, remaining -= len, x += char_width * len2) {
3596 len = (maxlen < remaining ? maxlen : remaining);
3597 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3600 if (remaining >= 1 && IS_SURROGATE_PAIR(text[0], text[1]))
3602 if (remaining-len >= 1 && IS_LOW_VARSEL(text[len]))
3604 else if (remaining-len >= 2 &&
3605 IS_HIGH_VARSEL(text[len], text[len+1]))
3609 if (len > lpDx_len) {
3610 lpDx_len = len * 9 / 8 + 16;
3611 lpDx = sresize(lpDx, lpDx_len, int);
3613 if (lpDx_maybe) lpDx_maybe = lpDx;
3618 /* only last char has dx width in SURROGATE PAIR and
3619 * VARIATION sequence */
3620 for (i = 0; i < len; i++) {
3621 lpDx[i] = char_width;
3622 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3623 if (i > 0) lpDx[i-1] = 0;
3626 lpDx[i] = char_width;
3627 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i],text[i+1])) {
3630 lpDx[i] = char_width;
3631 } else if (IS_LOW_VARSEL(text[i])) {
3632 if (i > 0) lpDx[i-1] = 0;
3633 lpDx[i] = char_width;
3638 /* We're using a private area for direct to font. (512 chars.) */
3639 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3640 /* Ho Hum, dbcs fonts are a PITA! */
3641 /* To display on W9x I have to convert to UCS */
3642 static wchar_t *uni_buf = 0;
3643 static int uni_len = 0;
3645 if (len > uni_len) {
3648 uni_buf = snewn(uni_len, wchar_t);
3651 for(nlen = mptr = 0; mptr<len; mptr++) {
3652 uni_buf[nlen] = 0xFFFD;
3653 if (IsDBCSLeadByteEx(ucsdata.font_codepage,
3654 (BYTE) text[mptr])) {
3656 dbcstext[0] = text[mptr] & 0xFF;
3657 dbcstext[1] = text[mptr+1] & 0xFF;
3658 lpDx[nlen] += char_width;
3659 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3660 dbcstext, 2, uni_buf+nlen, 1);
3666 dbcstext[0] = text[mptr] & 0xFF;
3667 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3668 dbcstext, 1, uni_buf+nlen, 1);
3675 ExtTextOutW(hdc, x + xoffset,
3676 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3677 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3678 &line_box, uni_buf, nlen,
3680 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3681 SetBkMode(hdc, TRANSPARENT);
3682 ExtTextOutW(hdc, x + xoffset - 1,
3683 y - font_height * (lattr ==
3684 LATTR_BOT) + text_adjust,
3685 ETO_CLIPPED, &line_box, uni_buf, nlen, lpDx_maybe);
3689 } else if (DIRECT_FONT(text[0])) {
3690 static char *directbuf = NULL;
3691 static int directlen = 0;
3693 if (len > directlen) {
3695 directbuf = sresize(directbuf, directlen, char);
3698 for (i = 0; i < len; i++)
3699 directbuf[i] = text[i] & 0xFF;
3701 ExtTextOut(hdc, x + xoffset,
3702 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3703 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3704 &line_box, directbuf, len, lpDx_maybe);
3705 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3706 SetBkMode(hdc, TRANSPARENT);
3708 /* GRR: This draws the character outside its box and
3709 * can leave 'droppings' even with the clip box! I
3710 * suppose I could loop it one character at a time ...
3713 * Or ... I could do a test print with "W", and use +1
3714 * or -1 for this shift depending on if the leftmost
3715 * column is blank...
3717 ExtTextOut(hdc, x + xoffset - 1,
3718 y - font_height * (lattr ==
3719 LATTR_BOT) + text_adjust,
3720 ETO_CLIPPED, &line_box, directbuf, len, lpDx_maybe);
3723 /* And 'normal' unicode characters */
3724 static WCHAR *wbuf = NULL;
3725 static int wlen = 0;
3731 wbuf = snewn(wlen, WCHAR);
3734 for (i = 0; i < len; i++)
3737 /* print Glyphs as they are, without Windows' Shaping*/
3738 general_textout(hdc, x + xoffset,
3739 y - font_height * (lattr==LATTR_BOT) + text_adjust,
3740 &line_box, wbuf, len, lpDx,
3741 opaque && !(attr & TATTR_COMBINING));
3743 /* And the shadow bold hack. */
3744 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3745 SetBkMode(hdc, TRANSPARENT);
3746 ExtTextOutW(hdc, x + xoffset - 1,
3747 y - font_height * (lattr ==
3748 LATTR_BOT) + text_adjust,
3749 ETO_CLIPPED, &line_box, wbuf, len, lpDx_maybe);
3754 * If we're looping round again, stop erasing the background
3757 SetBkMode(hdc, TRANSPARENT);
3760 if (lattr != LATTR_TOP && (force_manual_underline ||
3761 (und_mode == UND_LINE
3762 && (attr & ATTR_UNDER)))) {
3765 if (lattr == LATTR_BOT)
3766 dec = dec * 2 - font_height;
3768 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3769 MoveToEx(hdc, line_box.left, line_box.top + dec, NULL);
3770 LineTo(hdc, line_box.right, line_box.top + dec);
3771 oldpen = SelectObject(hdc, oldpen);
3772 DeleteObject(oldpen);
3777 * Wrapper that handles combining characters.
3779 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3780 unsigned long attr, int lattr)
3782 if (attr & TATTR_COMBINING) {
3783 unsigned long a = 0;
3785 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3786 if (len >= 2 && IS_SURROGATE_PAIR(text[0], text[1]))
3788 if (len-len0 >= 1 && IS_LOW_VARSEL(text[len0])) {
3789 attr &= ~TATTR_COMBINING;
3790 do_text_internal(ctx, x, y, text, len0+1, attr, lattr);
3793 a = TATTR_COMBINING;
3794 } else if (len-len0 >= 2 && IS_HIGH_VARSEL(text[len0], text[len0+1])) {
3795 attr &= ~TATTR_COMBINING;
3796 do_text_internal(ctx, x, y, text, len0+2, attr, lattr);
3799 a = TATTR_COMBINING;
3801 attr &= ~TATTR_COMBINING;
3805 if (len >= 1 && IS_SURROGATE_PAIR(text[0], text[1])) {
3806 do_text_internal(ctx, x, y, text, 2, attr | a, lattr);
3810 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3814 a = TATTR_COMBINING;
3817 do_text_internal(ctx, x, y, text, len, attr, lattr);
3820 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3821 unsigned long attr, int lattr)
3827 int ctype = cursor_type;
3829 lattr &= LATTR_MODE;
3831 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3832 if (*text != UCSWIDE) {
3833 do_text(ctx, x, y, text, len, attr, lattr);
3837 attr |= TATTR_RIGHTCURS;
3840 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3841 if (attr & ATTR_WIDE)
3848 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3851 pts[0].x = pts[1].x = pts[4].x = x;
3852 pts[2].x = pts[3].x = x + char_width - 1;
3853 pts[0].y = pts[3].y = pts[4].y = y;
3854 pts[1].y = pts[2].y = y + font_height - 1;
3855 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3856 Polyline(hdc, pts, 5);
3857 oldpen = SelectObject(hdc, oldpen);
3858 DeleteObject(oldpen);
3859 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3860 int startx, starty, dx, dy, length, i;
3863 starty = y + descent;
3866 length = char_width;
3869 if (attr & TATTR_RIGHTCURS)
3870 xadjust = char_width - 1;
3871 startx = x + xadjust;
3875 length = font_height;
3877 if (attr & TATTR_ACTCURS) {
3880 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3881 MoveToEx(hdc, startx, starty, NULL);
3882 LineTo(hdc, startx + dx * length, starty + dy * length);
3883 oldpen = SelectObject(hdc, oldpen);
3884 DeleteObject(oldpen);
3886 for (i = 0; i < length; i++) {
3888 SetPixel(hdc, startx, starty, colours[261]);
3897 /* This function gets the actual width of a character in the normal font.
3899 int char_width(Context ctx, int uc) {
3903 /* If the font max is the same as the font ave width then this
3904 * function is a no-op.
3906 if (!font_dualwidth) return 1;
3908 switch (uc & CSET_MASK) {
3910 uc = ucsdata.unitab_line[uc & 0xFF];
3913 uc = ucsdata.unitab_xterm[uc & 0xFF];
3916 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3919 if (DIRECT_FONT(uc)) {
3920 if (ucsdata.dbcs_screenfont) return 1;
3922 /* Speedup, I know of no font where ascii is the wrong width */
3923 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3926 if ( (uc & CSET_MASK) == CSET_ACP ) {
3927 SelectObject(hdc, fonts[FONT_NORMAL]);
3928 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3929 another_font(FONT_OEM);
3930 if (!fonts[FONT_OEM]) return 0;
3932 SelectObject(hdc, fonts[FONT_OEM]);
3936 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3937 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3940 /* Speedup, I know of no font where ascii is the wrong width */
3941 if (uc >= ' ' && uc <= '~') return 1;
3943 SelectObject(hdc, fonts[FONT_NORMAL]);
3944 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3945 /* Okay that one worked */ ;
3946 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3947 /* This should work on 9x too, but it's "less accurate" */ ;
3952 ibuf += font_width / 2 -1;
3958 DECL_WINDOWS_FUNCTION(static, BOOL, FlashWindowEx, (PFLASHWINFO));
3959 DECL_WINDOWS_FUNCTION(static, BOOL, ToUnicodeEx,
3960 (UINT, UINT, const BYTE *, LPWSTR, int, UINT, HKL));
3962 static void init_winfuncs(void)
3964 HMODULE user32_module = load_system32_dll("user32.dll");
3965 GET_WINDOWS_FUNCTION(user32_module, FlashWindowEx);
3966 GET_WINDOWS_FUNCTION(user32_module, ToUnicodeEx);
3970 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3971 * codes. Returns number of bytes used, zero to drop the message,
3972 * -1 to forward the message to Windows, or another negative number
3973 * to indicate a NUL-terminated "special" string.
3975 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3976 unsigned char *output)
3979 int scan, left_alt = 0, key_down, shift_state;
3981 unsigned char *p = output;
3982 static int alt_sum = 0;
3983 int funky_type = conf_get_int(conf, CONF_funky_type);
3984 int no_applic_k = conf_get_int(conf, CONF_no_applic_k);
3985 int ctrlaltkeys = conf_get_int(conf, CONF_ctrlaltkeys);
3986 int nethack_keypad = conf_get_int(conf, CONF_nethack_keypad);
3988 HKL kbd_layout = GetKeyboardLayout(0);
3990 static wchar_t keys_unicode[3];
3991 static int compose_char = 0;
3992 static WPARAM compose_keycode = 0;
3994 r = GetKeyboardState(keystate);
3996 memset(keystate, 0, sizeof(keystate));
3999 #define SHOW_TOASCII_RESULT
4000 { /* Tell us all about key events */
4001 static BYTE oldstate[256];
4002 static int first = 1;
4006 memcpy(oldstate, keystate, sizeof(oldstate));
4009 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
4011 } else if ((HIWORD(lParam) & KF_UP)
4012 && scan == (HIWORD(lParam) & 0xFF)) {
4016 if (wParam >= VK_F1 && wParam <= VK_F20)
4017 debug(("K_F%d", wParam + 1 - VK_F1));
4030 debug(("VK_%02x", wParam));
4032 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
4034 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
4036 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
4037 if (ch >= ' ' && ch <= '~')
4038 debug((", '%c'", ch));
4040 debug((", $%02x", ch));
4042 if (keys_unicode[0])
4043 debug((", KB0=%04x", keys_unicode[0]));
4044 if (keys_unicode[1])
4045 debug((", KB1=%04x", keys_unicode[1]));
4046 if (keys_unicode[2])
4047 debug((", KB2=%04x", keys_unicode[2]));
4049 if ((keystate[VK_SHIFT] & 0x80) != 0)
4051 if ((keystate[VK_CONTROL] & 0x80) != 0)
4053 if ((HIWORD(lParam) & KF_EXTENDED))
4055 if ((HIWORD(lParam) & KF_UP))
4059 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
4060 else if ((HIWORD(lParam) & KF_UP))
4061 oldstate[wParam & 0xFF] ^= 0x80;
4063 oldstate[wParam & 0xFF] ^= 0x81;
4065 for (ch = 0; ch < 256; ch++)
4066 if (oldstate[ch] != keystate[ch])
4067 debug((", M%02x=%02x", ch, keystate[ch]));
4069 memcpy(oldstate, keystate, sizeof(oldstate));
4073 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
4074 keystate[VK_RMENU] = keystate[VK_MENU];
4078 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
4079 if ((funky_type == FUNKY_VT400 ||
4080 (funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
4082 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
4084 wParam = VK_EXECUTE;
4086 /* UnToggle NUMLock */
4087 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
4088 keystate[VK_NUMLOCK] ^= 1;
4091 /* And write back the 'adjusted' state */
4092 SetKeyboardState(keystate);
4095 /* Disable Auto repeat if required */
4096 if (term->repeat_off &&
4097 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
4100 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
4103 key_down = ((HIWORD(lParam) & KF_UP) == 0);
4105 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
4106 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
4108 keystate[VK_MENU] = 0;
4110 keystate[VK_RMENU] = 0x80;
4115 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
4116 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
4117 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
4119 /* Note if AltGr was pressed and if it was used as a compose key */
4120 if (!compose_state) {
4121 compose_keycode = 0x100;
4122 if (conf_get_int(conf, CONF_compose_key)) {
4123 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
4124 compose_keycode = wParam;
4126 if (wParam == VK_APPS)
4127 compose_keycode = wParam;
4130 if (wParam == compose_keycode) {
4131 if (compose_state == 0
4132 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
4134 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
4138 } else if (compose_state == 1 && wParam != VK_CONTROL)
4141 if (compose_state > 1 && left_alt)
4144 /* Sanitize the number pad if not using a PC NumPad */
4145 if (left_alt || (term->app_keypad_keys && !no_applic_k
4146 && funky_type != FUNKY_XTERM)
4147 || funky_type == FUNKY_VT400 || nethack_keypad || compose_state) {
4148 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
4152 nParam = VK_NUMPAD0;
4155 nParam = VK_NUMPAD1;
4158 nParam = VK_NUMPAD2;
4161 nParam = VK_NUMPAD3;
4164 nParam = VK_NUMPAD4;
4167 nParam = VK_NUMPAD5;
4170 nParam = VK_NUMPAD6;
4173 nParam = VK_NUMPAD7;
4176 nParam = VK_NUMPAD8;
4179 nParam = VK_NUMPAD9;
4182 nParam = VK_DECIMAL;
4186 if (keystate[VK_NUMLOCK] & 1)
4193 /* If a key is pressed and AltGr is not active */
4194 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
4195 /* Okay, prepare for most alts then ... */
4199 /* Lets see if it's a pattern we know all about ... */
4200 if (wParam == VK_PRIOR && shift_state == 1) {
4201 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
4204 if (wParam == VK_PRIOR && shift_state == 2) {
4205 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
4208 if (wParam == VK_NEXT && shift_state == 1) {
4209 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
4212 if (wParam == VK_NEXT && shift_state == 2) {
4213 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
4216 if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) {
4217 term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1));
4220 if (wParam == VK_INSERT && shift_state == 1) {
4221 request_paste(NULL);
4224 if (left_alt && wParam == VK_F4 && conf_get_int(conf, CONF_alt_f4)) {
4227 if (left_alt && wParam == VK_SPACE && conf_get_int(conf,
4229 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
4232 if (left_alt && wParam == VK_RETURN &&
4233 conf_get_int(conf, CONF_fullscreenonaltenter) &&
4234 (conf_get_int(conf, CONF_resize_action) != RESIZE_DISABLED)) {
4235 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
4239 /* Control-Numlock for app-keypad mode switch */
4240 if (wParam == VK_PAUSE && shift_state == 2) {
4241 term->app_keypad_keys ^= 1;
4245 /* Nethack keypad */
4246 if (nethack_keypad && !left_alt) {
4249 *p++ = "bB\002\002"[shift_state & 3];
4252 *p++ = "jJ\012\012"[shift_state & 3];
4255 *p++ = "nN\016\016"[shift_state & 3];
4258 *p++ = "hH\010\010"[shift_state & 3];
4261 *p++ = shift_state ? '.' : '.';
4264 *p++ = "lL\014\014"[shift_state & 3];
4267 *p++ = "yY\031\031"[shift_state & 3];
4270 *p++ = "kK\013\013"[shift_state & 3];
4273 *p++ = "uU\025\025"[shift_state & 3];
4278 /* Application Keypad */
4282 if (funky_type == FUNKY_VT400 ||
4283 (funky_type <= FUNKY_LINUX &&
4284 term->app_keypad_keys && !no_applic_k)) switch (wParam) {
4298 if (term->app_keypad_keys && !no_applic_k)
4335 if (funky_type == FUNKY_XTERM) {
4340 } else if (shift_state)
4347 if (funky_type == FUNKY_XTERM)
4351 if (funky_type == FUNKY_XTERM)
4355 if (funky_type == FUNKY_XTERM)
4360 if (HIWORD(lParam) & KF_EXTENDED)
4365 if (term->vt52_mode) {
4366 if (xkey >= 'P' && xkey <= 'S')
4367 p += sprintf((char *) p, "\x1B%c", xkey);
4369 p += sprintf((char *) p, "\x1B?%c", xkey);
4371 p += sprintf((char *) p, "\x1BO%c", xkey);
4376 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
4377 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x7F : 0x08);
4381 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
4382 /* We do the opposite of what is configured */
4383 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x08 : 0x7F);
4387 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
4393 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
4397 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
4401 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
4403 back->special(backhandle, TS_BRK);
4406 if (wParam == VK_PAUSE) { /* Break/Pause */
4411 /* Control-2 to Control-8 are special */
4412 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
4413 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
4416 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
4420 if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) {
4424 if (shift_state == 3 && wParam == 0xDE) {
4425 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
4428 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
4435 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
4436 * for integer decimal nn.)
4438 * We also deal with the weird ones here. Linux VCs replace F1
4439 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
4440 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
4446 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
4449 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
4452 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
4455 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
4458 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
4461 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
4464 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
4467 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
4470 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
4473 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
4506 if ((shift_state&2) == 0) switch (wParam) {
4526 /* Reorder edit keys to physical order */
4527 if (funky_type == FUNKY_VT400 && code <= 6)
4528 code = "\0\2\1\4\5\3\6"[code];
4530 if (term->vt52_mode && code > 0 && code <= 6) {
4531 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4535 if (funky_type == FUNKY_SCO && code >= 11 && code <= 34) {
4536 /* SCO function keys */
4537 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4540 case VK_F1: index = 0; break;
4541 case VK_F2: index = 1; break;
4542 case VK_F3: index = 2; break;
4543 case VK_F4: index = 3; break;
4544 case VK_F5: index = 4; break;
4545 case VK_F6: index = 5; break;
4546 case VK_F7: index = 6; break;
4547 case VK_F8: index = 7; break;
4548 case VK_F9: index = 8; break;
4549 case VK_F10: index = 9; break;
4550 case VK_F11: index = 10; break;
4551 case VK_F12: index = 11; break;
4553 if (keystate[VK_SHIFT] & 0x80) index += 12;
4554 if (keystate[VK_CONTROL] & 0x80) index += 24;
4555 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4558 if (funky_type == FUNKY_SCO && /* SCO small keypad */
4559 code >= 1 && code <= 6) {
4560 char codes[] = "HL.FIG";
4564 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4568 if ((term->vt52_mode || funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4574 if (term->vt52_mode)
4575 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4578 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4581 if (funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4582 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4585 if (funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4586 if (term->vt52_mode)
4587 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4589 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4592 if ((code == 1 || code == 4) &&
4593 conf_get_int(conf, CONF_rxvt_homeend)) {
4594 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4598 p += sprintf((char *) p, "\x1B[%d~", code);
4603 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4604 * some reason seems to send VK_CLEAR to Windows...).
4626 p += format_arrow_key((char *)p, term, xkey, shift_state);
4632 * Finally, deal with Return ourselves. (Win95 seems to
4633 * foul it up when Alt is pressed, for some reason.)
4635 if (wParam == VK_RETURN) { /* Return */
4641 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4642 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4647 /* Okay we've done everything interesting; let windows deal with
4648 * the boring stuff */
4652 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4653 if(keystate[VK_CAPITAL] != 0 &&
4654 conf_get_int(conf, CONF_xlat_capslockcyr)) {
4656 keystate[VK_CAPITAL] = 0;
4659 /* XXX how do we know what the max size of the keys array should
4660 * be is? There's indication on MS' website of an Inquire/InquireEx
4661 * functioning returning a KBINFO structure which tells us. */
4662 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT && p_ToUnicodeEx) {
4663 r = p_ToUnicodeEx(wParam, scan, keystate, keys_unicode,
4664 lenof(keys_unicode), 0, kbd_layout);
4666 /* XXX 'keys' parameter is declared in MSDN documentation as
4668 * The experience of a French user indicates that on
4669 * Win98, WORD[] should be passed in, but on Win2K, it should
4670 * be BYTE[]. German WinXP and my Win2K with "US International"
4671 * driver corroborate this.
4672 * Experimentally I've conditionalised the behaviour on the
4673 * Win9x/NT split, but I suspect it's worse than that.
4674 * See wishlist item `win-dead-keys' for more horrible detail
4675 * and speculations. */
4677 static WORD keys[3];
4678 static BYTE keysb[3];
4679 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4681 for (i = 0; i < r; i++) {
4682 keysb[i] = (BYTE)keys[i];
4684 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)keysb, r,
4685 keys_unicode, lenof(keys_unicode));
4688 #ifdef SHOW_TOASCII_RESULT
4689 if (r == 1 && !key_down) {
4691 if (in_utf(term) || ucsdata.dbcs_screenfont)
4692 debug((", (U+%04x)", alt_sum));
4694 debug((", LCH(%d)", alt_sum));
4696 debug((", ACH(%d)", keys_unicode[0]));
4701 for (r1 = 0; r1 < r; r1++) {
4702 debug(("%s%d", r1 ? "," : "", keys_unicode[r1]));
4711 for (i = 0; i < r; i++) {
4712 wchar_t wch = keys_unicode[i];
4714 if (compose_state == 2 && wch >= ' ' && wch < 0x80) {
4719 if (compose_state == 3 && wch >= ' ' && wch < 0x80) {
4723 if ((nc = check_compose(compose_char, wch)) == -1) {
4724 MessageBeep(MB_ICONHAND);
4728 term_seen_key_event(term);
4730 luni_send(ldisc, &keybuf, 1, 1);
4738 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4740 term_seen_key_event(term);
4742 luni_send(ldisc, &keybuf, 1, 1);
4744 char ch = (char) alt_sum;
4746 * We need not bother about stdin
4747 * backlogs here, because in GUI PuTTY
4748 * we can't do anything about it
4749 * anyway; there's no means of asking
4750 * Windows to hold off on KEYDOWN
4751 * messages. We _have_ to buffer
4752 * everything we're sent.
4754 term_seen_key_event(term);
4756 ldisc_send(ldisc, &ch, 1, 1);
4760 term_seen_key_event(term);
4762 luni_send(ldisc, &wch, 1, 1);
4765 if(capsOn && wch < 0x80) {
4768 cbuf[1] = xlat_uskbd2cyrllic(wch);
4769 term_seen_key_event(term);
4771 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4776 term_seen_key_event(term);
4778 luni_send(ldisc, cbuf +!left_alt, 1+!!left_alt, 1);
4784 /* This is so the ALT-Numpad and dead keys work correctly. */
4785 keys_unicode[0] = 0;
4789 /* If we're definitly not building up an ALT-54321 then clear it */
4791 keys_unicode[0] = 0;
4792 /* If we will be using alt_sum fix the 256s */
4793 else if (keys_unicode[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4794 keys_unicode[0] = 10;
4798 * ALT alone may or may not want to bring up the System menu.
4799 * If it's not meant to, we return 0 on presses or releases of
4800 * ALT, to show that we've swallowed the keystroke. Otherwise
4801 * we return -1, which means Windows will give the keystroke
4802 * its default handling (i.e. bring up the System menu).
4804 if (wParam == VK_MENU && !conf_get_int(conf, CONF_alt_only))
4810 void set_title(void *frontend, char *title)
4813 window_name = snewn(1 + strlen(title), char);
4814 strcpy(window_name, title);
4815 if (conf_get_int(conf, CONF_win_name_always) || !IsIconic(hwnd))
4816 SetWindowText(hwnd, title);
4819 void set_icon(void *frontend, char *title)
4822 icon_name = snewn(1 + strlen(title), char);
4823 strcpy(icon_name, title);
4824 if (!conf_get_int(conf, CONF_win_name_always) && IsIconic(hwnd))
4825 SetWindowText(hwnd, title);
4828 void set_sbar(void *frontend, int total, int start, int page)
4832 if (!conf_get_int(conf, is_full_screen() ?
4833 CONF_scrollbar_in_fullscreen : CONF_scrollbar))
4836 si.cbSize = sizeof(si);
4837 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4839 si.nMax = total - 1;
4843 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4846 Context get_ctx(void *frontend)
4852 SelectPalette(hdc, pal, FALSE);
4858 void free_ctx(Context ctx)
4860 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4861 ReleaseDC(hwnd, ctx);
4864 static void real_palette_set(int n, int r, int g, int b)
4867 logpal->palPalEntry[n].peRed = r;
4868 logpal->palPalEntry[n].peGreen = g;
4869 logpal->palPalEntry[n].peBlue = b;
4870 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4871 colours[n] = PALETTERGB(r, g, b);
4872 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4874 colours[n] = RGB(r, g, b);
4877 void palette_set(void *frontend, int n, int r, int g, int b)
4881 if (n >= NALLCOLOURS)
4883 real_palette_set(n, r, g, b);
4885 HDC hdc = get_ctx(frontend);
4886 UnrealizeObject(pal);
4887 RealizePalette(hdc);
4890 if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))
4891 /* If Default Background changes, we need to ensure any
4892 * space between the text area and the window border is
4894 InvalidateRect(hwnd, NULL, TRUE);
4898 void palette_reset(void *frontend)
4903 for (i = 0; i < NALLCOLOURS; i++) {
4905 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4906 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4907 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4908 logpal->palPalEntry[i].peFlags = 0;
4909 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4910 defpal[i].rgbtGreen,
4911 defpal[i].rgbtBlue);
4913 colours[i] = RGB(defpal[i].rgbtRed,
4914 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4919 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4920 hdc = get_ctx(frontend);
4921 RealizePalette(hdc);
4924 /* Default Background may have changed. Ensure any space between
4925 * text area and window border is redrawn. */
4926 InvalidateRect(hwnd, NULL, TRUE);
4930 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4935 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4938 lock = GlobalLock(clipdata);
4941 memcpy(lock, data, len);
4942 ((unsigned char *) lock)[len] = 0;
4943 GlobalUnlock(clipdata);
4946 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4948 if (OpenClipboard(hwnd)) {
4950 SetClipboardData(CF_TEXT, clipdata);
4953 GlobalFree(clipdata);
4956 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4960 * Note: unlike write_aclip() this will not append a nul.
4962 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
4964 HGLOBAL clipdata, clipdata2, clipdata3;
4966 void *lock, *lock2, *lock3;
4968 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4970 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4971 len * sizeof(wchar_t));
4972 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4974 if (!clipdata || !clipdata2) {
4976 GlobalFree(clipdata);
4978 GlobalFree(clipdata2);
4981 if (!(lock = GlobalLock(clipdata))) {
4982 GlobalFree(clipdata);
4983 GlobalFree(clipdata2);
4986 if (!(lock2 = GlobalLock(clipdata2))) {
4987 GlobalUnlock(clipdata);
4988 GlobalFree(clipdata);
4989 GlobalFree(clipdata2);
4993 memcpy(lock, data, len * sizeof(wchar_t));
4994 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4996 if (conf_get_int(conf, CONF_rtf_paste)) {
4997 wchar_t unitab[256];
4999 unsigned char *tdata = (unsigned char *)lock2;
5000 wchar_t *udata = (wchar_t *)lock;
5001 int rtflen = 0, uindex = 0, tindex = 0;
5003 int multilen, blen, alen, totallen, i;
5004 char before[16], after[4];
5005 int fgcolour, lastfgcolour = 0;
5006 int bgcolour, lastbgcolour = 0;
5007 int attrBold, lastAttrBold = 0;
5008 int attrUnder, lastAttrUnder = 0;
5009 int palette[NALLCOLOURS];
5011 FontSpec *font = conf_get_fontspec(conf, CONF_font);
5013 get_unitab(CP_ACP, unitab, 0);
5015 rtfsize = 100 + strlen(font->name);
5016 rtf = snewn(rtfsize, char);
5017 rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
5018 font->name, font->height*2);
5021 * Add colour palette
5022 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
5026 * First - Determine all colours in use
5027 * o Foregound and background colours share the same palette
5030 memset(palette, 0, sizeof(palette));
5031 for (i = 0; i < (len-1); i++) {
5032 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5033 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5035 if (attr[i] & ATTR_REVERSE) {
5036 int tmpcolour = fgcolour; /* Swap foreground and background */
5037 fgcolour = bgcolour;
5038 bgcolour = tmpcolour;
5041 if (bold_colours && (attr[i] & ATTR_BOLD)) {
5042 if (fgcolour < 8) /* ANSI colours */
5044 else if (fgcolour >= 256) /* Default colours */
5048 if (attr[i] & ATTR_BLINK) {
5049 if (bgcolour < 8) /* ANSI colours */
5051 else if (bgcolour >= 256) /* Default colours */
5055 palette[fgcolour]++;
5056 palette[bgcolour]++;
5060 * Next - Create a reduced palette
5063 for (i = 0; i < NALLCOLOURS; i++) {
5064 if (palette[i] != 0)
5065 palette[i] = ++numcolours;
5069 * Finally - Write the colour table
5071 rtf = sresize(rtf, rtfsize + (numcolours * 25), char);
5072 strcat(rtf, "{\\colortbl ;");
5073 rtflen = strlen(rtf);
5075 for (i = 0; i < NALLCOLOURS; i++) {
5076 if (palette[i] != 0) {
5077 rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);
5080 strcpy(&rtf[rtflen], "}");
5085 * We want to construct a piece of RTF that specifies the
5086 * same Unicode text. To do this we will read back in
5087 * parallel from the Unicode data in `udata' and the
5088 * non-Unicode data in `tdata'. For each character in
5089 * `tdata' which becomes the right thing in `udata' when
5090 * looked up in `unitab', we just copy straight over from
5091 * tdata. For each one that doesn't, we must WCToMB it
5092 * individually and produce a \u escape sequence.
5094 * It would probably be more robust to just bite the bullet
5095 * and WCToMB each individual Unicode character one by one,
5096 * then MBToWC each one back to see if it was an accurate
5097 * translation; but that strikes me as a horrifying number
5098 * of Windows API calls so I want to see if this faster way
5099 * will work. If it screws up badly we can always revert to
5100 * the simple and slow way.
5102 while (tindex < len2 && uindex < len &&
5103 tdata[tindex] && udata[uindex]) {
5104 if (tindex + 1 < len2 &&
5105 tdata[tindex] == '\r' &&
5106 tdata[tindex+1] == '\n') {
5112 * Set text attributes
5115 if (rtfsize < rtflen + 64) {
5116 rtfsize = rtflen + 512;
5117 rtf = sresize(rtf, rtfsize, char);
5121 * Determine foreground and background colours
5123 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5124 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5126 if (attr[tindex] & ATTR_REVERSE) {
5127 int tmpcolour = fgcolour; /* Swap foreground and background */
5128 fgcolour = bgcolour;
5129 bgcolour = tmpcolour;
5132 if (bold_colours && (attr[tindex] & ATTR_BOLD)) {
5133 if (fgcolour < 8) /* ANSI colours */
5135 else if (fgcolour >= 256) /* Default colours */
5139 if (attr[tindex] & ATTR_BLINK) {
5140 if (bgcolour < 8) /* ANSI colours */
5142 else if (bgcolour >= 256) /* Default colours */
5147 * Collect other attributes
5149 if (bold_font_mode != BOLD_NONE)
5150 attrBold = attr[tindex] & ATTR_BOLD;
5154 attrUnder = attr[tindex] & ATTR_UNDER;
5158 * o If video isn't reversed, ignore colour attributes for default foregound
5160 * o Special case where bolded text is displayed using the default foregound
5161 * and background colours - force to bolded RTF.
5163 if (!(attr[tindex] & ATTR_REVERSE)) {
5164 if (bgcolour >= 256) /* Default color */
5165 bgcolour = -1; /* No coloring */
5167 if (fgcolour >= 256) { /* Default colour */
5168 if (bold_colours && (fgcolour & 1) && bgcolour == -1)
5169 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
5171 fgcolour = -1; /* No coloring */
5176 * Write RTF text attributes
5178 if (lastfgcolour != fgcolour) {
5179 lastfgcolour = fgcolour;
5180 rtflen += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
5183 if (lastbgcolour != bgcolour) {
5184 lastbgcolour = bgcolour;
5185 rtflen += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
5188 if (lastAttrBold != attrBold) {
5189 lastAttrBold = attrBold;
5190 rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
5193 if (lastAttrUnder != attrUnder) {
5194 lastAttrUnder = attrUnder;
5195 rtflen += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
5199 if (unitab[tdata[tindex]] == udata[uindex]) {
5205 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
5206 NULL, 0, NULL, NULL);
5207 if (multilen != 1) {
5208 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
5210 alen = 1; strcpy(after, "}");
5212 blen = sprintf(before, "\\u%d", udata[uindex]);
5213 alen = 0; after[0] = '\0';
5216 assert(tindex + multilen <= len2);
5217 totallen = blen + alen;
5218 for (i = 0; i < multilen; i++) {
5219 if (tdata[tindex+i] == '\\' ||
5220 tdata[tindex+i] == '{' ||
5221 tdata[tindex+i] == '}')
5223 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
5224 totallen += 6; /* \par\r\n */
5225 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
5231 if (rtfsize < rtflen + totallen + 3) {
5232 rtfsize = rtflen + totallen + 512;
5233 rtf = sresize(rtf, rtfsize, char);
5236 strcpy(rtf + rtflen, before); rtflen += blen;
5237 for (i = 0; i < multilen; i++) {
5238 if (tdata[tindex+i] == '\\' ||
5239 tdata[tindex+i] == '{' ||
5240 tdata[tindex+i] == '}') {
5241 rtf[rtflen++] = '\\';
5242 rtf[rtflen++] = tdata[tindex+i];
5243 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
5244 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
5245 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
5246 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
5248 rtf[rtflen++] = tdata[tindex+i];
5251 strcpy(rtf + rtflen, after); rtflen += alen;
5257 rtf[rtflen++] = '}'; /* Terminate RTF stream */
5258 rtf[rtflen++] = '\0';
5259 rtf[rtflen++] = '\0';
5261 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
5262 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
5263 memcpy(lock3, rtf, rtflen);
5264 GlobalUnlock(clipdata3);
5270 GlobalUnlock(clipdata);
5271 GlobalUnlock(clipdata2);
5274 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
5276 if (OpenClipboard(hwnd)) {
5278 SetClipboardData(CF_UNICODETEXT, clipdata);
5279 SetClipboardData(CF_TEXT, clipdata2);
5281 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
5284 GlobalFree(clipdata);
5285 GlobalFree(clipdata2);
5289 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
5292 static DWORD WINAPI clipboard_read_threadfunc(void *param)
5294 HWND hwnd = (HWND)param;
5297 if (OpenClipboard(NULL)) {
5298 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
5299 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)1, (LPARAM)clipdata);
5300 } else if ((clipdata = GetClipboardData(CF_TEXT))) {
5301 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)0, (LPARAM)clipdata);
5309 static int process_clipdata(HGLOBAL clipdata, int unicode)
5311 sfree(clipboard_contents);
5312 clipboard_contents = NULL;
5313 clipboard_length = 0;
5316 wchar_t *p = GlobalLock(clipdata);
5320 /* Unwilling to rely on Windows having wcslen() */
5321 for (p2 = p; *p2; p2++);
5322 clipboard_length = p2 - p;
5323 clipboard_contents = snewn(clipboard_length + 1, wchar_t);
5324 memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t));
5325 clipboard_contents[clipboard_length] = L'\0';
5329 char *s = GlobalLock(clipdata);
5333 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
5334 clipboard_contents = snewn(i, wchar_t);
5335 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1,
5336 clipboard_contents, i);
5337 clipboard_length = i - 1;
5338 clipboard_contents[clipboard_length] = L'\0';
5346 void request_paste(void *frontend)
5349 * I always thought pasting was synchronous in Windows; the
5350 * clipboard access functions certainly _look_ synchronous,
5351 * unlike the X ones. But in fact it seems that in some
5352 * situations the contents of the clipboard might not be
5353 * immediately available, and the clipboard-reading functions
5354 * may block. This leads to trouble if the application
5355 * delivering the clipboard data has to get hold of it by -
5356 * for example - talking over a network connection which is
5357 * forwarded through this very PuTTY.
5359 * Hence, we spawn a subthread to read the clipboard, and do
5360 * our paste when it's finished. The thread will send a
5361 * message back to our main window when it terminates, and
5362 * that tells us it's OK to paste.
5364 DWORD in_threadid; /* required for Win9x */
5365 CreateThread(NULL, 0, clipboard_read_threadfunc,
5366 hwnd, 0, &in_threadid);
5369 void get_clip(void *frontend, wchar_t **p, int *len)
5372 *p = clipboard_contents;
5373 *len = clipboard_length;
5379 * Move `lines' lines from position `from' to position `to' in the
5382 void optimised_move(void *frontend, int to, int from, int lines)
5387 min = (to < from ? to : from);
5388 max = to + from - min;
5390 r.left = offset_width;
5391 r.right = offset_width + term->cols * font_width;
5392 r.top = offset_height + min * font_height;
5393 r.bottom = offset_height + (max + lines) * font_height;
5394 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
5399 * Print a message box and perform a fatal exit.
5401 void fatalbox(const char *fmt, ...)
5404 char *stuff, morestuff[100];
5407 stuff = dupvprintf(fmt, ap);
5409 sprintf(morestuff, "%.70s Fatal Error", appname);
5410 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5416 * Print a modal (Really Bad) message box and perform a fatal exit.
5418 void modalfatalbox(const char *fmt, ...)
5421 char *stuff, morestuff[100];
5424 stuff = dupvprintf(fmt, ap);
5426 sprintf(morestuff, "%.70s Fatal Error", appname);
5427 MessageBox(hwnd, stuff, morestuff,
5428 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
5434 * Print a message box and don't close the connection.
5436 void nonfatal(const char *fmt, ...)
5439 char *stuff, morestuff[100];
5442 stuff = dupvprintf(fmt, ap);
5444 sprintf(morestuff, "%.70s Error", appname);
5445 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5449 static BOOL flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout)
5451 if (p_FlashWindowEx) {
5453 fi.cbSize = sizeof(fi);
5455 fi.dwFlags = dwFlags;
5457 fi.dwTimeout = dwTimeout;
5458 return (*p_FlashWindowEx)(&fi);
5461 return FALSE; /* shrug */
5464 static void flash_window(int mode);
5465 static long next_flash;
5466 static int flashing = 0;
5469 * Timer for platforms where we must maintain window flashing manually
5472 static void flash_window_timer(void *ctx, unsigned long now)
5474 if (flashing && now == next_flash) {
5480 * Manage window caption / taskbar flashing, if enabled.
5481 * 0 = stop, 1 = maintain, 2 = start
5483 static void flash_window(int mode)
5485 int beep_ind = conf_get_int(conf, CONF_beep_ind);
5486 if ((mode == 0) || (beep_ind == B_IND_DISABLED)) {
5490 if (p_FlashWindowEx)
5491 flash_window_ex(FLASHW_STOP, 0, 0);
5493 FlashWindow(hwnd, FALSE);
5496 } else if (mode == 2) {
5500 if (p_FlashWindowEx) {
5501 /* For so-called "steady" mode, we use uCount=2, which
5502 * seems to be the traditional number of flashes used
5503 * by user notifications (e.g., by Explorer).
5504 * uCount=0 appears to enable continuous flashing, per
5505 * "flashing" mode, although I haven't seen this
5507 flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
5508 (beep_ind == B_IND_FLASH ? 0 : 2),
5509 0 /* system cursor blink rate */);
5510 /* No need to schedule timer */
5512 FlashWindow(hwnd, TRUE);
5513 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5517 } else if ((mode == 1) && (beep_ind == B_IND_FLASH)) {
5519 if (flashing && !p_FlashWindowEx) {
5520 FlashWindow(hwnd, TRUE); /* toggle */
5521 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5529 void do_beep(void *frontend, int mode)
5531 if (mode == BELL_DEFAULT) {
5533 * For MessageBeep style bells, we want to be careful of
5534 * timing, because they don't have the nice property of
5535 * PlaySound bells that each one cancels the previous
5536 * active one. So we limit the rate to one per 50ms or so.
5538 static long lastbeep = 0;
5541 beepdiff = GetTickCount() - lastbeep;
5542 if (beepdiff >= 0 && beepdiff < 50)
5546 * The above MessageBeep call takes time, so we record the
5547 * time _after_ it finishes rather than before it starts.
5549 lastbeep = GetTickCount();
5550 } else if (mode == BELL_WAVEFILE) {
5551 Filename *bell_wavefile = conf_get_filename(conf, CONF_bell_wavefile);
5552 if (!PlaySound(bell_wavefile->path, NULL,
5553 SND_ASYNC | SND_FILENAME)) {
5554 char buf[sizeof(bell_wavefile->path) + 80];
5556 sprintf(buf, "Unable to play sound file\n%s\n"
5557 "Using default sound instead", bell_wavefile->path);
5558 sprintf(otherbuf, "%.70s Sound Error", appname);
5559 MessageBox(hwnd, buf, otherbuf,
5560 MB_OK | MB_ICONEXCLAMATION);
5561 conf_set_int(conf, CONF_beep, BELL_DEFAULT);
5563 } else if (mode == BELL_PCSPEAKER) {
5564 static long lastbeep = 0;
5567 beepdiff = GetTickCount() - lastbeep;
5568 if (beepdiff >= 0 && beepdiff < 50)
5572 * We must beep in different ways depending on whether this
5573 * is a 95-series or NT-series OS.
5575 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
5579 lastbeep = GetTickCount();
5581 /* Otherwise, either visual bell or disabled; do nothing here */
5582 if (!term->has_focus) {
5583 flash_window(2); /* start */
5588 * Minimise or restore the window in response to a server-side
5591 void set_iconic(void *frontend, int iconic)
5593 if (IsIconic(hwnd)) {
5595 ShowWindow(hwnd, SW_RESTORE);
5598 ShowWindow(hwnd, SW_MINIMIZE);
5603 * Move the window in response to a server-side request.
5605 void move_window(void *frontend, int x, int y)
5607 int resize_action = conf_get_int(conf, CONF_resize_action);
5608 if (resize_action == RESIZE_DISABLED ||
5609 resize_action == RESIZE_FONT ||
5613 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5617 * Move the window to the top or bottom of the z-order in response
5618 * to a server-side request.
5620 void set_zorder(void *frontend, int top)
5622 if (conf_get_int(conf, CONF_alwaysontop))
5623 return; /* ignore */
5624 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5625 SWP_NOMOVE | SWP_NOSIZE);
5629 * Refresh the window in response to a server-side request.
5631 void refresh_window(void *frontend)
5633 InvalidateRect(hwnd, NULL, TRUE);
5637 * Maximise or restore the window in response to a server-side
5640 void set_zoomed(void *frontend, int zoomed)
5642 if (IsZoomed(hwnd)) {
5644 ShowWindow(hwnd, SW_RESTORE);
5647 ShowWindow(hwnd, SW_MAXIMIZE);
5652 * Report whether the window is iconic, for terminal reports.
5654 int is_iconic(void *frontend)
5656 return IsIconic(hwnd);
5660 * Report the window's position, for terminal reports.
5662 void get_window_pos(void *frontend, int *x, int *y)
5665 GetWindowRect(hwnd, &r);
5671 * Report the window's pixel size, for terminal reports.
5673 void get_window_pixels(void *frontend, int *x, int *y)
5676 GetWindowRect(hwnd, &r);
5677 *x = r.right - r.left;
5678 *y = r.bottom - r.top;
5682 * Return the window or icon title.
5684 char *get_window_title(void *frontend, int icon)
5686 return icon ? icon_name : window_name;
5690 * See if we're in full-screen mode.
5692 static int is_full_screen()
5694 if (!IsZoomed(hwnd))
5696 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
5701 /* Get the rect/size of a full screen window using the nearest available
5702 * monitor in multimon systems; default to something sensible if only
5703 * one monitor is present. */
5704 static int get_fullscreen_rect(RECT * ss)
5706 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
5709 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
5710 mi.cbSize = sizeof(mi);
5711 GetMonitorInfo(mon, &mi);
5713 /* structure copy */
5717 /* could also use code like this:
5718 ss->left = ss->top = 0;
5719 ss->right = GetSystemMetrics(SM_CXSCREEN);
5720 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5722 return GetClientRect(GetDesktopWindow(), ss);
5728 * Go full-screen. This should only be called when we are already
5731 static void make_full_screen()
5736 assert(IsZoomed(hwnd));
5738 if (is_full_screen())
5741 /* Remove the window furniture. */
5742 style = GetWindowLongPtr(hwnd, GWL_STYLE);
5743 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5744 if (conf_get_int(conf, CONF_scrollbar_in_fullscreen))
5745 style |= WS_VSCROLL;
5747 style &= ~WS_VSCROLL;
5748 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5750 /* Resize ourselves to exactly cover the nearest monitor. */
5751 get_fullscreen_rect(&ss);
5752 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5757 /* We may have changed size as a result */
5761 /* Tick the menu item in the System and context menus. */
5764 for (i = 0; i < lenof(popup_menus); i++)
5765 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED);
5770 * Clear the full-screen attributes.
5772 static void clear_full_screen()
5774 DWORD oldstyle, style;
5776 /* Reinstate the window furniture. */
5777 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
5778 style |= WS_CAPTION | WS_BORDER;
5779 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
5780 style &= ~WS_THICKFRAME;
5782 style |= WS_THICKFRAME;
5783 if (conf_get_int(conf, CONF_scrollbar))
5784 style |= WS_VSCROLL;
5786 style &= ~WS_VSCROLL;
5787 if (style != oldstyle) {
5788 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5789 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5790 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5794 /* Untick the menu item in the System and context menus. */
5797 for (i = 0; i < lenof(popup_menus); i++)
5798 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED);
5803 * Toggle full-screen mode.
5805 static void flip_full_screen()
5807 if (is_full_screen()) {
5808 ShowWindow(hwnd, SW_RESTORE);
5809 } else if (IsZoomed(hwnd)) {
5812 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5813 ShowWindow(hwnd, SW_MAXIMIZE);
5817 void frontend_keypress(void *handle)
5820 * Keypress termination in non-Close-On-Exit mode is not
5821 * currently supported in PuTTY proper, because the window
5822 * always has a perfectly good Close button anyway. So we do
5828 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5830 return term_data(term, is_stderr, data, len);
5833 int from_backend_untrusted(void *frontend, const char *data, int len)
5835 return term_data_untrusted(term, data, len);
5838 int from_backend_eof(void *frontend)
5840 return TRUE; /* do respond to incoming EOF with outgoing */
5843 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
5846 ret = cmdline_get_passwd_input(p, in, inlen);
5848 ret = term_get_userpass_input(term, p, in, inlen);
5852 void agent_schedule_callback(void (*callback)(void *, void *, int),
5853 void *callback_ctx, void *data, int len)
5855 struct agent_callback *c = snew(struct agent_callback);
5856 c->callback = callback;
5857 c->callback_ctx = callback_ctx;
5860 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);