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 char *get_ttymode(void *frontend, const char *mode)
234 return term_get_ttymode(term, mode);
237 static void start_backend(void)
240 char msg[1024], *title;
245 * Select protocol. This is farmed out into a table in a
246 * separate file to enable an ssh-free variant.
248 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
250 char *str = dupprintf("%s Internal Error", appname);
251 MessageBox(NULL, "Unsupported protocol number found",
252 str, MB_OK | MB_ICONEXCLAMATION);
257 error = back->init(NULL, &backhandle, conf,
258 conf_get_str(conf, CONF_host),
259 conf_get_int(conf, CONF_port),
261 conf_get_int(conf, CONF_tcp_nodelay),
262 conf_get_int(conf, CONF_tcp_keepalives));
263 back->provide_logctx(backhandle, logctx);
265 char *str = dupprintf("%s Error", appname);
266 sprintf(msg, "Unable to open connection to\n"
267 "%.800s\n" "%s", conf_dest(conf), error);
268 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
272 window_name = icon_name = NULL;
273 title = conf_get_str(conf, CONF_wintitle);
275 sprintf(msg, "%s - %s", realhost, appname);
279 set_title(NULL, title);
280 set_icon(NULL, title);
283 * Connect the terminal to the backend for resize purposes.
285 term_provide_resize_fn(term, back->size, backhandle);
288 * Set up a line discipline.
290 ldisc = ldisc_create(conf, term, back, backhandle, NULL);
293 * Destroy the Restart Session menu item. (This will return
294 * failure if it's already absent, as it will be the very first
295 * time we call this function. We ignore that, because as long
296 * as the menu item ends up not being there, we don't care
297 * whether it was us who removed it or not!)
299 for (i = 0; i < lenof(popup_menus); i++) {
300 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
303 session_closed = FALSE;
306 static void close_session(void *ignored_context)
311 session_closed = TRUE;
312 sprintf(morestuff, "%.70s (inactive)", appname);
313 set_icon(NULL, morestuff);
314 set_title(NULL, morestuff);
321 back->free(backhandle);
324 term_provide_resize_fn(term, NULL, NULL);
325 update_specials_menu(NULL);
329 * Show the Restart Session menu item. Do a precautionary
330 * delete first to ensure we never end up with more than one.
332 for (i = 0; i < lenof(popup_menus); i++) {
333 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
334 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
335 IDM_RESTART, "&Restart Session");
339 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
343 int guess_width, guess_height;
347 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
351 InitCommonControls();
353 /* Ensure a Maximize setting in Explorer doesn't maximise the
359 char *str = dupprintf("%s Fatal Error", appname);
360 MessageBox(NULL, "Windows refuses to report a version",
361 str, MB_OK | MB_ICONEXCLAMATION);
367 * If we're running a version of Windows that doesn't support
368 * WM_MOUSEWHEEL, find out what message number we should be
371 if (osVersion.dwMajorVersion < 4 ||
372 (osVersion.dwMajorVersion == 4 &&
373 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
374 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
385 hr = CoInitialize(NULL);
386 if (hr != S_OK && hr != S_FALSE) {
387 char *str = dupprintf("%s Fatal Error", appname);
388 MessageBox(NULL, "Failed to initialize COM subsystem",
389 str, MB_OK | MB_ICONEXCLAMATION);
395 * Protect our process
400 if (! setprocessacl(error)) {
401 /* FIXME: prepare to stuff this into event log somehow */
402 MessageBox(NULL, "Process protection",
403 error, MB_OK | MB_ICONEXCLAMATION);
409 * Process the command line.
414 /* By default, we bring up the config dialog, rather than launching
415 * a session. This gets set to TRUE if something happens to change
416 * that (e.g., a hostname is specified on the command-line). */
417 int allow_launch = FALSE;
419 default_protocol = be_default_protocol;
420 /* Find the appropriate default port. */
422 Backend *b = backend_from_proto(default_protocol);
423 default_port = 0; /* illegal */
425 default_port = b->default_port;
427 conf_set_int(conf, CONF_logtype, LGTYP_NONE);
429 do_defaults(NULL, conf);
434 * Process a couple of command-line options which are more
435 * easily dealt with before the line is broken up into words.
436 * These are the old-fashioned but convenient @sessionname and
437 * the internal-use-only &sharedmemoryhandle, neither of which
438 * are combined with anything else.
440 while (*p && isspace(*p))
444 * An initial @ means that the whole of the rest of the
445 * command line should be treated as the name of a saved
446 * session, with _no quoting or escaping_. This makes it a
447 * very convenient means of automated saved-session
448 * launching, via IDM_SAVEDSESS or Windows 7 jump lists.
451 while (i > 1 && isspace(p[i - 1]))
454 do_defaults(p + 1, conf);
455 if (!conf_launchable(conf) && !do_config()) {
458 allow_launch = TRUE; /* allow it to be launched directly */
459 } else if (*p == '&') {
461 * An initial & means we've been given a command line
462 * containing the hex value of a HANDLE for a file
463 * mapping object, which we must then interpret as a
469 if (sscanf(p + 1, "%p:%u", &filemap, &cpsize) == 2 &&
470 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
471 0, 0, cpsize)) != NULL) {
472 conf_deserialise(conf, cp, cpsize);
474 CloseHandle(filemap);
475 } else if (!do_config()) {
481 * Otherwise, break up the command line and deal with
487 split_into_argv(cmdline, &argc, &argv, NULL);
489 for (i = 0; i < argc; i++) {
493 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
496 cmdline_error("option \"%s\" requires an argument", p);
497 } else if (ret == 2) {
498 i++; /* skip next argument */
499 } else if (ret == 1) {
500 continue; /* nothing further needs doing */
501 } else if (!strcmp(p, "-cleanup") ||
502 !strcmp(p, "-cleanup-during-uninstall")) {
504 * `putty -cleanup'. Remove all registry
505 * entries associated with PuTTY, and also find
506 * and delete the random seed file.
509 /* Are we being invoked from an uninstaller? */
510 if (!strcmp(p, "-cleanup-during-uninstall")) {
511 s1 = dupprintf("Remove saved sessions and random seed file?\n"
513 "If you hit Yes, ALL Registry entries associated\n"
514 "with %s will be removed, as well as the\n"
515 "random seed file. THIS PROCESS WILL\n"
516 "DESTROY YOUR SAVED SESSIONS.\n"
517 "(This only affects the currently logged-in user.)\n"
519 "If you hit No, uninstallation will proceed, but\n"
520 "saved sessions etc will be left on the machine.",
522 s2 = dupprintf("%s Uninstallation", appname);
524 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
525 "associated with %s, and will also remove\n"
526 "the random seed file. (This only affects the\n"
527 "currently logged-in user.)\n"
529 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
530 "Are you really sure you want to continue?",
532 s2 = dupprintf("%s Warning", appname);
534 if (message_box(s1, s2,
535 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
536 HELPCTXID(option_cleanup)) == IDYES) {
542 } else if (!strcmp(p, "-pgpfp")) {
545 } else if (*p != '-') {
549 * If we already have a host name, treat
550 * this argument as a port number. NB we
551 * have to treat this as a saved -P
552 * argument, so that it will be deferred
553 * until it's a good moment to run it.
555 int ret = cmdline_process_param("-P", p, 1, conf);
557 } else if (!strncmp(q, "telnet:", 7)) {
559 * If the hostname starts with "telnet:",
560 * set the protocol to Telnet and process
561 * the string as a Telnet URL.
566 if (q[0] == '/' && q[1] == '/')
568 conf_set_int(conf, CONF_protocol, PROT_TELNET);
570 p += host_strcspn(p, ":/");
575 conf_set_int(conf, CONF_port, atoi(p));
577 conf_set_int(conf, CONF_port, -1);
578 conf_set_str(conf, CONF_host, q);
582 * Otherwise, treat this argument as a host
585 while (*p && !isspace(*p))
589 conf_set_str(conf, CONF_host, q);
593 cmdline_error("unknown option \"%s\"", p);
598 cmdline_run_saved(conf);
600 if (loaded_session || got_host)
603 if ((!allow_launch || !conf_launchable(conf)) && !do_config()) {
608 * Muck about with the hostname in various ways.
611 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
612 char *host = hostbuf;
616 * Trim leading whitespace.
618 host += strspn(host, " \t");
621 * See if host is of the form user@host, and separate
622 * out the username if so.
624 if (host[0] != '\0') {
625 char *atsign = strrchr(host, '@');
628 conf_set_str(conf, CONF_username, host);
634 * Trim a colon suffix off the hostname if it's there. In
635 * order to protect unbracketed IPv6 address literals
636 * against this treatment, we do not do this if there's
637 * _more_ than one colon.
640 char *c = host_strchr(host, ':');
643 char *d = host_strchr(c+1, ':');
650 * Remove any remaining whitespace.
655 if (*q != ' ' && *q != '\t')
661 conf_set_str(conf, CONF_host, hostbuf);
670 wndclass.lpfnWndProc = WndProc;
671 wndclass.cbClsExtra = 0;
672 wndclass.cbWndExtra = 0;
673 wndclass.hInstance = inst;
674 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
675 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
676 wndclass.hbrBackground = NULL;
677 wndclass.lpszMenuName = NULL;
678 wndclass.lpszClassName = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
680 RegisterClassW(&wndclass);
683 memset(&ucsdata, 0, sizeof(ucsdata));
690 * Guess some defaults for the window size. This all gets
691 * updated later, so we don't really care too much. However, we
692 * do want the font width/height guesses to correspond to a
693 * large font rather than a small one...
700 guess_width = extra_width + font_width * conf_get_int(conf, CONF_width);
701 guess_height = extra_height + font_height*conf_get_int(conf, CONF_height);
704 get_fullscreen_rect(&r);
705 if (guess_width > r.right - r.left)
706 guess_width = r.right - r.left;
707 if (guess_height > r.bottom - r.top)
708 guess_height = r.bottom - r.top;
712 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
714 wchar_t *uappname = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
715 if (!conf_get_int(conf, CONF_scrollbar))
716 winmode &= ~(WS_VSCROLL);
717 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
718 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
719 if (conf_get_int(conf, CONF_alwaysontop))
720 exwinmode |= WS_EX_TOPMOST;
721 if (conf_get_int(conf, CONF_sunken_edge))
722 exwinmode |= WS_EX_CLIENTEDGE;
723 hwnd = CreateWindowExW(exwinmode, uappname, uappname,
724 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
725 guess_width, guess_height,
726 NULL, NULL, inst, NULL);
731 * Initialise the fonts, simultaneously correcting the guesses
732 * for font_{width,height}.
737 * Initialise the terminal. (We have to do this _after_
738 * creating the window, since the terminal is the first thing
739 * which will call schedule_timer(), which will in turn call
740 * timer_change_notify() which will expect hwnd to exist.)
742 term = term_init(conf, &ucsdata, NULL);
743 logctx = log_init(NULL, conf);
744 term_provide_logctx(term, logctx);
745 term_size(term, conf_get_int(conf, CONF_height),
746 conf_get_int(conf, CONF_width),
747 conf_get_int(conf, CONF_savelines));
750 * Correct the guesses for extra_{width,height}.
754 GetWindowRect(hwnd, &wr);
755 GetClientRect(hwnd, &cr);
756 offset_width = offset_height = conf_get_int(conf, CONF_window_border);
757 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
758 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
762 * Resize the window, now we know what size we _really_ want it
765 guess_width = extra_width + font_width * term->cols;
766 guess_height = extra_height + font_height * term->rows;
767 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
768 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
771 * Set up a caret bitmap, with no content.
775 int size = (font_width + 15) / 16 * 2 * font_height;
776 bits = snewn(size, char);
777 memset(bits, 0, size);
778 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
781 CreateCaret(hwnd, caretbm, font_width, font_height);
784 * Initialise the scroll bar.
789 si.cbSize = sizeof(si);
790 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
792 si.nMax = term->rows - 1;
793 si.nPage = term->rows;
795 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
799 * Prepare the mouse handler.
801 lastact = MA_NOTHING;
802 lastbtn = MBT_NOTHING;
803 dbltime = GetDoubleClickTime();
806 * Set up the session-control options on the system menu.
813 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
814 popup_menus[CTXMENU].menu = CreatePopupMenu();
815 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
817 savedsess_menu = CreateMenu();
818 get_sesslist(&sesslist, TRUE);
819 update_savedsess_menu();
821 for (j = 0; j < lenof(popup_menus); j++) {
822 m = popup_menus[j].menu;
824 AppendMenu(m, MF_SEPARATOR, 0, 0);
825 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
826 AppendMenu(m, MF_SEPARATOR, 0, 0);
827 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
828 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
829 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) savedsess_menu,
831 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
832 AppendMenu(m, MF_SEPARATOR, 0, 0);
833 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
834 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
835 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
836 AppendMenu(m, MF_SEPARATOR, 0, 0);
837 AppendMenu(m, (conf_get_int(conf, CONF_resize_action)
838 == RESIZE_DISABLED) ? MF_GRAYED : MF_ENABLED,
839 IDM_FULLSCREEN, "&Full Screen");
840 AppendMenu(m, MF_SEPARATOR, 0, 0);
842 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
843 str = dupprintf("&About %s", appname);
844 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
852 * Set up the initial input locale.
854 set_input_locale(GetKeyboardLayout(0));
857 * Finally show the window!
859 ShowWindow(hwnd, show);
860 SetForegroundWindow(hwnd);
863 * Set the palette up.
869 term_set_focus(term, GetForegroundWindow() == hwnd);
877 if (toplevel_callback_pending() ||
878 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
880 * If we have anything we'd like to do immediately, set
881 * the timeout for MsgWaitForMultipleObjects to zero so
882 * that we'll only do a quick check of our handles and
883 * then get on with whatever that was.
885 * One such option is a pending toplevel callback. The
886 * other is a non-empty Windows message queue, which you'd
887 * think we could leave to MsgWaitForMultipleObjects to
888 * check for us along with all the handles, but in fact we
889 * can't because once PeekMessage in one iteration of this
890 * loop has removed a message from the queue, the whole
891 * queue is considered uninteresting by the next
892 * invocation of MWFMO. So we check ourselves whether the
893 * message queue is non-empty, and if so, set this timeout
894 * to zero to ensure MWFMO doesn't block.
899 /* The messages seem unreliable; especially if we're being tricky */
900 term_set_focus(term, GetForegroundWindow() == hwnd);
903 handles = handle_get_events(&nhandles);
905 n = MsgWaitForMultipleObjects(nhandles, handles, FALSE,
906 timeout, QS_ALLINPUT);
908 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
909 handle_got_event(handles[n - WAIT_OBJECT_0]);
914 while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
915 if (msg.message == WM_QUIT)
916 goto finished; /* two-level break */
918 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
919 DispatchMessageW(&msg);
922 * WM_NETEVENT messages seem to jump ahead of others in
923 * the message queue. I'm not sure why; the docs for
924 * PeekMessage mention that messages are prioritised in
925 * some way, but I'm unclear on which priorities go where.
927 * Anyway, in practice I observe that WM_NETEVENT seems to
928 * jump to the head of the queue, which means that if we
929 * were to only process one message every time round this
930 * loop, we'd get nothing but NETEVENTs if the server
931 * flooded us with data, and stop responding to any other
932 * kind of window message. So instead, we keep on round
933 * this loop until we've consumed at least one message
934 * that _isn't_ a NETEVENT, or run out of messages
935 * completely (whichever comes first). And we don't go to
936 * run_toplevel_callbacks (which is where the netevents
937 * are actually processed, causing fresh NETEVENT messages
938 * to appear) until we've done this.
940 if (msg.message != WM_NETEVENT)
944 run_toplevel_callbacks();
948 cleanup_exit(msg.wParam); /* this doesn't return... */
949 return msg.wParam; /* ... but optimiser doesn't know */
955 void cleanup_exit(int code)
966 if (conf_get_int(conf, CONF_protocol) == PROT_SSH) {
981 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
983 char *do_select(SOCKET skt, int startup)
988 events = (FD_CONNECT | FD_READ | FD_WRITE |
989 FD_OOB | FD_CLOSE | FD_ACCEPT);
994 return "do_select(): internal error (hwnd==NULL)";
995 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
996 switch (p_WSAGetLastError()) {
998 return "Network is down";
1000 return "WSAAsyncSelect(): unknown error";
1007 * Refresh the saved-session submenu from `sesslist'.
1009 static void update_savedsess_menu(void)
1012 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
1013 /* skip sesslist.sessions[0] == Default Settings */
1015 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
1016 : MENU_SAVED_MAX+1);
1018 AppendMenu(savedsess_menu, MF_ENABLED,
1019 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
1020 sesslist.sessions[i]);
1021 if (sesslist.nsessions <= 1)
1022 AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)");
1026 * Update the Special Commands submenu.
1028 void update_specials_menu(void *frontend)
1034 specials = back->get_specials(backhandle);
1039 /* We can't use Windows to provide a stack for submenus, so
1040 * here's a lame "stack" that will do for now. */
1041 HMENU saved_menu = NULL;
1043 new_menu = CreatePopupMenu();
1044 for (i = 0; nesting > 0; i++) {
1045 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
1046 switch (specials[i].code) {
1048 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
1051 assert(nesting < 2);
1053 saved_menu = new_menu; /* XXX lame stacking */
1054 new_menu = CreatePopupMenu();
1055 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
1056 (UINT) new_menu, specials[i].name);
1061 new_menu = saved_menu; /* XXX lame stacking */
1066 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
1071 /* Squirrel the highest special. */
1078 for (j = 0; j < lenof(popup_menus); j++) {
1079 if (specials_menu) {
1080 /* XXX does this free up all submenus? */
1081 DeleteMenu(popup_menus[j].menu, (UINT)specials_menu, MF_BYCOMMAND);
1082 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
1085 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1086 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
1087 (UINT) new_menu, "S&pecial Command");
1088 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1089 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
1092 specials_menu = new_menu;
1095 static void update_mouse_pointer(void)
1098 int force_visible = FALSE;
1099 static int forced_visible = FALSE;
1100 switch (busy_status) {
1103 curstype = IDC_ARROW;
1105 curstype = IDC_IBEAM;
1108 curstype = IDC_APPSTARTING; /* this may be an abuse */
1109 force_visible = TRUE;
1112 curstype = IDC_WAIT;
1113 force_visible = TRUE;
1119 HCURSOR cursor = LoadCursor(NULL, curstype);
1120 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1121 SetCursor(cursor); /* force redraw of cursor at current posn */
1123 if (force_visible != forced_visible) {
1124 /* We want some cursor shapes to be visible always.
1125 * Along with show_mouseptr(), this manages the ShowCursor()
1126 * counter such that if we switch back to a non-force_visible
1127 * cursor, the previous visibility state is restored. */
1128 ShowCursor(force_visible);
1129 forced_visible = force_visible;
1133 void set_busy_status(void *frontend, int status)
1135 busy_status = status;
1136 update_mouse_pointer();
1140 * set or clear the "raw mouse message" mode
1142 void set_raw_mouse_mode(void *frontend, int activate)
1144 activate = activate && !conf_get_int(conf, CONF_no_mouse_rep);
1145 send_raw_mouse = activate;
1146 update_mouse_pointer();
1150 * Print a message box and close the connection.
1152 void connection_fatal(void *frontend, const char *fmt, ...)
1155 char *stuff, morestuff[100];
1158 stuff = dupvprintf(fmt, ap);
1160 sprintf(morestuff, "%.70s Fatal Error", appname);
1161 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1164 if (conf_get_int(conf, CONF_close_on_exit) == FORCE_ON)
1167 queue_toplevel_callback(close_session, NULL);
1172 * Report an error at the command-line parsing stage.
1174 void cmdline_error(const char *fmt, ...)
1177 char *stuff, morestuff[100];
1180 stuff = dupvprintf(fmt, ap);
1182 sprintf(morestuff, "%.70s Command Line Error", appname);
1183 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1189 * Actually do the job requested by a WM_NETEVENT
1191 static void wm_netevent_callback(void *vctx)
1193 struct wm_netevent_params *params = (struct wm_netevent_params *)vctx;
1194 select_result(params->wParam, params->lParam);
1199 * Copy the colour palette from the configuration data into defpal.
1200 * This is non-trivial because the colour indices are different.
1202 static void conftopalette(void)
1205 static const int ww[] = {
1206 256, 257, 258, 259, 260, 261,
1207 0, 8, 1, 9, 2, 10, 3, 11,
1208 4, 12, 5, 13, 6, 14, 7, 15
1211 for (i = 0; i < 22; i++) {
1213 defpal[w].rgbtRed = conf_get_int_int(conf, CONF_colours, i*3+0);
1214 defpal[w].rgbtGreen = conf_get_int_int(conf, CONF_colours, i*3+1);
1215 defpal[w].rgbtBlue = conf_get_int_int(conf, CONF_colours, i*3+2);
1217 for (i = 0; i < NEXTCOLOURS; i++) {
1219 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1220 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1221 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1222 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
1224 int shade = i - 216;
1225 shade = shade * 10 + 8;
1226 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1227 defpal[i+16].rgbtBlue = shade;
1231 /* Override with system colours if appropriate */
1232 if (conf_get_int(conf, CONF_system_colour))
1237 * Override bit of defpal with colours from the system.
1238 * (NB that this takes a copy the system colours at the time this is called,
1239 * so subsequent colour scheme changes don't take effect. To fix that we'd
1240 * probably want to be using GetSysColorBrush() and the like.)
1242 static void systopalette(void)
1245 static const struct { int nIndex; int norm; int bold; } or[] =
1247 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1248 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1249 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1250 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1253 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1254 COLORREF colour = GetSysColor(or[i].nIndex);
1255 defpal[or[i].norm].rgbtRed =
1256 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1257 defpal[or[i].norm].rgbtGreen =
1258 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1259 defpal[or[i].norm].rgbtBlue =
1260 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1265 * Set up the colour palette.
1267 static void init_palette(void)
1270 HDC hdc = GetDC(hwnd);
1272 if (conf_get_int(conf, CONF_try_palette) &&
1273 GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1275 * This is a genuine case where we must use smalloc
1276 * because the snew macros can't cope.
1278 logpal = smalloc(sizeof(*logpal)
1279 - sizeof(logpal->palPalEntry)
1280 + NALLCOLOURS * sizeof(PALETTEENTRY));
1281 logpal->palVersion = 0x300;
1282 logpal->palNumEntries = NALLCOLOURS;
1283 for (i = 0; i < NALLCOLOURS; i++) {
1284 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1285 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1286 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1287 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1289 pal = CreatePalette(logpal);
1291 SelectPalette(hdc, pal, FALSE);
1292 RealizePalette(hdc);
1293 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1296 ReleaseDC(hwnd, hdc);
1299 for (i = 0; i < NALLCOLOURS; i++)
1300 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1301 defpal[i].rgbtGreen,
1302 defpal[i].rgbtBlue);
1304 for (i = 0; i < NALLCOLOURS; i++)
1305 colours[i] = RGB(defpal[i].rgbtRed,
1306 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1310 * This is a wrapper to ExtTextOut() to force Windows to display
1311 * the precise glyphs we give it. Otherwise it would do its own
1312 * bidi and Arabic shaping, and we would end up uncertain which
1313 * characters it had put where.
1315 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1316 unsigned short *lpString, UINT cbCount,
1317 CONST INT *lpDx, int opaque)
1321 * The LCC include files apparently don't supply the
1322 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1323 * proper: the differences aren't important to us (the only
1324 * variable-width string parameter is one we don't use anyway).
1330 char *buffer = snewn(cbCount*2+2, char);
1331 char *classbuffer = snewn(cbCount, char);
1332 memset(&gcpr, 0, sizeof(gcpr));
1333 memset(buffer, 0, cbCount*2+2);
1334 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1336 gcpr.lStructSize = sizeof(gcpr);
1337 gcpr.lpGlyphs = (void *)buffer;
1338 gcpr.lpClass = (void *)classbuffer;
1339 gcpr.nGlyphs = cbCount;
1340 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1341 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1343 ExtTextOut(hdc, x, y,
1344 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1345 lprc, buffer, cbCount, lpDx);
1349 * The exact_textout() wrapper, unfortunately, destroys the useful
1350 * Windows `font linking' behaviour: automatic handling of Unicode
1351 * code points not supported in this font by falling back to a font
1352 * which does contain them. Therefore, we adopt a multi-layered
1353 * approach: for any potentially-bidi text, we use exact_textout(),
1354 * and for everything else we use a simple ExtTextOut as we did
1355 * before exact_textout() was introduced.
1357 static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1358 unsigned short *lpString, UINT cbCount,
1359 CONST INT *lpDx, int opaque)
1362 int bkmode = 0, got_bkmode = FALSE;
1366 for (i = 0; i < (int)cbCount ;) {
1367 int rtl = is_rtl(lpString[i]);
1371 for (j = i+1; j < (int)cbCount; j++) {
1372 if (rtl != is_rtl(lpString[j]))
1378 * Now [i,j) indicates a maximal substring of lpString
1379 * which should be displayed using the same textout
1383 exact_textout(hdc, xp, y, lprc, lpString+i, j-i,
1384 font_varpitch ? NULL : lpDx+i, opaque);
1386 ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1387 lprc, lpString+i, j-i,
1388 font_varpitch ? NULL : lpDx+i);
1394 bkmode = GetBkMode(hdc);
1396 SetBkMode(hdc, TRANSPARENT);
1401 SetBkMode(hdc, bkmode);
1404 static int get_font_width(HDC hdc, const TEXTMETRIC *tm)
1407 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1408 if (!(tm->tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1409 ret = tm->tmAveCharWidth;
1413 ABCFLOAT widths[LAST-FIRST + 1];
1416 font_varpitch = TRUE;
1417 font_dualwidth = TRUE;
1418 if (GetCharABCWidthsFloat(hdc, FIRST, LAST, widths)) {
1420 for (j = 0; j < lenof(widths); j++) {
1421 int width = (int)(0.5 + widths[j].abcfA +
1422 widths[j].abcfB + widths[j].abcfC);
1427 ret = tm->tmMaxCharWidth;
1436 * Initialise all the fonts we will need initially. There may be as many as
1437 * three or as few as one. The other (potentially) twenty-one fonts are done
1438 * if/when they are needed.
1442 * - check the font width and height, correcting our guesses if
1445 * - verify that the bold font is the same width as the ordinary
1446 * one, and engage shadow bolding if not.
1448 * - verify that the underlined font is the same width as the
1449 * ordinary one (manual underlining by means of line drawing can
1450 * be done in a pinch).
1452 static void init_fonts(int pick_width, int pick_height)
1461 int fw_dontcare, fw_bold;
1463 for (i = 0; i < FONT_MAXNO; i++)
1466 bold_font_mode = conf_get_int(conf, CONF_bold_style) & 1 ?
1467 BOLD_FONT : BOLD_NONE;
1468 bold_colours = conf_get_int(conf, CONF_bold_style) & 2 ? TRUE : FALSE;
1469 und_mode = UND_FONT;
1471 font = conf_get_fontspec(conf, CONF_font);
1473 fw_dontcare = FW_BOLD;
1476 fw_dontcare = FW_DONTCARE;
1483 font_height = pick_height;
1485 font_height = font->height;
1486 if (font_height > 0) {
1488 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1491 font_width = pick_width;
1493 quality = conf_get_int(conf, CONF_font_quality);
1494 #define f(i,c,w,u) \
1495 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1496 c, OUT_DEFAULT_PRECIS, \
1497 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), \
1498 FIXED_PITCH | FF_DONTCARE, font->name)
1500 f(FONT_NORMAL, font->charset, fw_dontcare, FALSE);
1502 SelectObject(hdc, fonts[FONT_NORMAL]);
1503 GetTextMetrics(hdc, &tm);
1505 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1507 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1508 if (!(tm.tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1509 font_varpitch = FALSE;
1510 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1512 font_varpitch = TRUE;
1513 font_dualwidth = TRUE;
1515 if (pick_width == 0 || pick_height == 0) {
1516 font_height = tm.tmHeight;
1517 font_width = get_font_width(hdc, &tm);
1520 #ifdef RDB_DEBUG_PATCH
1521 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1522 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1527 DWORD cset = tm.tmCharSet;
1528 memset(&info, 0xFF, sizeof(info));
1530 /* !!! Yes the next line is right */
1531 if (cset == OEM_CHARSET)
1532 ucsdata.font_codepage = GetOEMCP();
1534 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1535 ucsdata.font_codepage = info.ciACP;
1537 ucsdata.font_codepage = -1;
1539 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1540 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1543 f(FONT_UNDERLINE, font->charset, fw_dontcare, TRUE);
1546 * Some fonts, e.g. 9-pt Courier, draw their underlines
1547 * outside their character cell. We successfully prevent
1548 * screen corruption by clipping the text output, but then
1549 * we lose the underline completely. Here we try to work
1550 * out whether this is such a font, and if it is, we set a
1551 * flag that causes underlines to be drawn by hand.
1553 * Having tried other more sophisticated approaches (such
1554 * as examining the TEXTMETRIC structure or requesting the
1555 * height of a string), I think we'll do this the brute
1556 * force way: we create a small bitmap, draw an underlined
1557 * space on it, and test to see whether any pixels are
1558 * foreground-coloured. (Since we expect the underline to
1559 * go all the way across the character cell, we only search
1560 * down a single column of the bitmap, half way across.)
1564 HBITMAP und_bm, und_oldbm;
1568 und_dc = CreateCompatibleDC(hdc);
1569 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1570 und_oldbm = SelectObject(und_dc, und_bm);
1571 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1572 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1573 SetTextColor(und_dc, RGB(255, 255, 255));
1574 SetBkColor(und_dc, RGB(0, 0, 0));
1575 SetBkMode(und_dc, OPAQUE);
1576 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1578 for (i = 0; i < font_height; i++) {
1579 c = GetPixel(und_dc, font_width / 2, i);
1580 if (c != RGB(0, 0, 0))
1583 SelectObject(und_dc, und_oldbm);
1584 DeleteObject(und_bm);
1587 und_mode = UND_LINE;
1588 DeleteObject(fonts[FONT_UNDERLINE]);
1589 fonts[FONT_UNDERLINE] = 0;
1593 if (bold_font_mode == BOLD_FONT) {
1594 f(FONT_BOLD, font->charset, fw_bold, FALSE);
1598 descent = tm.tmAscent + 1;
1599 if (descent >= font_height)
1600 descent = font_height - 1;
1602 for (i = 0; i < 3; i++) {
1604 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1605 fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight;
1612 ReleaseDC(hwnd, hdc);
1614 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1615 und_mode = UND_LINE;
1616 DeleteObject(fonts[FONT_UNDERLINE]);
1617 fonts[FONT_UNDERLINE] = 0;
1620 if (bold_font_mode == BOLD_FONT &&
1621 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1622 bold_font_mode = BOLD_SHADOW;
1623 DeleteObject(fonts[FONT_BOLD]);
1624 fonts[FONT_BOLD] = 0;
1626 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1628 init_ucs(conf, &ucsdata);
1631 static void another_font(int fontno)
1634 int fw_dontcare, fw_bold, quality;
1639 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1642 basefont = (fontno & ~(FONT_BOLDUND));
1643 if (basefont != fontno && !fontflag[basefont])
1644 another_font(basefont);
1646 font = conf_get_fontspec(conf, CONF_font);
1649 fw_dontcare = FW_BOLD;
1652 fw_dontcare = FW_DONTCARE;
1662 if (fontno & FONT_WIDE)
1664 if (fontno & FONT_NARROW)
1666 if (fontno & FONT_OEM)
1668 if (fontno & FONT_BOLD)
1670 if (fontno & FONT_UNDERLINE)
1673 quality = conf_get_int(conf, CONF_font_quality);
1676 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1677 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1678 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality),
1679 DEFAULT_PITCH | FF_DONTCARE, s);
1681 fontflag[fontno] = 1;
1684 static void deinit_fonts(void)
1687 for (i = 0; i < FONT_MAXNO; i++) {
1689 DeleteObject(fonts[i]);
1695 void request_resize(void *frontend, int w, int h)
1699 /* If the window is maximized supress resizing attempts */
1700 if (IsZoomed(hwnd)) {
1701 if (conf_get_int(conf, CONF_resize_action) == RESIZE_TERM)
1705 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) return;
1706 if (h == term->rows && w == term->cols) return;
1708 /* Sanity checks ... */
1710 static int first_time = 1;
1713 switch (first_time) {
1715 /* Get the size of the screen */
1716 if (get_fullscreen_rect(&ss))
1717 /* first_time = 0 */ ;
1723 /* Make sure the values are sane */
1724 width = (ss.right - ss.left - extra_width) / 4;
1725 height = (ss.bottom - ss.top - extra_height) / 6;
1727 if (w > width || h > height)
1736 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
1738 if (conf_get_int(conf, CONF_resize_action) != RESIZE_FONT &&
1740 width = extra_width + font_width * w;
1741 height = extra_height + font_height * h;
1743 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1744 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1745 SWP_NOMOVE | SWP_NOZORDER);
1749 InvalidateRect(hwnd, NULL, TRUE);
1752 static void reset_window(int reinit) {
1754 * This function decides how to resize or redraw when the
1755 * user changes something.
1757 * This function doesn't like to change the terminal size but if the
1758 * font size is locked that may be it's only soluion.
1760 int win_width, win_height, resize_action, window_border;
1763 #ifdef RDB_DEBUG_PATCH
1764 debug((27, "reset_window()"));
1767 /* Current window sizes ... */
1768 GetWindowRect(hwnd, &wr);
1769 GetClientRect(hwnd, &cr);
1771 win_width = cr.right - cr.left;
1772 win_height = cr.bottom - cr.top;
1774 resize_action = conf_get_int(conf, CONF_resize_action);
1775 window_border = conf_get_int(conf, CONF_window_border);
1777 if (resize_action == RESIZE_DISABLED)
1780 /* Are we being forced to reload the fonts ? */
1782 #ifdef RDB_DEBUG_PATCH
1783 debug((27, "reset_window() -- Forced deinit"));
1789 /* Oh, looks like we're minimised */
1790 if (win_width == 0 || win_height == 0)
1793 /* Is the window out of position ? */
1795 (offset_width != (win_width-font_width*term->cols)/2 ||
1796 offset_height != (win_height-font_height*term->rows)/2) ){
1797 offset_width = (win_width-font_width*term->cols)/2;
1798 offset_height = (win_height-font_height*term->rows)/2;
1799 InvalidateRect(hwnd, NULL, TRUE);
1800 #ifdef RDB_DEBUG_PATCH
1801 debug((27, "reset_window() -> Reposition terminal"));
1805 if (IsZoomed(hwnd)) {
1806 /* We're fullscreen, this means we must not change the size of
1807 * the window so it's the font size or the terminal itself.
1810 extra_width = wr.right - wr.left - cr.right + cr.left;
1811 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1813 if (resize_action != RESIZE_TERM) {
1814 if (font_width != win_width/term->cols ||
1815 font_height != win_height/term->rows) {
1817 init_fonts(win_width/term->cols, win_height/term->rows);
1818 offset_width = (win_width-font_width*term->cols)/2;
1819 offset_height = (win_height-font_height*term->rows)/2;
1820 InvalidateRect(hwnd, NULL, TRUE);
1821 #ifdef RDB_DEBUG_PATCH
1822 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1823 font_width, font_height));
1827 if (font_width * term->cols != win_width ||
1828 font_height * term->rows != win_height) {
1829 /* Our only choice at this point is to change the
1830 * size of the terminal; Oh well.
1832 term_size(term, win_height/font_height, win_width/font_width,
1833 conf_get_int(conf, CONF_savelines));
1834 offset_width = (win_width-font_width*term->cols)/2;
1835 offset_height = (win_height-font_height*term->rows)/2;
1836 InvalidateRect(hwnd, NULL, TRUE);
1837 #ifdef RDB_DEBUG_PATCH
1838 debug((27, "reset_window() -> Zoomed term_size"));
1845 /* Hmm, a force re-init means we should ignore the current window
1846 * so we resize to the default font size.
1849 #ifdef RDB_DEBUG_PATCH
1850 debug((27, "reset_window() -> Forced re-init"));
1853 offset_width = offset_height = window_border;
1854 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1855 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1857 if (win_width != font_width*term->cols + offset_width*2 ||
1858 win_height != font_height*term->rows + offset_height*2) {
1860 /* If this is too large windows will resize it to the maximum
1861 * allowed window size, we will then be back in here and resize
1862 * the font or terminal to fit.
1864 SetWindowPos(hwnd, NULL, 0, 0,
1865 font_width*term->cols + extra_width,
1866 font_height*term->rows + extra_height,
1867 SWP_NOMOVE | SWP_NOZORDER);
1870 InvalidateRect(hwnd, NULL, TRUE);
1874 /* Okay the user doesn't want us to change the font so we try the
1875 * window. But that may be too big for the screen which forces us
1876 * to change the terminal.
1878 if ((resize_action == RESIZE_TERM && reinit<=0) ||
1879 (resize_action == RESIZE_EITHER && reinit<0) ||
1881 offset_width = offset_height = window_border;
1882 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1883 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1885 if (win_width != font_width*term->cols + offset_width*2 ||
1886 win_height != font_height*term->rows + offset_height*2) {
1891 get_fullscreen_rect(&ss);
1893 width = (ss.right - ss.left - extra_width) / font_width;
1894 height = (ss.bottom - ss.top - extra_height) / font_height;
1897 if ( term->rows > height || term->cols > width ) {
1898 if (resize_action == RESIZE_EITHER) {
1899 /* Make the font the biggest we can */
1900 if (term->cols > width)
1901 font_width = (ss.right - ss.left - extra_width)
1903 if (term->rows > height)
1904 font_height = (ss.bottom - ss.top - extra_height)
1908 init_fonts(font_width, font_height);
1910 width = (ss.right - ss.left - extra_width) / font_width;
1911 height = (ss.bottom - ss.top - extra_height) / font_height;
1913 if ( height > term->rows ) height = term->rows;
1914 if ( width > term->cols ) width = term->cols;
1915 term_size(term, height, width,
1916 conf_get_int(conf, CONF_savelines));
1917 #ifdef RDB_DEBUG_PATCH
1918 debug((27, "reset_window() -> term resize to (%d,%d)",
1924 SetWindowPos(hwnd, NULL, 0, 0,
1925 font_width*term->cols + extra_width,
1926 font_height*term->rows + extra_height,
1927 SWP_NOMOVE | SWP_NOZORDER);
1929 InvalidateRect(hwnd, NULL, TRUE);
1930 #ifdef RDB_DEBUG_PATCH
1931 debug((27, "reset_window() -> window resize to (%d,%d)",
1932 font_width*term->cols + extra_width,
1933 font_height*term->rows + extra_height));
1939 /* We're allowed to or must change the font but do we want to ? */
1941 if (font_width != (win_width-window_border*2)/term->cols ||
1942 font_height != (win_height-window_border*2)/term->rows) {
1945 init_fonts((win_width-window_border*2)/term->cols,
1946 (win_height-window_border*2)/term->rows);
1947 offset_width = (win_width-font_width*term->cols)/2;
1948 offset_height = (win_height-font_height*term->rows)/2;
1950 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1951 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1953 InvalidateRect(hwnd, NULL, TRUE);
1954 #ifdef RDB_DEBUG_PATCH
1955 debug((25, "reset_window() -> font resize to (%d,%d)",
1956 font_width, font_height));
1961 static void set_input_locale(HKL kl)
1965 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1966 lbuf, sizeof(lbuf));
1968 kbd_codepage = atoi(lbuf);
1971 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1973 int thistime = GetMessageTime();
1975 if (send_raw_mouse &&
1976 !(shift && conf_get_int(conf, CONF_mouse_override))) {
1977 lastbtn = MBT_NOTHING;
1978 term_mouse(term, b, translate_button(b), MA_CLICK,
1979 x, y, shift, ctrl, alt);
1983 if (lastbtn == b && thistime - lasttime < dbltime) {
1984 lastact = (lastact == MA_CLICK ? MA_2CLK :
1985 lastact == MA_2CLK ? MA_3CLK :
1986 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1991 if (lastact != MA_NOTHING)
1992 term_mouse(term, b, translate_button(b), lastact,
1993 x, y, shift, ctrl, alt);
1994 lasttime = thistime;
1998 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1999 * into a cooked one (SELECT, EXTEND, PASTE).
2001 static Mouse_Button translate_button(Mouse_Button button)
2003 if (button == MBT_LEFT)
2005 if (button == MBT_MIDDLE)
2006 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2007 MBT_PASTE : MBT_EXTEND;
2008 if (button == MBT_RIGHT)
2009 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2010 MBT_EXTEND : MBT_PASTE;
2011 return 0; /* shouldn't happen */
2014 static void show_mouseptr(int show)
2016 /* NB that the counter in ShowCursor() is also frobbed by
2017 * update_mouse_pointer() */
2018 static int cursor_visible = 1;
2019 if (!conf_get_int(conf, CONF_hide_mouseptr))
2020 show = 1; /* override if this feature disabled */
2021 if (cursor_visible && !show)
2023 else if (!cursor_visible && show)
2025 cursor_visible = show;
2028 static int is_alt_pressed(void)
2031 int r = GetKeyboardState(keystate);
2034 if (keystate[VK_MENU] & 0x80)
2036 if (keystate[VK_RMENU] & 0x80)
2041 static int resizing;
2043 void notify_remote_exit(void *fe)
2045 int exitcode, close_on_exit;
2047 if (!session_closed &&
2048 (exitcode = back->exitcode(backhandle)) >= 0) {
2049 close_on_exit = conf_get_int(conf, CONF_close_on_exit);
2050 /* Abnormal exits will already have set session_closed and taken
2051 * appropriate action. */
2052 if (close_on_exit == FORCE_ON ||
2053 (close_on_exit == AUTO && exitcode != INT_MAX)) {
2056 queue_toplevel_callback(close_session, NULL);
2057 session_closed = TRUE;
2058 /* exitcode == INT_MAX indicates that the connection was closed
2059 * by a fatal error, so an error box will be coming our way and
2060 * we should not generate this informational one. */
2061 if (exitcode != INT_MAX)
2062 MessageBox(hwnd, "Connection closed by remote host",
2063 appname, MB_OK | MB_ICONINFORMATION);
2068 void timer_change_notify(unsigned long next)
2070 unsigned long now = GETTICKCOUNT();
2072 if (now - next < INT_MAX)
2076 KillTimer(hwnd, TIMING_TIMER_ID);
2077 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
2078 timing_next_time = next;
2081 static void conf_cache_data(void)
2083 /* Cache some items from conf to speed lookups in very hot code */
2084 cursor_type = conf_get_int(conf, CONF_cursor_type);
2085 vtmode = conf_get_int(conf, CONF_vtmode);
2088 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2089 WPARAM wParam, LPARAM lParam)
2092 static int ignore_clip = FALSE;
2093 static int need_backend_resize = FALSE;
2094 static int fullscr_on_max = FALSE;
2095 static int processed_resize = FALSE;
2096 static UINT last_mousemove = 0;
2101 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
2104 KillTimer(hwnd, TIMING_TIMER_ID);
2105 if (run_timers(timing_next_time, &next)) {
2106 timer_change_notify(next);
2117 str = dupprintf("%s Exit Confirmation", appname);
2118 if (session_closed || !conf_get_int(conf, CONF_warn_on_close) ||
2120 "Are you sure you want to close this session?",
2121 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
2123 DestroyWindow(hwnd);
2131 case WM_INITMENUPOPUP:
2132 if ((HMENU)wParam == savedsess_menu) {
2133 /* About to pop up Saved Sessions sub-menu.
2134 * Refresh the session list. */
2135 get_sesslist(&sesslist, FALSE); /* free */
2136 get_sesslist(&sesslist, TRUE);
2137 update_savedsess_menu();
2143 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
2154 BOOL inherit_handles;
2156 PROCESS_INFORMATION pi;
2157 HANDLE filemap = NULL;
2159 if (wParam == IDM_DUPSESS) {
2161 * Allocate a file-mapping memory chunk for the
2164 SECURITY_ATTRIBUTES sa;
2168 size = conf_serialised_size(conf);
2170 sa.nLength = sizeof(sa);
2171 sa.lpSecurityDescriptor = NULL;
2172 sa.bInheritHandle = TRUE;
2173 filemap = CreateFileMapping(INVALID_HANDLE_VALUE,
2177 if (filemap && filemap != INVALID_HANDLE_VALUE) {
2178 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, size);
2180 conf_serialise(conf, p);
2184 inherit_handles = TRUE;
2185 sprintf(c, "putty &%p:%u", filemap, (unsigned)size);
2187 } else if (wParam == IDM_SAVEDSESS) {
2188 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
2189 / MENU_SAVED_STEP) + 1;
2190 if (sessno < (unsigned)sesslist.nsessions) {
2191 const char *session = sesslist.sessions[sessno];
2192 cl = dupprintf("putty @%s", session);
2193 inherit_handles = FALSE;
2197 } else /* IDM_NEWSESS */ {
2199 inherit_handles = FALSE;
2202 GetModuleFileName(NULL, b, sizeof(b) - 1);
2204 si.lpReserved = NULL;
2205 si.lpDesktop = NULL;
2209 si.lpReserved2 = NULL;
2210 CreateProcess(b, cl, NULL, NULL, inherit_handles,
2211 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
2212 CloseHandle(pi.hProcess);
2213 CloseHandle(pi.hThread);
2216 CloseHandle(filemap);
2223 logevent(NULL, "----- Session restarted -----");
2224 term_pwron(term, FALSE);
2233 int reconfig_result;
2238 reconfiguring = TRUE;
2241 * Copy the current window title into the stored
2242 * previous configuration, so that doing nothing to
2243 * the window title field in the config box doesn't
2244 * reset the title to its startup state.
2246 conf_set_str(conf, CONF_wintitle, window_name);
2248 prev_conf = conf_copy(conf);
2251 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2252 reconfiguring = FALSE;
2253 if (!reconfig_result) {
2254 conf_free(prev_conf);
2260 resize_action = conf_get_int(conf, CONF_resize_action);
2262 /* Disable full-screen if resizing forbidden */
2264 for (i = 0; i < lenof(popup_menus); i++)
2265 EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN,
2267 (resize_action == RESIZE_DISABLED)
2268 ? MF_GRAYED : MF_ENABLED);
2269 /* Gracefully unzoom if necessary */
2270 if (IsZoomed(hwnd) && (resize_action == RESIZE_DISABLED))
2271 ShowWindow(hwnd, SW_RESTORE);
2274 /* Pass new config data to the logging module */
2275 log_reconfig(logctx, conf);
2279 * Flush the line discipline's edit buffer in the
2280 * case where local editing has just been disabled.
2283 ldisc_configure(ldisc, conf);
2284 ldisc_echoedit_update(ldisc);
2293 /* Pass new config data to the terminal */
2294 term_reconfig(term, conf);
2296 /* Pass new config data to the back end */
2298 back->reconfig(backhandle, conf);
2300 /* Screen size changed ? */
2301 if (conf_get_int(conf, CONF_height) !=
2302 conf_get_int(prev_conf, CONF_height) ||
2303 conf_get_int(conf, CONF_width) !=
2304 conf_get_int(prev_conf, CONF_width) ||
2305 conf_get_int(conf, CONF_savelines) !=
2306 conf_get_int(prev_conf, CONF_savelines) ||
2307 resize_action == RESIZE_FONT ||
2308 (resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2309 resize_action == RESIZE_DISABLED)
2310 term_size(term, conf_get_int(conf, CONF_height),
2311 conf_get_int(conf, CONF_width),
2312 conf_get_int(conf, CONF_savelines));
2314 /* Enable or disable the scroll bar, etc */
2316 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2317 LONG nexflag, exflag =
2318 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2321 if (conf_get_int(conf, CONF_alwaysontop) !=
2322 conf_get_int(prev_conf, CONF_alwaysontop)) {
2323 if (conf_get_int(conf, CONF_alwaysontop)) {
2324 nexflag |= WS_EX_TOPMOST;
2325 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2326 SWP_NOMOVE | SWP_NOSIZE);
2328 nexflag &= ~(WS_EX_TOPMOST);
2329 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2330 SWP_NOMOVE | SWP_NOSIZE);
2333 if (conf_get_int(conf, CONF_sunken_edge))
2334 nexflag |= WS_EX_CLIENTEDGE;
2336 nexflag &= ~(WS_EX_CLIENTEDGE);
2339 if (conf_get_int(conf, is_full_screen() ?
2340 CONF_scrollbar_in_fullscreen :
2344 nflg &= ~WS_VSCROLL;
2346 if (resize_action == RESIZE_DISABLED ||
2348 nflg &= ~WS_THICKFRAME;
2350 nflg |= WS_THICKFRAME;
2352 if (resize_action == RESIZE_DISABLED)
2353 nflg &= ~WS_MAXIMIZEBOX;
2355 nflg |= WS_MAXIMIZEBOX;
2357 if (nflg != flag || nexflag != exflag) {
2359 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2360 if (nexflag != exflag)
2361 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2363 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2364 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2365 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2373 if (resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2378 set_title(NULL, conf_get_str(conf, CONF_wintitle));
2379 if (IsIconic(hwnd)) {
2381 conf_get_int(conf, CONF_win_name_always) ?
2382 window_name : icon_name);
2386 FontSpec *font = conf_get_fontspec(conf, CONF_font);
2387 FontSpec *prev_font = conf_get_fontspec(prev_conf,
2390 if (!strcmp(font->name, prev_font->name) ||
2391 !strcmp(conf_get_str(conf, CONF_line_codepage),
2392 conf_get_str(prev_conf, CONF_line_codepage)) ||
2393 font->isbold != prev_font->isbold ||
2394 font->height != prev_font->height ||
2395 font->charset != prev_font->charset ||
2396 conf_get_int(conf, CONF_font_quality) !=
2397 conf_get_int(prev_conf, CONF_font_quality) ||
2398 conf_get_int(conf, CONF_vtmode) !=
2399 conf_get_int(prev_conf, CONF_vtmode) ||
2400 conf_get_int(conf, CONF_bold_style) !=
2401 conf_get_int(prev_conf, CONF_bold_style) ||
2402 resize_action == RESIZE_DISABLED ||
2403 resize_action == RESIZE_EITHER ||
2404 resize_action != conf_get_int(prev_conf,
2405 CONF_resize_action))
2409 InvalidateRect(hwnd, NULL, TRUE);
2410 reset_window(init_lvl);
2412 conf_free(prev_conf);
2419 request_paste(NULL);
2425 term_pwron(term, TRUE);
2427 ldisc_echoedit_update(ldisc);
2433 launch_help(hwnd, NULL);
2437 * We get this if the System menu has been activated
2444 * We get this if the System menu has been activated
2445 * using the keyboard. This might happen from within
2446 * TranslateKey, in which case it really wants to be
2447 * followed by a `space' character to actually _bring
2448 * the menu up_ rather than just sitting there in
2449 * `ready to appear' state.
2451 show_mouseptr(1); /* make sure pointer is visible */
2453 PostMessage(hwnd, WM_CHAR, ' ', 0);
2455 case IDM_FULLSCREEN:
2459 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2460 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2462 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2463 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2465 * Ensure we haven't been sent a bogus SYSCOMMAND
2466 * which would cause us to reference invalid memory
2467 * and crash. Perhaps I'm just too paranoid here.
2469 if (i >= n_specials)
2472 back->special(backhandle, specials[i].code);
2477 #define X_POS(l) ((int)(short)LOWORD(l))
2478 #define Y_POS(l) ((int)(short)HIWORD(l))
2480 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2481 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2482 case WM_LBUTTONDOWN:
2483 case WM_MBUTTONDOWN:
2484 case WM_RBUTTONDOWN:
2488 if (message == WM_RBUTTONDOWN &&
2489 ((wParam & MK_CONTROL) ||
2490 (conf_get_int(conf, CONF_mouse_is_xterm) == 2))) {
2493 show_mouseptr(1); /* make sure pointer is visible */
2494 GetCursorPos(&cursorpos);
2495 TrackPopupMenu(popup_menus[CTXMENU].menu,
2496 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2497 cursorpos.x, cursorpos.y,
2505 case WM_LBUTTONDOWN:
2507 wParam |= MK_LBUTTON;
2510 case WM_MBUTTONDOWN:
2511 button = MBT_MIDDLE;
2512 wParam |= MK_MBUTTON;
2515 case WM_RBUTTONDOWN:
2517 wParam |= MK_RBUTTON;
2522 wParam &= ~MK_LBUTTON;
2526 button = MBT_MIDDLE;
2527 wParam &= ~MK_MBUTTON;
2532 wParam &= ~MK_RBUTTON;
2536 button = press = 0; /* shouldn't happen */
2540 * Special case: in full-screen mode, if the left
2541 * button is clicked in the very top left corner of the
2542 * window, we put up the System menu instead of doing
2546 char mouse_on_hotspot = 0;
2555 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2558 mi.cbSize = sizeof(MONITORINFO);
2559 GetMonitorInfo(mon, &mi);
2561 if (mi.rcMonitor.left == pt.x &&
2562 mi.rcMonitor.top == pt.y) {
2563 mouse_on_hotspot = 1;
2568 if (pt.x == 0 && pt.y == 0) {
2569 mouse_on_hotspot = 1;
2572 if (is_full_screen() && press &&
2573 button == MBT_LEFT && mouse_on_hotspot) {
2574 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2575 MAKELPARAM(pt.x, pt.y));
2582 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2583 wParam & MK_SHIFT, wParam & MK_CONTROL,
2587 term_mouse(term, button, translate_button(button), MA_RELEASE,
2588 TO_CHR_X(X_POS(lParam)),
2589 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2590 wParam & MK_CONTROL, is_alt_pressed());
2591 if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)))
2599 * Windows seems to like to occasionally send MOUSEMOVE
2600 * events even if the mouse hasn't moved. Don't unhide
2601 * the mouse pointer in this case.
2603 static WPARAM wp = 0;
2604 static LPARAM lp = 0;
2605 if (wParam != wp || lParam != lp ||
2606 last_mousemove != WM_MOUSEMOVE) {
2608 wp = wParam; lp = lParam;
2609 last_mousemove = WM_MOUSEMOVE;
2613 * Add the mouse position and message time to the random
2616 noise_ultralight(lParam);
2618 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2619 GetCapture() == hwnd) {
2621 if (wParam & MK_LBUTTON)
2623 else if (wParam & MK_MBUTTON)
2627 term_mouse(term, b, translate_button(b), MA_DRAG,
2628 TO_CHR_X(X_POS(lParam)),
2629 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2630 wParam & MK_CONTROL, is_alt_pressed());
2633 case WM_NCMOUSEMOVE:
2635 static WPARAM wp = 0;
2636 static LPARAM lp = 0;
2637 if (wParam != wp || lParam != lp ||
2638 last_mousemove != WM_NCMOUSEMOVE) {
2640 wp = wParam; lp = lParam;
2641 last_mousemove = WM_NCMOUSEMOVE;
2644 noise_ultralight(lParam);
2646 case WM_IGNORE_CLIP:
2647 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2649 case WM_DESTROYCLIPBOARD:
2651 term_deselect(term);
2652 ignore_clip = FALSE;
2659 hdc = BeginPaint(hwnd, &p);
2661 SelectPalette(hdc, pal, TRUE);
2662 RealizePalette(hdc);
2666 * We have to be careful about term_paint(). It will
2667 * set a bunch of character cells to INVALID and then
2668 * call do_paint(), which will redraw those cells and
2669 * _then mark them as done_. This may not be accurate:
2670 * when painting in WM_PAINT context we are restricted
2671 * to the rectangle which has just been exposed - so if
2672 * that only covers _part_ of a character cell and the
2673 * rest of it was already visible, that remainder will
2674 * not be redrawn at all. Accordingly, we must not
2675 * paint any character cell in a WM_PAINT context which
2676 * already has a pending update due to terminal output.
2677 * The simplest solution to this - and many, many
2678 * thanks to Hung-Te Lin for working all this out - is
2679 * not to do any actual painting at _all_ if there's a
2680 * pending terminal update: just mark the relevant
2681 * character cells as INVALID and wait for the
2682 * scheduled full update to sort it out.
2684 * I have a suspicion this isn't the _right_ solution.
2685 * An alternative approach would be to have terminal.c
2686 * separately track what _should_ be on the terminal
2687 * screen and what _is_ on the terminal screen, and
2688 * have two completely different types of redraw (one
2689 * for full updates, which syncs the former with the
2690 * terminal itself, and one for WM_PAINT which syncs
2691 * the latter with the former); yet another possibility
2692 * would be to have the Windows front end do what the
2693 * GTK one already does, and maintain a bitmap of the
2694 * current terminal appearance so that WM_PAINT becomes
2695 * completely trivial. However, this should do for now.
2697 term_paint(term, hdc,
2698 (p.rcPaint.left-offset_width)/font_width,
2699 (p.rcPaint.top-offset_height)/font_height,
2700 (p.rcPaint.right-offset_width-1)/font_width,
2701 (p.rcPaint.bottom-offset_height-1)/font_height,
2702 !term->window_update_pending);
2705 p.rcPaint.left < offset_width ||
2706 p.rcPaint.top < offset_height ||
2707 p.rcPaint.right >= offset_width + font_width*term->cols ||
2708 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2710 HBRUSH fillcolour, oldbrush;
2712 fillcolour = CreateSolidBrush (
2713 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2714 oldbrush = SelectObject(hdc, fillcolour);
2715 edge = CreatePen(PS_SOLID, 0,
2716 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2717 oldpen = SelectObject(hdc, edge);
2720 * Jordan Russell reports that this apparently
2721 * ineffectual IntersectClipRect() call masks a
2722 * Windows NT/2K bug causing strange display
2723 * problems when the PuTTY window is taller than
2724 * the primary monitor. It seems harmless enough...
2726 IntersectClipRect(hdc,
2727 p.rcPaint.left, p.rcPaint.top,
2728 p.rcPaint.right, p.rcPaint.bottom);
2730 ExcludeClipRect(hdc,
2731 offset_width, offset_height,
2732 offset_width+font_width*term->cols,
2733 offset_height+font_height*term->rows);
2735 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2736 p.rcPaint.right, p.rcPaint.bottom);
2738 /* SelectClipRgn(hdc, NULL); */
2740 SelectObject(hdc, oldbrush);
2741 DeleteObject(fillcolour);
2742 SelectObject(hdc, oldpen);
2745 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2746 SelectObject(hdc, GetStockObject(WHITE_PEN));
2754 * To protect against re-entrancy when Windows's recv()
2755 * immediately triggers a new WSAAsyncSelect window
2756 * message, we don't call select_result directly from this
2757 * handler but instead wait until we're back out at the
2758 * top level of the message loop.
2760 struct wm_netevent_params *params =
2761 snew(struct wm_netevent_params);
2762 params->wParam = wParam;
2763 params->lParam = lParam;
2764 queue_toplevel_callback(wm_netevent_callback, params);
2768 term_set_focus(term, TRUE);
2769 CreateCaret(hwnd, caretbm, font_width, font_height);
2771 flash_window(0); /* stop */
2777 term_set_focus(term, FALSE);
2779 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2782 case WM_ENTERSIZEMOVE:
2783 #ifdef RDB_DEBUG_PATCH
2784 debug((27, "WM_ENTERSIZEMOVE"));
2788 need_backend_resize = FALSE;
2790 case WM_EXITSIZEMOVE:
2793 #ifdef RDB_DEBUG_PATCH
2794 debug((27, "WM_EXITSIZEMOVE"));
2796 if (need_backend_resize) {
2797 term_size(term, conf_get_int(conf, CONF_height),
2798 conf_get_int(conf, CONF_width),
2799 conf_get_int(conf, CONF_savelines));
2800 InvalidateRect(hwnd, NULL, TRUE);
2805 * This does two jobs:
2806 * 1) Keep the sizetip uptodate
2807 * 2) Make sure the window size is _stepped_ in units of the font size.
2809 resize_action = conf_get_int(conf, CONF_resize_action);
2810 if (resize_action == RESIZE_TERM ||
2811 (resize_action == RESIZE_EITHER && !is_alt_pressed())) {
2812 int width, height, w, h, ew, eh;
2813 LPRECT r = (LPRECT) lParam;
2815 if (!need_backend_resize && resize_action == RESIZE_EITHER &&
2816 (conf_get_int(conf, CONF_height) != term->rows ||
2817 conf_get_int(conf, CONF_width) != term->cols)) {
2819 * Great! It seems that both the terminal size and the
2820 * font size have been changed and the user is now dragging.
2822 * It will now be difficult to get back to the configured
2825 * This would be easier but it seems to be too confusing.
2827 conf_set_int(conf, CONF_height, term->rows);
2828 conf_set_int(conf, CONF_width, term->cols);
2830 InvalidateRect(hwnd, NULL, TRUE);
2831 need_backend_resize = TRUE;
2834 width = r->right - r->left - extra_width;
2835 height = r->bottom - r->top - extra_height;
2836 w = (width + font_width / 2) / font_width;
2839 h = (height + font_height / 2) / font_height;
2842 UpdateSizeTip(hwnd, w, h);
2843 ew = width - w * font_width;
2844 eh = height - h * font_height;
2846 if (wParam == WMSZ_LEFT ||
2847 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2853 if (wParam == WMSZ_TOP ||
2854 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2864 int width, height, w, h, rv = 0;
2865 int window_border = conf_get_int(conf, CONF_window_border);
2866 int ex_width = extra_width + (window_border - offset_width) * 2;
2867 int ex_height = extra_height + (window_border - offset_height) * 2;
2868 LPRECT r = (LPRECT) lParam;
2870 width = r->right - r->left - ex_width;
2871 height = r->bottom - r->top - ex_height;
2873 w = (width + term->cols/2)/term->cols;
2874 h = (height + term->rows/2)/term->rows;
2875 if ( r->right != r->left + w*term->cols + ex_width)
2878 if (wParam == WMSZ_LEFT ||
2879 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2880 r->left = r->right - w*term->cols - ex_width;
2882 r->right = r->left + w*term->cols + ex_width;
2884 if (r->bottom != r->top + h*term->rows + ex_height)
2887 if (wParam == WMSZ_TOP ||
2888 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2889 r->top = r->bottom - h*term->rows - ex_height;
2891 r->bottom = r->top + h*term->rows + ex_height;
2895 /* break; (never reached) */
2896 case WM_FULLSCR_ON_MAX:
2897 fullscr_on_max = TRUE;
2900 sys_cursor_update();
2903 resize_action = conf_get_int(conf, CONF_resize_action);
2904 #ifdef RDB_DEBUG_PATCH
2905 debug((27, "WM_SIZE %s (%d,%d)",
2906 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2907 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2908 (wParam == SIZE_RESTORED && resizing) ? "to":
2909 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2911 LOWORD(lParam), HIWORD(lParam)));
2913 if (wParam == SIZE_MINIMIZED)
2915 conf_get_int(conf, CONF_win_name_always) ?
2916 window_name : icon_name);
2917 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2918 SetWindowText(hwnd, window_name);
2919 if (wParam == SIZE_RESTORED) {
2920 processed_resize = FALSE;
2921 clear_full_screen();
2922 if (processed_resize) {
2924 * Inhibit normal processing of this WM_SIZE; a
2925 * secondary one was triggered just now by
2926 * clear_full_screen which contained the correct
2932 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2933 fullscr_on_max = FALSE;
2934 processed_resize = FALSE;
2936 if (processed_resize) {
2938 * Inhibit normal processing of this WM_SIZE; a
2939 * secondary one was triggered just now by
2940 * make_full_screen which contained the correct client
2947 processed_resize = TRUE;
2949 if (resize_action == RESIZE_DISABLED) {
2950 /* A resize, well it better be a minimize. */
2954 int width, height, w, h;
2955 int window_border = conf_get_int(conf, CONF_window_border);
2957 width = LOWORD(lParam);
2958 height = HIWORD(lParam);
2960 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2962 prev_rows = term->rows;
2963 prev_cols = term->cols;
2964 if (resize_action == RESIZE_TERM) {
2965 w = width / font_width;
2967 h = height / font_height;
2972 * As below, if we're in the middle of an
2973 * interactive resize we don't call
2974 * back->size. In Windows 7, this case can
2975 * arise in maximisation as well via the Aero
2978 need_backend_resize = TRUE;
2979 conf_set_int(conf, CONF_height, h);
2980 conf_set_int(conf, CONF_width, w);
2982 term_size(term, h, w,
2983 conf_get_int(conf, CONF_savelines));
2987 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2989 if (resize_action == RESIZE_TERM) {
2990 w = (width-window_border*2) / font_width;
2992 h = (height-window_border*2) / font_height;
2994 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
2996 } else if (resize_action != RESIZE_FONT)
3000 } else if (wParam == SIZE_MINIMIZED) {
3002 } else if (resize_action == RESIZE_TERM ||
3003 (resize_action == RESIZE_EITHER &&
3004 !is_alt_pressed())) {
3005 w = (width-window_border*2) / font_width;
3007 h = (height-window_border*2) / font_height;
3012 * Don't call back->size in mid-resize. (To
3013 * prevent massive numbers of resize events
3014 * getting sent down the connection during an NT
3017 need_backend_resize = TRUE;
3018 conf_set_int(conf, CONF_height, h);
3019 conf_set_int(conf, CONF_width, w);
3021 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
3027 sys_cursor_update();
3030 switch (LOWORD(wParam)) {
3032 term_scroll(term, -1, 0);
3035 term_scroll(term, +1, 0);
3038 term_scroll(term, 0, +1);
3041 term_scroll(term, 0, -1);
3044 term_scroll(term, 0, +term->rows / 2);
3047 term_scroll(term, 0, -term->rows / 2);
3049 case SB_THUMBPOSITION:
3052 * Use GetScrollInfo instead of HIWORD(wParam) to get
3053 * 32-bit scroll position.
3058 si.cbSize = sizeof(si);
3059 si.fMask = SIF_TRACKPOS;
3060 if (GetScrollInfo(hwnd, SB_VERT, &si) == 0)
3061 si.nTrackPos = HIWORD(wParam);
3062 term_scroll(term, 1, si.nTrackPos);
3067 case WM_PALETTECHANGED:
3068 if ((HWND) wParam != hwnd && pal != NULL) {
3069 HDC hdc = get_ctx(NULL);
3071 if (RealizePalette(hdc) > 0)
3077 case WM_QUERYNEWPALETTE:
3079 HDC hdc = get_ctx(NULL);
3081 if (RealizePalette(hdc) > 0)
3093 * Add the scan code and keypress timing to the random
3096 noise_ultralight(lParam);
3099 * We don't do TranslateMessage since it disassociates the
3100 * resulting CHAR message from the KEYDOWN that sparked it,
3101 * which we occasionally don't want. Instead, we process
3102 * KEYDOWN, and call the Win32 translator functions so that
3103 * we get the translations under _our_ control.
3106 unsigned char buf[20];
3109 if (wParam == VK_PROCESSKEY || /* IME PROCESS key */
3110 wParam == VK_PACKET) { /* 'this key is a Unicode char' */
3111 if (message == WM_KEYDOWN) {
3114 m.message = WM_KEYDOWN;
3116 m.lParam = lParam & 0xdfff;
3117 TranslateMessage(&m);
3118 } else break; /* pass to Windows for default processing */
3120 len = TranslateKey(message, wParam, lParam, buf);
3122 return DefWindowProcW(hwnd, message, wParam, lParam);
3126 * We need not bother about stdin backlogs
3127 * here, because in GUI PuTTY we can't do
3128 * anything about it anyway; there's no means
3129 * of asking Windows to hold off on KEYDOWN
3130 * messages. We _have_ to buffer everything
3133 term_seen_key_event(term);
3135 ldisc_send(ldisc, buf, len, 1);
3141 case WM_INPUTLANGCHANGE:
3142 /* wParam == Font number */
3143 /* lParam == Locale */
3144 set_input_locale((HKL)lParam);
3145 sys_cursor_update();
3147 case WM_IME_STARTCOMPOSITION:
3149 HIMC hImc = ImmGetContext(hwnd);
3150 ImmSetCompositionFont(hImc, &lfont);
3151 ImmReleaseContext(hwnd, hImc);
3154 case WM_IME_COMPOSITION:
3160 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
3161 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
3163 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
3164 break; /* fall back to DefWindowProc */
3166 hIMC = ImmGetContext(hwnd);
3167 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3171 buff = snewn(n, char);
3172 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
3174 * Jaeyoun Chung reports that Korean character
3175 * input doesn't work correctly if we do a single
3176 * luni_send() covering the whole of buff. So
3177 * instead we luni_send the characters one by one.
3179 term_seen_key_event(term);
3180 /* don't divide SURROGATE PAIR */
3182 for (i = 0; i < n; i += 2) {
3183 WCHAR hs = *(unsigned short *)(buff+i);
3184 if (IS_HIGH_SURROGATE(hs) && i+2 < n) {
3185 WCHAR ls = *(unsigned short *)(buff+i+2);
3186 if (IS_LOW_SURROGATE(ls)) {
3187 luni_send(ldisc, (unsigned short *)(buff+i), 2, 1);
3192 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
3197 ImmReleaseContext(hwnd, hIMC);
3202 if (wParam & 0xFF00) {
3203 unsigned char buf[2];
3206 buf[0] = wParam >> 8;
3207 term_seen_key_event(term);
3209 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
3211 char c = (unsigned char) wParam;
3212 term_seen_key_event(term);
3214 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
3220 * Nevertheless, we are prepared to deal with WM_CHAR
3221 * messages, should they crop up. So if someone wants to
3222 * post the things to us as part of a macro manoeuvre,
3223 * we're ready to cope.
3226 static wchar_t pending_surrogate = 0;
3229 if (IS_HIGH_SURROGATE(c)) {
3230 pending_surrogate = c;
3231 } else if (IS_SURROGATE_PAIR(pending_surrogate, c)) {
3233 pair[0] = pending_surrogate;
3235 term_seen_key_event(term);
3236 luni_send(ldisc, pair, 2, 1);
3237 } else if (!IS_SURROGATE(c)) {
3238 term_seen_key_event(term);
3239 luni_send(ldisc, &c, 1, 1);
3243 case WM_SYSCOLORCHANGE:
3244 if (conf_get_int(conf, CONF_system_colour)) {
3245 /* Refresh palette from system colours. */
3246 /* XXX actually this zaps the entire palette. */
3249 /* Force a repaint of the terminal window. */
3250 term_invalidate(term);
3253 case WM_AGENT_CALLBACK:
3255 struct agent_callback *c = (struct agent_callback *)lParam;
3256 c->callback(c->callback_ctx, c->data, c->len);
3260 case WM_GOT_CLIPDATA:
3261 if (process_clipdata((HGLOBAL)lParam, wParam))
3262 term_do_paste(term);
3265 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
3266 int shift_pressed=0, control_pressed=0;
3268 if (message == WM_MOUSEWHEEL) {
3269 wheel_accumulator += (short)HIWORD(wParam);
3270 shift_pressed=LOWORD(wParam) & MK_SHIFT;
3271 control_pressed=LOWORD(wParam) & MK_CONTROL;
3274 wheel_accumulator += (int)wParam;
3275 if (GetKeyboardState(keys)!=0) {
3276 shift_pressed=keys[VK_SHIFT]&0x80;
3277 control_pressed=keys[VK_CONTROL]&0x80;
3281 /* process events when the threshold is reached */
3282 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
3285 /* reduce amount for next time */
3286 if (wheel_accumulator > 0) {
3288 wheel_accumulator -= WHEEL_DELTA;
3289 } else if (wheel_accumulator < 0) {
3291 wheel_accumulator += WHEEL_DELTA;
3295 if (send_raw_mouse &&
3296 !(conf_get_int(conf, CONF_mouse_override) &&
3298 /* Mouse wheel position is in screen coordinates for
3301 p.x = X_POS(lParam); p.y = Y_POS(lParam);
3302 if (ScreenToClient(hwnd, &p)) {
3303 /* send a mouse-down followed by a mouse up */
3304 term_mouse(term, b, translate_button(b),
3307 TO_CHR_Y(p.y), shift_pressed,
3308 control_pressed, is_alt_pressed());
3309 } /* else: not sure when this can fail */
3311 /* trigger a scroll */
3312 term_scroll(term, 0,
3314 -term->rows / 2 : term->rows / 2);
3322 * Any messages we don't process completely above are passed through to
3323 * DefWindowProc() for default processing.
3325 return DefWindowProcW(hwnd, message, wParam, lParam);
3329 * Move the system caret. (We maintain one, even though it's
3330 * invisible, for the benefit of blind people: apparently some
3331 * helper software tracks the system caret, so we should arrange to
3334 void sys_cursor(void *frontend, int x, int y)
3338 if (!term->has_focus) return;
3341 * Avoid gratuitously re-updating the cursor position and IMM
3342 * window if there's no actual change required.
3344 cx = x * font_width + offset_width;
3345 cy = y * font_height + offset_height;
3346 if (cx == caret_x && cy == caret_y)
3351 sys_cursor_update();
3354 static void sys_cursor_update(void)
3359 if (!term->has_focus) return;
3361 if (caret_x < 0 || caret_y < 0)
3364 SetCaretPos(caret_x, caret_y);
3366 /* IMM calls on Win98 and beyond only */
3367 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3369 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3370 osVersion.dwMinorVersion == 0) return; /* 95 */
3372 /* we should have the IMM functions */
3373 hIMC = ImmGetContext(hwnd);
3374 cf.dwStyle = CFS_POINT;
3375 cf.ptCurrentPos.x = caret_x;
3376 cf.ptCurrentPos.y = caret_y;
3377 ImmSetCompositionWindow(hIMC, &cf);
3379 ImmReleaseContext(hwnd, hIMC);
3383 * Draw a line of text in the window, at given character
3384 * coordinates, in given attributes.
3386 * We are allowed to fiddle with the contents of `text'.
3388 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3389 unsigned long attr, int lattr)
3392 int nfg, nbg, nfont;
3395 int force_manual_underline = 0;
3396 int fnt_width, char_width;
3397 int text_adjust = 0;
3399 int maxlen, remaining, opaque;
3400 int is_cursor = FALSE;
3401 static int *lpDx = NULL;
3402 static int lpDx_len = 0;
3404 int len2; /* for SURROGATE PAIR */
3406 lattr &= LATTR_MODE;
3408 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3410 if (attr & ATTR_WIDE)
3413 /* Only want the left half of double width lines */
3414 if (lattr != LATTR_NORM && x*2 >= term->cols)
3422 if ((attr & TATTR_ACTCURS) && (cursor_type == 0 || term->big_cursor)) {
3423 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3424 /* cursor fg and bg */
3425 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3430 if (vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3431 /* Assume a poorman font is borken in other ways too. */
3441 nfont |= FONT_WIDE + FONT_HIGH;
3444 if (attr & ATTR_NARROW)
3445 nfont |= FONT_NARROW;
3447 #ifdef USES_VTLINE_HACK
3448 /* Special hack for the VT100 linedraw glyphs. */
3449 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3450 switch ((unsigned char) (text[0])) {
3452 text_adjust = -2 * font_height / 5;
3455 text_adjust = -1 * font_height / 5;
3458 text_adjust = font_height / 5;
3461 text_adjust = 2 * font_height / 5;
3464 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3466 text[0] = ucsdata.unitab_xterm['q'];
3467 if (attr & ATTR_UNDER) {
3468 attr &= ~ATTR_UNDER;
3469 force_manual_underline = 1;
3474 /* Anything left as an original character set is unprintable. */
3475 if (DIRECT_CHAR(text[0]) &&
3476 (len < 2 || !IS_SURROGATE_PAIR(text[0], text[1]))) {
3478 for (i = 0; i < len; i++)
3483 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3486 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3487 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3488 if (bold_font_mode == BOLD_FONT && (attr & ATTR_BOLD))
3490 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3491 nfont |= FONT_UNDERLINE;
3492 another_font(nfont);
3493 if (!fonts[nfont]) {
3494 if (nfont & FONT_UNDERLINE)
3495 force_manual_underline = 1;
3496 /* Don't do the same for manual bold, it could be bad news. */
3498 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3500 another_font(nfont);
3502 nfont = FONT_NORMAL;
3503 if (attr & ATTR_REVERSE) {
3508 if (bold_colours && (attr & ATTR_BOLD) && !is_cursor) {
3509 if (nfg < 16) nfg |= 8;
3510 else if (nfg >= 256) nfg |= 1;
3512 if (bold_colours && (attr & ATTR_BLINK)) {
3513 if (nbg < 16) nbg |= 8;
3514 else if (nbg >= 256) nbg |= 1;
3518 SelectObject(hdc, fonts[nfont]);
3519 SetTextColor(hdc, fg);
3520 SetBkColor(hdc, bg);
3521 if (attr & TATTR_COMBINING)
3522 SetBkMode(hdc, TRANSPARENT);
3524 SetBkMode(hdc, OPAQUE);
3527 line_box.right = x + char_width * len;
3528 line_box.bottom = y + font_height;
3529 /* adjust line_box.right for SURROGATE PAIR & VARIATION SELECTOR */
3533 for (i = 0; i < len ; i++) {
3534 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3536 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i], text[i+1])) {
3537 rc_width += char_width;
3539 } else if (IS_LOW_VARSEL(text[i])) {
3542 rc_width += char_width;
3545 line_box.right = line_box.left + rc_width;
3548 /* Only want the left half of double width lines */
3549 if (line_box.right > font_width*term->cols+offset_width)
3550 line_box.right = font_width*term->cols+offset_width;
3552 if (font_varpitch) {
3554 * If we're using a variable-pitch font, we unconditionally
3555 * draw the glyphs one at a time and centre them in their
3556 * character cells (which means in particular that we must
3557 * disable the lpDx mechanism). This gives slightly odd but
3558 * generally reasonable results.
3560 xoffset = char_width / 2;
3561 SetTextAlign(hdc, TA_TOP | TA_CENTER | TA_NOUPDATECP);
3566 * In a fixed-pitch font, we draw the whole string in one go
3567 * in the normal way.
3570 SetTextAlign(hdc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
3575 opaque = TRUE; /* start by erasing the rectangle */
3576 for (remaining = len; remaining > 0;
3577 text += len, remaining -= len, x += char_width * len2) {
3578 len = (maxlen < remaining ? maxlen : remaining);
3579 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3582 if (remaining >= 1 && IS_SURROGATE_PAIR(text[0], text[1]))
3584 if (remaining-len >= 1 && IS_LOW_VARSEL(text[len]))
3586 else if (remaining-len >= 2 &&
3587 IS_HIGH_VARSEL(text[len], text[len+1]))
3591 if (len > lpDx_len) {
3592 lpDx_len = len * 9 / 8 + 16;
3593 lpDx = sresize(lpDx, lpDx_len, int);
3595 if (lpDx_maybe) lpDx_maybe = lpDx;
3600 /* only last char has dx width in SURROGATE PAIR and
3601 * VARIATION sequence */
3602 for (i = 0; i < len; i++) {
3603 lpDx[i] = char_width;
3604 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3605 if (i > 0) lpDx[i-1] = 0;
3608 lpDx[i] = char_width;
3609 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i],text[i+1])) {
3612 lpDx[i] = char_width;
3613 } else if (IS_LOW_VARSEL(text[i])) {
3614 if (i > 0) lpDx[i-1] = 0;
3615 lpDx[i] = char_width;
3620 /* We're using a private area for direct to font. (512 chars.) */
3621 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3622 /* Ho Hum, dbcs fonts are a PITA! */
3623 /* To display on W9x I have to convert to UCS */
3624 static wchar_t *uni_buf = 0;
3625 static int uni_len = 0;
3627 if (len > uni_len) {
3630 uni_buf = snewn(uni_len, wchar_t);
3633 for(nlen = mptr = 0; mptr<len; mptr++) {
3634 uni_buf[nlen] = 0xFFFD;
3635 if (IsDBCSLeadByteEx(ucsdata.font_codepage,
3636 (BYTE) text[mptr])) {
3638 dbcstext[0] = text[mptr] & 0xFF;
3639 dbcstext[1] = text[mptr+1] & 0xFF;
3640 lpDx[nlen] += char_width;
3641 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3642 dbcstext, 2, uni_buf+nlen, 1);
3648 dbcstext[0] = text[mptr] & 0xFF;
3649 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3650 dbcstext, 1, uni_buf+nlen, 1);
3657 ExtTextOutW(hdc, x + xoffset,
3658 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3659 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3660 &line_box, uni_buf, nlen,
3662 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3663 SetBkMode(hdc, TRANSPARENT);
3664 ExtTextOutW(hdc, x + xoffset - 1,
3665 y - font_height * (lattr ==
3666 LATTR_BOT) + text_adjust,
3667 ETO_CLIPPED, &line_box, uni_buf, nlen, lpDx_maybe);
3671 } else if (DIRECT_FONT(text[0])) {
3672 static char *directbuf = NULL;
3673 static int directlen = 0;
3675 if (len > directlen) {
3677 directbuf = sresize(directbuf, directlen, char);
3680 for (i = 0; i < len; i++)
3681 directbuf[i] = text[i] & 0xFF;
3683 ExtTextOut(hdc, x + xoffset,
3684 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3685 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3686 &line_box, directbuf, len, lpDx_maybe);
3687 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3688 SetBkMode(hdc, TRANSPARENT);
3690 /* GRR: This draws the character outside its box and
3691 * can leave 'droppings' even with the clip box! I
3692 * suppose I could loop it one character at a time ...
3695 * Or ... I could do a test print with "W", and use +1
3696 * or -1 for this shift depending on if the leftmost
3697 * column is blank...
3699 ExtTextOut(hdc, x + xoffset - 1,
3700 y - font_height * (lattr ==
3701 LATTR_BOT) + text_adjust,
3702 ETO_CLIPPED, &line_box, directbuf, len, lpDx_maybe);
3705 /* And 'normal' unicode characters */
3706 static WCHAR *wbuf = NULL;
3707 static int wlen = 0;
3713 wbuf = snewn(wlen, WCHAR);
3716 for (i = 0; i < len; i++)
3719 /* print Glyphs as they are, without Windows' Shaping*/
3720 general_textout(hdc, x + xoffset,
3721 y - font_height * (lattr==LATTR_BOT) + text_adjust,
3722 &line_box, wbuf, len, lpDx,
3723 opaque && !(attr & TATTR_COMBINING));
3725 /* And the shadow bold hack. */
3726 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3727 SetBkMode(hdc, TRANSPARENT);
3728 ExtTextOutW(hdc, x + xoffset - 1,
3729 y - font_height * (lattr ==
3730 LATTR_BOT) + text_adjust,
3731 ETO_CLIPPED, &line_box, wbuf, len, lpDx_maybe);
3736 * If we're looping round again, stop erasing the background
3739 SetBkMode(hdc, TRANSPARENT);
3742 if (lattr != LATTR_TOP && (force_manual_underline ||
3743 (und_mode == UND_LINE
3744 && (attr & ATTR_UNDER)))) {
3747 if (lattr == LATTR_BOT)
3748 dec = dec * 2 - font_height;
3750 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3751 MoveToEx(hdc, line_box.left, line_box.top + dec, NULL);
3752 LineTo(hdc, line_box.right, line_box.top + dec);
3753 oldpen = SelectObject(hdc, oldpen);
3754 DeleteObject(oldpen);
3759 * Wrapper that handles combining characters.
3761 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3762 unsigned long attr, int lattr)
3764 if (attr & TATTR_COMBINING) {
3765 unsigned long a = 0;
3767 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3768 if (len >= 2 && IS_SURROGATE_PAIR(text[0], text[1]))
3770 if (len-len0 >= 1 && IS_LOW_VARSEL(text[len0])) {
3771 attr &= ~TATTR_COMBINING;
3772 do_text_internal(ctx, x, y, text, len0+1, attr, lattr);
3775 a = TATTR_COMBINING;
3776 } else if (len-len0 >= 2 && IS_HIGH_VARSEL(text[len0], text[len0+1])) {
3777 attr &= ~TATTR_COMBINING;
3778 do_text_internal(ctx, x, y, text, len0+2, attr, lattr);
3781 a = TATTR_COMBINING;
3783 attr &= ~TATTR_COMBINING;
3787 if (len >= 1 && IS_SURROGATE_PAIR(text[0], text[1])) {
3788 do_text_internal(ctx, x, y, text, 2, attr | a, lattr);
3792 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3796 a = TATTR_COMBINING;
3799 do_text_internal(ctx, x, y, text, len, attr, lattr);
3802 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3803 unsigned long attr, int lattr)
3809 int ctype = cursor_type;
3811 lattr &= LATTR_MODE;
3813 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3814 if (*text != UCSWIDE) {
3815 do_text(ctx, x, y, text, len, attr, lattr);
3819 attr |= TATTR_RIGHTCURS;
3822 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3823 if (attr & ATTR_WIDE)
3830 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3833 pts[0].x = pts[1].x = pts[4].x = x;
3834 pts[2].x = pts[3].x = x + char_width - 1;
3835 pts[0].y = pts[3].y = pts[4].y = y;
3836 pts[1].y = pts[2].y = y + font_height - 1;
3837 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3838 Polyline(hdc, pts, 5);
3839 oldpen = SelectObject(hdc, oldpen);
3840 DeleteObject(oldpen);
3841 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3842 int startx, starty, dx, dy, length, i;
3845 starty = y + descent;
3848 length = char_width;
3851 if (attr & TATTR_RIGHTCURS)
3852 xadjust = char_width - 1;
3853 startx = x + xadjust;
3857 length = font_height;
3859 if (attr & TATTR_ACTCURS) {
3862 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3863 MoveToEx(hdc, startx, starty, NULL);
3864 LineTo(hdc, startx + dx * length, starty + dy * length);
3865 oldpen = SelectObject(hdc, oldpen);
3866 DeleteObject(oldpen);
3868 for (i = 0; i < length; i++) {
3870 SetPixel(hdc, startx, starty, colours[261]);
3879 /* This function gets the actual width of a character in the normal font.
3881 int char_width(Context ctx, int uc) {
3885 /* If the font max is the same as the font ave width then this
3886 * function is a no-op.
3888 if (!font_dualwidth) return 1;
3890 switch (uc & CSET_MASK) {
3892 uc = ucsdata.unitab_line[uc & 0xFF];
3895 uc = ucsdata.unitab_xterm[uc & 0xFF];
3898 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3901 if (DIRECT_FONT(uc)) {
3902 if (ucsdata.dbcs_screenfont) return 1;
3904 /* Speedup, I know of no font where ascii is the wrong width */
3905 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3908 if ( (uc & CSET_MASK) == CSET_ACP ) {
3909 SelectObject(hdc, fonts[FONT_NORMAL]);
3910 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3911 another_font(FONT_OEM);
3912 if (!fonts[FONT_OEM]) return 0;
3914 SelectObject(hdc, fonts[FONT_OEM]);
3918 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3919 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3922 /* Speedup, I know of no font where ascii is the wrong width */
3923 if (uc >= ' ' && uc <= '~') return 1;
3925 SelectObject(hdc, fonts[FONT_NORMAL]);
3926 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3927 /* Okay that one worked */ ;
3928 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3929 /* This should work on 9x too, but it's "less accurate" */ ;
3934 ibuf += font_width / 2 -1;
3940 DECL_WINDOWS_FUNCTION(static, BOOL, FlashWindowEx, (PFLASHWINFO));
3941 DECL_WINDOWS_FUNCTION(static, BOOL, ToUnicodeEx,
3942 (UINT, UINT, const BYTE *, LPWSTR, int, UINT, HKL));
3944 static void init_winfuncs(void)
3946 HMODULE user32_module = load_system32_dll("user32.dll");
3947 GET_WINDOWS_FUNCTION(user32_module, FlashWindowEx);
3948 GET_WINDOWS_FUNCTION(user32_module, ToUnicodeEx);
3952 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3953 * codes. Returns number of bytes used, zero to drop the message,
3954 * -1 to forward the message to Windows, or another negative number
3955 * to indicate a NUL-terminated "special" string.
3957 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3958 unsigned char *output)
3961 int scan, left_alt = 0, key_down, shift_state;
3963 unsigned char *p = output;
3964 static int alt_sum = 0;
3965 int funky_type = conf_get_int(conf, CONF_funky_type);
3966 int no_applic_k = conf_get_int(conf, CONF_no_applic_k);
3967 int ctrlaltkeys = conf_get_int(conf, CONF_ctrlaltkeys);
3968 int nethack_keypad = conf_get_int(conf, CONF_nethack_keypad);
3970 HKL kbd_layout = GetKeyboardLayout(0);
3972 static wchar_t keys_unicode[3];
3973 static int compose_char = 0;
3974 static WPARAM compose_keycode = 0;
3976 r = GetKeyboardState(keystate);
3978 memset(keystate, 0, sizeof(keystate));
3981 #define SHOW_TOASCII_RESULT
3982 { /* Tell us all about key events */
3983 static BYTE oldstate[256];
3984 static int first = 1;
3988 memcpy(oldstate, keystate, sizeof(oldstate));
3991 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3993 } else if ((HIWORD(lParam) & KF_UP)
3994 && scan == (HIWORD(lParam) & 0xFF)) {
3998 if (wParam >= VK_F1 && wParam <= VK_F20)
3999 debug(("K_F%d", wParam + 1 - VK_F1));
4012 debug(("VK_%02x", wParam));
4014 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
4016 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
4018 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
4019 if (ch >= ' ' && ch <= '~')
4020 debug((", '%c'", ch));
4022 debug((", $%02x", ch));
4024 if (keys_unicode[0])
4025 debug((", KB0=%04x", keys_unicode[0]));
4026 if (keys_unicode[1])
4027 debug((", KB1=%04x", keys_unicode[1]));
4028 if (keys_unicode[2])
4029 debug((", KB2=%04x", keys_unicode[2]));
4031 if ((keystate[VK_SHIFT] & 0x80) != 0)
4033 if ((keystate[VK_CONTROL] & 0x80) != 0)
4035 if ((HIWORD(lParam) & KF_EXTENDED))
4037 if ((HIWORD(lParam) & KF_UP))
4041 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
4042 else if ((HIWORD(lParam) & KF_UP))
4043 oldstate[wParam & 0xFF] ^= 0x80;
4045 oldstate[wParam & 0xFF] ^= 0x81;
4047 for (ch = 0; ch < 256; ch++)
4048 if (oldstate[ch] != keystate[ch])
4049 debug((", M%02x=%02x", ch, keystate[ch]));
4051 memcpy(oldstate, keystate, sizeof(oldstate));
4055 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
4056 keystate[VK_RMENU] = keystate[VK_MENU];
4060 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
4061 if ((funky_type == FUNKY_VT400 ||
4062 (funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
4064 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
4066 wParam = VK_EXECUTE;
4068 /* UnToggle NUMLock */
4069 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
4070 keystate[VK_NUMLOCK] ^= 1;
4073 /* And write back the 'adjusted' state */
4074 SetKeyboardState(keystate);
4077 /* Disable Auto repeat if required */
4078 if (term->repeat_off &&
4079 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
4082 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
4085 key_down = ((HIWORD(lParam) & KF_UP) == 0);
4087 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
4088 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
4090 keystate[VK_MENU] = 0;
4092 keystate[VK_RMENU] = 0x80;
4097 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
4098 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
4099 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
4101 /* Note if AltGr was pressed and if it was used as a compose key */
4102 if (!compose_state) {
4103 compose_keycode = 0x100;
4104 if (conf_get_int(conf, CONF_compose_key)) {
4105 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
4106 compose_keycode = wParam;
4108 if (wParam == VK_APPS)
4109 compose_keycode = wParam;
4112 if (wParam == compose_keycode) {
4113 if (compose_state == 0
4114 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
4116 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
4120 } else if (compose_state == 1 && wParam != VK_CONTROL)
4123 if (compose_state > 1 && left_alt)
4126 /* Sanitize the number pad if not using a PC NumPad */
4127 if (left_alt || (term->app_keypad_keys && !no_applic_k
4128 && funky_type != FUNKY_XTERM)
4129 || funky_type == FUNKY_VT400 || nethack_keypad || compose_state) {
4130 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
4134 nParam = VK_NUMPAD0;
4137 nParam = VK_NUMPAD1;
4140 nParam = VK_NUMPAD2;
4143 nParam = VK_NUMPAD3;
4146 nParam = VK_NUMPAD4;
4149 nParam = VK_NUMPAD5;
4152 nParam = VK_NUMPAD6;
4155 nParam = VK_NUMPAD7;
4158 nParam = VK_NUMPAD8;
4161 nParam = VK_NUMPAD9;
4164 nParam = VK_DECIMAL;
4168 if (keystate[VK_NUMLOCK] & 1)
4175 /* If a key is pressed and AltGr is not active */
4176 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
4177 /* Okay, prepare for most alts then ... */
4181 /* Lets see if it's a pattern we know all about ... */
4182 if (wParam == VK_PRIOR && shift_state == 1) {
4183 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
4186 if (wParam == VK_PRIOR && shift_state == 2) {
4187 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
4190 if (wParam == VK_NEXT && shift_state == 1) {
4191 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
4194 if (wParam == VK_NEXT && shift_state == 2) {
4195 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
4198 if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) {
4199 term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1));
4202 if (wParam == VK_INSERT && shift_state == 1) {
4203 request_paste(NULL);
4206 if (left_alt && wParam == VK_F4 && conf_get_int(conf, CONF_alt_f4)) {
4209 if (left_alt && wParam == VK_SPACE && conf_get_int(conf,
4211 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
4214 if (left_alt && wParam == VK_RETURN &&
4215 conf_get_int(conf, CONF_fullscreenonaltenter) &&
4216 (conf_get_int(conf, CONF_resize_action) != RESIZE_DISABLED)) {
4217 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
4221 /* Control-Numlock for app-keypad mode switch */
4222 if (wParam == VK_PAUSE && shift_state == 2) {
4223 term->app_keypad_keys ^= 1;
4227 /* Nethack keypad */
4228 if (nethack_keypad && !left_alt) {
4231 *p++ = "bB\002\002"[shift_state & 3];
4234 *p++ = "jJ\012\012"[shift_state & 3];
4237 *p++ = "nN\016\016"[shift_state & 3];
4240 *p++ = "hH\010\010"[shift_state & 3];
4243 *p++ = shift_state ? '.' : '.';
4246 *p++ = "lL\014\014"[shift_state & 3];
4249 *p++ = "yY\031\031"[shift_state & 3];
4252 *p++ = "kK\013\013"[shift_state & 3];
4255 *p++ = "uU\025\025"[shift_state & 3];
4260 /* Application Keypad */
4264 if (funky_type == FUNKY_VT400 ||
4265 (funky_type <= FUNKY_LINUX &&
4266 term->app_keypad_keys && !no_applic_k)) switch (wParam) {
4280 if (term->app_keypad_keys && !no_applic_k)
4317 if (funky_type == FUNKY_XTERM) {
4322 } else if (shift_state)
4329 if (funky_type == FUNKY_XTERM)
4333 if (funky_type == FUNKY_XTERM)
4337 if (funky_type == FUNKY_XTERM)
4342 if (HIWORD(lParam) & KF_EXTENDED)
4347 if (term->vt52_mode) {
4348 if (xkey >= 'P' && xkey <= 'S')
4349 p += sprintf((char *) p, "\x1B%c", xkey);
4351 p += sprintf((char *) p, "\x1B?%c", xkey);
4353 p += sprintf((char *) p, "\x1BO%c", xkey);
4358 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
4359 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x7F : 0x08);
4363 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
4364 /* We do the opposite of what is configured */
4365 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x08 : 0x7F);
4369 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
4375 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
4379 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
4383 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
4385 back->special(backhandle, TS_BRK);
4388 if (wParam == VK_PAUSE) { /* Break/Pause */
4393 /* Control-2 to Control-8 are special */
4394 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
4395 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
4398 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
4402 if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) {
4406 if (shift_state == 3 && wParam == 0xDE) {
4407 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
4410 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
4417 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
4418 * for integer decimal nn.)
4420 * We also deal with the weird ones here. Linux VCs replace F1
4421 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
4422 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
4428 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
4431 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
4434 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
4437 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
4440 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
4443 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
4446 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
4449 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
4452 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
4455 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
4488 if ((shift_state&2) == 0) switch (wParam) {
4508 /* Reorder edit keys to physical order */
4509 if (funky_type == FUNKY_VT400 && code <= 6)
4510 code = "\0\2\1\4\5\3\6"[code];
4512 if (term->vt52_mode && code > 0 && code <= 6) {
4513 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4517 if (funky_type == FUNKY_SCO && code >= 11 && code <= 34) {
4518 /* SCO function keys */
4519 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4522 case VK_F1: index = 0; break;
4523 case VK_F2: index = 1; break;
4524 case VK_F3: index = 2; break;
4525 case VK_F4: index = 3; break;
4526 case VK_F5: index = 4; break;
4527 case VK_F6: index = 5; break;
4528 case VK_F7: index = 6; break;
4529 case VK_F8: index = 7; break;
4530 case VK_F9: index = 8; break;
4531 case VK_F10: index = 9; break;
4532 case VK_F11: index = 10; break;
4533 case VK_F12: index = 11; break;
4535 if (keystate[VK_SHIFT] & 0x80) index += 12;
4536 if (keystate[VK_CONTROL] & 0x80) index += 24;
4537 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4540 if (funky_type == FUNKY_SCO && /* SCO small keypad */
4541 code >= 1 && code <= 6) {
4542 char codes[] = "HL.FIG";
4546 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4550 if ((term->vt52_mode || funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4556 if (term->vt52_mode)
4557 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4560 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4563 if (funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4564 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4567 if (funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4568 if (term->vt52_mode)
4569 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4571 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4574 if ((code == 1 || code == 4) &&
4575 conf_get_int(conf, CONF_rxvt_homeend)) {
4576 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4580 p += sprintf((char *) p, "\x1B[%d~", code);
4585 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4586 * some reason seems to send VK_CLEAR to Windows...).
4608 p += format_arrow_key(p, term, xkey, shift_state);
4614 * Finally, deal with Return ourselves. (Win95 seems to
4615 * foul it up when Alt is pressed, for some reason.)
4617 if (wParam == VK_RETURN) { /* Return */
4623 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4624 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4629 /* Okay we've done everything interesting; let windows deal with
4630 * the boring stuff */
4634 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4635 if(keystate[VK_CAPITAL] != 0 &&
4636 conf_get_int(conf, CONF_xlat_capslockcyr)) {
4638 keystate[VK_CAPITAL] = 0;
4641 /* XXX how do we know what the max size of the keys array should
4642 * be is? There's indication on MS' website of an Inquire/InquireEx
4643 * functioning returning a KBINFO structure which tells us. */
4644 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT && p_ToUnicodeEx) {
4645 r = p_ToUnicodeEx(wParam, scan, keystate, keys_unicode,
4646 lenof(keys_unicode), 0, kbd_layout);
4648 /* XXX 'keys' parameter is declared in MSDN documentation as
4650 * The experience of a French user indicates that on
4651 * Win98, WORD[] should be passed in, but on Win2K, it should
4652 * be BYTE[]. German WinXP and my Win2K with "US International"
4653 * driver corroborate this.
4654 * Experimentally I've conditionalised the behaviour on the
4655 * Win9x/NT split, but I suspect it's worse than that.
4656 * See wishlist item `win-dead-keys' for more horrible detail
4657 * and speculations. */
4659 static WORD keys[3];
4660 static BYTE keysb[3];
4661 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4663 for (i = 0; i < r; i++) {
4664 keysb[i] = (BYTE)keys[i];
4666 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)keysb, r,
4667 keys_unicode, lenof(keys_unicode));
4670 #ifdef SHOW_TOASCII_RESULT
4671 if (r == 1 && !key_down) {
4673 if (in_utf(term) || ucsdata.dbcs_screenfont)
4674 debug((", (U+%04x)", alt_sum));
4676 debug((", LCH(%d)", alt_sum));
4678 debug((", ACH(%d)", keys_unicode[0]));
4683 for (r1 = 0; r1 < r; r1++) {
4684 debug(("%s%d", r1 ? "," : "", keys_unicode[r1]));
4693 for (i = 0; i < r; i++) {
4694 wchar_t wch = keys_unicode[i];
4696 if (compose_state == 2 && wch >= ' ' && wch < 0x80) {
4701 if (compose_state == 3 && wch >= ' ' && wch < 0x80) {
4705 if ((nc = check_compose(compose_char, wch)) == -1) {
4706 MessageBeep(MB_ICONHAND);
4710 term_seen_key_event(term);
4712 luni_send(ldisc, &keybuf, 1, 1);
4720 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4722 term_seen_key_event(term);
4724 luni_send(ldisc, &keybuf, 1, 1);
4726 char ch = (char) alt_sum;
4728 * We need not bother about stdin
4729 * backlogs here, because in GUI PuTTY
4730 * we can't do anything about it
4731 * anyway; there's no means of asking
4732 * Windows to hold off on KEYDOWN
4733 * messages. We _have_ to buffer
4734 * everything we're sent.
4736 term_seen_key_event(term);
4738 ldisc_send(ldisc, &ch, 1, 1);
4742 term_seen_key_event(term);
4744 luni_send(ldisc, &wch, 1, 1);
4747 if(capsOn && wch < 0x80) {
4750 cbuf[1] = xlat_uskbd2cyrllic(wch);
4751 term_seen_key_event(term);
4753 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4758 term_seen_key_event(term);
4760 luni_send(ldisc, cbuf +!left_alt, 1+!!left_alt, 1);
4766 /* This is so the ALT-Numpad and dead keys work correctly. */
4767 keys_unicode[0] = 0;
4771 /* If we're definitly not building up an ALT-54321 then clear it */
4773 keys_unicode[0] = 0;
4774 /* If we will be using alt_sum fix the 256s */
4775 else if (keys_unicode[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4776 keys_unicode[0] = 10;
4780 * ALT alone may or may not want to bring up the System menu.
4781 * If it's not meant to, we return 0 on presses or releases of
4782 * ALT, to show that we've swallowed the keystroke. Otherwise
4783 * we return -1, which means Windows will give the keystroke
4784 * its default handling (i.e. bring up the System menu).
4786 if (wParam == VK_MENU && !conf_get_int(conf, CONF_alt_only))
4792 void set_title(void *frontend, char *title)
4795 window_name = snewn(1 + strlen(title), char);
4796 strcpy(window_name, title);
4797 if (conf_get_int(conf, CONF_win_name_always) || !IsIconic(hwnd))
4798 SetWindowText(hwnd, title);
4801 void set_icon(void *frontend, char *title)
4804 icon_name = snewn(1 + strlen(title), char);
4805 strcpy(icon_name, title);
4806 if (!conf_get_int(conf, CONF_win_name_always) && IsIconic(hwnd))
4807 SetWindowText(hwnd, title);
4810 void set_sbar(void *frontend, int total, int start, int page)
4814 if (!conf_get_int(conf, is_full_screen() ?
4815 CONF_scrollbar_in_fullscreen : CONF_scrollbar))
4818 si.cbSize = sizeof(si);
4819 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4821 si.nMax = total - 1;
4825 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4828 Context get_ctx(void *frontend)
4834 SelectPalette(hdc, pal, FALSE);
4840 void free_ctx(Context ctx)
4842 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4843 ReleaseDC(hwnd, ctx);
4846 static void real_palette_set(int n, int r, int g, int b)
4849 logpal->palPalEntry[n].peRed = r;
4850 logpal->palPalEntry[n].peGreen = g;
4851 logpal->palPalEntry[n].peBlue = b;
4852 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4853 colours[n] = PALETTERGB(r, g, b);
4854 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4856 colours[n] = RGB(r, g, b);
4859 void palette_set(void *frontend, int n, int r, int g, int b)
4863 if (n >= NALLCOLOURS)
4865 real_palette_set(n, r, g, b);
4867 HDC hdc = get_ctx(frontend);
4868 UnrealizeObject(pal);
4869 RealizePalette(hdc);
4872 if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))
4873 /* If Default Background changes, we need to ensure any
4874 * space between the text area and the window border is
4876 InvalidateRect(hwnd, NULL, TRUE);
4880 void palette_reset(void *frontend)
4885 for (i = 0; i < NALLCOLOURS; i++) {
4887 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4888 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4889 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4890 logpal->palPalEntry[i].peFlags = 0;
4891 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4892 defpal[i].rgbtGreen,
4893 defpal[i].rgbtBlue);
4895 colours[i] = RGB(defpal[i].rgbtRed,
4896 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4901 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4902 hdc = get_ctx(frontend);
4903 RealizePalette(hdc);
4906 /* Default Background may have changed. Ensure any space between
4907 * text area and window border is redrawn. */
4908 InvalidateRect(hwnd, NULL, TRUE);
4912 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4917 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4920 lock = GlobalLock(clipdata);
4923 memcpy(lock, data, len);
4924 ((unsigned char *) lock)[len] = 0;
4925 GlobalUnlock(clipdata);
4928 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4930 if (OpenClipboard(hwnd)) {
4932 SetClipboardData(CF_TEXT, clipdata);
4935 GlobalFree(clipdata);
4938 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4942 * Note: unlike write_aclip() this will not append a nul.
4944 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
4946 HGLOBAL clipdata, clipdata2, clipdata3;
4948 void *lock, *lock2, *lock3;
4950 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4952 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4953 len * sizeof(wchar_t));
4954 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4956 if (!clipdata || !clipdata2) {
4958 GlobalFree(clipdata);
4960 GlobalFree(clipdata2);
4963 if (!(lock = GlobalLock(clipdata))) {
4964 GlobalFree(clipdata);
4965 GlobalFree(clipdata2);
4968 if (!(lock2 = GlobalLock(clipdata2))) {
4969 GlobalUnlock(clipdata);
4970 GlobalFree(clipdata);
4971 GlobalFree(clipdata2);
4975 memcpy(lock, data, len * sizeof(wchar_t));
4976 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4978 if (conf_get_int(conf, CONF_rtf_paste)) {
4979 wchar_t unitab[256];
4981 unsigned char *tdata = (unsigned char *)lock2;
4982 wchar_t *udata = (wchar_t *)lock;
4983 int rtflen = 0, uindex = 0, tindex = 0;
4985 int multilen, blen, alen, totallen, i;
4986 char before[16], after[4];
4987 int fgcolour, lastfgcolour = 0;
4988 int bgcolour, lastbgcolour = 0;
4989 int attrBold, lastAttrBold = 0;
4990 int attrUnder, lastAttrUnder = 0;
4991 int palette[NALLCOLOURS];
4993 FontSpec *font = conf_get_fontspec(conf, CONF_font);
4995 get_unitab(CP_ACP, unitab, 0);
4997 rtfsize = 100 + strlen(font->name);
4998 rtf = snewn(rtfsize, char);
4999 rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
5000 font->name, font->height*2);
5003 * Add colour palette
5004 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
5008 * First - Determine all colours in use
5009 * o Foregound and background colours share the same palette
5012 memset(palette, 0, sizeof(palette));
5013 for (i = 0; i < (len-1); i++) {
5014 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5015 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5017 if (attr[i] & ATTR_REVERSE) {
5018 int tmpcolour = fgcolour; /* Swap foreground and background */
5019 fgcolour = bgcolour;
5020 bgcolour = tmpcolour;
5023 if (bold_colours && (attr[i] & ATTR_BOLD)) {
5024 if (fgcolour < 8) /* ANSI colours */
5026 else if (fgcolour >= 256) /* Default colours */
5030 if (attr[i] & ATTR_BLINK) {
5031 if (bgcolour < 8) /* ANSI colours */
5033 else if (bgcolour >= 256) /* Default colours */
5037 palette[fgcolour]++;
5038 palette[bgcolour]++;
5042 * Next - Create a reduced palette
5045 for (i = 0; i < NALLCOLOURS; i++) {
5046 if (palette[i] != 0)
5047 palette[i] = ++numcolours;
5051 * Finally - Write the colour table
5053 rtf = sresize(rtf, rtfsize + (numcolours * 25), char);
5054 strcat(rtf, "{\\colortbl ;");
5055 rtflen = strlen(rtf);
5057 for (i = 0; i < NALLCOLOURS; i++) {
5058 if (palette[i] != 0) {
5059 rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);
5062 strcpy(&rtf[rtflen], "}");
5067 * We want to construct a piece of RTF that specifies the
5068 * same Unicode text. To do this we will read back in
5069 * parallel from the Unicode data in `udata' and the
5070 * non-Unicode data in `tdata'. For each character in
5071 * `tdata' which becomes the right thing in `udata' when
5072 * looked up in `unitab', we just copy straight over from
5073 * tdata. For each one that doesn't, we must WCToMB it
5074 * individually and produce a \u escape sequence.
5076 * It would probably be more robust to just bite the bullet
5077 * and WCToMB each individual Unicode character one by one,
5078 * then MBToWC each one back to see if it was an accurate
5079 * translation; but that strikes me as a horrifying number
5080 * of Windows API calls so I want to see if this faster way
5081 * will work. If it screws up badly we can always revert to
5082 * the simple and slow way.
5084 while (tindex < len2 && uindex < len &&
5085 tdata[tindex] && udata[uindex]) {
5086 if (tindex + 1 < len2 &&
5087 tdata[tindex] == '\r' &&
5088 tdata[tindex+1] == '\n') {
5094 * Set text attributes
5097 if (rtfsize < rtflen + 64) {
5098 rtfsize = rtflen + 512;
5099 rtf = sresize(rtf, rtfsize, char);
5103 * Determine foreground and background colours
5105 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5106 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5108 if (attr[tindex] & ATTR_REVERSE) {
5109 int tmpcolour = fgcolour; /* Swap foreground and background */
5110 fgcolour = bgcolour;
5111 bgcolour = tmpcolour;
5114 if (bold_colours && (attr[tindex] & ATTR_BOLD)) {
5115 if (fgcolour < 8) /* ANSI colours */
5117 else if (fgcolour >= 256) /* Default colours */
5121 if (attr[tindex] & ATTR_BLINK) {
5122 if (bgcolour < 8) /* ANSI colours */
5124 else if (bgcolour >= 256) /* Default colours */
5129 * Collect other attributes
5131 if (bold_font_mode != BOLD_NONE)
5132 attrBold = attr[tindex] & ATTR_BOLD;
5136 attrUnder = attr[tindex] & ATTR_UNDER;
5140 * o If video isn't reversed, ignore colour attributes for default foregound
5142 * o Special case where bolded text is displayed using the default foregound
5143 * and background colours - force to bolded RTF.
5145 if (!(attr[tindex] & ATTR_REVERSE)) {
5146 if (bgcolour >= 256) /* Default color */
5147 bgcolour = -1; /* No coloring */
5149 if (fgcolour >= 256) { /* Default colour */
5150 if (bold_colours && (fgcolour & 1) && bgcolour == -1)
5151 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
5153 fgcolour = -1; /* No coloring */
5158 * Write RTF text attributes
5160 if (lastfgcolour != fgcolour) {
5161 lastfgcolour = fgcolour;
5162 rtflen += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
5165 if (lastbgcolour != bgcolour) {
5166 lastbgcolour = bgcolour;
5167 rtflen += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
5170 if (lastAttrBold != attrBold) {
5171 lastAttrBold = attrBold;
5172 rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
5175 if (lastAttrUnder != attrUnder) {
5176 lastAttrUnder = attrUnder;
5177 rtflen += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
5181 if (unitab[tdata[tindex]] == udata[uindex]) {
5187 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
5188 NULL, 0, NULL, NULL);
5189 if (multilen != 1) {
5190 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
5192 alen = 1; strcpy(after, "}");
5194 blen = sprintf(before, "\\u%d", udata[uindex]);
5195 alen = 0; after[0] = '\0';
5198 assert(tindex + multilen <= len2);
5199 totallen = blen + alen;
5200 for (i = 0; i < multilen; i++) {
5201 if (tdata[tindex+i] == '\\' ||
5202 tdata[tindex+i] == '{' ||
5203 tdata[tindex+i] == '}')
5205 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
5206 totallen += 6; /* \par\r\n */
5207 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
5213 if (rtfsize < rtflen + totallen + 3) {
5214 rtfsize = rtflen + totallen + 512;
5215 rtf = sresize(rtf, rtfsize, char);
5218 strcpy(rtf + rtflen, before); rtflen += blen;
5219 for (i = 0; i < multilen; i++) {
5220 if (tdata[tindex+i] == '\\' ||
5221 tdata[tindex+i] == '{' ||
5222 tdata[tindex+i] == '}') {
5223 rtf[rtflen++] = '\\';
5224 rtf[rtflen++] = tdata[tindex+i];
5225 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
5226 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
5227 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
5228 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
5230 rtf[rtflen++] = tdata[tindex+i];
5233 strcpy(rtf + rtflen, after); rtflen += alen;
5239 rtf[rtflen++] = '}'; /* Terminate RTF stream */
5240 rtf[rtflen++] = '\0';
5241 rtf[rtflen++] = '\0';
5243 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
5244 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
5245 memcpy(lock3, rtf, rtflen);
5246 GlobalUnlock(clipdata3);
5252 GlobalUnlock(clipdata);
5253 GlobalUnlock(clipdata2);
5256 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
5258 if (OpenClipboard(hwnd)) {
5260 SetClipboardData(CF_UNICODETEXT, clipdata);
5261 SetClipboardData(CF_TEXT, clipdata2);
5263 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
5266 GlobalFree(clipdata);
5267 GlobalFree(clipdata2);
5271 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
5274 static DWORD WINAPI clipboard_read_threadfunc(void *param)
5276 HWND hwnd = (HWND)param;
5279 if (OpenClipboard(NULL)) {
5280 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
5281 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)1, (LPARAM)clipdata);
5282 } else if ((clipdata = GetClipboardData(CF_TEXT))) {
5283 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)0, (LPARAM)clipdata);
5291 static int process_clipdata(HGLOBAL clipdata, int unicode)
5293 sfree(clipboard_contents);
5294 clipboard_contents = NULL;
5295 clipboard_length = 0;
5298 wchar_t *p = GlobalLock(clipdata);
5302 /* Unwilling to rely on Windows having wcslen() */
5303 for (p2 = p; *p2; p2++);
5304 clipboard_length = p2 - p;
5305 clipboard_contents = snewn(clipboard_length + 1, wchar_t);
5306 memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t));
5307 clipboard_contents[clipboard_length] = L'\0';
5311 char *s = GlobalLock(clipdata);
5315 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
5316 clipboard_contents = snewn(i, wchar_t);
5317 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1,
5318 clipboard_contents, i);
5319 clipboard_length = i - 1;
5320 clipboard_contents[clipboard_length] = L'\0';
5328 void request_paste(void *frontend)
5331 * I always thought pasting was synchronous in Windows; the
5332 * clipboard access functions certainly _look_ synchronous,
5333 * unlike the X ones. But in fact it seems that in some
5334 * situations the contents of the clipboard might not be
5335 * immediately available, and the clipboard-reading functions
5336 * may block. This leads to trouble if the application
5337 * delivering the clipboard data has to get hold of it by -
5338 * for example - talking over a network connection which is
5339 * forwarded through this very PuTTY.
5341 * Hence, we spawn a subthread to read the clipboard, and do
5342 * our paste when it's finished. The thread will send a
5343 * message back to our main window when it terminates, and
5344 * that tells us it's OK to paste.
5346 DWORD in_threadid; /* required for Win9x */
5347 CreateThread(NULL, 0, clipboard_read_threadfunc,
5348 hwnd, 0, &in_threadid);
5351 void get_clip(void *frontend, wchar_t **p, int *len)
5354 *p = clipboard_contents;
5355 *len = clipboard_length;
5361 * Move `lines' lines from position `from' to position `to' in the
5364 void optimised_move(void *frontend, int to, int from, int lines)
5369 min = (to < from ? to : from);
5370 max = to + from - min;
5372 r.left = offset_width;
5373 r.right = offset_width + term->cols * font_width;
5374 r.top = offset_height + min * font_height;
5375 r.bottom = offset_height + (max + lines) * font_height;
5376 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
5381 * Print a message box and perform a fatal exit.
5383 void fatalbox(const char *fmt, ...)
5386 char *stuff, morestuff[100];
5389 stuff = dupvprintf(fmt, ap);
5391 sprintf(morestuff, "%.70s Fatal Error", appname);
5392 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5398 * Print a modal (Really Bad) message box and perform a fatal exit.
5400 void modalfatalbox(const char *fmt, ...)
5403 char *stuff, morestuff[100];
5406 stuff = dupvprintf(fmt, ap);
5408 sprintf(morestuff, "%.70s Fatal Error", appname);
5409 MessageBox(hwnd, stuff, morestuff,
5410 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
5416 * Print a message box and don't close the connection.
5418 void nonfatal(const char *fmt, ...)
5421 char *stuff, morestuff[100];
5424 stuff = dupvprintf(fmt, ap);
5426 sprintf(morestuff, "%.70s Error", appname);
5427 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5431 static BOOL flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout)
5433 if (p_FlashWindowEx) {
5435 fi.cbSize = sizeof(fi);
5437 fi.dwFlags = dwFlags;
5439 fi.dwTimeout = dwTimeout;
5440 return (*p_FlashWindowEx)(&fi);
5443 return FALSE; /* shrug */
5446 static void flash_window(int mode);
5447 static long next_flash;
5448 static int flashing = 0;
5451 * Timer for platforms where we must maintain window flashing manually
5454 static void flash_window_timer(void *ctx, unsigned long now)
5456 if (flashing && now == next_flash) {
5462 * Manage window caption / taskbar flashing, if enabled.
5463 * 0 = stop, 1 = maintain, 2 = start
5465 static void flash_window(int mode)
5467 int beep_ind = conf_get_int(conf, CONF_beep_ind);
5468 if ((mode == 0) || (beep_ind == B_IND_DISABLED)) {
5472 if (p_FlashWindowEx)
5473 flash_window_ex(FLASHW_STOP, 0, 0);
5475 FlashWindow(hwnd, FALSE);
5478 } else if (mode == 2) {
5482 if (p_FlashWindowEx) {
5483 /* For so-called "steady" mode, we use uCount=2, which
5484 * seems to be the traditional number of flashes used
5485 * by user notifications (e.g., by Explorer).
5486 * uCount=0 appears to enable continuous flashing, per
5487 * "flashing" mode, although I haven't seen this
5489 flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
5490 (beep_ind == B_IND_FLASH ? 0 : 2),
5491 0 /* system cursor blink rate */);
5492 /* No need to schedule timer */
5494 FlashWindow(hwnd, TRUE);
5495 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5499 } else if ((mode == 1) && (beep_ind == B_IND_FLASH)) {
5501 if (flashing && !p_FlashWindowEx) {
5502 FlashWindow(hwnd, TRUE); /* toggle */
5503 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5511 void do_beep(void *frontend, int mode)
5513 if (mode == BELL_DEFAULT) {
5515 * For MessageBeep style bells, we want to be careful of
5516 * timing, because they don't have the nice property of
5517 * PlaySound bells that each one cancels the previous
5518 * active one. So we limit the rate to one per 50ms or so.
5520 static long lastbeep = 0;
5523 beepdiff = GetTickCount() - lastbeep;
5524 if (beepdiff >= 0 && beepdiff < 50)
5528 * The above MessageBeep call takes time, so we record the
5529 * time _after_ it finishes rather than before it starts.
5531 lastbeep = GetTickCount();
5532 } else if (mode == BELL_WAVEFILE) {
5533 Filename *bell_wavefile = conf_get_filename(conf, CONF_bell_wavefile);
5534 if (!PlaySound(bell_wavefile->path, NULL,
5535 SND_ASYNC | SND_FILENAME)) {
5536 char buf[sizeof(bell_wavefile->path) + 80];
5538 sprintf(buf, "Unable to play sound file\n%s\n"
5539 "Using default sound instead", bell_wavefile->path);
5540 sprintf(otherbuf, "%.70s Sound Error", appname);
5541 MessageBox(hwnd, buf, otherbuf,
5542 MB_OK | MB_ICONEXCLAMATION);
5543 conf_set_int(conf, CONF_beep, BELL_DEFAULT);
5545 } else if (mode == BELL_PCSPEAKER) {
5546 static long lastbeep = 0;
5549 beepdiff = GetTickCount() - lastbeep;
5550 if (beepdiff >= 0 && beepdiff < 50)
5554 * We must beep in different ways depending on whether this
5555 * is a 95-series or NT-series OS.
5557 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
5561 lastbeep = GetTickCount();
5563 /* Otherwise, either visual bell or disabled; do nothing here */
5564 if (!term->has_focus) {
5565 flash_window(2); /* start */
5570 * Minimise or restore the window in response to a server-side
5573 void set_iconic(void *frontend, int iconic)
5575 if (IsIconic(hwnd)) {
5577 ShowWindow(hwnd, SW_RESTORE);
5580 ShowWindow(hwnd, SW_MINIMIZE);
5585 * Move the window in response to a server-side request.
5587 void move_window(void *frontend, int x, int y)
5589 int resize_action = conf_get_int(conf, CONF_resize_action);
5590 if (resize_action == RESIZE_DISABLED ||
5591 resize_action == RESIZE_FONT ||
5595 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5599 * Move the window to the top or bottom of the z-order in response
5600 * to a server-side request.
5602 void set_zorder(void *frontend, int top)
5604 if (conf_get_int(conf, CONF_alwaysontop))
5605 return; /* ignore */
5606 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5607 SWP_NOMOVE | SWP_NOSIZE);
5611 * Refresh the window in response to a server-side request.
5613 void refresh_window(void *frontend)
5615 InvalidateRect(hwnd, NULL, TRUE);
5619 * Maximise or restore the window in response to a server-side
5622 void set_zoomed(void *frontend, int zoomed)
5624 if (IsZoomed(hwnd)) {
5626 ShowWindow(hwnd, SW_RESTORE);
5629 ShowWindow(hwnd, SW_MAXIMIZE);
5634 * Report whether the window is iconic, for terminal reports.
5636 int is_iconic(void *frontend)
5638 return IsIconic(hwnd);
5642 * Report the window's position, for terminal reports.
5644 void get_window_pos(void *frontend, int *x, int *y)
5647 GetWindowRect(hwnd, &r);
5653 * Report the window's pixel size, for terminal reports.
5655 void get_window_pixels(void *frontend, int *x, int *y)
5658 GetWindowRect(hwnd, &r);
5659 *x = r.right - r.left;
5660 *y = r.bottom - r.top;
5664 * Return the window or icon title.
5666 char *get_window_title(void *frontend, int icon)
5668 return icon ? icon_name : window_name;
5672 * See if we're in full-screen mode.
5674 static int is_full_screen()
5676 if (!IsZoomed(hwnd))
5678 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
5683 /* Get the rect/size of a full screen window using the nearest available
5684 * monitor in multimon systems; default to something sensible if only
5685 * one monitor is present. */
5686 static int get_fullscreen_rect(RECT * ss)
5688 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
5691 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
5692 mi.cbSize = sizeof(mi);
5693 GetMonitorInfo(mon, &mi);
5695 /* structure copy */
5699 /* could also use code like this:
5700 ss->left = ss->top = 0;
5701 ss->right = GetSystemMetrics(SM_CXSCREEN);
5702 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5704 return GetClientRect(GetDesktopWindow(), ss);
5710 * Go full-screen. This should only be called when we are already
5713 static void make_full_screen()
5718 assert(IsZoomed(hwnd));
5720 if (is_full_screen())
5723 /* Remove the window furniture. */
5724 style = GetWindowLongPtr(hwnd, GWL_STYLE);
5725 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5726 if (conf_get_int(conf, CONF_scrollbar_in_fullscreen))
5727 style |= WS_VSCROLL;
5729 style &= ~WS_VSCROLL;
5730 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5732 /* Resize ourselves to exactly cover the nearest monitor. */
5733 get_fullscreen_rect(&ss);
5734 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5739 /* We may have changed size as a result */
5743 /* Tick the menu item in the System and context menus. */
5746 for (i = 0; i < lenof(popup_menus); i++)
5747 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED);
5752 * Clear the full-screen attributes.
5754 static void clear_full_screen()
5756 DWORD oldstyle, style;
5758 /* Reinstate the window furniture. */
5759 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
5760 style |= WS_CAPTION | WS_BORDER;
5761 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
5762 style &= ~WS_THICKFRAME;
5764 style |= WS_THICKFRAME;
5765 if (conf_get_int(conf, CONF_scrollbar))
5766 style |= WS_VSCROLL;
5768 style &= ~WS_VSCROLL;
5769 if (style != oldstyle) {
5770 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5771 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5772 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5776 /* Untick the menu item in the System and context menus. */
5779 for (i = 0; i < lenof(popup_menus); i++)
5780 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED);
5785 * Toggle full-screen mode.
5787 static void flip_full_screen()
5789 if (is_full_screen()) {
5790 ShowWindow(hwnd, SW_RESTORE);
5791 } else if (IsZoomed(hwnd)) {
5794 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5795 ShowWindow(hwnd, SW_MAXIMIZE);
5799 void frontend_keypress(void *handle)
5802 * Keypress termination in non-Close-On-Exit mode is not
5803 * currently supported in PuTTY proper, because the window
5804 * always has a perfectly good Close button anyway. So we do
5810 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5812 return term_data(term, is_stderr, data, len);
5815 int from_backend_untrusted(void *frontend, const char *data, int len)
5817 return term_data_untrusted(term, data, len);
5820 int from_backend_eof(void *frontend)
5822 return TRUE; /* do respond to incoming EOF with outgoing */
5825 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
5828 ret = cmdline_get_passwd_input(p, in, inlen);
5830 ret = term_get_userpass_input(term, p, in, inlen);
5834 void agent_schedule_callback(void (*callback)(void *, void *, int),
5835 void *callback_ctx, void *data, int len)
5837 struct agent_callback *c = snew(struct agent_callback);
5838 c->callback = callback;
5839 c->callback_ctx = callback_ctx;
5842 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);