2 * window.c - the PuTTY(tel) main program, which runs a PuTTY terminal
3 * emulator and backend in a window.
14 #define NO_MULTIMON /* winelib doesn't have this */
18 #define COMPILE_MULTIMON_STUBS
21 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
37 /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
38 * wParam are used by Windows, and should be masked off, so we shouldn't
39 * attempt to store information in them. Hence all these identifiers have
40 * the low 4 bits clear. Also, identifiers should < 0xF000. */
42 #define IDM_SHOWLOG 0x0010
43 #define IDM_NEWSESS 0x0020
44 #define IDM_DUPSESS 0x0030
45 #define IDM_RESTART 0x0040
46 #define IDM_RECONF 0x0050
47 #define IDM_CLRSB 0x0060
48 #define IDM_RESET 0x0070
49 #define IDM_HELP 0x0140
50 #define IDM_ABOUT 0x0150
51 #define IDM_SAVEDSESS 0x0160
52 #define IDM_COPYALL 0x0170
53 #define IDM_FULLSCREEN 0x0180
54 #define IDM_PASTE 0x0190
55 #define IDM_SPECIALSEP 0x0200
57 #define IDM_SPECIAL_MIN 0x0400
58 #define IDM_SPECIAL_MAX 0x0800
60 #define IDM_SAVED_MIN 0x1000
61 #define IDM_SAVED_MAX 0x5000
62 #define MENU_SAVED_STEP 16
63 /* Maximum number of sessions on saved-session submenu */
64 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
66 #define WM_IGNORE_CLIP (WM_APP + 2)
67 #define WM_FULLSCR_ON_MAX (WM_APP + 3)
68 #define WM_AGENT_CALLBACK (WM_APP + 4)
69 #define WM_GOT_CLIPDATA (WM_APP + 6)
71 /* Needed for Chinese support and apparently not always defined. */
73 #define VK_PROCESSKEY 0xE5
76 /* Mouse wheel support. */
78 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
81 #define WHEEL_DELTA 120
84 /* VK_PACKET, used to send Unicode characters in WM_KEYDOWNs */
86 #define VK_PACKET 0xE7
89 static Mouse_Button translate_button(Mouse_Button button);
90 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
91 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
92 unsigned char *output);
93 static void conftopalette(void);
94 static void systopalette(void);
95 static void init_palette(void);
96 static void init_fonts(int, int);
97 static void another_font(int);
98 static void deinit_fonts(void);
99 static void set_input_locale(HKL);
100 static void update_savedsess_menu(void);
101 static void init_winfuncs(void);
103 static int is_full_screen(void);
104 static void make_full_screen(void);
105 static void clear_full_screen(void);
106 static void flip_full_screen(void);
107 static int process_clipdata(HGLOBAL clipdata, int unicode);
109 /* Window layout information */
110 static void reset_window(int);
111 static int extra_width, extra_height;
112 static int font_width, font_height, font_dualwidth, font_varpitch;
113 static int offset_width, offset_height;
114 static int was_zoomed = 0;
115 static int prev_rows, prev_cols;
117 static void flash_window(int mode);
118 static void sys_cursor_update(void);
119 static int get_fullscreen_rect(RECT * ss);
121 static int caret_x = -1, caret_y = -1;
123 static int kbd_codepage;
126 static Backend *back;
127 static void *backhandle;
129 static struct unicode_data ucsdata;
130 static int session_closed;
131 static int reconfiguring = FALSE;
133 static const struct telnet_special *specials = NULL;
134 static HMENU specials_menu = NULL;
135 static int n_specials = 0;
137 static wchar_t *clipboard_contents;
138 static size_t clipboard_length;
140 #define TIMING_TIMER_ID 1234
141 static long timing_next_time;
146 enum { SYSMENU, CTXMENU };
147 static HMENU savedsess_menu;
149 struct wm_netevent_params {
150 /* Used to pass data to wm_netevent_callback */
155 Conf *conf; /* exported to windlg.c */
157 static void conf_cache_data(void);
161 static struct sesslist sesslist; /* for saved-session menu */
163 struct agent_callback {
164 void (*callback)(void *, void *, int);
170 #define FONT_NORMAL 0
172 #define FONT_UNDERLINE 2
173 #define FONT_BOLDUND 3
174 #define FONT_WIDE 0x04
175 #define FONT_HIGH 0x08
176 #define FONT_NARROW 0x10
178 #define FONT_OEM 0x20
179 #define FONT_OEMBOLD 0x21
180 #define FONT_OEMUND 0x22
181 #define FONT_OEMBOLDUND 0x23
183 #define FONT_MAXNO 0x40
185 static HFONT fonts[FONT_MAXNO];
186 static LOGFONT lfont;
187 static int fontflag[FONT_MAXNO];
189 BOLD_NONE, BOLD_SHADOW, BOLD_FONT
191 static int bold_colours;
197 #define NCFGCOLOURS 22
198 #define NEXTCOLOURS 240
199 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
200 static COLORREF colours[NALLCOLOURS];
202 static LPLOGPALETTE logpal;
203 static RGBTRIPLE defpal[NALLCOLOURS];
205 static HBITMAP caretbm;
207 static int dbltime, lasttime, lastact;
208 static Mouse_Button lastbtn;
210 /* this allows xterm-style mouse handling. */
211 static int send_raw_mouse = 0;
212 static int wheel_accumulator = 0;
214 static int busy_status = BUSY_NOT;
216 static char *window_name, *icon_name;
218 static int compose_state = 0;
220 static UINT wm_mousewheel = WM_MOUSEWHEEL;
222 #define IS_HIGH_VARSEL(wch1, wch2) \
223 ((wch1) == 0xDB40 && ((wch2) >= 0xDD00 && (wch2) <= 0xDDEF))
224 #define IS_LOW_VARSEL(wch) \
225 (((wch) >= 0x180B && (wch) <= 0x180D) || /* MONGOLIAN FREE VARIATION SELECTOR */ \
226 ((wch) >= 0xFE00 && (wch) <= 0xFE0F)) /* VARIATION SELECTOR 1-16 */
228 const int share_can_be_downstream = TRUE;
229 const int share_can_be_upstream = TRUE;
231 /* Dummy routine, only required in plink. */
232 void frontend_echoedit_update(void *frontend, int echo, int edit)
236 int frontend_is_utf8(void *frontend)
238 return ucsdata.line_codepage == CP_UTF8;
241 char *get_ttymode(void *frontend, const char *mode)
243 return term_get_ttymode(term, mode);
246 static void start_backend(void)
249 char msg[1024], *title;
254 * Select protocol. This is farmed out into a table in a
255 * separate file to enable an ssh-free variant.
257 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
259 char *str = dupprintf("%s Internal Error", appname);
260 MessageBox(NULL, "Unsupported protocol number found",
261 str, MB_OK | MB_ICONEXCLAMATION);
266 error = back->init(NULL, &backhandle, conf,
267 conf_get_str(conf, CONF_host),
268 conf_get_int(conf, CONF_port),
270 conf_get_int(conf, CONF_tcp_nodelay),
271 conf_get_int(conf, CONF_tcp_keepalives));
272 back->provide_logctx(backhandle, logctx);
274 char *str = dupprintf("%s Error", appname);
275 sprintf(msg, "Unable to open connection to\n"
276 "%.800s\n" "%s", conf_dest(conf), error);
277 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
281 window_name = icon_name = NULL;
282 title = conf_get_str(conf, CONF_wintitle);
284 sprintf(msg, "%s - %s", realhost, appname);
288 set_title(NULL, title);
289 set_icon(NULL, title);
292 * Connect the terminal to the backend for resize purposes.
294 term_provide_resize_fn(term, back->size, backhandle);
297 * Set up a line discipline.
299 ldisc = ldisc_create(conf, term, back, backhandle, NULL);
302 * Destroy the Restart Session menu item. (This will return
303 * failure if it's already absent, as it will be the very first
304 * time we call this function. We ignore that, because as long
305 * as the menu item ends up not being there, we don't care
306 * whether it was us who removed it or not!)
308 for (i = 0; i < lenof(popup_menus); i++) {
309 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
312 session_closed = FALSE;
315 static void close_session(void *ignored_context)
320 session_closed = TRUE;
321 sprintf(morestuff, "%.70s (inactive)", appname);
322 set_icon(NULL, morestuff);
323 set_title(NULL, morestuff);
330 back->free(backhandle);
333 term_provide_resize_fn(term, NULL, NULL);
334 update_specials_menu(NULL);
338 * Show the Restart Session menu item. Do a precautionary
339 * delete first to ensure we never end up with more than one.
341 for (i = 0; i < lenof(popup_menus); i++) {
342 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
343 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
344 IDM_RESTART, "&Restart Session");
348 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
352 int guess_width, guess_height;
354 dll_hijacking_protection();
358 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
362 InitCommonControls();
364 /* Set Explicit App User Model Id so that jump lists don't cause
365 PuTTY to hang on to removable media. */
367 set_explicit_app_user_model_id();
369 /* Ensure a Maximize setting in Explorer doesn't maximise the
375 char *str = dupprintf("%s Fatal Error", appname);
376 MessageBox(NULL, "Windows refuses to report a version",
377 str, MB_OK | MB_ICONEXCLAMATION);
383 * If we're running a version of Windows that doesn't support
384 * WM_MOUSEWHEEL, find out what message number we should be
387 if (osVersion.dwMajorVersion < 4 ||
388 (osVersion.dwMajorVersion == 4 &&
389 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
390 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
401 hr = CoInitialize(NULL);
402 if (hr != S_OK && hr != S_FALSE) {
403 char *str = dupprintf("%s Fatal Error", appname);
404 MessageBox(NULL, "Failed to initialize COM subsystem",
405 str, MB_OK | MB_ICONEXCLAMATION);
411 * Process the command line.
416 /* By default, we bring up the config dialog, rather than launching
417 * a session. This gets set to TRUE if something happens to change
418 * that (e.g., a hostname is specified on the command-line). */
419 int allow_launch = FALSE;
421 default_protocol = be_default_protocol;
422 /* Find the appropriate default port. */
424 Backend *b = backend_from_proto(default_protocol);
425 default_port = 0; /* illegal */
427 default_port = b->default_port;
429 conf_set_int(conf, CONF_logtype, LGTYP_NONE);
431 do_defaults(NULL, conf);
436 * Process a couple of command-line options which are more
437 * easily dealt with before the line is broken up into words.
438 * These are the old-fashioned but convenient @sessionname and
439 * the internal-use-only &sharedmemoryhandle, plus the &R
440 * prefix for -restrict-acl, all of which are used by PuTTYs
441 * auto-launching each other via System-menu options.
443 while (*p && isspace(*p))
445 if (*p == '&' && p[1] == 'R' &&
446 (!p[2] || p[2] == '@' || p[2] == '&')) {
447 /* &R restrict-acl prefix */
448 restrict_process_acl();
449 restricted_acl = TRUE;
455 * An initial @ means that the whole of the rest of the
456 * command line should be treated as the name of a saved
457 * session, with _no quoting or escaping_. This makes it a
458 * very convenient means of automated saved-session
459 * launching, via IDM_SAVEDSESS or Windows 7 jump lists.
462 while (i > 1 && isspace(p[i - 1]))
465 do_defaults(p + 1, conf);
466 if (!conf_launchable(conf) && !do_config()) {
469 allow_launch = TRUE; /* allow it to be launched directly */
470 } else if (*p == '&') {
472 * An initial & means we've been given a command line
473 * containing the hex value of a HANDLE for a file
474 * mapping object, which we must then interpret as a
480 if (sscanf(p + 1, "%p:%u", &filemap, &cpsize) == 2 &&
481 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
482 0, 0, cpsize)) != NULL) {
483 conf_deserialise(conf, cp, cpsize);
485 CloseHandle(filemap);
486 } else if (!do_config()) {
491 /* Do-nothing case for an empty command line - or rather,
492 * for a command line that's empty _after_ we strip off
496 * Otherwise, break up the command line and deal with
502 split_into_argv(cmdline, &argc, &argv, NULL);
504 for (i = 0; i < argc; i++) {
508 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
511 cmdline_error("option \"%s\" requires an argument", p);
512 } else if (ret == 2) {
513 i++; /* skip next argument */
514 } else if (ret == 1) {
515 continue; /* nothing further needs doing */
516 } else if (!strcmp(p, "-cleanup")) {
518 * `putty -cleanup'. Remove all registry
519 * entries associated with PuTTY, and also find
520 * and delete the random seed file.
523 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
524 "associated with %s, and will also remove\n"
525 "the random seed file. (This only affects the\n"
526 "currently logged-in user.)\n"
528 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
529 "Are you really sure you want to continue?",
531 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);
847 if (restricted_acl) {
848 logevent(NULL, "Running with restricted process ACL");
854 * Set up the initial input locale.
856 set_input_locale(GetKeyboardLayout(0));
859 * Finally show the window!
861 ShowWindow(hwnd, show);
862 SetForegroundWindow(hwnd);
865 * Set the palette up.
871 term_set_focus(term, GetForegroundWindow() == hwnd);
879 if (toplevel_callback_pending() ||
880 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
882 * If we have anything we'd like to do immediately, set
883 * the timeout for MsgWaitForMultipleObjects to zero so
884 * that we'll only do a quick check of our handles and
885 * then get on with whatever that was.
887 * One such option is a pending toplevel callback. The
888 * other is a non-empty Windows message queue, which you'd
889 * think we could leave to MsgWaitForMultipleObjects to
890 * check for us along with all the handles, but in fact we
891 * can't because once PeekMessage in one iteration of this
892 * loop has removed a message from the queue, the whole
893 * queue is considered uninteresting by the next
894 * invocation of MWFMO. So we check ourselves whether the
895 * message queue is non-empty, and if so, set this timeout
896 * to zero to ensure MWFMO doesn't block.
901 /* The messages seem unreliable; especially if we're being tricky */
902 term_set_focus(term, GetForegroundWindow() == hwnd);
905 handles = handle_get_events(&nhandles);
907 n = MsgWaitForMultipleObjects(nhandles, handles, FALSE,
908 timeout, QS_ALLINPUT);
910 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
911 handle_got_event(handles[n - WAIT_OBJECT_0]);
916 while (PeekMessageW(&msg, NULL, 0, 0, PM_REMOVE)) {
917 if (msg.message == WM_QUIT)
918 goto finished; /* two-level break */
920 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
921 DispatchMessageW(&msg);
924 * WM_NETEVENT messages seem to jump ahead of others in
925 * the message queue. I'm not sure why; the docs for
926 * PeekMessage mention that messages are prioritised in
927 * some way, but I'm unclear on which priorities go where.
929 * Anyway, in practice I observe that WM_NETEVENT seems to
930 * jump to the head of the queue, which means that if we
931 * were to only process one message every time round this
932 * loop, we'd get nothing but NETEVENTs if the server
933 * flooded us with data, and stop responding to any other
934 * kind of window message. So instead, we keep on round
935 * this loop until we've consumed at least one message
936 * that _isn't_ a NETEVENT, or run out of messages
937 * completely (whichever comes first). And we don't go to
938 * run_toplevel_callbacks (which is where the netevents
939 * are actually processed, causing fresh NETEVENT messages
940 * to appear) until we've done this.
942 if (msg.message != WM_NETEVENT)
946 run_toplevel_callbacks();
950 cleanup_exit(msg.wParam); /* this doesn't return... */
951 return msg.wParam; /* ... but optimiser doesn't know */
957 void cleanup_exit(int code)
968 if (conf_get_int(conf, CONF_protocol) == PROT_SSH) {
983 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
985 char *do_select(SOCKET skt, int startup)
990 events = (FD_CONNECT | FD_READ | FD_WRITE |
991 FD_OOB | FD_CLOSE | FD_ACCEPT);
996 return "do_select(): internal error (hwnd==NULL)";
997 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
998 switch (p_WSAGetLastError()) {
1000 return "Network is down";
1002 return "WSAAsyncSelect(): unknown error";
1009 * Refresh the saved-session submenu from `sesslist'.
1011 static void update_savedsess_menu(void)
1014 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
1015 /* skip sesslist.sessions[0] == Default Settings */
1017 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
1018 : MENU_SAVED_MAX+1);
1020 AppendMenu(savedsess_menu, MF_ENABLED,
1021 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
1022 sesslist.sessions[i]);
1023 if (sesslist.nsessions <= 1)
1024 AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)");
1028 * Update the Special Commands submenu.
1030 void update_specials_menu(void *frontend)
1036 specials = back->get_specials(backhandle);
1041 /* We can't use Windows to provide a stack for submenus, so
1042 * here's a lame "stack" that will do for now. */
1043 HMENU saved_menu = NULL;
1045 new_menu = CreatePopupMenu();
1046 for (i = 0; nesting > 0; i++) {
1047 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
1048 switch (specials[i].code) {
1050 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
1053 assert(nesting < 2);
1055 saved_menu = new_menu; /* XXX lame stacking */
1056 new_menu = CreatePopupMenu();
1057 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
1058 (UINT_PTR) new_menu, specials[i].name);
1063 new_menu = saved_menu; /* XXX lame stacking */
1068 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
1073 /* Squirrel the highest special. */
1080 for (j = 0; j < lenof(popup_menus); j++) {
1081 if (specials_menu) {
1082 /* XXX does this free up all submenus? */
1083 DeleteMenu(popup_menus[j].menu, (UINT_PTR)specials_menu,
1085 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
1088 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1089 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
1090 (UINT_PTR) new_menu, "S&pecial Command");
1091 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1092 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
1095 specials_menu = new_menu;
1098 static void update_mouse_pointer(void)
1101 int force_visible = FALSE;
1102 static int forced_visible = FALSE;
1103 switch (busy_status) {
1106 curstype = IDC_ARROW;
1108 curstype = IDC_IBEAM;
1111 curstype = IDC_APPSTARTING; /* this may be an abuse */
1112 force_visible = TRUE;
1115 curstype = IDC_WAIT;
1116 force_visible = TRUE;
1122 HCURSOR cursor = LoadCursor(NULL, curstype);
1123 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1124 SetCursor(cursor); /* force redraw of cursor at current posn */
1126 if (force_visible != forced_visible) {
1127 /* We want some cursor shapes to be visible always.
1128 * Along with show_mouseptr(), this manages the ShowCursor()
1129 * counter such that if we switch back to a non-force_visible
1130 * cursor, the previous visibility state is restored. */
1131 ShowCursor(force_visible);
1132 forced_visible = force_visible;
1136 void set_busy_status(void *frontend, int status)
1138 busy_status = status;
1139 update_mouse_pointer();
1143 * set or clear the "raw mouse message" mode
1145 void set_raw_mouse_mode(void *frontend, int activate)
1147 activate = activate && !conf_get_int(conf, CONF_no_mouse_rep);
1148 send_raw_mouse = activate;
1149 update_mouse_pointer();
1153 * Print a message box and close the connection.
1155 void connection_fatal(void *frontend, const char *fmt, ...)
1158 char *stuff, morestuff[100];
1161 stuff = dupvprintf(fmt, ap);
1163 sprintf(morestuff, "%.70s Fatal Error", appname);
1164 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1167 if (conf_get_int(conf, CONF_close_on_exit) == FORCE_ON)
1170 queue_toplevel_callback(close_session, NULL);
1175 * Report an error at the command-line parsing stage.
1177 void cmdline_error(const char *fmt, ...)
1180 char *stuff, morestuff[100];
1183 stuff = dupvprintf(fmt, ap);
1185 sprintf(morestuff, "%.70s Command Line Error", appname);
1186 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1192 * Actually do the job requested by a WM_NETEVENT
1194 static void wm_netevent_callback(void *vctx)
1196 struct wm_netevent_params *params = (struct wm_netevent_params *)vctx;
1197 select_result(params->wParam, params->lParam);
1202 * Copy the colour palette from the configuration data into defpal.
1203 * This is non-trivial because the colour indices are different.
1205 static void conftopalette(void)
1208 static const int ww[] = {
1209 256, 257, 258, 259, 260, 261,
1210 0, 8, 1, 9, 2, 10, 3, 11,
1211 4, 12, 5, 13, 6, 14, 7, 15
1214 for (i = 0; i < 22; i++) {
1216 defpal[w].rgbtRed = conf_get_int_int(conf, CONF_colours, i*3+0);
1217 defpal[w].rgbtGreen = conf_get_int_int(conf, CONF_colours, i*3+1);
1218 defpal[w].rgbtBlue = conf_get_int_int(conf, CONF_colours, i*3+2);
1220 for (i = 0; i < NEXTCOLOURS; i++) {
1222 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1223 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1224 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1225 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
1227 int shade = i - 216;
1228 shade = shade * 10 + 8;
1229 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1230 defpal[i+16].rgbtBlue = shade;
1234 /* Override with system colours if appropriate */
1235 if (conf_get_int(conf, CONF_system_colour))
1240 * Override bit of defpal with colours from the system.
1241 * (NB that this takes a copy the system colours at the time this is called,
1242 * so subsequent colour scheme changes don't take effect. To fix that we'd
1243 * probably want to be using GetSysColorBrush() and the like.)
1245 static void systopalette(void)
1248 static const struct { int nIndex; int norm; int bold; } or[] =
1250 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1251 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1252 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1253 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1256 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1257 COLORREF colour = GetSysColor(or[i].nIndex);
1258 defpal[or[i].norm].rgbtRed =
1259 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1260 defpal[or[i].norm].rgbtGreen =
1261 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1262 defpal[or[i].norm].rgbtBlue =
1263 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1268 * Set up the colour palette.
1270 static void init_palette(void)
1273 HDC hdc = GetDC(hwnd);
1275 if (conf_get_int(conf, CONF_try_palette) &&
1276 GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1278 * This is a genuine case where we must use smalloc
1279 * because the snew macros can't cope.
1281 logpal = smalloc(sizeof(*logpal)
1282 - sizeof(logpal->palPalEntry)
1283 + NALLCOLOURS * sizeof(PALETTEENTRY));
1284 logpal->palVersion = 0x300;
1285 logpal->palNumEntries = NALLCOLOURS;
1286 for (i = 0; i < NALLCOLOURS; i++) {
1287 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1288 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1289 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1290 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1292 pal = CreatePalette(logpal);
1294 SelectPalette(hdc, pal, FALSE);
1295 RealizePalette(hdc);
1296 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1299 ReleaseDC(hwnd, hdc);
1302 for (i = 0; i < NALLCOLOURS; i++)
1303 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1304 defpal[i].rgbtGreen,
1305 defpal[i].rgbtBlue);
1307 for (i = 0; i < NALLCOLOURS; i++)
1308 colours[i] = RGB(defpal[i].rgbtRed,
1309 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1313 * This is a wrapper to ExtTextOut() to force Windows to display
1314 * the precise glyphs we give it. Otherwise it would do its own
1315 * bidi and Arabic shaping, and we would end up uncertain which
1316 * characters it had put where.
1318 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1319 unsigned short *lpString, UINT cbCount,
1320 CONST INT *lpDx, int opaque)
1324 * The LCC include files apparently don't supply the
1325 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1326 * proper: the differences aren't important to us (the only
1327 * variable-width string parameter is one we don't use anyway).
1333 char *buffer = snewn(cbCount*2+2, char);
1334 char *classbuffer = snewn(cbCount, char);
1335 memset(&gcpr, 0, sizeof(gcpr));
1336 memset(buffer, 0, cbCount*2+2);
1337 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1339 gcpr.lStructSize = sizeof(gcpr);
1340 gcpr.lpGlyphs = (void *)buffer;
1341 gcpr.lpClass = (void *)classbuffer;
1342 gcpr.nGlyphs = cbCount;
1343 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1344 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1346 ExtTextOut(hdc, x, y,
1347 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1348 lprc, buffer, cbCount, lpDx);
1352 * The exact_textout() wrapper, unfortunately, destroys the useful
1353 * Windows `font linking' behaviour: automatic handling of Unicode
1354 * code points not supported in this font by falling back to a font
1355 * which does contain them. Therefore, we adopt a multi-layered
1356 * approach: for any potentially-bidi text, we use exact_textout(),
1357 * and for everything else we use a simple ExtTextOut as we did
1358 * before exact_textout() was introduced.
1360 static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1361 unsigned short *lpString, UINT cbCount,
1362 CONST INT *lpDx, int opaque)
1365 int bkmode = 0, got_bkmode = FALSE;
1369 for (i = 0; i < (int)cbCount ;) {
1370 int rtl = is_rtl(lpString[i]);
1374 for (j = i+1; j < (int)cbCount; j++) {
1375 if (rtl != is_rtl(lpString[j]))
1381 * Now [i,j) indicates a maximal substring of lpString
1382 * which should be displayed using the same textout
1386 exact_textout(hdc, xp, y, lprc, lpString+i, j-i,
1387 font_varpitch ? NULL : lpDx+i, opaque);
1389 ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1390 lprc, lpString+i, j-i,
1391 font_varpitch ? NULL : lpDx+i);
1397 bkmode = GetBkMode(hdc);
1399 SetBkMode(hdc, TRANSPARENT);
1404 SetBkMode(hdc, bkmode);
1407 static int get_font_width(HDC hdc, const TEXTMETRIC *tm)
1410 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1411 if (!(tm->tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1412 ret = tm->tmAveCharWidth;
1416 ABCFLOAT widths[LAST-FIRST + 1];
1419 font_varpitch = TRUE;
1420 font_dualwidth = TRUE;
1421 if (GetCharABCWidthsFloat(hdc, FIRST, LAST, widths)) {
1423 for (j = 0; j < lenof(widths); j++) {
1424 int width = (int)(0.5 + widths[j].abcfA +
1425 widths[j].abcfB + widths[j].abcfC);
1430 ret = tm->tmMaxCharWidth;
1439 * Initialise all the fonts we will need initially. There may be as many as
1440 * three or as few as one. The other (potentially) twenty-one fonts are done
1441 * if/when they are needed.
1445 * - check the font width and height, correcting our guesses if
1448 * - verify that the bold font is the same width as the ordinary
1449 * one, and engage shadow bolding if not.
1451 * - verify that the underlined font is the same width as the
1452 * ordinary one (manual underlining by means of line drawing can
1453 * be done in a pinch).
1455 static void init_fonts(int pick_width, int pick_height)
1464 int fw_dontcare, fw_bold;
1466 for (i = 0; i < FONT_MAXNO; i++)
1469 bold_font_mode = conf_get_int(conf, CONF_bold_style) & 1 ?
1470 BOLD_FONT : BOLD_NONE;
1471 bold_colours = conf_get_int(conf, CONF_bold_style) & 2 ? TRUE : FALSE;
1472 und_mode = UND_FONT;
1474 font = conf_get_fontspec(conf, CONF_font);
1476 fw_dontcare = FW_BOLD;
1479 fw_dontcare = FW_DONTCARE;
1486 font_height = pick_height;
1488 font_height = font->height;
1489 if (font_height > 0) {
1491 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1494 font_width = pick_width;
1496 quality = conf_get_int(conf, CONF_font_quality);
1497 #define f(i,c,w,u) \
1498 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1499 c, OUT_DEFAULT_PRECIS, \
1500 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), \
1501 FIXED_PITCH | FF_DONTCARE, font->name)
1503 f(FONT_NORMAL, font->charset, fw_dontcare, FALSE);
1505 SelectObject(hdc, fonts[FONT_NORMAL]);
1506 GetTextMetrics(hdc, &tm);
1508 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1510 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1511 if (!(tm.tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1512 font_varpitch = FALSE;
1513 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1515 font_varpitch = TRUE;
1516 font_dualwidth = TRUE;
1518 if (pick_width == 0 || pick_height == 0) {
1519 font_height = tm.tmHeight;
1520 font_width = get_font_width(hdc, &tm);
1523 #ifdef RDB_DEBUG_PATCH
1524 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1525 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1530 DWORD cset = tm.tmCharSet;
1531 memset(&info, 0xFF, sizeof(info));
1533 /* !!! Yes the next line is right */
1534 if (cset == OEM_CHARSET)
1535 ucsdata.font_codepage = GetOEMCP();
1537 if (TranslateCharsetInfo ((DWORD *)(ULONG_PTR)cset,
1538 &info, TCI_SRCCHARSET))
1539 ucsdata.font_codepage = info.ciACP;
1541 ucsdata.font_codepage = -1;
1543 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1544 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1547 f(FONT_UNDERLINE, font->charset, fw_dontcare, TRUE);
1550 * Some fonts, e.g. 9-pt Courier, draw their underlines
1551 * outside their character cell. We successfully prevent
1552 * screen corruption by clipping the text output, but then
1553 * we lose the underline completely. Here we try to work
1554 * out whether this is such a font, and if it is, we set a
1555 * flag that causes underlines to be drawn by hand.
1557 * Having tried other more sophisticated approaches (such
1558 * as examining the TEXTMETRIC structure or requesting the
1559 * height of a string), I think we'll do this the brute
1560 * force way: we create a small bitmap, draw an underlined
1561 * space on it, and test to see whether any pixels are
1562 * foreground-coloured. (Since we expect the underline to
1563 * go all the way across the character cell, we only search
1564 * down a single column of the bitmap, half way across.)
1568 HBITMAP und_bm, und_oldbm;
1572 und_dc = CreateCompatibleDC(hdc);
1573 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1574 und_oldbm = SelectObject(und_dc, und_bm);
1575 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1576 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1577 SetTextColor(und_dc, RGB(255, 255, 255));
1578 SetBkColor(und_dc, RGB(0, 0, 0));
1579 SetBkMode(und_dc, OPAQUE);
1580 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1582 for (i = 0; i < font_height; i++) {
1583 c = GetPixel(und_dc, font_width / 2, i);
1584 if (c != RGB(0, 0, 0))
1587 SelectObject(und_dc, und_oldbm);
1588 DeleteObject(und_bm);
1591 und_mode = UND_LINE;
1592 DeleteObject(fonts[FONT_UNDERLINE]);
1593 fonts[FONT_UNDERLINE] = 0;
1597 if (bold_font_mode == BOLD_FONT) {
1598 f(FONT_BOLD, font->charset, fw_bold, FALSE);
1602 descent = tm.tmAscent + 1;
1603 if (descent >= font_height)
1604 descent = font_height - 1;
1606 for (i = 0; i < 3; i++) {
1608 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1609 fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight;
1616 ReleaseDC(hwnd, hdc);
1618 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1619 und_mode = UND_LINE;
1620 DeleteObject(fonts[FONT_UNDERLINE]);
1621 fonts[FONT_UNDERLINE] = 0;
1624 if (bold_font_mode == BOLD_FONT &&
1625 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1626 bold_font_mode = BOLD_SHADOW;
1627 DeleteObject(fonts[FONT_BOLD]);
1628 fonts[FONT_BOLD] = 0;
1630 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1632 init_ucs(conf, &ucsdata);
1635 static void another_font(int fontno)
1638 int fw_dontcare, fw_bold, quality;
1643 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1646 basefont = (fontno & ~(FONT_BOLDUND));
1647 if (basefont != fontno && !fontflag[basefont])
1648 another_font(basefont);
1650 font = conf_get_fontspec(conf, CONF_font);
1653 fw_dontcare = FW_BOLD;
1656 fw_dontcare = FW_DONTCARE;
1666 if (fontno & FONT_WIDE)
1668 if (fontno & FONT_NARROW)
1670 if (fontno & FONT_OEM)
1672 if (fontno & FONT_BOLD)
1674 if (fontno & FONT_UNDERLINE)
1677 quality = conf_get_int(conf, CONF_font_quality);
1680 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1681 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1682 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality),
1683 DEFAULT_PITCH | FF_DONTCARE, s);
1685 fontflag[fontno] = 1;
1688 static void deinit_fonts(void)
1691 for (i = 0; i < FONT_MAXNO; i++) {
1693 DeleteObject(fonts[i]);
1699 void request_resize(void *frontend, int w, int h)
1703 /* If the window is maximized supress resizing attempts */
1704 if (IsZoomed(hwnd)) {
1705 if (conf_get_int(conf, CONF_resize_action) == RESIZE_TERM)
1709 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) return;
1710 if (h == term->rows && w == term->cols) return;
1712 /* Sanity checks ... */
1714 static int first_time = 1;
1717 switch (first_time) {
1719 /* Get the size of the screen */
1720 if (get_fullscreen_rect(&ss))
1721 /* first_time = 0 */ ;
1727 /* Make sure the values are sane */
1728 width = (ss.right - ss.left - extra_width) / 4;
1729 height = (ss.bottom - ss.top - extra_height) / 6;
1731 if (w > width || h > height)
1740 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
1742 if (conf_get_int(conf, CONF_resize_action) != RESIZE_FONT &&
1744 width = extra_width + font_width * w;
1745 height = extra_height + font_height * h;
1747 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1748 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1749 SWP_NOMOVE | SWP_NOZORDER);
1753 InvalidateRect(hwnd, NULL, TRUE);
1756 static void reset_window(int reinit) {
1758 * This function decides how to resize or redraw when the
1759 * user changes something.
1761 * This function doesn't like to change the terminal size but if the
1762 * font size is locked that may be it's only soluion.
1764 int win_width, win_height, resize_action, window_border;
1767 #ifdef RDB_DEBUG_PATCH
1768 debug((27, "reset_window()"));
1771 /* Current window sizes ... */
1772 GetWindowRect(hwnd, &wr);
1773 GetClientRect(hwnd, &cr);
1775 win_width = cr.right - cr.left;
1776 win_height = cr.bottom - cr.top;
1778 resize_action = conf_get_int(conf, CONF_resize_action);
1779 window_border = conf_get_int(conf, CONF_window_border);
1781 if (resize_action == RESIZE_DISABLED)
1784 /* Are we being forced to reload the fonts ? */
1786 #ifdef RDB_DEBUG_PATCH
1787 debug((27, "reset_window() -- Forced deinit"));
1793 /* Oh, looks like we're minimised */
1794 if (win_width == 0 || win_height == 0)
1797 /* Is the window out of position ? */
1799 (offset_width != (win_width-font_width*term->cols)/2 ||
1800 offset_height != (win_height-font_height*term->rows)/2) ){
1801 offset_width = (win_width-font_width*term->cols)/2;
1802 offset_height = (win_height-font_height*term->rows)/2;
1803 InvalidateRect(hwnd, NULL, TRUE);
1804 #ifdef RDB_DEBUG_PATCH
1805 debug((27, "reset_window() -> Reposition terminal"));
1809 if (IsZoomed(hwnd)) {
1810 /* We're fullscreen, this means we must not change the size of
1811 * the window so it's the font size or the terminal itself.
1814 extra_width = wr.right - wr.left - cr.right + cr.left;
1815 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1817 if (resize_action != RESIZE_TERM) {
1818 if (font_width != win_width/term->cols ||
1819 font_height != win_height/term->rows) {
1821 init_fonts(win_width/term->cols, win_height/term->rows);
1822 offset_width = (win_width-font_width*term->cols)/2;
1823 offset_height = (win_height-font_height*term->rows)/2;
1824 InvalidateRect(hwnd, NULL, TRUE);
1825 #ifdef RDB_DEBUG_PATCH
1826 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1827 font_width, font_height));
1831 if (font_width * term->cols != win_width ||
1832 font_height * term->rows != win_height) {
1833 /* Our only choice at this point is to change the
1834 * size of the terminal; Oh well.
1836 term_size(term, win_height/font_height, win_width/font_width,
1837 conf_get_int(conf, CONF_savelines));
1838 offset_width = (win_width-font_width*term->cols)/2;
1839 offset_height = (win_height-font_height*term->rows)/2;
1840 InvalidateRect(hwnd, NULL, TRUE);
1841 #ifdef RDB_DEBUG_PATCH
1842 debug((27, "reset_window() -> Zoomed term_size"));
1849 /* Hmm, a force re-init means we should ignore the current window
1850 * so we resize to the default font size.
1853 #ifdef RDB_DEBUG_PATCH
1854 debug((27, "reset_window() -> Forced re-init"));
1857 offset_width = offset_height = window_border;
1858 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1859 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1861 if (win_width != font_width*term->cols + offset_width*2 ||
1862 win_height != font_height*term->rows + offset_height*2) {
1864 /* If this is too large windows will resize it to the maximum
1865 * allowed window size, we will then be back in here and resize
1866 * the font or terminal to fit.
1868 SetWindowPos(hwnd, NULL, 0, 0,
1869 font_width*term->cols + extra_width,
1870 font_height*term->rows + extra_height,
1871 SWP_NOMOVE | SWP_NOZORDER);
1874 InvalidateRect(hwnd, NULL, TRUE);
1878 /* Okay the user doesn't want us to change the font so we try the
1879 * window. But that may be too big for the screen which forces us
1880 * to change the terminal.
1882 if ((resize_action == RESIZE_TERM && reinit<=0) ||
1883 (resize_action == RESIZE_EITHER && reinit<0) ||
1885 offset_width = offset_height = window_border;
1886 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1887 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1889 if (win_width != font_width*term->cols + offset_width*2 ||
1890 win_height != font_height*term->rows + offset_height*2) {
1895 get_fullscreen_rect(&ss);
1897 width = (ss.right - ss.left - extra_width) / font_width;
1898 height = (ss.bottom - ss.top - extra_height) / font_height;
1901 if ( term->rows > height || term->cols > width ) {
1902 if (resize_action == RESIZE_EITHER) {
1903 /* Make the font the biggest we can */
1904 if (term->cols > width)
1905 font_width = (ss.right - ss.left - extra_width)
1907 if (term->rows > height)
1908 font_height = (ss.bottom - ss.top - extra_height)
1912 init_fonts(font_width, font_height);
1914 width = (ss.right - ss.left - extra_width) / font_width;
1915 height = (ss.bottom - ss.top - extra_height) / font_height;
1917 if ( height > term->rows ) height = term->rows;
1918 if ( width > term->cols ) width = term->cols;
1919 term_size(term, height, width,
1920 conf_get_int(conf, CONF_savelines));
1921 #ifdef RDB_DEBUG_PATCH
1922 debug((27, "reset_window() -> term resize to (%d,%d)",
1928 SetWindowPos(hwnd, NULL, 0, 0,
1929 font_width*term->cols + extra_width,
1930 font_height*term->rows + extra_height,
1931 SWP_NOMOVE | SWP_NOZORDER);
1933 InvalidateRect(hwnd, NULL, TRUE);
1934 #ifdef RDB_DEBUG_PATCH
1935 debug((27, "reset_window() -> window resize to (%d,%d)",
1936 font_width*term->cols + extra_width,
1937 font_height*term->rows + extra_height));
1943 /* We're allowed to or must change the font but do we want to ? */
1945 if (font_width != (win_width-window_border*2)/term->cols ||
1946 font_height != (win_height-window_border*2)/term->rows) {
1949 init_fonts((win_width-window_border*2)/term->cols,
1950 (win_height-window_border*2)/term->rows);
1951 offset_width = (win_width-font_width*term->cols)/2;
1952 offset_height = (win_height-font_height*term->rows)/2;
1954 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1955 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1957 InvalidateRect(hwnd, NULL, TRUE);
1958 #ifdef RDB_DEBUG_PATCH
1959 debug((25, "reset_window() -> font resize to (%d,%d)",
1960 font_width, font_height));
1965 static void set_input_locale(HKL kl)
1969 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1970 lbuf, sizeof(lbuf));
1972 kbd_codepage = atoi(lbuf);
1975 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1977 int thistime = GetMessageTime();
1979 if (send_raw_mouse &&
1980 !(shift && conf_get_int(conf, CONF_mouse_override))) {
1981 lastbtn = MBT_NOTHING;
1982 term_mouse(term, b, translate_button(b), MA_CLICK,
1983 x, y, shift, ctrl, alt);
1987 if (lastbtn == b && thistime - lasttime < dbltime) {
1988 lastact = (lastact == MA_CLICK ? MA_2CLK :
1989 lastact == MA_2CLK ? MA_3CLK :
1990 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1995 if (lastact != MA_NOTHING)
1996 term_mouse(term, b, translate_button(b), lastact,
1997 x, y, shift, ctrl, alt);
1998 lasttime = thistime;
2002 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
2003 * into a cooked one (SELECT, EXTEND, PASTE).
2005 static Mouse_Button translate_button(Mouse_Button button)
2007 if (button == MBT_LEFT)
2009 if (button == MBT_MIDDLE)
2010 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2011 MBT_PASTE : MBT_EXTEND;
2012 if (button == MBT_RIGHT)
2013 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
2014 MBT_EXTEND : MBT_PASTE;
2015 return 0; /* shouldn't happen */
2018 static void show_mouseptr(int show)
2020 /* NB that the counter in ShowCursor() is also frobbed by
2021 * update_mouse_pointer() */
2022 static int cursor_visible = 1;
2023 if (!conf_get_int(conf, CONF_hide_mouseptr))
2024 show = 1; /* override if this feature disabled */
2025 if (cursor_visible && !show)
2027 else if (!cursor_visible && show)
2029 cursor_visible = show;
2032 static int is_alt_pressed(void)
2035 int r = GetKeyboardState(keystate);
2038 if (keystate[VK_MENU] & 0x80)
2040 if (keystate[VK_RMENU] & 0x80)
2045 static int resizing;
2047 void notify_remote_exit(void *fe)
2049 int exitcode, close_on_exit;
2051 if (!session_closed &&
2052 (exitcode = back->exitcode(backhandle)) >= 0) {
2053 close_on_exit = conf_get_int(conf, CONF_close_on_exit);
2054 /* Abnormal exits will already have set session_closed and taken
2055 * appropriate action. */
2056 if (close_on_exit == FORCE_ON ||
2057 (close_on_exit == AUTO && exitcode != INT_MAX)) {
2060 queue_toplevel_callback(close_session, NULL);
2061 session_closed = TRUE;
2062 /* exitcode == INT_MAX indicates that the connection was closed
2063 * by a fatal error, so an error box will be coming our way and
2064 * we should not generate this informational one. */
2065 if (exitcode != INT_MAX)
2066 MessageBox(hwnd, "Connection closed by remote host",
2067 appname, MB_OK | MB_ICONINFORMATION);
2072 void timer_change_notify(unsigned long next)
2074 unsigned long now = GETTICKCOUNT();
2076 if (now - next < INT_MAX)
2080 KillTimer(hwnd, TIMING_TIMER_ID);
2081 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
2082 timing_next_time = next;
2085 static void conf_cache_data(void)
2087 /* Cache some items from conf to speed lookups in very hot code */
2088 cursor_type = conf_get_int(conf, CONF_cursor_type);
2089 vtmode = conf_get_int(conf, CONF_vtmode);
2092 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2093 WPARAM wParam, LPARAM lParam)
2096 static int ignore_clip = FALSE;
2097 static int need_backend_resize = FALSE;
2098 static int fullscr_on_max = FALSE;
2099 static int processed_resize = FALSE;
2100 static UINT last_mousemove = 0;
2105 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
2108 KillTimer(hwnd, TIMING_TIMER_ID);
2109 if (run_timers(timing_next_time, &next)) {
2110 timer_change_notify(next);
2121 str = dupprintf("%s Exit Confirmation", appname);
2122 if (session_closed || !conf_get_int(conf, CONF_warn_on_close) ||
2124 "Are you sure you want to close this session?",
2125 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
2127 DestroyWindow(hwnd);
2135 case WM_INITMENUPOPUP:
2136 if ((HMENU)wParam == savedsess_menu) {
2137 /* About to pop up Saved Sessions sub-menu.
2138 * Refresh the session list. */
2139 get_sesslist(&sesslist, FALSE); /* free */
2140 get_sesslist(&sesslist, TRUE);
2141 update_savedsess_menu();
2147 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
2157 const char *argprefix;
2158 BOOL inherit_handles;
2160 PROCESS_INFORMATION pi;
2161 HANDLE filemap = NULL;
2168 if (wParam == IDM_DUPSESS) {
2170 * Allocate a file-mapping memory chunk for the
2173 SECURITY_ATTRIBUTES sa;
2177 size = conf_serialised_size(conf);
2179 sa.nLength = sizeof(sa);
2180 sa.lpSecurityDescriptor = NULL;
2181 sa.bInheritHandle = TRUE;
2182 filemap = CreateFileMapping(INVALID_HANDLE_VALUE,
2186 if (filemap && filemap != INVALID_HANDLE_VALUE) {
2187 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, size);
2189 conf_serialise(conf, p);
2193 inherit_handles = TRUE;
2194 cl = dupprintf("putty %s&%p:%u", argprefix,
2195 filemap, (unsigned)size);
2196 } else if (wParam == IDM_SAVEDSESS) {
2197 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
2198 / MENU_SAVED_STEP) + 1;
2199 if (sessno < (unsigned)sesslist.nsessions) {
2200 const char *session = sesslist.sessions[sessno];
2201 cl = dupprintf("putty %s@%s", argprefix, session);
2202 inherit_handles = FALSE;
2205 } else /* IDM_NEWSESS */ {
2206 cl = dupprintf("putty%s%s",
2207 *argprefix ? " " : "",
2209 inherit_handles = FALSE;
2212 GetModuleFileName(NULL, b, sizeof(b) - 1);
2214 si.lpReserved = NULL;
2215 si.lpDesktop = NULL;
2219 si.lpReserved2 = NULL;
2220 CreateProcess(b, cl, NULL, NULL, inherit_handles,
2221 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
2222 CloseHandle(pi.hProcess);
2223 CloseHandle(pi.hThread);
2226 CloseHandle(filemap);
2232 logevent(NULL, "----- Session restarted -----");
2233 term_pwron(term, FALSE);
2242 int reconfig_result;
2247 reconfiguring = TRUE;
2250 * Copy the current window title into the stored
2251 * previous configuration, so that doing nothing to
2252 * the window title field in the config box doesn't
2253 * reset the title to its startup state.
2255 conf_set_str(conf, CONF_wintitle, window_name);
2257 prev_conf = conf_copy(conf);
2260 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2261 reconfiguring = FALSE;
2262 if (!reconfig_result) {
2263 conf_free(prev_conf);
2269 resize_action = conf_get_int(conf, CONF_resize_action);
2271 /* Disable full-screen if resizing forbidden */
2273 for (i = 0; i < lenof(popup_menus); i++)
2274 EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN,
2276 (resize_action == RESIZE_DISABLED)
2277 ? MF_GRAYED : MF_ENABLED);
2278 /* Gracefully unzoom if necessary */
2279 if (IsZoomed(hwnd) && (resize_action == RESIZE_DISABLED))
2280 ShowWindow(hwnd, SW_RESTORE);
2283 /* Pass new config data to the logging module */
2284 log_reconfig(logctx, conf);
2288 * Flush the line discipline's edit buffer in the
2289 * case where local editing has just been disabled.
2292 ldisc_configure(ldisc, conf);
2293 ldisc_echoedit_update(ldisc);
2302 /* Pass new config data to the terminal */
2303 term_reconfig(term, conf);
2305 /* Pass new config data to the back end */
2307 back->reconfig(backhandle, conf);
2309 /* Screen size changed ? */
2310 if (conf_get_int(conf, CONF_height) !=
2311 conf_get_int(prev_conf, CONF_height) ||
2312 conf_get_int(conf, CONF_width) !=
2313 conf_get_int(prev_conf, CONF_width) ||
2314 conf_get_int(conf, CONF_savelines) !=
2315 conf_get_int(prev_conf, CONF_savelines) ||
2316 resize_action == RESIZE_FONT ||
2317 (resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2318 resize_action == RESIZE_DISABLED)
2319 term_size(term, conf_get_int(conf, CONF_height),
2320 conf_get_int(conf, CONF_width),
2321 conf_get_int(conf, CONF_savelines));
2323 /* Enable or disable the scroll bar, etc */
2325 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2326 LONG nexflag, exflag =
2327 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2330 if (conf_get_int(conf, CONF_alwaysontop) !=
2331 conf_get_int(prev_conf, CONF_alwaysontop)) {
2332 if (conf_get_int(conf, CONF_alwaysontop)) {
2333 nexflag |= WS_EX_TOPMOST;
2334 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2335 SWP_NOMOVE | SWP_NOSIZE);
2337 nexflag &= ~(WS_EX_TOPMOST);
2338 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2339 SWP_NOMOVE | SWP_NOSIZE);
2342 if (conf_get_int(conf, CONF_sunken_edge))
2343 nexflag |= WS_EX_CLIENTEDGE;
2345 nexflag &= ~(WS_EX_CLIENTEDGE);
2348 if (conf_get_int(conf, is_full_screen() ?
2349 CONF_scrollbar_in_fullscreen :
2353 nflg &= ~WS_VSCROLL;
2355 if (resize_action == RESIZE_DISABLED ||
2357 nflg &= ~WS_THICKFRAME;
2359 nflg |= WS_THICKFRAME;
2361 if (resize_action == RESIZE_DISABLED)
2362 nflg &= ~WS_MAXIMIZEBOX;
2364 nflg |= WS_MAXIMIZEBOX;
2366 if (nflg != flag || nexflag != exflag) {
2368 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2369 if (nexflag != exflag)
2370 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2372 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2373 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2374 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2382 if (resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2387 set_title(NULL, conf_get_str(conf, CONF_wintitle));
2388 if (IsIconic(hwnd)) {
2390 conf_get_int(conf, CONF_win_name_always) ?
2391 window_name : icon_name);
2395 FontSpec *font = conf_get_fontspec(conf, CONF_font);
2396 FontSpec *prev_font = conf_get_fontspec(prev_conf,
2399 if (!strcmp(font->name, prev_font->name) ||
2400 !strcmp(conf_get_str(conf, CONF_line_codepage),
2401 conf_get_str(prev_conf, CONF_line_codepage)) ||
2402 font->isbold != prev_font->isbold ||
2403 font->height != prev_font->height ||
2404 font->charset != prev_font->charset ||
2405 conf_get_int(conf, CONF_font_quality) !=
2406 conf_get_int(prev_conf, CONF_font_quality) ||
2407 conf_get_int(conf, CONF_vtmode) !=
2408 conf_get_int(prev_conf, CONF_vtmode) ||
2409 conf_get_int(conf, CONF_bold_style) !=
2410 conf_get_int(prev_conf, CONF_bold_style) ||
2411 resize_action == RESIZE_DISABLED ||
2412 resize_action == RESIZE_EITHER ||
2413 resize_action != conf_get_int(prev_conf,
2414 CONF_resize_action))
2418 InvalidateRect(hwnd, NULL, TRUE);
2419 reset_window(init_lvl);
2421 conf_free(prev_conf);
2428 request_paste(NULL);
2434 term_pwron(term, TRUE);
2436 ldisc_echoedit_update(ldisc);
2442 launch_help(hwnd, NULL);
2446 * We get this if the System menu has been activated
2453 * We get this if the System menu has been activated
2454 * using the keyboard. This might happen from within
2455 * TranslateKey, in which case it really wants to be
2456 * followed by a `space' character to actually _bring
2457 * the menu up_ rather than just sitting there in
2458 * `ready to appear' state.
2460 show_mouseptr(1); /* make sure pointer is visible */
2462 PostMessage(hwnd, WM_CHAR, ' ', 0);
2464 case IDM_FULLSCREEN:
2468 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2469 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2471 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2472 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2474 * Ensure we haven't been sent a bogus SYSCOMMAND
2475 * which would cause us to reference invalid memory
2476 * and crash. Perhaps I'm just too paranoid here.
2478 if (i >= n_specials)
2481 back->special(backhandle, specials[i].code);
2486 #define X_POS(l) ((int)(short)LOWORD(l))
2487 #define Y_POS(l) ((int)(short)HIWORD(l))
2489 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2490 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2491 case WM_LBUTTONDOWN:
2492 case WM_MBUTTONDOWN:
2493 case WM_RBUTTONDOWN:
2497 if (message == WM_RBUTTONDOWN &&
2498 ((wParam & MK_CONTROL) ||
2499 (conf_get_int(conf, CONF_mouse_is_xterm) == 2))) {
2502 show_mouseptr(1); /* make sure pointer is visible */
2503 GetCursorPos(&cursorpos);
2504 TrackPopupMenu(popup_menus[CTXMENU].menu,
2505 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2506 cursorpos.x, cursorpos.y,
2514 case WM_LBUTTONDOWN:
2516 wParam |= MK_LBUTTON;
2519 case WM_MBUTTONDOWN:
2520 button = MBT_MIDDLE;
2521 wParam |= MK_MBUTTON;
2524 case WM_RBUTTONDOWN:
2526 wParam |= MK_RBUTTON;
2531 wParam &= ~MK_LBUTTON;
2535 button = MBT_MIDDLE;
2536 wParam &= ~MK_MBUTTON;
2541 wParam &= ~MK_RBUTTON;
2545 button = press = 0; /* shouldn't happen */
2549 * Special case: in full-screen mode, if the left
2550 * button is clicked in the very top left corner of the
2551 * window, we put up the System menu instead of doing
2555 char mouse_on_hotspot = 0;
2564 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2567 mi.cbSize = sizeof(MONITORINFO);
2568 GetMonitorInfo(mon, &mi);
2570 if (mi.rcMonitor.left == pt.x &&
2571 mi.rcMonitor.top == pt.y) {
2572 mouse_on_hotspot = 1;
2577 if (pt.x == 0 && pt.y == 0) {
2578 mouse_on_hotspot = 1;
2581 if (is_full_screen() && press &&
2582 button == MBT_LEFT && mouse_on_hotspot) {
2583 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2584 MAKELPARAM(pt.x, pt.y));
2591 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2592 wParam & MK_SHIFT, wParam & MK_CONTROL,
2596 term_mouse(term, button, translate_button(button), MA_RELEASE,
2597 TO_CHR_X(X_POS(lParam)),
2598 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2599 wParam & MK_CONTROL, is_alt_pressed());
2600 if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)))
2608 * Windows seems to like to occasionally send MOUSEMOVE
2609 * events even if the mouse hasn't moved. Don't unhide
2610 * the mouse pointer in this case.
2612 static WPARAM wp = 0;
2613 static LPARAM lp = 0;
2614 if (wParam != wp || lParam != lp ||
2615 last_mousemove != WM_MOUSEMOVE) {
2617 wp = wParam; lp = lParam;
2618 last_mousemove = WM_MOUSEMOVE;
2622 * Add the mouse position and message time to the random
2625 noise_ultralight(lParam);
2627 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2628 GetCapture() == hwnd) {
2630 if (wParam & MK_LBUTTON)
2632 else if (wParam & MK_MBUTTON)
2636 term_mouse(term, b, translate_button(b), MA_DRAG,
2637 TO_CHR_X(X_POS(lParam)),
2638 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2639 wParam & MK_CONTROL, is_alt_pressed());
2642 case WM_NCMOUSEMOVE:
2644 static WPARAM wp = 0;
2645 static LPARAM lp = 0;
2646 if (wParam != wp || lParam != lp ||
2647 last_mousemove != WM_NCMOUSEMOVE) {
2649 wp = wParam; lp = lParam;
2650 last_mousemove = WM_NCMOUSEMOVE;
2653 noise_ultralight(lParam);
2655 case WM_IGNORE_CLIP:
2656 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2658 case WM_DESTROYCLIPBOARD:
2660 term_deselect(term);
2661 ignore_clip = FALSE;
2668 hdc = BeginPaint(hwnd, &p);
2670 SelectPalette(hdc, pal, TRUE);
2671 RealizePalette(hdc);
2675 * We have to be careful about term_paint(). It will
2676 * set a bunch of character cells to INVALID and then
2677 * call do_paint(), which will redraw those cells and
2678 * _then mark them as done_. This may not be accurate:
2679 * when painting in WM_PAINT context we are restricted
2680 * to the rectangle which has just been exposed - so if
2681 * that only covers _part_ of a character cell and the
2682 * rest of it was already visible, that remainder will
2683 * not be redrawn at all. Accordingly, we must not
2684 * paint any character cell in a WM_PAINT context which
2685 * already has a pending update due to terminal output.
2686 * The simplest solution to this - and many, many
2687 * thanks to Hung-Te Lin for working all this out - is
2688 * not to do any actual painting at _all_ if there's a
2689 * pending terminal update: just mark the relevant
2690 * character cells as INVALID and wait for the
2691 * scheduled full update to sort it out.
2693 * I have a suspicion this isn't the _right_ solution.
2694 * An alternative approach would be to have terminal.c
2695 * separately track what _should_ be on the terminal
2696 * screen and what _is_ on the terminal screen, and
2697 * have two completely different types of redraw (one
2698 * for full updates, which syncs the former with the
2699 * terminal itself, and one for WM_PAINT which syncs
2700 * the latter with the former); yet another possibility
2701 * would be to have the Windows front end do what the
2702 * GTK one already does, and maintain a bitmap of the
2703 * current terminal appearance so that WM_PAINT becomes
2704 * completely trivial. However, this should do for now.
2706 term_paint(term, hdc,
2707 (p.rcPaint.left-offset_width)/font_width,
2708 (p.rcPaint.top-offset_height)/font_height,
2709 (p.rcPaint.right-offset_width-1)/font_width,
2710 (p.rcPaint.bottom-offset_height-1)/font_height,
2711 !term->window_update_pending);
2714 p.rcPaint.left < offset_width ||
2715 p.rcPaint.top < offset_height ||
2716 p.rcPaint.right >= offset_width + font_width*term->cols ||
2717 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2719 HBRUSH fillcolour, oldbrush;
2721 fillcolour = CreateSolidBrush (
2722 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2723 oldbrush = SelectObject(hdc, fillcolour);
2724 edge = CreatePen(PS_SOLID, 0,
2725 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2726 oldpen = SelectObject(hdc, edge);
2729 * Jordan Russell reports that this apparently
2730 * ineffectual IntersectClipRect() call masks a
2731 * Windows NT/2K bug causing strange display
2732 * problems when the PuTTY window is taller than
2733 * the primary monitor. It seems harmless enough...
2735 IntersectClipRect(hdc,
2736 p.rcPaint.left, p.rcPaint.top,
2737 p.rcPaint.right, p.rcPaint.bottom);
2739 ExcludeClipRect(hdc,
2740 offset_width, offset_height,
2741 offset_width+font_width*term->cols,
2742 offset_height+font_height*term->rows);
2744 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2745 p.rcPaint.right, p.rcPaint.bottom);
2747 /* SelectClipRgn(hdc, NULL); */
2749 SelectObject(hdc, oldbrush);
2750 DeleteObject(fillcolour);
2751 SelectObject(hdc, oldpen);
2754 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2755 SelectObject(hdc, GetStockObject(WHITE_PEN));
2763 * To protect against re-entrancy when Windows's recv()
2764 * immediately triggers a new WSAAsyncSelect window
2765 * message, we don't call select_result directly from this
2766 * handler but instead wait until we're back out at the
2767 * top level of the message loop.
2769 struct wm_netevent_params *params =
2770 snew(struct wm_netevent_params);
2771 params->wParam = wParam;
2772 params->lParam = lParam;
2773 queue_toplevel_callback(wm_netevent_callback, params);
2777 term_set_focus(term, TRUE);
2778 CreateCaret(hwnd, caretbm, font_width, font_height);
2780 flash_window(0); /* stop */
2786 term_set_focus(term, FALSE);
2788 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2791 case WM_ENTERSIZEMOVE:
2792 #ifdef RDB_DEBUG_PATCH
2793 debug((27, "WM_ENTERSIZEMOVE"));
2797 need_backend_resize = FALSE;
2799 case WM_EXITSIZEMOVE:
2802 #ifdef RDB_DEBUG_PATCH
2803 debug((27, "WM_EXITSIZEMOVE"));
2805 if (need_backend_resize) {
2806 term_size(term, conf_get_int(conf, CONF_height),
2807 conf_get_int(conf, CONF_width),
2808 conf_get_int(conf, CONF_savelines));
2809 InvalidateRect(hwnd, NULL, TRUE);
2814 * This does two jobs:
2815 * 1) Keep the sizetip uptodate
2816 * 2) Make sure the window size is _stepped_ in units of the font size.
2818 resize_action = conf_get_int(conf, CONF_resize_action);
2819 if (resize_action == RESIZE_TERM ||
2820 (resize_action == RESIZE_EITHER && !is_alt_pressed())) {
2821 int width, height, w, h, ew, eh;
2822 LPRECT r = (LPRECT) lParam;
2824 if (!need_backend_resize && resize_action == RESIZE_EITHER &&
2825 (conf_get_int(conf, CONF_height) != term->rows ||
2826 conf_get_int(conf, CONF_width) != term->cols)) {
2828 * Great! It seems that both the terminal size and the
2829 * font size have been changed and the user is now dragging.
2831 * It will now be difficult to get back to the configured
2834 * This would be easier but it seems to be too confusing.
2836 conf_set_int(conf, CONF_height, term->rows);
2837 conf_set_int(conf, CONF_width, term->cols);
2839 InvalidateRect(hwnd, NULL, TRUE);
2840 need_backend_resize = TRUE;
2843 width = r->right - r->left - extra_width;
2844 height = r->bottom - r->top - extra_height;
2845 w = (width + font_width / 2) / font_width;
2848 h = (height + font_height / 2) / font_height;
2851 UpdateSizeTip(hwnd, w, h);
2852 ew = width - w * font_width;
2853 eh = height - h * font_height;
2855 if (wParam == WMSZ_LEFT ||
2856 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2862 if (wParam == WMSZ_TOP ||
2863 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2873 int width, height, w, h, rv = 0;
2874 int window_border = conf_get_int(conf, CONF_window_border);
2875 int ex_width = extra_width + (window_border - offset_width) * 2;
2876 int ex_height = extra_height + (window_border - offset_height) * 2;
2877 LPRECT r = (LPRECT) lParam;
2879 width = r->right - r->left - ex_width;
2880 height = r->bottom - r->top - ex_height;
2882 w = (width + term->cols/2)/term->cols;
2883 h = (height + term->rows/2)/term->rows;
2884 if ( r->right != r->left + w*term->cols + ex_width)
2887 if (wParam == WMSZ_LEFT ||
2888 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2889 r->left = r->right - w*term->cols - ex_width;
2891 r->right = r->left + w*term->cols + ex_width;
2893 if (r->bottom != r->top + h*term->rows + ex_height)
2896 if (wParam == WMSZ_TOP ||
2897 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2898 r->top = r->bottom - h*term->rows - ex_height;
2900 r->bottom = r->top + h*term->rows + ex_height;
2904 /* break; (never reached) */
2905 case WM_FULLSCR_ON_MAX:
2906 fullscr_on_max = TRUE;
2909 sys_cursor_update();
2912 resize_action = conf_get_int(conf, CONF_resize_action);
2913 #ifdef RDB_DEBUG_PATCH
2914 debug((27, "WM_SIZE %s (%d,%d)",
2915 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2916 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2917 (wParam == SIZE_RESTORED && resizing) ? "to":
2918 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2920 LOWORD(lParam), HIWORD(lParam)));
2922 if (wParam == SIZE_MINIMIZED)
2924 conf_get_int(conf, CONF_win_name_always) ?
2925 window_name : icon_name);
2926 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2927 SetWindowText(hwnd, window_name);
2928 if (wParam == SIZE_RESTORED) {
2929 processed_resize = FALSE;
2930 clear_full_screen();
2931 if (processed_resize) {
2933 * Inhibit normal processing of this WM_SIZE; a
2934 * secondary one was triggered just now by
2935 * clear_full_screen which contained the correct
2941 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2942 fullscr_on_max = FALSE;
2943 processed_resize = FALSE;
2945 if (processed_resize) {
2947 * Inhibit normal processing of this WM_SIZE; a
2948 * secondary one was triggered just now by
2949 * make_full_screen which contained the correct client
2956 processed_resize = TRUE;
2958 if (resize_action == RESIZE_DISABLED) {
2959 /* A resize, well it better be a minimize. */
2963 int width, height, w, h;
2964 int window_border = conf_get_int(conf, CONF_window_border);
2966 width = LOWORD(lParam);
2967 height = HIWORD(lParam);
2969 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2971 prev_rows = term->rows;
2972 prev_cols = term->cols;
2973 if (resize_action == RESIZE_TERM) {
2974 w = width / font_width;
2976 h = height / font_height;
2981 * As below, if we're in the middle of an
2982 * interactive resize we don't call
2983 * back->size. In Windows 7, this case can
2984 * arise in maximisation as well via the Aero
2987 need_backend_resize = TRUE;
2988 conf_set_int(conf, CONF_height, h);
2989 conf_set_int(conf, CONF_width, w);
2991 term_size(term, h, w,
2992 conf_get_int(conf, CONF_savelines));
2996 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2998 if (resize_action == RESIZE_TERM) {
2999 w = (width-window_border*2) / font_width;
3001 h = (height-window_border*2) / font_height;
3003 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
3005 } else if (resize_action != RESIZE_FONT)
3009 } else if (wParam == SIZE_MINIMIZED) {
3011 } else if (resize_action == RESIZE_TERM ||
3012 (resize_action == RESIZE_EITHER &&
3013 !is_alt_pressed())) {
3014 w = (width-window_border*2) / font_width;
3016 h = (height-window_border*2) / font_height;
3021 * Don't call back->size in mid-resize. (To
3022 * prevent massive numbers of resize events
3023 * getting sent down the connection during an NT
3026 need_backend_resize = TRUE;
3027 conf_set_int(conf, CONF_height, h);
3028 conf_set_int(conf, CONF_width, w);
3030 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
3036 sys_cursor_update();
3039 switch (LOWORD(wParam)) {
3041 term_scroll(term, -1, 0);
3044 term_scroll(term, +1, 0);
3047 term_scroll(term, 0, +1);
3050 term_scroll(term, 0, -1);
3053 term_scroll(term, 0, +term->rows / 2);
3056 term_scroll(term, 0, -term->rows / 2);
3058 case SB_THUMBPOSITION:
3061 * Use GetScrollInfo instead of HIWORD(wParam) to get
3062 * 32-bit scroll position.
3067 si.cbSize = sizeof(si);
3068 si.fMask = SIF_TRACKPOS;
3069 if (GetScrollInfo(hwnd, SB_VERT, &si) == 0)
3070 si.nTrackPos = HIWORD(wParam);
3071 term_scroll(term, 1, si.nTrackPos);
3076 case WM_PALETTECHANGED:
3077 if ((HWND) wParam != hwnd && pal != NULL) {
3078 HDC hdc = get_ctx(NULL);
3080 if (RealizePalette(hdc) > 0)
3086 case WM_QUERYNEWPALETTE:
3088 HDC hdc = get_ctx(NULL);
3090 if (RealizePalette(hdc) > 0)
3102 * Add the scan code and keypress timing to the random
3105 noise_ultralight(lParam);
3108 * We don't do TranslateMessage since it disassociates the
3109 * resulting CHAR message from the KEYDOWN that sparked it,
3110 * which we occasionally don't want. Instead, we process
3111 * KEYDOWN, and call the Win32 translator functions so that
3112 * we get the translations under _our_ control.
3115 unsigned char buf[20];
3118 if (wParam == VK_PROCESSKEY || /* IME PROCESS key */
3119 wParam == VK_PACKET) { /* 'this key is a Unicode char' */
3120 if (message == WM_KEYDOWN) {
3123 m.message = WM_KEYDOWN;
3125 m.lParam = lParam & 0xdfff;
3126 TranslateMessage(&m);
3127 } else break; /* pass to Windows for default processing */
3129 len = TranslateKey(message, wParam, lParam, buf);
3131 return DefWindowProcW(hwnd, message, wParam, lParam);
3135 * We need not bother about stdin backlogs
3136 * here, because in GUI PuTTY we can't do
3137 * anything about it anyway; there's no means
3138 * of asking Windows to hold off on KEYDOWN
3139 * messages. We _have_ to buffer everything
3142 term_seen_key_event(term);
3144 ldisc_send(ldisc, (char *)buf, len, 1);
3150 case WM_INPUTLANGCHANGE:
3151 /* wParam == Font number */
3152 /* lParam == Locale */
3153 set_input_locale((HKL)lParam);
3154 sys_cursor_update();
3156 case WM_IME_STARTCOMPOSITION:
3158 HIMC hImc = ImmGetContext(hwnd);
3159 ImmSetCompositionFont(hImc, &lfont);
3160 ImmReleaseContext(hwnd, hImc);
3163 case WM_IME_COMPOSITION:
3169 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
3170 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
3172 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
3173 break; /* fall back to DefWindowProc */
3175 hIMC = ImmGetContext(hwnd);
3176 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3180 buff = snewn(n, char);
3181 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
3183 * Jaeyoun Chung reports that Korean character
3184 * input doesn't work correctly if we do a single
3185 * luni_send() covering the whole of buff. So
3186 * instead we luni_send the characters one by one.
3188 term_seen_key_event(term);
3189 /* don't divide SURROGATE PAIR */
3191 for (i = 0; i < n; i += 2) {
3192 WCHAR hs = *(unsigned short *)(buff+i);
3193 if (IS_HIGH_SURROGATE(hs) && i+2 < n) {
3194 WCHAR ls = *(unsigned short *)(buff+i+2);
3195 if (IS_LOW_SURROGATE(ls)) {
3196 luni_send(ldisc, (unsigned short *)(buff+i), 2, 1);
3201 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
3206 ImmReleaseContext(hwnd, hIMC);
3211 if (wParam & 0xFF00) {
3215 buf[0] = wParam >> 8;
3216 term_seen_key_event(term);
3218 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
3220 char c = (unsigned char) wParam;
3221 term_seen_key_event(term);
3223 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
3229 * Nevertheless, we are prepared to deal with WM_CHAR
3230 * messages, should they crop up. So if someone wants to
3231 * post the things to us as part of a macro manoeuvre,
3232 * we're ready to cope.
3235 static wchar_t pending_surrogate = 0;
3238 if (IS_HIGH_SURROGATE(c)) {
3239 pending_surrogate = c;
3240 } else if (IS_SURROGATE_PAIR(pending_surrogate, c)) {
3242 pair[0] = pending_surrogate;
3244 term_seen_key_event(term);
3245 luni_send(ldisc, pair, 2, 1);
3246 } else if (!IS_SURROGATE(c)) {
3247 term_seen_key_event(term);
3248 luni_send(ldisc, &c, 1, 1);
3252 case WM_SYSCOLORCHANGE:
3253 if (conf_get_int(conf, CONF_system_colour)) {
3254 /* Refresh palette from system colours. */
3255 /* XXX actually this zaps the entire palette. */
3258 /* Force a repaint of the terminal window. */
3259 term_invalidate(term);
3262 case WM_AGENT_CALLBACK:
3264 struct agent_callback *c = (struct agent_callback *)lParam;
3265 c->callback(c->callback_ctx, c->data, c->len);
3269 case WM_GOT_CLIPDATA:
3270 if (process_clipdata((HGLOBAL)lParam, wParam))
3271 term_do_paste(term);
3274 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
3275 int shift_pressed=0, control_pressed=0;
3277 if (message == WM_MOUSEWHEEL) {
3278 wheel_accumulator += (short)HIWORD(wParam);
3279 shift_pressed=LOWORD(wParam) & MK_SHIFT;
3280 control_pressed=LOWORD(wParam) & MK_CONTROL;
3283 wheel_accumulator += (int)wParam;
3284 if (GetKeyboardState(keys)!=0) {
3285 shift_pressed=keys[VK_SHIFT]&0x80;
3286 control_pressed=keys[VK_CONTROL]&0x80;
3290 /* process events when the threshold is reached */
3291 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
3294 /* reduce amount for next time */
3295 if (wheel_accumulator > 0) {
3297 wheel_accumulator -= WHEEL_DELTA;
3298 } else if (wheel_accumulator < 0) {
3300 wheel_accumulator += WHEEL_DELTA;
3304 if (send_raw_mouse &&
3305 !(conf_get_int(conf, CONF_mouse_override) &&
3307 /* Mouse wheel position is in screen coordinates for
3310 p.x = X_POS(lParam); p.y = Y_POS(lParam);
3311 if (ScreenToClient(hwnd, &p)) {
3312 /* send a mouse-down followed by a mouse up */
3313 term_mouse(term, b, translate_button(b),
3316 TO_CHR_Y(p.y), shift_pressed,
3317 control_pressed, is_alt_pressed());
3318 } /* else: not sure when this can fail */
3320 /* trigger a scroll */
3321 term_scroll(term, 0,
3323 -term->rows / 2 : term->rows / 2);
3331 * Any messages we don't process completely above are passed through to
3332 * DefWindowProc() for default processing.
3334 return DefWindowProcW(hwnd, message, wParam, lParam);
3338 * Move the system caret. (We maintain one, even though it's
3339 * invisible, for the benefit of blind people: apparently some
3340 * helper software tracks the system caret, so we should arrange to
3343 void sys_cursor(void *frontend, int x, int y)
3347 if (!term->has_focus) return;
3350 * Avoid gratuitously re-updating the cursor position and IMM
3351 * window if there's no actual change required.
3353 cx = x * font_width + offset_width;
3354 cy = y * font_height + offset_height;
3355 if (cx == caret_x && cy == caret_y)
3360 sys_cursor_update();
3363 static void sys_cursor_update(void)
3368 if (!term->has_focus) return;
3370 if (caret_x < 0 || caret_y < 0)
3373 SetCaretPos(caret_x, caret_y);
3375 /* IMM calls on Win98 and beyond only */
3376 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3378 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3379 osVersion.dwMinorVersion == 0) return; /* 95 */
3381 /* we should have the IMM functions */
3382 hIMC = ImmGetContext(hwnd);
3383 cf.dwStyle = CFS_POINT;
3384 cf.ptCurrentPos.x = caret_x;
3385 cf.ptCurrentPos.y = caret_y;
3386 ImmSetCompositionWindow(hIMC, &cf);
3388 ImmReleaseContext(hwnd, hIMC);
3392 * Draw a line of text in the window, at given character
3393 * coordinates, in given attributes.
3395 * We are allowed to fiddle with the contents of `text'.
3397 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3398 unsigned long attr, int lattr)
3401 int nfg, nbg, nfont;
3404 int force_manual_underline = 0;
3405 int fnt_width, char_width;
3406 int text_adjust = 0;
3408 int maxlen, remaining, opaque;
3409 int is_cursor = FALSE;
3410 static int *lpDx = NULL;
3411 static int lpDx_len = 0;
3413 int len2; /* for SURROGATE PAIR */
3415 lattr &= LATTR_MODE;
3417 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3419 if (attr & ATTR_WIDE)
3422 /* Only want the left half of double width lines */
3423 if (lattr != LATTR_NORM && x*2 >= term->cols)
3431 if ((attr & TATTR_ACTCURS) && (cursor_type == 0 || term->big_cursor)) {
3432 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3433 /* cursor fg and bg */
3434 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3439 if (vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3440 /* Assume a poorman font is borken in other ways too. */
3450 nfont |= FONT_WIDE + FONT_HIGH;
3453 if (attr & ATTR_NARROW)
3454 nfont |= FONT_NARROW;
3456 #ifdef USES_VTLINE_HACK
3457 /* Special hack for the VT100 linedraw glyphs. */
3458 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3459 switch ((unsigned char) (text[0])) {
3461 text_adjust = -2 * font_height / 5;
3464 text_adjust = -1 * font_height / 5;
3467 text_adjust = font_height / 5;
3470 text_adjust = 2 * font_height / 5;
3473 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3475 text[0] = ucsdata.unitab_xterm['q'];
3476 if (attr & ATTR_UNDER) {
3477 attr &= ~ATTR_UNDER;
3478 force_manual_underline = 1;
3483 /* Anything left as an original character set is unprintable. */
3484 if (DIRECT_CHAR(text[0]) &&
3485 (len < 2 || !IS_SURROGATE_PAIR(text[0], text[1]))) {
3487 for (i = 0; i < len; i++)
3492 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3495 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3496 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3497 if (bold_font_mode == BOLD_FONT && (attr & ATTR_BOLD))
3499 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3500 nfont |= FONT_UNDERLINE;
3501 another_font(nfont);
3502 if (!fonts[nfont]) {
3503 if (nfont & FONT_UNDERLINE)
3504 force_manual_underline = 1;
3505 /* Don't do the same for manual bold, it could be bad news. */
3507 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3509 another_font(nfont);
3511 nfont = FONT_NORMAL;
3512 if (attr & ATTR_REVERSE) {
3517 if (bold_colours && (attr & ATTR_BOLD) && !is_cursor) {
3518 if (nfg < 16) nfg |= 8;
3519 else if (nfg >= 256) nfg |= 1;
3521 if (bold_colours && (attr & ATTR_BLINK)) {
3522 if (nbg < 16) nbg |= 8;
3523 else if (nbg >= 256) nbg |= 1;
3527 SelectObject(hdc, fonts[nfont]);
3528 SetTextColor(hdc, fg);
3529 SetBkColor(hdc, bg);
3530 if (attr & TATTR_COMBINING)
3531 SetBkMode(hdc, TRANSPARENT);
3533 SetBkMode(hdc, OPAQUE);
3536 line_box.right = x + char_width * len;
3537 line_box.bottom = y + font_height;
3538 /* adjust line_box.right for SURROGATE PAIR & VARIATION SELECTOR */
3542 for (i = 0; i < len ; i++) {
3543 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3545 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i], text[i+1])) {
3546 rc_width += char_width;
3548 } else if (IS_LOW_VARSEL(text[i])) {
3551 rc_width += char_width;
3554 line_box.right = line_box.left + rc_width;
3557 /* Only want the left half of double width lines */
3558 if (line_box.right > font_width*term->cols+offset_width)
3559 line_box.right = font_width*term->cols+offset_width;
3561 if (font_varpitch) {
3563 * If we're using a variable-pitch font, we unconditionally
3564 * draw the glyphs one at a time and centre them in their
3565 * character cells (which means in particular that we must
3566 * disable the lpDx mechanism). This gives slightly odd but
3567 * generally reasonable results.
3569 xoffset = char_width / 2;
3570 SetTextAlign(hdc, TA_TOP | TA_CENTER | TA_NOUPDATECP);
3575 * In a fixed-pitch font, we draw the whole string in one go
3576 * in the normal way.
3579 SetTextAlign(hdc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
3584 opaque = TRUE; /* start by erasing the rectangle */
3585 for (remaining = len; remaining > 0;
3586 text += len, remaining -= len, x += char_width * len2) {
3587 len = (maxlen < remaining ? maxlen : remaining);
3588 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3591 if (remaining >= 1 && IS_SURROGATE_PAIR(text[0], text[1]))
3593 if (remaining-len >= 1 && IS_LOW_VARSEL(text[len]))
3595 else if (remaining-len >= 2 &&
3596 IS_HIGH_VARSEL(text[len], text[len+1]))
3600 if (len > lpDx_len) {
3601 lpDx_len = len * 9 / 8 + 16;
3602 lpDx = sresize(lpDx, lpDx_len, int);
3604 if (lpDx_maybe) lpDx_maybe = lpDx;
3609 /* only last char has dx width in SURROGATE PAIR and
3610 * VARIATION sequence */
3611 for (i = 0; i < len; i++) {
3612 lpDx[i] = char_width;
3613 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3614 if (i > 0) lpDx[i-1] = 0;
3617 lpDx[i] = char_width;
3618 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i],text[i+1])) {
3621 lpDx[i] = char_width;
3622 } else if (IS_LOW_VARSEL(text[i])) {
3623 if (i > 0) lpDx[i-1] = 0;
3624 lpDx[i] = char_width;
3629 /* We're using a private area for direct to font. (512 chars.) */
3630 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3631 /* Ho Hum, dbcs fonts are a PITA! */
3632 /* To display on W9x I have to convert to UCS */
3633 static wchar_t *uni_buf = 0;
3634 static int uni_len = 0;
3636 if (len > uni_len) {
3639 uni_buf = snewn(uni_len, wchar_t);
3642 for(nlen = mptr = 0; mptr<len; mptr++) {
3643 uni_buf[nlen] = 0xFFFD;
3644 if (IsDBCSLeadByteEx(ucsdata.font_codepage,
3645 (BYTE) text[mptr])) {
3647 dbcstext[0] = text[mptr] & 0xFF;
3648 dbcstext[1] = text[mptr+1] & 0xFF;
3649 lpDx[nlen] += char_width;
3650 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3651 dbcstext, 2, uni_buf+nlen, 1);
3657 dbcstext[0] = text[mptr] & 0xFF;
3658 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3659 dbcstext, 1, uni_buf+nlen, 1);
3666 ExtTextOutW(hdc, x + xoffset,
3667 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3668 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3669 &line_box, uni_buf, nlen,
3671 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3672 SetBkMode(hdc, TRANSPARENT);
3673 ExtTextOutW(hdc, x + xoffset - 1,
3674 y - font_height * (lattr ==
3675 LATTR_BOT) + text_adjust,
3676 ETO_CLIPPED, &line_box, uni_buf, nlen, lpDx_maybe);
3680 } else if (DIRECT_FONT(text[0])) {
3681 static char *directbuf = NULL;
3682 static int directlen = 0;
3684 if (len > directlen) {
3686 directbuf = sresize(directbuf, directlen, char);
3689 for (i = 0; i < len; i++)
3690 directbuf[i] = text[i] & 0xFF;
3692 ExtTextOut(hdc, x + xoffset,
3693 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3694 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3695 &line_box, directbuf, len, lpDx_maybe);
3696 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3697 SetBkMode(hdc, TRANSPARENT);
3699 /* GRR: This draws the character outside its box and
3700 * can leave 'droppings' even with the clip box! I
3701 * suppose I could loop it one character at a time ...
3704 * Or ... I could do a test print with "W", and use +1
3705 * or -1 for this shift depending on if the leftmost
3706 * column is blank...
3708 ExtTextOut(hdc, x + xoffset - 1,
3709 y - font_height * (lattr ==
3710 LATTR_BOT) + text_adjust,
3711 ETO_CLIPPED, &line_box, directbuf, len, lpDx_maybe);
3714 /* And 'normal' unicode characters */
3715 static WCHAR *wbuf = NULL;
3716 static int wlen = 0;
3722 wbuf = snewn(wlen, WCHAR);
3725 for (i = 0; i < len; i++)
3728 /* print Glyphs as they are, without Windows' Shaping*/
3729 general_textout(hdc, x + xoffset,
3730 y - font_height * (lattr==LATTR_BOT) + text_adjust,
3731 &line_box, wbuf, len, lpDx,
3732 opaque && !(attr & TATTR_COMBINING));
3734 /* And the shadow bold hack. */
3735 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3736 SetBkMode(hdc, TRANSPARENT);
3737 ExtTextOutW(hdc, x + xoffset - 1,
3738 y - font_height * (lattr ==
3739 LATTR_BOT) + text_adjust,
3740 ETO_CLIPPED, &line_box, wbuf, len, lpDx_maybe);
3745 * If we're looping round again, stop erasing the background
3748 SetBkMode(hdc, TRANSPARENT);
3751 if (lattr != LATTR_TOP && (force_manual_underline ||
3752 (und_mode == UND_LINE
3753 && (attr & ATTR_UNDER)))) {
3756 if (lattr == LATTR_BOT)
3757 dec = dec * 2 - font_height;
3759 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3760 MoveToEx(hdc, line_box.left, line_box.top + dec, NULL);
3761 LineTo(hdc, line_box.right, line_box.top + dec);
3762 oldpen = SelectObject(hdc, oldpen);
3763 DeleteObject(oldpen);
3768 * Wrapper that handles combining characters.
3770 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3771 unsigned long attr, int lattr)
3773 if (attr & TATTR_COMBINING) {
3774 unsigned long a = 0;
3776 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3777 if (len >= 2 && IS_SURROGATE_PAIR(text[0], text[1]))
3779 if (len-len0 >= 1 && IS_LOW_VARSEL(text[len0])) {
3780 attr &= ~TATTR_COMBINING;
3781 do_text_internal(ctx, x, y, text, len0+1, attr, lattr);
3784 a = TATTR_COMBINING;
3785 } else if (len-len0 >= 2 && IS_HIGH_VARSEL(text[len0], text[len0+1])) {
3786 attr &= ~TATTR_COMBINING;
3787 do_text_internal(ctx, x, y, text, len0+2, attr, lattr);
3790 a = TATTR_COMBINING;
3792 attr &= ~TATTR_COMBINING;
3796 if (len >= 1 && IS_SURROGATE_PAIR(text[0], text[1])) {
3797 do_text_internal(ctx, x, y, text, 2, attr | a, lattr);
3801 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3805 a = TATTR_COMBINING;
3808 do_text_internal(ctx, x, y, text, len, attr, lattr);
3811 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3812 unsigned long attr, int lattr)
3818 int ctype = cursor_type;
3820 lattr &= LATTR_MODE;
3822 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3823 if (*text != UCSWIDE) {
3824 do_text(ctx, x, y, text, len, attr, lattr);
3828 attr |= TATTR_RIGHTCURS;
3831 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3832 if (attr & ATTR_WIDE)
3839 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3842 pts[0].x = pts[1].x = pts[4].x = x;
3843 pts[2].x = pts[3].x = x + char_width - 1;
3844 pts[0].y = pts[3].y = pts[4].y = y;
3845 pts[1].y = pts[2].y = y + font_height - 1;
3846 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3847 Polyline(hdc, pts, 5);
3848 oldpen = SelectObject(hdc, oldpen);
3849 DeleteObject(oldpen);
3850 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3851 int startx, starty, dx, dy, length, i;
3854 starty = y + descent;
3857 length = char_width;
3860 if (attr & TATTR_RIGHTCURS)
3861 xadjust = char_width - 1;
3862 startx = x + xadjust;
3866 length = font_height;
3868 if (attr & TATTR_ACTCURS) {
3871 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3872 MoveToEx(hdc, startx, starty, NULL);
3873 LineTo(hdc, startx + dx * length, starty + dy * length);
3874 oldpen = SelectObject(hdc, oldpen);
3875 DeleteObject(oldpen);
3877 for (i = 0; i < length; i++) {
3879 SetPixel(hdc, startx, starty, colours[261]);
3888 /* This function gets the actual width of a character in the normal font.
3890 int char_width(Context ctx, int uc) {
3894 /* If the font max is the same as the font ave width then this
3895 * function is a no-op.
3897 if (!font_dualwidth) return 1;
3899 switch (uc & CSET_MASK) {
3901 uc = ucsdata.unitab_line[uc & 0xFF];
3904 uc = ucsdata.unitab_xterm[uc & 0xFF];
3907 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3910 if (DIRECT_FONT(uc)) {
3911 if (ucsdata.dbcs_screenfont) return 1;
3913 /* Speedup, I know of no font where ascii is the wrong width */
3914 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3917 if ( (uc & CSET_MASK) == CSET_ACP ) {
3918 SelectObject(hdc, fonts[FONT_NORMAL]);
3919 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3920 another_font(FONT_OEM);
3921 if (!fonts[FONT_OEM]) return 0;
3923 SelectObject(hdc, fonts[FONT_OEM]);
3927 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3928 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3931 /* Speedup, I know of no font where ascii is the wrong width */
3932 if (uc >= ' ' && uc <= '~') return 1;
3934 SelectObject(hdc, fonts[FONT_NORMAL]);
3935 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3936 /* Okay that one worked */ ;
3937 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3938 /* This should work on 9x too, but it's "less accurate" */ ;
3943 ibuf += font_width / 2 -1;
3949 DECL_WINDOWS_FUNCTION(static, BOOL, FlashWindowEx, (PFLASHWINFO));
3950 DECL_WINDOWS_FUNCTION(static, BOOL, ToUnicodeEx,
3951 (UINT, UINT, const BYTE *, LPWSTR, int, UINT, HKL));
3953 static void init_winfuncs(void)
3955 HMODULE user32_module = load_system32_dll("user32.dll");
3956 GET_WINDOWS_FUNCTION(user32_module, FlashWindowEx);
3957 GET_WINDOWS_FUNCTION(user32_module, ToUnicodeEx);
3961 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3962 * codes. Returns number of bytes used, zero to drop the message,
3963 * -1 to forward the message to Windows, or another negative number
3964 * to indicate a NUL-terminated "special" string.
3966 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3967 unsigned char *output)
3970 int scan, left_alt = 0, key_down, shift_state;
3972 unsigned char *p = output;
3973 static int alt_sum = 0;
3974 int funky_type = conf_get_int(conf, CONF_funky_type);
3975 int no_applic_k = conf_get_int(conf, CONF_no_applic_k);
3976 int ctrlaltkeys = conf_get_int(conf, CONF_ctrlaltkeys);
3977 int nethack_keypad = conf_get_int(conf, CONF_nethack_keypad);
3979 HKL kbd_layout = GetKeyboardLayout(0);
3981 static wchar_t keys_unicode[3];
3982 static int compose_char = 0;
3983 static WPARAM compose_keycode = 0;
3985 r = GetKeyboardState(keystate);
3987 memset(keystate, 0, sizeof(keystate));
3990 #define SHOW_TOASCII_RESULT
3991 { /* Tell us all about key events */
3992 static BYTE oldstate[256];
3993 static int first = 1;
3997 memcpy(oldstate, keystate, sizeof(oldstate));
4000 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
4002 } else if ((HIWORD(lParam) & KF_UP)
4003 && scan == (HIWORD(lParam) & 0xFF)) {
4007 if (wParam >= VK_F1 && wParam <= VK_F20)
4008 debug(("K_F%d", wParam + 1 - VK_F1));
4021 debug(("VK_%02x", wParam));
4023 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
4025 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
4027 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
4028 if (ch >= ' ' && ch <= '~')
4029 debug((", '%c'", ch));
4031 debug((", $%02x", ch));
4033 if (keys_unicode[0])
4034 debug((", KB0=%04x", keys_unicode[0]));
4035 if (keys_unicode[1])
4036 debug((", KB1=%04x", keys_unicode[1]));
4037 if (keys_unicode[2])
4038 debug((", KB2=%04x", keys_unicode[2]));
4040 if ((keystate[VK_SHIFT] & 0x80) != 0)
4042 if ((keystate[VK_CONTROL] & 0x80) != 0)
4044 if ((HIWORD(lParam) & KF_EXTENDED))
4046 if ((HIWORD(lParam) & KF_UP))
4050 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
4051 else if ((HIWORD(lParam) & KF_UP))
4052 oldstate[wParam & 0xFF] ^= 0x80;
4054 oldstate[wParam & 0xFF] ^= 0x81;
4056 for (ch = 0; ch < 256; ch++)
4057 if (oldstate[ch] != keystate[ch])
4058 debug((", M%02x=%02x", ch, keystate[ch]));
4060 memcpy(oldstate, keystate, sizeof(oldstate));
4064 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
4065 keystate[VK_RMENU] = keystate[VK_MENU];
4069 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
4070 if ((funky_type == FUNKY_VT400 ||
4071 (funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
4073 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
4075 wParam = VK_EXECUTE;
4077 /* UnToggle NUMLock */
4078 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
4079 keystate[VK_NUMLOCK] ^= 1;
4082 /* And write back the 'adjusted' state */
4083 SetKeyboardState(keystate);
4086 /* Disable Auto repeat if required */
4087 if (term->repeat_off &&
4088 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
4091 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
4094 key_down = ((HIWORD(lParam) & KF_UP) == 0);
4096 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
4097 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
4099 keystate[VK_MENU] = 0;
4101 keystate[VK_RMENU] = 0x80;
4106 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
4107 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
4108 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
4110 /* Note if AltGr was pressed and if it was used as a compose key */
4111 if (!compose_state) {
4112 compose_keycode = 0x100;
4113 if (conf_get_int(conf, CONF_compose_key)) {
4114 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
4115 compose_keycode = wParam;
4117 if (wParam == VK_APPS)
4118 compose_keycode = wParam;
4121 if (wParam == compose_keycode) {
4122 if (compose_state == 0
4123 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
4125 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
4129 } else if (compose_state == 1 && wParam != VK_CONTROL)
4132 if (compose_state > 1 && left_alt)
4135 /* Sanitize the number pad if not using a PC NumPad */
4136 if (left_alt || (term->app_keypad_keys && !no_applic_k
4137 && funky_type != FUNKY_XTERM)
4138 || funky_type == FUNKY_VT400 || nethack_keypad || compose_state) {
4139 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
4143 nParam = VK_NUMPAD0;
4146 nParam = VK_NUMPAD1;
4149 nParam = VK_NUMPAD2;
4152 nParam = VK_NUMPAD3;
4155 nParam = VK_NUMPAD4;
4158 nParam = VK_NUMPAD5;
4161 nParam = VK_NUMPAD6;
4164 nParam = VK_NUMPAD7;
4167 nParam = VK_NUMPAD8;
4170 nParam = VK_NUMPAD9;
4173 nParam = VK_DECIMAL;
4177 if (keystate[VK_NUMLOCK] & 1)
4184 /* If a key is pressed and AltGr is not active */
4185 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
4186 /* Okay, prepare for most alts then ... */
4190 /* Lets see if it's a pattern we know all about ... */
4191 if (wParam == VK_PRIOR && shift_state == 1) {
4192 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
4195 if (wParam == VK_PRIOR && shift_state == 2) {
4196 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
4199 if (wParam == VK_NEXT && shift_state == 1) {
4200 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
4203 if (wParam == VK_NEXT && shift_state == 2) {
4204 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
4207 if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) {
4208 term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1));
4211 if (wParam == VK_INSERT && shift_state == 1) {
4212 request_paste(NULL);
4215 if (left_alt && wParam == VK_F4 && conf_get_int(conf, CONF_alt_f4)) {
4218 if (left_alt && wParam == VK_SPACE && conf_get_int(conf,
4220 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
4223 if (left_alt && wParam == VK_RETURN &&
4224 conf_get_int(conf, CONF_fullscreenonaltenter) &&
4225 (conf_get_int(conf, CONF_resize_action) != RESIZE_DISABLED)) {
4226 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
4230 /* Control-Numlock for app-keypad mode switch */
4231 if (wParam == VK_PAUSE && shift_state == 2) {
4232 term->app_keypad_keys ^= 1;
4236 /* Nethack keypad */
4237 if (nethack_keypad && !left_alt) {
4240 *p++ = "bB\002\002"[shift_state & 3];
4243 *p++ = "jJ\012\012"[shift_state & 3];
4246 *p++ = "nN\016\016"[shift_state & 3];
4249 *p++ = "hH\010\010"[shift_state & 3];
4255 *p++ = "lL\014\014"[shift_state & 3];
4258 *p++ = "yY\031\031"[shift_state & 3];
4261 *p++ = "kK\013\013"[shift_state & 3];
4264 *p++ = "uU\025\025"[shift_state & 3];
4269 /* Application Keypad */
4273 if (funky_type == FUNKY_VT400 ||
4274 (funky_type <= FUNKY_LINUX &&
4275 term->app_keypad_keys && !no_applic_k)) switch (wParam) {
4289 if (term->app_keypad_keys && !no_applic_k)
4326 if (funky_type == FUNKY_XTERM) {
4331 } else if (shift_state)
4338 if (funky_type == FUNKY_XTERM)
4342 if (funky_type == FUNKY_XTERM)
4346 if (funky_type == FUNKY_XTERM)
4351 if (HIWORD(lParam) & KF_EXTENDED)
4356 if (term->vt52_mode) {
4357 if (xkey >= 'P' && xkey <= 'S')
4358 p += sprintf((char *) p, "\x1B%c", xkey);
4360 p += sprintf((char *) p, "\x1B?%c", xkey);
4362 p += sprintf((char *) p, "\x1BO%c", xkey);
4367 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
4368 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x7F : 0x08);
4372 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
4373 /* We do the opposite of what is configured */
4374 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x08 : 0x7F);
4378 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
4384 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
4388 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
4392 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
4394 back->special(backhandle, TS_BRK);
4397 if (wParam == VK_PAUSE) { /* Break/Pause */
4402 /* Control-2 to Control-8 are special */
4403 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
4404 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
4407 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
4411 if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) {
4415 if (shift_state == 3 && wParam == 0xDE) {
4416 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
4419 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
4426 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
4427 * for integer decimal nn.)
4429 * We also deal with the weird ones here. Linux VCs replace F1
4430 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
4431 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
4437 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
4440 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
4443 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
4446 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
4449 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
4452 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
4455 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
4458 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
4461 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
4464 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
4497 if ((shift_state&2) == 0) switch (wParam) {
4517 /* Reorder edit keys to physical order */
4518 if (funky_type == FUNKY_VT400 && code <= 6)
4519 code = "\0\2\1\4\5\3\6"[code];
4521 if (term->vt52_mode && code > 0 && code <= 6) {
4522 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4526 if (funky_type == FUNKY_SCO && code >= 11 && code <= 34) {
4527 /* SCO function keys */
4528 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4531 case VK_F1: index = 0; break;
4532 case VK_F2: index = 1; break;
4533 case VK_F3: index = 2; break;
4534 case VK_F4: index = 3; break;
4535 case VK_F5: index = 4; break;
4536 case VK_F6: index = 5; break;
4537 case VK_F7: index = 6; break;
4538 case VK_F8: index = 7; break;
4539 case VK_F9: index = 8; break;
4540 case VK_F10: index = 9; break;
4541 case VK_F11: index = 10; break;
4542 case VK_F12: index = 11; break;
4544 if (keystate[VK_SHIFT] & 0x80) index += 12;
4545 if (keystate[VK_CONTROL] & 0x80) index += 24;
4546 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4549 if (funky_type == FUNKY_SCO && /* SCO small keypad */
4550 code >= 1 && code <= 6) {
4551 char codes[] = "HL.FIG";
4555 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4559 if ((term->vt52_mode || funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4565 if (term->vt52_mode)
4566 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4569 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4572 if (funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4573 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4576 if (funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4577 if (term->vt52_mode)
4578 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4580 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4583 if ((code == 1 || code == 4) &&
4584 conf_get_int(conf, CONF_rxvt_homeend)) {
4585 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4589 p += sprintf((char *) p, "\x1B[%d~", code);
4594 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4595 * some reason seems to send VK_CLEAR to Windows...).
4617 p += format_arrow_key((char *)p, term, xkey, shift_state);
4623 * Finally, deal with Return ourselves. (Win95 seems to
4624 * foul it up when Alt is pressed, for some reason.)
4626 if (wParam == VK_RETURN) { /* Return */
4632 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4633 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4638 /* Okay we've done everything interesting; let windows deal with
4639 * the boring stuff */
4643 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4644 if(keystate[VK_CAPITAL] != 0 &&
4645 conf_get_int(conf, CONF_xlat_capslockcyr)) {
4647 keystate[VK_CAPITAL] = 0;
4650 /* XXX how do we know what the max size of the keys array should
4651 * be is? There's indication on MS' website of an Inquire/InquireEx
4652 * functioning returning a KBINFO structure which tells us. */
4653 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT && p_ToUnicodeEx) {
4654 r = p_ToUnicodeEx(wParam, scan, keystate, keys_unicode,
4655 lenof(keys_unicode), 0, kbd_layout);
4657 /* XXX 'keys' parameter is declared in MSDN documentation as
4659 * The experience of a French user indicates that on
4660 * Win98, WORD[] should be passed in, but on Win2K, it should
4661 * be BYTE[]. German WinXP and my Win2K with "US International"
4662 * driver corroborate this.
4663 * Experimentally I've conditionalised the behaviour on the
4664 * Win9x/NT split, but I suspect it's worse than that.
4665 * See wishlist item `win-dead-keys' for more horrible detail
4666 * and speculations. */
4668 static WORD keys[3];
4669 static BYTE keysb[3];
4670 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4672 for (i = 0; i < r; i++) {
4673 keysb[i] = (BYTE)keys[i];
4675 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)keysb, r,
4676 keys_unicode, lenof(keys_unicode));
4679 #ifdef SHOW_TOASCII_RESULT
4680 if (r == 1 && !key_down) {
4682 if (in_utf(term) || ucsdata.dbcs_screenfont)
4683 debug((", (U+%04x)", alt_sum));
4685 debug((", LCH(%d)", alt_sum));
4687 debug((", ACH(%d)", keys_unicode[0]));
4692 for (r1 = 0; r1 < r; r1++) {
4693 debug(("%s%d", r1 ? "," : "", keys_unicode[r1]));
4702 for (i = 0; i < r; i++) {
4703 wchar_t wch = keys_unicode[i];
4705 if (compose_state == 2 && wch >= ' ' && wch < 0x80) {
4710 if (compose_state == 3 && wch >= ' ' && wch < 0x80) {
4714 if ((nc = check_compose(compose_char, wch)) == -1) {
4715 MessageBeep(MB_ICONHAND);
4719 term_seen_key_event(term);
4721 luni_send(ldisc, &keybuf, 1, 1);
4729 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4731 term_seen_key_event(term);
4733 luni_send(ldisc, &keybuf, 1, 1);
4735 char ch = (char) alt_sum;
4737 * We need not bother about stdin
4738 * backlogs here, because in GUI PuTTY
4739 * we can't do anything about it
4740 * anyway; there's no means of asking
4741 * Windows to hold off on KEYDOWN
4742 * messages. We _have_ to buffer
4743 * everything we're sent.
4745 term_seen_key_event(term);
4747 ldisc_send(ldisc, &ch, 1, 1);
4751 term_seen_key_event(term);
4753 luni_send(ldisc, &wch, 1, 1);
4756 if(capsOn && wch < 0x80) {
4759 cbuf[1] = xlat_uskbd2cyrllic(wch);
4760 term_seen_key_event(term);
4762 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4767 term_seen_key_event(term);
4769 luni_send(ldisc, cbuf +!left_alt, 1+!!left_alt, 1);
4775 /* This is so the ALT-Numpad and dead keys work correctly. */
4776 keys_unicode[0] = 0;
4780 /* If we're definitly not building up an ALT-54321 then clear it */
4782 keys_unicode[0] = 0;
4783 /* If we will be using alt_sum fix the 256s */
4784 else if (keys_unicode[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4785 keys_unicode[0] = 10;
4789 * ALT alone may or may not want to bring up the System menu.
4790 * If it's not meant to, we return 0 on presses or releases of
4791 * ALT, to show that we've swallowed the keystroke. Otherwise
4792 * we return -1, which means Windows will give the keystroke
4793 * its default handling (i.e. bring up the System menu).
4795 if (wParam == VK_MENU && !conf_get_int(conf, CONF_alt_only))
4801 void set_title(void *frontend, char *title)
4804 window_name = snewn(1 + strlen(title), char);
4805 strcpy(window_name, title);
4806 if (conf_get_int(conf, CONF_win_name_always) || !IsIconic(hwnd))
4807 SetWindowText(hwnd, title);
4810 void set_icon(void *frontend, char *title)
4813 icon_name = snewn(1 + strlen(title), char);
4814 strcpy(icon_name, title);
4815 if (!conf_get_int(conf, CONF_win_name_always) && IsIconic(hwnd))
4816 SetWindowText(hwnd, title);
4819 void set_sbar(void *frontend, int total, int start, int page)
4823 if (!conf_get_int(conf, is_full_screen() ?
4824 CONF_scrollbar_in_fullscreen : CONF_scrollbar))
4827 si.cbSize = sizeof(si);
4828 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4830 si.nMax = total - 1;
4834 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4837 Context get_ctx(void *frontend)
4843 SelectPalette(hdc, pal, FALSE);
4849 void free_ctx(Context ctx)
4851 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4852 ReleaseDC(hwnd, ctx);
4855 static void real_palette_set(int n, int r, int g, int b)
4858 logpal->palPalEntry[n].peRed = r;
4859 logpal->palPalEntry[n].peGreen = g;
4860 logpal->palPalEntry[n].peBlue = b;
4861 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4862 colours[n] = PALETTERGB(r, g, b);
4863 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4865 colours[n] = RGB(r, g, b);
4868 void palette_set(void *frontend, int n, int r, int g, int b)
4872 if (n >= NALLCOLOURS)
4874 real_palette_set(n, r, g, b);
4876 HDC hdc = get_ctx(frontend);
4877 UnrealizeObject(pal);
4878 RealizePalette(hdc);
4881 if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))
4882 /* If Default Background changes, we need to ensure any
4883 * space between the text area and the window border is
4885 InvalidateRect(hwnd, NULL, TRUE);
4889 void palette_reset(void *frontend)
4894 for (i = 0; i < NALLCOLOURS; i++) {
4896 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4897 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4898 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4899 logpal->palPalEntry[i].peFlags = 0;
4900 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4901 defpal[i].rgbtGreen,
4902 defpal[i].rgbtBlue);
4904 colours[i] = RGB(defpal[i].rgbtRed,
4905 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4910 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4911 hdc = get_ctx(frontend);
4912 RealizePalette(hdc);
4915 /* Default Background may have changed. Ensure any space between
4916 * text area and window border is redrawn. */
4917 InvalidateRect(hwnd, NULL, TRUE);
4921 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4926 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4929 lock = GlobalLock(clipdata);
4932 memcpy(lock, data, len);
4933 ((unsigned char *) lock)[len] = 0;
4934 GlobalUnlock(clipdata);
4937 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4939 if (OpenClipboard(hwnd)) {
4941 SetClipboardData(CF_TEXT, clipdata);
4944 GlobalFree(clipdata);
4947 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4951 * Note: unlike write_aclip() this will not append a nul.
4953 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
4955 HGLOBAL clipdata, clipdata2, clipdata3;
4957 void *lock, *lock2, *lock3;
4959 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4961 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4962 len * sizeof(wchar_t));
4963 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4965 if (!clipdata || !clipdata2) {
4967 GlobalFree(clipdata);
4969 GlobalFree(clipdata2);
4972 if (!(lock = GlobalLock(clipdata))) {
4973 GlobalFree(clipdata);
4974 GlobalFree(clipdata2);
4977 if (!(lock2 = GlobalLock(clipdata2))) {
4978 GlobalUnlock(clipdata);
4979 GlobalFree(clipdata);
4980 GlobalFree(clipdata2);
4984 memcpy(lock, data, len * sizeof(wchar_t));
4985 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4987 if (conf_get_int(conf, CONF_rtf_paste)) {
4988 wchar_t unitab[256];
4990 unsigned char *tdata = (unsigned char *)lock2;
4991 wchar_t *udata = (wchar_t *)lock;
4992 int rtflen = 0, uindex = 0, tindex = 0;
4994 int multilen, blen, alen, totallen, i;
4995 char before[16], after[4];
4996 int fgcolour, lastfgcolour = 0;
4997 int bgcolour, lastbgcolour = 0;
4998 int attrBold, lastAttrBold = 0;
4999 int attrUnder, lastAttrUnder = 0;
5000 int palette[NALLCOLOURS];
5002 FontSpec *font = conf_get_fontspec(conf, CONF_font);
5004 get_unitab(CP_ACP, unitab, 0);
5006 rtfsize = 100 + strlen(font->name);
5007 rtf = snewn(rtfsize, char);
5008 rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
5009 font->name, font->height*2);
5012 * Add colour palette
5013 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
5017 * First - Determine all colours in use
5018 * o Foregound and background colours share the same palette
5021 memset(palette, 0, sizeof(palette));
5022 for (i = 0; i < (len-1); i++) {
5023 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5024 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5026 if (attr[i] & ATTR_REVERSE) {
5027 int tmpcolour = fgcolour; /* Swap foreground and background */
5028 fgcolour = bgcolour;
5029 bgcolour = tmpcolour;
5032 if (bold_colours && (attr[i] & ATTR_BOLD)) {
5033 if (fgcolour < 8) /* ANSI colours */
5035 else if (fgcolour >= 256) /* Default colours */
5039 if (attr[i] & ATTR_BLINK) {
5040 if (bgcolour < 8) /* ANSI colours */
5042 else if (bgcolour >= 256) /* Default colours */
5046 palette[fgcolour]++;
5047 palette[bgcolour]++;
5051 * Next - Create a reduced palette
5054 for (i = 0; i < NALLCOLOURS; i++) {
5055 if (palette[i] != 0)
5056 palette[i] = ++numcolours;
5060 * Finally - Write the colour table
5062 rtf = sresize(rtf, rtfsize + (numcolours * 25), char);
5063 strcat(rtf, "{\\colortbl ;");
5064 rtflen = strlen(rtf);
5066 for (i = 0; i < NALLCOLOURS; i++) {
5067 if (palette[i] != 0) {
5068 rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);
5071 strcpy(&rtf[rtflen], "}");
5076 * We want to construct a piece of RTF that specifies the
5077 * same Unicode text. To do this we will read back in
5078 * parallel from the Unicode data in `udata' and the
5079 * non-Unicode data in `tdata'. For each character in
5080 * `tdata' which becomes the right thing in `udata' when
5081 * looked up in `unitab', we just copy straight over from
5082 * tdata. For each one that doesn't, we must WCToMB it
5083 * individually and produce a \u escape sequence.
5085 * It would probably be more robust to just bite the bullet
5086 * and WCToMB each individual Unicode character one by one,
5087 * then MBToWC each one back to see if it was an accurate
5088 * translation; but that strikes me as a horrifying number
5089 * of Windows API calls so I want to see if this faster way
5090 * will work. If it screws up badly we can always revert to
5091 * the simple and slow way.
5093 while (tindex < len2 && uindex < len &&
5094 tdata[tindex] && udata[uindex]) {
5095 if (tindex + 1 < len2 &&
5096 tdata[tindex] == '\r' &&
5097 tdata[tindex+1] == '\n') {
5103 * Set text attributes
5106 if (rtfsize < rtflen + 64) {
5107 rtfsize = rtflen + 512;
5108 rtf = sresize(rtf, rtfsize, char);
5112 * Determine foreground and background colours
5114 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5115 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5117 if (attr[tindex] & ATTR_REVERSE) {
5118 int tmpcolour = fgcolour; /* Swap foreground and background */
5119 fgcolour = bgcolour;
5120 bgcolour = tmpcolour;
5123 if (bold_colours && (attr[tindex] & ATTR_BOLD)) {
5124 if (fgcolour < 8) /* ANSI colours */
5126 else if (fgcolour >= 256) /* Default colours */
5130 if (attr[tindex] & ATTR_BLINK) {
5131 if (bgcolour < 8) /* ANSI colours */
5133 else if (bgcolour >= 256) /* Default colours */
5138 * Collect other attributes
5140 if (bold_font_mode != BOLD_NONE)
5141 attrBold = attr[tindex] & ATTR_BOLD;
5145 attrUnder = attr[tindex] & ATTR_UNDER;
5149 * o If video isn't reversed, ignore colour attributes for default foregound
5151 * o Special case where bolded text is displayed using the default foregound
5152 * and background colours - force to bolded RTF.
5154 if (!(attr[tindex] & ATTR_REVERSE)) {
5155 if (bgcolour >= 256) /* Default color */
5156 bgcolour = -1; /* No coloring */
5158 if (fgcolour >= 256) { /* Default colour */
5159 if (bold_colours && (fgcolour & 1) && bgcolour == -1)
5160 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
5162 fgcolour = -1; /* No coloring */
5167 * Write RTF text attributes
5169 if (lastfgcolour != fgcolour) {
5170 lastfgcolour = fgcolour;
5171 rtflen += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
5174 if (lastbgcolour != bgcolour) {
5175 lastbgcolour = bgcolour;
5176 rtflen += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
5179 if (lastAttrBold != attrBold) {
5180 lastAttrBold = attrBold;
5181 rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
5184 if (lastAttrUnder != attrUnder) {
5185 lastAttrUnder = attrUnder;
5186 rtflen += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
5190 if (unitab[tdata[tindex]] == udata[uindex]) {
5196 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
5197 NULL, 0, NULL, NULL);
5198 if (multilen != 1) {
5199 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
5201 alen = 1; strcpy(after, "}");
5203 blen = sprintf(before, "\\u%d", udata[uindex]);
5204 alen = 0; after[0] = '\0';
5207 assert(tindex + multilen <= len2);
5208 totallen = blen + alen;
5209 for (i = 0; i < multilen; i++) {
5210 if (tdata[tindex+i] == '\\' ||
5211 tdata[tindex+i] == '{' ||
5212 tdata[tindex+i] == '}')
5214 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
5215 totallen += 6; /* \par\r\n */
5216 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
5222 if (rtfsize < rtflen + totallen + 3) {
5223 rtfsize = rtflen + totallen + 512;
5224 rtf = sresize(rtf, rtfsize, char);
5227 strcpy(rtf + rtflen, before); rtflen += blen;
5228 for (i = 0; i < multilen; i++) {
5229 if (tdata[tindex+i] == '\\' ||
5230 tdata[tindex+i] == '{' ||
5231 tdata[tindex+i] == '}') {
5232 rtf[rtflen++] = '\\';
5233 rtf[rtflen++] = tdata[tindex+i];
5234 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
5235 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
5236 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
5237 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
5239 rtf[rtflen++] = tdata[tindex+i];
5242 strcpy(rtf + rtflen, after); rtflen += alen;
5248 rtf[rtflen++] = '}'; /* Terminate RTF stream */
5249 rtf[rtflen++] = '\0';
5250 rtf[rtflen++] = '\0';
5252 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
5253 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
5254 memcpy(lock3, rtf, rtflen);
5255 GlobalUnlock(clipdata3);
5261 GlobalUnlock(clipdata);
5262 GlobalUnlock(clipdata2);
5265 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
5267 if (OpenClipboard(hwnd)) {
5269 SetClipboardData(CF_UNICODETEXT, clipdata);
5270 SetClipboardData(CF_TEXT, clipdata2);
5272 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
5275 GlobalFree(clipdata);
5276 GlobalFree(clipdata2);
5280 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
5283 static DWORD WINAPI clipboard_read_threadfunc(void *param)
5285 HWND hwnd = (HWND)param;
5288 if (OpenClipboard(NULL)) {
5289 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
5290 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)1, (LPARAM)clipdata);
5291 } else if ((clipdata = GetClipboardData(CF_TEXT))) {
5292 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)0, (LPARAM)clipdata);
5300 static int process_clipdata(HGLOBAL clipdata, int unicode)
5302 sfree(clipboard_contents);
5303 clipboard_contents = NULL;
5304 clipboard_length = 0;
5307 wchar_t *p = GlobalLock(clipdata);
5311 /* Unwilling to rely on Windows having wcslen() */
5312 for (p2 = p; *p2; p2++);
5313 clipboard_length = p2 - p;
5314 clipboard_contents = snewn(clipboard_length + 1, wchar_t);
5315 memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t));
5316 clipboard_contents[clipboard_length] = L'\0';
5320 char *s = GlobalLock(clipdata);
5324 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
5325 clipboard_contents = snewn(i, wchar_t);
5326 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1,
5327 clipboard_contents, i);
5328 clipboard_length = i - 1;
5329 clipboard_contents[clipboard_length] = L'\0';
5337 void request_paste(void *frontend)
5340 * I always thought pasting was synchronous in Windows; the
5341 * clipboard access functions certainly _look_ synchronous,
5342 * unlike the X ones. But in fact it seems that in some
5343 * situations the contents of the clipboard might not be
5344 * immediately available, and the clipboard-reading functions
5345 * may block. This leads to trouble if the application
5346 * delivering the clipboard data has to get hold of it by -
5347 * for example - talking over a network connection which is
5348 * forwarded through this very PuTTY.
5350 * Hence, we spawn a subthread to read the clipboard, and do
5351 * our paste when it's finished. The thread will send a
5352 * message back to our main window when it terminates, and
5353 * that tells us it's OK to paste.
5355 DWORD in_threadid; /* required for Win9x */
5356 CreateThread(NULL, 0, clipboard_read_threadfunc,
5357 hwnd, 0, &in_threadid);
5360 void get_clip(void *frontend, wchar_t **p, int *len)
5363 *p = clipboard_contents;
5364 *len = clipboard_length;
5370 * Move `lines' lines from position `from' to position `to' in the
5373 void optimised_move(void *frontend, int to, int from, int lines)
5378 min = (to < from ? to : from);
5379 max = to + from - min;
5381 r.left = offset_width;
5382 r.right = offset_width + term->cols * font_width;
5383 r.top = offset_height + min * font_height;
5384 r.bottom = offset_height + (max + lines) * font_height;
5385 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
5390 * Print a message box and perform a fatal exit.
5392 void fatalbox(const char *fmt, ...)
5395 char *stuff, morestuff[100];
5398 stuff = dupvprintf(fmt, ap);
5400 sprintf(morestuff, "%.70s Fatal Error", appname);
5401 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5407 * Print a modal (Really Bad) message box and perform a fatal exit.
5409 void modalfatalbox(const char *fmt, ...)
5412 char *stuff, morestuff[100];
5415 stuff = dupvprintf(fmt, ap);
5417 sprintf(morestuff, "%.70s Fatal Error", appname);
5418 MessageBox(hwnd, stuff, morestuff,
5419 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
5425 * Print a message box and don't close the connection.
5427 void nonfatal(const char *fmt, ...)
5430 char *stuff, morestuff[100];
5433 stuff = dupvprintf(fmt, ap);
5435 sprintf(morestuff, "%.70s Error", appname);
5436 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5440 static BOOL flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout)
5442 if (p_FlashWindowEx) {
5444 fi.cbSize = sizeof(fi);
5446 fi.dwFlags = dwFlags;
5448 fi.dwTimeout = dwTimeout;
5449 return (*p_FlashWindowEx)(&fi);
5452 return FALSE; /* shrug */
5455 static void flash_window(int mode);
5456 static long next_flash;
5457 static int flashing = 0;
5460 * Timer for platforms where we must maintain window flashing manually
5463 static void flash_window_timer(void *ctx, unsigned long now)
5465 if (flashing && now == next_flash) {
5471 * Manage window caption / taskbar flashing, if enabled.
5472 * 0 = stop, 1 = maintain, 2 = start
5474 static void flash_window(int mode)
5476 int beep_ind = conf_get_int(conf, CONF_beep_ind);
5477 if ((mode == 0) || (beep_ind == B_IND_DISABLED)) {
5481 if (p_FlashWindowEx)
5482 flash_window_ex(FLASHW_STOP, 0, 0);
5484 FlashWindow(hwnd, FALSE);
5487 } else if (mode == 2) {
5491 if (p_FlashWindowEx) {
5492 /* For so-called "steady" mode, we use uCount=2, which
5493 * seems to be the traditional number of flashes used
5494 * by user notifications (e.g., by Explorer).
5495 * uCount=0 appears to enable continuous flashing, per
5496 * "flashing" mode, although I haven't seen this
5498 flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
5499 (beep_ind == B_IND_FLASH ? 0 : 2),
5500 0 /* system cursor blink rate */);
5501 /* No need to schedule timer */
5503 FlashWindow(hwnd, TRUE);
5504 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5508 } else if ((mode == 1) && (beep_ind == B_IND_FLASH)) {
5510 if (flashing && !p_FlashWindowEx) {
5511 FlashWindow(hwnd, TRUE); /* toggle */
5512 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5520 void do_beep(void *frontend, int mode)
5522 if (mode == BELL_DEFAULT) {
5524 * For MessageBeep style bells, we want to be careful of
5525 * timing, because they don't have the nice property of
5526 * PlaySound bells that each one cancels the previous
5527 * active one. So we limit the rate to one per 50ms or so.
5529 static long lastbeep = 0;
5532 beepdiff = GetTickCount() - lastbeep;
5533 if (beepdiff >= 0 && beepdiff < 50)
5537 * The above MessageBeep call takes time, so we record the
5538 * time _after_ it finishes rather than before it starts.
5540 lastbeep = GetTickCount();
5541 } else if (mode == BELL_WAVEFILE) {
5542 Filename *bell_wavefile = conf_get_filename(conf, CONF_bell_wavefile);
5543 if (!PlaySound(bell_wavefile->path, NULL,
5544 SND_ASYNC | SND_FILENAME)) {
5545 char buf[sizeof(bell_wavefile->path) + 80];
5547 sprintf(buf, "Unable to play sound file\n%s\n"
5548 "Using default sound instead", bell_wavefile->path);
5549 sprintf(otherbuf, "%.70s Sound Error", appname);
5550 MessageBox(hwnd, buf, otherbuf,
5551 MB_OK | MB_ICONEXCLAMATION);
5552 conf_set_int(conf, CONF_beep, BELL_DEFAULT);
5554 } else if (mode == BELL_PCSPEAKER) {
5555 static long lastbeep = 0;
5558 beepdiff = GetTickCount() - lastbeep;
5559 if (beepdiff >= 0 && beepdiff < 50)
5563 * We must beep in different ways depending on whether this
5564 * is a 95-series or NT-series OS.
5566 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
5570 lastbeep = GetTickCount();
5572 /* Otherwise, either visual bell or disabled; do nothing here */
5573 if (!term->has_focus) {
5574 flash_window(2); /* start */
5579 * Minimise or restore the window in response to a server-side
5582 void set_iconic(void *frontend, int iconic)
5584 if (IsIconic(hwnd)) {
5586 ShowWindow(hwnd, SW_RESTORE);
5589 ShowWindow(hwnd, SW_MINIMIZE);
5594 * Move the window in response to a server-side request.
5596 void move_window(void *frontend, int x, int y)
5598 int resize_action = conf_get_int(conf, CONF_resize_action);
5599 if (resize_action == RESIZE_DISABLED ||
5600 resize_action == RESIZE_FONT ||
5604 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5608 * Move the window to the top or bottom of the z-order in response
5609 * to a server-side request.
5611 void set_zorder(void *frontend, int top)
5613 if (conf_get_int(conf, CONF_alwaysontop))
5614 return; /* ignore */
5615 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5616 SWP_NOMOVE | SWP_NOSIZE);
5620 * Refresh the window in response to a server-side request.
5622 void refresh_window(void *frontend)
5624 InvalidateRect(hwnd, NULL, TRUE);
5628 * Maximise or restore the window in response to a server-side
5631 void set_zoomed(void *frontend, int zoomed)
5633 if (IsZoomed(hwnd)) {
5635 ShowWindow(hwnd, SW_RESTORE);
5638 ShowWindow(hwnd, SW_MAXIMIZE);
5643 * Report whether the window is iconic, for terminal reports.
5645 int is_iconic(void *frontend)
5647 return IsIconic(hwnd);
5651 * Report the window's position, for terminal reports.
5653 void get_window_pos(void *frontend, int *x, int *y)
5656 GetWindowRect(hwnd, &r);
5662 * Report the window's pixel size, for terminal reports.
5664 void get_window_pixels(void *frontend, int *x, int *y)
5667 GetWindowRect(hwnd, &r);
5668 *x = r.right - r.left;
5669 *y = r.bottom - r.top;
5673 * Return the window or icon title.
5675 char *get_window_title(void *frontend, int icon)
5677 return icon ? icon_name : window_name;
5681 * See if we're in full-screen mode.
5683 static int is_full_screen()
5685 if (!IsZoomed(hwnd))
5687 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
5692 /* Get the rect/size of a full screen window using the nearest available
5693 * monitor in multimon systems; default to something sensible if only
5694 * one monitor is present. */
5695 static int get_fullscreen_rect(RECT * ss)
5697 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
5700 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
5701 mi.cbSize = sizeof(mi);
5702 GetMonitorInfo(mon, &mi);
5704 /* structure copy */
5708 /* could also use code like this:
5709 ss->left = ss->top = 0;
5710 ss->right = GetSystemMetrics(SM_CXSCREEN);
5711 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5713 return GetClientRect(GetDesktopWindow(), ss);
5719 * Go full-screen. This should only be called when we are already
5722 static void make_full_screen()
5727 assert(IsZoomed(hwnd));
5729 if (is_full_screen())
5732 /* Remove the window furniture. */
5733 style = GetWindowLongPtr(hwnd, GWL_STYLE);
5734 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5735 if (conf_get_int(conf, CONF_scrollbar_in_fullscreen))
5736 style |= WS_VSCROLL;
5738 style &= ~WS_VSCROLL;
5739 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5741 /* Resize ourselves to exactly cover the nearest monitor. */
5742 get_fullscreen_rect(&ss);
5743 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5748 /* We may have changed size as a result */
5752 /* Tick the menu item in the System and context menus. */
5755 for (i = 0; i < lenof(popup_menus); i++)
5756 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED);
5761 * Clear the full-screen attributes.
5763 static void clear_full_screen()
5765 DWORD oldstyle, style;
5767 /* Reinstate the window furniture. */
5768 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
5769 style |= WS_CAPTION | WS_BORDER;
5770 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
5771 style &= ~WS_THICKFRAME;
5773 style |= WS_THICKFRAME;
5774 if (conf_get_int(conf, CONF_scrollbar))
5775 style |= WS_VSCROLL;
5777 style &= ~WS_VSCROLL;
5778 if (style != oldstyle) {
5779 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5780 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5781 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5785 /* Untick the menu item in the System and context menus. */
5788 for (i = 0; i < lenof(popup_menus); i++)
5789 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED);
5794 * Toggle full-screen mode.
5796 static void flip_full_screen()
5798 if (is_full_screen()) {
5799 ShowWindow(hwnd, SW_RESTORE);
5800 } else if (IsZoomed(hwnd)) {
5803 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5804 ShowWindow(hwnd, SW_MAXIMIZE);
5808 void frontend_keypress(void *handle)
5811 * Keypress termination in non-Close-On-Exit mode is not
5812 * currently supported in PuTTY proper, because the window
5813 * always has a perfectly good Close button anyway. So we do
5819 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5821 return term_data(term, is_stderr, data, len);
5824 int from_backend_untrusted(void *frontend, const char *data, int len)
5826 return term_data_untrusted(term, data, len);
5829 int from_backend_eof(void *frontend)
5831 return TRUE; /* do respond to incoming EOF with outgoing */
5834 int get_userpass_input(prompts_t *p, const unsigned char *in, int inlen)
5837 ret = cmdline_get_passwd_input(p, in, inlen);
5839 ret = term_get_userpass_input(term, p, in, inlen);
5843 void agent_schedule_callback(void (*callback)(void *, void *, int),
5844 void *callback_ctx, void *data, int len)
5846 struct agent_callback *c = snew(struct agent_callback);
5847 c->callback = callback;
5848 c->callback_ctx = callback_ctx;
5851 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);