2 * window.c - the PuTTY(tel) main program, which runs a PuTTY terminal
3 * emulator and backend in a window.
14 #define COMPILE_MULTIMON_STUBS
17 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
33 /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
34 * wParam are used by Windows, and should be masked off, so we shouldn't
35 * attempt to store information in them. Hence all these identifiers have
36 * the low 4 bits clear. Also, identifiers should < 0xF000. */
38 #define IDM_SHOWLOG 0x0010
39 #define IDM_NEWSESS 0x0020
40 #define IDM_DUPSESS 0x0030
41 #define IDM_RESTART 0x0040
42 #define IDM_RECONF 0x0050
43 #define IDM_CLRSB 0x0060
44 #define IDM_RESET 0x0070
45 #define IDM_HELP 0x0140
46 #define IDM_ABOUT 0x0150
47 #define IDM_SAVEDSESS 0x0160
48 #define IDM_COPYALL 0x0170
49 #define IDM_FULLSCREEN 0x0180
50 #define IDM_PASTE 0x0190
51 #define IDM_SPECIALSEP 0x0200
53 #define IDM_SPECIAL_MIN 0x0400
54 #define IDM_SPECIAL_MAX 0x0800
56 #define IDM_SAVED_MIN 0x1000
57 #define IDM_SAVED_MAX 0x5000
58 #define MENU_SAVED_STEP 16
59 /* Maximum number of sessions on saved-session submenu */
60 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
62 #define WM_IGNORE_CLIP (WM_APP + 2)
63 #define WM_FULLSCR_ON_MAX (WM_APP + 3)
64 #define WM_AGENT_CALLBACK (WM_APP + 4)
65 #define WM_GOT_CLIPDATA (WM_APP + 6)
67 /* Needed for Chinese support and apparently not always defined. */
69 #define VK_PROCESSKEY 0xE5
72 /* Mouse wheel support. */
74 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
77 #define WHEEL_DELTA 120
80 /* VK_PACKET, used to send Unicode characters in WM_KEYDOWNs */
82 #define VK_PACKET 0xE7
85 static Mouse_Button translate_button(Mouse_Button button);
86 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
87 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
88 unsigned char *output);
89 static void conftopalette(void);
90 static void systopalette(void);
91 static void init_palette(void);
92 static void init_fonts(int, int);
93 static void another_font(int);
94 static void deinit_fonts(void);
95 static void set_input_locale(HKL);
96 static void update_savedsess_menu(void);
97 static void init_winfuncs(void);
99 static int is_full_screen(void);
100 static void make_full_screen(void);
101 static void clear_full_screen(void);
102 static void flip_full_screen(void);
103 static int process_clipdata(HGLOBAL clipdata, int unicode);
105 /* Window layout information */
106 static void reset_window(int);
107 static int extra_width, extra_height;
108 static int font_width, font_height, font_dualwidth, font_varpitch;
109 static int offset_width, offset_height;
110 static int was_zoomed = 0;
111 static int prev_rows, prev_cols;
113 static void flash_window(int mode);
114 static void sys_cursor_update(void);
115 static int get_fullscreen_rect(RECT * ss);
117 static int caret_x = -1, caret_y = -1;
119 static int kbd_codepage;
122 static Backend *back;
123 static void *backhandle;
125 static struct unicode_data ucsdata;
126 static int session_closed;
127 static int reconfiguring = FALSE;
129 static const struct telnet_special *specials = NULL;
130 static HMENU specials_menu = NULL;
131 static int n_specials = 0;
133 static wchar_t *clipboard_contents;
134 static size_t clipboard_length;
136 #define TIMING_TIMER_ID 1234
137 static long timing_next_time;
142 enum { SYSMENU, CTXMENU };
143 static HMENU savedsess_menu;
145 struct wm_netevent_params {
146 /* Used to pass data to wm_netevent_callback */
151 Conf *conf; /* exported to windlg.c */
153 static void conf_cache_data(void);
157 static struct sesslist sesslist; /* for saved-session menu */
159 struct agent_callback {
160 void (*callback)(void *, void *, int);
166 #define FONT_NORMAL 0
168 #define FONT_UNDERLINE 2
169 #define FONT_BOLDUND 3
170 #define FONT_WIDE 0x04
171 #define FONT_HIGH 0x08
172 #define FONT_NARROW 0x10
174 #define FONT_OEM 0x20
175 #define FONT_OEMBOLD 0x21
176 #define FONT_OEMUND 0x22
177 #define FONT_OEMBOLDUND 0x23
179 #define FONT_MAXNO 0x40
181 static HFONT fonts[FONT_MAXNO];
182 static LOGFONT lfont;
183 static int fontflag[FONT_MAXNO];
185 BOLD_NONE, BOLD_SHADOW, BOLD_FONT
187 static int bold_colours;
193 #define NCFGCOLOURS 22
194 #define NEXTCOLOURS 240
195 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
196 static COLORREF colours[NALLCOLOURS];
198 static LPLOGPALETTE logpal;
199 static RGBTRIPLE defpal[NALLCOLOURS];
201 static HBITMAP caretbm;
203 static int dbltime, lasttime, lastact;
204 static Mouse_Button lastbtn;
206 /* this allows xterm-style mouse handling. */
207 static int send_raw_mouse = 0;
208 static int wheel_accumulator = 0;
210 static int busy_status = BUSY_NOT;
212 static char *window_name, *icon_name;
214 static int compose_state = 0;
216 static UINT wm_mousewheel = WM_MOUSEWHEEL;
218 #define IS_HIGH_VARSEL(wch1, wch2) \
219 ((wch1) == 0xDB40 && ((wch2) >= 0xDD00 && (wch2) <= 0xDDEF))
220 #define IS_LOW_VARSEL(wch) \
221 (((wch) >= 0x180B && (wch) <= 0x180D) || /* MONGOLIAN FREE VARIATION SELECTOR */ \
222 ((wch) >= 0xFE00 && (wch) <= 0xFE0F)) /* VARIATION SELECTOR 1-16 */
224 const int share_can_be_downstream = TRUE;
225 const int share_can_be_upstream = TRUE;
227 /* Dummy routine, only required in plink. */
228 void frontend_echoedit_update(void *frontend, int echo, int edit)
232 int frontend_is_utf8(void *frontend)
234 return ucsdata.line_codepage == CP_UTF8;
237 char *get_ttymode(void *frontend, const char *mode)
239 return term_get_ttymode(term, mode);
242 static void start_backend(void)
245 char msg[1024], *title;
250 * Select protocol. This is farmed out into a table in a
251 * separate file to enable an ssh-free variant.
253 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
255 char *str = dupprintf("%s Internal Error", appname);
256 MessageBox(NULL, "Unsupported protocol number found",
257 str, MB_OK | MB_ICONEXCLAMATION);
262 error = back->init(NULL, &backhandle, conf,
263 conf_get_str(conf, CONF_host),
264 conf_get_int(conf, CONF_port),
266 conf_get_int(conf, CONF_tcp_nodelay),
267 conf_get_int(conf, CONF_tcp_keepalives));
268 back->provide_logctx(backhandle, logctx);
270 char *str = dupprintf("%s Error", appname);
271 sprintf(msg, "Unable to open connection to\n"
272 "%.800s\n" "%s", conf_dest(conf), error);
273 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
277 window_name = icon_name = NULL;
278 title = conf_get_str(conf, CONF_wintitle);
280 sprintf(msg, "%s - %s", realhost, appname);
284 set_title(NULL, title);
285 set_icon(NULL, title);
288 * Connect the terminal to the backend for resize purposes.
290 term_provide_resize_fn(term, back->size, backhandle);
293 * Set up a line discipline.
295 ldisc = ldisc_create(conf, term, back, backhandle, NULL);
298 * Destroy the Restart Session menu item. (This will return
299 * failure if it's already absent, as it will be the very first
300 * time we call this function. We ignore that, because as long
301 * as the menu item ends up not being there, we don't care
302 * whether it was us who removed it or not!)
304 for (i = 0; i < lenof(popup_menus); i++) {
305 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
308 session_closed = FALSE;
311 static void close_session(void *ignored_context)
316 session_closed = TRUE;
317 sprintf(morestuff, "%.70s (inactive)", appname);
318 set_icon(NULL, morestuff);
319 set_title(NULL, morestuff);
326 back->free(backhandle);
329 term_provide_resize_fn(term, NULL, NULL);
330 update_specials_menu(NULL);
334 * Show the Restart Session menu item. Do a precautionary
335 * delete first to ensure we never end up with more than one.
337 for (i = 0; i < lenof(popup_menus); i++) {
338 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
339 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
340 IDM_RESTART, "&Restart Session");
344 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
348 int guess_width, guess_height;
350 dll_hijacking_protection();
354 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
358 InitCommonControls();
360 /* Set Explicit App User Model Id so that jump lists don't cause
361 PuTTY to hang on to removable media. */
363 set_explicit_app_user_model_id();
365 /* Ensure a Maximize setting in Explorer doesn't maximise the
371 char *str = dupprintf("%s Fatal Error", appname);
372 MessageBox(NULL, "Windows refuses to report a version",
373 str, MB_OK | MB_ICONEXCLAMATION);
379 * If we're running a version of Windows that doesn't support
380 * WM_MOUSEWHEEL, find out what message number we should be
383 if (osVersion.dwMajorVersion < 4 ||
384 (osVersion.dwMajorVersion == 4 &&
385 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
386 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
397 hr = CoInitialize(NULL);
398 if (hr != S_OK && hr != S_FALSE) {
399 char *str = dupprintf("%s Fatal Error", appname);
400 MessageBox(NULL, "Failed to initialize COM subsystem",
401 str, MB_OK | MB_ICONEXCLAMATION);
407 * Process the command line.
412 /* By default, we bring up the config dialog, rather than launching
413 * a session. This gets set to TRUE if something happens to change
414 * that (e.g., a hostname is specified on the command-line). */
415 int allow_launch = FALSE;
417 default_protocol = be_default_protocol;
418 /* Find the appropriate default port. */
420 Backend *b = backend_from_proto(default_protocol);
421 default_port = 0; /* illegal */
423 default_port = b->default_port;
425 conf_set_int(conf, CONF_logtype, LGTYP_NONE);
427 do_defaults(NULL, conf);
432 * Process a couple of command-line options which are more
433 * easily dealt with before the line is broken up into words.
434 * These are the old-fashioned but convenient @sessionname and
435 * the internal-use-only &sharedmemoryhandle, neither of which
436 * are combined with anything else.
438 while (*p && isspace(*p))
442 * An initial @ means that the whole of the rest of the
443 * command line should be treated as the name of a saved
444 * session, with _no quoting or escaping_. This makes it a
445 * very convenient means of automated saved-session
446 * launching, via IDM_SAVEDSESS or Windows 7 jump lists.
449 while (i > 1 && isspace(p[i - 1]))
452 do_defaults(p + 1, conf);
453 if (!conf_launchable(conf) && !do_config()) {
456 allow_launch = TRUE; /* allow it to be launched directly */
457 } else if (*p == '&') {
459 * An initial & means we've been given a command line
460 * containing the hex value of a HANDLE for a file
461 * mapping object, which we must then interpret as a
467 if (sscanf(p + 1, "%p:%u", &filemap, &cpsize) == 2 &&
468 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
469 0, 0, cpsize)) != NULL) {
470 conf_deserialise(conf, cp, cpsize);
472 CloseHandle(filemap);
473 } else if (!do_config()) {
479 * Otherwise, break up the command line and deal with
485 split_into_argv(cmdline, &argc, &argv, NULL);
487 for (i = 0; i < argc; i++) {
491 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
494 cmdline_error("option \"%s\" requires an argument", p);
495 } else if (ret == 2) {
496 i++; /* skip next argument */
497 } else if (ret == 1) {
498 continue; /* nothing further needs doing */
499 } else if (!strcmp(p, "-cleanup") ||
500 !strcmp(p, "-cleanup-during-uninstall")) {
502 * `putty -cleanup'. Remove all registry
503 * entries associated with PuTTY, and also find
504 * and delete the random seed file.
507 /* Are we being invoked from an uninstaller? */
508 if (!strcmp(p, "-cleanup-during-uninstall")) {
509 s1 = dupprintf("Remove saved sessions and random seed file?\n"
511 "If you hit Yes, ALL Registry entries associated\n"
512 "with %s will be removed, as well as the\n"
513 "random seed file. THIS PROCESS WILL\n"
514 "DESTROY YOUR SAVED SESSIONS.\n"
515 "(This only affects the currently logged-in user.)\n"
517 "If you hit No, uninstallation will proceed, but\n"
518 "saved sessions etc will be left on the machine.",
520 s2 = dupprintf("%s Uninstallation", appname);
522 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
523 "associated with %s, and will also remove\n"
524 "the random seed file. (This only affects the\n"
525 "currently logged-in user.)\n"
527 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
528 "Are you really sure you want to continue?",
530 s2 = dupprintf("%s Warning", appname);
532 if (message_box(s1, s2,
533 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
534 HELPCTXID(option_cleanup)) == IDYES) {
540 } else if (!strcmp(p, "-pgpfp")) {
543 } else if (*p != '-') {
547 * If we already have a host name, treat
548 * this argument as a port number. NB we
549 * have to treat this as a saved -P
550 * argument, so that it will be deferred
551 * until it's a good moment to run it.
553 int ret = cmdline_process_param("-P", p, 1, conf);
555 } else if (!strncmp(q, "telnet:", 7)) {
557 * If the hostname starts with "telnet:",
558 * set the protocol to Telnet and process
559 * the string as a Telnet URL.
564 if (q[0] == '/' && q[1] == '/')
566 conf_set_int(conf, CONF_protocol, PROT_TELNET);
568 p += host_strcspn(p, ":/");
573 conf_set_int(conf, CONF_port, atoi(p));
575 conf_set_int(conf, CONF_port, -1);
576 conf_set_str(conf, CONF_host, q);
580 * Otherwise, treat this argument as a host
583 while (*p && !isspace(*p))
587 conf_set_str(conf, CONF_host, q);
591 cmdline_error("unknown option \"%s\"", p);
596 cmdline_run_saved(conf);
598 if (loaded_session || got_host)
601 if ((!allow_launch || !conf_launchable(conf)) && !do_config()) {
606 * Muck about with the hostname in various ways.
609 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
610 char *host = hostbuf;
614 * Trim leading whitespace.
616 host += strspn(host, " \t");
619 * See if host is of the form user@host, and separate
620 * out the username if so.
622 if (host[0] != '\0') {
623 char *atsign = strrchr(host, '@');
626 conf_set_str(conf, CONF_username, host);
632 * Trim a colon suffix off the hostname if it's there. In
633 * order to protect unbracketed IPv6 address literals
634 * against this treatment, we do not do this if there's
635 * _more_ than one colon.
638 char *c = host_strchr(host, ':');
641 char *d = host_strchr(c+1, ':');
648 * Remove any remaining whitespace.
653 if (*q != ' ' && *q != '\t')
659 conf_set_str(conf, CONF_host, hostbuf);
668 wndclass.lpfnWndProc = WndProc;
669 wndclass.cbClsExtra = 0;
670 wndclass.cbWndExtra = 0;
671 wndclass.hInstance = inst;
672 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
673 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
674 wndclass.hbrBackground = NULL;
675 wndclass.lpszMenuName = NULL;
676 wndclass.lpszClassName = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
678 RegisterClassW(&wndclass);
681 memset(&ucsdata, 0, sizeof(ucsdata));
688 * Guess some defaults for the window size. This all gets
689 * updated later, so we don't really care too much. However, we
690 * do want the font width/height guesses to correspond to a
691 * large font rather than a small one...
698 guess_width = extra_width + font_width * conf_get_int(conf, CONF_width);
699 guess_height = extra_height + font_height*conf_get_int(conf, CONF_height);
702 get_fullscreen_rect(&r);
703 if (guess_width > r.right - r.left)
704 guess_width = r.right - r.left;
705 if (guess_height > r.bottom - r.top)
706 guess_height = r.bottom - r.top;
710 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
712 wchar_t *uappname = dup_mb_to_wc(DEFAULT_CODEPAGE, 0, appname);
713 if (!conf_get_int(conf, CONF_scrollbar))
714 winmode &= ~(WS_VSCROLL);
715 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
716 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
717 if (conf_get_int(conf, CONF_alwaysontop))
718 exwinmode |= WS_EX_TOPMOST;
719 if (conf_get_int(conf, CONF_sunken_edge))
720 exwinmode |= WS_EX_CLIENTEDGE;
721 hwnd = CreateWindowExW(exwinmode, uappname, uappname,
722 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
723 guess_width, guess_height,
724 NULL, NULL, inst, NULL);
729 * Initialise the fonts, simultaneously correcting the guesses
730 * for font_{width,height}.
735 * Initialise the terminal. (We have to do this _after_
736 * creating the window, since the terminal is the first thing
737 * which will call schedule_timer(), which will in turn call
738 * timer_change_notify() which will expect hwnd to exist.)
740 term = term_init(conf, &ucsdata, NULL);
741 logctx = log_init(NULL, conf);
742 term_provide_logctx(term, logctx);
743 term_size(term, conf_get_int(conf, CONF_height),
744 conf_get_int(conf, CONF_width),
745 conf_get_int(conf, CONF_savelines));
748 * Correct the guesses for extra_{width,height}.
752 GetWindowRect(hwnd, &wr);
753 GetClientRect(hwnd, &cr);
754 offset_width = offset_height = conf_get_int(conf, CONF_window_border);
755 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
756 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
760 * Resize the window, now we know what size we _really_ want it
763 guess_width = extra_width + font_width * term->cols;
764 guess_height = extra_height + font_height * term->rows;
765 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
766 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
769 * Set up a caret bitmap, with no content.
773 int size = (font_width + 15) / 16 * 2 * font_height;
774 bits = snewn(size, char);
775 memset(bits, 0, size);
776 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
779 CreateCaret(hwnd, caretbm, font_width, font_height);
782 * Initialise the scroll bar.
787 si.cbSize = sizeof(si);
788 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
790 si.nMax = term->rows - 1;
791 si.nPage = term->rows;
793 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
797 * Prepare the mouse handler.
799 lastact = MA_NOTHING;
800 lastbtn = MBT_NOTHING;
801 dbltime = GetDoubleClickTime();
804 * Set up the session-control options on the system menu.
811 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
812 popup_menus[CTXMENU].menu = CreatePopupMenu();
813 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
815 savedsess_menu = CreateMenu();
816 get_sesslist(&sesslist, TRUE);
817 update_savedsess_menu();
819 for (j = 0; j < lenof(popup_menus); j++) {
820 m = popup_menus[j].menu;
822 AppendMenu(m, MF_SEPARATOR, 0, 0);
823 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
824 AppendMenu(m, MF_SEPARATOR, 0, 0);
825 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
826 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
827 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT_PTR) savedsess_menu,
829 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
830 AppendMenu(m, MF_SEPARATOR, 0, 0);
831 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
832 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
833 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
834 AppendMenu(m, MF_SEPARATOR, 0, 0);
835 AppendMenu(m, (conf_get_int(conf, CONF_resize_action)
836 == RESIZE_DISABLED) ? MF_GRAYED : MF_ENABLED,
837 IDM_FULLSCREEN, "&Full Screen");
838 AppendMenu(m, MF_SEPARATOR, 0, 0);
840 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
841 str = dupprintf("&About %s", appname);
842 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
850 * Set up the initial input locale.
852 set_input_locale(GetKeyboardLayout(0));
855 * Finally show the window!
857 ShowWindow(hwnd, show);
858 SetForegroundWindow(hwnd);
861 * Set the palette up.
867 term_set_focus(term, GetForegroundWindow() == hwnd);
875 if (toplevel_callback_pending() ||
876 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
878 * If we have anything we'd like to do immediately, set
879 * the timeout for MsgWaitForMultipleObjects to zero so
880 * that we'll only do a quick check of our handles and
881 * then get on with whatever that was.
883 * One such option is a pending toplevel callback. The
884 * other is a non-empty Windows message queue, which you'd
885 * think we could leave to MsgWaitForMultipleObjects to
886 * check for us along with all the handles, but in fact we
887 * can't because once PeekMessage in one iteration of this
888 * loop has removed a message from the queue, the whole
889 * queue is considered uninteresting by the next
890 * invocation of MWFMO. So we check ourselves whether the
891 * message queue is non-empty, and if so, set this timeout
892 * to zero to ensure MWFMO doesn't block.
897 /* The messages seem unreliable; especially if we're being tricky */
898 term_set_focus(term, GetForegroundWindow() == hwnd);
901 handles = handle_get_events(&nhandles);
903 n = MsgWaitForMultipleObjects(nhandles, handles, FALSE,
904 timeout, QS_ALLINPUT);
906 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
907 handle_got_event(handles[n - WAIT_OBJECT_0]);
912 while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
913 if (msg.message == WM_QUIT)
914 goto finished; /* two-level break */
916 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
917 DispatchMessageW(&msg);
920 * WM_NETEVENT messages seem to jump ahead of others in
921 * the message queue. I'm not sure why; the docs for
922 * PeekMessage mention that messages are prioritised in
923 * some way, but I'm unclear on which priorities go where.
925 * Anyway, in practice I observe that WM_NETEVENT seems to
926 * jump to the head of the queue, which means that if we
927 * were to only process one message every time round this
928 * loop, we'd get nothing but NETEVENTs if the server
929 * flooded us with data, and stop responding to any other
930 * kind of window message. So instead, we keep on round
931 * this loop until we've consumed at least one message
932 * that _isn't_ a NETEVENT, or run out of messages
933 * completely (whichever comes first). And we don't go to
934 * run_toplevel_callbacks (which is where the netevents
935 * are actually processed, causing fresh NETEVENT messages
936 * to appear) until we've done this.
938 if (msg.message != WM_NETEVENT)
942 run_toplevel_callbacks();
946 cleanup_exit(msg.wParam); /* this doesn't return... */
947 return msg.wParam; /* ... but optimiser doesn't know */
953 void cleanup_exit(int code)
964 if (conf_get_int(conf, CONF_protocol) == PROT_SSH) {
979 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
981 char *do_select(SOCKET skt, int startup)
986 events = (FD_CONNECT | FD_READ | FD_WRITE |
987 FD_OOB | FD_CLOSE | FD_ACCEPT);
992 return "do_select(): internal error (hwnd==NULL)";
993 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
994 switch (p_WSAGetLastError()) {
996 return "Network is down";
998 return "WSAAsyncSelect(): unknown error";
1005 * Refresh the saved-session submenu from `sesslist'.
1007 static void update_savedsess_menu(void)
1010 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
1011 /* skip sesslist.sessions[0] == Default Settings */
1013 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
1014 : MENU_SAVED_MAX+1);
1016 AppendMenu(savedsess_menu, MF_ENABLED,
1017 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
1018 sesslist.sessions[i]);
1019 if (sesslist.nsessions <= 1)
1020 AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)");
1024 * Update the Special Commands submenu.
1026 void update_specials_menu(void *frontend)
1032 specials = back->get_specials(backhandle);
1037 /* We can't use Windows to provide a stack for submenus, so
1038 * here's a lame "stack" that will do for now. */
1039 HMENU saved_menu = NULL;
1041 new_menu = CreatePopupMenu();
1042 for (i = 0; nesting > 0; i++) {
1043 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
1044 switch (specials[i].code) {
1046 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
1049 assert(nesting < 2);
1051 saved_menu = new_menu; /* XXX lame stacking */
1052 new_menu = CreatePopupMenu();
1053 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
1054 (UINT_PTR) new_menu, specials[i].name);
1059 new_menu = saved_menu; /* XXX lame stacking */
1064 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
1069 /* Squirrel the highest special. */
1076 for (j = 0; j < lenof(popup_menus); j++) {
1077 if (specials_menu) {
1078 /* XXX does this free up all submenus? */
1079 DeleteMenu(popup_menus[j].menu, (UINT_PTR)specials_menu,
1081 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
1084 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1085 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
1086 (UINT_PTR) new_menu, "S&pecial Command");
1087 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1088 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
1091 specials_menu = new_menu;
1094 static void update_mouse_pointer(void)
1097 int force_visible = FALSE;
1098 static int forced_visible = FALSE;
1099 switch (busy_status) {
1102 curstype = IDC_ARROW;
1104 curstype = IDC_IBEAM;
1107 curstype = IDC_APPSTARTING; /* this may be an abuse */
1108 force_visible = TRUE;
1111 curstype = IDC_WAIT;
1112 force_visible = TRUE;
1118 HCURSOR cursor = LoadCursor(NULL, curstype);
1119 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1120 SetCursor(cursor); /* force redraw of cursor at current posn */
1122 if (force_visible != forced_visible) {
1123 /* We want some cursor shapes to be visible always.
1124 * Along with show_mouseptr(), this manages the ShowCursor()
1125 * counter such that if we switch back to a non-force_visible
1126 * cursor, the previous visibility state is restored. */
1127 ShowCursor(force_visible);
1128 forced_visible = force_visible;
1132 void set_busy_status(void *frontend, int status)
1134 busy_status = status;
1135 update_mouse_pointer();
1139 * set or clear the "raw mouse message" mode
1141 void set_raw_mouse_mode(void *frontend, int activate)
1143 activate = activate && !conf_get_int(conf, CONF_no_mouse_rep);
1144 send_raw_mouse = activate;
1145 update_mouse_pointer();
1149 * Print a message box and close the connection.
1151 void connection_fatal(void *frontend, const char *fmt, ...)
1154 char *stuff, morestuff[100];
1157 stuff = dupvprintf(fmt, ap);
1159 sprintf(morestuff, "%.70s Fatal Error", appname);
1160 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1163 if (conf_get_int(conf, CONF_close_on_exit) == FORCE_ON)
1166 queue_toplevel_callback(close_session, NULL);
1171 * Report an error at the command-line parsing stage.
1173 void cmdline_error(const char *fmt, ...)
1176 char *stuff, morestuff[100];
1179 stuff = dupvprintf(fmt, ap);
1181 sprintf(morestuff, "%.70s Command Line Error", appname);
1182 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1188 * Actually do the job requested by a WM_NETEVENT
1190 static void wm_netevent_callback(void *vctx)
1192 struct wm_netevent_params *params = (struct wm_netevent_params *)vctx;
1193 select_result(params->wParam, params->lParam);
1198 * Copy the colour palette from the configuration data into defpal.
1199 * This is non-trivial because the colour indices are different.
1201 static void conftopalette(void)
1204 static const int ww[] = {
1205 256, 257, 258, 259, 260, 261,
1206 0, 8, 1, 9, 2, 10, 3, 11,
1207 4, 12, 5, 13, 6, 14, 7, 15
1210 for (i = 0; i < 22; i++) {
1212 defpal[w].rgbtRed = conf_get_int_int(conf, CONF_colours, i*3+0);
1213 defpal[w].rgbtGreen = conf_get_int_int(conf, CONF_colours, i*3+1);
1214 defpal[w].rgbtBlue = conf_get_int_int(conf, CONF_colours, i*3+2);
1216 for (i = 0; i < NEXTCOLOURS; i++) {
1218 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1219 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1220 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1221 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
1223 int shade = i - 216;
1224 shade = shade * 10 + 8;
1225 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1226 defpal[i+16].rgbtBlue = shade;
1230 /* Override with system colours if appropriate */
1231 if (conf_get_int(conf, CONF_system_colour))
1236 * Override bit of defpal with colours from the system.
1237 * (NB that this takes a copy the system colours at the time this is called,
1238 * so subsequent colour scheme changes don't take effect. To fix that we'd
1239 * probably want to be using GetSysColorBrush() and the like.)
1241 static void systopalette(void)
1244 static const struct { int nIndex; int norm; int bold; } or[] =
1246 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1247 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1248 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1249 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1252 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1253 COLORREF colour = GetSysColor(or[i].nIndex);
1254 defpal[or[i].norm].rgbtRed =
1255 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1256 defpal[or[i].norm].rgbtGreen =
1257 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1258 defpal[or[i].norm].rgbtBlue =
1259 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1264 * Set up the colour palette.
1266 static void init_palette(void)
1269 HDC hdc = GetDC(hwnd);
1271 if (conf_get_int(conf, CONF_try_palette) &&
1272 GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1274 * This is a genuine case where we must use smalloc
1275 * because the snew macros can't cope.
1277 logpal = smalloc(sizeof(*logpal)
1278 - sizeof(logpal->palPalEntry)
1279 + NALLCOLOURS * sizeof(PALETTEENTRY));
1280 logpal->palVersion = 0x300;
1281 logpal->palNumEntries = NALLCOLOURS;
1282 for (i = 0; i < NALLCOLOURS; i++) {
1283 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1284 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1285 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1286 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1288 pal = CreatePalette(logpal);
1290 SelectPalette(hdc, pal, FALSE);
1291 RealizePalette(hdc);
1292 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1295 ReleaseDC(hwnd, hdc);
1298 for (i = 0; i < NALLCOLOURS; i++)
1299 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1300 defpal[i].rgbtGreen,
1301 defpal[i].rgbtBlue);
1303 for (i = 0; i < NALLCOLOURS; i++)
1304 colours[i] = RGB(defpal[i].rgbtRed,
1305 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1309 * This is a wrapper to ExtTextOut() to force Windows to display
1310 * the precise glyphs we give it. Otherwise it would do its own
1311 * bidi and Arabic shaping, and we would end up uncertain which
1312 * characters it had put where.
1314 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1315 unsigned short *lpString, UINT cbCount,
1316 CONST INT *lpDx, int opaque)
1320 * The LCC include files apparently don't supply the
1321 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1322 * proper: the differences aren't important to us (the only
1323 * variable-width string parameter is one we don't use anyway).
1329 char *buffer = snewn(cbCount*2+2, char);
1330 char *classbuffer = snewn(cbCount, char);
1331 memset(&gcpr, 0, sizeof(gcpr));
1332 memset(buffer, 0, cbCount*2+2);
1333 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1335 gcpr.lStructSize = sizeof(gcpr);
1336 gcpr.lpGlyphs = (void *)buffer;
1337 gcpr.lpClass = (void *)classbuffer;
1338 gcpr.nGlyphs = cbCount;
1339 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1340 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1342 ExtTextOut(hdc, x, y,
1343 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1344 lprc, buffer, cbCount, lpDx);
1348 * The exact_textout() wrapper, unfortunately, destroys the useful
1349 * Windows `font linking' behaviour: automatic handling of Unicode
1350 * code points not supported in this font by falling back to a font
1351 * which does contain them. Therefore, we adopt a multi-layered
1352 * approach: for any potentially-bidi text, we use exact_textout(),
1353 * and for everything else we use a simple ExtTextOut as we did
1354 * before exact_textout() was introduced.
1356 static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1357 unsigned short *lpString, UINT cbCount,
1358 CONST INT *lpDx, int opaque)
1361 int bkmode = 0, got_bkmode = FALSE;
1365 for (i = 0; i < (int)cbCount ;) {
1366 int rtl = is_rtl(lpString[i]);
1370 for (j = i+1; j < (int)cbCount; j++) {
1371 if (rtl != is_rtl(lpString[j]))
1377 * Now [i,j) indicates a maximal substring of lpString
1378 * which should be displayed using the same textout
1382 exact_textout(hdc, xp, y, lprc, lpString+i, j-i,
1383 font_varpitch ? NULL : lpDx+i, opaque);
1385 ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1386 lprc, lpString+i, j-i,
1387 font_varpitch ? NULL : lpDx+i);
1393 bkmode = GetBkMode(hdc);
1395 SetBkMode(hdc, TRANSPARENT);
1400 SetBkMode(hdc, bkmode);
1403 static int get_font_width(HDC hdc, const TEXTMETRIC *tm)
1406 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1407 if (!(tm->tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1408 ret = tm->tmAveCharWidth;
1412 ABCFLOAT widths[LAST-FIRST + 1];
1415 font_varpitch = TRUE;
1416 font_dualwidth = TRUE;
1417 if (GetCharABCWidthsFloat(hdc, FIRST, LAST, widths)) {
1419 for (j = 0; j < lenof(widths); j++) {
1420 int width = (int)(0.5 + widths[j].abcfA +
1421 widths[j].abcfB + widths[j].abcfC);
1426 ret = tm->tmMaxCharWidth;
1435 * Initialise all the fonts we will need initially. There may be as many as
1436 * three or as few as one. The other (potentially) twenty-one fonts are done
1437 * if/when they are needed.
1441 * - check the font width and height, correcting our guesses if
1444 * - verify that the bold font is the same width as the ordinary
1445 * one, and engage shadow bolding if not.
1447 * - verify that the underlined font is the same width as the
1448 * ordinary one (manual underlining by means of line drawing can
1449 * be done in a pinch).
1451 static void init_fonts(int pick_width, int pick_height)
1460 int fw_dontcare, fw_bold;
1462 for (i = 0; i < FONT_MAXNO; i++)
1465 bold_font_mode = conf_get_int(conf, CONF_bold_style) & 1 ?
1466 BOLD_FONT : BOLD_NONE;
1467 bold_colours = conf_get_int(conf, CONF_bold_style) & 2 ? TRUE : FALSE;
1468 und_mode = UND_FONT;
1470 font = conf_get_fontspec(conf, CONF_font);
1472 fw_dontcare = FW_BOLD;
1475 fw_dontcare = FW_DONTCARE;
1482 font_height = pick_height;
1484 font_height = font->height;
1485 if (font_height > 0) {
1487 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1490 font_width = pick_width;
1492 quality = conf_get_int(conf, CONF_font_quality);
1493 #define f(i,c,w,u) \
1494 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1495 c, OUT_DEFAULT_PRECIS, \
1496 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), \
1497 FIXED_PITCH | FF_DONTCARE, font->name)
1499 f(FONT_NORMAL, font->charset, fw_dontcare, FALSE);
1501 SelectObject(hdc, fonts[FONT_NORMAL]);
1502 GetTextMetrics(hdc, &tm);
1504 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1506 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1507 if (!(tm.tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1508 font_varpitch = FALSE;
1509 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1511 font_varpitch = TRUE;
1512 font_dualwidth = TRUE;
1514 if (pick_width == 0 || pick_height == 0) {
1515 font_height = tm.tmHeight;
1516 font_width = get_font_width(hdc, &tm);
1519 #ifdef RDB_DEBUG_PATCH
1520 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1521 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1526 DWORD cset = tm.tmCharSet;
1527 memset(&info, 0xFF, sizeof(info));
1529 /* !!! Yes the next line is right */
1530 if (cset == OEM_CHARSET)
1531 ucsdata.font_codepage = GetOEMCP();
1533 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1534 ucsdata.font_codepage = info.ciACP;
1536 ucsdata.font_codepage = -1;
1538 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1539 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1542 f(FONT_UNDERLINE, font->charset, fw_dontcare, TRUE);
1545 * Some fonts, e.g. 9-pt Courier, draw their underlines
1546 * outside their character cell. We successfully prevent
1547 * screen corruption by clipping the text output, but then
1548 * we lose the underline completely. Here we try to work
1549 * out whether this is such a font, and if it is, we set a
1550 * flag that causes underlines to be drawn by hand.
1552 * Having tried other more sophisticated approaches (such
1553 * as examining the TEXTMETRIC structure or requesting the
1554 * height of a string), I think we'll do this the brute
1555 * force way: we create a small bitmap, draw an underlined
1556 * space on it, and test to see whether any pixels are
1557 * foreground-coloured. (Since we expect the underline to
1558 * go all the way across the character cell, we only search
1559 * down a single column of the bitmap, half way across.)
1563 HBITMAP und_bm, und_oldbm;
1567 und_dc = CreateCompatibleDC(hdc);
1568 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1569 und_oldbm = SelectObject(und_dc, und_bm);
1570 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1571 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1572 SetTextColor(und_dc, RGB(255, 255, 255));
1573 SetBkColor(und_dc, RGB(0, 0, 0));
1574 SetBkMode(und_dc, OPAQUE);
1575 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1577 for (i = 0; i < font_height; i++) {
1578 c = GetPixel(und_dc, font_width / 2, i);
1579 if (c != RGB(0, 0, 0))
1582 SelectObject(und_dc, und_oldbm);
1583 DeleteObject(und_bm);
1586 und_mode = UND_LINE;
1587 DeleteObject(fonts[FONT_UNDERLINE]);
1588 fonts[FONT_UNDERLINE] = 0;
1592 if (bold_font_mode == BOLD_FONT) {
1593 f(FONT_BOLD, font->charset, fw_bold, FALSE);
1597 descent = tm.tmAscent + 1;
1598 if (descent >= font_height)
1599 descent = font_height - 1;
1601 for (i = 0; i < 3; i++) {
1603 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1604 fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight;
1611 ReleaseDC(hwnd, hdc);
1613 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1614 und_mode = UND_LINE;
1615 DeleteObject(fonts[FONT_UNDERLINE]);
1616 fonts[FONT_UNDERLINE] = 0;
1619 if (bold_font_mode == BOLD_FONT &&
1620 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1621 bold_font_mode = BOLD_SHADOW;
1622 DeleteObject(fonts[FONT_BOLD]);
1623 fonts[FONT_BOLD] = 0;
1625 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1627 init_ucs(conf, &ucsdata);
1630 static void another_font(int fontno)
1633 int fw_dontcare, fw_bold, quality;
1638 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1641 basefont = (fontno & ~(FONT_BOLDUND));
1642 if (basefont != fontno && !fontflag[basefont])
1643 another_font(basefont);
1645 font = conf_get_fontspec(conf, CONF_font);
1648 fw_dontcare = FW_BOLD;
1651 fw_dontcare = FW_DONTCARE;
1661 if (fontno & FONT_WIDE)
1663 if (fontno & FONT_NARROW)
1665 if (fontno & FONT_OEM)
1667 if (fontno & FONT_BOLD)
1669 if (fontno & FONT_UNDERLINE)
1672 quality = conf_get_int(conf, CONF_font_quality);
1675 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1676 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1677 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality),
1678 DEFAULT_PITCH | FF_DONTCARE, s);
1680 fontflag[fontno] = 1;
1683 static void deinit_fonts(void)
1686 for (i = 0; i < FONT_MAXNO; i++) {
1688 DeleteObject(fonts[i]);
1694 void request_resize(void *frontend, int w, int h)
1698 /* If the window is maximized supress resizing attempts */
1699 if (IsZoomed(hwnd)) {
1700 if (conf_get_int(conf, CONF_resize_action) == RESIZE_TERM)
1704 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) return;
1705 if (h == term->rows && w == term->cols) return;
1707 /* Sanity checks ... */
1709 static int first_time = 1;
1712 switch (first_time) {
1714 /* Get the size of the screen */
1715 if (get_fullscreen_rect(&ss))
1716 /* first_time = 0 */ ;
1722 /* Make sure the values are sane */
1723 width = (ss.right - ss.left - extra_width) / 4;
1724 height = (ss.bottom - ss.top - extra_height) / 6;
1726 if (w > width || h > height)
1735 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
1737 if (conf_get_int(conf, CONF_resize_action) != RESIZE_FONT &&
1739 width = extra_width + font_width * w;
1740 height = extra_height + font_height * h;
1742 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1743 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1744 SWP_NOMOVE | SWP_NOZORDER);
1748 InvalidateRect(hwnd, NULL, TRUE);
1751 static void reset_window(int reinit) {
1753 * This function decides how to resize or redraw when the
1754 * user changes something.
1756 * This function doesn't like to change the terminal size but if the
1757 * font size is locked that may be it's only soluion.
1759 int win_width, win_height, resize_action, window_border;
1762 #ifdef RDB_DEBUG_PATCH
1763 debug((27, "reset_window()"));
1766 /* Current window sizes ... */
1767 GetWindowRect(hwnd, &wr);
1768 GetClientRect(hwnd, &cr);
1770 win_width = cr.right - cr.left;
1771 win_height = cr.bottom - cr.top;
1773 resize_action = conf_get_int(conf, CONF_resize_action);
1774 window_border = conf_get_int(conf, CONF_window_border);
1776 if (resize_action == RESIZE_DISABLED)
1779 /* Are we being forced to reload the fonts ? */
1781 #ifdef RDB_DEBUG_PATCH
1782 debug((27, "reset_window() -- Forced deinit"));
1788 /* Oh, looks like we're minimised */
1789 if (win_width == 0 || win_height == 0)
1792 /* Is the window out of position ? */
1794 (offset_width != (win_width-font_width*term->cols)/2 ||
1795 offset_height != (win_height-font_height*term->rows)/2) ){
1796 offset_width = (win_width-font_width*term->cols)/2;
1797 offset_height = (win_height-font_height*term->rows)/2;
1798 InvalidateRect(hwnd, NULL, TRUE);
1799 #ifdef RDB_DEBUG_PATCH
1800 debug((27, "reset_window() -> Reposition terminal"));
1804 if (IsZoomed(hwnd)) {
1805 /* We're fullscreen, this means we must not change the size of
1806 * the window so it's the font size or the terminal itself.
1809 extra_width = wr.right - wr.left - cr.right + cr.left;
1810 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1812 if (resize_action != RESIZE_TERM) {
1813 if (font_width != win_width/term->cols ||
1814 font_height != win_height/term->rows) {
1816 init_fonts(win_width/term->cols, win_height/term->rows);
1817 offset_width = (win_width-font_width*term->cols)/2;
1818 offset_height = (win_height-font_height*term->rows)/2;
1819 InvalidateRect(hwnd, NULL, TRUE);
1820 #ifdef RDB_DEBUG_PATCH
1821 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1822 font_width, font_height));
1826 if (font_width * term->cols != win_width ||
1827 font_height * term->rows != win_height) {
1828 /* Our only choice at this point is to change the
1829 * size of the terminal; Oh well.
1831 term_size(term, win_height/font_height, win_width/font_width,
1832 conf_get_int(conf, CONF_savelines));
1833 offset_width = (win_width-font_width*term->cols)/2;
1834 offset_height = (win_height-font_height*term->rows)/2;
1835 InvalidateRect(hwnd, NULL, TRUE);
1836 #ifdef RDB_DEBUG_PATCH
1837 debug((27, "reset_window() -> Zoomed term_size"));
1844 /* Hmm, a force re-init means we should ignore the current window
1845 * so we resize to the default font size.
1848 #ifdef RDB_DEBUG_PATCH
1849 debug((27, "reset_window() -> Forced re-init"));
1852 offset_width = offset_height = window_border;
1853 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1854 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1856 if (win_width != font_width*term->cols + offset_width*2 ||
1857 win_height != font_height*term->rows + offset_height*2) {
1859 /* If this is too large windows will resize it to the maximum
1860 * allowed window size, we will then be back in here and resize
1861 * the font or terminal to fit.
1863 SetWindowPos(hwnd, NULL, 0, 0,
1864 font_width*term->cols + extra_width,
1865 font_height*term->rows + extra_height,
1866 SWP_NOMOVE | SWP_NOZORDER);
1869 InvalidateRect(hwnd, NULL, TRUE);
1873 /* Okay the user doesn't want us to change the font so we try the
1874 * window. But that may be too big for the screen which forces us
1875 * to change the terminal.
1877 if ((resize_action == RESIZE_TERM && reinit<=0) ||
1878 (resize_action == RESIZE_EITHER && reinit<0) ||
1880 offset_width = offset_height = window_border;
1881 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1882 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1884 if (win_width != font_width*term->cols + offset_width*2 ||
1885 win_height != font_height*term->rows + offset_height*2) {
1890 get_fullscreen_rect(&ss);
1892 width = (ss.right - ss.left - extra_width) / font_width;
1893 height = (ss.bottom - ss.top - extra_height) / font_height;
1896 if ( term->rows > height || term->cols > width ) {
1897 if (resize_action == RESIZE_EITHER) {
1898 /* Make the font the biggest we can */
1899 if (term->cols > width)
1900 font_width = (ss.right - ss.left - extra_width)
1902 if (term->rows > height)
1903 font_height = (ss.bottom - ss.top - extra_height)
1907 init_fonts(font_width, font_height);
1909 width = (ss.right - ss.left - extra_width) / font_width;
1910 height = (ss.bottom - ss.top - extra_height) / font_height;
1912 if ( height > term->rows ) height = term->rows;
1913 if ( width > term->cols ) width = term->cols;
1914 term_size(term, height, width,
1915 conf_get_int(conf, CONF_savelines));
1916 #ifdef RDB_DEBUG_PATCH
1917 debug((27, "reset_window() -> term resize to (%d,%d)",
1923 SetWindowPos(hwnd, NULL, 0, 0,
1924 font_width*term->cols + extra_width,
1925 font_height*term->rows + extra_height,
1926 SWP_NOMOVE | SWP_NOZORDER);
1928 InvalidateRect(hwnd, NULL, TRUE);
1929 #ifdef RDB_DEBUG_PATCH
1930 debug((27, "reset_window() -> window resize to (%d,%d)",
1931 font_width*term->cols + extra_width,
1932 font_height*term->rows + extra_height));
1938 /* We're allowed to or must change the font but do we want to ? */
1940 if (font_width != (win_width-window_border*2)/term->cols ||
1941 font_height != (win_height-window_border*2)/term->rows) {
1944 init_fonts((win_width-window_border*2)/term->cols,
1945 (win_height-window_border*2)/term->rows);
1946 offset_width = (win_width-font_width*term->cols)/2;
1947 offset_height = (win_height-font_height*term->rows)/2;
1949 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1950 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1952 InvalidateRect(hwnd, NULL, TRUE);
1953 #ifdef RDB_DEBUG_PATCH
1954 debug((25, "reset_window() -> font resize to (%d,%d)",
1955 font_width, font_height));
1960 static void set_input_locale(HKL kl)
1964 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1965 lbuf, sizeof(lbuf));
1967 kbd_codepage = atoi(lbuf);
1970 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1972 int thistime = GetMessageTime();
1974 if (send_raw_mouse &&
1975 !(shift && conf_get_int(conf, CONF_mouse_override))) {
1976 lastbtn = MBT_NOTHING;
1977 term_mouse(term, b, translate_button(b), MA_CLICK,
1978 x, y, shift, ctrl, alt);
1982 if (lastbtn == b && thistime - lasttime < dbltime) {
1983 lastact = (lastact == MA_CLICK ? MA_2CLK :
1984 lastact == MA_2CLK ? MA_3CLK :
1985 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1990 if (lastact != MA_NOTHING)
1991 term_mouse(term, b, translate_button(b), lastact,
1992 x, y, shift, ctrl, alt);
1993 lasttime = thistime;
1997 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1998 * into a cooked one (SELECT, EXTEND, PASTE).
2000 static Mouse_Button translate_button(Mouse_Button button)
2002 if (button == MBT_LEFT)
2004 if (button == MBT_MIDDLE)
2005 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2006 MBT_PASTE : MBT_EXTEND;
2007 if (button == MBT_RIGHT)
2008 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2009 MBT_EXTEND : MBT_PASTE;
2010 return 0; /* shouldn't happen */
2013 static void show_mouseptr(int show)
2015 /* NB that the counter in ShowCursor() is also frobbed by
2016 * update_mouse_pointer() */
2017 static int cursor_visible = 1;
2018 if (!conf_get_int(conf, CONF_hide_mouseptr))
2019 show = 1; /* override if this feature disabled */
2020 if (cursor_visible && !show)
2022 else if (!cursor_visible && show)
2024 cursor_visible = show;
2027 static int is_alt_pressed(void)
2030 int r = GetKeyboardState(keystate);
2033 if (keystate[VK_MENU] & 0x80)
2035 if (keystate[VK_RMENU] & 0x80)
2040 static int resizing;
2042 void notify_remote_exit(void *fe)
2044 int exitcode, close_on_exit;
2046 if (!session_closed &&
2047 (exitcode = back->exitcode(backhandle)) >= 0) {
2048 close_on_exit = conf_get_int(conf, CONF_close_on_exit);
2049 /* Abnormal exits will already have set session_closed and taken
2050 * appropriate action. */
2051 if (close_on_exit == FORCE_ON ||
2052 (close_on_exit == AUTO && exitcode != INT_MAX)) {
2055 queue_toplevel_callback(close_session, NULL);
2056 session_closed = TRUE;
2057 /* exitcode == INT_MAX indicates that the connection was closed
2058 * by a fatal error, so an error box will be coming our way and
2059 * we should not generate this informational one. */
2060 if (exitcode != INT_MAX)
2061 MessageBox(hwnd, "Connection closed by remote host",
2062 appname, MB_OK | MB_ICONINFORMATION);
2067 void timer_change_notify(unsigned long next)
2069 unsigned long now = GETTICKCOUNT();
2071 if (now - next < INT_MAX)
2075 KillTimer(hwnd, TIMING_TIMER_ID);
2076 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
2077 timing_next_time = next;
2080 static void conf_cache_data(void)
2082 /* Cache some items from conf to speed lookups in very hot code */
2083 cursor_type = conf_get_int(conf, CONF_cursor_type);
2084 vtmode = conf_get_int(conf, CONF_vtmode);
2087 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2088 WPARAM wParam, LPARAM lParam)
2091 static int ignore_clip = FALSE;
2092 static int need_backend_resize = FALSE;
2093 static int fullscr_on_max = FALSE;
2094 static int processed_resize = FALSE;
2095 static UINT last_mousemove = 0;
2100 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
2103 KillTimer(hwnd, TIMING_TIMER_ID);
2104 if (run_timers(timing_next_time, &next)) {
2105 timer_change_notify(next);
2116 str = dupprintf("%s Exit Confirmation", appname);
2117 if (session_closed || !conf_get_int(conf, CONF_warn_on_close) ||
2119 "Are you sure you want to close this session?",
2120 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
2122 DestroyWindow(hwnd);
2130 case WM_INITMENUPOPUP:
2131 if ((HMENU)wParam == savedsess_menu) {
2132 /* About to pop up Saved Sessions sub-menu.
2133 * Refresh the session list. */
2134 get_sesslist(&sesslist, FALSE); /* free */
2135 get_sesslist(&sesslist, TRUE);
2136 update_savedsess_menu();
2142 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
2153 BOOL inherit_handles;
2155 PROCESS_INFORMATION pi;
2156 HANDLE filemap = NULL;
2158 if (wParam == IDM_DUPSESS) {
2160 * Allocate a file-mapping memory chunk for the
2163 SECURITY_ATTRIBUTES sa;
2167 size = conf_serialised_size(conf);
2169 sa.nLength = sizeof(sa);
2170 sa.lpSecurityDescriptor = NULL;
2171 sa.bInheritHandle = TRUE;
2172 filemap = CreateFileMapping(INVALID_HANDLE_VALUE,
2176 if (filemap && filemap != INVALID_HANDLE_VALUE) {
2177 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, size);
2179 conf_serialise(conf, p);
2183 inherit_handles = TRUE;
2184 sprintf(c, "putty &%p:%u", filemap, (unsigned)size);
2186 } else if (wParam == IDM_SAVEDSESS) {
2187 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
2188 / MENU_SAVED_STEP) + 1;
2189 if (sessno < (unsigned)sesslist.nsessions) {
2190 const char *session = sesslist.sessions[sessno];
2191 cl = dupprintf("putty @%s", session);
2192 inherit_handles = FALSE;
2196 } else /* IDM_NEWSESS */ {
2198 inherit_handles = FALSE;
2201 GetModuleFileName(NULL, b, sizeof(b) - 1);
2203 si.lpReserved = NULL;
2204 si.lpDesktop = NULL;
2208 si.lpReserved2 = NULL;
2209 CreateProcess(b, cl, NULL, NULL, inherit_handles,
2210 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
2211 CloseHandle(pi.hProcess);
2212 CloseHandle(pi.hThread);
2215 CloseHandle(filemap);
2222 logevent(NULL, "----- Session restarted -----");
2223 term_pwron(term, FALSE);
2232 int reconfig_result;
2237 reconfiguring = TRUE;
2240 * Copy the current window title into the stored
2241 * previous configuration, so that doing nothing to
2242 * the window title field in the config box doesn't
2243 * reset the title to its startup state.
2245 conf_set_str(conf, CONF_wintitle, window_name);
2247 prev_conf = conf_copy(conf);
2250 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2251 reconfiguring = FALSE;
2252 if (!reconfig_result) {
2253 conf_free(prev_conf);
2259 resize_action = conf_get_int(conf, CONF_resize_action);
2261 /* Disable full-screen if resizing forbidden */
2263 for (i = 0; i < lenof(popup_menus); i++)
2264 EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN,
2266 (resize_action == RESIZE_DISABLED)
2267 ? MF_GRAYED : MF_ENABLED);
2268 /* Gracefully unzoom if necessary */
2269 if (IsZoomed(hwnd) && (resize_action == RESIZE_DISABLED))
2270 ShowWindow(hwnd, SW_RESTORE);
2273 /* Pass new config data to the logging module */
2274 log_reconfig(logctx, conf);
2278 * Flush the line discipline's edit buffer in the
2279 * case where local editing has just been disabled.
2282 ldisc_configure(ldisc, conf);
2283 ldisc_echoedit_update(ldisc);
2292 /* Pass new config data to the terminal */
2293 term_reconfig(term, conf);
2295 /* Pass new config data to the back end */
2297 back->reconfig(backhandle, conf);
2299 /* Screen size changed ? */
2300 if (conf_get_int(conf, CONF_height) !=
2301 conf_get_int(prev_conf, CONF_height) ||
2302 conf_get_int(conf, CONF_width) !=
2303 conf_get_int(prev_conf, CONF_width) ||
2304 conf_get_int(conf, CONF_savelines) !=
2305 conf_get_int(prev_conf, CONF_savelines) ||
2306 resize_action == RESIZE_FONT ||
2307 (resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2308 resize_action == RESIZE_DISABLED)
2309 term_size(term, conf_get_int(conf, CONF_height),
2310 conf_get_int(conf, CONF_width),
2311 conf_get_int(conf, CONF_savelines));
2313 /* Enable or disable the scroll bar, etc */
2315 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2316 LONG nexflag, exflag =
2317 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2320 if (conf_get_int(conf, CONF_alwaysontop) !=
2321 conf_get_int(prev_conf, CONF_alwaysontop)) {
2322 if (conf_get_int(conf, CONF_alwaysontop)) {
2323 nexflag |= WS_EX_TOPMOST;
2324 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2325 SWP_NOMOVE | SWP_NOSIZE);
2327 nexflag &= ~(WS_EX_TOPMOST);
2328 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2329 SWP_NOMOVE | SWP_NOSIZE);
2332 if (conf_get_int(conf, CONF_sunken_edge))
2333 nexflag |= WS_EX_CLIENTEDGE;
2335 nexflag &= ~(WS_EX_CLIENTEDGE);
2338 if (conf_get_int(conf, is_full_screen() ?
2339 CONF_scrollbar_in_fullscreen :
2343 nflg &= ~WS_VSCROLL;
2345 if (resize_action == RESIZE_DISABLED ||
2347 nflg &= ~WS_THICKFRAME;
2349 nflg |= WS_THICKFRAME;
2351 if (resize_action == RESIZE_DISABLED)
2352 nflg &= ~WS_MAXIMIZEBOX;
2354 nflg |= WS_MAXIMIZEBOX;
2356 if (nflg != flag || nexflag != exflag) {
2358 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2359 if (nexflag != exflag)
2360 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2362 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2363 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2364 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2372 if (resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2377 set_title(NULL, conf_get_str(conf, CONF_wintitle));
2378 if (IsIconic(hwnd)) {
2380 conf_get_int(conf, CONF_win_name_always) ?
2381 window_name : icon_name);
2385 FontSpec *font = conf_get_fontspec(conf, CONF_font);
2386 FontSpec *prev_font = conf_get_fontspec(prev_conf,
2389 if (!strcmp(font->name, prev_font->name) ||
2390 !strcmp(conf_get_str(conf, CONF_line_codepage),
2391 conf_get_str(prev_conf, CONF_line_codepage)) ||
2392 font->isbold != prev_font->isbold ||
2393 font->height != prev_font->height ||
2394 font->charset != prev_font->charset ||
2395 conf_get_int(conf, CONF_font_quality) !=
2396 conf_get_int(prev_conf, CONF_font_quality) ||
2397 conf_get_int(conf, CONF_vtmode) !=
2398 conf_get_int(prev_conf, CONF_vtmode) ||
2399 conf_get_int(conf, CONF_bold_style) !=
2400 conf_get_int(prev_conf, CONF_bold_style) ||
2401 resize_action == RESIZE_DISABLED ||
2402 resize_action == RESIZE_EITHER ||
2403 resize_action != conf_get_int(prev_conf,
2404 CONF_resize_action))
2408 InvalidateRect(hwnd, NULL, TRUE);
2409 reset_window(init_lvl);
2411 conf_free(prev_conf);
2418 request_paste(NULL);
2424 term_pwron(term, TRUE);
2426 ldisc_echoedit_update(ldisc);
2432 launch_help(hwnd, NULL);
2436 * We get this if the System menu has been activated
2443 * We get this if the System menu has been activated
2444 * using the keyboard. This might happen from within
2445 * TranslateKey, in which case it really wants to be
2446 * followed by a `space' character to actually _bring
2447 * the menu up_ rather than just sitting there in
2448 * `ready to appear' state.
2450 show_mouseptr(1); /* make sure pointer is visible */
2452 PostMessage(hwnd, WM_CHAR, ' ', 0);
2454 case IDM_FULLSCREEN:
2458 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2459 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2461 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2462 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2464 * Ensure we haven't been sent a bogus SYSCOMMAND
2465 * which would cause us to reference invalid memory
2466 * and crash. Perhaps I'm just too paranoid here.
2468 if (i >= n_specials)
2471 back->special(backhandle, specials[i].code);
2476 #define X_POS(l) ((int)(short)LOWORD(l))
2477 #define Y_POS(l) ((int)(short)HIWORD(l))
2479 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2480 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2481 case WM_LBUTTONDOWN:
2482 case WM_MBUTTONDOWN:
2483 case WM_RBUTTONDOWN:
2487 if (message == WM_RBUTTONDOWN &&
2488 ((wParam & MK_CONTROL) ||
2489 (conf_get_int(conf, CONF_mouse_is_xterm) == 2))) {
2492 show_mouseptr(1); /* make sure pointer is visible */
2493 GetCursorPos(&cursorpos);
2494 TrackPopupMenu(popup_menus[CTXMENU].menu,
2495 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2496 cursorpos.x, cursorpos.y,
2504 case WM_LBUTTONDOWN:
2506 wParam |= MK_LBUTTON;
2509 case WM_MBUTTONDOWN:
2510 button = MBT_MIDDLE;
2511 wParam |= MK_MBUTTON;
2514 case WM_RBUTTONDOWN:
2516 wParam |= MK_RBUTTON;
2521 wParam &= ~MK_LBUTTON;
2525 button = MBT_MIDDLE;
2526 wParam &= ~MK_MBUTTON;
2531 wParam &= ~MK_RBUTTON;
2535 button = press = 0; /* shouldn't happen */
2539 * Special case: in full-screen mode, if the left
2540 * button is clicked in the very top left corner of the
2541 * window, we put up the System menu instead of doing
2545 char mouse_on_hotspot = 0;
2554 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2557 mi.cbSize = sizeof(MONITORINFO);
2558 GetMonitorInfo(mon, &mi);
2560 if (mi.rcMonitor.left == pt.x &&
2561 mi.rcMonitor.top == pt.y) {
2562 mouse_on_hotspot = 1;
2567 if (pt.x == 0 && pt.y == 0) {
2568 mouse_on_hotspot = 1;
2571 if (is_full_screen() && press &&
2572 button == MBT_LEFT && mouse_on_hotspot) {
2573 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2574 MAKELPARAM(pt.x, pt.y));
2581 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2582 wParam & MK_SHIFT, wParam & MK_CONTROL,
2586 term_mouse(term, button, translate_button(button), MA_RELEASE,
2587 TO_CHR_X(X_POS(lParam)),
2588 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2589 wParam & MK_CONTROL, is_alt_pressed());
2590 if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)))
2598 * Windows seems to like to occasionally send MOUSEMOVE
2599 * events even if the mouse hasn't moved. Don't unhide
2600 * the mouse pointer in this case.
2602 static WPARAM wp = 0;
2603 static LPARAM lp = 0;
2604 if (wParam != wp || lParam != lp ||
2605 last_mousemove != WM_MOUSEMOVE) {
2607 wp = wParam; lp = lParam;
2608 last_mousemove = WM_MOUSEMOVE;
2612 * Add the mouse position and message time to the random
2615 noise_ultralight(lParam);
2617 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2618 GetCapture() == hwnd) {
2620 if (wParam & MK_LBUTTON)
2622 else if (wParam & MK_MBUTTON)
2626 term_mouse(term, b, translate_button(b), MA_DRAG,
2627 TO_CHR_X(X_POS(lParam)),
2628 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2629 wParam & MK_CONTROL, is_alt_pressed());
2632 case WM_NCMOUSEMOVE:
2634 static WPARAM wp = 0;
2635 static LPARAM lp = 0;
2636 if (wParam != wp || lParam != lp ||
2637 last_mousemove != WM_NCMOUSEMOVE) {
2639 wp = wParam; lp = lParam;
2640 last_mousemove = WM_NCMOUSEMOVE;
2643 noise_ultralight(lParam);
2645 case WM_IGNORE_CLIP:
2646 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2648 case WM_DESTROYCLIPBOARD:
2650 term_deselect(term);
2651 ignore_clip = FALSE;
2658 hdc = BeginPaint(hwnd, &p);
2660 SelectPalette(hdc, pal, TRUE);
2661 RealizePalette(hdc);
2665 * We have to be careful about term_paint(). It will
2666 * set a bunch of character cells to INVALID and then
2667 * call do_paint(), which will redraw those cells and
2668 * _then mark them as done_. This may not be accurate:
2669 * when painting in WM_PAINT context we are restricted
2670 * to the rectangle which has just been exposed - so if
2671 * that only covers _part_ of a character cell and the
2672 * rest of it was already visible, that remainder will
2673 * not be redrawn at all. Accordingly, we must not
2674 * paint any character cell in a WM_PAINT context which
2675 * already has a pending update due to terminal output.
2676 * The simplest solution to this - and many, many
2677 * thanks to Hung-Te Lin for working all this out - is
2678 * not to do any actual painting at _all_ if there's a
2679 * pending terminal update: just mark the relevant
2680 * character cells as INVALID and wait for the
2681 * scheduled full update to sort it out.
2683 * I have a suspicion this isn't the _right_ solution.
2684 * An alternative approach would be to have terminal.c
2685 * separately track what _should_ be on the terminal
2686 * screen and what _is_ on the terminal screen, and
2687 * have two completely different types of redraw (one
2688 * for full updates, which syncs the former with the
2689 * terminal itself, and one for WM_PAINT which syncs
2690 * the latter with the former); yet another possibility
2691 * would be to have the Windows front end do what the
2692 * GTK one already does, and maintain a bitmap of the
2693 * current terminal appearance so that WM_PAINT becomes
2694 * completely trivial. However, this should do for now.
2696 term_paint(term, hdc,
2697 (p.rcPaint.left-offset_width)/font_width,
2698 (p.rcPaint.top-offset_height)/font_height,
2699 (p.rcPaint.right-offset_width-1)/font_width,
2700 (p.rcPaint.bottom-offset_height-1)/font_height,
2701 !term->window_update_pending);
2704 p.rcPaint.left < offset_width ||
2705 p.rcPaint.top < offset_height ||
2706 p.rcPaint.right >= offset_width + font_width*term->cols ||
2707 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2709 HBRUSH fillcolour, oldbrush;
2711 fillcolour = CreateSolidBrush (
2712 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2713 oldbrush = SelectObject(hdc, fillcolour);
2714 edge = CreatePen(PS_SOLID, 0,
2715 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2716 oldpen = SelectObject(hdc, edge);
2719 * Jordan Russell reports that this apparently
2720 * ineffectual IntersectClipRect() call masks a
2721 * Windows NT/2K bug causing strange display
2722 * problems when the PuTTY window is taller than
2723 * the primary monitor. It seems harmless enough...
2725 IntersectClipRect(hdc,
2726 p.rcPaint.left, p.rcPaint.top,
2727 p.rcPaint.right, p.rcPaint.bottom);
2729 ExcludeClipRect(hdc,
2730 offset_width, offset_height,
2731 offset_width+font_width*term->cols,
2732 offset_height+font_height*term->rows);
2734 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2735 p.rcPaint.right, p.rcPaint.bottom);
2737 /* SelectClipRgn(hdc, NULL); */
2739 SelectObject(hdc, oldbrush);
2740 DeleteObject(fillcolour);
2741 SelectObject(hdc, oldpen);
2744 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2745 SelectObject(hdc, GetStockObject(WHITE_PEN));
2753 * To protect against re-entrancy when Windows's recv()
2754 * immediately triggers a new WSAAsyncSelect window
2755 * message, we don't call select_result directly from this
2756 * handler but instead wait until we're back out at the
2757 * top level of the message loop.
2759 struct wm_netevent_params *params =
2760 snew(struct wm_netevent_params);
2761 params->wParam = wParam;
2762 params->lParam = lParam;
2763 queue_toplevel_callback(wm_netevent_callback, params);
2767 term_set_focus(term, TRUE);
2768 CreateCaret(hwnd, caretbm, font_width, font_height);
2770 flash_window(0); /* stop */
2776 term_set_focus(term, FALSE);
2778 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2781 case WM_ENTERSIZEMOVE:
2782 #ifdef RDB_DEBUG_PATCH
2783 debug((27, "WM_ENTERSIZEMOVE"));
2787 need_backend_resize = FALSE;
2789 case WM_EXITSIZEMOVE:
2792 #ifdef RDB_DEBUG_PATCH
2793 debug((27, "WM_EXITSIZEMOVE"));
2795 if (need_backend_resize) {
2796 term_size(term, conf_get_int(conf, CONF_height),
2797 conf_get_int(conf, CONF_width),
2798 conf_get_int(conf, CONF_savelines));
2799 InvalidateRect(hwnd, NULL, TRUE);
2804 * This does two jobs:
2805 * 1) Keep the sizetip uptodate
2806 * 2) Make sure the window size is _stepped_ in units of the font size.
2808 resize_action = conf_get_int(conf, CONF_resize_action);
2809 if (resize_action == RESIZE_TERM ||
2810 (resize_action == RESIZE_EITHER && !is_alt_pressed())) {
2811 int width, height, w, h, ew, eh;
2812 LPRECT r = (LPRECT) lParam;
2814 if (!need_backend_resize && resize_action == RESIZE_EITHER &&
2815 (conf_get_int(conf, CONF_height) != term->rows ||
2816 conf_get_int(conf, CONF_width) != term->cols)) {
2818 * Great! It seems that both the terminal size and the
2819 * font size have been changed and the user is now dragging.
2821 * It will now be difficult to get back to the configured
2824 * This would be easier but it seems to be too confusing.
2826 conf_set_int(conf, CONF_height, term->rows);
2827 conf_set_int(conf, CONF_width, term->cols);
2829 InvalidateRect(hwnd, NULL, TRUE);
2830 need_backend_resize = TRUE;
2833 width = r->right - r->left - extra_width;
2834 height = r->bottom - r->top - extra_height;
2835 w = (width + font_width / 2) / font_width;
2838 h = (height + font_height / 2) / font_height;
2841 UpdateSizeTip(hwnd, w, h);
2842 ew = width - w * font_width;
2843 eh = height - h * font_height;
2845 if (wParam == WMSZ_LEFT ||
2846 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2852 if (wParam == WMSZ_TOP ||
2853 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2863 int width, height, w, h, rv = 0;
2864 int window_border = conf_get_int(conf, CONF_window_border);
2865 int ex_width = extra_width + (window_border - offset_width) * 2;
2866 int ex_height = extra_height + (window_border - offset_height) * 2;
2867 LPRECT r = (LPRECT) lParam;
2869 width = r->right - r->left - ex_width;
2870 height = r->bottom - r->top - ex_height;
2872 w = (width + term->cols/2)/term->cols;
2873 h = (height + term->rows/2)/term->rows;
2874 if ( r->right != r->left + w*term->cols + ex_width)
2877 if (wParam == WMSZ_LEFT ||
2878 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2879 r->left = r->right - w*term->cols - ex_width;
2881 r->right = r->left + w*term->cols + ex_width;
2883 if (r->bottom != r->top + h*term->rows + ex_height)
2886 if (wParam == WMSZ_TOP ||
2887 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2888 r->top = r->bottom - h*term->rows - ex_height;
2890 r->bottom = r->top + h*term->rows + ex_height;
2894 /* break; (never reached) */
2895 case WM_FULLSCR_ON_MAX:
2896 fullscr_on_max = TRUE;
2899 sys_cursor_update();
2902 resize_action = conf_get_int(conf, CONF_resize_action);
2903 #ifdef RDB_DEBUG_PATCH
2904 debug((27, "WM_SIZE %s (%d,%d)",
2905 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2906 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2907 (wParam == SIZE_RESTORED && resizing) ? "to":
2908 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2910 LOWORD(lParam), HIWORD(lParam)));
2912 if (wParam == SIZE_MINIMIZED)
2914 conf_get_int(conf, CONF_win_name_always) ?
2915 window_name : icon_name);
2916 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2917 SetWindowText(hwnd, window_name);
2918 if (wParam == SIZE_RESTORED) {
2919 processed_resize = FALSE;
2920 clear_full_screen();
2921 if (processed_resize) {
2923 * Inhibit normal processing of this WM_SIZE; a
2924 * secondary one was triggered just now by
2925 * clear_full_screen which contained the correct
2931 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2932 fullscr_on_max = FALSE;
2933 processed_resize = FALSE;
2935 if (processed_resize) {
2937 * Inhibit normal processing of this WM_SIZE; a
2938 * secondary one was triggered just now by
2939 * make_full_screen which contained the correct client
2946 processed_resize = TRUE;
2948 if (resize_action == RESIZE_DISABLED) {
2949 /* A resize, well it better be a minimize. */
2953 int width, height, w, h;
2954 int window_border = conf_get_int(conf, CONF_window_border);
2956 width = LOWORD(lParam);
2957 height = HIWORD(lParam);
2959 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2961 prev_rows = term->rows;
2962 prev_cols = term->cols;
2963 if (resize_action == RESIZE_TERM) {
2964 w = width / font_width;
2966 h = height / font_height;
2971 * As below, if we're in the middle of an
2972 * interactive resize we don't call
2973 * back->size. In Windows 7, this case can
2974 * arise in maximisation as well via the Aero
2977 need_backend_resize = TRUE;
2978 conf_set_int(conf, CONF_height, h);
2979 conf_set_int(conf, CONF_width, w);
2981 term_size(term, h, w,
2982 conf_get_int(conf, CONF_savelines));
2986 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2988 if (resize_action == RESIZE_TERM) {
2989 w = (width-window_border*2) / font_width;
2991 h = (height-window_border*2) / font_height;
2993 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
2995 } else if (resize_action != RESIZE_FONT)
2999 } else if (wParam == SIZE_MINIMIZED) {
3001 } else if (resize_action == RESIZE_TERM ||
3002 (resize_action == RESIZE_EITHER &&
3003 !is_alt_pressed())) {
3004 w = (width-window_border*2) / font_width;
3006 h = (height-window_border*2) / font_height;
3011 * Don't call back->size in mid-resize. (To
3012 * prevent massive numbers of resize events
3013 * getting sent down the connection during an NT
3016 need_backend_resize = TRUE;
3017 conf_set_int(conf, CONF_height, h);
3018 conf_set_int(conf, CONF_width, w);
3020 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
3026 sys_cursor_update();
3029 switch (LOWORD(wParam)) {
3031 term_scroll(term, -1, 0);
3034 term_scroll(term, +1, 0);
3037 term_scroll(term, 0, +1);
3040 term_scroll(term, 0, -1);
3043 term_scroll(term, 0, +term->rows / 2);
3046 term_scroll(term, 0, -term->rows / 2);
3048 case SB_THUMBPOSITION:
3051 * Use GetScrollInfo instead of HIWORD(wParam) to get
3052 * 32-bit scroll position.
3057 si.cbSize = sizeof(si);
3058 si.fMask = SIF_TRACKPOS;
3059 if (GetScrollInfo(hwnd, SB_VERT, &si) == 0)
3060 si.nTrackPos = HIWORD(wParam);
3061 term_scroll(term, 1, si.nTrackPos);
3066 case WM_PALETTECHANGED:
3067 if ((HWND) wParam != hwnd && pal != NULL) {
3068 HDC hdc = get_ctx(NULL);
3070 if (RealizePalette(hdc) > 0)
3076 case WM_QUERYNEWPALETTE:
3078 HDC hdc = get_ctx(NULL);
3080 if (RealizePalette(hdc) > 0)
3092 * Add the scan code and keypress timing to the random
3095 noise_ultralight(lParam);
3098 * We don't do TranslateMessage since it disassociates the
3099 * resulting CHAR message from the KEYDOWN that sparked it,
3100 * which we occasionally don't want. Instead, we process
3101 * KEYDOWN, and call the Win32 translator functions so that
3102 * we get the translations under _our_ control.
3105 unsigned char buf[20];
3108 if (wParam == VK_PROCESSKEY || /* IME PROCESS key */
3109 wParam == VK_PACKET) { /* 'this key is a Unicode char' */
3110 if (message == WM_KEYDOWN) {
3113 m.message = WM_KEYDOWN;
3115 m.lParam = lParam & 0xdfff;
3116 TranslateMessage(&m);
3117 } else break; /* pass to Windows for default processing */
3119 len = TranslateKey(message, wParam, lParam, buf);
3121 return DefWindowProcW(hwnd, message, wParam, lParam);
3125 * We need not bother about stdin backlogs
3126 * here, because in GUI PuTTY we can't do
3127 * anything about it anyway; there's no means
3128 * of asking Windows to hold off on KEYDOWN
3129 * messages. We _have_ to buffer everything
3132 term_seen_key_event(term);
3134 ldisc_send(ldisc, (char *)buf, len, 1);
3140 case WM_INPUTLANGCHANGE:
3141 /* wParam == Font number */
3142 /* lParam == Locale */
3143 set_input_locale((HKL)lParam);
3144 sys_cursor_update();
3146 case WM_IME_STARTCOMPOSITION:
3148 HIMC hImc = ImmGetContext(hwnd);
3149 ImmSetCompositionFont(hImc, &lfont);
3150 ImmReleaseContext(hwnd, hImc);
3153 case WM_IME_COMPOSITION:
3159 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
3160 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
3162 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
3163 break; /* fall back to DefWindowProc */
3165 hIMC = ImmGetContext(hwnd);
3166 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3170 buff = snewn(n, char);
3171 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
3173 * Jaeyoun Chung reports that Korean character
3174 * input doesn't work correctly if we do a single
3175 * luni_send() covering the whole of buff. So
3176 * instead we luni_send the characters one by one.
3178 term_seen_key_event(term);
3179 /* don't divide SURROGATE PAIR */
3181 for (i = 0; i < n; i += 2) {
3182 WCHAR hs = *(unsigned short *)(buff+i);
3183 if (IS_HIGH_SURROGATE(hs) && i+2 < n) {
3184 WCHAR ls = *(unsigned short *)(buff+i+2);
3185 if (IS_LOW_SURROGATE(ls)) {
3186 luni_send(ldisc, (unsigned short *)(buff+i), 2, 1);
3191 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
3196 ImmReleaseContext(hwnd, hIMC);
3201 if (wParam & 0xFF00) {
3205 buf[0] = wParam >> 8;
3206 term_seen_key_event(term);
3208 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
3210 char c = (unsigned char) wParam;
3211 term_seen_key_event(term);
3213 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
3219 * Nevertheless, we are prepared to deal with WM_CHAR
3220 * messages, should they crop up. So if someone wants to
3221 * post the things to us as part of a macro manoeuvre,
3222 * we're ready to cope.
3225 static wchar_t pending_surrogate = 0;
3228 if (IS_HIGH_SURROGATE(c)) {
3229 pending_surrogate = c;
3230 } else if (IS_SURROGATE_PAIR(pending_surrogate, c)) {
3232 pair[0] = pending_surrogate;
3234 term_seen_key_event(term);
3235 luni_send(ldisc, pair, 2, 1);
3236 } else if (!IS_SURROGATE(c)) {
3237 term_seen_key_event(term);
3238 luni_send(ldisc, &c, 1, 1);
3242 case WM_SYSCOLORCHANGE:
3243 if (conf_get_int(conf, CONF_system_colour)) {
3244 /* Refresh palette from system colours. */
3245 /* XXX actually this zaps the entire palette. */
3248 /* Force a repaint of the terminal window. */
3249 term_invalidate(term);
3252 case WM_AGENT_CALLBACK:
3254 struct agent_callback *c = (struct agent_callback *)lParam;
3255 c->callback(c->callback_ctx, c->data, c->len);
3259 case WM_GOT_CLIPDATA:
3260 if (process_clipdata((HGLOBAL)lParam, wParam))
3261 term_do_paste(term);
3264 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
3265 int shift_pressed=0, control_pressed=0;
3267 if (message == WM_MOUSEWHEEL) {
3268 wheel_accumulator += (short)HIWORD(wParam);
3269 shift_pressed=LOWORD(wParam) & MK_SHIFT;
3270 control_pressed=LOWORD(wParam) & MK_CONTROL;
3273 wheel_accumulator += (int)wParam;
3274 if (GetKeyboardState(keys)!=0) {
3275 shift_pressed=keys[VK_SHIFT]&0x80;
3276 control_pressed=keys[VK_CONTROL]&0x80;
3280 /* process events when the threshold is reached */
3281 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
3284 /* reduce amount for next time */
3285 if (wheel_accumulator > 0) {
3287 wheel_accumulator -= WHEEL_DELTA;
3288 } else if (wheel_accumulator < 0) {
3290 wheel_accumulator += WHEEL_DELTA;
3294 if (send_raw_mouse &&
3295 !(conf_get_int(conf, CONF_mouse_override) &&
3297 /* Mouse wheel position is in screen coordinates for
3300 p.x = X_POS(lParam); p.y = Y_POS(lParam);
3301 if (ScreenToClient(hwnd, &p)) {
3302 /* send a mouse-down followed by a mouse up */
3303 term_mouse(term, b, translate_button(b),
3306 TO_CHR_Y(p.y), shift_pressed,
3307 control_pressed, is_alt_pressed());
3308 } /* else: not sure when this can fail */
3310 /* trigger a scroll */
3311 term_scroll(term, 0,
3313 -term->rows / 2 : term->rows / 2);
3321 * Any messages we don't process completely above are passed through to
3322 * DefWindowProc() for default processing.
3324 return DefWindowProcW(hwnd, message, wParam, lParam);
3328 * Move the system caret. (We maintain one, even though it's
3329 * invisible, for the benefit of blind people: apparently some
3330 * helper software tracks the system caret, so we should arrange to
3333 void sys_cursor(void *frontend, int x, int y)
3337 if (!term->has_focus) return;
3340 * Avoid gratuitously re-updating the cursor position and IMM
3341 * window if there's no actual change required.
3343 cx = x * font_width + offset_width;
3344 cy = y * font_height + offset_height;
3345 if (cx == caret_x && cy == caret_y)
3350 sys_cursor_update();
3353 static void sys_cursor_update(void)
3358 if (!term->has_focus) return;
3360 if (caret_x < 0 || caret_y < 0)
3363 SetCaretPos(caret_x, caret_y);
3365 /* IMM calls on Win98 and beyond only */
3366 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3368 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3369 osVersion.dwMinorVersion == 0) return; /* 95 */
3371 /* we should have the IMM functions */
3372 hIMC = ImmGetContext(hwnd);
3373 cf.dwStyle = CFS_POINT;
3374 cf.ptCurrentPos.x = caret_x;
3375 cf.ptCurrentPos.y = caret_y;
3376 ImmSetCompositionWindow(hIMC, &cf);
3378 ImmReleaseContext(hwnd, hIMC);
3382 * Draw a line of text in the window, at given character
3383 * coordinates, in given attributes.
3385 * We are allowed to fiddle with the contents of `text'.
3387 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3388 unsigned long attr, int lattr)
3391 int nfg, nbg, nfont;
3394 int force_manual_underline = 0;
3395 int fnt_width, char_width;
3396 int text_adjust = 0;
3398 int maxlen, remaining, opaque;
3399 int is_cursor = FALSE;
3400 static int *lpDx = NULL;
3401 static int lpDx_len = 0;
3403 int len2; /* for SURROGATE PAIR */
3405 lattr &= LATTR_MODE;
3407 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3409 if (attr & ATTR_WIDE)
3412 /* Only want the left half of double width lines */
3413 if (lattr != LATTR_NORM && x*2 >= term->cols)
3421 if ((attr & TATTR_ACTCURS) && (cursor_type == 0 || term->big_cursor)) {
3422 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3423 /* cursor fg and bg */
3424 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3429 if (vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3430 /* Assume a poorman font is borken in other ways too. */
3440 nfont |= FONT_WIDE + FONT_HIGH;
3443 if (attr & ATTR_NARROW)
3444 nfont |= FONT_NARROW;
3446 #ifdef USES_VTLINE_HACK
3447 /* Special hack for the VT100 linedraw glyphs. */
3448 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3449 switch ((unsigned char) (text[0])) {
3451 text_adjust = -2 * font_height / 5;
3454 text_adjust = -1 * font_height / 5;
3457 text_adjust = font_height / 5;
3460 text_adjust = 2 * font_height / 5;
3463 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3465 text[0] = ucsdata.unitab_xterm['q'];
3466 if (attr & ATTR_UNDER) {
3467 attr &= ~ATTR_UNDER;
3468 force_manual_underline = 1;
3473 /* Anything left as an original character set is unprintable. */
3474 if (DIRECT_CHAR(text[0]) &&
3475 (len < 2 || !IS_SURROGATE_PAIR(text[0], text[1]))) {
3477 for (i = 0; i < len; i++)
3482 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3485 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3486 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3487 if (bold_font_mode == BOLD_FONT && (attr & ATTR_BOLD))
3489 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3490 nfont |= FONT_UNDERLINE;
3491 another_font(nfont);
3492 if (!fonts[nfont]) {
3493 if (nfont & FONT_UNDERLINE)
3494 force_manual_underline = 1;
3495 /* Don't do the same for manual bold, it could be bad news. */
3497 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3499 another_font(nfont);
3501 nfont = FONT_NORMAL;
3502 if (attr & ATTR_REVERSE) {
3507 if (bold_colours && (attr & ATTR_BOLD) && !is_cursor) {
3508 if (nfg < 16) nfg |= 8;
3509 else if (nfg >= 256) nfg |= 1;
3511 if (bold_colours && (attr & ATTR_BLINK)) {
3512 if (nbg < 16) nbg |= 8;
3513 else if (nbg >= 256) nbg |= 1;
3517 SelectObject(hdc, fonts[nfont]);
3518 SetTextColor(hdc, fg);
3519 SetBkColor(hdc, bg);
3520 if (attr & TATTR_COMBINING)
3521 SetBkMode(hdc, TRANSPARENT);
3523 SetBkMode(hdc, OPAQUE);
3526 line_box.right = x + char_width * len;
3527 line_box.bottom = y + font_height;
3528 /* adjust line_box.right for SURROGATE PAIR & VARIATION SELECTOR */
3532 for (i = 0; i < len ; i++) {
3533 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3535 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i], text[i+1])) {
3536 rc_width += char_width;
3538 } else if (IS_LOW_VARSEL(text[i])) {
3541 rc_width += char_width;
3544 line_box.right = line_box.left + rc_width;
3547 /* Only want the left half of double width lines */
3548 if (line_box.right > font_width*term->cols+offset_width)
3549 line_box.right = font_width*term->cols+offset_width;
3551 if (font_varpitch) {
3553 * If we're using a variable-pitch font, we unconditionally
3554 * draw the glyphs one at a time and centre them in their
3555 * character cells (which means in particular that we must
3556 * disable the lpDx mechanism). This gives slightly odd but
3557 * generally reasonable results.
3559 xoffset = char_width / 2;
3560 SetTextAlign(hdc, TA_TOP | TA_CENTER | TA_NOUPDATECP);
3565 * In a fixed-pitch font, we draw the whole string in one go
3566 * in the normal way.
3569 SetTextAlign(hdc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
3574 opaque = TRUE; /* start by erasing the rectangle */
3575 for (remaining = len; remaining > 0;
3576 text += len, remaining -= len, x += char_width * len2) {
3577 len = (maxlen < remaining ? maxlen : remaining);
3578 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3581 if (remaining >= 1 && IS_SURROGATE_PAIR(text[0], text[1]))
3583 if (remaining-len >= 1 && IS_LOW_VARSEL(text[len]))
3585 else if (remaining-len >= 2 &&
3586 IS_HIGH_VARSEL(text[len], text[len+1]))
3590 if (len > lpDx_len) {
3591 lpDx_len = len * 9 / 8 + 16;
3592 lpDx = sresize(lpDx, lpDx_len, int);
3594 if (lpDx_maybe) lpDx_maybe = lpDx;
3599 /* only last char has dx width in SURROGATE PAIR and
3600 * VARIATION sequence */
3601 for (i = 0; i < len; i++) {
3602 lpDx[i] = char_width;
3603 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3604 if (i > 0) lpDx[i-1] = 0;
3607 lpDx[i] = char_width;
3608 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i],text[i+1])) {
3611 lpDx[i] = char_width;
3612 } else if (IS_LOW_VARSEL(text[i])) {
3613 if (i > 0) lpDx[i-1] = 0;
3614 lpDx[i] = char_width;
3619 /* We're using a private area for direct to font. (512 chars.) */
3620 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3621 /* Ho Hum, dbcs fonts are a PITA! */
3622 /* To display on W9x I have to convert to UCS */
3623 static wchar_t *uni_buf = 0;
3624 static int uni_len = 0;
3626 if (len > uni_len) {
3629 uni_buf = snewn(uni_len, wchar_t);
3632 for(nlen = mptr = 0; mptr<len; mptr++) {
3633 uni_buf[nlen] = 0xFFFD;
3634 if (IsDBCSLeadByteEx(ucsdata.font_codepage,
3635 (BYTE) text[mptr])) {
3637 dbcstext[0] = text[mptr] & 0xFF;
3638 dbcstext[1] = text[mptr+1] & 0xFF;
3639 lpDx[nlen] += char_width;
3640 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3641 dbcstext, 2, uni_buf+nlen, 1);
3647 dbcstext[0] = text[mptr] & 0xFF;
3648 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3649 dbcstext, 1, uni_buf+nlen, 1);
3656 ExtTextOutW(hdc, x + xoffset,
3657 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3658 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3659 &line_box, uni_buf, nlen,
3661 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3662 SetBkMode(hdc, TRANSPARENT);
3663 ExtTextOutW(hdc, x + xoffset - 1,
3664 y - font_height * (lattr ==
3665 LATTR_BOT) + text_adjust,
3666 ETO_CLIPPED, &line_box, uni_buf, nlen, lpDx_maybe);
3670 } else if (DIRECT_FONT(text[0])) {
3671 static char *directbuf = NULL;
3672 static int directlen = 0;
3674 if (len > directlen) {
3676 directbuf = sresize(directbuf, directlen, char);
3679 for (i = 0; i < len; i++)
3680 directbuf[i] = text[i] & 0xFF;
3682 ExtTextOut(hdc, x + xoffset,
3683 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3684 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3685 &line_box, directbuf, len, lpDx_maybe);
3686 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3687 SetBkMode(hdc, TRANSPARENT);
3689 /* GRR: This draws the character outside its box and
3690 * can leave 'droppings' even with the clip box! I
3691 * suppose I could loop it one character at a time ...
3694 * Or ... I could do a test print with "W", and use +1
3695 * or -1 for this shift depending on if the leftmost
3696 * column is blank...
3698 ExtTextOut(hdc, x + xoffset - 1,
3699 y - font_height * (lattr ==
3700 LATTR_BOT) + text_adjust,
3701 ETO_CLIPPED, &line_box, directbuf, len, lpDx_maybe);
3704 /* And 'normal' unicode characters */
3705 static WCHAR *wbuf = NULL;
3706 static int wlen = 0;
3712 wbuf = snewn(wlen, WCHAR);
3715 for (i = 0; i < len; i++)
3718 /* print Glyphs as they are, without Windows' Shaping*/
3719 general_textout(hdc, x + xoffset,
3720 y - font_height * (lattr==LATTR_BOT) + text_adjust,
3721 &line_box, wbuf, len, lpDx,
3722 opaque && !(attr & TATTR_COMBINING));
3724 /* And the shadow bold hack. */
3725 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3726 SetBkMode(hdc, TRANSPARENT);
3727 ExtTextOutW(hdc, x + xoffset - 1,
3728 y - font_height * (lattr ==
3729 LATTR_BOT) + text_adjust,
3730 ETO_CLIPPED, &line_box, wbuf, len, lpDx_maybe);
3735 * If we're looping round again, stop erasing the background
3738 SetBkMode(hdc, TRANSPARENT);
3741 if (lattr != LATTR_TOP && (force_manual_underline ||
3742 (und_mode == UND_LINE
3743 && (attr & ATTR_UNDER)))) {
3746 if (lattr == LATTR_BOT)
3747 dec = dec * 2 - font_height;
3749 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3750 MoveToEx(hdc, line_box.left, line_box.top + dec, NULL);
3751 LineTo(hdc, line_box.right, line_box.top + dec);
3752 oldpen = SelectObject(hdc, oldpen);
3753 DeleteObject(oldpen);
3758 * Wrapper that handles combining characters.
3760 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3761 unsigned long attr, int lattr)
3763 if (attr & TATTR_COMBINING) {
3764 unsigned long a = 0;
3766 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3767 if (len >= 2 && IS_SURROGATE_PAIR(text[0], text[1]))
3769 if (len-len0 >= 1 && IS_LOW_VARSEL(text[len0])) {
3770 attr &= ~TATTR_COMBINING;
3771 do_text_internal(ctx, x, y, text, len0+1, attr, lattr);
3774 a = TATTR_COMBINING;
3775 } else if (len-len0 >= 2 && IS_HIGH_VARSEL(text[len0], text[len0+1])) {
3776 attr &= ~TATTR_COMBINING;
3777 do_text_internal(ctx, x, y, text, len0+2, attr, lattr);
3780 a = TATTR_COMBINING;
3782 attr &= ~TATTR_COMBINING;
3786 if (len >= 1 && IS_SURROGATE_PAIR(text[0], text[1])) {
3787 do_text_internal(ctx, x, y, text, 2, attr | a, lattr);
3791 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3795 a = TATTR_COMBINING;
3798 do_text_internal(ctx, x, y, text, len, attr, lattr);
3801 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3802 unsigned long attr, int lattr)
3808 int ctype = cursor_type;
3810 lattr &= LATTR_MODE;
3812 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3813 if (*text != UCSWIDE) {
3814 do_text(ctx, x, y, text, len, attr, lattr);
3818 attr |= TATTR_RIGHTCURS;
3821 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3822 if (attr & ATTR_WIDE)
3829 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3832 pts[0].x = pts[1].x = pts[4].x = x;
3833 pts[2].x = pts[3].x = x + char_width - 1;
3834 pts[0].y = pts[3].y = pts[4].y = y;
3835 pts[1].y = pts[2].y = y + font_height - 1;
3836 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3837 Polyline(hdc, pts, 5);
3838 oldpen = SelectObject(hdc, oldpen);
3839 DeleteObject(oldpen);
3840 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3841 int startx, starty, dx, dy, length, i;
3844 starty = y + descent;
3847 length = char_width;
3850 if (attr & TATTR_RIGHTCURS)
3851 xadjust = char_width - 1;
3852 startx = x + xadjust;
3856 length = font_height;
3858 if (attr & TATTR_ACTCURS) {
3861 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3862 MoveToEx(hdc, startx, starty, NULL);
3863 LineTo(hdc, startx + dx * length, starty + dy * length);
3864 oldpen = SelectObject(hdc, oldpen);
3865 DeleteObject(oldpen);
3867 for (i = 0; i < length; i++) {
3869 SetPixel(hdc, startx, starty, colours[261]);
3878 /* This function gets the actual width of a character in the normal font.
3880 int char_width(Context ctx, int uc) {
3884 /* If the font max is the same as the font ave width then this
3885 * function is a no-op.
3887 if (!font_dualwidth) return 1;
3889 switch (uc & CSET_MASK) {
3891 uc = ucsdata.unitab_line[uc & 0xFF];
3894 uc = ucsdata.unitab_xterm[uc & 0xFF];
3897 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3900 if (DIRECT_FONT(uc)) {
3901 if (ucsdata.dbcs_screenfont) return 1;
3903 /* Speedup, I know of no font where ascii is the wrong width */
3904 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3907 if ( (uc & CSET_MASK) == CSET_ACP ) {
3908 SelectObject(hdc, fonts[FONT_NORMAL]);
3909 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3910 another_font(FONT_OEM);
3911 if (!fonts[FONT_OEM]) return 0;
3913 SelectObject(hdc, fonts[FONT_OEM]);
3917 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3918 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3921 /* Speedup, I know of no font where ascii is the wrong width */
3922 if (uc >= ' ' && uc <= '~') return 1;
3924 SelectObject(hdc, fonts[FONT_NORMAL]);
3925 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3926 /* Okay that one worked */ ;
3927 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3928 /* This should work on 9x too, but it's "less accurate" */ ;
3933 ibuf += font_width / 2 -1;
3939 DECL_WINDOWS_FUNCTION(static, BOOL, FlashWindowEx, (PFLASHWINFO));
3940 DECL_WINDOWS_FUNCTION(static, BOOL, ToUnicodeEx,
3941 (UINT, UINT, const BYTE *, LPWSTR, int, UINT, HKL));
3943 static void init_winfuncs(void)
3945 HMODULE user32_module = load_system32_dll("user32.dll");
3946 GET_WINDOWS_FUNCTION(user32_module, FlashWindowEx);
3947 GET_WINDOWS_FUNCTION(user32_module, ToUnicodeEx);
3951 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3952 * codes. Returns number of bytes used, zero to drop the message,
3953 * -1 to forward the message to Windows, or another negative number
3954 * to indicate a NUL-terminated "special" string.
3956 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3957 unsigned char *output)
3960 int scan, left_alt = 0, key_down, shift_state;
3962 unsigned char *p = output;
3963 static int alt_sum = 0;
3964 int funky_type = conf_get_int(conf, CONF_funky_type);
3965 int no_applic_k = conf_get_int(conf, CONF_no_applic_k);
3966 int ctrlaltkeys = conf_get_int(conf, CONF_ctrlaltkeys);
3967 int nethack_keypad = conf_get_int(conf, CONF_nethack_keypad);
3969 HKL kbd_layout = GetKeyboardLayout(0);
3971 static wchar_t keys_unicode[3];
3972 static int compose_char = 0;
3973 static WPARAM compose_keycode = 0;
3975 r = GetKeyboardState(keystate);
3977 memset(keystate, 0, sizeof(keystate));
3980 #define SHOW_TOASCII_RESULT
3981 { /* Tell us all about key events */
3982 static BYTE oldstate[256];
3983 static int first = 1;
3987 memcpy(oldstate, keystate, sizeof(oldstate));
3990 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3992 } else if ((HIWORD(lParam) & KF_UP)
3993 && scan == (HIWORD(lParam) & 0xFF)) {
3997 if (wParam >= VK_F1 && wParam <= VK_F20)
3998 debug(("K_F%d", wParam + 1 - VK_F1));
4011 debug(("VK_%02x", wParam));
4013 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
4015 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
4017 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
4018 if (ch >= ' ' && ch <= '~')
4019 debug((", '%c'", ch));
4021 debug((", $%02x", ch));
4023 if (keys_unicode[0])
4024 debug((", KB0=%04x", keys_unicode[0]));
4025 if (keys_unicode[1])
4026 debug((", KB1=%04x", keys_unicode[1]));
4027 if (keys_unicode[2])
4028 debug((", KB2=%04x", keys_unicode[2]));
4030 if ((keystate[VK_SHIFT] & 0x80) != 0)
4032 if ((keystate[VK_CONTROL] & 0x80) != 0)
4034 if ((HIWORD(lParam) & KF_EXTENDED))
4036 if ((HIWORD(lParam) & KF_UP))
4040 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
4041 else if ((HIWORD(lParam) & KF_UP))
4042 oldstate[wParam & 0xFF] ^= 0x80;
4044 oldstate[wParam & 0xFF] ^= 0x81;
4046 for (ch = 0; ch < 256; ch++)
4047 if (oldstate[ch] != keystate[ch])
4048 debug((", M%02x=%02x", ch, keystate[ch]));
4050 memcpy(oldstate, keystate, sizeof(oldstate));
4054 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
4055 keystate[VK_RMENU] = keystate[VK_MENU];
4059 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
4060 if ((funky_type == FUNKY_VT400 ||
4061 (funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
4063 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
4065 wParam = VK_EXECUTE;
4067 /* UnToggle NUMLock */
4068 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
4069 keystate[VK_NUMLOCK] ^= 1;
4072 /* And write back the 'adjusted' state */
4073 SetKeyboardState(keystate);
4076 /* Disable Auto repeat if required */
4077 if (term->repeat_off &&
4078 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
4081 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
4084 key_down = ((HIWORD(lParam) & KF_UP) == 0);
4086 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
4087 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
4089 keystate[VK_MENU] = 0;
4091 keystate[VK_RMENU] = 0x80;
4096 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
4097 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
4098 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
4100 /* Note if AltGr was pressed and if it was used as a compose key */
4101 if (!compose_state) {
4102 compose_keycode = 0x100;
4103 if (conf_get_int(conf, CONF_compose_key)) {
4104 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
4105 compose_keycode = wParam;
4107 if (wParam == VK_APPS)
4108 compose_keycode = wParam;
4111 if (wParam == compose_keycode) {
4112 if (compose_state == 0
4113 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
4115 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
4119 } else if (compose_state == 1 && wParam != VK_CONTROL)
4122 if (compose_state > 1 && left_alt)
4125 /* Sanitize the number pad if not using a PC NumPad */
4126 if (left_alt || (term->app_keypad_keys && !no_applic_k
4127 && funky_type != FUNKY_XTERM)
4128 || funky_type == FUNKY_VT400 || nethack_keypad || compose_state) {
4129 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
4133 nParam = VK_NUMPAD0;
4136 nParam = VK_NUMPAD1;
4139 nParam = VK_NUMPAD2;
4142 nParam = VK_NUMPAD3;
4145 nParam = VK_NUMPAD4;
4148 nParam = VK_NUMPAD5;
4151 nParam = VK_NUMPAD6;
4154 nParam = VK_NUMPAD7;
4157 nParam = VK_NUMPAD8;
4160 nParam = VK_NUMPAD9;
4163 nParam = VK_DECIMAL;
4167 if (keystate[VK_NUMLOCK] & 1)
4174 /* If a key is pressed and AltGr is not active */
4175 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
4176 /* Okay, prepare for most alts then ... */
4180 /* Lets see if it's a pattern we know all about ... */
4181 if (wParam == VK_PRIOR && shift_state == 1) {
4182 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
4185 if (wParam == VK_PRIOR && shift_state == 2) {
4186 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
4189 if (wParam == VK_NEXT && shift_state == 1) {
4190 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
4193 if (wParam == VK_NEXT && shift_state == 2) {
4194 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
4197 if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) {
4198 term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1));
4201 if (wParam == VK_INSERT && shift_state == 1) {
4202 request_paste(NULL);
4205 if (left_alt && wParam == VK_F4 && conf_get_int(conf, CONF_alt_f4)) {
4208 if (left_alt && wParam == VK_SPACE && conf_get_int(conf,
4210 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
4213 if (left_alt && wParam == VK_RETURN &&
4214 conf_get_int(conf, CONF_fullscreenonaltenter) &&
4215 (conf_get_int(conf, CONF_resize_action) != RESIZE_DISABLED)) {
4216 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
4220 /* Control-Numlock for app-keypad mode switch */
4221 if (wParam == VK_PAUSE && shift_state == 2) {
4222 term->app_keypad_keys ^= 1;
4226 /* Nethack keypad */
4227 if (nethack_keypad && !left_alt) {
4230 *p++ = "bB\002\002"[shift_state & 3];
4233 *p++ = "jJ\012\012"[shift_state & 3];
4236 *p++ = "nN\016\016"[shift_state & 3];
4239 *p++ = "hH\010\010"[shift_state & 3];
4242 *p++ = shift_state ? '.' : '.';
4245 *p++ = "lL\014\014"[shift_state & 3];
4248 *p++ = "yY\031\031"[shift_state & 3];
4251 *p++ = "kK\013\013"[shift_state & 3];
4254 *p++ = "uU\025\025"[shift_state & 3];
4259 /* Application Keypad */
4263 if (funky_type == FUNKY_VT400 ||
4264 (funky_type <= FUNKY_LINUX &&
4265 term->app_keypad_keys && !no_applic_k)) switch (wParam) {
4279 if (term->app_keypad_keys && !no_applic_k)
4316 if (funky_type == FUNKY_XTERM) {
4321 } else if (shift_state)
4328 if (funky_type == FUNKY_XTERM)
4332 if (funky_type == FUNKY_XTERM)
4336 if (funky_type == FUNKY_XTERM)
4341 if (HIWORD(lParam) & KF_EXTENDED)
4346 if (term->vt52_mode) {
4347 if (xkey >= 'P' && xkey <= 'S')
4348 p += sprintf((char *) p, "\x1B%c", xkey);
4350 p += sprintf((char *) p, "\x1B?%c", xkey);
4352 p += sprintf((char *) p, "\x1BO%c", xkey);
4357 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
4358 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x7F : 0x08);
4362 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
4363 /* We do the opposite of what is configured */
4364 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x08 : 0x7F);
4368 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
4374 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
4378 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
4382 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
4384 back->special(backhandle, TS_BRK);
4387 if (wParam == VK_PAUSE) { /* Break/Pause */
4392 /* Control-2 to Control-8 are special */
4393 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
4394 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
4397 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
4401 if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) {
4405 if (shift_state == 3 && wParam == 0xDE) {
4406 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
4409 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
4416 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
4417 * for integer decimal nn.)
4419 * We also deal with the weird ones here. Linux VCs replace F1
4420 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
4421 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
4427 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
4430 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
4433 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
4436 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
4439 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
4442 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
4445 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
4448 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
4451 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
4454 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
4487 if ((shift_state&2) == 0) switch (wParam) {
4507 /* Reorder edit keys to physical order */
4508 if (funky_type == FUNKY_VT400 && code <= 6)
4509 code = "\0\2\1\4\5\3\6"[code];
4511 if (term->vt52_mode && code > 0 && code <= 6) {
4512 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4516 if (funky_type == FUNKY_SCO && code >= 11 && code <= 34) {
4517 /* SCO function keys */
4518 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4521 case VK_F1: index = 0; break;
4522 case VK_F2: index = 1; break;
4523 case VK_F3: index = 2; break;
4524 case VK_F4: index = 3; break;
4525 case VK_F5: index = 4; break;
4526 case VK_F6: index = 5; break;
4527 case VK_F7: index = 6; break;
4528 case VK_F8: index = 7; break;
4529 case VK_F9: index = 8; break;
4530 case VK_F10: index = 9; break;
4531 case VK_F11: index = 10; break;
4532 case VK_F12: index = 11; break;
4534 if (keystate[VK_SHIFT] & 0x80) index += 12;
4535 if (keystate[VK_CONTROL] & 0x80) index += 24;
4536 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4539 if (funky_type == FUNKY_SCO && /* SCO small keypad */
4540 code >= 1 && code <= 6) {
4541 char codes[] = "HL.FIG";
4545 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4549 if ((term->vt52_mode || funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4555 if (term->vt52_mode)
4556 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4559 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4562 if (funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4563 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4566 if (funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4567 if (term->vt52_mode)
4568 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4570 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4573 if ((code == 1 || code == 4) &&
4574 conf_get_int(conf, CONF_rxvt_homeend)) {
4575 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4579 p += sprintf((char *) p, "\x1B[%d~", code);
4584 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4585 * some reason seems to send VK_CLEAR to Windows...).
4607 p += format_arrow_key((char *)p, term, xkey, shift_state);
4613 * Finally, deal with Return ourselves. (Win95 seems to
4614 * foul it up when Alt is pressed, for some reason.)
4616 if (wParam == VK_RETURN) { /* Return */
4622 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4623 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4628 /* Okay we've done everything interesting; let windows deal with
4629 * the boring stuff */
4633 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4634 if(keystate[VK_CAPITAL] != 0 &&
4635 conf_get_int(conf, CONF_xlat_capslockcyr)) {
4637 keystate[VK_CAPITAL] = 0;
4640 /* XXX how do we know what the max size of the keys array should
4641 * be is? There's indication on MS' website of an Inquire/InquireEx
4642 * functioning returning a KBINFO structure which tells us. */
4643 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT && p_ToUnicodeEx) {
4644 r = p_ToUnicodeEx(wParam, scan, keystate, keys_unicode,
4645 lenof(keys_unicode), 0, kbd_layout);
4647 /* XXX 'keys' parameter is declared in MSDN documentation as
4649 * The experience of a French user indicates that on
4650 * Win98, WORD[] should be passed in, but on Win2K, it should
4651 * be BYTE[]. German WinXP and my Win2K with "US International"
4652 * driver corroborate this.
4653 * Experimentally I've conditionalised the behaviour on the
4654 * Win9x/NT split, but I suspect it's worse than that.
4655 * See wishlist item `win-dead-keys' for more horrible detail
4656 * and speculations. */
4658 static WORD keys[3];
4659 static BYTE keysb[3];
4660 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4662 for (i = 0; i < r; i++) {
4663 keysb[i] = (BYTE)keys[i];
4665 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)keysb, r,
4666 keys_unicode, lenof(keys_unicode));
4669 #ifdef SHOW_TOASCII_RESULT
4670 if (r == 1 && !key_down) {
4672 if (in_utf(term) || ucsdata.dbcs_screenfont)
4673 debug((", (U+%04x)", alt_sum));
4675 debug((", LCH(%d)", alt_sum));
4677 debug((", ACH(%d)", keys_unicode[0]));
4682 for (r1 = 0; r1 < r; r1++) {
4683 debug(("%s%d", r1 ? "," : "", keys_unicode[r1]));
4692 for (i = 0; i < r; i++) {
4693 wchar_t wch = keys_unicode[i];
4695 if (compose_state == 2 && wch >= ' ' && wch < 0x80) {
4700 if (compose_state == 3 && wch >= ' ' && wch < 0x80) {
4704 if ((nc = check_compose(compose_char, wch)) == -1) {
4705 MessageBeep(MB_ICONHAND);
4709 term_seen_key_event(term);
4711 luni_send(ldisc, &keybuf, 1, 1);
4719 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4721 term_seen_key_event(term);
4723 luni_send(ldisc, &keybuf, 1, 1);
4725 char ch = (char) alt_sum;
4727 * We need not bother about stdin
4728 * backlogs here, because in GUI PuTTY
4729 * we can't do anything about it
4730 * anyway; there's no means of asking
4731 * Windows to hold off on KEYDOWN
4732 * messages. We _have_ to buffer
4733 * everything we're sent.
4735 term_seen_key_event(term);
4737 ldisc_send(ldisc, &ch, 1, 1);
4741 term_seen_key_event(term);
4743 luni_send(ldisc, &wch, 1, 1);
4746 if(capsOn && wch < 0x80) {
4749 cbuf[1] = xlat_uskbd2cyrllic(wch);
4750 term_seen_key_event(term);
4752 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4757 term_seen_key_event(term);
4759 luni_send(ldisc, cbuf +!left_alt, 1+!!left_alt, 1);
4765 /* This is so the ALT-Numpad and dead keys work correctly. */
4766 keys_unicode[0] = 0;
4770 /* If we're definitly not building up an ALT-54321 then clear it */
4772 keys_unicode[0] = 0;
4773 /* If we will be using alt_sum fix the 256s */
4774 else if (keys_unicode[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4775 keys_unicode[0] = 10;
4779 * ALT alone may or may not want to bring up the System menu.
4780 * If it's not meant to, we return 0 on presses or releases of
4781 * ALT, to show that we've swallowed the keystroke. Otherwise
4782 * we return -1, which means Windows will give the keystroke
4783 * its default handling (i.e. bring up the System menu).
4785 if (wParam == VK_MENU && !conf_get_int(conf, CONF_alt_only))
4791 void set_title(void *frontend, char *title)
4794 window_name = snewn(1 + strlen(title), char);
4795 strcpy(window_name, title);
4796 if (conf_get_int(conf, CONF_win_name_always) || !IsIconic(hwnd))
4797 SetWindowText(hwnd, title);
4800 void set_icon(void *frontend, char *title)
4803 icon_name = snewn(1 + strlen(title), char);
4804 strcpy(icon_name, title);
4805 if (!conf_get_int(conf, CONF_win_name_always) && IsIconic(hwnd))
4806 SetWindowText(hwnd, title);
4809 void set_sbar(void *frontend, int total, int start, int page)
4813 if (!conf_get_int(conf, is_full_screen() ?
4814 CONF_scrollbar_in_fullscreen : CONF_scrollbar))
4817 si.cbSize = sizeof(si);
4818 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4820 si.nMax = total - 1;
4824 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4827 Context get_ctx(void *frontend)
4833 SelectPalette(hdc, pal, FALSE);
4839 void free_ctx(Context ctx)
4841 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4842 ReleaseDC(hwnd, ctx);
4845 static void real_palette_set(int n, int r, int g, int b)
4848 logpal->palPalEntry[n].peRed = r;
4849 logpal->palPalEntry[n].peGreen = g;
4850 logpal->palPalEntry[n].peBlue = b;
4851 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4852 colours[n] = PALETTERGB(r, g, b);
4853 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4855 colours[n] = RGB(r, g, b);
4858 void palette_set(void *frontend, int n, int r, int g, int b)
4862 if (n >= NALLCOLOURS)
4864 real_palette_set(n, r, g, b);
4866 HDC hdc = get_ctx(frontend);
4867 UnrealizeObject(pal);
4868 RealizePalette(hdc);
4871 if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))
4872 /* If Default Background changes, we need to ensure any
4873 * space between the text area and the window border is
4875 InvalidateRect(hwnd, NULL, TRUE);
4879 void palette_reset(void *frontend)
4884 for (i = 0; i < NALLCOLOURS; i++) {
4886 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4887 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4888 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4889 logpal->palPalEntry[i].peFlags = 0;
4890 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4891 defpal[i].rgbtGreen,
4892 defpal[i].rgbtBlue);
4894 colours[i] = RGB(defpal[i].rgbtRed,
4895 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4900 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4901 hdc = get_ctx(frontend);
4902 RealizePalette(hdc);
4905 /* Default Background may have changed. Ensure any space between
4906 * text area and window border is redrawn. */
4907 InvalidateRect(hwnd, NULL, TRUE);
4911 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4916 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4919 lock = GlobalLock(clipdata);
4922 memcpy(lock, data, len);
4923 ((unsigned char *) lock)[len] = 0;
4924 GlobalUnlock(clipdata);
4927 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4929 if (OpenClipboard(hwnd)) {
4931 SetClipboardData(CF_TEXT, clipdata);
4934 GlobalFree(clipdata);
4937 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4941 * Note: unlike write_aclip() this will not append a nul.
4943 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
4945 HGLOBAL clipdata, clipdata2, clipdata3;
4947 void *lock, *lock2, *lock3;
4949 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4951 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4952 len * sizeof(wchar_t));
4953 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4955 if (!clipdata || !clipdata2) {
4957 GlobalFree(clipdata);
4959 GlobalFree(clipdata2);
4962 if (!(lock = GlobalLock(clipdata))) {
4963 GlobalFree(clipdata);
4964 GlobalFree(clipdata2);
4967 if (!(lock2 = GlobalLock(clipdata2))) {
4968 GlobalUnlock(clipdata);
4969 GlobalFree(clipdata);
4970 GlobalFree(clipdata2);
4974 memcpy(lock, data, len * sizeof(wchar_t));
4975 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4977 if (conf_get_int(conf, CONF_rtf_paste)) {
4978 wchar_t unitab[256];
4980 unsigned char *tdata = (unsigned char *)lock2;
4981 wchar_t *udata = (wchar_t *)lock;
4982 int rtflen = 0, uindex = 0, tindex = 0;
4984 int multilen, blen, alen, totallen, i;
4985 char before[16], after[4];
4986 int fgcolour, lastfgcolour = 0;
4987 int bgcolour, lastbgcolour = 0;
4988 int attrBold, lastAttrBold = 0;
4989 int attrUnder, lastAttrUnder = 0;
4990 int palette[NALLCOLOURS];
4992 FontSpec *font = conf_get_fontspec(conf, CONF_font);
4994 get_unitab(CP_ACP, unitab, 0);
4996 rtfsize = 100 + strlen(font->name);
4997 rtf = snewn(rtfsize, char);
4998 rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
4999 font->name, font->height*2);
5002 * Add colour palette
5003 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
5007 * First - Determine all colours in use
5008 * o Foregound and background colours share the same palette
5011 memset(palette, 0, sizeof(palette));
5012 for (i = 0; i < (len-1); i++) {
5013 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5014 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5016 if (attr[i] & ATTR_REVERSE) {
5017 int tmpcolour = fgcolour; /* Swap foreground and background */
5018 fgcolour = bgcolour;
5019 bgcolour = tmpcolour;
5022 if (bold_colours && (attr[i] & ATTR_BOLD)) {
5023 if (fgcolour < 8) /* ANSI colours */
5025 else if (fgcolour >= 256) /* Default colours */
5029 if (attr[i] & ATTR_BLINK) {
5030 if (bgcolour < 8) /* ANSI colours */
5032 else if (bgcolour >= 256) /* Default colours */
5036 palette[fgcolour]++;
5037 palette[bgcolour]++;
5041 * Next - Create a reduced palette
5044 for (i = 0; i < NALLCOLOURS; i++) {
5045 if (palette[i] != 0)
5046 palette[i] = ++numcolours;
5050 * Finally - Write the colour table
5052 rtf = sresize(rtf, rtfsize + (numcolours * 25), char);
5053 strcat(rtf, "{\\colortbl ;");
5054 rtflen = strlen(rtf);
5056 for (i = 0; i < NALLCOLOURS; i++) {
5057 if (palette[i] != 0) {
5058 rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);
5061 strcpy(&rtf[rtflen], "}");
5066 * We want to construct a piece of RTF that specifies the
5067 * same Unicode text. To do this we will read back in
5068 * parallel from the Unicode data in `udata' and the
5069 * non-Unicode data in `tdata'. For each character in
5070 * `tdata' which becomes the right thing in `udata' when
5071 * looked up in `unitab', we just copy straight over from
5072 * tdata. For each one that doesn't, we must WCToMB it
5073 * individually and produce a \u escape sequence.
5075 * It would probably be more robust to just bite the bullet
5076 * and WCToMB each individual Unicode character one by one,
5077 * then MBToWC each one back to see if it was an accurate
5078 * translation; but that strikes me as a horrifying number
5079 * of Windows API calls so I want to see if this faster way
5080 * will work. If it screws up badly we can always revert to
5081 * the simple and slow way.
5083 while (tindex < len2 && uindex < len &&
5084 tdata[tindex] && udata[uindex]) {
5085 if (tindex + 1 < len2 &&
5086 tdata[tindex] == '\r' &&
5087 tdata[tindex+1] == '\n') {
5093 * Set text attributes
5096 if (rtfsize < rtflen + 64) {
5097 rtfsize = rtflen + 512;
5098 rtf = sresize(rtf, rtfsize, char);
5102 * Determine foreground and background colours
5104 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5105 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5107 if (attr[tindex] & ATTR_REVERSE) {
5108 int tmpcolour = fgcolour; /* Swap foreground and background */
5109 fgcolour = bgcolour;
5110 bgcolour = tmpcolour;
5113 if (bold_colours && (attr[tindex] & ATTR_BOLD)) {
5114 if (fgcolour < 8) /* ANSI colours */
5116 else if (fgcolour >= 256) /* Default colours */
5120 if (attr[tindex] & ATTR_BLINK) {
5121 if (bgcolour < 8) /* ANSI colours */
5123 else if (bgcolour >= 256) /* Default colours */
5128 * Collect other attributes
5130 if (bold_font_mode != BOLD_NONE)
5131 attrBold = attr[tindex] & ATTR_BOLD;
5135 attrUnder = attr[tindex] & ATTR_UNDER;
5139 * o If video isn't reversed, ignore colour attributes for default foregound
5141 * o Special case where bolded text is displayed using the default foregound
5142 * and background colours - force to bolded RTF.
5144 if (!(attr[tindex] & ATTR_REVERSE)) {
5145 if (bgcolour >= 256) /* Default color */
5146 bgcolour = -1; /* No coloring */
5148 if (fgcolour >= 256) { /* Default colour */
5149 if (bold_colours && (fgcolour & 1) && bgcolour == -1)
5150 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
5152 fgcolour = -1; /* No coloring */
5157 * Write RTF text attributes
5159 if (lastfgcolour != fgcolour) {
5160 lastfgcolour = fgcolour;
5161 rtflen += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
5164 if (lastbgcolour != bgcolour) {
5165 lastbgcolour = bgcolour;
5166 rtflen += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
5169 if (lastAttrBold != attrBold) {
5170 lastAttrBold = attrBold;
5171 rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
5174 if (lastAttrUnder != attrUnder) {
5175 lastAttrUnder = attrUnder;
5176 rtflen += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
5180 if (unitab[tdata[tindex]] == udata[uindex]) {
5186 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
5187 NULL, 0, NULL, NULL);
5188 if (multilen != 1) {
5189 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
5191 alen = 1; strcpy(after, "}");
5193 blen = sprintf(before, "\\u%d", udata[uindex]);
5194 alen = 0; after[0] = '\0';
5197 assert(tindex + multilen <= len2);
5198 totallen = blen + alen;
5199 for (i = 0; i < multilen; i++) {
5200 if (tdata[tindex+i] == '\\' ||
5201 tdata[tindex+i] == '{' ||
5202 tdata[tindex+i] == '}')
5204 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
5205 totallen += 6; /* \par\r\n */
5206 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
5212 if (rtfsize < rtflen + totallen + 3) {
5213 rtfsize = rtflen + totallen + 512;
5214 rtf = sresize(rtf, rtfsize, char);
5217 strcpy(rtf + rtflen, before); rtflen += blen;
5218 for (i = 0; i < multilen; i++) {
5219 if (tdata[tindex+i] == '\\' ||
5220 tdata[tindex+i] == '{' ||
5221 tdata[tindex+i] == '}') {
5222 rtf[rtflen++] = '\\';
5223 rtf[rtflen++] = tdata[tindex+i];
5224 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
5225 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
5226 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
5227 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
5229 rtf[rtflen++] = tdata[tindex+i];
5232 strcpy(rtf + rtflen, after); rtflen += alen;
5238 rtf[rtflen++] = '}'; /* Terminate RTF stream */
5239 rtf[rtflen++] = '\0';
5240 rtf[rtflen++] = '\0';
5242 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
5243 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
5244 memcpy(lock3, rtf, rtflen);
5245 GlobalUnlock(clipdata3);
5251 GlobalUnlock(clipdata);
5252 GlobalUnlock(clipdata2);
5255 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
5257 if (OpenClipboard(hwnd)) {
5259 SetClipboardData(CF_UNICODETEXT, clipdata);
5260 SetClipboardData(CF_TEXT, clipdata2);
5262 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
5265 GlobalFree(clipdata);
5266 GlobalFree(clipdata2);
5270 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
5273 static DWORD WINAPI clipboard_read_threadfunc(void *param)
5275 HWND hwnd = (HWND)param;
5278 if (OpenClipboard(NULL)) {
5279 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
5280 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)1, (LPARAM)clipdata);
5281 } else if ((clipdata = GetClipboardData(CF_TEXT))) {
5282 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)0, (LPARAM)clipdata);
5290 static int process_clipdata(HGLOBAL clipdata, int unicode)
5292 sfree(clipboard_contents);
5293 clipboard_contents = NULL;
5294 clipboard_length = 0;
5297 wchar_t *p = GlobalLock(clipdata);
5301 /* Unwilling to rely on Windows having wcslen() */
5302 for (p2 = p; *p2; p2++);
5303 clipboard_length = p2 - p;
5304 clipboard_contents = snewn(clipboard_length + 1, wchar_t);
5305 memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t));
5306 clipboard_contents[clipboard_length] = L'\0';
5310 char *s = GlobalLock(clipdata);
5314 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
5315 clipboard_contents = snewn(i, wchar_t);
5316 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1,
5317 clipboard_contents, i);
5318 clipboard_length = i - 1;
5319 clipboard_contents[clipboard_length] = L'\0';
5327 void request_paste(void *frontend)
5330 * I always thought pasting was synchronous in Windows; the
5331 * clipboard access functions certainly _look_ synchronous,
5332 * unlike the X ones. But in fact it seems that in some
5333 * situations the contents of the clipboard might not be
5334 * immediately available, and the clipboard-reading functions
5335 * may block. This leads to trouble if the application
5336 * delivering the clipboard data has to get hold of it by -
5337 * for example - talking over a network connection which is
5338 * forwarded through this very PuTTY.
5340 * Hence, we spawn a subthread to read the clipboard, and do
5341 * our paste when it's finished. The thread will send a
5342 * message back to our main window when it terminates, and
5343 * that tells us it's OK to paste.
5345 DWORD in_threadid; /* required for Win9x */
5346 CreateThread(NULL, 0, clipboard_read_threadfunc,
5347 hwnd, 0, &in_threadid);
5350 void get_clip(void *frontend, wchar_t **p, int *len)
5353 *p = clipboard_contents;
5354 *len = clipboard_length;
5360 * Move `lines' lines from position `from' to position `to' in the
5363 void optimised_move(void *frontend, int to, int from, int lines)
5368 min = (to < from ? to : from);
5369 max = to + from - min;
5371 r.left = offset_width;
5372 r.right = offset_width + term->cols * font_width;
5373 r.top = offset_height + min * font_height;
5374 r.bottom = offset_height + (max + lines) * font_height;
5375 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
5380 * Print a message box and perform a fatal exit.
5382 void fatalbox(const char *fmt, ...)
5385 char *stuff, morestuff[100];
5388 stuff = dupvprintf(fmt, ap);
5390 sprintf(morestuff, "%.70s Fatal Error", appname);
5391 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5397 * Print a modal (Really Bad) message box and perform a fatal exit.
5399 void modalfatalbox(const char *fmt, ...)
5402 char *stuff, morestuff[100];
5405 stuff = dupvprintf(fmt, ap);
5407 sprintf(morestuff, "%.70s Fatal Error", appname);
5408 MessageBox(hwnd, stuff, morestuff,
5409 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
5415 * Print a message box and don't close the connection.
5417 void nonfatal(const char *fmt, ...)
5420 char *stuff, morestuff[100];
5423 stuff = dupvprintf(fmt, ap);
5425 sprintf(morestuff, "%.70s Error", appname);
5426 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5430 static BOOL flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout)
5432 if (p_FlashWindowEx) {
5434 fi.cbSize = sizeof(fi);
5436 fi.dwFlags = dwFlags;
5438 fi.dwTimeout = dwTimeout;
5439 return (*p_FlashWindowEx)(&fi);
5442 return FALSE; /* shrug */
5445 static void flash_window(int mode);
5446 static long next_flash;
5447 static int flashing = 0;
5450 * Timer for platforms where we must maintain window flashing manually
5453 static void flash_window_timer(void *ctx, unsigned long now)
5455 if (flashing && now == next_flash) {
5461 * Manage window caption / taskbar flashing, if enabled.
5462 * 0 = stop, 1 = maintain, 2 = start
5464 static void flash_window(int mode)
5466 int beep_ind = conf_get_int(conf, CONF_beep_ind);
5467 if ((mode == 0) || (beep_ind == B_IND_DISABLED)) {
5471 if (p_FlashWindowEx)
5472 flash_window_ex(FLASHW_STOP, 0, 0);
5474 FlashWindow(hwnd, FALSE);
5477 } else if (mode == 2) {
5481 if (p_FlashWindowEx) {
5482 /* For so-called "steady" mode, we use uCount=2, which
5483 * seems to be the traditional number of flashes used
5484 * by user notifications (e.g., by Explorer).
5485 * uCount=0 appears to enable continuous flashing, per
5486 * "flashing" mode, although I haven't seen this
5488 flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
5489 (beep_ind == B_IND_FLASH ? 0 : 2),
5490 0 /* system cursor blink rate */);
5491 /* No need to schedule timer */
5493 FlashWindow(hwnd, TRUE);
5494 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5498 } else if ((mode == 1) && (beep_ind == B_IND_FLASH)) {
5500 if (flashing && !p_FlashWindowEx) {
5501 FlashWindow(hwnd, TRUE); /* toggle */
5502 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5510 void do_beep(void *frontend, int mode)
5512 if (mode == BELL_DEFAULT) {
5514 * For MessageBeep style bells, we want to be careful of
5515 * timing, because they don't have the nice property of
5516 * PlaySound bells that each one cancels the previous
5517 * active one. So we limit the rate to one per 50ms or so.
5519 static long lastbeep = 0;
5522 beepdiff = GetTickCount() - lastbeep;
5523 if (beepdiff >= 0 && beepdiff < 50)
5527 * The above MessageBeep call takes time, so we record the
5528 * time _after_ it finishes rather than before it starts.
5530 lastbeep = GetTickCount();
5531 } else if (mode == BELL_WAVEFILE) {
5532 Filename *bell_wavefile = conf_get_filename(conf, CONF_bell_wavefile);
5533 if (!PlaySound(bell_wavefile->path, NULL,
5534 SND_ASYNC | SND_FILENAME)) {
5535 char buf[sizeof(bell_wavefile->path) + 80];
5537 sprintf(buf, "Unable to play sound file\n%s\n"
5538 "Using default sound instead", bell_wavefile->path);
5539 sprintf(otherbuf, "%.70s Sound Error", appname);
5540 MessageBox(hwnd, buf, otherbuf,
5541 MB_OK | MB_ICONEXCLAMATION);
5542 conf_set_int(conf, CONF_beep, BELL_DEFAULT);
5544 } else if (mode == BELL_PCSPEAKER) {
5545 static long lastbeep = 0;
5548 beepdiff = GetTickCount() - lastbeep;
5549 if (beepdiff >= 0 && beepdiff < 50)
5553 * We must beep in different ways depending on whether this
5554 * is a 95-series or NT-series OS.
5556 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
5560 lastbeep = GetTickCount();
5562 /* Otherwise, either visual bell or disabled; do nothing here */
5563 if (!term->has_focus) {
5564 flash_window(2); /* start */
5569 * Minimise or restore the window in response to a server-side
5572 void set_iconic(void *frontend, int iconic)
5574 if (IsIconic(hwnd)) {
5576 ShowWindow(hwnd, SW_RESTORE);
5579 ShowWindow(hwnd, SW_MINIMIZE);
5584 * Move the window in response to a server-side request.
5586 void move_window(void *frontend, int x, int y)
5588 int resize_action = conf_get_int(conf, CONF_resize_action);
5589 if (resize_action == RESIZE_DISABLED ||
5590 resize_action == RESIZE_FONT ||
5594 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5598 * Move the window to the top or bottom of the z-order in response
5599 * to a server-side request.
5601 void set_zorder(void *frontend, int top)
5603 if (conf_get_int(conf, CONF_alwaysontop))
5604 return; /* ignore */
5605 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5606 SWP_NOMOVE | SWP_NOSIZE);
5610 * Refresh the window in response to a server-side request.
5612 void refresh_window(void *frontend)
5614 InvalidateRect(hwnd, NULL, TRUE);
5618 * Maximise or restore the window in response to a server-side
5621 void set_zoomed(void *frontend, int zoomed)
5623 if (IsZoomed(hwnd)) {
5625 ShowWindow(hwnd, SW_RESTORE);
5628 ShowWindow(hwnd, SW_MAXIMIZE);
5633 * Report whether the window is iconic, for terminal reports.
5635 int is_iconic(void *frontend)
5637 return IsIconic(hwnd);
5641 * Report the window's position, for terminal reports.
5643 void get_window_pos(void *frontend, int *x, int *y)
5646 GetWindowRect(hwnd, &r);
5652 * Report the window's pixel size, for terminal reports.
5654 void get_window_pixels(void *frontend, int *x, int *y)
5657 GetWindowRect(hwnd, &r);
5658 *x = r.right - r.left;
5659 *y = r.bottom - r.top;
5663 * Return the window or icon title.
5665 char *get_window_title(void *frontend, int icon)
5667 return icon ? icon_name : window_name;
5671 * See if we're in full-screen mode.
5673 static int is_full_screen()
5675 if (!IsZoomed(hwnd))
5677 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
5682 /* Get the rect/size of a full screen window using the nearest available
5683 * monitor in multimon systems; default to something sensible if only
5684 * one monitor is present. */
5685 static int get_fullscreen_rect(RECT * ss)
5687 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
5690 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
5691 mi.cbSize = sizeof(mi);
5692 GetMonitorInfo(mon, &mi);
5694 /* structure copy */
5698 /* could also use code like this:
5699 ss->left = ss->top = 0;
5700 ss->right = GetSystemMetrics(SM_CXSCREEN);
5701 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5703 return GetClientRect(GetDesktopWindow(), ss);
5709 * Go full-screen. This should only be called when we are already
5712 static void make_full_screen()
5717 assert(IsZoomed(hwnd));
5719 if (is_full_screen())
5722 /* Remove the window furniture. */
5723 style = GetWindowLongPtr(hwnd, GWL_STYLE);
5724 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5725 if (conf_get_int(conf, CONF_scrollbar_in_fullscreen))
5726 style |= WS_VSCROLL;
5728 style &= ~WS_VSCROLL;
5729 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5731 /* Resize ourselves to exactly cover the nearest monitor. */
5732 get_fullscreen_rect(&ss);
5733 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5738 /* We may have changed size as a result */
5742 /* Tick the menu item in the System and context menus. */
5745 for (i = 0; i < lenof(popup_menus); i++)
5746 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED);
5751 * Clear the full-screen attributes.
5753 static void clear_full_screen()
5755 DWORD oldstyle, style;
5757 /* Reinstate the window furniture. */
5758 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
5759 style |= WS_CAPTION | WS_BORDER;
5760 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
5761 style &= ~WS_THICKFRAME;
5763 style |= WS_THICKFRAME;
5764 if (conf_get_int(conf, CONF_scrollbar))
5765 style |= WS_VSCROLL;
5767 style &= ~WS_VSCROLL;
5768 if (style != oldstyle) {
5769 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5770 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5771 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5775 /* Untick the menu item in the System and context menus. */
5778 for (i = 0; i < lenof(popup_menus); i++)
5779 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED);
5784 * Toggle full-screen mode.
5786 static void flip_full_screen()
5788 if (is_full_screen()) {
5789 ShowWindow(hwnd, SW_RESTORE);
5790 } else if (IsZoomed(hwnd)) {
5793 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5794 ShowWindow(hwnd, SW_MAXIMIZE);
5798 void frontend_keypress(void *handle)
5801 * Keypress termination in non-Close-On-Exit mode is not
5802 * currently supported in PuTTY proper, because the window
5803 * always has a perfectly good Close button anyway. So we do
5809 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5811 return term_data(term, is_stderr, data, len);
5814 int from_backend_untrusted(void *frontend, const char *data, int len)
5816 return term_data_untrusted(term, data, len);
5819 int from_backend_eof(void *frontend)
5821 return TRUE; /* do respond to incoming EOF with outgoing */
5824 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
5827 ret = cmdline_get_passwd_input(p, in, inlen);
5829 ret = term_get_userpass_input(term, p, in, inlen);
5833 void agent_schedule_callback(void (*callback)(void *, void *, int),
5834 void *callback_ctx, void *data, int len)
5836 struct agent_callback *c = snew(struct agent_callback);
5837 c->callback = callback;
5838 c->callback_ctx = callback_ctx;
5841 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);