2 * window.c - the PuTTY(tel) main program, which runs a PuTTY terminal
3 * emulator and backend in a window.
14 #define COMPILE_MULTIMON_STUBS
17 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
33 /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
34 * wParam are used by Windows, and should be masked off, so we shouldn't
35 * attempt to store information in them. Hence all these identifiers have
36 * the low 4 bits clear. Also, identifiers should < 0xF000. */
38 #define IDM_SHOWLOG 0x0010
39 #define IDM_NEWSESS 0x0020
40 #define IDM_DUPSESS 0x0030
41 #define IDM_RESTART 0x0040
42 #define IDM_RECONF 0x0050
43 #define IDM_CLRSB 0x0060
44 #define IDM_RESET 0x0070
45 #define IDM_HELP 0x0140
46 #define IDM_ABOUT 0x0150
47 #define IDM_SAVEDSESS 0x0160
48 #define IDM_COPYALL 0x0170
49 #define IDM_FULLSCREEN 0x0180
50 #define IDM_PASTE 0x0190
51 #define IDM_SPECIALSEP 0x0200
53 #define IDM_SPECIAL_MIN 0x0400
54 #define IDM_SPECIAL_MAX 0x0800
56 #define IDM_SAVED_MIN 0x1000
57 #define IDM_SAVED_MAX 0x5000
58 #define MENU_SAVED_STEP 16
59 /* Maximum number of sessions on saved-session submenu */
60 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
62 #define WM_IGNORE_CLIP (WM_APP + 2)
63 #define WM_FULLSCR_ON_MAX (WM_APP + 3)
64 #define WM_AGENT_CALLBACK (WM_APP + 4)
65 #define WM_GOT_CLIPDATA (WM_APP + 6)
67 /* Needed for Chinese support and apparently not always defined. */
69 #define VK_PROCESSKEY 0xE5
72 /* Mouse wheel support. */
74 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
77 #define WHEEL_DELTA 120
80 /* VK_PACKET, used to send Unicode characters in WM_KEYDOWNs */
82 #define VK_PACKET 0xE7
85 static Mouse_Button translate_button(Mouse_Button button);
86 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
87 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
88 unsigned char *output);
89 static void conftopalette(void);
90 static void systopalette(void);
91 static void init_palette(void);
92 static void init_fonts(int, int);
93 static void another_font(int);
94 static void deinit_fonts(void);
95 static void set_input_locale(HKL);
96 static void update_savedsess_menu(void);
97 static void init_winfuncs(void);
99 static int is_full_screen(void);
100 static void make_full_screen(void);
101 static void clear_full_screen(void);
102 static void flip_full_screen(void);
103 static int process_clipdata(HGLOBAL clipdata, int unicode);
105 /* Window layout information */
106 static void reset_window(int);
107 static int extra_width, extra_height;
108 static int font_width, font_height, font_dualwidth, font_varpitch;
109 static int offset_width, offset_height;
110 static int was_zoomed = 0;
111 static int prev_rows, prev_cols;
113 static void flash_window(int mode);
114 static void sys_cursor_update(void);
115 static int get_fullscreen_rect(RECT * ss);
117 static int caret_x = -1, caret_y = -1;
119 static int kbd_codepage;
122 static Backend *back;
123 static void *backhandle;
125 static struct unicode_data ucsdata;
126 static int session_closed;
127 static int reconfiguring = FALSE;
129 static const struct telnet_special *specials = NULL;
130 static HMENU specials_menu = NULL;
131 static int n_specials = 0;
133 static wchar_t *clipboard_contents;
134 static size_t clipboard_length;
136 #define TIMING_TIMER_ID 1234
137 static long timing_next_time;
142 enum { SYSMENU, CTXMENU };
143 static HMENU savedsess_menu;
145 struct wm_netevent_params {
146 /* Used to pass data to wm_netevent_callback */
151 Conf *conf; /* exported to windlg.c */
153 static void conf_cache_data(void);
157 static struct sesslist sesslist; /* for saved-session menu */
159 struct agent_callback {
160 void (*callback)(void *, void *, int);
166 #define FONT_NORMAL 0
168 #define FONT_UNDERLINE 2
169 #define FONT_BOLDUND 3
170 #define FONT_WIDE 0x04
171 #define FONT_HIGH 0x08
172 #define FONT_NARROW 0x10
174 #define FONT_OEM 0x20
175 #define FONT_OEMBOLD 0x21
176 #define FONT_OEMUND 0x22
177 #define FONT_OEMBOLDUND 0x23
179 #define FONT_MAXNO 0x40
181 static HFONT fonts[FONT_MAXNO];
182 static LOGFONT lfont;
183 static int fontflag[FONT_MAXNO];
185 BOLD_NONE, BOLD_SHADOW, BOLD_FONT
187 static int bold_colours;
193 #define NCFGCOLOURS 22
194 #define NEXTCOLOURS 240
195 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
196 static COLORREF colours[NALLCOLOURS];
198 static LPLOGPALETTE logpal;
199 static RGBTRIPLE defpal[NALLCOLOURS];
201 static HBITMAP caretbm;
203 static int dbltime, lasttime, lastact;
204 static Mouse_Button lastbtn;
206 /* this allows xterm-style mouse handling. */
207 static int send_raw_mouse = 0;
208 static int wheel_accumulator = 0;
210 static int busy_status = BUSY_NOT;
212 static char *window_name, *icon_name;
214 static int compose_state = 0;
216 static UINT wm_mousewheel = WM_MOUSEWHEEL;
218 #define IS_HIGH_VARSEL(wch1, wch2) \
219 ((wch1) == 0xDB40 && ((wch2) >= 0xDD00 && (wch2) <= 0xDDEF))
220 #define IS_LOW_VARSEL(wch) \
221 (((wch) >= 0x180B && (wch) <= 0x180D) || /* MONGOLIAN FREE VARIATION SELECTOR */ \
222 ((wch) >= 0xFE00 && (wch) <= 0xFE0F)) /* VARIATION SELECTOR 1-16 */
224 const int share_can_be_downstream = TRUE;
225 const int share_can_be_upstream = TRUE;
227 /* Dummy routine, only required in plink. */
228 void frontend_echoedit_update(void *frontend, int echo, int edit)
232 int frontend_is_utf8(void *frontend)
234 return ucsdata.line_codepage == CP_UTF8;
237 char *get_ttymode(void *frontend, const char *mode)
239 return term_get_ttymode(term, mode);
242 static void start_backend(void)
245 char msg[1024], *title;
250 * Select protocol. This is farmed out into a table in a
251 * separate file to enable an ssh-free variant.
253 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
255 char *str = dupprintf("%s Internal Error", appname);
256 MessageBox(NULL, "Unsupported protocol number found",
257 str, MB_OK | MB_ICONEXCLAMATION);
262 error = back->init(NULL, &backhandle, conf,
263 conf_get_str(conf, CONF_host),
264 conf_get_int(conf, CONF_port),
266 conf_get_int(conf, CONF_tcp_nodelay),
267 conf_get_int(conf, CONF_tcp_keepalives));
268 back->provide_logctx(backhandle, logctx);
270 char *str = dupprintf("%s Error", appname);
271 sprintf(msg, "Unable to open connection to\n"
272 "%.800s\n" "%s", conf_dest(conf), error);
273 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
277 window_name = icon_name = NULL;
278 title = conf_get_str(conf, CONF_wintitle);
280 sprintf(msg, "%s - %s", realhost, appname);
284 set_title(NULL, title);
285 set_icon(NULL, title);
288 * Connect the terminal to the backend for resize purposes.
290 term_provide_resize_fn(term, back->size, backhandle);
293 * Set up a line discipline.
295 ldisc = ldisc_create(conf, term, back, backhandle, NULL);
298 * Destroy the Restart Session menu item. (This will return
299 * failure if it's already absent, as it will be the very first
300 * time we call this function. We ignore that, because as long
301 * as the menu item ends up not being there, we don't care
302 * whether it was us who removed it or not!)
304 for (i = 0; i < lenof(popup_menus); i++) {
305 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
308 session_closed = FALSE;
311 static void close_session(void *ignored_context)
316 session_closed = TRUE;
317 sprintf(morestuff, "%.70s (inactive)", appname);
318 set_icon(NULL, morestuff);
319 set_title(NULL, morestuff);
326 back->free(backhandle);
329 term_provide_resize_fn(term, NULL, NULL);
330 update_specials_menu(NULL);
334 * Show the Restart Session menu item. Do a precautionary
335 * delete first to ensure we never end up with more than one.
337 for (i = 0; i < lenof(popup_menus); i++) {
338 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
339 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
340 IDM_RESTART, "&Restart Session");
344 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
348 int guess_width, guess_height;
352 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
356 InitCommonControls();
358 /* Ensure a Maximize setting in Explorer doesn't maximise the
364 char *str = dupprintf("%s Fatal Error", appname);
365 MessageBox(NULL, "Windows refuses to report a version",
366 str, MB_OK | MB_ICONEXCLAMATION);
372 * If we're running a version of Windows that doesn't support
373 * WM_MOUSEWHEEL, find out what message number we should be
376 if (osVersion.dwMajorVersion < 4 ||
377 (osVersion.dwMajorVersion == 4 &&
378 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
379 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
390 hr = CoInitialize(NULL);
391 if (hr != S_OK && hr != S_FALSE) {
392 char *str = dupprintf("%s Fatal Error", appname);
393 MessageBox(NULL, "Failed to initialize COM subsystem",
394 str, MB_OK | MB_ICONEXCLAMATION);
400 * Protect our process
403 #if !defined UNPROTECT && !defined NO_SECURITY
405 if (! setprocessacl(error)) {
406 char *message = dupprintf("Could not restrict process ACL: %s",
408 logevent(NULL, message);
415 * Process the command line.
420 /* By default, we bring up the config dialog, rather than launching
421 * a session. This gets set to TRUE if something happens to change
422 * that (e.g., a hostname is specified on the command-line). */
423 int allow_launch = FALSE;
425 default_protocol = be_default_protocol;
426 /* Find the appropriate default port. */
428 Backend *b = backend_from_proto(default_protocol);
429 default_port = 0; /* illegal */
431 default_port = b->default_port;
433 conf_set_int(conf, CONF_logtype, LGTYP_NONE);
435 do_defaults(NULL, conf);
440 * Process a couple of command-line options which are more
441 * easily dealt with before the line is broken up into words.
442 * These are the old-fashioned but convenient @sessionname and
443 * the internal-use-only &sharedmemoryhandle, neither of which
444 * are combined with anything else.
446 while (*p && isspace(*p))
450 * An initial @ means that the whole of the rest of the
451 * command line should be treated as the name of a saved
452 * session, with _no quoting or escaping_. This makes it a
453 * very convenient means of automated saved-session
454 * launching, via IDM_SAVEDSESS or Windows 7 jump lists.
457 while (i > 1 && isspace(p[i - 1]))
460 do_defaults(p + 1, conf);
461 if (!conf_launchable(conf) && !do_config()) {
464 allow_launch = TRUE; /* allow it to be launched directly */
465 } else if (*p == '&') {
467 * An initial & means we've been given a command line
468 * containing the hex value of a HANDLE for a file
469 * mapping object, which we must then interpret as a
475 if (sscanf(p + 1, "%p:%u", &filemap, &cpsize) == 2 &&
476 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
477 0, 0, cpsize)) != NULL) {
478 conf_deserialise(conf, cp, cpsize);
480 CloseHandle(filemap);
481 } else if (!do_config()) {
487 * Otherwise, break up the command line and deal with
493 split_into_argv(cmdline, &argc, &argv, NULL);
495 for (i = 0; i < argc; i++) {
499 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
502 cmdline_error("option \"%s\" requires an argument", p);
503 } else if (ret == 2) {
504 i++; /* skip next argument */
505 } else if (ret == 1) {
506 continue; /* nothing further needs doing */
507 } else if (!strcmp(p, "-cleanup") ||
508 !strcmp(p, "-cleanup-during-uninstall")) {
510 * `putty -cleanup'. Remove all registry
511 * entries associated with PuTTY, and also find
512 * and delete the random seed file.
515 /* Are we being invoked from an uninstaller? */
516 if (!strcmp(p, "-cleanup-during-uninstall")) {
517 s1 = dupprintf("Remove saved sessions and random seed file?\n"
519 "If you hit Yes, ALL Registry entries associated\n"
520 "with %s will be removed, as well as the\n"
521 "random seed file. THIS PROCESS WILL\n"
522 "DESTROY YOUR SAVED SESSIONS.\n"
523 "(This only affects the currently logged-in user.)\n"
525 "If you hit No, uninstallation will proceed, but\n"
526 "saved sessions etc will be left on the machine.",
528 s2 = dupprintf("%s Uninstallation", appname);
530 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
531 "associated with %s, and will also remove\n"
532 "the random seed file. (This only affects the\n"
533 "currently logged-in user.)\n"
535 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
536 "Are you really sure you want to continue?",
538 s2 = dupprintf("%s Warning", appname);
540 if (message_box(s1, s2,
541 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
542 HELPCTXID(option_cleanup)) == IDYES) {
548 } else if (!strcmp(p, "-pgpfp")) {
551 } else if (*p != '-') {
555 * If we already have a host name, treat
556 * this argument as a port number. NB we
557 * have to treat this as a saved -P
558 * argument, so that it will be deferred
559 * until it's a good moment to run it.
561 int ret = cmdline_process_param("-P", p, 1, conf);
563 } else if (!strncmp(q, "telnet:", 7)) {
565 * If the hostname starts with "telnet:",
566 * set the protocol to Telnet and process
567 * the string as a Telnet URL.
572 if (q[0] == '/' && q[1] == '/')
574 conf_set_int(conf, CONF_protocol, PROT_TELNET);
576 p += host_strcspn(p, ":/");
581 conf_set_int(conf, CONF_port, atoi(p));
583 conf_set_int(conf, CONF_port, -1);
584 conf_set_str(conf, CONF_host, q);
588 * Otherwise, treat this argument as a host
591 while (*p && !isspace(*p))
595 conf_set_str(conf, CONF_host, q);
599 cmdline_error("unknown option \"%s\"", p);
604 cmdline_run_saved(conf);
606 if (loaded_session || got_host)
609 if ((!allow_launch || !conf_launchable(conf)) && !do_config()) {
614 * Muck about with the hostname in various ways.
617 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
618 char *host = hostbuf;
622 * Trim leading whitespace.
624 host += strspn(host, " \t");
627 * See if host is of the form user@host, and separate
628 * out the username if so.
630 if (host[0] != '\0') {
631 char *atsign = strrchr(host, '@');
634 conf_set_str(conf, CONF_username, host);
640 * Trim a colon suffix off the hostname if it's there. In
641 * order to protect unbracketed IPv6 address literals
642 * against this treatment, we do not do this if there's
643 * _more_ than one colon.
646 char *c = host_strchr(host, ':');
649 char *d = host_strchr(c+1, ':');
656 * Remove any remaining whitespace.
661 if (*q != ' ' && *q != '\t')
667 conf_set_str(conf, CONF_host, hostbuf);
676 wndclass.lpfnWndProc = WndProc;
677 wndclass.cbClsExtra = 0;
678 wndclass.cbWndExtra = 0;
679 wndclass.hInstance = inst;
680 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
681 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
682 wndclass.hbrBackground = NULL;
683 wndclass.lpszMenuName = NULL;
684 wndclass.lpszClassName = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
686 RegisterClassW(&wndclass);
689 memset(&ucsdata, 0, sizeof(ucsdata));
696 * Guess some defaults for the window size. This all gets
697 * updated later, so we don't really care too much. However, we
698 * do want the font width/height guesses to correspond to a
699 * large font rather than a small one...
706 guess_width = extra_width + font_width * conf_get_int(conf, CONF_width);
707 guess_height = extra_height + font_height*conf_get_int(conf, CONF_height);
710 get_fullscreen_rect(&r);
711 if (guess_width > r.right - r.left)
712 guess_width = r.right - r.left;
713 if (guess_height > r.bottom - r.top)
714 guess_height = r.bottom - r.top;
718 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
720 wchar_t *uappname = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
721 if (!conf_get_int(conf, CONF_scrollbar))
722 winmode &= ~(WS_VSCROLL);
723 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
724 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
725 if (conf_get_int(conf, CONF_alwaysontop))
726 exwinmode |= WS_EX_TOPMOST;
727 if (conf_get_int(conf, CONF_sunken_edge))
728 exwinmode |= WS_EX_CLIENTEDGE;
729 hwnd = CreateWindowExW(exwinmode, uappname, uappname,
730 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
731 guess_width, guess_height,
732 NULL, NULL, inst, NULL);
737 * Initialise the fonts, simultaneously correcting the guesses
738 * for font_{width,height}.
743 * Initialise the terminal. (We have to do this _after_
744 * creating the window, since the terminal is the first thing
745 * which will call schedule_timer(), which will in turn call
746 * timer_change_notify() which will expect hwnd to exist.)
748 term = term_init(conf, &ucsdata, NULL);
749 logctx = log_init(NULL, conf);
750 term_provide_logctx(term, logctx);
751 term_size(term, conf_get_int(conf, CONF_height),
752 conf_get_int(conf, CONF_width),
753 conf_get_int(conf, CONF_savelines));
756 * Correct the guesses for extra_{width,height}.
760 GetWindowRect(hwnd, &wr);
761 GetClientRect(hwnd, &cr);
762 offset_width = offset_height = conf_get_int(conf, CONF_window_border);
763 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
764 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
768 * Resize the window, now we know what size we _really_ want it
771 guess_width = extra_width + font_width * term->cols;
772 guess_height = extra_height + font_height * term->rows;
773 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
774 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
777 * Set up a caret bitmap, with no content.
781 int size = (font_width + 15) / 16 * 2 * font_height;
782 bits = snewn(size, char);
783 memset(bits, 0, size);
784 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
787 CreateCaret(hwnd, caretbm, font_width, font_height);
790 * Initialise the scroll bar.
795 si.cbSize = sizeof(si);
796 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
798 si.nMax = term->rows - 1;
799 si.nPage = term->rows;
801 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
805 * Prepare the mouse handler.
807 lastact = MA_NOTHING;
808 lastbtn = MBT_NOTHING;
809 dbltime = GetDoubleClickTime();
812 * Set up the session-control options on the system menu.
819 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
820 popup_menus[CTXMENU].menu = CreatePopupMenu();
821 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
823 savedsess_menu = CreateMenu();
824 get_sesslist(&sesslist, TRUE);
825 update_savedsess_menu();
827 for (j = 0; j < lenof(popup_menus); j++) {
828 m = popup_menus[j].menu;
830 AppendMenu(m, MF_SEPARATOR, 0, 0);
831 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
832 AppendMenu(m, MF_SEPARATOR, 0, 0);
833 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
834 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
835 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT_PTR) savedsess_menu,
837 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
838 AppendMenu(m, MF_SEPARATOR, 0, 0);
839 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
840 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
841 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
842 AppendMenu(m, MF_SEPARATOR, 0, 0);
843 AppendMenu(m, (conf_get_int(conf, CONF_resize_action)
844 == RESIZE_DISABLED) ? MF_GRAYED : MF_ENABLED,
845 IDM_FULLSCREEN, "&Full Screen");
846 AppendMenu(m, MF_SEPARATOR, 0, 0);
848 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
849 str = dupprintf("&About %s", appname);
850 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
858 * Set up the initial input locale.
860 set_input_locale(GetKeyboardLayout(0));
863 * Finally show the window!
865 ShowWindow(hwnd, show);
866 SetForegroundWindow(hwnd);
869 * Set the palette up.
875 term_set_focus(term, GetForegroundWindow() == hwnd);
883 if (toplevel_callback_pending() ||
884 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
886 * If we have anything we'd like to do immediately, set
887 * the timeout for MsgWaitForMultipleObjects to zero so
888 * that we'll only do a quick check of our handles and
889 * then get on with whatever that was.
891 * One such option is a pending toplevel callback. The
892 * other is a non-empty Windows message queue, which you'd
893 * think we could leave to MsgWaitForMultipleObjects to
894 * check for us along with all the handles, but in fact we
895 * can't because once PeekMessage in one iteration of this
896 * loop has removed a message from the queue, the whole
897 * queue is considered uninteresting by the next
898 * invocation of MWFMO. So we check ourselves whether the
899 * message queue is non-empty, and if so, set this timeout
900 * to zero to ensure MWFMO doesn't block.
905 /* The messages seem unreliable; especially if we're being tricky */
906 term_set_focus(term, GetForegroundWindow() == hwnd);
909 handles = handle_get_events(&nhandles);
911 n = MsgWaitForMultipleObjects(nhandles, handles, FALSE,
912 timeout, QS_ALLINPUT);
914 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
915 handle_got_event(handles[n - WAIT_OBJECT_0]);
920 while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
921 if (msg.message == WM_QUIT)
922 goto finished; /* two-level break */
924 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
925 DispatchMessageW(&msg);
928 * WM_NETEVENT messages seem to jump ahead of others in
929 * the message queue. I'm not sure why; the docs for
930 * PeekMessage mention that messages are prioritised in
931 * some way, but I'm unclear on which priorities go where.
933 * Anyway, in practice I observe that WM_NETEVENT seems to
934 * jump to the head of the queue, which means that if we
935 * were to only process one message every time round this
936 * loop, we'd get nothing but NETEVENTs if the server
937 * flooded us with data, and stop responding to any other
938 * kind of window message. So instead, we keep on round
939 * this loop until we've consumed at least one message
940 * that _isn't_ a NETEVENT, or run out of messages
941 * completely (whichever comes first). And we don't go to
942 * run_toplevel_callbacks (which is where the netevents
943 * are actually processed, causing fresh NETEVENT messages
944 * to appear) until we've done this.
946 if (msg.message != WM_NETEVENT)
950 run_toplevel_callbacks();
954 cleanup_exit(msg.wParam); /* this doesn't return... */
955 return msg.wParam; /* ... but optimiser doesn't know */
961 void cleanup_exit(int code)
972 if (conf_get_int(conf, CONF_protocol) == PROT_SSH) {
987 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
989 char *do_select(SOCKET skt, int startup)
994 events = (FD_CONNECT | FD_READ | FD_WRITE |
995 FD_OOB | FD_CLOSE | FD_ACCEPT);
1000 return "do_select(): internal error (hwnd==NULL)";
1001 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
1002 switch (p_WSAGetLastError()) {
1004 return "Network is down";
1006 return "WSAAsyncSelect(): unknown error";
1013 * Refresh the saved-session submenu from `sesslist'.
1015 static void update_savedsess_menu(void)
1018 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
1019 /* skip sesslist.sessions[0] == Default Settings */
1021 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
1022 : MENU_SAVED_MAX+1);
1024 AppendMenu(savedsess_menu, MF_ENABLED,
1025 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
1026 sesslist.sessions[i]);
1027 if (sesslist.nsessions <= 1)
1028 AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)");
1032 * Update the Special Commands submenu.
1034 void update_specials_menu(void *frontend)
1040 specials = back->get_specials(backhandle);
1045 /* We can't use Windows to provide a stack for submenus, so
1046 * here's a lame "stack" that will do for now. */
1047 HMENU saved_menu = NULL;
1049 new_menu = CreatePopupMenu();
1050 for (i = 0; nesting > 0; i++) {
1051 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
1052 switch (specials[i].code) {
1054 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
1057 assert(nesting < 2);
1059 saved_menu = new_menu; /* XXX lame stacking */
1060 new_menu = CreatePopupMenu();
1061 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
1062 (UINT_PTR) new_menu, specials[i].name);
1067 new_menu = saved_menu; /* XXX lame stacking */
1072 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
1077 /* Squirrel the highest special. */
1084 for (j = 0; j < lenof(popup_menus); j++) {
1085 if (specials_menu) {
1086 /* XXX does this free up all submenus? */
1087 DeleteMenu(popup_menus[j].menu, (UINT_PTR)specials_menu,
1089 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
1092 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1093 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
1094 (UINT_PTR) new_menu, "S&pecial Command");
1095 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1096 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
1099 specials_menu = new_menu;
1102 static void update_mouse_pointer(void)
1105 int force_visible = FALSE;
1106 static int forced_visible = FALSE;
1107 switch (busy_status) {
1110 curstype = IDC_ARROW;
1112 curstype = IDC_IBEAM;
1115 curstype = IDC_APPSTARTING; /* this may be an abuse */
1116 force_visible = TRUE;
1119 curstype = IDC_WAIT;
1120 force_visible = TRUE;
1126 HCURSOR cursor = LoadCursor(NULL, curstype);
1127 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1128 SetCursor(cursor); /* force redraw of cursor at current posn */
1130 if (force_visible != forced_visible) {
1131 /* We want some cursor shapes to be visible always.
1132 * Along with show_mouseptr(), this manages the ShowCursor()
1133 * counter such that if we switch back to a non-force_visible
1134 * cursor, the previous visibility state is restored. */
1135 ShowCursor(force_visible);
1136 forced_visible = force_visible;
1140 void set_busy_status(void *frontend, int status)
1142 busy_status = status;
1143 update_mouse_pointer();
1147 * set or clear the "raw mouse message" mode
1149 void set_raw_mouse_mode(void *frontend, int activate)
1151 activate = activate && !conf_get_int(conf, CONF_no_mouse_rep);
1152 send_raw_mouse = activate;
1153 update_mouse_pointer();
1157 * Print a message box and close the connection.
1159 void connection_fatal(void *frontend, const char *fmt, ...)
1162 char *stuff, morestuff[100];
1165 stuff = dupvprintf(fmt, ap);
1167 sprintf(morestuff, "%.70s Fatal Error", appname);
1168 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1171 if (conf_get_int(conf, CONF_close_on_exit) == FORCE_ON)
1174 queue_toplevel_callback(close_session, NULL);
1179 * Report an error at the command-line parsing stage.
1181 void cmdline_error(const char *fmt, ...)
1184 char *stuff, morestuff[100];
1187 stuff = dupvprintf(fmt, ap);
1189 sprintf(morestuff, "%.70s Command Line Error", appname);
1190 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1196 * Actually do the job requested by a WM_NETEVENT
1198 static void wm_netevent_callback(void *vctx)
1200 struct wm_netevent_params *params = (struct wm_netevent_params *)vctx;
1201 select_result(params->wParam, params->lParam);
1206 * Copy the colour palette from the configuration data into defpal.
1207 * This is non-trivial because the colour indices are different.
1209 static void conftopalette(void)
1212 static const int ww[] = {
1213 256, 257, 258, 259, 260, 261,
1214 0, 8, 1, 9, 2, 10, 3, 11,
1215 4, 12, 5, 13, 6, 14, 7, 15
1218 for (i = 0; i < 22; i++) {
1220 defpal[w].rgbtRed = conf_get_int_int(conf, CONF_colours, i*3+0);
1221 defpal[w].rgbtGreen = conf_get_int_int(conf, CONF_colours, i*3+1);
1222 defpal[w].rgbtBlue = conf_get_int_int(conf, CONF_colours, i*3+2);
1224 for (i = 0; i < NEXTCOLOURS; i++) {
1226 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1227 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1228 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1229 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
1231 int shade = i - 216;
1232 shade = shade * 10 + 8;
1233 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1234 defpal[i+16].rgbtBlue = shade;
1238 /* Override with system colours if appropriate */
1239 if (conf_get_int(conf, CONF_system_colour))
1244 * Override bit of defpal with colours from the system.
1245 * (NB that this takes a copy the system colours at the time this is called,
1246 * so subsequent colour scheme changes don't take effect. To fix that we'd
1247 * probably want to be using GetSysColorBrush() and the like.)
1249 static void systopalette(void)
1252 static const struct { int nIndex; int norm; int bold; } or[] =
1254 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1255 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1256 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1257 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1260 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1261 COLORREF colour = GetSysColor(or[i].nIndex);
1262 defpal[or[i].norm].rgbtRed =
1263 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1264 defpal[or[i].norm].rgbtGreen =
1265 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1266 defpal[or[i].norm].rgbtBlue =
1267 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1272 * Set up the colour palette.
1274 static void init_palette(void)
1277 HDC hdc = GetDC(hwnd);
1279 if (conf_get_int(conf, CONF_try_palette) &&
1280 GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1282 * This is a genuine case where we must use smalloc
1283 * because the snew macros can't cope.
1285 logpal = smalloc(sizeof(*logpal)
1286 - sizeof(logpal->palPalEntry)
1287 + NALLCOLOURS * sizeof(PALETTEENTRY));
1288 logpal->palVersion = 0x300;
1289 logpal->palNumEntries = NALLCOLOURS;
1290 for (i = 0; i < NALLCOLOURS; i++) {
1291 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1292 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1293 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1294 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1296 pal = CreatePalette(logpal);
1298 SelectPalette(hdc, pal, FALSE);
1299 RealizePalette(hdc);
1300 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1303 ReleaseDC(hwnd, hdc);
1306 for (i = 0; i < NALLCOLOURS; i++)
1307 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1308 defpal[i].rgbtGreen,
1309 defpal[i].rgbtBlue);
1311 for (i = 0; i < NALLCOLOURS; i++)
1312 colours[i] = RGB(defpal[i].rgbtRed,
1313 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1317 * This is a wrapper to ExtTextOut() to force Windows to display
1318 * the precise glyphs we give it. Otherwise it would do its own
1319 * bidi and Arabic shaping, and we would end up uncertain which
1320 * characters it had put where.
1322 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1323 unsigned short *lpString, UINT cbCount,
1324 CONST INT *lpDx, int opaque)
1328 * The LCC include files apparently don't supply the
1329 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1330 * proper: the differences aren't important to us (the only
1331 * variable-width string parameter is one we don't use anyway).
1337 char *buffer = snewn(cbCount*2+2, char);
1338 char *classbuffer = snewn(cbCount, char);
1339 memset(&gcpr, 0, sizeof(gcpr));
1340 memset(buffer, 0, cbCount*2+2);
1341 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1343 gcpr.lStructSize = sizeof(gcpr);
1344 gcpr.lpGlyphs = (void *)buffer;
1345 gcpr.lpClass = (void *)classbuffer;
1346 gcpr.nGlyphs = cbCount;
1347 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1348 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1350 ExtTextOut(hdc, x, y,
1351 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1352 lprc, buffer, cbCount, lpDx);
1356 * The exact_textout() wrapper, unfortunately, destroys the useful
1357 * Windows `font linking' behaviour: automatic handling of Unicode
1358 * code points not supported in this font by falling back to a font
1359 * which does contain them. Therefore, we adopt a multi-layered
1360 * approach: for any potentially-bidi text, we use exact_textout(),
1361 * and for everything else we use a simple ExtTextOut as we did
1362 * before exact_textout() was introduced.
1364 static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1365 unsigned short *lpString, UINT cbCount,
1366 CONST INT *lpDx, int opaque)
1369 int bkmode = 0, got_bkmode = FALSE;
1373 for (i = 0; i < (int)cbCount ;) {
1374 int rtl = is_rtl(lpString[i]);
1378 for (j = i+1; j < (int)cbCount; j++) {
1379 if (rtl != is_rtl(lpString[j]))
1385 * Now [i,j) indicates a maximal substring of lpString
1386 * which should be displayed using the same textout
1390 exact_textout(hdc, xp, y, lprc, lpString+i, j-i,
1391 font_varpitch ? NULL : lpDx+i, opaque);
1393 ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1394 lprc, lpString+i, j-i,
1395 font_varpitch ? NULL : lpDx+i);
1401 bkmode = GetBkMode(hdc);
1403 SetBkMode(hdc, TRANSPARENT);
1408 SetBkMode(hdc, bkmode);
1411 static int get_font_width(HDC hdc, const TEXTMETRIC *tm)
1414 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1415 if (!(tm->tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1416 ret = tm->tmAveCharWidth;
1420 ABCFLOAT widths[LAST-FIRST + 1];
1423 font_varpitch = TRUE;
1424 font_dualwidth = TRUE;
1425 if (GetCharABCWidthsFloat(hdc, FIRST, LAST, widths)) {
1427 for (j = 0; j < lenof(widths); j++) {
1428 int width = (int)(0.5 + widths[j].abcfA +
1429 widths[j].abcfB + widths[j].abcfC);
1434 ret = tm->tmMaxCharWidth;
1443 * Initialise all the fonts we will need initially. There may be as many as
1444 * three or as few as one. The other (potentially) twenty-one fonts are done
1445 * if/when they are needed.
1449 * - check the font width and height, correcting our guesses if
1452 * - verify that the bold font is the same width as the ordinary
1453 * one, and engage shadow bolding if not.
1455 * - verify that the underlined font is the same width as the
1456 * ordinary one (manual underlining by means of line drawing can
1457 * be done in a pinch).
1459 static void init_fonts(int pick_width, int pick_height)
1468 int fw_dontcare, fw_bold;
1470 for (i = 0; i < FONT_MAXNO; i++)
1473 bold_font_mode = conf_get_int(conf, CONF_bold_style) & 1 ?
1474 BOLD_FONT : BOLD_NONE;
1475 bold_colours = conf_get_int(conf, CONF_bold_style) & 2 ? TRUE : FALSE;
1476 und_mode = UND_FONT;
1478 font = conf_get_fontspec(conf, CONF_font);
1480 fw_dontcare = FW_BOLD;
1483 fw_dontcare = FW_DONTCARE;
1490 font_height = pick_height;
1492 font_height = font->height;
1493 if (font_height > 0) {
1495 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1498 font_width = pick_width;
1500 quality = conf_get_int(conf, CONF_font_quality);
1501 #define f(i,c,w,u) \
1502 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1503 c, OUT_DEFAULT_PRECIS, \
1504 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), \
1505 FIXED_PITCH | FF_DONTCARE, font->name)
1507 f(FONT_NORMAL, font->charset, fw_dontcare, FALSE);
1509 SelectObject(hdc, fonts[FONT_NORMAL]);
1510 GetTextMetrics(hdc, &tm);
1512 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1514 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1515 if (!(tm.tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1516 font_varpitch = FALSE;
1517 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1519 font_varpitch = TRUE;
1520 font_dualwidth = TRUE;
1522 if (pick_width == 0 || pick_height == 0) {
1523 font_height = tm.tmHeight;
1524 font_width = get_font_width(hdc, &tm);
1527 #ifdef RDB_DEBUG_PATCH
1528 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1529 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1534 DWORD cset = tm.tmCharSet;
1535 memset(&info, 0xFF, sizeof(info));
1537 /* !!! Yes the next line is right */
1538 if (cset == OEM_CHARSET)
1539 ucsdata.font_codepage = GetOEMCP();
1541 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1542 ucsdata.font_codepage = info.ciACP;
1544 ucsdata.font_codepage = -1;
1546 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1547 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1550 f(FONT_UNDERLINE, font->charset, fw_dontcare, TRUE);
1553 * Some fonts, e.g. 9-pt Courier, draw their underlines
1554 * outside their character cell. We successfully prevent
1555 * screen corruption by clipping the text output, but then
1556 * we lose the underline completely. Here we try to work
1557 * out whether this is such a font, and if it is, we set a
1558 * flag that causes underlines to be drawn by hand.
1560 * Having tried other more sophisticated approaches (such
1561 * as examining the TEXTMETRIC structure or requesting the
1562 * height of a string), I think we'll do this the brute
1563 * force way: we create a small bitmap, draw an underlined
1564 * space on it, and test to see whether any pixels are
1565 * foreground-coloured. (Since we expect the underline to
1566 * go all the way across the character cell, we only search
1567 * down a single column of the bitmap, half way across.)
1571 HBITMAP und_bm, und_oldbm;
1575 und_dc = CreateCompatibleDC(hdc);
1576 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1577 und_oldbm = SelectObject(und_dc, und_bm);
1578 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1579 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1580 SetTextColor(und_dc, RGB(255, 255, 255));
1581 SetBkColor(und_dc, RGB(0, 0, 0));
1582 SetBkMode(und_dc, OPAQUE);
1583 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1585 for (i = 0; i < font_height; i++) {
1586 c = GetPixel(und_dc, font_width / 2, i);
1587 if (c != RGB(0, 0, 0))
1590 SelectObject(und_dc, und_oldbm);
1591 DeleteObject(und_bm);
1594 und_mode = UND_LINE;
1595 DeleteObject(fonts[FONT_UNDERLINE]);
1596 fonts[FONT_UNDERLINE] = 0;
1600 if (bold_font_mode == BOLD_FONT) {
1601 f(FONT_BOLD, font->charset, fw_bold, FALSE);
1605 descent = tm.tmAscent + 1;
1606 if (descent >= font_height)
1607 descent = font_height - 1;
1609 for (i = 0; i < 3; i++) {
1611 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1612 fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight;
1619 ReleaseDC(hwnd, hdc);
1621 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1622 und_mode = UND_LINE;
1623 DeleteObject(fonts[FONT_UNDERLINE]);
1624 fonts[FONT_UNDERLINE] = 0;
1627 if (bold_font_mode == BOLD_FONT &&
1628 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1629 bold_font_mode = BOLD_SHADOW;
1630 DeleteObject(fonts[FONT_BOLD]);
1631 fonts[FONT_BOLD] = 0;
1633 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1635 init_ucs(conf, &ucsdata);
1638 static void another_font(int fontno)
1641 int fw_dontcare, fw_bold, quality;
1646 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1649 basefont = (fontno & ~(FONT_BOLDUND));
1650 if (basefont != fontno && !fontflag[basefont])
1651 another_font(basefont);
1653 font = conf_get_fontspec(conf, CONF_font);
1656 fw_dontcare = FW_BOLD;
1659 fw_dontcare = FW_DONTCARE;
1669 if (fontno & FONT_WIDE)
1671 if (fontno & FONT_NARROW)
1673 if (fontno & FONT_OEM)
1675 if (fontno & FONT_BOLD)
1677 if (fontno & FONT_UNDERLINE)
1680 quality = conf_get_int(conf, CONF_font_quality);
1683 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1684 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1685 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality),
1686 DEFAULT_PITCH | FF_DONTCARE, s);
1688 fontflag[fontno] = 1;
1691 static void deinit_fonts(void)
1694 for (i = 0; i < FONT_MAXNO; i++) {
1696 DeleteObject(fonts[i]);
1702 void request_resize(void *frontend, int w, int h)
1706 /* If the window is maximized supress resizing attempts */
1707 if (IsZoomed(hwnd)) {
1708 if (conf_get_int(conf, CONF_resize_action) == RESIZE_TERM)
1712 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) return;
1713 if (h == term->rows && w == term->cols) return;
1715 /* Sanity checks ... */
1717 static int first_time = 1;
1720 switch (first_time) {
1722 /* Get the size of the screen */
1723 if (get_fullscreen_rect(&ss))
1724 /* first_time = 0 */ ;
1730 /* Make sure the values are sane */
1731 width = (ss.right - ss.left - extra_width) / 4;
1732 height = (ss.bottom - ss.top - extra_height) / 6;
1734 if (w > width || h > height)
1743 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
1745 if (conf_get_int(conf, CONF_resize_action) != RESIZE_FONT &&
1747 width = extra_width + font_width * w;
1748 height = extra_height + font_height * h;
1750 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1751 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1752 SWP_NOMOVE | SWP_NOZORDER);
1756 InvalidateRect(hwnd, NULL, TRUE);
1759 static void reset_window(int reinit) {
1761 * This function decides how to resize or redraw when the
1762 * user changes something.
1764 * This function doesn't like to change the terminal size but if the
1765 * font size is locked that may be it's only soluion.
1767 int win_width, win_height, resize_action, window_border;
1770 #ifdef RDB_DEBUG_PATCH
1771 debug((27, "reset_window()"));
1774 /* Current window sizes ... */
1775 GetWindowRect(hwnd, &wr);
1776 GetClientRect(hwnd, &cr);
1778 win_width = cr.right - cr.left;
1779 win_height = cr.bottom - cr.top;
1781 resize_action = conf_get_int(conf, CONF_resize_action);
1782 window_border = conf_get_int(conf, CONF_window_border);
1784 if (resize_action == RESIZE_DISABLED)
1787 /* Are we being forced to reload the fonts ? */
1789 #ifdef RDB_DEBUG_PATCH
1790 debug((27, "reset_window() -- Forced deinit"));
1796 /* Oh, looks like we're minimised */
1797 if (win_width == 0 || win_height == 0)
1800 /* Is the window out of position ? */
1802 (offset_width != (win_width-font_width*term->cols)/2 ||
1803 offset_height != (win_height-font_height*term->rows)/2) ){
1804 offset_width = (win_width-font_width*term->cols)/2;
1805 offset_height = (win_height-font_height*term->rows)/2;
1806 InvalidateRect(hwnd, NULL, TRUE);
1807 #ifdef RDB_DEBUG_PATCH
1808 debug((27, "reset_window() -> Reposition terminal"));
1812 if (IsZoomed(hwnd)) {
1813 /* We're fullscreen, this means we must not change the size of
1814 * the window so it's the font size or the terminal itself.
1817 extra_width = wr.right - wr.left - cr.right + cr.left;
1818 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1820 if (resize_action != RESIZE_TERM) {
1821 if (font_width != win_width/term->cols ||
1822 font_height != win_height/term->rows) {
1824 init_fonts(win_width/term->cols, win_height/term->rows);
1825 offset_width = (win_width-font_width*term->cols)/2;
1826 offset_height = (win_height-font_height*term->rows)/2;
1827 InvalidateRect(hwnd, NULL, TRUE);
1828 #ifdef RDB_DEBUG_PATCH
1829 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1830 font_width, font_height));
1834 if (font_width * term->cols != win_width ||
1835 font_height * term->rows != win_height) {
1836 /* Our only choice at this point is to change the
1837 * size of the terminal; Oh well.
1839 term_size(term, win_height/font_height, win_width/font_width,
1840 conf_get_int(conf, CONF_savelines));
1841 offset_width = (win_width-font_width*term->cols)/2;
1842 offset_height = (win_height-font_height*term->rows)/2;
1843 InvalidateRect(hwnd, NULL, TRUE);
1844 #ifdef RDB_DEBUG_PATCH
1845 debug((27, "reset_window() -> Zoomed term_size"));
1852 /* Hmm, a force re-init means we should ignore the current window
1853 * so we resize to the default font size.
1856 #ifdef RDB_DEBUG_PATCH
1857 debug((27, "reset_window() -> Forced re-init"));
1860 offset_width = offset_height = window_border;
1861 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1862 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1864 if (win_width != font_width*term->cols + offset_width*2 ||
1865 win_height != font_height*term->rows + offset_height*2) {
1867 /* If this is too large windows will resize it to the maximum
1868 * allowed window size, we will then be back in here and resize
1869 * the font or terminal to fit.
1871 SetWindowPos(hwnd, NULL, 0, 0,
1872 font_width*term->cols + extra_width,
1873 font_height*term->rows + extra_height,
1874 SWP_NOMOVE | SWP_NOZORDER);
1877 InvalidateRect(hwnd, NULL, TRUE);
1881 /* Okay the user doesn't want us to change the font so we try the
1882 * window. But that may be too big for the screen which forces us
1883 * to change the terminal.
1885 if ((resize_action == RESIZE_TERM && reinit<=0) ||
1886 (resize_action == RESIZE_EITHER && reinit<0) ||
1888 offset_width = offset_height = window_border;
1889 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1890 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1892 if (win_width != font_width*term->cols + offset_width*2 ||
1893 win_height != font_height*term->rows + offset_height*2) {
1898 get_fullscreen_rect(&ss);
1900 width = (ss.right - ss.left - extra_width) / font_width;
1901 height = (ss.bottom - ss.top - extra_height) / font_height;
1904 if ( term->rows > height || term->cols > width ) {
1905 if (resize_action == RESIZE_EITHER) {
1906 /* Make the font the biggest we can */
1907 if (term->cols > width)
1908 font_width = (ss.right - ss.left - extra_width)
1910 if (term->rows > height)
1911 font_height = (ss.bottom - ss.top - extra_height)
1915 init_fonts(font_width, font_height);
1917 width = (ss.right - ss.left - extra_width) / font_width;
1918 height = (ss.bottom - ss.top - extra_height) / font_height;
1920 if ( height > term->rows ) height = term->rows;
1921 if ( width > term->cols ) width = term->cols;
1922 term_size(term, height, width,
1923 conf_get_int(conf, CONF_savelines));
1924 #ifdef RDB_DEBUG_PATCH
1925 debug((27, "reset_window() -> term resize to (%d,%d)",
1931 SetWindowPos(hwnd, NULL, 0, 0,
1932 font_width*term->cols + extra_width,
1933 font_height*term->rows + extra_height,
1934 SWP_NOMOVE | SWP_NOZORDER);
1936 InvalidateRect(hwnd, NULL, TRUE);
1937 #ifdef RDB_DEBUG_PATCH
1938 debug((27, "reset_window() -> window resize to (%d,%d)",
1939 font_width*term->cols + extra_width,
1940 font_height*term->rows + extra_height));
1946 /* We're allowed to or must change the font but do we want to ? */
1948 if (font_width != (win_width-window_border*2)/term->cols ||
1949 font_height != (win_height-window_border*2)/term->rows) {
1952 init_fonts((win_width-window_border*2)/term->cols,
1953 (win_height-window_border*2)/term->rows);
1954 offset_width = (win_width-font_width*term->cols)/2;
1955 offset_height = (win_height-font_height*term->rows)/2;
1957 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1958 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1960 InvalidateRect(hwnd, NULL, TRUE);
1961 #ifdef RDB_DEBUG_PATCH
1962 debug((25, "reset_window() -> font resize to (%d,%d)",
1963 font_width, font_height));
1968 static void set_input_locale(HKL kl)
1972 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1973 lbuf, sizeof(lbuf));
1975 kbd_codepage = atoi(lbuf);
1978 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1980 int thistime = GetMessageTime();
1982 if (send_raw_mouse &&
1983 !(shift && conf_get_int(conf, CONF_mouse_override))) {
1984 lastbtn = MBT_NOTHING;
1985 term_mouse(term, b, translate_button(b), MA_CLICK,
1986 x, y, shift, ctrl, alt);
1990 if (lastbtn == b && thistime - lasttime < dbltime) {
1991 lastact = (lastact == MA_CLICK ? MA_2CLK :
1992 lastact == MA_2CLK ? MA_3CLK :
1993 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1998 if (lastact != MA_NOTHING)
1999 term_mouse(term, b, translate_button(b), lastact,
2000 x, y, shift, ctrl, alt);
2001 lasttime = thistime;
2005 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
2006 * into a cooked one (SELECT, EXTEND, PASTE).
2008 static Mouse_Button translate_button(Mouse_Button button)
2010 if (button == MBT_LEFT)
2012 if (button == MBT_MIDDLE)
2013 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2014 MBT_PASTE : MBT_EXTEND;
2015 if (button == MBT_RIGHT)
2016 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2017 MBT_EXTEND : MBT_PASTE;
2018 return 0; /* shouldn't happen */
2021 static void show_mouseptr(int show)
2023 /* NB that the counter in ShowCursor() is also frobbed by
2024 * update_mouse_pointer() */
2025 static int cursor_visible = 1;
2026 if (!conf_get_int(conf, CONF_hide_mouseptr))
2027 show = 1; /* override if this feature disabled */
2028 if (cursor_visible && !show)
2030 else if (!cursor_visible && show)
2032 cursor_visible = show;
2035 static int is_alt_pressed(void)
2038 int r = GetKeyboardState(keystate);
2041 if (keystate[VK_MENU] & 0x80)
2043 if (keystate[VK_RMENU] & 0x80)
2048 static int resizing;
2050 void notify_remote_exit(void *fe)
2052 int exitcode, close_on_exit;
2054 if (!session_closed &&
2055 (exitcode = back->exitcode(backhandle)) >= 0) {
2056 close_on_exit = conf_get_int(conf, CONF_close_on_exit);
2057 /* Abnormal exits will already have set session_closed and taken
2058 * appropriate action. */
2059 if (close_on_exit == FORCE_ON ||
2060 (close_on_exit == AUTO && exitcode != INT_MAX)) {
2063 queue_toplevel_callback(close_session, NULL);
2064 session_closed = TRUE;
2065 /* exitcode == INT_MAX indicates that the connection was closed
2066 * by a fatal error, so an error box will be coming our way and
2067 * we should not generate this informational one. */
2068 if (exitcode != INT_MAX)
2069 MessageBox(hwnd, "Connection closed by remote host",
2070 appname, MB_OK | MB_ICONINFORMATION);
2075 void timer_change_notify(unsigned long next)
2077 unsigned long now = GETTICKCOUNT();
2079 if (now - next < INT_MAX)
2083 KillTimer(hwnd, TIMING_TIMER_ID);
2084 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
2085 timing_next_time = next;
2088 static void conf_cache_data(void)
2090 /* Cache some items from conf to speed lookups in very hot code */
2091 cursor_type = conf_get_int(conf, CONF_cursor_type);
2092 vtmode = conf_get_int(conf, CONF_vtmode);
2095 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2096 WPARAM wParam, LPARAM lParam)
2099 static int ignore_clip = FALSE;
2100 static int need_backend_resize = FALSE;
2101 static int fullscr_on_max = FALSE;
2102 static int processed_resize = FALSE;
2103 static UINT last_mousemove = 0;
2108 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
2111 KillTimer(hwnd, TIMING_TIMER_ID);
2112 if (run_timers(timing_next_time, &next)) {
2113 timer_change_notify(next);
2124 str = dupprintf("%s Exit Confirmation", appname);
2125 if (session_closed || !conf_get_int(conf, CONF_warn_on_close) ||
2127 "Are you sure you want to close this session?",
2128 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
2130 DestroyWindow(hwnd);
2138 case WM_INITMENUPOPUP:
2139 if ((HMENU)wParam == savedsess_menu) {
2140 /* About to pop up Saved Sessions sub-menu.
2141 * Refresh the session list. */
2142 get_sesslist(&sesslist, FALSE); /* free */
2143 get_sesslist(&sesslist, TRUE);
2144 update_savedsess_menu();
2150 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
2161 BOOL inherit_handles;
2163 PROCESS_INFORMATION pi;
2164 HANDLE filemap = NULL;
2166 if (wParam == IDM_DUPSESS) {
2168 * Allocate a file-mapping memory chunk for the
2171 SECURITY_ATTRIBUTES sa;
2175 size = conf_serialised_size(conf);
2177 sa.nLength = sizeof(sa);
2178 sa.lpSecurityDescriptor = NULL;
2179 sa.bInheritHandle = TRUE;
2180 filemap = CreateFileMapping(INVALID_HANDLE_VALUE,
2184 if (filemap && filemap != INVALID_HANDLE_VALUE) {
2185 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, size);
2187 conf_serialise(conf, p);
2191 inherit_handles = TRUE;
2192 sprintf(c, "putty &%p:%u", filemap, (unsigned)size);
2194 } else if (wParam == IDM_SAVEDSESS) {
2195 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
2196 / MENU_SAVED_STEP) + 1;
2197 if (sessno < (unsigned)sesslist.nsessions) {
2198 const char *session = sesslist.sessions[sessno];
2199 cl = dupprintf("putty @%s", session);
2200 inherit_handles = FALSE;
2204 } else /* IDM_NEWSESS */ {
2206 inherit_handles = FALSE;
2209 GetModuleFileName(NULL, b, sizeof(b) - 1);
2211 si.lpReserved = NULL;
2212 si.lpDesktop = NULL;
2216 si.lpReserved2 = NULL;
2217 CreateProcess(b, cl, NULL, NULL, inherit_handles,
2218 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
2219 CloseHandle(pi.hProcess);
2220 CloseHandle(pi.hThread);
2223 CloseHandle(filemap);
2230 logevent(NULL, "----- Session restarted -----");
2231 term_pwron(term, FALSE);
2240 int reconfig_result;
2245 reconfiguring = TRUE;
2248 * Copy the current window title into the stored
2249 * previous configuration, so that doing nothing to
2250 * the window title field in the config box doesn't
2251 * reset the title to its startup state.
2253 conf_set_str(conf, CONF_wintitle, window_name);
2255 prev_conf = conf_copy(conf);
2258 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2259 reconfiguring = FALSE;
2260 if (!reconfig_result) {
2261 conf_free(prev_conf);
2267 resize_action = conf_get_int(conf, CONF_resize_action);
2269 /* Disable full-screen if resizing forbidden */
2271 for (i = 0; i < lenof(popup_menus); i++)
2272 EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN,
2274 (resize_action == RESIZE_DISABLED)
2275 ? MF_GRAYED : MF_ENABLED);
2276 /* Gracefully unzoom if necessary */
2277 if (IsZoomed(hwnd) && (resize_action == RESIZE_DISABLED))
2278 ShowWindow(hwnd, SW_RESTORE);
2281 /* Pass new config data to the logging module */
2282 log_reconfig(logctx, conf);
2286 * Flush the line discipline's edit buffer in the
2287 * case where local editing has just been disabled.
2290 ldisc_configure(ldisc, conf);
2291 ldisc_echoedit_update(ldisc);
2300 /* Pass new config data to the terminal */
2301 term_reconfig(term, conf);
2303 /* Pass new config data to the back end */
2305 back->reconfig(backhandle, conf);
2307 /* Screen size changed ? */
2308 if (conf_get_int(conf, CONF_height) !=
2309 conf_get_int(prev_conf, CONF_height) ||
2310 conf_get_int(conf, CONF_width) !=
2311 conf_get_int(prev_conf, CONF_width) ||
2312 conf_get_int(conf, CONF_savelines) !=
2313 conf_get_int(prev_conf, CONF_savelines) ||
2314 resize_action == RESIZE_FONT ||
2315 (resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2316 resize_action == RESIZE_DISABLED)
2317 term_size(term, conf_get_int(conf, CONF_height),
2318 conf_get_int(conf, CONF_width),
2319 conf_get_int(conf, CONF_savelines));
2321 /* Enable or disable the scroll bar, etc */
2323 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2324 LONG nexflag, exflag =
2325 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2328 if (conf_get_int(conf, CONF_alwaysontop) !=
2329 conf_get_int(prev_conf, CONF_alwaysontop)) {
2330 if (conf_get_int(conf, CONF_alwaysontop)) {
2331 nexflag |= WS_EX_TOPMOST;
2332 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2333 SWP_NOMOVE | SWP_NOSIZE);
2335 nexflag &= ~(WS_EX_TOPMOST);
2336 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2337 SWP_NOMOVE | SWP_NOSIZE);
2340 if (conf_get_int(conf, CONF_sunken_edge))
2341 nexflag |= WS_EX_CLIENTEDGE;
2343 nexflag &= ~(WS_EX_CLIENTEDGE);
2346 if (conf_get_int(conf, is_full_screen() ?
2347 CONF_scrollbar_in_fullscreen :
2351 nflg &= ~WS_VSCROLL;
2353 if (resize_action == RESIZE_DISABLED ||
2355 nflg &= ~WS_THICKFRAME;
2357 nflg |= WS_THICKFRAME;
2359 if (resize_action == RESIZE_DISABLED)
2360 nflg &= ~WS_MAXIMIZEBOX;
2362 nflg |= WS_MAXIMIZEBOX;
2364 if (nflg != flag || nexflag != exflag) {
2366 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2367 if (nexflag != exflag)
2368 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2370 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2371 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2372 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2380 if (resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2385 set_title(NULL, conf_get_str(conf, CONF_wintitle));
2386 if (IsIconic(hwnd)) {
2388 conf_get_int(conf, CONF_win_name_always) ?
2389 window_name : icon_name);
2393 FontSpec *font = conf_get_fontspec(conf, CONF_font);
2394 FontSpec *prev_font = conf_get_fontspec(prev_conf,
2397 if (!strcmp(font->name, prev_font->name) ||
2398 !strcmp(conf_get_str(conf, CONF_line_codepage),
2399 conf_get_str(prev_conf, CONF_line_codepage)) ||
2400 font->isbold != prev_font->isbold ||
2401 font->height != prev_font->height ||
2402 font->charset != prev_font->charset ||
2403 conf_get_int(conf, CONF_font_quality) !=
2404 conf_get_int(prev_conf, CONF_font_quality) ||
2405 conf_get_int(conf, CONF_vtmode) !=
2406 conf_get_int(prev_conf, CONF_vtmode) ||
2407 conf_get_int(conf, CONF_bold_style) !=
2408 conf_get_int(prev_conf, CONF_bold_style) ||
2409 resize_action == RESIZE_DISABLED ||
2410 resize_action == RESIZE_EITHER ||
2411 resize_action != conf_get_int(prev_conf,
2412 CONF_resize_action))
2416 InvalidateRect(hwnd, NULL, TRUE);
2417 reset_window(init_lvl);
2419 conf_free(prev_conf);
2426 request_paste(NULL);
2432 term_pwron(term, TRUE);
2434 ldisc_echoedit_update(ldisc);
2440 launch_help(hwnd, NULL);
2444 * We get this if the System menu has been activated
2451 * We get this if the System menu has been activated
2452 * using the keyboard. This might happen from within
2453 * TranslateKey, in which case it really wants to be
2454 * followed by a `space' character to actually _bring
2455 * the menu up_ rather than just sitting there in
2456 * `ready to appear' state.
2458 show_mouseptr(1); /* make sure pointer is visible */
2460 PostMessage(hwnd, WM_CHAR, ' ', 0);
2462 case IDM_FULLSCREEN:
2466 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2467 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2469 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2470 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2472 * Ensure we haven't been sent a bogus SYSCOMMAND
2473 * which would cause us to reference invalid memory
2474 * and crash. Perhaps I'm just too paranoid here.
2476 if (i >= n_specials)
2479 back->special(backhandle, specials[i].code);
2484 #define X_POS(l) ((int)(short)LOWORD(l))
2485 #define Y_POS(l) ((int)(short)HIWORD(l))
2487 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2488 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2489 case WM_LBUTTONDOWN:
2490 case WM_MBUTTONDOWN:
2491 case WM_RBUTTONDOWN:
2495 if (message == WM_RBUTTONDOWN &&
2496 ((wParam & MK_CONTROL) ||
2497 (conf_get_int(conf, CONF_mouse_is_xterm) == 2))) {
2500 show_mouseptr(1); /* make sure pointer is visible */
2501 GetCursorPos(&cursorpos);
2502 TrackPopupMenu(popup_menus[CTXMENU].menu,
2503 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2504 cursorpos.x, cursorpos.y,
2512 case WM_LBUTTONDOWN:
2514 wParam |= MK_LBUTTON;
2517 case WM_MBUTTONDOWN:
2518 button = MBT_MIDDLE;
2519 wParam |= MK_MBUTTON;
2522 case WM_RBUTTONDOWN:
2524 wParam |= MK_RBUTTON;
2529 wParam &= ~MK_LBUTTON;
2533 button = MBT_MIDDLE;
2534 wParam &= ~MK_MBUTTON;
2539 wParam &= ~MK_RBUTTON;
2543 button = press = 0; /* shouldn't happen */
2547 * Special case: in full-screen mode, if the left
2548 * button is clicked in the very top left corner of the
2549 * window, we put up the System menu instead of doing
2553 char mouse_on_hotspot = 0;
2562 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2565 mi.cbSize = sizeof(MONITORINFO);
2566 GetMonitorInfo(mon, &mi);
2568 if (mi.rcMonitor.left == pt.x &&
2569 mi.rcMonitor.top == pt.y) {
2570 mouse_on_hotspot = 1;
2575 if (pt.x == 0 && pt.y == 0) {
2576 mouse_on_hotspot = 1;
2579 if (is_full_screen() && press &&
2580 button == MBT_LEFT && mouse_on_hotspot) {
2581 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2582 MAKELPARAM(pt.x, pt.y));
2589 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2590 wParam & MK_SHIFT, wParam & MK_CONTROL,
2594 term_mouse(term, button, translate_button(button), MA_RELEASE,
2595 TO_CHR_X(X_POS(lParam)),
2596 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2597 wParam & MK_CONTROL, is_alt_pressed());
2598 if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)))
2606 * Windows seems to like to occasionally send MOUSEMOVE
2607 * events even if the mouse hasn't moved. Don't unhide
2608 * the mouse pointer in this case.
2610 static WPARAM wp = 0;
2611 static LPARAM lp = 0;
2612 if (wParam != wp || lParam != lp ||
2613 last_mousemove != WM_MOUSEMOVE) {
2615 wp = wParam; lp = lParam;
2616 last_mousemove = WM_MOUSEMOVE;
2620 * Add the mouse position and message time to the random
2623 noise_ultralight(lParam);
2625 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2626 GetCapture() == hwnd) {
2628 if (wParam & MK_LBUTTON)
2630 else if (wParam & MK_MBUTTON)
2634 term_mouse(term, b, translate_button(b), MA_DRAG,
2635 TO_CHR_X(X_POS(lParam)),
2636 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2637 wParam & MK_CONTROL, is_alt_pressed());
2640 case WM_NCMOUSEMOVE:
2642 static WPARAM wp = 0;
2643 static LPARAM lp = 0;
2644 if (wParam != wp || lParam != lp ||
2645 last_mousemove != WM_NCMOUSEMOVE) {
2647 wp = wParam; lp = lParam;
2648 last_mousemove = WM_NCMOUSEMOVE;
2651 noise_ultralight(lParam);
2653 case WM_IGNORE_CLIP:
2654 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2656 case WM_DESTROYCLIPBOARD:
2658 term_deselect(term);
2659 ignore_clip = FALSE;
2666 hdc = BeginPaint(hwnd, &p);
2668 SelectPalette(hdc, pal, TRUE);
2669 RealizePalette(hdc);
2673 * We have to be careful about term_paint(). It will
2674 * set a bunch of character cells to INVALID and then
2675 * call do_paint(), which will redraw those cells and
2676 * _then mark them as done_. This may not be accurate:
2677 * when painting in WM_PAINT context we are restricted
2678 * to the rectangle which has just been exposed - so if
2679 * that only covers _part_ of a character cell and the
2680 * rest of it was already visible, that remainder will
2681 * not be redrawn at all. Accordingly, we must not
2682 * paint any character cell in a WM_PAINT context which
2683 * already has a pending update due to terminal output.
2684 * The simplest solution to this - and many, many
2685 * thanks to Hung-Te Lin for working all this out - is
2686 * not to do any actual painting at _all_ if there's a
2687 * pending terminal update: just mark the relevant
2688 * character cells as INVALID and wait for the
2689 * scheduled full update to sort it out.
2691 * I have a suspicion this isn't the _right_ solution.
2692 * An alternative approach would be to have terminal.c
2693 * separately track what _should_ be on the terminal
2694 * screen and what _is_ on the terminal screen, and
2695 * have two completely different types of redraw (one
2696 * for full updates, which syncs the former with the
2697 * terminal itself, and one for WM_PAINT which syncs
2698 * the latter with the former); yet another possibility
2699 * would be to have the Windows front end do what the
2700 * GTK one already does, and maintain a bitmap of the
2701 * current terminal appearance so that WM_PAINT becomes
2702 * completely trivial. However, this should do for now.
2704 term_paint(term, hdc,
2705 (p.rcPaint.left-offset_width)/font_width,
2706 (p.rcPaint.top-offset_height)/font_height,
2707 (p.rcPaint.right-offset_width-1)/font_width,
2708 (p.rcPaint.bottom-offset_height-1)/font_height,
2709 !term->window_update_pending);
2712 p.rcPaint.left < offset_width ||
2713 p.rcPaint.top < offset_height ||
2714 p.rcPaint.right >= offset_width + font_width*term->cols ||
2715 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2717 HBRUSH fillcolour, oldbrush;
2719 fillcolour = CreateSolidBrush (
2720 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2721 oldbrush = SelectObject(hdc, fillcolour);
2722 edge = CreatePen(PS_SOLID, 0,
2723 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2724 oldpen = SelectObject(hdc, edge);
2727 * Jordan Russell reports that this apparently
2728 * ineffectual IntersectClipRect() call masks a
2729 * Windows NT/2K bug causing strange display
2730 * problems when the PuTTY window is taller than
2731 * the primary monitor. It seems harmless enough...
2733 IntersectClipRect(hdc,
2734 p.rcPaint.left, p.rcPaint.top,
2735 p.rcPaint.right, p.rcPaint.bottom);
2737 ExcludeClipRect(hdc,
2738 offset_width, offset_height,
2739 offset_width+font_width*term->cols,
2740 offset_height+font_height*term->rows);
2742 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2743 p.rcPaint.right, p.rcPaint.bottom);
2745 /* SelectClipRgn(hdc, NULL); */
2747 SelectObject(hdc, oldbrush);
2748 DeleteObject(fillcolour);
2749 SelectObject(hdc, oldpen);
2752 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2753 SelectObject(hdc, GetStockObject(WHITE_PEN));
2761 * To protect against re-entrancy when Windows's recv()
2762 * immediately triggers a new WSAAsyncSelect window
2763 * message, we don't call select_result directly from this
2764 * handler but instead wait until we're back out at the
2765 * top level of the message loop.
2767 struct wm_netevent_params *params =
2768 snew(struct wm_netevent_params);
2769 params->wParam = wParam;
2770 params->lParam = lParam;
2771 queue_toplevel_callback(wm_netevent_callback, params);
2775 term_set_focus(term, TRUE);
2776 CreateCaret(hwnd, caretbm, font_width, font_height);
2778 flash_window(0); /* stop */
2784 term_set_focus(term, FALSE);
2786 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2789 case WM_ENTERSIZEMOVE:
2790 #ifdef RDB_DEBUG_PATCH
2791 debug((27, "WM_ENTERSIZEMOVE"));
2795 need_backend_resize = FALSE;
2797 case WM_EXITSIZEMOVE:
2800 #ifdef RDB_DEBUG_PATCH
2801 debug((27, "WM_EXITSIZEMOVE"));
2803 if (need_backend_resize) {
2804 term_size(term, conf_get_int(conf, CONF_height),
2805 conf_get_int(conf, CONF_width),
2806 conf_get_int(conf, CONF_savelines));
2807 InvalidateRect(hwnd, NULL, TRUE);
2812 * This does two jobs:
2813 * 1) Keep the sizetip uptodate
2814 * 2) Make sure the window size is _stepped_ in units of the font size.
2816 resize_action = conf_get_int(conf, CONF_resize_action);
2817 if (resize_action == RESIZE_TERM ||
2818 (resize_action == RESIZE_EITHER && !is_alt_pressed())) {
2819 int width, height, w, h, ew, eh;
2820 LPRECT r = (LPRECT) lParam;
2822 if (!need_backend_resize && resize_action == RESIZE_EITHER &&
2823 (conf_get_int(conf, CONF_height) != term->rows ||
2824 conf_get_int(conf, CONF_width) != term->cols)) {
2826 * Great! It seems that both the terminal size and the
2827 * font size have been changed and the user is now dragging.
2829 * It will now be difficult to get back to the configured
2832 * This would be easier but it seems to be too confusing.
2834 conf_set_int(conf, CONF_height, term->rows);
2835 conf_set_int(conf, CONF_width, term->cols);
2837 InvalidateRect(hwnd, NULL, TRUE);
2838 need_backend_resize = TRUE;
2841 width = r->right - r->left - extra_width;
2842 height = r->bottom - r->top - extra_height;
2843 w = (width + font_width / 2) / font_width;
2846 h = (height + font_height / 2) / font_height;
2849 UpdateSizeTip(hwnd, w, h);
2850 ew = width - w * font_width;
2851 eh = height - h * font_height;
2853 if (wParam == WMSZ_LEFT ||
2854 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2860 if (wParam == WMSZ_TOP ||
2861 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2871 int width, height, w, h, rv = 0;
2872 int window_border = conf_get_int(conf, CONF_window_border);
2873 int ex_width = extra_width + (window_border - offset_width) * 2;
2874 int ex_height = extra_height + (window_border - offset_height) * 2;
2875 LPRECT r = (LPRECT) lParam;
2877 width = r->right - r->left - ex_width;
2878 height = r->bottom - r->top - ex_height;
2880 w = (width + term->cols/2)/term->cols;
2881 h = (height + term->rows/2)/term->rows;
2882 if ( r->right != r->left + w*term->cols + ex_width)
2885 if (wParam == WMSZ_LEFT ||
2886 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2887 r->left = r->right - w*term->cols - ex_width;
2889 r->right = r->left + w*term->cols + ex_width;
2891 if (r->bottom != r->top + h*term->rows + ex_height)
2894 if (wParam == WMSZ_TOP ||
2895 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2896 r->top = r->bottom - h*term->rows - ex_height;
2898 r->bottom = r->top + h*term->rows + ex_height;
2902 /* break; (never reached) */
2903 case WM_FULLSCR_ON_MAX:
2904 fullscr_on_max = TRUE;
2907 sys_cursor_update();
2910 resize_action = conf_get_int(conf, CONF_resize_action);
2911 #ifdef RDB_DEBUG_PATCH
2912 debug((27, "WM_SIZE %s (%d,%d)",
2913 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2914 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2915 (wParam == SIZE_RESTORED && resizing) ? "to":
2916 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2918 LOWORD(lParam), HIWORD(lParam)));
2920 if (wParam == SIZE_MINIMIZED)
2922 conf_get_int(conf, CONF_win_name_always) ?
2923 window_name : icon_name);
2924 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2925 SetWindowText(hwnd, window_name);
2926 if (wParam == SIZE_RESTORED) {
2927 processed_resize = FALSE;
2928 clear_full_screen();
2929 if (processed_resize) {
2931 * Inhibit normal processing of this WM_SIZE; a
2932 * secondary one was triggered just now by
2933 * clear_full_screen which contained the correct
2939 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2940 fullscr_on_max = FALSE;
2941 processed_resize = FALSE;
2943 if (processed_resize) {
2945 * Inhibit normal processing of this WM_SIZE; a
2946 * secondary one was triggered just now by
2947 * make_full_screen which contained the correct client
2954 processed_resize = TRUE;
2956 if (resize_action == RESIZE_DISABLED) {
2957 /* A resize, well it better be a minimize. */
2961 int width, height, w, h;
2962 int window_border = conf_get_int(conf, CONF_window_border);
2964 width = LOWORD(lParam);
2965 height = HIWORD(lParam);
2967 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2969 prev_rows = term->rows;
2970 prev_cols = term->cols;
2971 if (resize_action == RESIZE_TERM) {
2972 w = width / font_width;
2974 h = height / font_height;
2979 * As below, if we're in the middle of an
2980 * interactive resize we don't call
2981 * back->size. In Windows 7, this case can
2982 * arise in maximisation as well via the Aero
2985 need_backend_resize = TRUE;
2986 conf_set_int(conf, CONF_height, h);
2987 conf_set_int(conf, CONF_width, w);
2989 term_size(term, h, w,
2990 conf_get_int(conf, CONF_savelines));
2994 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2996 if (resize_action == RESIZE_TERM) {
2997 w = (width-window_border*2) / font_width;
2999 h = (height-window_border*2) / font_height;
3001 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
3003 } else if (resize_action != RESIZE_FONT)
3007 } else if (wParam == SIZE_MINIMIZED) {
3009 } else if (resize_action == RESIZE_TERM ||
3010 (resize_action == RESIZE_EITHER &&
3011 !is_alt_pressed())) {
3012 w = (width-window_border*2) / font_width;
3014 h = (height-window_border*2) / font_height;
3019 * Don't call back->size in mid-resize. (To
3020 * prevent massive numbers of resize events
3021 * getting sent down the connection during an NT
3024 need_backend_resize = TRUE;
3025 conf_set_int(conf, CONF_height, h);
3026 conf_set_int(conf, CONF_width, w);
3028 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
3034 sys_cursor_update();
3037 switch (LOWORD(wParam)) {
3039 term_scroll(term, -1, 0);
3042 term_scroll(term, +1, 0);
3045 term_scroll(term, 0, +1);
3048 term_scroll(term, 0, -1);
3051 term_scroll(term, 0, +term->rows / 2);
3054 term_scroll(term, 0, -term->rows / 2);
3056 case SB_THUMBPOSITION:
3059 * Use GetScrollInfo instead of HIWORD(wParam) to get
3060 * 32-bit scroll position.
3065 si.cbSize = sizeof(si);
3066 si.fMask = SIF_TRACKPOS;
3067 if (GetScrollInfo(hwnd, SB_VERT, &si) == 0)
3068 si.nTrackPos = HIWORD(wParam);
3069 term_scroll(term, 1, si.nTrackPos);
3074 case WM_PALETTECHANGED:
3075 if ((HWND) wParam != hwnd && pal != NULL) {
3076 HDC hdc = get_ctx(NULL);
3078 if (RealizePalette(hdc) > 0)
3084 case WM_QUERYNEWPALETTE:
3086 HDC hdc = get_ctx(NULL);
3088 if (RealizePalette(hdc) > 0)
3100 * Add the scan code and keypress timing to the random
3103 noise_ultralight(lParam);
3106 * We don't do TranslateMessage since it disassociates the
3107 * resulting CHAR message from the KEYDOWN that sparked it,
3108 * which we occasionally don't want. Instead, we process
3109 * KEYDOWN, and call the Win32 translator functions so that
3110 * we get the translations under _our_ control.
3113 unsigned char buf[20];
3116 if (wParam == VK_PROCESSKEY || /* IME PROCESS key */
3117 wParam == VK_PACKET) { /* 'this key is a Unicode char' */
3118 if (message == WM_KEYDOWN) {
3121 m.message = WM_KEYDOWN;
3123 m.lParam = lParam & 0xdfff;
3124 TranslateMessage(&m);
3125 } else break; /* pass to Windows for default processing */
3127 len = TranslateKey(message, wParam, lParam, buf);
3129 return DefWindowProcW(hwnd, message, wParam, lParam);
3133 * We need not bother about stdin backlogs
3134 * here, because in GUI PuTTY we can't do
3135 * anything about it anyway; there's no means
3136 * of asking Windows to hold off on KEYDOWN
3137 * messages. We _have_ to buffer everything
3140 term_seen_key_event(term);
3142 ldisc_send(ldisc, buf, len, 1);
3148 case WM_INPUTLANGCHANGE:
3149 /* wParam == Font number */
3150 /* lParam == Locale */
3151 set_input_locale((HKL)lParam);
3152 sys_cursor_update();
3154 case WM_IME_STARTCOMPOSITION:
3156 HIMC hImc = ImmGetContext(hwnd);
3157 ImmSetCompositionFont(hImc, &lfont);
3158 ImmReleaseContext(hwnd, hImc);
3161 case WM_IME_COMPOSITION:
3167 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
3168 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
3170 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
3171 break; /* fall back to DefWindowProc */
3173 hIMC = ImmGetContext(hwnd);
3174 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3178 buff = snewn(n, char);
3179 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
3181 * Jaeyoun Chung reports that Korean character
3182 * input doesn't work correctly if we do a single
3183 * luni_send() covering the whole of buff. So
3184 * instead we luni_send the characters one by one.
3186 term_seen_key_event(term);
3187 /* don't divide SURROGATE PAIR */
3189 for (i = 0; i < n; i += 2) {
3190 WCHAR hs = *(unsigned short *)(buff+i);
3191 if (IS_HIGH_SURROGATE(hs) && i+2 < n) {
3192 WCHAR ls = *(unsigned short *)(buff+i+2);
3193 if (IS_LOW_SURROGATE(ls)) {
3194 luni_send(ldisc, (unsigned short *)(buff+i), 2, 1);
3199 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
3204 ImmReleaseContext(hwnd, hIMC);
3209 if (wParam & 0xFF00) {
3210 unsigned char buf[2];
3213 buf[0] = wParam >> 8;
3214 term_seen_key_event(term);
3216 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
3218 char c = (unsigned char) wParam;
3219 term_seen_key_event(term);
3221 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
3227 * Nevertheless, we are prepared to deal with WM_CHAR
3228 * messages, should they crop up. So if someone wants to
3229 * post the things to us as part of a macro manoeuvre,
3230 * we're ready to cope.
3233 static wchar_t pending_surrogate = 0;
3236 if (IS_HIGH_SURROGATE(c)) {
3237 pending_surrogate = c;
3238 } else if (IS_SURROGATE_PAIR(pending_surrogate, c)) {
3240 pair[0] = pending_surrogate;
3242 term_seen_key_event(term);
3243 luni_send(ldisc, pair, 2, 1);
3244 } else if (!IS_SURROGATE(c)) {
3245 term_seen_key_event(term);
3246 luni_send(ldisc, &c, 1, 1);
3250 case WM_SYSCOLORCHANGE:
3251 if (conf_get_int(conf, CONF_system_colour)) {
3252 /* Refresh palette from system colours. */
3253 /* XXX actually this zaps the entire palette. */
3256 /* Force a repaint of the terminal window. */
3257 term_invalidate(term);
3260 case WM_AGENT_CALLBACK:
3262 struct agent_callback *c = (struct agent_callback *)lParam;
3263 c->callback(c->callback_ctx, c->data, c->len);
3267 case WM_GOT_CLIPDATA:
3268 if (process_clipdata((HGLOBAL)lParam, wParam))
3269 term_do_paste(term);
3272 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
3273 int shift_pressed=0, control_pressed=0;
3275 if (message == WM_MOUSEWHEEL) {
3276 wheel_accumulator += (short)HIWORD(wParam);
3277 shift_pressed=LOWORD(wParam) & MK_SHIFT;
3278 control_pressed=LOWORD(wParam) & MK_CONTROL;
3281 wheel_accumulator += (int)wParam;
3282 if (GetKeyboardState(keys)!=0) {
3283 shift_pressed=keys[VK_SHIFT]&0x80;
3284 control_pressed=keys[VK_CONTROL]&0x80;
3288 /* process events when the threshold is reached */
3289 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
3292 /* reduce amount for next time */
3293 if (wheel_accumulator > 0) {
3295 wheel_accumulator -= WHEEL_DELTA;
3296 } else if (wheel_accumulator < 0) {
3298 wheel_accumulator += WHEEL_DELTA;
3302 if (send_raw_mouse &&
3303 !(conf_get_int(conf, CONF_mouse_override) &&
3305 /* Mouse wheel position is in screen coordinates for
3308 p.x = X_POS(lParam); p.y = Y_POS(lParam);
3309 if (ScreenToClient(hwnd, &p)) {
3310 /* send a mouse-down followed by a mouse up */
3311 term_mouse(term, b, translate_button(b),
3314 TO_CHR_Y(p.y), shift_pressed,
3315 control_pressed, is_alt_pressed());
3316 } /* else: not sure when this can fail */
3318 /* trigger a scroll */
3319 term_scroll(term, 0,
3321 -term->rows / 2 : term->rows / 2);
3329 * Any messages we don't process completely above are passed through to
3330 * DefWindowProc() for default processing.
3332 return DefWindowProcW(hwnd, message, wParam, lParam);
3336 * Move the system caret. (We maintain one, even though it's
3337 * invisible, for the benefit of blind people: apparently some
3338 * helper software tracks the system caret, so we should arrange to
3341 void sys_cursor(void *frontend, int x, int y)
3345 if (!term->has_focus) return;
3348 * Avoid gratuitously re-updating the cursor position and IMM
3349 * window if there's no actual change required.
3351 cx = x * font_width + offset_width;
3352 cy = y * font_height + offset_height;
3353 if (cx == caret_x && cy == caret_y)
3358 sys_cursor_update();
3361 static void sys_cursor_update(void)
3366 if (!term->has_focus) return;
3368 if (caret_x < 0 || caret_y < 0)
3371 SetCaretPos(caret_x, caret_y);
3373 /* IMM calls on Win98 and beyond only */
3374 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3376 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3377 osVersion.dwMinorVersion == 0) return; /* 95 */
3379 /* we should have the IMM functions */
3380 hIMC = ImmGetContext(hwnd);
3381 cf.dwStyle = CFS_POINT;
3382 cf.ptCurrentPos.x = caret_x;
3383 cf.ptCurrentPos.y = caret_y;
3384 ImmSetCompositionWindow(hIMC, &cf);
3386 ImmReleaseContext(hwnd, hIMC);
3390 * Draw a line of text in the window, at given character
3391 * coordinates, in given attributes.
3393 * We are allowed to fiddle with the contents of `text'.
3395 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3396 unsigned long attr, int lattr)
3399 int nfg, nbg, nfont;
3402 int force_manual_underline = 0;
3403 int fnt_width, char_width;
3404 int text_adjust = 0;
3406 int maxlen, remaining, opaque;
3407 int is_cursor = FALSE;
3408 static int *lpDx = NULL;
3409 static int lpDx_len = 0;
3411 int len2; /* for SURROGATE PAIR */
3413 lattr &= LATTR_MODE;
3415 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3417 if (attr & ATTR_WIDE)
3420 /* Only want the left half of double width lines */
3421 if (lattr != LATTR_NORM && x*2 >= term->cols)
3429 if ((attr & TATTR_ACTCURS) && (cursor_type == 0 || term->big_cursor)) {
3430 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3431 /* cursor fg and bg */
3432 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3437 if (vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3438 /* Assume a poorman font is borken in other ways too. */
3448 nfont |= FONT_WIDE + FONT_HIGH;
3451 if (attr & ATTR_NARROW)
3452 nfont |= FONT_NARROW;
3454 #ifdef USES_VTLINE_HACK
3455 /* Special hack for the VT100 linedraw glyphs. */
3456 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3457 switch ((unsigned char) (text[0])) {
3459 text_adjust = -2 * font_height / 5;
3462 text_adjust = -1 * font_height / 5;
3465 text_adjust = font_height / 5;
3468 text_adjust = 2 * font_height / 5;
3471 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3473 text[0] = ucsdata.unitab_xterm['q'];
3474 if (attr & ATTR_UNDER) {
3475 attr &= ~ATTR_UNDER;
3476 force_manual_underline = 1;
3481 /* Anything left as an original character set is unprintable. */
3482 if (DIRECT_CHAR(text[0]) &&
3483 (len < 2 || !IS_SURROGATE_PAIR(text[0], text[1]))) {
3485 for (i = 0; i < len; i++)
3490 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3493 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3494 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3495 if (bold_font_mode == BOLD_FONT && (attr & ATTR_BOLD))
3497 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3498 nfont |= FONT_UNDERLINE;
3499 another_font(nfont);
3500 if (!fonts[nfont]) {
3501 if (nfont & FONT_UNDERLINE)
3502 force_manual_underline = 1;
3503 /* Don't do the same for manual bold, it could be bad news. */
3505 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3507 another_font(nfont);
3509 nfont = FONT_NORMAL;
3510 if (attr & ATTR_REVERSE) {
3515 if (bold_colours && (attr & ATTR_BOLD) && !is_cursor) {
3516 if (nfg < 16) nfg |= 8;
3517 else if (nfg >= 256) nfg |= 1;
3519 if (bold_colours && (attr & ATTR_BLINK)) {
3520 if (nbg < 16) nbg |= 8;
3521 else if (nbg >= 256) nbg |= 1;
3525 SelectObject(hdc, fonts[nfont]);
3526 SetTextColor(hdc, fg);
3527 SetBkColor(hdc, bg);
3528 if (attr & TATTR_COMBINING)
3529 SetBkMode(hdc, TRANSPARENT);
3531 SetBkMode(hdc, OPAQUE);
3534 line_box.right = x + char_width * len;
3535 line_box.bottom = y + font_height;
3536 /* adjust line_box.right for SURROGATE PAIR & VARIATION SELECTOR */
3540 for (i = 0; i < len ; i++) {
3541 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3543 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i], text[i+1])) {
3544 rc_width += char_width;
3546 } else if (IS_LOW_VARSEL(text[i])) {
3549 rc_width += char_width;
3552 line_box.right = line_box.left + rc_width;
3555 /* Only want the left half of double width lines */
3556 if (line_box.right > font_width*term->cols+offset_width)
3557 line_box.right = font_width*term->cols+offset_width;
3559 if (font_varpitch) {
3561 * If we're using a variable-pitch font, we unconditionally
3562 * draw the glyphs one at a time and centre them in their
3563 * character cells (which means in particular that we must
3564 * disable the lpDx mechanism). This gives slightly odd but
3565 * generally reasonable results.
3567 xoffset = char_width / 2;
3568 SetTextAlign(hdc, TA_TOP | TA_CENTER | TA_NOUPDATECP);
3573 * In a fixed-pitch font, we draw the whole string in one go
3574 * in the normal way.
3577 SetTextAlign(hdc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
3582 opaque = TRUE; /* start by erasing the rectangle */
3583 for (remaining = len; remaining > 0;
3584 text += len, remaining -= len, x += char_width * len2) {
3585 len = (maxlen < remaining ? maxlen : remaining);
3586 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3589 if (remaining >= 1 && IS_SURROGATE_PAIR(text[0], text[1]))
3591 if (remaining-len >= 1 && IS_LOW_VARSEL(text[len]))
3593 else if (remaining-len >= 2 &&
3594 IS_HIGH_VARSEL(text[len], text[len+1]))
3598 if (len > lpDx_len) {
3599 lpDx_len = len * 9 / 8 + 16;
3600 lpDx = sresize(lpDx, lpDx_len, int);
3602 if (lpDx_maybe) lpDx_maybe = lpDx;
3607 /* only last char has dx width in SURROGATE PAIR and
3608 * VARIATION sequence */
3609 for (i = 0; i < len; i++) {
3610 lpDx[i] = char_width;
3611 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3612 if (i > 0) lpDx[i-1] = 0;
3615 lpDx[i] = char_width;
3616 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i],text[i+1])) {
3619 lpDx[i] = char_width;
3620 } else if (IS_LOW_VARSEL(text[i])) {
3621 if (i > 0) lpDx[i-1] = 0;
3622 lpDx[i] = char_width;
3627 /* We're using a private area for direct to font. (512 chars.) */
3628 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3629 /* Ho Hum, dbcs fonts are a PITA! */
3630 /* To display on W9x I have to convert to UCS */
3631 static wchar_t *uni_buf = 0;
3632 static int uni_len = 0;
3634 if (len > uni_len) {
3637 uni_buf = snewn(uni_len, wchar_t);
3640 for(nlen = mptr = 0; mptr<len; mptr++) {
3641 uni_buf[nlen] = 0xFFFD;
3642 if (IsDBCSLeadByteEx(ucsdata.font_codepage,
3643 (BYTE) text[mptr])) {
3645 dbcstext[0] = text[mptr] & 0xFF;
3646 dbcstext[1] = text[mptr+1] & 0xFF;
3647 lpDx[nlen] += char_width;
3648 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3649 dbcstext, 2, uni_buf+nlen, 1);
3655 dbcstext[0] = text[mptr] & 0xFF;
3656 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3657 dbcstext, 1, uni_buf+nlen, 1);
3664 ExtTextOutW(hdc, x + xoffset,
3665 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3666 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3667 &line_box, uni_buf, nlen,
3669 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3670 SetBkMode(hdc, TRANSPARENT);
3671 ExtTextOutW(hdc, x + xoffset - 1,
3672 y - font_height * (lattr ==
3673 LATTR_BOT) + text_adjust,
3674 ETO_CLIPPED, &line_box, uni_buf, nlen, lpDx_maybe);
3678 } else if (DIRECT_FONT(text[0])) {
3679 static char *directbuf = NULL;
3680 static int directlen = 0;
3682 if (len > directlen) {
3684 directbuf = sresize(directbuf, directlen, char);
3687 for (i = 0; i < len; i++)
3688 directbuf[i] = text[i] & 0xFF;
3690 ExtTextOut(hdc, x + xoffset,
3691 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3692 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3693 &line_box, directbuf, len, lpDx_maybe);
3694 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3695 SetBkMode(hdc, TRANSPARENT);
3697 /* GRR: This draws the character outside its box and
3698 * can leave 'droppings' even with the clip box! I
3699 * suppose I could loop it one character at a time ...
3702 * Or ... I could do a test print with "W", and use +1
3703 * or -1 for this shift depending on if the leftmost
3704 * column is blank...
3706 ExtTextOut(hdc, x + xoffset - 1,
3707 y - font_height * (lattr ==
3708 LATTR_BOT) + text_adjust,
3709 ETO_CLIPPED, &line_box, directbuf, len, lpDx_maybe);
3712 /* And 'normal' unicode characters */
3713 static WCHAR *wbuf = NULL;
3714 static int wlen = 0;
3720 wbuf = snewn(wlen, WCHAR);
3723 for (i = 0; i < len; i++)
3726 /* print Glyphs as they are, without Windows' Shaping*/
3727 general_textout(hdc, x + xoffset,
3728 y - font_height * (lattr==LATTR_BOT) + text_adjust,
3729 &line_box, wbuf, len, lpDx,
3730 opaque && !(attr & TATTR_COMBINING));
3732 /* And the shadow bold hack. */
3733 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3734 SetBkMode(hdc, TRANSPARENT);
3735 ExtTextOutW(hdc, x + xoffset - 1,
3736 y - font_height * (lattr ==
3737 LATTR_BOT) + text_adjust,
3738 ETO_CLIPPED, &line_box, wbuf, len, lpDx_maybe);
3743 * If we're looping round again, stop erasing the background
3746 SetBkMode(hdc, TRANSPARENT);
3749 if (lattr != LATTR_TOP && (force_manual_underline ||
3750 (und_mode == UND_LINE
3751 && (attr & ATTR_UNDER)))) {
3754 if (lattr == LATTR_BOT)
3755 dec = dec * 2 - font_height;
3757 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3758 MoveToEx(hdc, line_box.left, line_box.top + dec, NULL);
3759 LineTo(hdc, line_box.right, line_box.top + dec);
3760 oldpen = SelectObject(hdc, oldpen);
3761 DeleteObject(oldpen);
3766 * Wrapper that handles combining characters.
3768 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3769 unsigned long attr, int lattr)
3771 if (attr & TATTR_COMBINING) {
3772 unsigned long a = 0;
3774 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3775 if (len >= 2 && IS_SURROGATE_PAIR(text[0], text[1]))
3777 if (len-len0 >= 1 && IS_LOW_VARSEL(text[len0])) {
3778 attr &= ~TATTR_COMBINING;
3779 do_text_internal(ctx, x, y, text, len0+1, attr, lattr);
3782 a = TATTR_COMBINING;
3783 } else if (len-len0 >= 2 && IS_HIGH_VARSEL(text[len0], text[len0+1])) {
3784 attr &= ~TATTR_COMBINING;
3785 do_text_internal(ctx, x, y, text, len0+2, attr, lattr);
3788 a = TATTR_COMBINING;
3790 attr &= ~TATTR_COMBINING;
3794 if (len >= 1 && IS_SURROGATE_PAIR(text[0], text[1])) {
3795 do_text_internal(ctx, x, y, text, 2, attr | a, lattr);
3799 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3803 a = TATTR_COMBINING;
3806 do_text_internal(ctx, x, y, text, len, attr, lattr);
3809 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3810 unsigned long attr, int lattr)
3816 int ctype = cursor_type;
3818 lattr &= LATTR_MODE;
3820 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3821 if (*text != UCSWIDE) {
3822 do_text(ctx, x, y, text, len, attr, lattr);
3826 attr |= TATTR_RIGHTCURS;
3829 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3830 if (attr & ATTR_WIDE)
3837 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3840 pts[0].x = pts[1].x = pts[4].x = x;
3841 pts[2].x = pts[3].x = x + char_width - 1;
3842 pts[0].y = pts[3].y = pts[4].y = y;
3843 pts[1].y = pts[2].y = y + font_height - 1;
3844 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3845 Polyline(hdc, pts, 5);
3846 oldpen = SelectObject(hdc, oldpen);
3847 DeleteObject(oldpen);
3848 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3849 int startx, starty, dx, dy, length, i;
3852 starty = y + descent;
3855 length = char_width;
3858 if (attr & TATTR_RIGHTCURS)
3859 xadjust = char_width - 1;
3860 startx = x + xadjust;
3864 length = font_height;
3866 if (attr & TATTR_ACTCURS) {
3869 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3870 MoveToEx(hdc, startx, starty, NULL);
3871 LineTo(hdc, startx + dx * length, starty + dy * length);
3872 oldpen = SelectObject(hdc, oldpen);
3873 DeleteObject(oldpen);
3875 for (i = 0; i < length; i++) {
3877 SetPixel(hdc, startx, starty, colours[261]);
3886 /* This function gets the actual width of a character in the normal font.
3888 int char_width(Context ctx, int uc) {
3892 /* If the font max is the same as the font ave width then this
3893 * function is a no-op.
3895 if (!font_dualwidth) return 1;
3897 switch (uc & CSET_MASK) {
3899 uc = ucsdata.unitab_line[uc & 0xFF];
3902 uc = ucsdata.unitab_xterm[uc & 0xFF];
3905 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3908 if (DIRECT_FONT(uc)) {
3909 if (ucsdata.dbcs_screenfont) return 1;
3911 /* Speedup, I know of no font where ascii is the wrong width */
3912 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3915 if ( (uc & CSET_MASK) == CSET_ACP ) {
3916 SelectObject(hdc, fonts[FONT_NORMAL]);
3917 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3918 another_font(FONT_OEM);
3919 if (!fonts[FONT_OEM]) return 0;
3921 SelectObject(hdc, fonts[FONT_OEM]);
3925 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3926 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3929 /* Speedup, I know of no font where ascii is the wrong width */
3930 if (uc >= ' ' && uc <= '~') return 1;
3932 SelectObject(hdc, fonts[FONT_NORMAL]);
3933 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3934 /* Okay that one worked */ ;
3935 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3936 /* This should work on 9x too, but it's "less accurate" */ ;
3941 ibuf += font_width / 2 -1;
3947 DECL_WINDOWS_FUNCTION(static, BOOL, FlashWindowEx, (PFLASHWINFO));
3948 DECL_WINDOWS_FUNCTION(static, BOOL, ToUnicodeEx,
3949 (UINT, UINT, const BYTE *, LPWSTR, int, UINT, HKL));
3951 static void init_winfuncs(void)
3953 HMODULE user32_module = load_system32_dll("user32.dll");
3954 GET_WINDOWS_FUNCTION(user32_module, FlashWindowEx);
3955 GET_WINDOWS_FUNCTION(user32_module, ToUnicodeEx);
3959 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3960 * codes. Returns number of bytes used, zero to drop the message,
3961 * -1 to forward the message to Windows, or another negative number
3962 * to indicate a NUL-terminated "special" string.
3964 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3965 unsigned char *output)
3968 int scan, left_alt = 0, key_down, shift_state;
3970 unsigned char *p = output;
3971 static int alt_sum = 0;
3972 int funky_type = conf_get_int(conf, CONF_funky_type);
3973 int no_applic_k = conf_get_int(conf, CONF_no_applic_k);
3974 int ctrlaltkeys = conf_get_int(conf, CONF_ctrlaltkeys);
3975 int nethack_keypad = conf_get_int(conf, CONF_nethack_keypad);
3977 HKL kbd_layout = GetKeyboardLayout(0);
3979 static wchar_t keys_unicode[3];
3980 static int compose_char = 0;
3981 static WPARAM compose_keycode = 0;
3983 r = GetKeyboardState(keystate);
3985 memset(keystate, 0, sizeof(keystate));
3988 #define SHOW_TOASCII_RESULT
3989 { /* Tell us all about key events */
3990 static BYTE oldstate[256];
3991 static int first = 1;
3995 memcpy(oldstate, keystate, sizeof(oldstate));
3998 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
4000 } else if ((HIWORD(lParam) & KF_UP)
4001 && scan == (HIWORD(lParam) & 0xFF)) {
4005 if (wParam >= VK_F1 && wParam <= VK_F20)
4006 debug(("K_F%d", wParam + 1 - VK_F1));
4019 debug(("VK_%02x", wParam));
4021 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
4023 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
4025 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
4026 if (ch >= ' ' && ch <= '~')
4027 debug((", '%c'", ch));
4029 debug((", $%02x", ch));
4031 if (keys_unicode[0])
4032 debug((", KB0=%04x", keys_unicode[0]));
4033 if (keys_unicode[1])
4034 debug((", KB1=%04x", keys_unicode[1]));
4035 if (keys_unicode[2])
4036 debug((", KB2=%04x", keys_unicode[2]));
4038 if ((keystate[VK_SHIFT] & 0x80) != 0)
4040 if ((keystate[VK_CONTROL] & 0x80) != 0)
4042 if ((HIWORD(lParam) & KF_EXTENDED))
4044 if ((HIWORD(lParam) & KF_UP))
4048 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
4049 else if ((HIWORD(lParam) & KF_UP))
4050 oldstate[wParam & 0xFF] ^= 0x80;
4052 oldstate[wParam & 0xFF] ^= 0x81;
4054 for (ch = 0; ch < 256; ch++)
4055 if (oldstate[ch] != keystate[ch])
4056 debug((", M%02x=%02x", ch, keystate[ch]));
4058 memcpy(oldstate, keystate, sizeof(oldstate));
4062 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
4063 keystate[VK_RMENU] = keystate[VK_MENU];
4067 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
4068 if ((funky_type == FUNKY_VT400 ||
4069 (funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
4071 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
4073 wParam = VK_EXECUTE;
4075 /* UnToggle NUMLock */
4076 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
4077 keystate[VK_NUMLOCK] ^= 1;
4080 /* And write back the 'adjusted' state */
4081 SetKeyboardState(keystate);
4084 /* Disable Auto repeat if required */
4085 if (term->repeat_off &&
4086 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
4089 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
4092 key_down = ((HIWORD(lParam) & KF_UP) == 0);
4094 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
4095 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
4097 keystate[VK_MENU] = 0;
4099 keystate[VK_RMENU] = 0x80;
4104 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
4105 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
4106 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
4108 /* Note if AltGr was pressed and if it was used as a compose key */
4109 if (!compose_state) {
4110 compose_keycode = 0x100;
4111 if (conf_get_int(conf, CONF_compose_key)) {
4112 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
4113 compose_keycode = wParam;
4115 if (wParam == VK_APPS)
4116 compose_keycode = wParam;
4119 if (wParam == compose_keycode) {
4120 if (compose_state == 0
4121 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
4123 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
4127 } else if (compose_state == 1 && wParam != VK_CONTROL)
4130 if (compose_state > 1 && left_alt)
4133 /* Sanitize the number pad if not using a PC NumPad */
4134 if (left_alt || (term->app_keypad_keys && !no_applic_k
4135 && funky_type != FUNKY_XTERM)
4136 || funky_type == FUNKY_VT400 || nethack_keypad || compose_state) {
4137 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
4141 nParam = VK_NUMPAD0;
4144 nParam = VK_NUMPAD1;
4147 nParam = VK_NUMPAD2;
4150 nParam = VK_NUMPAD3;
4153 nParam = VK_NUMPAD4;
4156 nParam = VK_NUMPAD5;
4159 nParam = VK_NUMPAD6;
4162 nParam = VK_NUMPAD7;
4165 nParam = VK_NUMPAD8;
4168 nParam = VK_NUMPAD9;
4171 nParam = VK_DECIMAL;
4175 if (keystate[VK_NUMLOCK] & 1)
4182 /* If a key is pressed and AltGr is not active */
4183 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
4184 /* Okay, prepare for most alts then ... */
4188 /* Lets see if it's a pattern we know all about ... */
4189 if (wParam == VK_PRIOR && shift_state == 1) {
4190 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
4193 if (wParam == VK_PRIOR && shift_state == 2) {
4194 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
4197 if (wParam == VK_NEXT && shift_state == 1) {
4198 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
4201 if (wParam == VK_NEXT && shift_state == 2) {
4202 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
4205 if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) {
4206 term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1));
4209 if (wParam == VK_INSERT && shift_state == 1) {
4210 request_paste(NULL);
4213 if (left_alt && wParam == VK_F4 && conf_get_int(conf, CONF_alt_f4)) {
4216 if (left_alt && wParam == VK_SPACE && conf_get_int(conf,
4218 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
4221 if (left_alt && wParam == VK_RETURN &&
4222 conf_get_int(conf, CONF_fullscreenonaltenter) &&
4223 (conf_get_int(conf, CONF_resize_action) != RESIZE_DISABLED)) {
4224 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
4228 /* Control-Numlock for app-keypad mode switch */
4229 if (wParam == VK_PAUSE && shift_state == 2) {
4230 term->app_keypad_keys ^= 1;
4234 /* Nethack keypad */
4235 if (nethack_keypad && !left_alt) {
4238 *p++ = "bB\002\002"[shift_state & 3];
4241 *p++ = "jJ\012\012"[shift_state & 3];
4244 *p++ = "nN\016\016"[shift_state & 3];
4247 *p++ = "hH\010\010"[shift_state & 3];
4250 *p++ = shift_state ? '.' : '.';
4253 *p++ = "lL\014\014"[shift_state & 3];
4256 *p++ = "yY\031\031"[shift_state & 3];
4259 *p++ = "kK\013\013"[shift_state & 3];
4262 *p++ = "uU\025\025"[shift_state & 3];
4267 /* Application Keypad */
4271 if (funky_type == FUNKY_VT400 ||
4272 (funky_type <= FUNKY_LINUX &&
4273 term->app_keypad_keys && !no_applic_k)) switch (wParam) {
4287 if (term->app_keypad_keys && !no_applic_k)
4324 if (funky_type == FUNKY_XTERM) {
4329 } else if (shift_state)
4336 if (funky_type == FUNKY_XTERM)
4340 if (funky_type == FUNKY_XTERM)
4344 if (funky_type == FUNKY_XTERM)
4349 if (HIWORD(lParam) & KF_EXTENDED)
4354 if (term->vt52_mode) {
4355 if (xkey >= 'P' && xkey <= 'S')
4356 p += sprintf((char *) p, "\x1B%c", xkey);
4358 p += sprintf((char *) p, "\x1B?%c", xkey);
4360 p += sprintf((char *) p, "\x1BO%c", xkey);
4365 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
4366 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x7F : 0x08);
4370 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
4371 /* We do the opposite of what is configured */
4372 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x08 : 0x7F);
4376 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
4382 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
4386 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
4390 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
4392 back->special(backhandle, TS_BRK);
4395 if (wParam == VK_PAUSE) { /* Break/Pause */
4400 /* Control-2 to Control-8 are special */
4401 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
4402 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
4405 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
4409 if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) {
4413 if (shift_state == 3 && wParam == 0xDE) {
4414 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
4417 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
4424 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
4425 * for integer decimal nn.)
4427 * We also deal with the weird ones here. Linux VCs replace F1
4428 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
4429 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
4435 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
4438 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
4441 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
4444 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
4447 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
4450 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
4453 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
4456 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
4459 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
4462 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
4495 if ((shift_state&2) == 0) switch (wParam) {
4515 /* Reorder edit keys to physical order */
4516 if (funky_type == FUNKY_VT400 && code <= 6)
4517 code = "\0\2\1\4\5\3\6"[code];
4519 if (term->vt52_mode && code > 0 && code <= 6) {
4520 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4524 if (funky_type == FUNKY_SCO && code >= 11 && code <= 34) {
4525 /* SCO function keys */
4526 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4529 case VK_F1: index = 0; break;
4530 case VK_F2: index = 1; break;
4531 case VK_F3: index = 2; break;
4532 case VK_F4: index = 3; break;
4533 case VK_F5: index = 4; break;
4534 case VK_F6: index = 5; break;
4535 case VK_F7: index = 6; break;
4536 case VK_F8: index = 7; break;
4537 case VK_F9: index = 8; break;
4538 case VK_F10: index = 9; break;
4539 case VK_F11: index = 10; break;
4540 case VK_F12: index = 11; break;
4542 if (keystate[VK_SHIFT] & 0x80) index += 12;
4543 if (keystate[VK_CONTROL] & 0x80) index += 24;
4544 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4547 if (funky_type == FUNKY_SCO && /* SCO small keypad */
4548 code >= 1 && code <= 6) {
4549 char codes[] = "HL.FIG";
4553 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4557 if ((term->vt52_mode || funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4563 if (term->vt52_mode)
4564 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4567 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4570 if (funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4571 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4574 if (funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4575 if (term->vt52_mode)
4576 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4578 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4581 if ((code == 1 || code == 4) &&
4582 conf_get_int(conf, CONF_rxvt_homeend)) {
4583 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4587 p += sprintf((char *) p, "\x1B[%d~", code);
4592 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4593 * some reason seems to send VK_CLEAR to Windows...).
4615 p += format_arrow_key(p, term, xkey, shift_state);
4621 * Finally, deal with Return ourselves. (Win95 seems to
4622 * foul it up when Alt is pressed, for some reason.)
4624 if (wParam == VK_RETURN) { /* Return */
4630 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4631 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4636 /* Okay we've done everything interesting; let windows deal with
4637 * the boring stuff */
4641 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4642 if(keystate[VK_CAPITAL] != 0 &&
4643 conf_get_int(conf, CONF_xlat_capslockcyr)) {
4645 keystate[VK_CAPITAL] = 0;
4648 /* XXX how do we know what the max size of the keys array should
4649 * be is? There's indication on MS' website of an Inquire/InquireEx
4650 * functioning returning a KBINFO structure which tells us. */
4651 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT && p_ToUnicodeEx) {
4652 r = p_ToUnicodeEx(wParam, scan, keystate, keys_unicode,
4653 lenof(keys_unicode), 0, kbd_layout);
4655 /* XXX 'keys' parameter is declared in MSDN documentation as
4657 * The experience of a French user indicates that on
4658 * Win98, WORD[] should be passed in, but on Win2K, it should
4659 * be BYTE[]. German WinXP and my Win2K with "US International"
4660 * driver corroborate this.
4661 * Experimentally I've conditionalised the behaviour on the
4662 * Win9x/NT split, but I suspect it's worse than that.
4663 * See wishlist item `win-dead-keys' for more horrible detail
4664 * and speculations. */
4666 static WORD keys[3];
4667 static BYTE keysb[3];
4668 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4670 for (i = 0; i < r; i++) {
4671 keysb[i] = (BYTE)keys[i];
4673 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)keysb, r,
4674 keys_unicode, lenof(keys_unicode));
4677 #ifdef SHOW_TOASCII_RESULT
4678 if (r == 1 && !key_down) {
4680 if (in_utf(term) || ucsdata.dbcs_screenfont)
4681 debug((", (U+%04x)", alt_sum));
4683 debug((", LCH(%d)", alt_sum));
4685 debug((", ACH(%d)", keys_unicode[0]));
4690 for (r1 = 0; r1 < r; r1++) {
4691 debug(("%s%d", r1 ? "," : "", keys_unicode[r1]));
4700 for (i = 0; i < r; i++) {
4701 wchar_t wch = keys_unicode[i];
4703 if (compose_state == 2 && wch >= ' ' && wch < 0x80) {
4708 if (compose_state == 3 && wch >= ' ' && wch < 0x80) {
4712 if ((nc = check_compose(compose_char, wch)) == -1) {
4713 MessageBeep(MB_ICONHAND);
4717 term_seen_key_event(term);
4719 luni_send(ldisc, &keybuf, 1, 1);
4727 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4729 term_seen_key_event(term);
4731 luni_send(ldisc, &keybuf, 1, 1);
4733 char ch = (char) alt_sum;
4735 * We need not bother about stdin
4736 * backlogs here, because in GUI PuTTY
4737 * we can't do anything about it
4738 * anyway; there's no means of asking
4739 * Windows to hold off on KEYDOWN
4740 * messages. We _have_ to buffer
4741 * everything we're sent.
4743 term_seen_key_event(term);
4745 ldisc_send(ldisc, &ch, 1, 1);
4749 term_seen_key_event(term);
4751 luni_send(ldisc, &wch, 1, 1);
4754 if(capsOn && wch < 0x80) {
4757 cbuf[1] = xlat_uskbd2cyrllic(wch);
4758 term_seen_key_event(term);
4760 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4765 term_seen_key_event(term);
4767 luni_send(ldisc, cbuf +!left_alt, 1+!!left_alt, 1);
4773 /* This is so the ALT-Numpad and dead keys work correctly. */
4774 keys_unicode[0] = 0;
4778 /* If we're definitly not building up an ALT-54321 then clear it */
4780 keys_unicode[0] = 0;
4781 /* If we will be using alt_sum fix the 256s */
4782 else if (keys_unicode[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4783 keys_unicode[0] = 10;
4787 * ALT alone may or may not want to bring up the System menu.
4788 * If it's not meant to, we return 0 on presses or releases of
4789 * ALT, to show that we've swallowed the keystroke. Otherwise
4790 * we return -1, which means Windows will give the keystroke
4791 * its default handling (i.e. bring up the System menu).
4793 if (wParam == VK_MENU && !conf_get_int(conf, CONF_alt_only))
4799 void set_title(void *frontend, char *title)
4802 window_name = snewn(1 + strlen(title), char);
4803 strcpy(window_name, title);
4804 if (conf_get_int(conf, CONF_win_name_always) || !IsIconic(hwnd))
4805 SetWindowText(hwnd, title);
4808 void set_icon(void *frontend, char *title)
4811 icon_name = snewn(1 + strlen(title), char);
4812 strcpy(icon_name, title);
4813 if (!conf_get_int(conf, CONF_win_name_always) && IsIconic(hwnd))
4814 SetWindowText(hwnd, title);
4817 void set_sbar(void *frontend, int total, int start, int page)
4821 if (!conf_get_int(conf, is_full_screen() ?
4822 CONF_scrollbar_in_fullscreen : CONF_scrollbar))
4825 si.cbSize = sizeof(si);
4826 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4828 si.nMax = total - 1;
4832 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4835 Context get_ctx(void *frontend)
4841 SelectPalette(hdc, pal, FALSE);
4847 void free_ctx(Context ctx)
4849 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4850 ReleaseDC(hwnd, ctx);
4853 static void real_palette_set(int n, int r, int g, int b)
4856 logpal->palPalEntry[n].peRed = r;
4857 logpal->palPalEntry[n].peGreen = g;
4858 logpal->palPalEntry[n].peBlue = b;
4859 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4860 colours[n] = PALETTERGB(r, g, b);
4861 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4863 colours[n] = RGB(r, g, b);
4866 void palette_set(void *frontend, int n, int r, int g, int b)
4870 if (n >= NALLCOLOURS)
4872 real_palette_set(n, r, g, b);
4874 HDC hdc = get_ctx(frontend);
4875 UnrealizeObject(pal);
4876 RealizePalette(hdc);
4879 if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))
4880 /* If Default Background changes, we need to ensure any
4881 * space between the text area and the window border is
4883 InvalidateRect(hwnd, NULL, TRUE);
4887 void palette_reset(void *frontend)
4892 for (i = 0; i < NALLCOLOURS; i++) {
4894 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4895 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4896 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4897 logpal->palPalEntry[i].peFlags = 0;
4898 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4899 defpal[i].rgbtGreen,
4900 defpal[i].rgbtBlue);
4902 colours[i] = RGB(defpal[i].rgbtRed,
4903 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4908 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4909 hdc = get_ctx(frontend);
4910 RealizePalette(hdc);
4913 /* Default Background may have changed. Ensure any space between
4914 * text area and window border is redrawn. */
4915 InvalidateRect(hwnd, NULL, TRUE);
4919 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4924 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4927 lock = GlobalLock(clipdata);
4930 memcpy(lock, data, len);
4931 ((unsigned char *) lock)[len] = 0;
4932 GlobalUnlock(clipdata);
4935 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4937 if (OpenClipboard(hwnd)) {
4939 SetClipboardData(CF_TEXT, clipdata);
4942 GlobalFree(clipdata);
4945 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4949 * Note: unlike write_aclip() this will not append a nul.
4951 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
4953 HGLOBAL clipdata, clipdata2, clipdata3;
4955 void *lock, *lock2, *lock3;
4957 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4959 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4960 len * sizeof(wchar_t));
4961 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4963 if (!clipdata || !clipdata2) {
4965 GlobalFree(clipdata);
4967 GlobalFree(clipdata2);
4970 if (!(lock = GlobalLock(clipdata))) {
4971 GlobalFree(clipdata);
4972 GlobalFree(clipdata2);
4975 if (!(lock2 = GlobalLock(clipdata2))) {
4976 GlobalUnlock(clipdata);
4977 GlobalFree(clipdata);
4978 GlobalFree(clipdata2);
4982 memcpy(lock, data, len * sizeof(wchar_t));
4983 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4985 if (conf_get_int(conf, CONF_rtf_paste)) {
4986 wchar_t unitab[256];
4988 unsigned char *tdata = (unsigned char *)lock2;
4989 wchar_t *udata = (wchar_t *)lock;
4990 int rtflen = 0, uindex = 0, tindex = 0;
4992 int multilen, blen, alen, totallen, i;
4993 char before[16], after[4];
4994 int fgcolour, lastfgcolour = 0;
4995 int bgcolour, lastbgcolour = 0;
4996 int attrBold, lastAttrBold = 0;
4997 int attrUnder, lastAttrUnder = 0;
4998 int palette[NALLCOLOURS];
5000 FontSpec *font = conf_get_fontspec(conf, CONF_font);
5002 get_unitab(CP_ACP, unitab, 0);
5004 rtfsize = 100 + strlen(font->name);
5005 rtf = snewn(rtfsize, char);
5006 rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
5007 font->name, font->height*2);
5010 * Add colour palette
5011 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
5015 * First - Determine all colours in use
5016 * o Foregound and background colours share the same palette
5019 memset(palette, 0, sizeof(palette));
5020 for (i = 0; i < (len-1); i++) {
5021 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5022 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5024 if (attr[i] & ATTR_REVERSE) {
5025 int tmpcolour = fgcolour; /* Swap foreground and background */
5026 fgcolour = bgcolour;
5027 bgcolour = tmpcolour;
5030 if (bold_colours && (attr[i] & ATTR_BOLD)) {
5031 if (fgcolour < 8) /* ANSI colours */
5033 else if (fgcolour >= 256) /* Default colours */
5037 if (attr[i] & ATTR_BLINK) {
5038 if (bgcolour < 8) /* ANSI colours */
5040 else if (bgcolour >= 256) /* Default colours */
5044 palette[fgcolour]++;
5045 palette[bgcolour]++;
5049 * Next - Create a reduced palette
5052 for (i = 0; i < NALLCOLOURS; i++) {
5053 if (palette[i] != 0)
5054 palette[i] = ++numcolours;
5058 * Finally - Write the colour table
5060 rtf = sresize(rtf, rtfsize + (numcolours * 25), char);
5061 strcat(rtf, "{\\colortbl ;");
5062 rtflen = strlen(rtf);
5064 for (i = 0; i < NALLCOLOURS; i++) {
5065 if (palette[i] != 0) {
5066 rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);
5069 strcpy(&rtf[rtflen], "}");
5074 * We want to construct a piece of RTF that specifies the
5075 * same Unicode text. To do this we will read back in
5076 * parallel from the Unicode data in `udata' and the
5077 * non-Unicode data in `tdata'. For each character in
5078 * `tdata' which becomes the right thing in `udata' when
5079 * looked up in `unitab', we just copy straight over from
5080 * tdata. For each one that doesn't, we must WCToMB it
5081 * individually and produce a \u escape sequence.
5083 * It would probably be more robust to just bite the bullet
5084 * and WCToMB each individual Unicode character one by one,
5085 * then MBToWC each one back to see if it was an accurate
5086 * translation; but that strikes me as a horrifying number
5087 * of Windows API calls so I want to see if this faster way
5088 * will work. If it screws up badly we can always revert to
5089 * the simple and slow way.
5091 while (tindex < len2 && uindex < len &&
5092 tdata[tindex] && udata[uindex]) {
5093 if (tindex + 1 < len2 &&
5094 tdata[tindex] == '\r' &&
5095 tdata[tindex+1] == '\n') {
5101 * Set text attributes
5104 if (rtfsize < rtflen + 64) {
5105 rtfsize = rtflen + 512;
5106 rtf = sresize(rtf, rtfsize, char);
5110 * Determine foreground and background colours
5112 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5113 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5115 if (attr[tindex] & ATTR_REVERSE) {
5116 int tmpcolour = fgcolour; /* Swap foreground and background */
5117 fgcolour = bgcolour;
5118 bgcolour = tmpcolour;
5121 if (bold_colours && (attr[tindex] & ATTR_BOLD)) {
5122 if (fgcolour < 8) /* ANSI colours */
5124 else if (fgcolour >= 256) /* Default colours */
5128 if (attr[tindex] & ATTR_BLINK) {
5129 if (bgcolour < 8) /* ANSI colours */
5131 else if (bgcolour >= 256) /* Default colours */
5136 * Collect other attributes
5138 if (bold_font_mode != BOLD_NONE)
5139 attrBold = attr[tindex] & ATTR_BOLD;
5143 attrUnder = attr[tindex] & ATTR_UNDER;
5147 * o If video isn't reversed, ignore colour attributes for default foregound
5149 * o Special case where bolded text is displayed using the default foregound
5150 * and background colours - force to bolded RTF.
5152 if (!(attr[tindex] & ATTR_REVERSE)) {
5153 if (bgcolour >= 256) /* Default color */
5154 bgcolour = -1; /* No coloring */
5156 if (fgcolour >= 256) { /* Default colour */
5157 if (bold_colours && (fgcolour & 1) && bgcolour == -1)
5158 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
5160 fgcolour = -1; /* No coloring */
5165 * Write RTF text attributes
5167 if (lastfgcolour != fgcolour) {
5168 lastfgcolour = fgcolour;
5169 rtflen += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
5172 if (lastbgcolour != bgcolour) {
5173 lastbgcolour = bgcolour;
5174 rtflen += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
5177 if (lastAttrBold != attrBold) {
5178 lastAttrBold = attrBold;
5179 rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
5182 if (lastAttrUnder != attrUnder) {
5183 lastAttrUnder = attrUnder;
5184 rtflen += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
5188 if (unitab[tdata[tindex]] == udata[uindex]) {
5194 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
5195 NULL, 0, NULL, NULL);
5196 if (multilen != 1) {
5197 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
5199 alen = 1; strcpy(after, "}");
5201 blen = sprintf(before, "\\u%d", udata[uindex]);
5202 alen = 0; after[0] = '\0';
5205 assert(tindex + multilen <= len2);
5206 totallen = blen + alen;
5207 for (i = 0; i < multilen; i++) {
5208 if (tdata[tindex+i] == '\\' ||
5209 tdata[tindex+i] == '{' ||
5210 tdata[tindex+i] == '}')
5212 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
5213 totallen += 6; /* \par\r\n */
5214 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
5220 if (rtfsize < rtflen + totallen + 3) {
5221 rtfsize = rtflen + totallen + 512;
5222 rtf = sresize(rtf, rtfsize, char);
5225 strcpy(rtf + rtflen, before); rtflen += blen;
5226 for (i = 0; i < multilen; i++) {
5227 if (tdata[tindex+i] == '\\' ||
5228 tdata[tindex+i] == '{' ||
5229 tdata[tindex+i] == '}') {
5230 rtf[rtflen++] = '\\';
5231 rtf[rtflen++] = tdata[tindex+i];
5232 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
5233 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
5234 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
5235 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
5237 rtf[rtflen++] = tdata[tindex+i];
5240 strcpy(rtf + rtflen, after); rtflen += alen;
5246 rtf[rtflen++] = '}'; /* Terminate RTF stream */
5247 rtf[rtflen++] = '\0';
5248 rtf[rtflen++] = '\0';
5250 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
5251 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
5252 memcpy(lock3, rtf, rtflen);
5253 GlobalUnlock(clipdata3);
5259 GlobalUnlock(clipdata);
5260 GlobalUnlock(clipdata2);
5263 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
5265 if (OpenClipboard(hwnd)) {
5267 SetClipboardData(CF_UNICODETEXT, clipdata);
5268 SetClipboardData(CF_TEXT, clipdata2);
5270 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
5273 GlobalFree(clipdata);
5274 GlobalFree(clipdata2);
5278 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
5281 static DWORD WINAPI clipboard_read_threadfunc(void *param)
5283 HWND hwnd = (HWND)param;
5286 if (OpenClipboard(NULL)) {
5287 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
5288 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)1, (LPARAM)clipdata);
5289 } else if ((clipdata = GetClipboardData(CF_TEXT))) {
5290 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)0, (LPARAM)clipdata);
5298 static int process_clipdata(HGLOBAL clipdata, int unicode)
5300 sfree(clipboard_contents);
5301 clipboard_contents = NULL;
5302 clipboard_length = 0;
5305 wchar_t *p = GlobalLock(clipdata);
5309 /* Unwilling to rely on Windows having wcslen() */
5310 for (p2 = p; *p2; p2++);
5311 clipboard_length = p2 - p;
5312 clipboard_contents = snewn(clipboard_length + 1, wchar_t);
5313 memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t));
5314 clipboard_contents[clipboard_length] = L'\0';
5318 char *s = GlobalLock(clipdata);
5322 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
5323 clipboard_contents = snewn(i, wchar_t);
5324 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1,
5325 clipboard_contents, i);
5326 clipboard_length = i - 1;
5327 clipboard_contents[clipboard_length] = L'\0';
5335 void request_paste(void *frontend)
5338 * I always thought pasting was synchronous in Windows; the
5339 * clipboard access functions certainly _look_ synchronous,
5340 * unlike the X ones. But in fact it seems that in some
5341 * situations the contents of the clipboard might not be
5342 * immediately available, and the clipboard-reading functions
5343 * may block. This leads to trouble if the application
5344 * delivering the clipboard data has to get hold of it by -
5345 * for example - talking over a network connection which is
5346 * forwarded through this very PuTTY.
5348 * Hence, we spawn a subthread to read the clipboard, and do
5349 * our paste when it's finished. The thread will send a
5350 * message back to our main window when it terminates, and
5351 * that tells us it's OK to paste.
5353 DWORD in_threadid; /* required for Win9x */
5354 CreateThread(NULL, 0, clipboard_read_threadfunc,
5355 hwnd, 0, &in_threadid);
5358 void get_clip(void *frontend, wchar_t **p, int *len)
5361 *p = clipboard_contents;
5362 *len = clipboard_length;
5368 * Move `lines' lines from position `from' to position `to' in the
5371 void optimised_move(void *frontend, int to, int from, int lines)
5376 min = (to < from ? to : from);
5377 max = to + from - min;
5379 r.left = offset_width;
5380 r.right = offset_width + term->cols * font_width;
5381 r.top = offset_height + min * font_height;
5382 r.bottom = offset_height + (max + lines) * font_height;
5383 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
5388 * Print a message box and perform a fatal exit.
5390 void fatalbox(const char *fmt, ...)
5393 char *stuff, morestuff[100];
5396 stuff = dupvprintf(fmt, ap);
5398 sprintf(morestuff, "%.70s Fatal Error", appname);
5399 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5405 * Print a modal (Really Bad) message box and perform a fatal exit.
5407 void modalfatalbox(const char *fmt, ...)
5410 char *stuff, morestuff[100];
5413 stuff = dupvprintf(fmt, ap);
5415 sprintf(morestuff, "%.70s Fatal Error", appname);
5416 MessageBox(hwnd, stuff, morestuff,
5417 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
5423 * Print a message box and don't close the connection.
5425 void nonfatal(const char *fmt, ...)
5428 char *stuff, morestuff[100];
5431 stuff = dupvprintf(fmt, ap);
5433 sprintf(morestuff, "%.70s Error", appname);
5434 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5438 static BOOL flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout)
5440 if (p_FlashWindowEx) {
5442 fi.cbSize = sizeof(fi);
5444 fi.dwFlags = dwFlags;
5446 fi.dwTimeout = dwTimeout;
5447 return (*p_FlashWindowEx)(&fi);
5450 return FALSE; /* shrug */
5453 static void flash_window(int mode);
5454 static long next_flash;
5455 static int flashing = 0;
5458 * Timer for platforms where we must maintain window flashing manually
5461 static void flash_window_timer(void *ctx, unsigned long now)
5463 if (flashing && now == next_flash) {
5469 * Manage window caption / taskbar flashing, if enabled.
5470 * 0 = stop, 1 = maintain, 2 = start
5472 static void flash_window(int mode)
5474 int beep_ind = conf_get_int(conf, CONF_beep_ind);
5475 if ((mode == 0) || (beep_ind == B_IND_DISABLED)) {
5479 if (p_FlashWindowEx)
5480 flash_window_ex(FLASHW_STOP, 0, 0);
5482 FlashWindow(hwnd, FALSE);
5485 } else if (mode == 2) {
5489 if (p_FlashWindowEx) {
5490 /* For so-called "steady" mode, we use uCount=2, which
5491 * seems to be the traditional number of flashes used
5492 * by user notifications (e.g., by Explorer).
5493 * uCount=0 appears to enable continuous flashing, per
5494 * "flashing" mode, although I haven't seen this
5496 flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
5497 (beep_ind == B_IND_FLASH ? 0 : 2),
5498 0 /* system cursor blink rate */);
5499 /* No need to schedule timer */
5501 FlashWindow(hwnd, TRUE);
5502 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5506 } else if ((mode == 1) && (beep_ind == B_IND_FLASH)) {
5508 if (flashing && !p_FlashWindowEx) {
5509 FlashWindow(hwnd, TRUE); /* toggle */
5510 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5518 void do_beep(void *frontend, int mode)
5520 if (mode == BELL_DEFAULT) {
5522 * For MessageBeep style bells, we want to be careful of
5523 * timing, because they don't have the nice property of
5524 * PlaySound bells that each one cancels the previous
5525 * active one. So we limit the rate to one per 50ms or so.
5527 static long lastbeep = 0;
5530 beepdiff = GetTickCount() - lastbeep;
5531 if (beepdiff >= 0 && beepdiff < 50)
5535 * The above MessageBeep call takes time, so we record the
5536 * time _after_ it finishes rather than before it starts.
5538 lastbeep = GetTickCount();
5539 } else if (mode == BELL_WAVEFILE) {
5540 Filename *bell_wavefile = conf_get_filename(conf, CONF_bell_wavefile);
5541 if (!PlaySound(bell_wavefile->path, NULL,
5542 SND_ASYNC | SND_FILENAME)) {
5543 char buf[sizeof(bell_wavefile->path) + 80];
5545 sprintf(buf, "Unable to play sound file\n%s\n"
5546 "Using default sound instead", bell_wavefile->path);
5547 sprintf(otherbuf, "%.70s Sound Error", appname);
5548 MessageBox(hwnd, buf, otherbuf,
5549 MB_OK | MB_ICONEXCLAMATION);
5550 conf_set_int(conf, CONF_beep, BELL_DEFAULT);
5552 } else if (mode == BELL_PCSPEAKER) {
5553 static long lastbeep = 0;
5556 beepdiff = GetTickCount() - lastbeep;
5557 if (beepdiff >= 0 && beepdiff < 50)
5561 * We must beep in different ways depending on whether this
5562 * is a 95-series or NT-series OS.
5564 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
5568 lastbeep = GetTickCount();
5570 /* Otherwise, either visual bell or disabled; do nothing here */
5571 if (!term->has_focus) {
5572 flash_window(2); /* start */
5577 * Minimise or restore the window in response to a server-side
5580 void set_iconic(void *frontend, int iconic)
5582 if (IsIconic(hwnd)) {
5584 ShowWindow(hwnd, SW_RESTORE);
5587 ShowWindow(hwnd, SW_MINIMIZE);
5592 * Move the window in response to a server-side request.
5594 void move_window(void *frontend, int x, int y)
5596 int resize_action = conf_get_int(conf, CONF_resize_action);
5597 if (resize_action == RESIZE_DISABLED ||
5598 resize_action == RESIZE_FONT ||
5602 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5606 * Move the window to the top or bottom of the z-order in response
5607 * to a server-side request.
5609 void set_zorder(void *frontend, int top)
5611 if (conf_get_int(conf, CONF_alwaysontop))
5612 return; /* ignore */
5613 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5614 SWP_NOMOVE | SWP_NOSIZE);
5618 * Refresh the window in response to a server-side request.
5620 void refresh_window(void *frontend)
5622 InvalidateRect(hwnd, NULL, TRUE);
5626 * Maximise or restore the window in response to a server-side
5629 void set_zoomed(void *frontend, int zoomed)
5631 if (IsZoomed(hwnd)) {
5633 ShowWindow(hwnd, SW_RESTORE);
5636 ShowWindow(hwnd, SW_MAXIMIZE);
5641 * Report whether the window is iconic, for terminal reports.
5643 int is_iconic(void *frontend)
5645 return IsIconic(hwnd);
5649 * Report the window's position, for terminal reports.
5651 void get_window_pos(void *frontend, int *x, int *y)
5654 GetWindowRect(hwnd, &r);
5660 * Report the window's pixel size, for terminal reports.
5662 void get_window_pixels(void *frontend, int *x, int *y)
5665 GetWindowRect(hwnd, &r);
5666 *x = r.right - r.left;
5667 *y = r.bottom - r.top;
5671 * Return the window or icon title.
5673 char *get_window_title(void *frontend, int icon)
5675 return icon ? icon_name : window_name;
5679 * See if we're in full-screen mode.
5681 static int is_full_screen()
5683 if (!IsZoomed(hwnd))
5685 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
5690 /* Get the rect/size of a full screen window using the nearest available
5691 * monitor in multimon systems; default to something sensible if only
5692 * one monitor is present. */
5693 static int get_fullscreen_rect(RECT * ss)
5695 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
5698 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
5699 mi.cbSize = sizeof(mi);
5700 GetMonitorInfo(mon, &mi);
5702 /* structure copy */
5706 /* could also use code like this:
5707 ss->left = ss->top = 0;
5708 ss->right = GetSystemMetrics(SM_CXSCREEN);
5709 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5711 return GetClientRect(GetDesktopWindow(), ss);
5717 * Go full-screen. This should only be called when we are already
5720 static void make_full_screen()
5725 assert(IsZoomed(hwnd));
5727 if (is_full_screen())
5730 /* Remove the window furniture. */
5731 style = GetWindowLongPtr(hwnd, GWL_STYLE);
5732 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5733 if (conf_get_int(conf, CONF_scrollbar_in_fullscreen))
5734 style |= WS_VSCROLL;
5736 style &= ~WS_VSCROLL;
5737 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5739 /* Resize ourselves to exactly cover the nearest monitor. */
5740 get_fullscreen_rect(&ss);
5741 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5746 /* We may have changed size as a result */
5750 /* Tick the menu item in the System and context menus. */
5753 for (i = 0; i < lenof(popup_menus); i++)
5754 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED);
5759 * Clear the full-screen attributes.
5761 static void clear_full_screen()
5763 DWORD oldstyle, style;
5765 /* Reinstate the window furniture. */
5766 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
5767 style |= WS_CAPTION | WS_BORDER;
5768 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
5769 style &= ~WS_THICKFRAME;
5771 style |= WS_THICKFRAME;
5772 if (conf_get_int(conf, CONF_scrollbar))
5773 style |= WS_VSCROLL;
5775 style &= ~WS_VSCROLL;
5776 if (style != oldstyle) {
5777 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5778 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5779 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5783 /* Untick the menu item in the System and context menus. */
5786 for (i = 0; i < lenof(popup_menus); i++)
5787 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED);
5792 * Toggle full-screen mode.
5794 static void flip_full_screen()
5796 if (is_full_screen()) {
5797 ShowWindow(hwnd, SW_RESTORE);
5798 } else if (IsZoomed(hwnd)) {
5801 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5802 ShowWindow(hwnd, SW_MAXIMIZE);
5806 void frontend_keypress(void *handle)
5809 * Keypress termination in non-Close-On-Exit mode is not
5810 * currently supported in PuTTY proper, because the window
5811 * always has a perfectly good Close button anyway. So we do
5817 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5819 return term_data(term, is_stderr, data, len);
5822 int from_backend_untrusted(void *frontend, const char *data, int len)
5824 return term_data_untrusted(term, data, len);
5827 int from_backend_eof(void *frontend)
5829 return TRUE; /* do respond to incoming EOF with outgoing */
5832 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
5835 ret = cmdline_get_passwd_input(p, in, inlen);
5837 ret = term_get_userpass_input(term, p, in, inlen);
5841 void agent_schedule_callback(void (*callback)(void *, void *, int),
5842 void *callback_ctx, void *data, int len)
5844 struct agent_callback *c = snew(struct agent_callback);
5845 c->callback = callback;
5846 c->callback_ctx = callback_ctx;
5849 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);