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 char *message = dupprintf("Could not restrict process ACL: %s",
403 logevent(NULL, message);
410 * Process the command line.
415 /* By default, we bring up the config dialog, rather than launching
416 * a session. This gets set to TRUE if something happens to change
417 * that (e.g., a hostname is specified on the command-line). */
418 int allow_launch = FALSE;
420 default_protocol = be_default_protocol;
421 /* Find the appropriate default port. */
423 Backend *b = backend_from_proto(default_protocol);
424 default_port = 0; /* illegal */
426 default_port = b->default_port;
428 conf_set_int(conf, CONF_logtype, LGTYP_NONE);
430 do_defaults(NULL, conf);
435 * Process a couple of command-line options which are more
436 * easily dealt with before the line is broken up into words.
437 * These are the old-fashioned but convenient @sessionname and
438 * the internal-use-only &sharedmemoryhandle, neither of which
439 * are combined with anything else.
441 while (*p && isspace(*p))
445 * An initial @ means that the whole of the rest of the
446 * command line should be treated as the name of a saved
447 * session, with _no quoting or escaping_. This makes it a
448 * very convenient means of automated saved-session
449 * launching, via IDM_SAVEDSESS or Windows 7 jump lists.
452 while (i > 1 && isspace(p[i - 1]))
455 do_defaults(p + 1, conf);
456 if (!conf_launchable(conf) && !do_config()) {
459 allow_launch = TRUE; /* allow it to be launched directly */
460 } else if (*p == '&') {
462 * An initial & means we've been given a command line
463 * containing the hex value of a HANDLE for a file
464 * mapping object, which we must then interpret as a
470 if (sscanf(p + 1, "%p:%u", &filemap, &cpsize) == 2 &&
471 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
472 0, 0, cpsize)) != NULL) {
473 conf_deserialise(conf, cp, cpsize);
475 CloseHandle(filemap);
476 } else if (!do_config()) {
482 * Otherwise, break up the command line and deal with
488 split_into_argv(cmdline, &argc, &argv, NULL);
490 for (i = 0; i < argc; i++) {
494 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
497 cmdline_error("option \"%s\" requires an argument", p);
498 } else if (ret == 2) {
499 i++; /* skip next argument */
500 } else if (ret == 1) {
501 continue; /* nothing further needs doing */
502 } else if (!strcmp(p, "-cleanup") ||
503 !strcmp(p, "-cleanup-during-uninstall")) {
505 * `putty -cleanup'. Remove all registry
506 * entries associated with PuTTY, and also find
507 * and delete the random seed file.
510 /* Are we being invoked from an uninstaller? */
511 if (!strcmp(p, "-cleanup-during-uninstall")) {
512 s1 = dupprintf("Remove saved sessions and random seed file?\n"
514 "If you hit Yes, ALL Registry entries associated\n"
515 "with %s will be removed, as well as the\n"
516 "random seed file. THIS PROCESS WILL\n"
517 "DESTROY YOUR SAVED SESSIONS.\n"
518 "(This only affects the currently logged-in user.)\n"
520 "If you hit No, uninstallation will proceed, but\n"
521 "saved sessions etc will be left on the machine.",
523 s2 = dupprintf("%s Uninstallation", appname);
525 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
526 "associated with %s, and will also remove\n"
527 "the random seed file. (This only affects the\n"
528 "currently logged-in user.)\n"
530 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
531 "Are you really sure you want to continue?",
533 s2 = dupprintf("%s Warning", appname);
535 if (message_box(s1, s2,
536 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
537 HELPCTXID(option_cleanup)) == IDYES) {
543 } else if (!strcmp(p, "-pgpfp")) {
546 } else if (*p != '-') {
550 * If we already have a host name, treat
551 * this argument as a port number. NB we
552 * have to treat this as a saved -P
553 * argument, so that it will be deferred
554 * until it's a good moment to run it.
556 int ret = cmdline_process_param("-P", p, 1, conf);
558 } else if (!strncmp(q, "telnet:", 7)) {
560 * If the hostname starts with "telnet:",
561 * set the protocol to Telnet and process
562 * the string as a Telnet URL.
567 if (q[0] == '/' && q[1] == '/')
569 conf_set_int(conf, CONF_protocol, PROT_TELNET);
571 p += host_strcspn(p, ":/");
576 conf_set_int(conf, CONF_port, atoi(p));
578 conf_set_int(conf, CONF_port, -1);
579 conf_set_str(conf, CONF_host, q);
583 * Otherwise, treat this argument as a host
586 while (*p && !isspace(*p))
590 conf_set_str(conf, CONF_host, q);
594 cmdline_error("unknown option \"%s\"", p);
599 cmdline_run_saved(conf);
601 if (loaded_session || got_host)
604 if ((!allow_launch || !conf_launchable(conf)) && !do_config()) {
609 * Muck about with the hostname in various ways.
612 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
613 char *host = hostbuf;
617 * Trim leading whitespace.
619 host += strspn(host, " \t");
622 * See if host is of the form user@host, and separate
623 * out the username if so.
625 if (host[0] != '\0') {
626 char *atsign = strrchr(host, '@');
629 conf_set_str(conf, CONF_username, host);
635 * Trim a colon suffix off the hostname if it's there. In
636 * order to protect unbracketed IPv6 address literals
637 * against this treatment, we do not do this if there's
638 * _more_ than one colon.
641 char *c = host_strchr(host, ':');
644 char *d = host_strchr(c+1, ':');
651 * Remove any remaining whitespace.
656 if (*q != ' ' && *q != '\t')
662 conf_set_str(conf, CONF_host, hostbuf);
671 wndclass.lpfnWndProc = WndProc;
672 wndclass.cbClsExtra = 0;
673 wndclass.cbWndExtra = 0;
674 wndclass.hInstance = inst;
675 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
676 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
677 wndclass.hbrBackground = NULL;
678 wndclass.lpszMenuName = NULL;
679 wndclass.lpszClassName = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
681 RegisterClassW(&wndclass);
684 memset(&ucsdata, 0, sizeof(ucsdata));
691 * Guess some defaults for the window size. This all gets
692 * updated later, so we don't really care too much. However, we
693 * do want the font width/height guesses to correspond to a
694 * large font rather than a small one...
701 guess_width = extra_width + font_width * conf_get_int(conf, CONF_width);
702 guess_height = extra_height + font_height*conf_get_int(conf, CONF_height);
705 get_fullscreen_rect(&r);
706 if (guess_width > r.right - r.left)
707 guess_width = r.right - r.left;
708 if (guess_height > r.bottom - r.top)
709 guess_height = r.bottom - r.top;
713 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
715 wchar_t *uappname = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
716 if (!conf_get_int(conf, CONF_scrollbar))
717 winmode &= ~(WS_VSCROLL);
718 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
719 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
720 if (conf_get_int(conf, CONF_alwaysontop))
721 exwinmode |= WS_EX_TOPMOST;
722 if (conf_get_int(conf, CONF_sunken_edge))
723 exwinmode |= WS_EX_CLIENTEDGE;
724 hwnd = CreateWindowExW(exwinmode, uappname, uappname,
725 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
726 guess_width, guess_height,
727 NULL, NULL, inst, NULL);
732 * Initialise the fonts, simultaneously correcting the guesses
733 * for font_{width,height}.
738 * Initialise the terminal. (We have to do this _after_
739 * creating the window, since the terminal is the first thing
740 * which will call schedule_timer(), which will in turn call
741 * timer_change_notify() which will expect hwnd to exist.)
743 term = term_init(conf, &ucsdata, NULL);
744 logctx = log_init(NULL, conf);
745 term_provide_logctx(term, logctx);
746 term_size(term, conf_get_int(conf, CONF_height),
747 conf_get_int(conf, CONF_width),
748 conf_get_int(conf, CONF_savelines));
751 * Correct the guesses for extra_{width,height}.
755 GetWindowRect(hwnd, &wr);
756 GetClientRect(hwnd, &cr);
757 offset_width = offset_height = conf_get_int(conf, CONF_window_border);
758 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
759 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
763 * Resize the window, now we know what size we _really_ want it
766 guess_width = extra_width + font_width * term->cols;
767 guess_height = extra_height + font_height * term->rows;
768 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
769 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
772 * Set up a caret bitmap, with no content.
776 int size = (font_width + 15) / 16 * 2 * font_height;
777 bits = snewn(size, char);
778 memset(bits, 0, size);
779 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
782 CreateCaret(hwnd, caretbm, font_width, font_height);
785 * Initialise the scroll bar.
790 si.cbSize = sizeof(si);
791 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
793 si.nMax = term->rows - 1;
794 si.nPage = term->rows;
796 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
800 * Prepare the mouse handler.
802 lastact = MA_NOTHING;
803 lastbtn = MBT_NOTHING;
804 dbltime = GetDoubleClickTime();
807 * Set up the session-control options on the system menu.
814 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
815 popup_menus[CTXMENU].menu = CreatePopupMenu();
816 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
818 savedsess_menu = CreateMenu();
819 get_sesslist(&sesslist, TRUE);
820 update_savedsess_menu();
822 for (j = 0; j < lenof(popup_menus); j++) {
823 m = popup_menus[j].menu;
825 AppendMenu(m, MF_SEPARATOR, 0, 0);
826 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
827 AppendMenu(m, MF_SEPARATOR, 0, 0);
828 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
829 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
830 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) savedsess_menu,
832 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
833 AppendMenu(m, MF_SEPARATOR, 0, 0);
834 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
835 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
836 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
837 AppendMenu(m, MF_SEPARATOR, 0, 0);
838 AppendMenu(m, (conf_get_int(conf, CONF_resize_action)
839 == RESIZE_DISABLED) ? MF_GRAYED : MF_ENABLED,
840 IDM_FULLSCREEN, "&Full Screen");
841 AppendMenu(m, MF_SEPARATOR, 0, 0);
843 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
844 str = dupprintf("&About %s", appname);
845 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
853 * Set up the initial input locale.
855 set_input_locale(GetKeyboardLayout(0));
858 * Finally show the window!
860 ShowWindow(hwnd, show);
861 SetForegroundWindow(hwnd);
864 * Set the palette up.
870 term_set_focus(term, GetForegroundWindow() == hwnd);
878 if (toplevel_callback_pending() ||
879 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
881 * If we have anything we'd like to do immediately, set
882 * the timeout for MsgWaitForMultipleObjects to zero so
883 * that we'll only do a quick check of our handles and
884 * then get on with whatever that was.
886 * One such option is a pending toplevel callback. The
887 * other is a non-empty Windows message queue, which you'd
888 * think we could leave to MsgWaitForMultipleObjects to
889 * check for us along with all the handles, but in fact we
890 * can't because once PeekMessage in one iteration of this
891 * loop has removed a message from the queue, the whole
892 * queue is considered uninteresting by the next
893 * invocation of MWFMO. So we check ourselves whether the
894 * message queue is non-empty, and if so, set this timeout
895 * to zero to ensure MWFMO doesn't block.
900 /* The messages seem unreliable; especially if we're being tricky */
901 term_set_focus(term, GetForegroundWindow() == hwnd);
904 handles = handle_get_events(&nhandles);
906 n = MsgWaitForMultipleObjects(nhandles, handles, FALSE,
907 timeout, QS_ALLINPUT);
909 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
910 handle_got_event(handles[n - WAIT_OBJECT_0]);
915 while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
916 if (msg.message == WM_QUIT)
917 goto finished; /* two-level break */
919 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
920 DispatchMessageW(&msg);
923 * WM_NETEVENT messages seem to jump ahead of others in
924 * the message queue. I'm not sure why; the docs for
925 * PeekMessage mention that messages are prioritised in
926 * some way, but I'm unclear on which priorities go where.
928 * Anyway, in practice I observe that WM_NETEVENT seems to
929 * jump to the head of the queue, which means that if we
930 * were to only process one message every time round this
931 * loop, we'd get nothing but NETEVENTs if the server
932 * flooded us with data, and stop responding to any other
933 * kind of window message. So instead, we keep on round
934 * this loop until we've consumed at least one message
935 * that _isn't_ a NETEVENT, or run out of messages
936 * completely (whichever comes first). And we don't go to
937 * run_toplevel_callbacks (which is where the netevents
938 * are actually processed, causing fresh NETEVENT messages
939 * to appear) until we've done this.
941 if (msg.message != WM_NETEVENT)
945 run_toplevel_callbacks();
949 cleanup_exit(msg.wParam); /* this doesn't return... */
950 return msg.wParam; /* ... but optimiser doesn't know */
956 void cleanup_exit(int code)
967 if (conf_get_int(conf, CONF_protocol) == PROT_SSH) {
982 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
984 char *do_select(SOCKET skt, int startup)
989 events = (FD_CONNECT | FD_READ | FD_WRITE |
990 FD_OOB | FD_CLOSE | FD_ACCEPT);
995 return "do_select(): internal error (hwnd==NULL)";
996 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
997 switch (p_WSAGetLastError()) {
999 return "Network is down";
1001 return "WSAAsyncSelect(): unknown error";
1008 * Refresh the saved-session submenu from `sesslist'.
1010 static void update_savedsess_menu(void)
1013 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
1014 /* skip sesslist.sessions[0] == Default Settings */
1016 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
1017 : MENU_SAVED_MAX+1);
1019 AppendMenu(savedsess_menu, MF_ENABLED,
1020 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
1021 sesslist.sessions[i]);
1022 if (sesslist.nsessions <= 1)
1023 AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)");
1027 * Update the Special Commands submenu.
1029 void update_specials_menu(void *frontend)
1035 specials = back->get_specials(backhandle);
1040 /* We can't use Windows to provide a stack for submenus, so
1041 * here's a lame "stack" that will do for now. */
1042 HMENU saved_menu = NULL;
1044 new_menu = CreatePopupMenu();
1045 for (i = 0; nesting > 0; i++) {
1046 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
1047 switch (specials[i].code) {
1049 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
1052 assert(nesting < 2);
1054 saved_menu = new_menu; /* XXX lame stacking */
1055 new_menu = CreatePopupMenu();
1056 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
1057 (UINT) new_menu, specials[i].name);
1062 new_menu = saved_menu; /* XXX lame stacking */
1067 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
1072 /* Squirrel the highest special. */
1079 for (j = 0; j < lenof(popup_menus); j++) {
1080 if (specials_menu) {
1081 /* XXX does this free up all submenus? */
1082 DeleteMenu(popup_menus[j].menu, (UINT)specials_menu, MF_BYCOMMAND);
1083 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
1086 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1087 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
1088 (UINT) new_menu, "S&pecial Command");
1089 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1090 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
1093 specials_menu = new_menu;
1096 static void update_mouse_pointer(void)
1099 int force_visible = FALSE;
1100 static int forced_visible = FALSE;
1101 switch (busy_status) {
1104 curstype = IDC_ARROW;
1106 curstype = IDC_IBEAM;
1109 curstype = IDC_APPSTARTING; /* this may be an abuse */
1110 force_visible = TRUE;
1113 curstype = IDC_WAIT;
1114 force_visible = TRUE;
1120 HCURSOR cursor = LoadCursor(NULL, curstype);
1121 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1122 SetCursor(cursor); /* force redraw of cursor at current posn */
1124 if (force_visible != forced_visible) {
1125 /* We want some cursor shapes to be visible always.
1126 * Along with show_mouseptr(), this manages the ShowCursor()
1127 * counter such that if we switch back to a non-force_visible
1128 * cursor, the previous visibility state is restored. */
1129 ShowCursor(force_visible);
1130 forced_visible = force_visible;
1134 void set_busy_status(void *frontend, int status)
1136 busy_status = status;
1137 update_mouse_pointer();
1141 * set or clear the "raw mouse message" mode
1143 void set_raw_mouse_mode(void *frontend, int activate)
1145 activate = activate && !conf_get_int(conf, CONF_no_mouse_rep);
1146 send_raw_mouse = activate;
1147 update_mouse_pointer();
1151 * Print a message box and close the connection.
1153 void connection_fatal(void *frontend, const char *fmt, ...)
1156 char *stuff, morestuff[100];
1159 stuff = dupvprintf(fmt, ap);
1161 sprintf(morestuff, "%.70s Fatal Error", appname);
1162 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1165 if (conf_get_int(conf, CONF_close_on_exit) == FORCE_ON)
1168 queue_toplevel_callback(close_session, NULL);
1173 * Report an error at the command-line parsing stage.
1175 void cmdline_error(const char *fmt, ...)
1178 char *stuff, morestuff[100];
1181 stuff = dupvprintf(fmt, ap);
1183 sprintf(morestuff, "%.70s Command Line Error", appname);
1184 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1190 * Actually do the job requested by a WM_NETEVENT
1192 static void wm_netevent_callback(void *vctx)
1194 struct wm_netevent_params *params = (struct wm_netevent_params *)vctx;
1195 select_result(params->wParam, params->lParam);
1200 * Copy the colour palette from the configuration data into defpal.
1201 * This is non-trivial because the colour indices are different.
1203 static void conftopalette(void)
1206 static const int ww[] = {
1207 256, 257, 258, 259, 260, 261,
1208 0, 8, 1, 9, 2, 10, 3, 11,
1209 4, 12, 5, 13, 6, 14, 7, 15
1212 for (i = 0; i < 22; i++) {
1214 defpal[w].rgbtRed = conf_get_int_int(conf, CONF_colours, i*3+0);
1215 defpal[w].rgbtGreen = conf_get_int_int(conf, CONF_colours, i*3+1);
1216 defpal[w].rgbtBlue = conf_get_int_int(conf, CONF_colours, i*3+2);
1218 for (i = 0; i < NEXTCOLOURS; i++) {
1220 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1221 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1222 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1223 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
1225 int shade = i - 216;
1226 shade = shade * 10 + 8;
1227 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1228 defpal[i+16].rgbtBlue = shade;
1232 /* Override with system colours if appropriate */
1233 if (conf_get_int(conf, CONF_system_colour))
1238 * Override bit of defpal with colours from the system.
1239 * (NB that this takes a copy the system colours at the time this is called,
1240 * so subsequent colour scheme changes don't take effect. To fix that we'd
1241 * probably want to be using GetSysColorBrush() and the like.)
1243 static void systopalette(void)
1246 static const struct { int nIndex; int norm; int bold; } or[] =
1248 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1249 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1250 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1251 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1254 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1255 COLORREF colour = GetSysColor(or[i].nIndex);
1256 defpal[or[i].norm].rgbtRed =
1257 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1258 defpal[or[i].norm].rgbtGreen =
1259 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1260 defpal[or[i].norm].rgbtBlue =
1261 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1266 * Set up the colour palette.
1268 static void init_palette(void)
1271 HDC hdc = GetDC(hwnd);
1273 if (conf_get_int(conf, CONF_try_palette) &&
1274 GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1276 * This is a genuine case where we must use smalloc
1277 * because the snew macros can't cope.
1279 logpal = smalloc(sizeof(*logpal)
1280 - sizeof(logpal->palPalEntry)
1281 + NALLCOLOURS * sizeof(PALETTEENTRY));
1282 logpal->palVersion = 0x300;
1283 logpal->palNumEntries = NALLCOLOURS;
1284 for (i = 0; i < NALLCOLOURS; i++) {
1285 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1286 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1287 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1288 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1290 pal = CreatePalette(logpal);
1292 SelectPalette(hdc, pal, FALSE);
1293 RealizePalette(hdc);
1294 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1297 ReleaseDC(hwnd, hdc);
1300 for (i = 0; i < NALLCOLOURS; i++)
1301 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1302 defpal[i].rgbtGreen,
1303 defpal[i].rgbtBlue);
1305 for (i = 0; i < NALLCOLOURS; i++)
1306 colours[i] = RGB(defpal[i].rgbtRed,
1307 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1311 * This is a wrapper to ExtTextOut() to force Windows to display
1312 * the precise glyphs we give it. Otherwise it would do its own
1313 * bidi and Arabic shaping, and we would end up uncertain which
1314 * characters it had put where.
1316 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1317 unsigned short *lpString, UINT cbCount,
1318 CONST INT *lpDx, int opaque)
1322 * The LCC include files apparently don't supply the
1323 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1324 * proper: the differences aren't important to us (the only
1325 * variable-width string parameter is one we don't use anyway).
1331 char *buffer = snewn(cbCount*2+2, char);
1332 char *classbuffer = snewn(cbCount, char);
1333 memset(&gcpr, 0, sizeof(gcpr));
1334 memset(buffer, 0, cbCount*2+2);
1335 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1337 gcpr.lStructSize = sizeof(gcpr);
1338 gcpr.lpGlyphs = (void *)buffer;
1339 gcpr.lpClass = (void *)classbuffer;
1340 gcpr.nGlyphs = cbCount;
1341 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1342 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1344 ExtTextOut(hdc, x, y,
1345 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1346 lprc, buffer, cbCount, lpDx);
1350 * The exact_textout() wrapper, unfortunately, destroys the useful
1351 * Windows `font linking' behaviour: automatic handling of Unicode
1352 * code points not supported in this font by falling back to a font
1353 * which does contain them. Therefore, we adopt a multi-layered
1354 * approach: for any potentially-bidi text, we use exact_textout(),
1355 * and for everything else we use a simple ExtTextOut as we did
1356 * before exact_textout() was introduced.
1358 static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1359 unsigned short *lpString, UINT cbCount,
1360 CONST INT *lpDx, int opaque)
1363 int bkmode = 0, got_bkmode = FALSE;
1367 for (i = 0; i < (int)cbCount ;) {
1368 int rtl = is_rtl(lpString[i]);
1372 for (j = i+1; j < (int)cbCount; j++) {
1373 if (rtl != is_rtl(lpString[j]))
1379 * Now [i,j) indicates a maximal substring of lpString
1380 * which should be displayed using the same textout
1384 exact_textout(hdc, xp, y, lprc, lpString+i, j-i,
1385 font_varpitch ? NULL : lpDx+i, opaque);
1387 ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1388 lprc, lpString+i, j-i,
1389 font_varpitch ? NULL : lpDx+i);
1395 bkmode = GetBkMode(hdc);
1397 SetBkMode(hdc, TRANSPARENT);
1402 SetBkMode(hdc, bkmode);
1405 static int get_font_width(HDC hdc, const TEXTMETRIC *tm)
1408 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1409 if (!(tm->tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1410 ret = tm->tmAveCharWidth;
1414 ABCFLOAT widths[LAST-FIRST + 1];
1417 font_varpitch = TRUE;
1418 font_dualwidth = TRUE;
1419 if (GetCharABCWidthsFloat(hdc, FIRST, LAST, widths)) {
1421 for (j = 0; j < lenof(widths); j++) {
1422 int width = (int)(0.5 + widths[j].abcfA +
1423 widths[j].abcfB + widths[j].abcfC);
1428 ret = tm->tmMaxCharWidth;
1437 * Initialise all the fonts we will need initially. There may be as many as
1438 * three or as few as one. The other (potentially) twenty-one fonts are done
1439 * if/when they are needed.
1443 * - check the font width and height, correcting our guesses if
1446 * - verify that the bold font is the same width as the ordinary
1447 * one, and engage shadow bolding if not.
1449 * - verify that the underlined font is the same width as the
1450 * ordinary one (manual underlining by means of line drawing can
1451 * be done in a pinch).
1453 static void init_fonts(int pick_width, int pick_height)
1462 int fw_dontcare, fw_bold;
1464 for (i = 0; i < FONT_MAXNO; i++)
1467 bold_font_mode = conf_get_int(conf, CONF_bold_style) & 1 ?
1468 BOLD_FONT : BOLD_NONE;
1469 bold_colours = conf_get_int(conf, CONF_bold_style) & 2 ? TRUE : FALSE;
1470 und_mode = UND_FONT;
1472 font = conf_get_fontspec(conf, CONF_font);
1474 fw_dontcare = FW_BOLD;
1477 fw_dontcare = FW_DONTCARE;
1484 font_height = pick_height;
1486 font_height = font->height;
1487 if (font_height > 0) {
1489 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1492 font_width = pick_width;
1494 quality = conf_get_int(conf, CONF_font_quality);
1495 #define f(i,c,w,u) \
1496 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1497 c, OUT_DEFAULT_PRECIS, \
1498 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), \
1499 FIXED_PITCH | FF_DONTCARE, font->name)
1501 f(FONT_NORMAL, font->charset, fw_dontcare, FALSE);
1503 SelectObject(hdc, fonts[FONT_NORMAL]);
1504 GetTextMetrics(hdc, &tm);
1506 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1508 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1509 if (!(tm.tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1510 font_varpitch = FALSE;
1511 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1513 font_varpitch = TRUE;
1514 font_dualwidth = TRUE;
1516 if (pick_width == 0 || pick_height == 0) {
1517 font_height = tm.tmHeight;
1518 font_width = get_font_width(hdc, &tm);
1521 #ifdef RDB_DEBUG_PATCH
1522 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1523 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1528 DWORD cset = tm.tmCharSet;
1529 memset(&info, 0xFF, sizeof(info));
1531 /* !!! Yes the next line is right */
1532 if (cset == OEM_CHARSET)
1533 ucsdata.font_codepage = GetOEMCP();
1535 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1536 ucsdata.font_codepage = info.ciACP;
1538 ucsdata.font_codepage = -1;
1540 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1541 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1544 f(FONT_UNDERLINE, font->charset, fw_dontcare, TRUE);
1547 * Some fonts, e.g. 9-pt Courier, draw their underlines
1548 * outside their character cell. We successfully prevent
1549 * screen corruption by clipping the text output, but then
1550 * we lose the underline completely. Here we try to work
1551 * out whether this is such a font, and if it is, we set a
1552 * flag that causes underlines to be drawn by hand.
1554 * Having tried other more sophisticated approaches (such
1555 * as examining the TEXTMETRIC structure or requesting the
1556 * height of a string), I think we'll do this the brute
1557 * force way: we create a small bitmap, draw an underlined
1558 * space on it, and test to see whether any pixels are
1559 * foreground-coloured. (Since we expect the underline to
1560 * go all the way across the character cell, we only search
1561 * down a single column of the bitmap, half way across.)
1565 HBITMAP und_bm, und_oldbm;
1569 und_dc = CreateCompatibleDC(hdc);
1570 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1571 und_oldbm = SelectObject(und_dc, und_bm);
1572 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1573 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1574 SetTextColor(und_dc, RGB(255, 255, 255));
1575 SetBkColor(und_dc, RGB(0, 0, 0));
1576 SetBkMode(und_dc, OPAQUE);
1577 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1579 for (i = 0; i < font_height; i++) {
1580 c = GetPixel(und_dc, font_width / 2, i);
1581 if (c != RGB(0, 0, 0))
1584 SelectObject(und_dc, und_oldbm);
1585 DeleteObject(und_bm);
1588 und_mode = UND_LINE;
1589 DeleteObject(fonts[FONT_UNDERLINE]);
1590 fonts[FONT_UNDERLINE] = 0;
1594 if (bold_font_mode == BOLD_FONT) {
1595 f(FONT_BOLD, font->charset, fw_bold, FALSE);
1599 descent = tm.tmAscent + 1;
1600 if (descent >= font_height)
1601 descent = font_height - 1;
1603 for (i = 0; i < 3; i++) {
1605 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1606 fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight;
1613 ReleaseDC(hwnd, hdc);
1615 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1616 und_mode = UND_LINE;
1617 DeleteObject(fonts[FONT_UNDERLINE]);
1618 fonts[FONT_UNDERLINE] = 0;
1621 if (bold_font_mode == BOLD_FONT &&
1622 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1623 bold_font_mode = BOLD_SHADOW;
1624 DeleteObject(fonts[FONT_BOLD]);
1625 fonts[FONT_BOLD] = 0;
1627 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1629 init_ucs(conf, &ucsdata);
1632 static void another_font(int fontno)
1635 int fw_dontcare, fw_bold, quality;
1640 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1643 basefont = (fontno & ~(FONT_BOLDUND));
1644 if (basefont != fontno && !fontflag[basefont])
1645 another_font(basefont);
1647 font = conf_get_fontspec(conf, CONF_font);
1650 fw_dontcare = FW_BOLD;
1653 fw_dontcare = FW_DONTCARE;
1663 if (fontno & FONT_WIDE)
1665 if (fontno & FONT_NARROW)
1667 if (fontno & FONT_OEM)
1669 if (fontno & FONT_BOLD)
1671 if (fontno & FONT_UNDERLINE)
1674 quality = conf_get_int(conf, CONF_font_quality);
1677 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1678 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1679 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality),
1680 DEFAULT_PITCH | FF_DONTCARE, s);
1682 fontflag[fontno] = 1;
1685 static void deinit_fonts(void)
1688 for (i = 0; i < FONT_MAXNO; i++) {
1690 DeleteObject(fonts[i]);
1696 void request_resize(void *frontend, int w, int h)
1700 /* If the window is maximized supress resizing attempts */
1701 if (IsZoomed(hwnd)) {
1702 if (conf_get_int(conf, CONF_resize_action) == RESIZE_TERM)
1706 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) return;
1707 if (h == term->rows && w == term->cols) return;
1709 /* Sanity checks ... */
1711 static int first_time = 1;
1714 switch (first_time) {
1716 /* Get the size of the screen */
1717 if (get_fullscreen_rect(&ss))
1718 /* first_time = 0 */ ;
1724 /* Make sure the values are sane */
1725 width = (ss.right - ss.left - extra_width) / 4;
1726 height = (ss.bottom - ss.top - extra_height) / 6;
1728 if (w > width || h > height)
1737 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
1739 if (conf_get_int(conf, CONF_resize_action) != RESIZE_FONT &&
1741 width = extra_width + font_width * w;
1742 height = extra_height + font_height * h;
1744 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1745 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1746 SWP_NOMOVE | SWP_NOZORDER);
1750 InvalidateRect(hwnd, NULL, TRUE);
1753 static void reset_window(int reinit) {
1755 * This function decides how to resize or redraw when the
1756 * user changes something.
1758 * This function doesn't like to change the terminal size but if the
1759 * font size is locked that may be it's only soluion.
1761 int win_width, win_height, resize_action, window_border;
1764 #ifdef RDB_DEBUG_PATCH
1765 debug((27, "reset_window()"));
1768 /* Current window sizes ... */
1769 GetWindowRect(hwnd, &wr);
1770 GetClientRect(hwnd, &cr);
1772 win_width = cr.right - cr.left;
1773 win_height = cr.bottom - cr.top;
1775 resize_action = conf_get_int(conf, CONF_resize_action);
1776 window_border = conf_get_int(conf, CONF_window_border);
1778 if (resize_action == RESIZE_DISABLED)
1781 /* Are we being forced to reload the fonts ? */
1783 #ifdef RDB_DEBUG_PATCH
1784 debug((27, "reset_window() -- Forced deinit"));
1790 /* Oh, looks like we're minimised */
1791 if (win_width == 0 || win_height == 0)
1794 /* Is the window out of position ? */
1796 (offset_width != (win_width-font_width*term->cols)/2 ||
1797 offset_height != (win_height-font_height*term->rows)/2) ){
1798 offset_width = (win_width-font_width*term->cols)/2;
1799 offset_height = (win_height-font_height*term->rows)/2;
1800 InvalidateRect(hwnd, NULL, TRUE);
1801 #ifdef RDB_DEBUG_PATCH
1802 debug((27, "reset_window() -> Reposition terminal"));
1806 if (IsZoomed(hwnd)) {
1807 /* We're fullscreen, this means we must not change the size of
1808 * the window so it's the font size or the terminal itself.
1811 extra_width = wr.right - wr.left - cr.right + cr.left;
1812 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1814 if (resize_action != RESIZE_TERM) {
1815 if (font_width != win_width/term->cols ||
1816 font_height != win_height/term->rows) {
1818 init_fonts(win_width/term->cols, win_height/term->rows);
1819 offset_width = (win_width-font_width*term->cols)/2;
1820 offset_height = (win_height-font_height*term->rows)/2;
1821 InvalidateRect(hwnd, NULL, TRUE);
1822 #ifdef RDB_DEBUG_PATCH
1823 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1824 font_width, font_height));
1828 if (font_width * term->cols != win_width ||
1829 font_height * term->rows != win_height) {
1830 /* Our only choice at this point is to change the
1831 * size of the terminal; Oh well.
1833 term_size(term, win_height/font_height, win_width/font_width,
1834 conf_get_int(conf, CONF_savelines));
1835 offset_width = (win_width-font_width*term->cols)/2;
1836 offset_height = (win_height-font_height*term->rows)/2;
1837 InvalidateRect(hwnd, NULL, TRUE);
1838 #ifdef RDB_DEBUG_PATCH
1839 debug((27, "reset_window() -> Zoomed term_size"));
1846 /* Hmm, a force re-init means we should ignore the current window
1847 * so we resize to the default font size.
1850 #ifdef RDB_DEBUG_PATCH
1851 debug((27, "reset_window() -> Forced re-init"));
1854 offset_width = offset_height = window_border;
1855 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1856 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1858 if (win_width != font_width*term->cols + offset_width*2 ||
1859 win_height != font_height*term->rows + offset_height*2) {
1861 /* If this is too large windows will resize it to the maximum
1862 * allowed window size, we will then be back in here and resize
1863 * the font or terminal to fit.
1865 SetWindowPos(hwnd, NULL, 0, 0,
1866 font_width*term->cols + extra_width,
1867 font_height*term->rows + extra_height,
1868 SWP_NOMOVE | SWP_NOZORDER);
1871 InvalidateRect(hwnd, NULL, TRUE);
1875 /* Okay the user doesn't want us to change the font so we try the
1876 * window. But that may be too big for the screen which forces us
1877 * to change the terminal.
1879 if ((resize_action == RESIZE_TERM && reinit<=0) ||
1880 (resize_action == RESIZE_EITHER && reinit<0) ||
1882 offset_width = offset_height = window_border;
1883 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1884 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1886 if (win_width != font_width*term->cols + offset_width*2 ||
1887 win_height != font_height*term->rows + offset_height*2) {
1892 get_fullscreen_rect(&ss);
1894 width = (ss.right - ss.left - extra_width) / font_width;
1895 height = (ss.bottom - ss.top - extra_height) / font_height;
1898 if ( term->rows > height || term->cols > width ) {
1899 if (resize_action == RESIZE_EITHER) {
1900 /* Make the font the biggest we can */
1901 if (term->cols > width)
1902 font_width = (ss.right - ss.left - extra_width)
1904 if (term->rows > height)
1905 font_height = (ss.bottom - ss.top - extra_height)
1909 init_fonts(font_width, font_height);
1911 width = (ss.right - ss.left - extra_width) / font_width;
1912 height = (ss.bottom - ss.top - extra_height) / font_height;
1914 if ( height > term->rows ) height = term->rows;
1915 if ( width > term->cols ) width = term->cols;
1916 term_size(term, height, width,
1917 conf_get_int(conf, CONF_savelines));
1918 #ifdef RDB_DEBUG_PATCH
1919 debug((27, "reset_window() -> term resize to (%d,%d)",
1925 SetWindowPos(hwnd, NULL, 0, 0,
1926 font_width*term->cols + extra_width,
1927 font_height*term->rows + extra_height,
1928 SWP_NOMOVE | SWP_NOZORDER);
1930 InvalidateRect(hwnd, NULL, TRUE);
1931 #ifdef RDB_DEBUG_PATCH
1932 debug((27, "reset_window() -> window resize to (%d,%d)",
1933 font_width*term->cols + extra_width,
1934 font_height*term->rows + extra_height));
1940 /* We're allowed to or must change the font but do we want to ? */
1942 if (font_width != (win_width-window_border*2)/term->cols ||
1943 font_height != (win_height-window_border*2)/term->rows) {
1946 init_fonts((win_width-window_border*2)/term->cols,
1947 (win_height-window_border*2)/term->rows);
1948 offset_width = (win_width-font_width*term->cols)/2;
1949 offset_height = (win_height-font_height*term->rows)/2;
1951 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1952 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1954 InvalidateRect(hwnd, NULL, TRUE);
1955 #ifdef RDB_DEBUG_PATCH
1956 debug((25, "reset_window() -> font resize to (%d,%d)",
1957 font_width, font_height));
1962 static void set_input_locale(HKL kl)
1966 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1967 lbuf, sizeof(lbuf));
1969 kbd_codepage = atoi(lbuf);
1972 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1974 int thistime = GetMessageTime();
1976 if (send_raw_mouse &&
1977 !(shift && conf_get_int(conf, CONF_mouse_override))) {
1978 lastbtn = MBT_NOTHING;
1979 term_mouse(term, b, translate_button(b), MA_CLICK,
1980 x, y, shift, ctrl, alt);
1984 if (lastbtn == b && thistime - lasttime < dbltime) {
1985 lastact = (lastact == MA_CLICK ? MA_2CLK :
1986 lastact == MA_2CLK ? MA_3CLK :
1987 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1992 if (lastact != MA_NOTHING)
1993 term_mouse(term, b, translate_button(b), lastact,
1994 x, y, shift, ctrl, alt);
1995 lasttime = thistime;
1999 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
2000 * into a cooked one (SELECT, EXTEND, PASTE).
2002 static Mouse_Button translate_button(Mouse_Button button)
2004 if (button == MBT_LEFT)
2006 if (button == MBT_MIDDLE)
2007 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2008 MBT_PASTE : MBT_EXTEND;
2009 if (button == MBT_RIGHT)
2010 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2011 MBT_EXTEND : MBT_PASTE;
2012 return 0; /* shouldn't happen */
2015 static void show_mouseptr(int show)
2017 /* NB that the counter in ShowCursor() is also frobbed by
2018 * update_mouse_pointer() */
2019 static int cursor_visible = 1;
2020 if (!conf_get_int(conf, CONF_hide_mouseptr))
2021 show = 1; /* override if this feature disabled */
2022 if (cursor_visible && !show)
2024 else if (!cursor_visible && show)
2026 cursor_visible = show;
2029 static int is_alt_pressed(void)
2032 int r = GetKeyboardState(keystate);
2035 if (keystate[VK_MENU] & 0x80)
2037 if (keystate[VK_RMENU] & 0x80)
2042 static int resizing;
2044 void notify_remote_exit(void *fe)
2046 int exitcode, close_on_exit;
2048 if (!session_closed &&
2049 (exitcode = back->exitcode(backhandle)) >= 0) {
2050 close_on_exit = conf_get_int(conf, CONF_close_on_exit);
2051 /* Abnormal exits will already have set session_closed and taken
2052 * appropriate action. */
2053 if (close_on_exit == FORCE_ON ||
2054 (close_on_exit == AUTO && exitcode != INT_MAX)) {
2057 queue_toplevel_callback(close_session, NULL);
2058 session_closed = TRUE;
2059 /* exitcode == INT_MAX indicates that the connection was closed
2060 * by a fatal error, so an error box will be coming our way and
2061 * we should not generate this informational one. */
2062 if (exitcode != INT_MAX)
2063 MessageBox(hwnd, "Connection closed by remote host",
2064 appname, MB_OK | MB_ICONINFORMATION);
2069 void timer_change_notify(unsigned long next)
2071 unsigned long now = GETTICKCOUNT();
2073 if (now - next < INT_MAX)
2077 KillTimer(hwnd, TIMING_TIMER_ID);
2078 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
2079 timing_next_time = next;
2082 static void conf_cache_data(void)
2084 /* Cache some items from conf to speed lookups in very hot code */
2085 cursor_type = conf_get_int(conf, CONF_cursor_type);
2086 vtmode = conf_get_int(conf, CONF_vtmode);
2089 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2090 WPARAM wParam, LPARAM lParam)
2093 static int ignore_clip = FALSE;
2094 static int need_backend_resize = FALSE;
2095 static int fullscr_on_max = FALSE;
2096 static int processed_resize = FALSE;
2097 static UINT last_mousemove = 0;
2102 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
2105 KillTimer(hwnd, TIMING_TIMER_ID);
2106 if (run_timers(timing_next_time, &next)) {
2107 timer_change_notify(next);
2118 str = dupprintf("%s Exit Confirmation", appname);
2119 if (session_closed || !conf_get_int(conf, CONF_warn_on_close) ||
2121 "Are you sure you want to close this session?",
2122 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
2124 DestroyWindow(hwnd);
2132 case WM_INITMENUPOPUP:
2133 if ((HMENU)wParam == savedsess_menu) {
2134 /* About to pop up Saved Sessions sub-menu.
2135 * Refresh the session list. */
2136 get_sesslist(&sesslist, FALSE); /* free */
2137 get_sesslist(&sesslist, TRUE);
2138 update_savedsess_menu();
2144 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
2155 BOOL inherit_handles;
2157 PROCESS_INFORMATION pi;
2158 HANDLE filemap = NULL;
2160 if (wParam == IDM_DUPSESS) {
2162 * Allocate a file-mapping memory chunk for the
2165 SECURITY_ATTRIBUTES sa;
2169 size = conf_serialised_size(conf);
2171 sa.nLength = sizeof(sa);
2172 sa.lpSecurityDescriptor = NULL;
2173 sa.bInheritHandle = TRUE;
2174 filemap = CreateFileMapping(INVALID_HANDLE_VALUE,
2178 if (filemap && filemap != INVALID_HANDLE_VALUE) {
2179 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, size);
2181 conf_serialise(conf, p);
2185 inherit_handles = TRUE;
2186 sprintf(c, "putty &%p:%u", filemap, (unsigned)size);
2188 } else if (wParam == IDM_SAVEDSESS) {
2189 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
2190 / MENU_SAVED_STEP) + 1;
2191 if (sessno < (unsigned)sesslist.nsessions) {
2192 const char *session = sesslist.sessions[sessno];
2193 cl = dupprintf("putty @%s", session);
2194 inherit_handles = FALSE;
2198 } else /* IDM_NEWSESS */ {
2200 inherit_handles = FALSE;
2203 GetModuleFileName(NULL, b, sizeof(b) - 1);
2205 si.lpReserved = NULL;
2206 si.lpDesktop = NULL;
2210 si.lpReserved2 = NULL;
2211 CreateProcess(b, cl, NULL, NULL, inherit_handles,
2212 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
2213 CloseHandle(pi.hProcess);
2214 CloseHandle(pi.hThread);
2217 CloseHandle(filemap);
2224 logevent(NULL, "----- Session restarted -----");
2225 term_pwron(term, FALSE);
2234 int reconfig_result;
2239 reconfiguring = TRUE;
2242 * Copy the current window title into the stored
2243 * previous configuration, so that doing nothing to
2244 * the window title field in the config box doesn't
2245 * reset the title to its startup state.
2247 conf_set_str(conf, CONF_wintitle, window_name);
2249 prev_conf = conf_copy(conf);
2252 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2253 reconfiguring = FALSE;
2254 if (!reconfig_result) {
2255 conf_free(prev_conf);
2261 resize_action = conf_get_int(conf, CONF_resize_action);
2263 /* Disable full-screen if resizing forbidden */
2265 for (i = 0; i < lenof(popup_menus); i++)
2266 EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN,
2268 (resize_action == RESIZE_DISABLED)
2269 ? MF_GRAYED : MF_ENABLED);
2270 /* Gracefully unzoom if necessary */
2271 if (IsZoomed(hwnd) && (resize_action == RESIZE_DISABLED))
2272 ShowWindow(hwnd, SW_RESTORE);
2275 /* Pass new config data to the logging module */
2276 log_reconfig(logctx, conf);
2280 * Flush the line discipline's edit buffer in the
2281 * case where local editing has just been disabled.
2284 ldisc_configure(ldisc, conf);
2285 ldisc_echoedit_update(ldisc);
2294 /* Pass new config data to the terminal */
2295 term_reconfig(term, conf);
2297 /* Pass new config data to the back end */
2299 back->reconfig(backhandle, conf);
2301 /* Screen size changed ? */
2302 if (conf_get_int(conf, CONF_height) !=
2303 conf_get_int(prev_conf, CONF_height) ||
2304 conf_get_int(conf, CONF_width) !=
2305 conf_get_int(prev_conf, CONF_width) ||
2306 conf_get_int(conf, CONF_savelines) !=
2307 conf_get_int(prev_conf, CONF_savelines) ||
2308 resize_action == RESIZE_FONT ||
2309 (resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2310 resize_action == RESIZE_DISABLED)
2311 term_size(term, conf_get_int(conf, CONF_height),
2312 conf_get_int(conf, CONF_width),
2313 conf_get_int(conf, CONF_savelines));
2315 /* Enable or disable the scroll bar, etc */
2317 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2318 LONG nexflag, exflag =
2319 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2322 if (conf_get_int(conf, CONF_alwaysontop) !=
2323 conf_get_int(prev_conf, CONF_alwaysontop)) {
2324 if (conf_get_int(conf, CONF_alwaysontop)) {
2325 nexflag |= WS_EX_TOPMOST;
2326 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2327 SWP_NOMOVE | SWP_NOSIZE);
2329 nexflag &= ~(WS_EX_TOPMOST);
2330 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2331 SWP_NOMOVE | SWP_NOSIZE);
2334 if (conf_get_int(conf, CONF_sunken_edge))
2335 nexflag |= WS_EX_CLIENTEDGE;
2337 nexflag &= ~(WS_EX_CLIENTEDGE);
2340 if (conf_get_int(conf, is_full_screen() ?
2341 CONF_scrollbar_in_fullscreen :
2345 nflg &= ~WS_VSCROLL;
2347 if (resize_action == RESIZE_DISABLED ||
2349 nflg &= ~WS_THICKFRAME;
2351 nflg |= WS_THICKFRAME;
2353 if (resize_action == RESIZE_DISABLED)
2354 nflg &= ~WS_MAXIMIZEBOX;
2356 nflg |= WS_MAXIMIZEBOX;
2358 if (nflg != flag || nexflag != exflag) {
2360 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2361 if (nexflag != exflag)
2362 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2364 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2365 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2366 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2374 if (resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2379 set_title(NULL, conf_get_str(conf, CONF_wintitle));
2380 if (IsIconic(hwnd)) {
2382 conf_get_int(conf, CONF_win_name_always) ?
2383 window_name : icon_name);
2387 FontSpec *font = conf_get_fontspec(conf, CONF_font);
2388 FontSpec *prev_font = conf_get_fontspec(prev_conf,
2391 if (!strcmp(font->name, prev_font->name) ||
2392 !strcmp(conf_get_str(conf, CONF_line_codepage),
2393 conf_get_str(prev_conf, CONF_line_codepage)) ||
2394 font->isbold != prev_font->isbold ||
2395 font->height != prev_font->height ||
2396 font->charset != prev_font->charset ||
2397 conf_get_int(conf, CONF_font_quality) !=
2398 conf_get_int(prev_conf, CONF_font_quality) ||
2399 conf_get_int(conf, CONF_vtmode) !=
2400 conf_get_int(prev_conf, CONF_vtmode) ||
2401 conf_get_int(conf, CONF_bold_style) !=
2402 conf_get_int(prev_conf, CONF_bold_style) ||
2403 resize_action == RESIZE_DISABLED ||
2404 resize_action == RESIZE_EITHER ||
2405 resize_action != conf_get_int(prev_conf,
2406 CONF_resize_action))
2410 InvalidateRect(hwnd, NULL, TRUE);
2411 reset_window(init_lvl);
2413 conf_free(prev_conf);
2420 request_paste(NULL);
2426 term_pwron(term, TRUE);
2428 ldisc_echoedit_update(ldisc);
2434 launch_help(hwnd, NULL);
2438 * We get this if the System menu has been activated
2445 * We get this if the System menu has been activated
2446 * using the keyboard. This might happen from within
2447 * TranslateKey, in which case it really wants to be
2448 * followed by a `space' character to actually _bring
2449 * the menu up_ rather than just sitting there in
2450 * `ready to appear' state.
2452 show_mouseptr(1); /* make sure pointer is visible */
2454 PostMessage(hwnd, WM_CHAR, ' ', 0);
2456 case IDM_FULLSCREEN:
2460 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2461 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2463 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2464 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2466 * Ensure we haven't been sent a bogus SYSCOMMAND
2467 * which would cause us to reference invalid memory
2468 * and crash. Perhaps I'm just too paranoid here.
2470 if (i >= n_specials)
2473 back->special(backhandle, specials[i].code);
2478 #define X_POS(l) ((int)(short)LOWORD(l))
2479 #define Y_POS(l) ((int)(short)HIWORD(l))
2481 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2482 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2483 case WM_LBUTTONDOWN:
2484 case WM_MBUTTONDOWN:
2485 case WM_RBUTTONDOWN:
2489 if (message == WM_RBUTTONDOWN &&
2490 ((wParam & MK_CONTROL) ||
2491 (conf_get_int(conf, CONF_mouse_is_xterm) == 2))) {
2494 show_mouseptr(1); /* make sure pointer is visible */
2495 GetCursorPos(&cursorpos);
2496 TrackPopupMenu(popup_menus[CTXMENU].menu,
2497 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2498 cursorpos.x, cursorpos.y,
2506 case WM_LBUTTONDOWN:
2508 wParam |= MK_LBUTTON;
2511 case WM_MBUTTONDOWN:
2512 button = MBT_MIDDLE;
2513 wParam |= MK_MBUTTON;
2516 case WM_RBUTTONDOWN:
2518 wParam |= MK_RBUTTON;
2523 wParam &= ~MK_LBUTTON;
2527 button = MBT_MIDDLE;
2528 wParam &= ~MK_MBUTTON;
2533 wParam &= ~MK_RBUTTON;
2537 button = press = 0; /* shouldn't happen */
2541 * Special case: in full-screen mode, if the left
2542 * button is clicked in the very top left corner of the
2543 * window, we put up the System menu instead of doing
2547 char mouse_on_hotspot = 0;
2556 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2559 mi.cbSize = sizeof(MONITORINFO);
2560 GetMonitorInfo(mon, &mi);
2562 if (mi.rcMonitor.left == pt.x &&
2563 mi.rcMonitor.top == pt.y) {
2564 mouse_on_hotspot = 1;
2569 if (pt.x == 0 && pt.y == 0) {
2570 mouse_on_hotspot = 1;
2573 if (is_full_screen() && press &&
2574 button == MBT_LEFT && mouse_on_hotspot) {
2575 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2576 MAKELPARAM(pt.x, pt.y));
2583 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2584 wParam & MK_SHIFT, wParam & MK_CONTROL,
2588 term_mouse(term, button, translate_button(button), MA_RELEASE,
2589 TO_CHR_X(X_POS(lParam)),
2590 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2591 wParam & MK_CONTROL, is_alt_pressed());
2592 if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)))
2600 * Windows seems to like to occasionally send MOUSEMOVE
2601 * events even if the mouse hasn't moved. Don't unhide
2602 * the mouse pointer in this case.
2604 static WPARAM wp = 0;
2605 static LPARAM lp = 0;
2606 if (wParam != wp || lParam != lp ||
2607 last_mousemove != WM_MOUSEMOVE) {
2609 wp = wParam; lp = lParam;
2610 last_mousemove = WM_MOUSEMOVE;
2614 * Add the mouse position and message time to the random
2617 noise_ultralight(lParam);
2619 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2620 GetCapture() == hwnd) {
2622 if (wParam & MK_LBUTTON)
2624 else if (wParam & MK_MBUTTON)
2628 term_mouse(term, b, translate_button(b), MA_DRAG,
2629 TO_CHR_X(X_POS(lParam)),
2630 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2631 wParam & MK_CONTROL, is_alt_pressed());
2634 case WM_NCMOUSEMOVE:
2636 static WPARAM wp = 0;
2637 static LPARAM lp = 0;
2638 if (wParam != wp || lParam != lp ||
2639 last_mousemove != WM_NCMOUSEMOVE) {
2641 wp = wParam; lp = lParam;
2642 last_mousemove = WM_NCMOUSEMOVE;
2645 noise_ultralight(lParam);
2647 case WM_IGNORE_CLIP:
2648 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2650 case WM_DESTROYCLIPBOARD:
2652 term_deselect(term);
2653 ignore_clip = FALSE;
2660 hdc = BeginPaint(hwnd, &p);
2662 SelectPalette(hdc, pal, TRUE);
2663 RealizePalette(hdc);
2667 * We have to be careful about term_paint(). It will
2668 * set a bunch of character cells to INVALID and then
2669 * call do_paint(), which will redraw those cells and
2670 * _then mark them as done_. This may not be accurate:
2671 * when painting in WM_PAINT context we are restricted
2672 * to the rectangle which has just been exposed - so if
2673 * that only covers _part_ of a character cell and the
2674 * rest of it was already visible, that remainder will
2675 * not be redrawn at all. Accordingly, we must not
2676 * paint any character cell in a WM_PAINT context which
2677 * already has a pending update due to terminal output.
2678 * The simplest solution to this - and many, many
2679 * thanks to Hung-Te Lin for working all this out - is
2680 * not to do any actual painting at _all_ if there's a
2681 * pending terminal update: just mark the relevant
2682 * character cells as INVALID and wait for the
2683 * scheduled full update to sort it out.
2685 * I have a suspicion this isn't the _right_ solution.
2686 * An alternative approach would be to have terminal.c
2687 * separately track what _should_ be on the terminal
2688 * screen and what _is_ on the terminal screen, and
2689 * have two completely different types of redraw (one
2690 * for full updates, which syncs the former with the
2691 * terminal itself, and one for WM_PAINT which syncs
2692 * the latter with the former); yet another possibility
2693 * would be to have the Windows front end do what the
2694 * GTK one already does, and maintain a bitmap of the
2695 * current terminal appearance so that WM_PAINT becomes
2696 * completely trivial. However, this should do for now.
2698 term_paint(term, hdc,
2699 (p.rcPaint.left-offset_width)/font_width,
2700 (p.rcPaint.top-offset_height)/font_height,
2701 (p.rcPaint.right-offset_width-1)/font_width,
2702 (p.rcPaint.bottom-offset_height-1)/font_height,
2703 !term->window_update_pending);
2706 p.rcPaint.left < offset_width ||
2707 p.rcPaint.top < offset_height ||
2708 p.rcPaint.right >= offset_width + font_width*term->cols ||
2709 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2711 HBRUSH fillcolour, oldbrush;
2713 fillcolour = CreateSolidBrush (
2714 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2715 oldbrush = SelectObject(hdc, fillcolour);
2716 edge = CreatePen(PS_SOLID, 0,
2717 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2718 oldpen = SelectObject(hdc, edge);
2721 * Jordan Russell reports that this apparently
2722 * ineffectual IntersectClipRect() call masks a
2723 * Windows NT/2K bug causing strange display
2724 * problems when the PuTTY window is taller than
2725 * the primary monitor. It seems harmless enough...
2727 IntersectClipRect(hdc,
2728 p.rcPaint.left, p.rcPaint.top,
2729 p.rcPaint.right, p.rcPaint.bottom);
2731 ExcludeClipRect(hdc,
2732 offset_width, offset_height,
2733 offset_width+font_width*term->cols,
2734 offset_height+font_height*term->rows);
2736 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2737 p.rcPaint.right, p.rcPaint.bottom);
2739 /* SelectClipRgn(hdc, NULL); */
2741 SelectObject(hdc, oldbrush);
2742 DeleteObject(fillcolour);
2743 SelectObject(hdc, oldpen);
2746 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2747 SelectObject(hdc, GetStockObject(WHITE_PEN));
2755 * To protect against re-entrancy when Windows's recv()
2756 * immediately triggers a new WSAAsyncSelect window
2757 * message, we don't call select_result directly from this
2758 * handler but instead wait until we're back out at the
2759 * top level of the message loop.
2761 struct wm_netevent_params *params =
2762 snew(struct wm_netevent_params);
2763 params->wParam = wParam;
2764 params->lParam = lParam;
2765 queue_toplevel_callback(wm_netevent_callback, params);
2769 term_set_focus(term, TRUE);
2770 CreateCaret(hwnd, caretbm, font_width, font_height);
2772 flash_window(0); /* stop */
2778 term_set_focus(term, FALSE);
2780 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2783 case WM_ENTERSIZEMOVE:
2784 #ifdef RDB_DEBUG_PATCH
2785 debug((27, "WM_ENTERSIZEMOVE"));
2789 need_backend_resize = FALSE;
2791 case WM_EXITSIZEMOVE:
2794 #ifdef RDB_DEBUG_PATCH
2795 debug((27, "WM_EXITSIZEMOVE"));
2797 if (need_backend_resize) {
2798 term_size(term, conf_get_int(conf, CONF_height),
2799 conf_get_int(conf, CONF_width),
2800 conf_get_int(conf, CONF_savelines));
2801 InvalidateRect(hwnd, NULL, TRUE);
2806 * This does two jobs:
2807 * 1) Keep the sizetip uptodate
2808 * 2) Make sure the window size is _stepped_ in units of the font size.
2810 resize_action = conf_get_int(conf, CONF_resize_action);
2811 if (resize_action == RESIZE_TERM ||
2812 (resize_action == RESIZE_EITHER && !is_alt_pressed())) {
2813 int width, height, w, h, ew, eh;
2814 LPRECT r = (LPRECT) lParam;
2816 if (!need_backend_resize && resize_action == RESIZE_EITHER &&
2817 (conf_get_int(conf, CONF_height) != term->rows ||
2818 conf_get_int(conf, CONF_width) != term->cols)) {
2820 * Great! It seems that both the terminal size and the
2821 * font size have been changed and the user is now dragging.
2823 * It will now be difficult to get back to the configured
2826 * This would be easier but it seems to be too confusing.
2828 conf_set_int(conf, CONF_height, term->rows);
2829 conf_set_int(conf, CONF_width, term->cols);
2831 InvalidateRect(hwnd, NULL, TRUE);
2832 need_backend_resize = TRUE;
2835 width = r->right - r->left - extra_width;
2836 height = r->bottom - r->top - extra_height;
2837 w = (width + font_width / 2) / font_width;
2840 h = (height + font_height / 2) / font_height;
2843 UpdateSizeTip(hwnd, w, h);
2844 ew = width - w * font_width;
2845 eh = height - h * font_height;
2847 if (wParam == WMSZ_LEFT ||
2848 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2854 if (wParam == WMSZ_TOP ||
2855 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2865 int width, height, w, h, rv = 0;
2866 int window_border = conf_get_int(conf, CONF_window_border);
2867 int ex_width = extra_width + (window_border - offset_width) * 2;
2868 int ex_height = extra_height + (window_border - offset_height) * 2;
2869 LPRECT r = (LPRECT) lParam;
2871 width = r->right - r->left - ex_width;
2872 height = r->bottom - r->top - ex_height;
2874 w = (width + term->cols/2)/term->cols;
2875 h = (height + term->rows/2)/term->rows;
2876 if ( r->right != r->left + w*term->cols + ex_width)
2879 if (wParam == WMSZ_LEFT ||
2880 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2881 r->left = r->right - w*term->cols - ex_width;
2883 r->right = r->left + w*term->cols + ex_width;
2885 if (r->bottom != r->top + h*term->rows + ex_height)
2888 if (wParam == WMSZ_TOP ||
2889 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2890 r->top = r->bottom - h*term->rows - ex_height;
2892 r->bottom = r->top + h*term->rows + ex_height;
2896 /* break; (never reached) */
2897 case WM_FULLSCR_ON_MAX:
2898 fullscr_on_max = TRUE;
2901 sys_cursor_update();
2904 resize_action = conf_get_int(conf, CONF_resize_action);
2905 #ifdef RDB_DEBUG_PATCH
2906 debug((27, "WM_SIZE %s (%d,%d)",
2907 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2908 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2909 (wParam == SIZE_RESTORED && resizing) ? "to":
2910 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2912 LOWORD(lParam), HIWORD(lParam)));
2914 if (wParam == SIZE_MINIMIZED)
2916 conf_get_int(conf, CONF_win_name_always) ?
2917 window_name : icon_name);
2918 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2919 SetWindowText(hwnd, window_name);
2920 if (wParam == SIZE_RESTORED) {
2921 processed_resize = FALSE;
2922 clear_full_screen();
2923 if (processed_resize) {
2925 * Inhibit normal processing of this WM_SIZE; a
2926 * secondary one was triggered just now by
2927 * clear_full_screen which contained the correct
2933 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2934 fullscr_on_max = FALSE;
2935 processed_resize = FALSE;
2937 if (processed_resize) {
2939 * Inhibit normal processing of this WM_SIZE; a
2940 * secondary one was triggered just now by
2941 * make_full_screen which contained the correct client
2948 processed_resize = TRUE;
2950 if (resize_action == RESIZE_DISABLED) {
2951 /* A resize, well it better be a minimize. */
2955 int width, height, w, h;
2956 int window_border = conf_get_int(conf, CONF_window_border);
2958 width = LOWORD(lParam);
2959 height = HIWORD(lParam);
2961 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2963 prev_rows = term->rows;
2964 prev_cols = term->cols;
2965 if (resize_action == RESIZE_TERM) {
2966 w = width / font_width;
2968 h = height / font_height;
2973 * As below, if we're in the middle of an
2974 * interactive resize we don't call
2975 * back->size. In Windows 7, this case can
2976 * arise in maximisation as well via the Aero
2979 need_backend_resize = TRUE;
2980 conf_set_int(conf, CONF_height, h);
2981 conf_set_int(conf, CONF_width, w);
2983 term_size(term, h, w,
2984 conf_get_int(conf, CONF_savelines));
2988 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2990 if (resize_action == RESIZE_TERM) {
2991 w = (width-window_border*2) / font_width;
2993 h = (height-window_border*2) / font_height;
2995 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
2997 } else if (resize_action != RESIZE_FONT)
3001 } else if (wParam == SIZE_MINIMIZED) {
3003 } else if (resize_action == RESIZE_TERM ||
3004 (resize_action == RESIZE_EITHER &&
3005 !is_alt_pressed())) {
3006 w = (width-window_border*2) / font_width;
3008 h = (height-window_border*2) / font_height;
3013 * Don't call back->size in mid-resize. (To
3014 * prevent massive numbers of resize events
3015 * getting sent down the connection during an NT
3018 need_backend_resize = TRUE;
3019 conf_set_int(conf, CONF_height, h);
3020 conf_set_int(conf, CONF_width, w);
3022 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
3028 sys_cursor_update();
3031 switch (LOWORD(wParam)) {
3033 term_scroll(term, -1, 0);
3036 term_scroll(term, +1, 0);
3039 term_scroll(term, 0, +1);
3042 term_scroll(term, 0, -1);
3045 term_scroll(term, 0, +term->rows / 2);
3048 term_scroll(term, 0, -term->rows / 2);
3050 case SB_THUMBPOSITION:
3053 * Use GetScrollInfo instead of HIWORD(wParam) to get
3054 * 32-bit scroll position.
3059 si.cbSize = sizeof(si);
3060 si.fMask = SIF_TRACKPOS;
3061 if (GetScrollInfo(hwnd, SB_VERT, &si) == 0)
3062 si.nTrackPos = HIWORD(wParam);
3063 term_scroll(term, 1, si.nTrackPos);
3068 case WM_PALETTECHANGED:
3069 if ((HWND) wParam != hwnd && pal != NULL) {
3070 HDC hdc = get_ctx(NULL);
3072 if (RealizePalette(hdc) > 0)
3078 case WM_QUERYNEWPALETTE:
3080 HDC hdc = get_ctx(NULL);
3082 if (RealizePalette(hdc) > 0)
3094 * Add the scan code and keypress timing to the random
3097 noise_ultralight(lParam);
3100 * We don't do TranslateMessage since it disassociates the
3101 * resulting CHAR message from the KEYDOWN that sparked it,
3102 * which we occasionally don't want. Instead, we process
3103 * KEYDOWN, and call the Win32 translator functions so that
3104 * we get the translations under _our_ control.
3107 unsigned char buf[20];
3110 if (wParam == VK_PROCESSKEY || /* IME PROCESS key */
3111 wParam == VK_PACKET) { /* 'this key is a Unicode char' */
3112 if (message == WM_KEYDOWN) {
3115 m.message = WM_KEYDOWN;
3117 m.lParam = lParam & 0xdfff;
3118 TranslateMessage(&m);
3119 } else break; /* pass to Windows for default processing */
3121 len = TranslateKey(message, wParam, lParam, buf);
3123 return DefWindowProcW(hwnd, message, wParam, lParam);
3127 * We need not bother about stdin backlogs
3128 * here, because in GUI PuTTY we can't do
3129 * anything about it anyway; there's no means
3130 * of asking Windows to hold off on KEYDOWN
3131 * messages. We _have_ to buffer everything
3134 term_seen_key_event(term);
3136 ldisc_send(ldisc, buf, len, 1);
3142 case WM_INPUTLANGCHANGE:
3143 /* wParam == Font number */
3144 /* lParam == Locale */
3145 set_input_locale((HKL)lParam);
3146 sys_cursor_update();
3148 case WM_IME_STARTCOMPOSITION:
3150 HIMC hImc = ImmGetContext(hwnd);
3151 ImmSetCompositionFont(hImc, &lfont);
3152 ImmReleaseContext(hwnd, hImc);
3155 case WM_IME_COMPOSITION:
3161 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
3162 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
3164 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
3165 break; /* fall back to DefWindowProc */
3167 hIMC = ImmGetContext(hwnd);
3168 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3172 buff = snewn(n, char);
3173 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
3175 * Jaeyoun Chung reports that Korean character
3176 * input doesn't work correctly if we do a single
3177 * luni_send() covering the whole of buff. So
3178 * instead we luni_send the characters one by one.
3180 term_seen_key_event(term);
3181 /* don't divide SURROGATE PAIR */
3183 for (i = 0; i < n; i += 2) {
3184 WCHAR hs = *(unsigned short *)(buff+i);
3185 if (IS_HIGH_SURROGATE(hs) && i+2 < n) {
3186 WCHAR ls = *(unsigned short *)(buff+i+2);
3187 if (IS_LOW_SURROGATE(ls)) {
3188 luni_send(ldisc, (unsigned short *)(buff+i), 2, 1);
3193 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
3198 ImmReleaseContext(hwnd, hIMC);
3203 if (wParam & 0xFF00) {
3204 unsigned char buf[2];
3207 buf[0] = wParam >> 8;
3208 term_seen_key_event(term);
3210 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
3212 char c = (unsigned char) wParam;
3213 term_seen_key_event(term);
3215 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
3221 * Nevertheless, we are prepared to deal with WM_CHAR
3222 * messages, should they crop up. So if someone wants to
3223 * post the things to us as part of a macro manoeuvre,
3224 * we're ready to cope.
3227 static wchar_t pending_surrogate = 0;
3230 if (IS_HIGH_SURROGATE(c)) {
3231 pending_surrogate = c;
3232 } else if (IS_SURROGATE_PAIR(pending_surrogate, c)) {
3234 pair[0] = pending_surrogate;
3236 term_seen_key_event(term);
3237 luni_send(ldisc, pair, 2, 1);
3238 } else if (!IS_SURROGATE(c)) {
3239 term_seen_key_event(term);
3240 luni_send(ldisc, &c, 1, 1);
3244 case WM_SYSCOLORCHANGE:
3245 if (conf_get_int(conf, CONF_system_colour)) {
3246 /* Refresh palette from system colours. */
3247 /* XXX actually this zaps the entire palette. */
3250 /* Force a repaint of the terminal window. */
3251 term_invalidate(term);
3254 case WM_AGENT_CALLBACK:
3256 struct agent_callback *c = (struct agent_callback *)lParam;
3257 c->callback(c->callback_ctx, c->data, c->len);
3261 case WM_GOT_CLIPDATA:
3262 if (process_clipdata((HGLOBAL)lParam, wParam))
3263 term_do_paste(term);
3266 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
3267 int shift_pressed=0, control_pressed=0;
3269 if (message == WM_MOUSEWHEEL) {
3270 wheel_accumulator += (short)HIWORD(wParam);
3271 shift_pressed=LOWORD(wParam) & MK_SHIFT;
3272 control_pressed=LOWORD(wParam) & MK_CONTROL;
3275 wheel_accumulator += (int)wParam;
3276 if (GetKeyboardState(keys)!=0) {
3277 shift_pressed=keys[VK_SHIFT]&0x80;
3278 control_pressed=keys[VK_CONTROL]&0x80;
3282 /* process events when the threshold is reached */
3283 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
3286 /* reduce amount for next time */
3287 if (wheel_accumulator > 0) {
3289 wheel_accumulator -= WHEEL_DELTA;
3290 } else if (wheel_accumulator < 0) {
3292 wheel_accumulator += WHEEL_DELTA;
3296 if (send_raw_mouse &&
3297 !(conf_get_int(conf, CONF_mouse_override) &&
3299 /* Mouse wheel position is in screen coordinates for
3302 p.x = X_POS(lParam); p.y = Y_POS(lParam);
3303 if (ScreenToClient(hwnd, &p)) {
3304 /* send a mouse-down followed by a mouse up */
3305 term_mouse(term, b, translate_button(b),
3308 TO_CHR_Y(p.y), shift_pressed,
3309 control_pressed, is_alt_pressed());
3310 } /* else: not sure when this can fail */
3312 /* trigger a scroll */
3313 term_scroll(term, 0,
3315 -term->rows / 2 : term->rows / 2);
3323 * Any messages we don't process completely above are passed through to
3324 * DefWindowProc() for default processing.
3326 return DefWindowProcW(hwnd, message, wParam, lParam);
3330 * Move the system caret. (We maintain one, even though it's
3331 * invisible, for the benefit of blind people: apparently some
3332 * helper software tracks the system caret, so we should arrange to
3335 void sys_cursor(void *frontend, int x, int y)
3339 if (!term->has_focus) return;
3342 * Avoid gratuitously re-updating the cursor position and IMM
3343 * window if there's no actual change required.
3345 cx = x * font_width + offset_width;
3346 cy = y * font_height + offset_height;
3347 if (cx == caret_x && cy == caret_y)
3352 sys_cursor_update();
3355 static void sys_cursor_update(void)
3360 if (!term->has_focus) return;
3362 if (caret_x < 0 || caret_y < 0)
3365 SetCaretPos(caret_x, caret_y);
3367 /* IMM calls on Win98 and beyond only */
3368 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3370 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3371 osVersion.dwMinorVersion == 0) return; /* 95 */
3373 /* we should have the IMM functions */
3374 hIMC = ImmGetContext(hwnd);
3375 cf.dwStyle = CFS_POINT;
3376 cf.ptCurrentPos.x = caret_x;
3377 cf.ptCurrentPos.y = caret_y;
3378 ImmSetCompositionWindow(hIMC, &cf);
3380 ImmReleaseContext(hwnd, hIMC);
3384 * Draw a line of text in the window, at given character
3385 * coordinates, in given attributes.
3387 * We are allowed to fiddle with the contents of `text'.
3389 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3390 unsigned long attr, int lattr)
3393 int nfg, nbg, nfont;
3396 int force_manual_underline = 0;
3397 int fnt_width, char_width;
3398 int text_adjust = 0;
3400 int maxlen, remaining, opaque;
3401 int is_cursor = FALSE;
3402 static int *lpDx = NULL;
3403 static int lpDx_len = 0;
3405 int len2; /* for SURROGATE PAIR */
3407 lattr &= LATTR_MODE;
3409 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3411 if (attr & ATTR_WIDE)
3414 /* Only want the left half of double width lines */
3415 if (lattr != LATTR_NORM && x*2 >= term->cols)
3423 if ((attr & TATTR_ACTCURS) && (cursor_type == 0 || term->big_cursor)) {
3424 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3425 /* cursor fg and bg */
3426 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3431 if (vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3432 /* Assume a poorman font is borken in other ways too. */
3442 nfont |= FONT_WIDE + FONT_HIGH;
3445 if (attr & ATTR_NARROW)
3446 nfont |= FONT_NARROW;
3448 #ifdef USES_VTLINE_HACK
3449 /* Special hack for the VT100 linedraw glyphs. */
3450 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3451 switch ((unsigned char) (text[0])) {
3453 text_adjust = -2 * font_height / 5;
3456 text_adjust = -1 * font_height / 5;
3459 text_adjust = font_height / 5;
3462 text_adjust = 2 * font_height / 5;
3465 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3467 text[0] = ucsdata.unitab_xterm['q'];
3468 if (attr & ATTR_UNDER) {
3469 attr &= ~ATTR_UNDER;
3470 force_manual_underline = 1;
3475 /* Anything left as an original character set is unprintable. */
3476 if (DIRECT_CHAR(text[0]) &&
3477 (len < 2 || !IS_SURROGATE_PAIR(text[0], text[1]))) {
3479 for (i = 0; i < len; i++)
3484 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3487 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3488 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3489 if (bold_font_mode == BOLD_FONT && (attr & ATTR_BOLD))
3491 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3492 nfont |= FONT_UNDERLINE;
3493 another_font(nfont);
3494 if (!fonts[nfont]) {
3495 if (nfont & FONT_UNDERLINE)
3496 force_manual_underline = 1;
3497 /* Don't do the same for manual bold, it could be bad news. */
3499 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3501 another_font(nfont);
3503 nfont = FONT_NORMAL;
3504 if (attr & ATTR_REVERSE) {
3509 if (bold_colours && (attr & ATTR_BOLD) && !is_cursor) {
3510 if (nfg < 16) nfg |= 8;
3511 else if (nfg >= 256) nfg |= 1;
3513 if (bold_colours && (attr & ATTR_BLINK)) {
3514 if (nbg < 16) nbg |= 8;
3515 else if (nbg >= 256) nbg |= 1;
3519 SelectObject(hdc, fonts[nfont]);
3520 SetTextColor(hdc, fg);
3521 SetBkColor(hdc, bg);
3522 if (attr & TATTR_COMBINING)
3523 SetBkMode(hdc, TRANSPARENT);
3525 SetBkMode(hdc, OPAQUE);
3528 line_box.right = x + char_width * len;
3529 line_box.bottom = y + font_height;
3530 /* adjust line_box.right for SURROGATE PAIR & VARIATION SELECTOR */
3534 for (i = 0; i < len ; i++) {
3535 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3537 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i], text[i+1])) {
3538 rc_width += char_width;
3540 } else if (IS_LOW_VARSEL(text[i])) {
3543 rc_width += char_width;
3546 line_box.right = line_box.left + rc_width;
3549 /* Only want the left half of double width lines */
3550 if (line_box.right > font_width*term->cols+offset_width)
3551 line_box.right = font_width*term->cols+offset_width;
3553 if (font_varpitch) {
3555 * If we're using a variable-pitch font, we unconditionally
3556 * draw the glyphs one at a time and centre them in their
3557 * character cells (which means in particular that we must
3558 * disable the lpDx mechanism). This gives slightly odd but
3559 * generally reasonable results.
3561 xoffset = char_width / 2;
3562 SetTextAlign(hdc, TA_TOP | TA_CENTER | TA_NOUPDATECP);
3567 * In a fixed-pitch font, we draw the whole string in one go
3568 * in the normal way.
3571 SetTextAlign(hdc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
3576 opaque = TRUE; /* start by erasing the rectangle */
3577 for (remaining = len; remaining > 0;
3578 text += len, remaining -= len, x += char_width * len2) {
3579 len = (maxlen < remaining ? maxlen : remaining);
3580 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3583 if (remaining >= 1 && IS_SURROGATE_PAIR(text[0], text[1]))
3585 if (remaining-len >= 1 && IS_LOW_VARSEL(text[len]))
3587 else if (remaining-len >= 2 &&
3588 IS_HIGH_VARSEL(text[len], text[len+1]))
3592 if (len > lpDx_len) {
3593 lpDx_len = len * 9 / 8 + 16;
3594 lpDx = sresize(lpDx, lpDx_len, int);
3596 if (lpDx_maybe) lpDx_maybe = lpDx;
3601 /* only last char has dx width in SURROGATE PAIR and
3602 * VARIATION sequence */
3603 for (i = 0; i < len; i++) {
3604 lpDx[i] = char_width;
3605 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3606 if (i > 0) lpDx[i-1] = 0;
3609 lpDx[i] = char_width;
3610 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i],text[i+1])) {
3613 lpDx[i] = char_width;
3614 } else if (IS_LOW_VARSEL(text[i])) {
3615 if (i > 0) lpDx[i-1] = 0;
3616 lpDx[i] = char_width;
3621 /* We're using a private area for direct to font. (512 chars.) */
3622 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3623 /* Ho Hum, dbcs fonts are a PITA! */
3624 /* To display on W9x I have to convert to UCS */
3625 static wchar_t *uni_buf = 0;
3626 static int uni_len = 0;
3628 if (len > uni_len) {
3631 uni_buf = snewn(uni_len, wchar_t);
3634 for(nlen = mptr = 0; mptr<len; mptr++) {
3635 uni_buf[nlen] = 0xFFFD;
3636 if (IsDBCSLeadByteEx(ucsdata.font_codepage,
3637 (BYTE) text[mptr])) {
3639 dbcstext[0] = text[mptr] & 0xFF;
3640 dbcstext[1] = text[mptr+1] & 0xFF;
3641 lpDx[nlen] += char_width;
3642 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3643 dbcstext, 2, uni_buf+nlen, 1);
3649 dbcstext[0] = text[mptr] & 0xFF;
3650 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3651 dbcstext, 1, uni_buf+nlen, 1);
3658 ExtTextOutW(hdc, x + xoffset,
3659 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3660 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3661 &line_box, uni_buf, nlen,
3663 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3664 SetBkMode(hdc, TRANSPARENT);
3665 ExtTextOutW(hdc, x + xoffset - 1,
3666 y - font_height * (lattr ==
3667 LATTR_BOT) + text_adjust,
3668 ETO_CLIPPED, &line_box, uni_buf, nlen, lpDx_maybe);
3672 } else if (DIRECT_FONT(text[0])) {
3673 static char *directbuf = NULL;
3674 static int directlen = 0;
3676 if (len > directlen) {
3678 directbuf = sresize(directbuf, directlen, char);
3681 for (i = 0; i < len; i++)
3682 directbuf[i] = text[i] & 0xFF;
3684 ExtTextOut(hdc, x + xoffset,
3685 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3686 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3687 &line_box, directbuf, len, lpDx_maybe);
3688 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3689 SetBkMode(hdc, TRANSPARENT);
3691 /* GRR: This draws the character outside its box and
3692 * can leave 'droppings' even with the clip box! I
3693 * suppose I could loop it one character at a time ...
3696 * Or ... I could do a test print with "W", and use +1
3697 * or -1 for this shift depending on if the leftmost
3698 * column is blank...
3700 ExtTextOut(hdc, x + xoffset - 1,
3701 y - font_height * (lattr ==
3702 LATTR_BOT) + text_adjust,
3703 ETO_CLIPPED, &line_box, directbuf, len, lpDx_maybe);
3706 /* And 'normal' unicode characters */
3707 static WCHAR *wbuf = NULL;
3708 static int wlen = 0;
3714 wbuf = snewn(wlen, WCHAR);
3717 for (i = 0; i < len; i++)
3720 /* print Glyphs as they are, without Windows' Shaping*/
3721 general_textout(hdc, x + xoffset,
3722 y - font_height * (lattr==LATTR_BOT) + text_adjust,
3723 &line_box, wbuf, len, lpDx,
3724 opaque && !(attr & TATTR_COMBINING));
3726 /* And the shadow bold hack. */
3727 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3728 SetBkMode(hdc, TRANSPARENT);
3729 ExtTextOutW(hdc, x + xoffset - 1,
3730 y - font_height * (lattr ==
3731 LATTR_BOT) + text_adjust,
3732 ETO_CLIPPED, &line_box, wbuf, len, lpDx_maybe);
3737 * If we're looping round again, stop erasing the background
3740 SetBkMode(hdc, TRANSPARENT);
3743 if (lattr != LATTR_TOP && (force_manual_underline ||
3744 (und_mode == UND_LINE
3745 && (attr & ATTR_UNDER)))) {
3748 if (lattr == LATTR_BOT)
3749 dec = dec * 2 - font_height;
3751 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3752 MoveToEx(hdc, line_box.left, line_box.top + dec, NULL);
3753 LineTo(hdc, line_box.right, line_box.top + dec);
3754 oldpen = SelectObject(hdc, oldpen);
3755 DeleteObject(oldpen);
3760 * Wrapper that handles combining characters.
3762 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3763 unsigned long attr, int lattr)
3765 if (attr & TATTR_COMBINING) {
3766 unsigned long a = 0;
3768 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3769 if (len >= 2 && IS_SURROGATE_PAIR(text[0], text[1]))
3771 if (len-len0 >= 1 && IS_LOW_VARSEL(text[len0])) {
3772 attr &= ~TATTR_COMBINING;
3773 do_text_internal(ctx, x, y, text, len0+1, attr, lattr);
3776 a = TATTR_COMBINING;
3777 } else if (len-len0 >= 2 && IS_HIGH_VARSEL(text[len0], text[len0+1])) {
3778 attr &= ~TATTR_COMBINING;
3779 do_text_internal(ctx, x, y, text, len0+2, attr, lattr);
3782 a = TATTR_COMBINING;
3784 attr &= ~TATTR_COMBINING;
3788 if (len >= 1 && IS_SURROGATE_PAIR(text[0], text[1])) {
3789 do_text_internal(ctx, x, y, text, 2, attr | a, lattr);
3793 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3797 a = TATTR_COMBINING;
3800 do_text_internal(ctx, x, y, text, len, attr, lattr);
3803 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3804 unsigned long attr, int lattr)
3810 int ctype = cursor_type;
3812 lattr &= LATTR_MODE;
3814 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3815 if (*text != UCSWIDE) {
3816 do_text(ctx, x, y, text, len, attr, lattr);
3820 attr |= TATTR_RIGHTCURS;
3823 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3824 if (attr & ATTR_WIDE)
3831 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3834 pts[0].x = pts[1].x = pts[4].x = x;
3835 pts[2].x = pts[3].x = x + char_width - 1;
3836 pts[0].y = pts[3].y = pts[4].y = y;
3837 pts[1].y = pts[2].y = y + font_height - 1;
3838 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3839 Polyline(hdc, pts, 5);
3840 oldpen = SelectObject(hdc, oldpen);
3841 DeleteObject(oldpen);
3842 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3843 int startx, starty, dx, dy, length, i;
3846 starty = y + descent;
3849 length = char_width;
3852 if (attr & TATTR_RIGHTCURS)
3853 xadjust = char_width - 1;
3854 startx = x + xadjust;
3858 length = font_height;
3860 if (attr & TATTR_ACTCURS) {
3863 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3864 MoveToEx(hdc, startx, starty, NULL);
3865 LineTo(hdc, startx + dx * length, starty + dy * length);
3866 oldpen = SelectObject(hdc, oldpen);
3867 DeleteObject(oldpen);
3869 for (i = 0; i < length; i++) {
3871 SetPixel(hdc, startx, starty, colours[261]);
3880 /* This function gets the actual width of a character in the normal font.
3882 int char_width(Context ctx, int uc) {
3886 /* If the font max is the same as the font ave width then this
3887 * function is a no-op.
3889 if (!font_dualwidth) return 1;
3891 switch (uc & CSET_MASK) {
3893 uc = ucsdata.unitab_line[uc & 0xFF];
3896 uc = ucsdata.unitab_xterm[uc & 0xFF];
3899 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3902 if (DIRECT_FONT(uc)) {
3903 if (ucsdata.dbcs_screenfont) return 1;
3905 /* Speedup, I know of no font where ascii is the wrong width */
3906 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3909 if ( (uc & CSET_MASK) == CSET_ACP ) {
3910 SelectObject(hdc, fonts[FONT_NORMAL]);
3911 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3912 another_font(FONT_OEM);
3913 if (!fonts[FONT_OEM]) return 0;
3915 SelectObject(hdc, fonts[FONT_OEM]);
3919 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3920 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3923 /* Speedup, I know of no font where ascii is the wrong width */
3924 if (uc >= ' ' && uc <= '~') return 1;
3926 SelectObject(hdc, fonts[FONT_NORMAL]);
3927 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3928 /* Okay that one worked */ ;
3929 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3930 /* This should work on 9x too, but it's "less accurate" */ ;
3935 ibuf += font_width / 2 -1;
3941 DECL_WINDOWS_FUNCTION(static, BOOL, FlashWindowEx, (PFLASHWINFO));
3942 DECL_WINDOWS_FUNCTION(static, BOOL, ToUnicodeEx,
3943 (UINT, UINT, const BYTE *, LPWSTR, int, UINT, HKL));
3945 static void init_winfuncs(void)
3947 HMODULE user32_module = load_system32_dll("user32.dll");
3948 GET_WINDOWS_FUNCTION(user32_module, FlashWindowEx);
3949 GET_WINDOWS_FUNCTION(user32_module, ToUnicodeEx);
3953 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3954 * codes. Returns number of bytes used, zero to drop the message,
3955 * -1 to forward the message to Windows, or another negative number
3956 * to indicate a NUL-terminated "special" string.
3958 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3959 unsigned char *output)
3962 int scan, left_alt = 0, key_down, shift_state;
3964 unsigned char *p = output;
3965 static int alt_sum = 0;
3966 int funky_type = conf_get_int(conf, CONF_funky_type);
3967 int no_applic_k = conf_get_int(conf, CONF_no_applic_k);
3968 int ctrlaltkeys = conf_get_int(conf, CONF_ctrlaltkeys);
3969 int nethack_keypad = conf_get_int(conf, CONF_nethack_keypad);
3971 HKL kbd_layout = GetKeyboardLayout(0);
3973 static wchar_t keys_unicode[3];
3974 static int compose_char = 0;
3975 static WPARAM compose_keycode = 0;
3977 r = GetKeyboardState(keystate);
3979 memset(keystate, 0, sizeof(keystate));
3982 #define SHOW_TOASCII_RESULT
3983 { /* Tell us all about key events */
3984 static BYTE oldstate[256];
3985 static int first = 1;
3989 memcpy(oldstate, keystate, sizeof(oldstate));
3992 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3994 } else if ((HIWORD(lParam) & KF_UP)
3995 && scan == (HIWORD(lParam) & 0xFF)) {
3999 if (wParam >= VK_F1 && wParam <= VK_F20)
4000 debug(("K_F%d", wParam + 1 - VK_F1));
4013 debug(("VK_%02x", wParam));
4015 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
4017 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
4019 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
4020 if (ch >= ' ' && ch <= '~')
4021 debug((", '%c'", ch));
4023 debug((", $%02x", ch));
4025 if (keys_unicode[0])
4026 debug((", KB0=%04x", keys_unicode[0]));
4027 if (keys_unicode[1])
4028 debug((", KB1=%04x", keys_unicode[1]));
4029 if (keys_unicode[2])
4030 debug((", KB2=%04x", keys_unicode[2]));
4032 if ((keystate[VK_SHIFT] & 0x80) != 0)
4034 if ((keystate[VK_CONTROL] & 0x80) != 0)
4036 if ((HIWORD(lParam) & KF_EXTENDED))
4038 if ((HIWORD(lParam) & KF_UP))
4042 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
4043 else if ((HIWORD(lParam) & KF_UP))
4044 oldstate[wParam & 0xFF] ^= 0x80;
4046 oldstate[wParam & 0xFF] ^= 0x81;
4048 for (ch = 0; ch < 256; ch++)
4049 if (oldstate[ch] != keystate[ch])
4050 debug((", M%02x=%02x", ch, keystate[ch]));
4052 memcpy(oldstate, keystate, sizeof(oldstate));
4056 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
4057 keystate[VK_RMENU] = keystate[VK_MENU];
4061 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
4062 if ((funky_type == FUNKY_VT400 ||
4063 (funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
4065 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
4067 wParam = VK_EXECUTE;
4069 /* UnToggle NUMLock */
4070 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
4071 keystate[VK_NUMLOCK] ^= 1;
4074 /* And write back the 'adjusted' state */
4075 SetKeyboardState(keystate);
4078 /* Disable Auto repeat if required */
4079 if (term->repeat_off &&
4080 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
4083 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
4086 key_down = ((HIWORD(lParam) & KF_UP) == 0);
4088 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
4089 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
4091 keystate[VK_MENU] = 0;
4093 keystate[VK_RMENU] = 0x80;
4098 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
4099 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
4100 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
4102 /* Note if AltGr was pressed and if it was used as a compose key */
4103 if (!compose_state) {
4104 compose_keycode = 0x100;
4105 if (conf_get_int(conf, CONF_compose_key)) {
4106 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
4107 compose_keycode = wParam;
4109 if (wParam == VK_APPS)
4110 compose_keycode = wParam;
4113 if (wParam == compose_keycode) {
4114 if (compose_state == 0
4115 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
4117 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
4121 } else if (compose_state == 1 && wParam != VK_CONTROL)
4124 if (compose_state > 1 && left_alt)
4127 /* Sanitize the number pad if not using a PC NumPad */
4128 if (left_alt || (term->app_keypad_keys && !no_applic_k
4129 && funky_type != FUNKY_XTERM)
4130 || funky_type == FUNKY_VT400 || nethack_keypad || compose_state) {
4131 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
4135 nParam = VK_NUMPAD0;
4138 nParam = VK_NUMPAD1;
4141 nParam = VK_NUMPAD2;
4144 nParam = VK_NUMPAD3;
4147 nParam = VK_NUMPAD4;
4150 nParam = VK_NUMPAD5;
4153 nParam = VK_NUMPAD6;
4156 nParam = VK_NUMPAD7;
4159 nParam = VK_NUMPAD8;
4162 nParam = VK_NUMPAD9;
4165 nParam = VK_DECIMAL;
4169 if (keystate[VK_NUMLOCK] & 1)
4176 /* If a key is pressed and AltGr is not active */
4177 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
4178 /* Okay, prepare for most alts then ... */
4182 /* Lets see if it's a pattern we know all about ... */
4183 if (wParam == VK_PRIOR && shift_state == 1) {
4184 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
4187 if (wParam == VK_PRIOR && shift_state == 2) {
4188 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
4191 if (wParam == VK_NEXT && shift_state == 1) {
4192 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
4195 if (wParam == VK_NEXT && shift_state == 2) {
4196 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
4199 if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) {
4200 term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1));
4203 if (wParam == VK_INSERT && shift_state == 1) {
4204 request_paste(NULL);
4207 if (left_alt && wParam == VK_F4 && conf_get_int(conf, CONF_alt_f4)) {
4210 if (left_alt && wParam == VK_SPACE && conf_get_int(conf,
4212 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
4215 if (left_alt && wParam == VK_RETURN &&
4216 conf_get_int(conf, CONF_fullscreenonaltenter) &&
4217 (conf_get_int(conf, CONF_resize_action) != RESIZE_DISABLED)) {
4218 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
4222 /* Control-Numlock for app-keypad mode switch */
4223 if (wParam == VK_PAUSE && shift_state == 2) {
4224 term->app_keypad_keys ^= 1;
4228 /* Nethack keypad */
4229 if (nethack_keypad && !left_alt) {
4232 *p++ = "bB\002\002"[shift_state & 3];
4235 *p++ = "jJ\012\012"[shift_state & 3];
4238 *p++ = "nN\016\016"[shift_state & 3];
4241 *p++ = "hH\010\010"[shift_state & 3];
4244 *p++ = shift_state ? '.' : '.';
4247 *p++ = "lL\014\014"[shift_state & 3];
4250 *p++ = "yY\031\031"[shift_state & 3];
4253 *p++ = "kK\013\013"[shift_state & 3];
4256 *p++ = "uU\025\025"[shift_state & 3];
4261 /* Application Keypad */
4265 if (funky_type == FUNKY_VT400 ||
4266 (funky_type <= FUNKY_LINUX &&
4267 term->app_keypad_keys && !no_applic_k)) switch (wParam) {
4281 if (term->app_keypad_keys && !no_applic_k)
4318 if (funky_type == FUNKY_XTERM) {
4323 } else if (shift_state)
4330 if (funky_type == FUNKY_XTERM)
4334 if (funky_type == FUNKY_XTERM)
4338 if (funky_type == FUNKY_XTERM)
4343 if (HIWORD(lParam) & KF_EXTENDED)
4348 if (term->vt52_mode) {
4349 if (xkey >= 'P' && xkey <= 'S')
4350 p += sprintf((char *) p, "\x1B%c", xkey);
4352 p += sprintf((char *) p, "\x1B?%c", xkey);
4354 p += sprintf((char *) p, "\x1BO%c", xkey);
4359 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
4360 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x7F : 0x08);
4364 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
4365 /* We do the opposite of what is configured */
4366 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x08 : 0x7F);
4370 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
4376 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
4380 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
4384 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
4386 back->special(backhandle, TS_BRK);
4389 if (wParam == VK_PAUSE) { /* Break/Pause */
4394 /* Control-2 to Control-8 are special */
4395 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
4396 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
4399 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
4403 if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) {
4407 if (shift_state == 3 && wParam == 0xDE) {
4408 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
4411 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
4418 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
4419 * for integer decimal nn.)
4421 * We also deal with the weird ones here. Linux VCs replace F1
4422 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
4423 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
4429 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
4432 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
4435 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
4438 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
4441 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
4444 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
4447 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
4450 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
4453 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
4456 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
4489 if ((shift_state&2) == 0) switch (wParam) {
4509 /* Reorder edit keys to physical order */
4510 if (funky_type == FUNKY_VT400 && code <= 6)
4511 code = "\0\2\1\4\5\3\6"[code];
4513 if (term->vt52_mode && code > 0 && code <= 6) {
4514 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4518 if (funky_type == FUNKY_SCO && code >= 11 && code <= 34) {
4519 /* SCO function keys */
4520 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4523 case VK_F1: index = 0; break;
4524 case VK_F2: index = 1; break;
4525 case VK_F3: index = 2; break;
4526 case VK_F4: index = 3; break;
4527 case VK_F5: index = 4; break;
4528 case VK_F6: index = 5; break;
4529 case VK_F7: index = 6; break;
4530 case VK_F8: index = 7; break;
4531 case VK_F9: index = 8; break;
4532 case VK_F10: index = 9; break;
4533 case VK_F11: index = 10; break;
4534 case VK_F12: index = 11; break;
4536 if (keystate[VK_SHIFT] & 0x80) index += 12;
4537 if (keystate[VK_CONTROL] & 0x80) index += 24;
4538 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4541 if (funky_type == FUNKY_SCO && /* SCO small keypad */
4542 code >= 1 && code <= 6) {
4543 char codes[] = "HL.FIG";
4547 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4551 if ((term->vt52_mode || funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4557 if (term->vt52_mode)
4558 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4561 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4564 if (funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4565 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4568 if (funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4569 if (term->vt52_mode)
4570 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4572 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4575 if ((code == 1 || code == 4) &&
4576 conf_get_int(conf, CONF_rxvt_homeend)) {
4577 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4581 p += sprintf((char *) p, "\x1B[%d~", code);
4586 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4587 * some reason seems to send VK_CLEAR to Windows...).
4609 p += format_arrow_key(p, term, xkey, shift_state);
4615 * Finally, deal with Return ourselves. (Win95 seems to
4616 * foul it up when Alt is pressed, for some reason.)
4618 if (wParam == VK_RETURN) { /* Return */
4624 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4625 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4630 /* Okay we've done everything interesting; let windows deal with
4631 * the boring stuff */
4635 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4636 if(keystate[VK_CAPITAL] != 0 &&
4637 conf_get_int(conf, CONF_xlat_capslockcyr)) {
4639 keystate[VK_CAPITAL] = 0;
4642 /* XXX how do we know what the max size of the keys array should
4643 * be is? There's indication on MS' website of an Inquire/InquireEx
4644 * functioning returning a KBINFO structure which tells us. */
4645 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT && p_ToUnicodeEx) {
4646 r = p_ToUnicodeEx(wParam, scan, keystate, keys_unicode,
4647 lenof(keys_unicode), 0, kbd_layout);
4649 /* XXX 'keys' parameter is declared in MSDN documentation as
4651 * The experience of a French user indicates that on
4652 * Win98, WORD[] should be passed in, but on Win2K, it should
4653 * be BYTE[]. German WinXP and my Win2K with "US International"
4654 * driver corroborate this.
4655 * Experimentally I've conditionalised the behaviour on the
4656 * Win9x/NT split, but I suspect it's worse than that.
4657 * See wishlist item `win-dead-keys' for more horrible detail
4658 * and speculations. */
4660 static WORD keys[3];
4661 static BYTE keysb[3];
4662 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4664 for (i = 0; i < r; i++) {
4665 keysb[i] = (BYTE)keys[i];
4667 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)keysb, r,
4668 keys_unicode, lenof(keys_unicode));
4671 #ifdef SHOW_TOASCII_RESULT
4672 if (r == 1 && !key_down) {
4674 if (in_utf(term) || ucsdata.dbcs_screenfont)
4675 debug((", (U+%04x)", alt_sum));
4677 debug((", LCH(%d)", alt_sum));
4679 debug((", ACH(%d)", keys_unicode[0]));
4684 for (r1 = 0; r1 < r; r1++) {
4685 debug(("%s%d", r1 ? "," : "", keys_unicode[r1]));
4694 for (i = 0; i < r; i++) {
4695 wchar_t wch = keys_unicode[i];
4697 if (compose_state == 2 && wch >= ' ' && wch < 0x80) {
4702 if (compose_state == 3 && wch >= ' ' && wch < 0x80) {
4706 if ((nc = check_compose(compose_char, wch)) == -1) {
4707 MessageBeep(MB_ICONHAND);
4711 term_seen_key_event(term);
4713 luni_send(ldisc, &keybuf, 1, 1);
4721 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4723 term_seen_key_event(term);
4725 luni_send(ldisc, &keybuf, 1, 1);
4727 char ch = (char) alt_sum;
4729 * We need not bother about stdin
4730 * backlogs here, because in GUI PuTTY
4731 * we can't do anything about it
4732 * anyway; there's no means of asking
4733 * Windows to hold off on KEYDOWN
4734 * messages. We _have_ to buffer
4735 * everything we're sent.
4737 term_seen_key_event(term);
4739 ldisc_send(ldisc, &ch, 1, 1);
4743 term_seen_key_event(term);
4745 luni_send(ldisc, &wch, 1, 1);
4748 if(capsOn && wch < 0x80) {
4751 cbuf[1] = xlat_uskbd2cyrllic(wch);
4752 term_seen_key_event(term);
4754 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4759 term_seen_key_event(term);
4761 luni_send(ldisc, cbuf +!left_alt, 1+!!left_alt, 1);
4767 /* This is so the ALT-Numpad and dead keys work correctly. */
4768 keys_unicode[0] = 0;
4772 /* If we're definitly not building up an ALT-54321 then clear it */
4774 keys_unicode[0] = 0;
4775 /* If we will be using alt_sum fix the 256s */
4776 else if (keys_unicode[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4777 keys_unicode[0] = 10;
4781 * ALT alone may or may not want to bring up the System menu.
4782 * If it's not meant to, we return 0 on presses or releases of
4783 * ALT, to show that we've swallowed the keystroke. Otherwise
4784 * we return -1, which means Windows will give the keystroke
4785 * its default handling (i.e. bring up the System menu).
4787 if (wParam == VK_MENU && !conf_get_int(conf, CONF_alt_only))
4793 void set_title(void *frontend, char *title)
4796 window_name = snewn(1 + strlen(title), char);
4797 strcpy(window_name, title);
4798 if (conf_get_int(conf, CONF_win_name_always) || !IsIconic(hwnd))
4799 SetWindowText(hwnd, title);
4802 void set_icon(void *frontend, char *title)
4805 icon_name = snewn(1 + strlen(title), char);
4806 strcpy(icon_name, title);
4807 if (!conf_get_int(conf, CONF_win_name_always) && IsIconic(hwnd))
4808 SetWindowText(hwnd, title);
4811 void set_sbar(void *frontend, int total, int start, int page)
4815 if (!conf_get_int(conf, is_full_screen() ?
4816 CONF_scrollbar_in_fullscreen : CONF_scrollbar))
4819 si.cbSize = sizeof(si);
4820 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4822 si.nMax = total - 1;
4826 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4829 Context get_ctx(void *frontend)
4835 SelectPalette(hdc, pal, FALSE);
4841 void free_ctx(Context ctx)
4843 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4844 ReleaseDC(hwnd, ctx);
4847 static void real_palette_set(int n, int r, int g, int b)
4850 logpal->palPalEntry[n].peRed = r;
4851 logpal->palPalEntry[n].peGreen = g;
4852 logpal->palPalEntry[n].peBlue = b;
4853 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4854 colours[n] = PALETTERGB(r, g, b);
4855 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4857 colours[n] = RGB(r, g, b);
4860 void palette_set(void *frontend, int n, int r, int g, int b)
4864 if (n >= NALLCOLOURS)
4866 real_palette_set(n, r, g, b);
4868 HDC hdc = get_ctx(frontend);
4869 UnrealizeObject(pal);
4870 RealizePalette(hdc);
4873 if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))
4874 /* If Default Background changes, we need to ensure any
4875 * space between the text area and the window border is
4877 InvalidateRect(hwnd, NULL, TRUE);
4881 void palette_reset(void *frontend)
4886 for (i = 0; i < NALLCOLOURS; i++) {
4888 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4889 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4890 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4891 logpal->palPalEntry[i].peFlags = 0;
4892 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4893 defpal[i].rgbtGreen,
4894 defpal[i].rgbtBlue);
4896 colours[i] = RGB(defpal[i].rgbtRed,
4897 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4902 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4903 hdc = get_ctx(frontend);
4904 RealizePalette(hdc);
4907 /* Default Background may have changed. Ensure any space between
4908 * text area and window border is redrawn. */
4909 InvalidateRect(hwnd, NULL, TRUE);
4913 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4918 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4921 lock = GlobalLock(clipdata);
4924 memcpy(lock, data, len);
4925 ((unsigned char *) lock)[len] = 0;
4926 GlobalUnlock(clipdata);
4929 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4931 if (OpenClipboard(hwnd)) {
4933 SetClipboardData(CF_TEXT, clipdata);
4936 GlobalFree(clipdata);
4939 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4943 * Note: unlike write_aclip() this will not append a nul.
4945 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
4947 HGLOBAL clipdata, clipdata2, clipdata3;
4949 void *lock, *lock2, *lock3;
4951 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4953 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4954 len * sizeof(wchar_t));
4955 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4957 if (!clipdata || !clipdata2) {
4959 GlobalFree(clipdata);
4961 GlobalFree(clipdata2);
4964 if (!(lock = GlobalLock(clipdata))) {
4965 GlobalFree(clipdata);
4966 GlobalFree(clipdata2);
4969 if (!(lock2 = GlobalLock(clipdata2))) {
4970 GlobalUnlock(clipdata);
4971 GlobalFree(clipdata);
4972 GlobalFree(clipdata2);
4976 memcpy(lock, data, len * sizeof(wchar_t));
4977 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4979 if (conf_get_int(conf, CONF_rtf_paste)) {
4980 wchar_t unitab[256];
4982 unsigned char *tdata = (unsigned char *)lock2;
4983 wchar_t *udata = (wchar_t *)lock;
4984 int rtflen = 0, uindex = 0, tindex = 0;
4986 int multilen, blen, alen, totallen, i;
4987 char before[16], after[4];
4988 int fgcolour, lastfgcolour = 0;
4989 int bgcolour, lastbgcolour = 0;
4990 int attrBold, lastAttrBold = 0;
4991 int attrUnder, lastAttrUnder = 0;
4992 int palette[NALLCOLOURS];
4994 FontSpec *font = conf_get_fontspec(conf, CONF_font);
4996 get_unitab(CP_ACP, unitab, 0);
4998 rtfsize = 100 + strlen(font->name);
4999 rtf = snewn(rtfsize, char);
5000 rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
5001 font->name, font->height*2);
5004 * Add colour palette
5005 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
5009 * First - Determine all colours in use
5010 * o Foregound and background colours share the same palette
5013 memset(palette, 0, sizeof(palette));
5014 for (i = 0; i < (len-1); i++) {
5015 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5016 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5018 if (attr[i] & ATTR_REVERSE) {
5019 int tmpcolour = fgcolour; /* Swap foreground and background */
5020 fgcolour = bgcolour;
5021 bgcolour = tmpcolour;
5024 if (bold_colours && (attr[i] & ATTR_BOLD)) {
5025 if (fgcolour < 8) /* ANSI colours */
5027 else if (fgcolour >= 256) /* Default colours */
5031 if (attr[i] & ATTR_BLINK) {
5032 if (bgcolour < 8) /* ANSI colours */
5034 else if (bgcolour >= 256) /* Default colours */
5038 palette[fgcolour]++;
5039 palette[bgcolour]++;
5043 * Next - Create a reduced palette
5046 for (i = 0; i < NALLCOLOURS; i++) {
5047 if (palette[i] != 0)
5048 palette[i] = ++numcolours;
5052 * Finally - Write the colour table
5054 rtf = sresize(rtf, rtfsize + (numcolours * 25), char);
5055 strcat(rtf, "{\\colortbl ;");
5056 rtflen = strlen(rtf);
5058 for (i = 0; i < NALLCOLOURS; i++) {
5059 if (palette[i] != 0) {
5060 rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);
5063 strcpy(&rtf[rtflen], "}");
5068 * We want to construct a piece of RTF that specifies the
5069 * same Unicode text. To do this we will read back in
5070 * parallel from the Unicode data in `udata' and the
5071 * non-Unicode data in `tdata'. For each character in
5072 * `tdata' which becomes the right thing in `udata' when
5073 * looked up in `unitab', we just copy straight over from
5074 * tdata. For each one that doesn't, we must WCToMB it
5075 * individually and produce a \u escape sequence.
5077 * It would probably be more robust to just bite the bullet
5078 * and WCToMB each individual Unicode character one by one,
5079 * then MBToWC each one back to see if it was an accurate
5080 * translation; but that strikes me as a horrifying number
5081 * of Windows API calls so I want to see if this faster way
5082 * will work. If it screws up badly we can always revert to
5083 * the simple and slow way.
5085 while (tindex < len2 && uindex < len &&
5086 tdata[tindex] && udata[uindex]) {
5087 if (tindex + 1 < len2 &&
5088 tdata[tindex] == '\r' &&
5089 tdata[tindex+1] == '\n') {
5095 * Set text attributes
5098 if (rtfsize < rtflen + 64) {
5099 rtfsize = rtflen + 512;
5100 rtf = sresize(rtf, rtfsize, char);
5104 * Determine foreground and background colours
5106 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5107 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5109 if (attr[tindex] & ATTR_REVERSE) {
5110 int tmpcolour = fgcolour; /* Swap foreground and background */
5111 fgcolour = bgcolour;
5112 bgcolour = tmpcolour;
5115 if (bold_colours && (attr[tindex] & ATTR_BOLD)) {
5116 if (fgcolour < 8) /* ANSI colours */
5118 else if (fgcolour >= 256) /* Default colours */
5122 if (attr[tindex] & ATTR_BLINK) {
5123 if (bgcolour < 8) /* ANSI colours */
5125 else if (bgcolour >= 256) /* Default colours */
5130 * Collect other attributes
5132 if (bold_font_mode != BOLD_NONE)
5133 attrBold = attr[tindex] & ATTR_BOLD;
5137 attrUnder = attr[tindex] & ATTR_UNDER;
5141 * o If video isn't reversed, ignore colour attributes for default foregound
5143 * o Special case where bolded text is displayed using the default foregound
5144 * and background colours - force to bolded RTF.
5146 if (!(attr[tindex] & ATTR_REVERSE)) {
5147 if (bgcolour >= 256) /* Default color */
5148 bgcolour = -1; /* No coloring */
5150 if (fgcolour >= 256) { /* Default colour */
5151 if (bold_colours && (fgcolour & 1) && bgcolour == -1)
5152 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
5154 fgcolour = -1; /* No coloring */
5159 * Write RTF text attributes
5161 if (lastfgcolour != fgcolour) {
5162 lastfgcolour = fgcolour;
5163 rtflen += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
5166 if (lastbgcolour != bgcolour) {
5167 lastbgcolour = bgcolour;
5168 rtflen += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
5171 if (lastAttrBold != attrBold) {
5172 lastAttrBold = attrBold;
5173 rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
5176 if (lastAttrUnder != attrUnder) {
5177 lastAttrUnder = attrUnder;
5178 rtflen += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
5182 if (unitab[tdata[tindex]] == udata[uindex]) {
5188 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
5189 NULL, 0, NULL, NULL);
5190 if (multilen != 1) {
5191 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
5193 alen = 1; strcpy(after, "}");
5195 blen = sprintf(before, "\\u%d", udata[uindex]);
5196 alen = 0; after[0] = '\0';
5199 assert(tindex + multilen <= len2);
5200 totallen = blen + alen;
5201 for (i = 0; i < multilen; i++) {
5202 if (tdata[tindex+i] == '\\' ||
5203 tdata[tindex+i] == '{' ||
5204 tdata[tindex+i] == '}')
5206 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
5207 totallen += 6; /* \par\r\n */
5208 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
5214 if (rtfsize < rtflen + totallen + 3) {
5215 rtfsize = rtflen + totallen + 512;
5216 rtf = sresize(rtf, rtfsize, char);
5219 strcpy(rtf + rtflen, before); rtflen += blen;
5220 for (i = 0; i < multilen; i++) {
5221 if (tdata[tindex+i] == '\\' ||
5222 tdata[tindex+i] == '{' ||
5223 tdata[tindex+i] == '}') {
5224 rtf[rtflen++] = '\\';
5225 rtf[rtflen++] = tdata[tindex+i];
5226 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
5227 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
5228 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
5229 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
5231 rtf[rtflen++] = tdata[tindex+i];
5234 strcpy(rtf + rtflen, after); rtflen += alen;
5240 rtf[rtflen++] = '}'; /* Terminate RTF stream */
5241 rtf[rtflen++] = '\0';
5242 rtf[rtflen++] = '\0';
5244 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
5245 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
5246 memcpy(lock3, rtf, rtflen);
5247 GlobalUnlock(clipdata3);
5253 GlobalUnlock(clipdata);
5254 GlobalUnlock(clipdata2);
5257 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
5259 if (OpenClipboard(hwnd)) {
5261 SetClipboardData(CF_UNICODETEXT, clipdata);
5262 SetClipboardData(CF_TEXT, clipdata2);
5264 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
5267 GlobalFree(clipdata);
5268 GlobalFree(clipdata2);
5272 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
5275 static DWORD WINAPI clipboard_read_threadfunc(void *param)
5277 HWND hwnd = (HWND)param;
5280 if (OpenClipboard(NULL)) {
5281 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
5282 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)1, (LPARAM)clipdata);
5283 } else if ((clipdata = GetClipboardData(CF_TEXT))) {
5284 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)0, (LPARAM)clipdata);
5292 static int process_clipdata(HGLOBAL clipdata, int unicode)
5294 sfree(clipboard_contents);
5295 clipboard_contents = NULL;
5296 clipboard_length = 0;
5299 wchar_t *p = GlobalLock(clipdata);
5303 /* Unwilling to rely on Windows having wcslen() */
5304 for (p2 = p; *p2; p2++);
5305 clipboard_length = p2 - p;
5306 clipboard_contents = snewn(clipboard_length + 1, wchar_t);
5307 memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t));
5308 clipboard_contents[clipboard_length] = L'\0';
5312 char *s = GlobalLock(clipdata);
5316 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
5317 clipboard_contents = snewn(i, wchar_t);
5318 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1,
5319 clipboard_contents, i);
5320 clipboard_length = i - 1;
5321 clipboard_contents[clipboard_length] = L'\0';
5329 void request_paste(void *frontend)
5332 * I always thought pasting was synchronous in Windows; the
5333 * clipboard access functions certainly _look_ synchronous,
5334 * unlike the X ones. But in fact it seems that in some
5335 * situations the contents of the clipboard might not be
5336 * immediately available, and the clipboard-reading functions
5337 * may block. This leads to trouble if the application
5338 * delivering the clipboard data has to get hold of it by -
5339 * for example - talking over a network connection which is
5340 * forwarded through this very PuTTY.
5342 * Hence, we spawn a subthread to read the clipboard, and do
5343 * our paste when it's finished. The thread will send a
5344 * message back to our main window when it terminates, and
5345 * that tells us it's OK to paste.
5347 DWORD in_threadid; /* required for Win9x */
5348 CreateThread(NULL, 0, clipboard_read_threadfunc,
5349 hwnd, 0, &in_threadid);
5352 void get_clip(void *frontend, wchar_t **p, int *len)
5355 *p = clipboard_contents;
5356 *len = clipboard_length;
5362 * Move `lines' lines from position `from' to position `to' in the
5365 void optimised_move(void *frontend, int to, int from, int lines)
5370 min = (to < from ? to : from);
5371 max = to + from - min;
5373 r.left = offset_width;
5374 r.right = offset_width + term->cols * font_width;
5375 r.top = offset_height + min * font_height;
5376 r.bottom = offset_height + (max + lines) * font_height;
5377 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
5382 * Print a message box and perform a fatal exit.
5384 void fatalbox(const char *fmt, ...)
5387 char *stuff, morestuff[100];
5390 stuff = dupvprintf(fmt, ap);
5392 sprintf(morestuff, "%.70s Fatal Error", appname);
5393 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5399 * Print a modal (Really Bad) message box and perform a fatal exit.
5401 void modalfatalbox(const char *fmt, ...)
5404 char *stuff, morestuff[100];
5407 stuff = dupvprintf(fmt, ap);
5409 sprintf(morestuff, "%.70s Fatal Error", appname);
5410 MessageBox(hwnd, stuff, morestuff,
5411 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
5417 * Print a message box and don't close the connection.
5419 void nonfatal(const char *fmt, ...)
5422 char *stuff, morestuff[100];
5425 stuff = dupvprintf(fmt, ap);
5427 sprintf(morestuff, "%.70s Error", appname);
5428 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5432 static BOOL flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout)
5434 if (p_FlashWindowEx) {
5436 fi.cbSize = sizeof(fi);
5438 fi.dwFlags = dwFlags;
5440 fi.dwTimeout = dwTimeout;
5441 return (*p_FlashWindowEx)(&fi);
5444 return FALSE; /* shrug */
5447 static void flash_window(int mode);
5448 static long next_flash;
5449 static int flashing = 0;
5452 * Timer for platforms where we must maintain window flashing manually
5455 static void flash_window_timer(void *ctx, unsigned long now)
5457 if (flashing && now == next_flash) {
5463 * Manage window caption / taskbar flashing, if enabled.
5464 * 0 = stop, 1 = maintain, 2 = start
5466 static void flash_window(int mode)
5468 int beep_ind = conf_get_int(conf, CONF_beep_ind);
5469 if ((mode == 0) || (beep_ind == B_IND_DISABLED)) {
5473 if (p_FlashWindowEx)
5474 flash_window_ex(FLASHW_STOP, 0, 0);
5476 FlashWindow(hwnd, FALSE);
5479 } else if (mode == 2) {
5483 if (p_FlashWindowEx) {
5484 /* For so-called "steady" mode, we use uCount=2, which
5485 * seems to be the traditional number of flashes used
5486 * by user notifications (e.g., by Explorer).
5487 * uCount=0 appears to enable continuous flashing, per
5488 * "flashing" mode, although I haven't seen this
5490 flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
5491 (beep_ind == B_IND_FLASH ? 0 : 2),
5492 0 /* system cursor blink rate */);
5493 /* No need to schedule timer */
5495 FlashWindow(hwnd, TRUE);
5496 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5500 } else if ((mode == 1) && (beep_ind == B_IND_FLASH)) {
5502 if (flashing && !p_FlashWindowEx) {
5503 FlashWindow(hwnd, TRUE); /* toggle */
5504 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5512 void do_beep(void *frontend, int mode)
5514 if (mode == BELL_DEFAULT) {
5516 * For MessageBeep style bells, we want to be careful of
5517 * timing, because they don't have the nice property of
5518 * PlaySound bells that each one cancels the previous
5519 * active one. So we limit the rate to one per 50ms or so.
5521 static long lastbeep = 0;
5524 beepdiff = GetTickCount() - lastbeep;
5525 if (beepdiff >= 0 && beepdiff < 50)
5529 * The above MessageBeep call takes time, so we record the
5530 * time _after_ it finishes rather than before it starts.
5532 lastbeep = GetTickCount();
5533 } else if (mode == BELL_WAVEFILE) {
5534 Filename *bell_wavefile = conf_get_filename(conf, CONF_bell_wavefile);
5535 if (!PlaySound(bell_wavefile->path, NULL,
5536 SND_ASYNC | SND_FILENAME)) {
5537 char buf[sizeof(bell_wavefile->path) + 80];
5539 sprintf(buf, "Unable to play sound file\n%s\n"
5540 "Using default sound instead", bell_wavefile->path);
5541 sprintf(otherbuf, "%.70s Sound Error", appname);
5542 MessageBox(hwnd, buf, otherbuf,
5543 MB_OK | MB_ICONEXCLAMATION);
5544 conf_set_int(conf, CONF_beep, BELL_DEFAULT);
5546 } else if (mode == BELL_PCSPEAKER) {
5547 static long lastbeep = 0;
5550 beepdiff = GetTickCount() - lastbeep;
5551 if (beepdiff >= 0 && beepdiff < 50)
5555 * We must beep in different ways depending on whether this
5556 * is a 95-series or NT-series OS.
5558 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
5562 lastbeep = GetTickCount();
5564 /* Otherwise, either visual bell or disabled; do nothing here */
5565 if (!term->has_focus) {
5566 flash_window(2); /* start */
5571 * Minimise or restore the window in response to a server-side
5574 void set_iconic(void *frontend, int iconic)
5576 if (IsIconic(hwnd)) {
5578 ShowWindow(hwnd, SW_RESTORE);
5581 ShowWindow(hwnd, SW_MINIMIZE);
5586 * Move the window in response to a server-side request.
5588 void move_window(void *frontend, int x, int y)
5590 int resize_action = conf_get_int(conf, CONF_resize_action);
5591 if (resize_action == RESIZE_DISABLED ||
5592 resize_action == RESIZE_FONT ||
5596 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5600 * Move the window to the top or bottom of the z-order in response
5601 * to a server-side request.
5603 void set_zorder(void *frontend, int top)
5605 if (conf_get_int(conf, CONF_alwaysontop))
5606 return; /* ignore */
5607 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5608 SWP_NOMOVE | SWP_NOSIZE);
5612 * Refresh the window in response to a server-side request.
5614 void refresh_window(void *frontend)
5616 InvalidateRect(hwnd, NULL, TRUE);
5620 * Maximise or restore the window in response to a server-side
5623 void set_zoomed(void *frontend, int zoomed)
5625 if (IsZoomed(hwnd)) {
5627 ShowWindow(hwnd, SW_RESTORE);
5630 ShowWindow(hwnd, SW_MAXIMIZE);
5635 * Report whether the window is iconic, for terminal reports.
5637 int is_iconic(void *frontend)
5639 return IsIconic(hwnd);
5643 * Report the window's position, for terminal reports.
5645 void get_window_pos(void *frontend, int *x, int *y)
5648 GetWindowRect(hwnd, &r);
5654 * Report the window's pixel size, for terminal reports.
5656 void get_window_pixels(void *frontend, int *x, int *y)
5659 GetWindowRect(hwnd, &r);
5660 *x = r.right - r.left;
5661 *y = r.bottom - r.top;
5665 * Return the window or icon title.
5667 char *get_window_title(void *frontend, int icon)
5669 return icon ? icon_name : window_name;
5673 * See if we're in full-screen mode.
5675 static int is_full_screen()
5677 if (!IsZoomed(hwnd))
5679 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
5684 /* Get the rect/size of a full screen window using the nearest available
5685 * monitor in multimon systems; default to something sensible if only
5686 * one monitor is present. */
5687 static int get_fullscreen_rect(RECT * ss)
5689 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
5692 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
5693 mi.cbSize = sizeof(mi);
5694 GetMonitorInfo(mon, &mi);
5696 /* structure copy */
5700 /* could also use code like this:
5701 ss->left = ss->top = 0;
5702 ss->right = GetSystemMetrics(SM_CXSCREEN);
5703 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5705 return GetClientRect(GetDesktopWindow(), ss);
5711 * Go full-screen. This should only be called when we are already
5714 static void make_full_screen()
5719 assert(IsZoomed(hwnd));
5721 if (is_full_screen())
5724 /* Remove the window furniture. */
5725 style = GetWindowLongPtr(hwnd, GWL_STYLE);
5726 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5727 if (conf_get_int(conf, CONF_scrollbar_in_fullscreen))
5728 style |= WS_VSCROLL;
5730 style &= ~WS_VSCROLL;
5731 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5733 /* Resize ourselves to exactly cover the nearest monitor. */
5734 get_fullscreen_rect(&ss);
5735 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5740 /* We may have changed size as a result */
5744 /* Tick the menu item in the System and context menus. */
5747 for (i = 0; i < lenof(popup_menus); i++)
5748 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED);
5753 * Clear the full-screen attributes.
5755 static void clear_full_screen()
5757 DWORD oldstyle, style;
5759 /* Reinstate the window furniture. */
5760 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
5761 style |= WS_CAPTION | WS_BORDER;
5762 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
5763 style &= ~WS_THICKFRAME;
5765 style |= WS_THICKFRAME;
5766 if (conf_get_int(conf, CONF_scrollbar))
5767 style |= WS_VSCROLL;
5769 style &= ~WS_VSCROLL;
5770 if (style != oldstyle) {
5771 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5772 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5773 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5777 /* Untick the menu item in the System and context menus. */
5780 for (i = 0; i < lenof(popup_menus); i++)
5781 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED);
5786 * Toggle full-screen mode.
5788 static void flip_full_screen()
5790 if (is_full_screen()) {
5791 ShowWindow(hwnd, SW_RESTORE);
5792 } else if (IsZoomed(hwnd)) {
5795 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5796 ShowWindow(hwnd, SW_MAXIMIZE);
5800 void frontend_keypress(void *handle)
5803 * Keypress termination in non-Close-On-Exit mode is not
5804 * currently supported in PuTTY proper, because the window
5805 * always has a perfectly good Close button anyway. So we do
5811 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5813 return term_data(term, is_stderr, data, len);
5816 int from_backend_untrusted(void *frontend, const char *data, int len)
5818 return term_data_untrusted(term, data, len);
5821 int from_backend_eof(void *frontend)
5823 return TRUE; /* do respond to incoming EOF with outgoing */
5826 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
5829 ret = cmdline_get_passwd_input(p, in, inlen);
5831 ret = term_get_userpass_input(term, p, in, inlen);
5835 void agent_schedule_callback(void (*callback)(void *, void *, int),
5836 void *callback_ctx, void *data, int len)
5838 struct agent_callback *c = snew(struct agent_callback);
5839 c->callback = callback;
5840 c->callback_ctx = callback_ctx;
5843 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);