7 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
15 #define COMPILE_MULTIMON_STUBS
25 /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
26 * wParam are used by Windows, and should be masked off, so we shouldn't
27 * attempt to store information in them. Hence all these identifiers have
28 * the low 4 bits clear. Also, identifiers should < 0xF000. */
30 #define IDM_SHOWLOG 0x0010
31 #define IDM_NEWSESS 0x0020
32 #define IDM_DUPSESS 0x0030
33 #define IDM_RESTART 0x0040
34 #define IDM_RECONF 0x0050
35 #define IDM_CLRSB 0x0060
36 #define IDM_RESET 0x0070
37 #define IDM_HELP 0x0140
38 #define IDM_ABOUT 0x0150
39 #define IDM_SAVEDSESS 0x0160
40 #define IDM_COPYALL 0x0170
41 #define IDM_FULLSCREEN 0x0180
42 #define IDM_PASTE 0x0190
43 #define IDM_SPECIALSEP 0x0200
45 #define IDM_SPECIAL_MIN 0x0400
46 #define IDM_SPECIAL_MAX 0x0800
48 #define IDM_SAVED_MIN 0x1000
49 #define IDM_SAVED_MAX 0x5000
50 #define MENU_SAVED_STEP 16
51 /* Maximum number of sessions on saved-session submenu */
52 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
54 #define WM_IGNORE_CLIP (WM_APP + 2)
55 #define WM_FULLSCR_ON_MAX (WM_APP + 3)
56 #define WM_AGENT_CALLBACK (WM_APP + 4)
58 /* Needed for Chinese support and apparently not always defined. */
60 #define VK_PROCESSKEY 0xE5
63 /* Mouse wheel support. */
65 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
68 #define WHEEL_DELTA 120
71 static Mouse_Button translate_button(Mouse_Button button);
72 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
73 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
74 unsigned char *output);
75 static void cfgtopalette(void);
76 static void systopalette(void);
77 static void init_palette(void);
78 static void init_fonts(int, int);
79 static void another_font(int);
80 static void deinit_fonts(void);
81 static void set_input_locale(HKL);
82 static void update_savedsess_menu(void);
84 static int is_full_screen(void);
85 static void make_full_screen(void);
86 static void clear_full_screen(void);
87 static void flip_full_screen(void);
89 /* Window layout information */
90 static void reset_window(int);
91 static int extra_width, extra_height;
92 static int font_width, font_height, font_dualwidth;
93 static int offset_width, offset_height;
94 static int was_zoomed = 0;
95 static int prev_rows, prev_cols;
97 static void enact_netevent(WPARAM, LPARAM);
98 static void flash_window(int mode);
99 static void sys_cursor_update(void);
100 static int is_shift_pressed(void);
101 static int get_fullscreen_rect(RECT * ss);
103 static int caret_x = -1, caret_y = -1;
105 static int kbd_codepage;
108 static Backend *back;
109 static void *backhandle;
111 static struct unicode_data ucsdata;
112 static int session_closed;
113 static int reconfiguring = FALSE;
115 static const struct telnet_special *specials = NULL;
116 static HMENU specials_menu = NULL;
117 static int n_specials = 0;
119 #define TIMING_TIMER_ID 1234
120 static long timing_next_time;
125 enum { SYSMENU, CTXMENU };
126 static HMENU savedsess_menu;
128 Config cfg; /* exported to windlg.c */
130 static struct sesslist sesslist; /* for saved-session menu */
132 struct agent_callback {
133 void (*callback)(void *, void *, int);
139 #define FONT_NORMAL 0
141 #define FONT_UNDERLINE 2
142 #define FONT_BOLDUND 3
143 #define FONT_WIDE 0x04
144 #define FONT_HIGH 0x08
145 #define FONT_NARROW 0x10
147 #define FONT_OEM 0x20
148 #define FONT_OEMBOLD 0x21
149 #define FONT_OEMUND 0x22
150 #define FONT_OEMBOLDUND 0x23
152 #define FONT_MAXNO 0x2F
154 static HFONT fonts[FONT_MAXNO];
155 static LOGFONT lfont;
156 static int fontflag[FONT_MAXNO];
158 BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT
165 #define NCFGCOLOURS 22
166 #define NEXTCOLOURS 240
167 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
168 static COLORREF colours[NALLCOLOURS];
170 static LPLOGPALETTE logpal;
171 static RGBTRIPLE defpal[NALLCOLOURS];
173 static HBITMAP caretbm;
175 static int dbltime, lasttime, lastact;
176 static Mouse_Button lastbtn;
178 /* this allows xterm-style mouse handling. */
179 static int send_raw_mouse = 0;
180 static int wheel_accumulator = 0;
182 static int busy_status = BUSY_NOT;
184 static char *window_name, *icon_name;
186 static int compose_state = 0;
188 static UINT wm_mousewheel = WM_MOUSEWHEEL;
190 /* Dummy routine, only required in plink. */
191 void ldisc_update(void *frontend, int echo, int edit)
195 char *get_ttymode(void *frontend, const char *mode)
197 return term_get_ttymode(term, mode);
200 static void start_backend(void)
203 char msg[1024], *title;
208 * Select protocol. This is farmed out into a table in a
209 * separate file to enable an ssh-free variant.
212 for (i = 0; backends[i].backend != NULL; i++)
213 if (backends[i].protocol == cfg.protocol) {
214 back = backends[i].backend;
218 char *str = dupprintf("%s Internal Error", appname);
219 MessageBox(NULL, "Unsupported protocol number found",
220 str, MB_OK | MB_ICONEXCLAMATION);
225 error = back->init(NULL, &backhandle, &cfg,
226 cfg.host, cfg.port, &realhost, cfg.tcp_nodelay,
228 back->provide_logctx(backhandle, logctx);
230 char *str = dupprintf("%s Error", appname);
231 sprintf(msg, "Unable to open connection to\n"
232 "%.800s\n" "%s", cfg.host, error);
233 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
237 window_name = icon_name = NULL;
239 title = cfg.wintitle;
241 sprintf(msg, "%s - %s", realhost, appname);
245 set_title(NULL, title);
246 set_icon(NULL, title);
249 * Connect the terminal to the backend for resize purposes.
251 term_provide_resize_fn(term, back->size, backhandle);
254 * Set up a line discipline.
256 ldisc = ldisc_create(&cfg, term, back, backhandle, NULL);
259 * Destroy the Restart Session menu item. (This will return
260 * failure if it's already absent, as it will be the very first
261 * time we call this function. We ignore that, because as long
262 * as the menu item ends up not being there, we don't care
263 * whether it was us who removed it or not!)
265 for (i = 0; i < lenof(popup_menus); i++) {
266 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
269 session_closed = FALSE;
272 static void close_session(void)
277 session_closed = TRUE;
278 sprintf(morestuff, "%.70s (inactive)", appname);
279 set_icon(NULL, morestuff);
280 set_title(NULL, morestuff);
287 back->free(backhandle);
290 update_specials_menu(NULL);
294 * Show the Restart Session menu item. Do a precautionary
295 * delete first to ensure we never end up with more than one.
297 for (i = 0; i < lenof(popup_menus); i++) {
298 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
299 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
300 IDM_RESTART, "&Restart Session");
304 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
308 int guess_width, guess_height;
312 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
316 InitCommonControls();
318 /* Ensure a Maximize setting in Explorer doesn't maximise the
324 char *str = dupprintf("%s Fatal Error", appname);
325 MessageBox(NULL, "Windows refuses to report a version",
326 str, MB_OK | MB_ICONEXCLAMATION);
332 * If we're running a version of Windows that doesn't support
333 * WM_MOUSEWHEEL, find out what message number we should be
336 if (osVersion.dwMajorVersion < 4 ||
337 (osVersion.dwMajorVersion == 4 &&
338 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
339 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
342 * See if we can find our Help file.
345 char b[2048], *p, *q, *r;
347 GetModuleFileName(NULL, b, sizeof(b) - 1);
349 p = strrchr(b, '\\');
350 if (p && p >= r) r = p+1;
352 if (q && q >= r) r = q+1;
353 strcpy(r, PUTTY_HELP_FILE);
354 if ( (fp = fopen(b, "r")) != NULL) {
355 help_path = dupstr(b);
359 strcpy(r, PUTTY_HELP_CONTENTS);
360 if ( (fp = fopen(b, "r")) != NULL) {
361 help_has_contents = TRUE;
364 help_has_contents = FALSE;
368 * Process the command line.
374 default_protocol = be_default_protocol;
375 /* Find the appropriate default port. */
378 default_port = 0; /* illegal */
379 for (i = 0; backends[i].backend != NULL; i++)
380 if (backends[i].protocol == default_protocol) {
381 default_port = backends[i].backend->default_port;
385 cfg.logtype = LGTYP_NONE;
387 do_defaults(NULL, &cfg);
392 * Process a couple of command-line options which are more
393 * easily dealt with before the line is broken up into
394 * words. These are the soon-to-be-defunct @sessionname and
395 * the internal-use-only &sharedmemoryhandle, neither of
396 * which are combined with anything else.
398 while (*p && isspace(*p))
402 while (i > 1 && isspace(p[i - 1]))
405 do_defaults(p + 1, &cfg);
406 if (!*cfg.host && !do_config()) {
409 } else if (*p == '&') {
411 * An initial & means we've been given a command line
412 * containing the hex value of a HANDLE for a file
413 * mapping object, which we must then extract as a
418 if (sscanf(p + 1, "%p", &filemap) == 1 &&
419 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
420 0, 0, sizeof(Config))) != NULL) {
423 CloseHandle(filemap);
424 } else if (!do_config()) {
429 * Otherwise, break up the command line and deal with
435 split_into_argv(cmdline, &argc, &argv, NULL);
437 for (i = 0; i < argc; i++) {
441 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
444 cmdline_error("option \"%s\" requires an argument", p);
445 } else if (ret == 2) {
446 i++; /* skip next argument */
447 } else if (ret == 1) {
448 continue; /* nothing further needs doing */
449 } else if (!strcmp(p, "-cleanup") ||
450 !strcmp(p, "-cleanup-during-uninstall")) {
452 * `putty -cleanup'. Remove all registry
453 * entries associated with PuTTY, and also find
454 * and delete the random seed file.
457 /* Are we being invoked from an uninstaller? */
458 if (!strcmp(p, "-cleanup-during-uninstall")) {
459 s1 = dupprintf("Remove saved sessions and random seed file?\n"
461 "If you hit Yes, ALL Registry entries associated\n"
462 "with %s will be removed, as well as the\n"
463 "random seed file. THIS PROCESS WILL\n"
464 "DESTROY YOUR SAVED SESSIONS.\n"
465 "(This only affects the currently logged-in user.)\n"
467 "If you hit No, uninstallation will proceed, but\n"
468 "saved sessions etc will be left on the machine.",
470 s2 = dupprintf("%s Uninstallation", appname);
472 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
473 "associated with %s, and will also remove\n"
474 "the random seed file. (This only affects the\n"
475 "currently logged-in user.)\n"
477 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
478 "Are you really sure you want to continue?",
480 s2 = dupprintf("%s Warning", appname);
482 if (message_box(s1, s2,
483 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
484 HELPCTXID(option_cleanup)) == IDYES) {
490 } else if (!strcmp(p, "-pgpfp")) {
493 } else if (*p != '-') {
497 * If we already have a host name, treat
498 * this argument as a port number. NB we
499 * have to treat this as a saved -P
500 * argument, so that it will be deferred
501 * until it's a good moment to run it.
503 int ret = cmdline_process_param("-P", p, 1, &cfg);
505 } else if (!strncmp(q, "telnet:", 7)) {
507 * If the hostname starts with "telnet:",
508 * set the protocol to Telnet and process
509 * the string as a Telnet URL.
514 if (q[0] == '/' && q[1] == '/')
516 cfg.protocol = PROT_TELNET;
518 while (*p && *p != ':' && *p != '/')
527 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
528 cfg.host[sizeof(cfg.host) - 1] = '\0';
532 * Otherwise, treat this argument as a host
535 while (*p && !isspace(*p))
539 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
540 cfg.host[sizeof(cfg.host) - 1] = '\0';
544 cmdline_error("unknown option \"%s\"", p);
549 cmdline_run_saved(&cfg);
551 if (!*cfg.host && !do_config()) {
556 * Trim leading whitespace off the hostname if it's there.
559 int space = strspn(cfg.host, " \t");
560 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
563 /* See if host is of the form user@host */
564 if (cfg.host[0] != '\0') {
565 char *atsign = strrchr(cfg.host, '@');
566 /* Make sure we're not overflowing the user field */
568 if (atsign - cfg.host < sizeof cfg.username) {
569 strncpy(cfg.username, cfg.host, atsign - cfg.host);
570 cfg.username[atsign - cfg.host] = '\0';
572 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
577 * Trim a colon suffix off the hostname if it's there. In
578 * order to protect IPv6 address literals against this
579 * treatment, we do not do this if there's _more_ than one
583 char *c = strchr(cfg.host, ':');
586 char *d = strchr(c+1, ':');
593 * Remove any remaining whitespace from the hostname.
597 while (cfg.host[p2] != '\0') {
598 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
599 cfg.host[p1] = cfg.host[p2];
608 /* Check for invalid Port number (i.e. zero) */
610 char *str = dupprintf("%s Internal Error", appname);
611 MessageBox(NULL, "Invalid Port Number",
612 str, MB_OK | MB_ICONEXCLAMATION);
619 wndclass.lpfnWndProc = WndProc;
620 wndclass.cbClsExtra = 0;
621 wndclass.cbWndExtra = 0;
622 wndclass.hInstance = inst;
623 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
624 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
625 wndclass.hbrBackground = NULL;
626 wndclass.lpszMenuName = NULL;
627 wndclass.lpszClassName = appname;
629 RegisterClass(&wndclass);
632 memset(&ucsdata, 0, sizeof(ucsdata));
637 * Guess some defaults for the window size. This all gets
638 * updated later, so we don't really care too much. However, we
639 * do want the font width/height guesses to correspond to a
640 * large font rather than a small one...
647 guess_width = extra_width + font_width * cfg.width;
648 guess_height = extra_height + font_height * cfg.height;
651 get_fullscreen_rect(&r);
652 if (guess_width > r.right - r.left)
653 guess_width = r.right - r.left;
654 if (guess_height > r.bottom - r.top)
655 guess_height = r.bottom - r.top;
659 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
662 winmode &= ~(WS_VSCROLL);
663 if (cfg.resize_action == RESIZE_DISABLED)
664 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
666 exwinmode |= WS_EX_TOPMOST;
668 exwinmode |= WS_EX_CLIENTEDGE;
669 hwnd = CreateWindowEx(exwinmode, appname, appname,
670 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
671 guess_width, guess_height,
672 NULL, NULL, inst, NULL);
676 * Initialise the terminal. (We have to do this _after_
677 * creating the window, since the terminal is the first thing
678 * which will call schedule_timer(), which will in turn call
679 * timer_change_notify() which will expect hwnd to exist.)
681 term = term_init(&cfg, &ucsdata, NULL);
682 logctx = log_init(NULL, &cfg);
683 term_provide_logctx(term, logctx);
684 term_size(term, cfg.height, cfg.width, cfg.savelines);
687 * Initialise the fonts, simultaneously correcting the guesses
688 * for font_{width,height}.
693 * Correct the guesses for extra_{width,height}.
697 GetWindowRect(hwnd, &wr);
698 GetClientRect(hwnd, &cr);
699 offset_width = offset_height = cfg.window_border;
700 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
701 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
705 * Resize the window, now we know what size we _really_ want it
708 guess_width = extra_width + font_width * term->cols;
709 guess_height = extra_height + font_height * term->rows;
710 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
711 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
714 * Set up a caret bitmap, with no content.
718 int size = (font_width + 15) / 16 * 2 * font_height;
719 bits = snewn(size, char);
720 memset(bits, 0, size);
721 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
724 CreateCaret(hwnd, caretbm, font_width, font_height);
727 * Initialise the scroll bar.
732 si.cbSize = sizeof(si);
733 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
735 si.nMax = term->rows - 1;
736 si.nPage = term->rows;
738 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
742 * Prepare the mouse handler.
744 lastact = MA_NOTHING;
745 lastbtn = MBT_NOTHING;
746 dbltime = GetDoubleClickTime();
749 * Set up the session-control options on the system menu.
756 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
757 popup_menus[CTXMENU].menu = CreatePopupMenu();
758 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
760 savedsess_menu = CreateMenu();
761 get_sesslist(&sesslist, TRUE);
762 update_savedsess_menu();
764 for (j = 0; j < lenof(popup_menus); j++) {
765 m = popup_menus[j].menu;
767 AppendMenu(m, MF_SEPARATOR, 0, 0);
768 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
769 AppendMenu(m, MF_SEPARATOR, 0, 0);
770 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
771 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
772 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) savedsess_menu,
774 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
775 AppendMenu(m, MF_SEPARATOR, 0, 0);
776 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
777 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
778 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
779 AppendMenu(m, MF_SEPARATOR, 0, 0);
780 AppendMenu(m, (cfg.resize_action == RESIZE_DISABLED) ?
781 MF_GRAYED : MF_ENABLED, IDM_FULLSCREEN, "&Full Screen");
782 AppendMenu(m, MF_SEPARATOR, 0, 0);
784 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
785 str = dupprintf("&About %s", appname);
786 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
794 * Set up the initial input locale.
796 set_input_locale(GetKeyboardLayout(0));
799 * Finally show the window!
801 ShowWindow(hwnd, show);
802 SetForegroundWindow(hwnd);
805 * Set the palette up.
811 term_set_focus(term, GetForegroundWindow() == hwnd);
814 if (GetMessage(&msg, NULL, 0, 0) == 1) {
815 while (msg.message != WM_QUIT) {
816 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
817 DispatchMessage(&msg);
818 /* Send the paste buffer if there's anything to send */
820 /* If there's nothing new in the queue then we can do everything
821 * we've delayed, reading the socket, writing, and repainting
824 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
827 /* The messages seem unreliable; especially if we're being tricky */
828 term_set_focus(term, GetForegroundWindow() == hwnd);
830 net_pending_errors();
832 /* There's no point rescanning everything in the message queue
833 * so we do an apparently unnecessary wait here
836 if (GetMessage(&msg, NULL, 0, 0) != 1)
841 cleanup_exit(msg.wParam); /* this doesn't return... */
842 return msg.wParam; /* ... but optimiser doesn't know */
848 void cleanup_exit(int code)
859 if (cfg.protocol == PROT_SSH) {
870 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
872 char *do_select(SOCKET skt, int startup)
877 events = (FD_CONNECT | FD_READ | FD_WRITE |
878 FD_OOB | FD_CLOSE | FD_ACCEPT);
883 return "do_select(): internal error (hwnd==NULL)";
884 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
885 switch (p_WSAGetLastError()) {
887 return "Network is down";
889 return "WSAAsyncSelect(): unknown error";
896 * Refresh the saved-session submenu from `sesslist'.
898 static void update_savedsess_menu(void)
901 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
902 /* skip sesslist.sessions[0] == Default Settings */
904 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
907 AppendMenu(savedsess_menu, MF_ENABLED,
908 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
909 sesslist.sessions[i]);
913 * Update the Special Commands submenu.
915 void update_specials_menu(void *frontend)
921 specials = back->get_specials(backhandle);
926 /* We can't use Windows to provide a stack for submenus, so
927 * here's a lame "stack" that will do for now. */
928 HMENU saved_menu = NULL;
930 new_menu = CreatePopupMenu();
931 for (i = 0; nesting > 0; i++) {
932 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
933 switch (specials[i].code) {
935 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
940 saved_menu = new_menu; /* XXX lame stacking */
941 new_menu = CreatePopupMenu();
942 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
943 (UINT) new_menu, specials[i].name);
948 new_menu = saved_menu; /* XXX lame stacking */
953 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
958 /* Squirrel the highest special. */
965 for (j = 0; j < lenof(popup_menus); j++) {
967 /* XXX does this free up all submenus? */
968 DeleteMenu(popup_menus[j].menu, specials_menu, MF_BYCOMMAND);
969 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
972 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
973 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
974 (UINT) new_menu, "S&pecial Command");
975 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
976 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
979 specials_menu = new_menu;
982 static void update_mouse_pointer(void)
985 int force_visible = FALSE;
986 static int forced_visible = FALSE;
987 switch (busy_status) {
990 curstype = IDC_ARROW;
992 curstype = IDC_IBEAM;
995 curstype = IDC_APPSTARTING; /* this may be an abuse */
996 force_visible = TRUE;
1000 force_visible = TRUE;
1006 HCURSOR cursor = LoadCursor(NULL, curstype);
1007 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1008 SetCursor(cursor); /* force redraw of cursor at current posn */
1010 if (force_visible != forced_visible) {
1011 /* We want some cursor shapes to be visible always.
1012 * Along with show_mouseptr(), this manages the ShowCursor()
1013 * counter such that if we switch back to a non-force_visible
1014 * cursor, the previous visibility state is restored. */
1015 ShowCursor(force_visible);
1016 forced_visible = force_visible;
1020 void set_busy_status(void *frontend, int status)
1022 busy_status = status;
1023 update_mouse_pointer();
1027 * set or clear the "raw mouse message" mode
1029 void set_raw_mouse_mode(void *frontend, int activate)
1031 activate = activate && !cfg.no_mouse_rep;
1032 send_raw_mouse = activate;
1033 update_mouse_pointer();
1037 * Print a message box and close the connection.
1039 void connection_fatal(void *frontend, char *fmt, ...)
1042 char *stuff, morestuff[100];
1045 stuff = dupvprintf(fmt, ap);
1047 sprintf(morestuff, "%.70s Fatal Error", appname);
1048 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1051 if (cfg.close_on_exit == FORCE_ON)
1059 * Report an error at the command-line parsing stage.
1061 void cmdline_error(char *fmt, ...)
1064 char *stuff, morestuff[100];
1067 stuff = dupvprintf(fmt, ap);
1069 sprintf(morestuff, "%.70s Command Line Error", appname);
1070 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1076 * Actually do the job requested by a WM_NETEVENT
1078 static void enact_netevent(WPARAM wParam, LPARAM lParam)
1080 static int reentering = 0;
1081 extern int select_result(WPARAM, LPARAM);
1085 return; /* don't unpend the pending */
1088 ret = select_result(wParam, lParam);
1091 if (ret == 0 && !session_closed) {
1092 /* Abnormal exits will already have set session_closed and taken
1093 * appropriate action. */
1094 if (cfg.close_on_exit == FORCE_ON ||
1095 cfg.close_on_exit == AUTO) PostQuitMessage(0);
1098 session_closed = TRUE;
1099 MessageBox(hwnd, "Connection closed by remote host",
1100 appname, MB_OK | MB_ICONINFORMATION);
1106 * Copy the colour palette from the configuration data into defpal.
1107 * This is non-trivial because the colour indices are different.
1109 static void cfgtopalette(void)
1112 static const int ww[] = {
1113 256, 257, 258, 259, 260, 261,
1114 0, 8, 1, 9, 2, 10, 3, 11,
1115 4, 12, 5, 13, 6, 14, 7, 15
1118 for (i = 0; i < 22; i++) {
1120 defpal[w].rgbtRed = cfg.colours[i][0];
1121 defpal[w].rgbtGreen = cfg.colours[i][1];
1122 defpal[w].rgbtBlue = cfg.colours[i][2];
1124 for (i = 0; i < NEXTCOLOURS; i++) {
1126 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1127 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1128 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1129 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
1131 int shade = i - 216;
1132 shade = shade * 10 + 8;
1133 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1134 defpal[i+16].rgbtBlue = shade;
1138 /* Override with system colours if appropriate */
1139 if (cfg.system_colour)
1144 * Override bit of defpal with colours from the system.
1145 * (NB that this takes a copy the system colours at the time this is called,
1146 * so subsequent colour scheme changes don't take effect. To fix that we'd
1147 * probably want to be using GetSysColorBrush() and the like.)
1149 static void systopalette(void)
1152 static const struct { int nIndex; int norm; int bold; } or[] =
1154 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1155 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1156 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1157 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1160 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1161 COLORREF colour = GetSysColor(or[i].nIndex);
1162 defpal[or[i].norm].rgbtRed =
1163 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1164 defpal[or[i].norm].rgbtGreen =
1165 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1166 defpal[or[i].norm].rgbtBlue =
1167 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1172 * Set up the colour palette.
1174 static void init_palette(void)
1177 HDC hdc = GetDC(hwnd);
1179 if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1181 * This is a genuine case where we must use smalloc
1182 * because the snew macros can't cope.
1184 logpal = smalloc(sizeof(*logpal)
1185 - sizeof(logpal->palPalEntry)
1186 + NALLCOLOURS * sizeof(PALETTEENTRY));
1187 logpal->palVersion = 0x300;
1188 logpal->palNumEntries = NALLCOLOURS;
1189 for (i = 0; i < NALLCOLOURS; i++) {
1190 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1191 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1192 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1193 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1195 pal = CreatePalette(logpal);
1197 SelectPalette(hdc, pal, FALSE);
1198 RealizePalette(hdc);
1199 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1202 ReleaseDC(hwnd, hdc);
1205 for (i = 0; i < NALLCOLOURS; i++)
1206 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1207 defpal[i].rgbtGreen,
1208 defpal[i].rgbtBlue);
1210 for (i = 0; i < NALLCOLOURS; i++)
1211 colours[i] = RGB(defpal[i].rgbtRed,
1212 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1216 * This is a wrapper to ExtTextOut() to force Windows to display
1217 * the precise glyphs we give it. Otherwise it would do its own
1218 * bidi and Arabic shaping, and we would end up uncertain which
1219 * characters it had put where.
1221 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1222 unsigned short *lpString, UINT cbCount,
1223 CONST INT *lpDx, int opaque)
1227 * The LCC include files apparently don't supply the
1228 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1229 * proper: the differences aren't important to us (the only
1230 * variable-width string parameter is one we don't use anyway).
1236 char *buffer = snewn(cbCount*2+2, char);
1237 char *classbuffer = snewn(cbCount, char);
1238 memset(&gcpr, 0, sizeof(gcpr));
1239 memset(buffer, 0, cbCount*2+2);
1240 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1242 gcpr.lStructSize = sizeof(gcpr);
1243 gcpr.lpGlyphs = (void *)buffer;
1244 gcpr.lpClass = classbuffer;
1245 gcpr.nGlyphs = cbCount;
1247 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1248 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1250 ExtTextOut(hdc, x, y,
1251 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1252 lprc, buffer, cbCount, lpDx);
1256 * Initialise all the fonts we will need initially. There may be as many as
1257 * three or as few as one. The other (poentially) twentyone fonts are done
1258 * if/when they are needed.
1262 * - check the font width and height, correcting our guesses if
1265 * - verify that the bold font is the same width as the ordinary
1266 * one, and engage shadow bolding if not.
1268 * - verify that the underlined font is the same width as the
1269 * ordinary one (manual underlining by means of line drawing can
1270 * be done in a pinch).
1272 static void init_fonts(int pick_width, int pick_height)
1279 int fw_dontcare, fw_bold;
1281 for (i = 0; i < FONT_MAXNO; i++)
1284 bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
1285 und_mode = UND_FONT;
1287 if (cfg.font.isbold) {
1288 fw_dontcare = FW_BOLD;
1291 fw_dontcare = FW_DONTCARE;
1298 font_height = pick_height;
1300 font_height = cfg.font.height;
1301 if (font_height > 0) {
1303 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1306 font_width = pick_width;
1308 #define f(i,c,w,u) \
1309 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1310 c, OUT_DEFAULT_PRECIS, \
1311 CLIP_DEFAULT_PRECIS, FONT_QUALITY(cfg.font_quality), \
1312 FIXED_PITCH | FF_DONTCARE, cfg.font.name)
1314 f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);
1316 SelectObject(hdc, fonts[FONT_NORMAL]);
1317 GetTextMetrics(hdc, &tm);
1319 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1321 if (pick_width == 0 || pick_height == 0) {
1322 font_height = tm.tmHeight;
1323 font_width = tm.tmAveCharWidth;
1325 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1327 #ifdef RDB_DEBUG_PATCH
1328 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1329 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1334 DWORD cset = tm.tmCharSet;
1335 memset(&info, 0xFF, sizeof(info));
1337 /* !!! Yes the next line is right */
1338 if (cset == OEM_CHARSET)
1339 ucsdata.font_codepage = GetOEMCP();
1341 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1342 ucsdata.font_codepage = info.ciACP;
1344 ucsdata.font_codepage = -1;
1346 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1347 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1350 f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);
1353 * Some fonts, e.g. 9-pt Courier, draw their underlines
1354 * outside their character cell. We successfully prevent
1355 * screen corruption by clipping the text output, but then
1356 * we lose the underline completely. Here we try to work
1357 * out whether this is such a font, and if it is, we set a
1358 * flag that causes underlines to be drawn by hand.
1360 * Having tried other more sophisticated approaches (such
1361 * as examining the TEXTMETRIC structure or requesting the
1362 * height of a string), I think we'll do this the brute
1363 * force way: we create a small bitmap, draw an underlined
1364 * space on it, and test to see whether any pixels are
1365 * foreground-coloured. (Since we expect the underline to
1366 * go all the way across the character cell, we only search
1367 * down a single column of the bitmap, half way across.)
1371 HBITMAP und_bm, und_oldbm;
1375 und_dc = CreateCompatibleDC(hdc);
1376 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1377 und_oldbm = SelectObject(und_dc, und_bm);
1378 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1379 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1380 SetTextColor(und_dc, RGB(255, 255, 255));
1381 SetBkColor(und_dc, RGB(0, 0, 0));
1382 SetBkMode(und_dc, OPAQUE);
1383 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1385 for (i = 0; i < font_height; i++) {
1386 c = GetPixel(und_dc, font_width / 2, i);
1387 if (c != RGB(0, 0, 0))
1390 SelectObject(und_dc, und_oldbm);
1391 DeleteObject(und_bm);
1394 und_mode = UND_LINE;
1395 DeleteObject(fonts[FONT_UNDERLINE]);
1396 fonts[FONT_UNDERLINE] = 0;
1400 if (bold_mode == BOLD_FONT) {
1401 f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);
1405 descent = tm.tmAscent + 1;
1406 if (descent >= font_height)
1407 descent = font_height - 1;
1409 for (i = 0; i < 3; i++) {
1411 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1412 fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
1419 ReleaseDC(hwnd, hdc);
1421 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1422 und_mode = UND_LINE;
1423 DeleteObject(fonts[FONT_UNDERLINE]);
1424 fonts[FONT_UNDERLINE] = 0;
1427 if (bold_mode == BOLD_FONT &&
1428 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1429 bold_mode = BOLD_SHADOW;
1430 DeleteObject(fonts[FONT_BOLD]);
1431 fonts[FONT_BOLD] = 0;
1433 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1435 init_ucs(&cfg, &ucsdata);
1438 static void another_font(int fontno)
1441 int fw_dontcare, fw_bold;
1445 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1448 basefont = (fontno & ~(FONT_BOLDUND));
1449 if (basefont != fontno && !fontflag[basefont])
1450 another_font(basefont);
1452 if (cfg.font.isbold) {
1453 fw_dontcare = FW_BOLD;
1456 fw_dontcare = FW_DONTCARE;
1460 c = cfg.font.charset;
1466 if (fontno & FONT_WIDE)
1468 if (fontno & FONT_NARROW)
1470 if (fontno & FONT_OEM)
1472 if (fontno & FONT_BOLD)
1474 if (fontno & FONT_UNDERLINE)
1478 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1479 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1480 CLIP_DEFAULT_PRECIS, FONT_QUALITY(cfg.font_quality),
1481 FIXED_PITCH | FF_DONTCARE, s);
1483 fontflag[fontno] = 1;
1486 static void deinit_fonts(void)
1489 for (i = 0; i < FONT_MAXNO; i++) {
1491 DeleteObject(fonts[i]);
1497 void request_resize(void *frontend, int w, int h)
1501 /* If the window is maximized supress resizing attempts */
1502 if (IsZoomed(hwnd)) {
1503 if (cfg.resize_action == RESIZE_TERM)
1507 if (cfg.resize_action == RESIZE_DISABLED) return;
1508 if (h == term->rows && w == term->cols) return;
1510 /* Sanity checks ... */
1512 static int first_time = 1;
1515 switch (first_time) {
1517 /* Get the size of the screen */
1518 if (get_fullscreen_rect(&ss))
1519 /* first_time = 0 */ ;
1525 /* Make sure the values are sane */
1526 width = (ss.right - ss.left - extra_width) / 4;
1527 height = (ss.bottom - ss.top - extra_height) / 6;
1529 if (w > width || h > height)
1538 term_size(term, h, w, cfg.savelines);
1540 if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {
1541 width = extra_width + font_width * w;
1542 height = extra_height + font_height * h;
1544 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1545 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1546 SWP_NOMOVE | SWP_NOZORDER);
1550 InvalidateRect(hwnd, NULL, TRUE);
1553 static void reset_window(int reinit) {
1555 * This function decides how to resize or redraw when the
1556 * user changes something.
1558 * This function doesn't like to change the terminal size but if the
1559 * font size is locked that may be it's only soluion.
1561 int win_width, win_height;
1564 #ifdef RDB_DEBUG_PATCH
1565 debug((27, "reset_window()"));
1568 /* Current window sizes ... */
1569 GetWindowRect(hwnd, &wr);
1570 GetClientRect(hwnd, &cr);
1572 win_width = cr.right - cr.left;
1573 win_height = cr.bottom - cr.top;
1575 if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;
1577 /* Are we being forced to reload the fonts ? */
1579 #ifdef RDB_DEBUG_PATCH
1580 debug((27, "reset_window() -- Forced deinit"));
1586 /* Oh, looks like we're minimised */
1587 if (win_width == 0 || win_height == 0)
1590 /* Is the window out of position ? */
1592 (offset_width != (win_width-font_width*term->cols)/2 ||
1593 offset_height != (win_height-font_height*term->rows)/2) ){
1594 offset_width = (win_width-font_width*term->cols)/2;
1595 offset_height = (win_height-font_height*term->rows)/2;
1596 InvalidateRect(hwnd, NULL, TRUE);
1597 #ifdef RDB_DEBUG_PATCH
1598 debug((27, "reset_window() -> Reposition terminal"));
1602 if (IsZoomed(hwnd)) {
1603 /* We're fullscreen, this means we must not change the size of
1604 * the window so it's the font size or the terminal itself.
1607 extra_width = wr.right - wr.left - cr.right + cr.left;
1608 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1610 if (cfg.resize_action != RESIZE_TERM) {
1611 if ( font_width != win_width/term->cols ||
1612 font_height != win_height/term->rows) {
1614 init_fonts(win_width/term->cols, win_height/term->rows);
1615 offset_width = (win_width-font_width*term->cols)/2;
1616 offset_height = (win_height-font_height*term->rows)/2;
1617 InvalidateRect(hwnd, NULL, TRUE);
1618 #ifdef RDB_DEBUG_PATCH
1619 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1620 font_width, font_height));
1624 if ( font_width != win_width/term->cols ||
1625 font_height != win_height/term->rows) {
1626 /* Our only choice at this point is to change the
1627 * size of the terminal; Oh well.
1629 term_size(term, win_height/font_height, win_width/font_width,
1631 offset_width = (win_width-font_width*term->cols)/2;
1632 offset_height = (win_height-font_height*term->rows)/2;
1633 InvalidateRect(hwnd, NULL, TRUE);
1634 #ifdef RDB_DEBUG_PATCH
1635 debug((27, "reset_window() -> Zoomed term_size"));
1642 /* Hmm, a force re-init means we should ignore the current window
1643 * so we resize to the default font size.
1646 #ifdef RDB_DEBUG_PATCH
1647 debug((27, "reset_window() -> Forced re-init"));
1650 offset_width = offset_height = cfg.window_border;
1651 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1652 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1654 if (win_width != font_width*term->cols + offset_width*2 ||
1655 win_height != font_height*term->rows + offset_height*2) {
1657 /* If this is too large windows will resize it to the maximum
1658 * allowed window size, we will then be back in here and resize
1659 * the font or terminal to fit.
1661 SetWindowPos(hwnd, NULL, 0, 0,
1662 font_width*term->cols + extra_width,
1663 font_height*term->rows + extra_height,
1664 SWP_NOMOVE | SWP_NOZORDER);
1667 InvalidateRect(hwnd, NULL, TRUE);
1671 /* Okay the user doesn't want us to change the font so we try the
1672 * window. But that may be too big for the screen which forces us
1673 * to change the terminal.
1675 if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||
1676 (cfg.resize_action == RESIZE_EITHER && reinit<0) ||
1678 offset_width = offset_height = cfg.window_border;
1679 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1680 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1682 if (win_width != font_width*term->cols + offset_width*2 ||
1683 win_height != font_height*term->rows + offset_height*2) {
1688 get_fullscreen_rect(&ss);
1690 width = (ss.right - ss.left - extra_width) / font_width;
1691 height = (ss.bottom - ss.top - extra_height) / font_height;
1694 if ( term->rows > height || term->cols > width ) {
1695 if (cfg.resize_action == RESIZE_EITHER) {
1696 /* Make the font the biggest we can */
1697 if (term->cols > width)
1698 font_width = (ss.right - ss.left - extra_width)
1700 if (term->rows > height)
1701 font_height = (ss.bottom - ss.top - extra_height)
1705 init_fonts(font_width, font_height);
1707 width = (ss.right - ss.left - extra_width) / font_width;
1708 height = (ss.bottom - ss.top - extra_height) / font_height;
1710 if ( height > term->rows ) height = term->rows;
1711 if ( width > term->cols ) width = term->cols;
1712 term_size(term, height, width, cfg.savelines);
1713 #ifdef RDB_DEBUG_PATCH
1714 debug((27, "reset_window() -> term resize to (%d,%d)",
1720 SetWindowPos(hwnd, NULL, 0, 0,
1721 font_width*term->cols + extra_width,
1722 font_height*term->rows + extra_height,
1723 SWP_NOMOVE | SWP_NOZORDER);
1725 InvalidateRect(hwnd, NULL, TRUE);
1726 #ifdef RDB_DEBUG_PATCH
1727 debug((27, "reset_window() -> window resize to (%d,%d)",
1728 font_width*term->cols + extra_width,
1729 font_height*term->rows + extra_height));
1735 /* We're allowed to or must change the font but do we want to ? */
1737 if (font_width != (win_width-cfg.window_border*2)/term->cols ||
1738 font_height != (win_height-cfg.window_border*2)/term->rows) {
1741 init_fonts((win_width-cfg.window_border*2)/term->cols,
1742 (win_height-cfg.window_border*2)/term->rows);
1743 offset_width = (win_width-font_width*term->cols)/2;
1744 offset_height = (win_height-font_height*term->rows)/2;
1746 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1747 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1749 InvalidateRect(hwnd, NULL, TRUE);
1750 #ifdef RDB_DEBUG_PATCH
1751 debug((25, "reset_window() -> font resize to (%d,%d)",
1752 font_width, font_height));
1757 static void set_input_locale(HKL kl)
1761 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1762 lbuf, sizeof(lbuf));
1764 kbd_codepage = atoi(lbuf);
1767 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1769 int thistime = GetMessageTime();
1771 if (send_raw_mouse && !(cfg.mouse_override && shift)) {
1772 lastbtn = MBT_NOTHING;
1773 term_mouse(term, b, translate_button(b), MA_CLICK,
1774 x, y, shift, ctrl, alt);
1778 if (lastbtn == b && thistime - lasttime < dbltime) {
1779 lastact = (lastact == MA_CLICK ? MA_2CLK :
1780 lastact == MA_2CLK ? MA_3CLK :
1781 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1786 if (lastact != MA_NOTHING)
1787 term_mouse(term, b, translate_button(b), lastact,
1788 x, y, shift, ctrl, alt);
1789 lasttime = thistime;
1793 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1794 * into a cooked one (SELECT, EXTEND, PASTE).
1796 static Mouse_Button translate_button(Mouse_Button button)
1798 if (button == MBT_LEFT)
1800 if (button == MBT_MIDDLE)
1801 return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
1802 if (button == MBT_RIGHT)
1803 return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
1804 return 0; /* shouldn't happen */
1807 static void show_mouseptr(int show)
1809 /* NB that the counter in ShowCursor() is also frobbed by
1810 * update_mouse_pointer() */
1811 static int cursor_visible = 1;
1812 if (!cfg.hide_mouseptr) /* override if this feature disabled */
1814 if (cursor_visible && !show)
1816 else if (!cursor_visible && show)
1818 cursor_visible = show;
1821 static int is_alt_pressed(void)
1824 int r = GetKeyboardState(keystate);
1827 if (keystate[VK_MENU] & 0x80)
1829 if (keystate[VK_RMENU] & 0x80)
1834 static int is_shift_pressed(void)
1837 int r = GetKeyboardState(keystate);
1840 if (keystate[VK_SHIFT] & 0x80)
1845 static int resizing;
1847 void notify_remote_exit(void *fe) { /* stub not needed in this frontend */ }
1849 void timer_change_notify(long next)
1851 long ticks = next - GETTICKCOUNT();
1852 if (ticks <= 0) ticks = 1; /* just in case */
1853 KillTimer(hwnd, TIMING_TIMER_ID);
1854 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
1855 timing_next_time = next;
1858 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1859 WPARAM wParam, LPARAM lParam)
1862 static int ignore_clip = FALSE;
1863 static int need_backend_resize = FALSE;
1864 static int fullscr_on_max = FALSE;
1865 static UINT last_mousemove = 0;
1869 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
1872 KillTimer(hwnd, TIMING_TIMER_ID);
1873 if (run_timers(timing_next_time, &next)) {
1874 timer_change_notify(next);
1885 str = dupprintf("%s Exit Confirmation", appname);
1886 if (!cfg.warn_on_close || session_closed ||
1888 "Are you sure you want to close this session?",
1889 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
1891 DestroyWindow(hwnd);
1899 case WM_INITMENUPOPUP:
1900 if ((HMENU)wParam == savedsess_menu) {
1901 /* About to pop up Saved Sessions sub-menu.
1902 * Refresh the session list. */
1903 get_sesslist(&sesslist, FALSE); /* free */
1904 get_sesslist(&sesslist, TRUE);
1905 update_savedsess_menu();
1911 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
1922 BOOL inherit_handles;
1924 PROCESS_INFORMATION pi;
1925 HANDLE filemap = NULL;
1927 if (wParam == IDM_DUPSESS) {
1929 * Allocate a file-mapping memory chunk for the
1932 SECURITY_ATTRIBUTES sa;
1935 sa.nLength = sizeof(sa);
1936 sa.lpSecurityDescriptor = NULL;
1937 sa.bInheritHandle = TRUE;
1938 filemap = CreateFileMapping((HANDLE) 0xFFFFFFFF,
1941 0, sizeof(Config), NULL);
1943 p = (Config *) MapViewOfFile(filemap,
1945 0, 0, sizeof(Config));
1947 *p = cfg; /* structure copy */
1951 inherit_handles = TRUE;
1952 sprintf(c, "putty &%p", filemap);
1954 } else if (wParam == IDM_SAVEDSESS) {
1955 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
1956 / MENU_SAVED_STEP) + 1;
1957 if (sessno < sesslist.nsessions) {
1958 char *session = sesslist.sessions[sessno];
1959 /* XXX spaces? quotes? "-load"? */
1960 cl = dupprintf("putty @%s", session);
1961 inherit_handles = FALSE;
1965 } else /* IDM_NEWSESS */ {
1967 inherit_handles = FALSE;
1970 GetModuleFileName(NULL, b, sizeof(b) - 1);
1972 si.lpReserved = NULL;
1973 si.lpDesktop = NULL;
1977 si.lpReserved2 = NULL;
1978 CreateProcess(b, cl, NULL, NULL, inherit_handles,
1979 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
1982 CloseHandle(filemap);
1989 logevent(NULL, "----- Session restarted -----");
1998 int reconfig_result;
2003 reconfiguring = TRUE;
2005 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
2009 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2010 reconfiguring = FALSE;
2011 if (!reconfig_result)
2015 /* Disable full-screen if resizing forbidden */
2016 HMENU m = GetSystemMenu (hwnd, FALSE);
2017 EnableMenuItem(m, IDM_FULLSCREEN, MF_BYCOMMAND |
2018 (cfg.resize_action == RESIZE_DISABLED)
2019 ? MF_GRAYED : MF_ENABLED);
2020 /* Gracefully unzoom if necessary */
2021 if (IsZoomed(hwnd) &&
2022 (cfg.resize_action == RESIZE_DISABLED)) {
2023 ShowWindow(hwnd, SW_RESTORE);
2027 /* Pass new config data to the logging module */
2028 log_reconfig(logctx, &cfg);
2032 * Flush the line discipline's edit buffer in the
2033 * case where local editing has just been disabled.
2036 ldisc_send(ldisc, NULL, 0, 0);
2044 /* Pass new config data to the terminal */
2045 term_reconfig(term, &cfg);
2047 /* Pass new config data to the back end */
2049 back->reconfig(backhandle, &cfg);
2051 /* Screen size changed ? */
2052 if (cfg.height != prev_cfg.height ||
2053 cfg.width != prev_cfg.width ||
2054 cfg.savelines != prev_cfg.savelines ||
2055 cfg.resize_action == RESIZE_FONT ||
2056 (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2057 cfg.resize_action == RESIZE_DISABLED)
2058 term_size(term, cfg.height, cfg.width, cfg.savelines);
2060 /* Enable or disable the scroll bar, etc */
2062 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2063 LONG nexflag, exflag =
2064 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2067 if (cfg.alwaysontop != prev_cfg.alwaysontop) {
2068 if (cfg.alwaysontop) {
2069 nexflag |= WS_EX_TOPMOST;
2070 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2071 SWP_NOMOVE | SWP_NOSIZE);
2073 nexflag &= ~(WS_EX_TOPMOST);
2074 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2075 SWP_NOMOVE | SWP_NOSIZE);
2078 if (cfg.sunken_edge)
2079 nexflag |= WS_EX_CLIENTEDGE;
2081 nexflag &= ~(WS_EX_CLIENTEDGE);
2084 if (is_full_screen() ?
2085 cfg.scrollbar_in_fullscreen : cfg.scrollbar)
2088 nflg &= ~WS_VSCROLL;
2090 if (cfg.resize_action == RESIZE_DISABLED ||
2092 nflg &= ~WS_THICKFRAME;
2094 nflg |= WS_THICKFRAME;
2096 if (cfg.resize_action == RESIZE_DISABLED)
2097 nflg &= ~WS_MAXIMIZEBOX;
2099 nflg |= WS_MAXIMIZEBOX;
2101 if (nflg != flag || nexflag != exflag) {
2103 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2104 if (nexflag != exflag)
2105 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2107 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2108 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2109 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2117 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2122 set_title(NULL, cfg.wintitle);
2123 if (IsIconic(hwnd)) {
2125 cfg.win_name_always ? window_name :
2129 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
2130 strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
2131 cfg.font.isbold != prev_cfg.font.isbold ||
2132 cfg.font.height != prev_cfg.font.height ||
2133 cfg.font.charset != prev_cfg.font.charset ||
2134 cfg.font_quality != prev_cfg.font_quality ||
2135 cfg.vtmode != prev_cfg.vtmode ||
2136 cfg.bold_colour != prev_cfg.bold_colour ||
2137 cfg.resize_action == RESIZE_DISABLED ||
2138 cfg.resize_action == RESIZE_EITHER ||
2139 (cfg.resize_action != prev_cfg.resize_action))
2142 InvalidateRect(hwnd, NULL, TRUE);
2143 reset_window(init_lvl);
2144 net_pending_errors();
2151 term_do_paste(term);
2159 ldisc_send(ldisc, NULL, 0, 0);
2165 WinHelp(hwnd, help_path,
2166 help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
2170 * We get this if the System menu has been activated
2177 * We get this if the System menu has been activated
2178 * using the keyboard. This might happen from within
2179 * TranslateKey, in which case it really wants to be
2180 * followed by a `space' character to actually _bring
2181 * the menu up_ rather than just sitting there in
2182 * `ready to appear' state.
2184 show_mouseptr(1); /* make sure pointer is visible */
2186 PostMessage(hwnd, WM_CHAR, ' ', 0);
2188 case IDM_FULLSCREEN:
2192 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2193 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2195 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2196 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2198 * Ensure we haven't been sent a bogus SYSCOMMAND
2199 * which would cause us to reference invalid memory
2200 * and crash. Perhaps I'm just too paranoid here.
2202 if (i >= n_specials)
2205 back->special(backhandle, specials[i].code);
2206 net_pending_errors();
2211 #define X_POS(l) ((int)(short)LOWORD(l))
2212 #define Y_POS(l) ((int)(short)HIWORD(l))
2214 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2215 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2216 case WM_LBUTTONDOWN:
2217 case WM_MBUTTONDOWN:
2218 case WM_RBUTTONDOWN:
2222 if (message == WM_RBUTTONDOWN &&
2223 ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
2226 show_mouseptr(1); /* make sure pointer is visible */
2227 GetCursorPos(&cursorpos);
2228 TrackPopupMenu(popup_menus[CTXMENU].menu,
2229 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2230 cursorpos.x, cursorpos.y,
2238 case WM_LBUTTONDOWN:
2242 case WM_MBUTTONDOWN:
2243 button = MBT_MIDDLE;
2246 case WM_RBUTTONDOWN:
2255 button = MBT_MIDDLE;
2263 button = press = 0; /* shouldn't happen */
2267 * Special case: in full-screen mode, if the left
2268 * button is clicked in the very top left corner of the
2269 * window, we put up the System menu instead of doing
2273 char mouse_on_hotspot = 0;
2282 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2285 mi.cbSize = sizeof(MONITORINFO);
2286 GetMonitorInfo(mon, &mi);
2288 if (mi.rcMonitor.left == pt.x &&
2289 mi.rcMonitor.top == pt.y) {
2290 mouse_on_hotspot = 1;
2295 if (pt.x == 0 && pt.y == 0) {
2296 mouse_on_hotspot = 1;
2299 if (is_full_screen() && press &&
2300 button == MBT_LEFT && mouse_on_hotspot) {
2301 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2302 MAKELPARAM(pt.x, pt.y));
2309 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2310 wParam & MK_SHIFT, wParam & MK_CONTROL,
2314 term_mouse(term, button, translate_button(button), MA_RELEASE,
2315 TO_CHR_X(X_POS(lParam)),
2316 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2317 wParam & MK_CONTROL, is_alt_pressed());
2325 * Windows seems to like to occasionally send MOUSEMOVE
2326 * events even if the mouse hasn't moved. Don't unhide
2327 * the mouse pointer in this case.
2329 static WPARAM wp = 0;
2330 static LPARAM lp = 0;
2331 if (wParam != wp || lParam != lp ||
2332 last_mousemove != WM_MOUSEMOVE) {
2334 wp = wParam; lp = lParam;
2335 last_mousemove = WM_MOUSEMOVE;
2339 * Add the mouse position and message time to the random
2342 noise_ultralight(lParam);
2344 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2345 GetCapture() == hwnd) {
2347 if (wParam & MK_LBUTTON)
2349 else if (wParam & MK_MBUTTON)
2353 term_mouse(term, b, translate_button(b), MA_DRAG,
2354 TO_CHR_X(X_POS(lParam)),
2355 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2356 wParam & MK_CONTROL, is_alt_pressed());
2359 case WM_NCMOUSEMOVE:
2361 static WPARAM wp = 0;
2362 static LPARAM lp = 0;
2363 if (wParam != wp || lParam != lp ||
2364 last_mousemove != WM_NCMOUSEMOVE) {
2366 wp = wParam; lp = lParam;
2367 last_mousemove = WM_NCMOUSEMOVE;
2370 noise_ultralight(lParam);
2372 case WM_IGNORE_CLIP:
2373 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2375 case WM_DESTROYCLIPBOARD:
2377 term_deselect(term);
2378 ignore_clip = FALSE;
2385 hdc = BeginPaint(hwnd, &p);
2387 SelectPalette(hdc, pal, TRUE);
2388 RealizePalette(hdc);
2392 * We have to be careful about term_paint(). It will
2393 * set a bunch of character cells to INVALID and then
2394 * call do_paint(), which will redraw those cells and
2395 * _then mark them as done_. This may not be accurate:
2396 * when painting in WM_PAINT context we are restricted
2397 * to the rectangle which has just been exposed - so if
2398 * that only covers _part_ of a character cell and the
2399 * rest of it was already visible, that remainder will
2400 * not be redrawn at all. Accordingly, we must not
2401 * paint any character cell in a WM_PAINT context which
2402 * already has a pending update due to terminal output.
2403 * The simplest solution to this - and many, many
2404 * thanks to Hung-Te Lin for working all this out - is
2405 * not to do any actual painting at _all_ if there's a
2406 * pending terminal update: just mark the relevant
2407 * character cells as INVALID and wait for the
2408 * scheduled full update to sort it out.
2410 * I have a suspicion this isn't the _right_ solution.
2411 * An alternative approach would be to have terminal.c
2412 * separately track what _should_ be on the terminal
2413 * screen and what _is_ on the terminal screen, and
2414 * have two completely different types of redraw (one
2415 * for full updates, which syncs the former with the
2416 * terminal itself, and one for WM_PAINT which syncs
2417 * the latter with the former); yet another possibility
2418 * would be to have the Windows front end do what the
2419 * GTK one already does, and maintain a bitmap of the
2420 * current terminal appearance so that WM_PAINT becomes
2421 * completely trivial. However, this should do for now.
2423 term_paint(term, hdc,
2424 (p.rcPaint.left-offset_width)/font_width,
2425 (p.rcPaint.top-offset_height)/font_height,
2426 (p.rcPaint.right-offset_width-1)/font_width,
2427 (p.rcPaint.bottom-offset_height-1)/font_height,
2428 !term->window_update_pending);
2431 p.rcPaint.left < offset_width ||
2432 p.rcPaint.top < offset_height ||
2433 p.rcPaint.right >= offset_width + font_width*term->cols ||
2434 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2436 HBRUSH fillcolour, oldbrush;
2438 fillcolour = CreateSolidBrush (
2439 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2440 oldbrush = SelectObject(hdc, fillcolour);
2441 edge = CreatePen(PS_SOLID, 0,
2442 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2443 oldpen = SelectObject(hdc, edge);
2446 * Jordan Russell reports that this apparently
2447 * ineffectual IntersectClipRect() call masks a
2448 * Windows NT/2K bug causing strange display
2449 * problems when the PuTTY window is taller than
2450 * the primary monitor. It seems harmless enough...
2452 IntersectClipRect(hdc,
2453 p.rcPaint.left, p.rcPaint.top,
2454 p.rcPaint.right, p.rcPaint.bottom);
2456 ExcludeClipRect(hdc,
2457 offset_width, offset_height,
2458 offset_width+font_width*term->cols,
2459 offset_height+font_height*term->rows);
2461 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2462 p.rcPaint.right, p.rcPaint.bottom);
2464 /* SelectClipRgn(hdc, NULL); */
2466 SelectObject(hdc, oldbrush);
2467 DeleteObject(fillcolour);
2468 SelectObject(hdc, oldpen);
2471 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2472 SelectObject(hdc, GetStockObject(WHITE_PEN));
2478 enact_netevent(wParam, lParam);
2479 net_pending_errors();
2482 term_set_focus(term, TRUE);
2483 CreateCaret(hwnd, caretbm, font_width, font_height);
2485 flash_window(0); /* stop */
2491 term_set_focus(term, FALSE);
2493 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2496 case WM_ENTERSIZEMOVE:
2497 #ifdef RDB_DEBUG_PATCH
2498 debug((27, "WM_ENTERSIZEMOVE"));
2502 need_backend_resize = FALSE;
2504 case WM_EXITSIZEMOVE:
2507 #ifdef RDB_DEBUG_PATCH
2508 debug((27, "WM_EXITSIZEMOVE"));
2510 if (need_backend_resize) {
2511 term_size(term, cfg.height, cfg.width, cfg.savelines);
2512 InvalidateRect(hwnd, NULL, TRUE);
2517 * This does two jobs:
2518 * 1) Keep the sizetip uptodate
2519 * 2) Make sure the window size is _stepped_ in units of the font size.
2521 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2522 int width, height, w, h, ew, eh;
2523 LPRECT r = (LPRECT) lParam;
2525 if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
2526 (cfg.height != term->rows || cfg.width != term->cols )) {
2528 * Great! It seems that both the terminal size and the
2529 * font size have been changed and the user is now dragging.
2531 * It will now be difficult to get back to the configured
2534 * This would be easier but it seems to be too confusing.
2536 term_size(term, cfg.height, cfg.width, cfg.savelines);
2539 cfg.height=term->rows; cfg.width=term->cols;
2541 InvalidateRect(hwnd, NULL, TRUE);
2542 need_backend_resize = TRUE;
2545 width = r->right - r->left - extra_width;
2546 height = r->bottom - r->top - extra_height;
2547 w = (width + font_width / 2) / font_width;
2550 h = (height + font_height / 2) / font_height;
2553 UpdateSizeTip(hwnd, w, h);
2554 ew = width - w * font_width;
2555 eh = height - h * font_height;
2557 if (wParam == WMSZ_LEFT ||
2558 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2564 if (wParam == WMSZ_TOP ||
2565 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2575 int width, height, w, h, rv = 0;
2576 int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2577 int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2578 LPRECT r = (LPRECT) lParam;
2580 width = r->right - r->left - ex_width;
2581 height = r->bottom - r->top - ex_height;
2583 w = (width + term->cols/2)/term->cols;
2584 h = (height + term->rows/2)/term->rows;
2585 if ( r->right != r->left + w*term->cols + ex_width)
2588 if (wParam == WMSZ_LEFT ||
2589 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2590 r->left = r->right - w*term->cols - ex_width;
2592 r->right = r->left + w*term->cols + ex_width;
2594 if (r->bottom != r->top + h*term->rows + ex_height)
2597 if (wParam == WMSZ_TOP ||
2598 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2599 r->top = r->bottom - h*term->rows - ex_height;
2601 r->bottom = r->top + h*term->rows + ex_height;
2605 /* break; (never reached) */
2606 case WM_FULLSCR_ON_MAX:
2607 fullscr_on_max = TRUE;
2610 sys_cursor_update();
2613 #ifdef RDB_DEBUG_PATCH
2614 debug((27, "WM_SIZE %s (%d,%d)",
2615 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2616 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2617 (wParam == SIZE_RESTORED && resizing) ? "to":
2618 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2620 LOWORD(lParam), HIWORD(lParam)));
2622 if (wParam == SIZE_MINIMIZED)
2624 cfg.win_name_always ? window_name : icon_name);
2625 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2626 SetWindowText(hwnd, window_name);
2627 if (wParam == SIZE_RESTORED)
2628 clear_full_screen();
2629 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2630 fullscr_on_max = FALSE;
2634 if (cfg.resize_action == RESIZE_DISABLED) {
2635 /* A resize, well it better be a minimize. */
2639 int width, height, w, h;
2641 width = LOWORD(lParam);
2642 height = HIWORD(lParam);
2645 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2647 prev_rows = term->rows;
2648 prev_cols = term->cols;
2649 if (cfg.resize_action == RESIZE_TERM) {
2650 w = width / font_width;
2652 h = height / font_height;
2655 term_size(term, h, w, cfg.savelines);
2658 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2660 if (cfg.resize_action == RESIZE_TERM)
2661 term_size(term, prev_rows, prev_cols, cfg.savelines);
2662 if (cfg.resize_action != RESIZE_FONT)
2667 /* This is an unexpected resize, these will normally happen
2668 * if the window is too large. Probably either the user
2669 * selected a huge font or the screen size has changed.
2671 * This is also called with minimize.
2673 else reset_window(-1);
2677 * Don't call back->size in mid-resize. (To prevent
2678 * massive numbers of resize events getting sent
2679 * down the connection during an NT opaque drag.)
2682 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2683 need_backend_resize = TRUE;
2684 w = (width-cfg.window_border*2) / font_width;
2686 h = (height-cfg.window_border*2) / font_height;
2695 sys_cursor_update();
2698 switch (LOWORD(wParam)) {
2700 term_scroll(term, -1, 0);
2703 term_scroll(term, +1, 0);
2706 term_scroll(term, 0, +1);
2709 term_scroll(term, 0, -1);
2712 term_scroll(term, 0, +term->rows / 2);
2715 term_scroll(term, 0, -term->rows / 2);
2717 case SB_THUMBPOSITION:
2719 term_scroll(term, 1, HIWORD(wParam));
2723 case WM_PALETTECHANGED:
2724 if ((HWND) wParam != hwnd && pal != NULL) {
2725 HDC hdc = get_ctx(NULL);
2727 if (RealizePalette(hdc) > 0)
2733 case WM_QUERYNEWPALETTE:
2735 HDC hdc = get_ctx(NULL);
2737 if (RealizePalette(hdc) > 0)
2749 * Add the scan code and keypress timing to the random
2752 noise_ultralight(lParam);
2755 * We don't do TranslateMessage since it disassociates the
2756 * resulting CHAR message from the KEYDOWN that sparked it,
2757 * which we occasionally don't want. Instead, we process
2758 * KEYDOWN, and call the Win32 translator functions so that
2759 * we get the translations under _our_ control.
2762 unsigned char buf[20];
2765 if (wParam == VK_PROCESSKEY) { /* IME PROCESS key */
2766 if (message == WM_KEYDOWN) {
2769 m.message = WM_KEYDOWN;
2771 m.lParam = lParam & 0xdfff;
2772 TranslateMessage(&m);
2773 } else break; /* pass to Windows for default processing */
2775 len = TranslateKey(message, wParam, lParam, buf);
2777 return DefWindowProc(hwnd, message, wParam, lParam);
2781 * Interrupt an ongoing paste. I'm not sure
2782 * this is sensible, but for the moment it's
2783 * preferable to having to faff about buffering
2789 * We need not bother about stdin backlogs
2790 * here, because in GUI PuTTY we can't do
2791 * anything about it anyway; there's no means
2792 * of asking Windows to hold off on KEYDOWN
2793 * messages. We _have_ to buffer everything
2796 term_seen_key_event(term);
2798 ldisc_send(ldisc, buf, len, 1);
2803 net_pending_errors();
2805 case WM_INPUTLANGCHANGE:
2806 /* wParam == Font number */
2807 /* lParam == Locale */
2808 set_input_locale((HKL)lParam);
2809 sys_cursor_update();
2811 case WM_IME_STARTCOMPOSITION:
2813 HIMC hImc = ImmGetContext(hwnd);
2814 ImmSetCompositionFont(hImc, &lfont);
2815 ImmReleaseContext(hwnd, hImc);
2818 case WM_IME_COMPOSITION:
2824 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
2825 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2827 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2828 break; /* fall back to DefWindowProc */
2830 hIMC = ImmGetContext(hwnd);
2831 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2835 buff = snewn(n, char);
2836 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
2838 * Jaeyoun Chung reports that Korean character
2839 * input doesn't work correctly if we do a single
2840 * luni_send() covering the whole of buff. So
2841 * instead we luni_send the characters one by one.
2843 term_seen_key_event(term);
2844 for (i = 0; i < n; i += 2) {
2846 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2850 ImmReleaseContext(hwnd, hIMC);
2855 if (wParam & 0xFF00) {
2856 unsigned char buf[2];
2859 buf[0] = wParam >> 8;
2860 term_seen_key_event(term);
2862 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
2864 char c = (unsigned char) wParam;
2865 term_seen_key_event(term);
2867 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
2873 * Nevertheless, we are prepared to deal with WM_CHAR
2874 * messages, should they crop up. So if someone wants to
2875 * post the things to us as part of a macro manoeuvre,
2876 * we're ready to cope.
2879 char c = (unsigned char)wParam;
2880 term_seen_key_event(term);
2882 lpage_send(ldisc, CP_ACP, &c, 1, 1);
2885 case WM_SYSCOLORCHANGE:
2886 if (cfg.system_colour) {
2887 /* Refresh palette from system colours. */
2888 /* XXX actually this zaps the entire palette. */
2891 /* Force a repaint of the terminal window. */
2892 term_invalidate(term);
2895 case WM_AGENT_CALLBACK:
2897 struct agent_callback *c = (struct agent_callback *)lParam;
2898 c->callback(c->callback_ctx, c->data, c->len);
2903 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
2904 int shift_pressed=0, control_pressed=0;
2906 if (message == WM_MOUSEWHEEL) {
2907 wheel_accumulator += (short)HIWORD(wParam);
2908 shift_pressed=LOWORD(wParam) & MK_SHIFT;
2909 control_pressed=LOWORD(wParam) & MK_CONTROL;
2912 wheel_accumulator += (int)wParam;
2913 if (GetKeyboardState(keys)!=0) {
2914 shift_pressed=keys[VK_SHIFT]&0x80;
2915 control_pressed=keys[VK_CONTROL]&0x80;
2919 /* process events when the threshold is reached */
2920 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
2923 /* reduce amount for next time */
2924 if (wheel_accumulator > 0) {
2926 wheel_accumulator -= WHEEL_DELTA;
2927 } else if (wheel_accumulator < 0) {
2929 wheel_accumulator += WHEEL_DELTA;
2933 if (send_raw_mouse &&
2934 !(cfg.mouse_override && shift_pressed)) {
2935 /* send a mouse-down followed by a mouse up */
2936 term_mouse(term, b, translate_button(b),
2938 TO_CHR_X(X_POS(lParam)),
2939 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2940 control_pressed, is_alt_pressed());
2941 term_mouse(term, b, translate_button(b),
2942 MA_RELEASE, TO_CHR_X(X_POS(lParam)),
2943 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2944 control_pressed, is_alt_pressed());
2946 /* trigger a scroll */
2947 term_scroll(term, 0,
2949 -term->rows / 2 : term->rows / 2);
2957 * Any messages we don't process completely above are passed through to
2958 * DefWindowProc() for default processing.
2960 return DefWindowProc(hwnd, message, wParam, lParam);
2964 * Move the system caret. (We maintain one, even though it's
2965 * invisible, for the benefit of blind people: apparently some
2966 * helper software tracks the system caret, so we should arrange to
2969 void sys_cursor(void *frontend, int x, int y)
2973 if (!term->has_focus) return;
2976 * Avoid gratuitously re-updating the cursor position and IMM
2977 * window if there's no actual change required.
2979 cx = x * font_width + offset_width;
2980 cy = y * font_height + offset_height;
2981 if (cx == caret_x && cy == caret_y)
2986 sys_cursor_update();
2989 static void sys_cursor_update(void)
2994 if (!term->has_focus) return;
2996 if (caret_x < 0 || caret_y < 0)
2999 SetCaretPos(caret_x, caret_y);
3001 /* IMM calls on Win98 and beyond only */
3002 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3004 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3005 osVersion.dwMinorVersion == 0) return; /* 95 */
3007 /* we should have the IMM functions */
3008 hIMC = ImmGetContext(hwnd);
3009 cf.dwStyle = CFS_POINT;
3010 cf.ptCurrentPos.x = caret_x;
3011 cf.ptCurrentPos.y = caret_y;
3012 ImmSetCompositionWindow(hIMC, &cf);
3014 ImmReleaseContext(hwnd, hIMC);
3018 * Draw a line of text in the window, at given character
3019 * coordinates, in given attributes.
3021 * We are allowed to fiddle with the contents of `text'.
3023 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3024 unsigned long attr, int lattr)
3027 int nfg, nbg, nfont;
3030 int force_manual_underline = 0;
3031 int fnt_width, char_width;
3032 int text_adjust = 0;
3033 static int *IpDx = 0, IpDxLEN = 0;
3035 lattr &= LATTR_MODE;
3037 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3039 if (attr & ATTR_WIDE)
3042 if (len > IpDxLEN || IpDx[0] != char_width) {
3044 if (len > IpDxLEN) {
3046 IpDx = snewn(len + 16, int);
3047 IpDxLEN = (len + 16);
3049 for (i = 0; i < IpDxLEN; i++)
3050 IpDx[i] = char_width;
3053 /* Only want the left half of double width lines */
3054 if (lattr != LATTR_NORM && x*2 >= term->cols)
3062 if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
3063 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3064 if (bold_mode == BOLD_COLOURS)
3067 /* cursor fg and bg */
3068 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3072 if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3073 /* Assume a poorman font is borken in other ways too. */
3083 nfont |= FONT_WIDE + FONT_HIGH;
3086 if (attr & ATTR_NARROW)
3087 nfont |= FONT_NARROW;
3089 /* Special hack for the VT100 linedraw glyphs. */
3090 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3091 switch ((unsigned char) (text[0])) {
3093 text_adjust = -2 * font_height / 5;
3096 text_adjust = -1 * font_height / 5;
3099 text_adjust = font_height / 5;
3102 text_adjust = 2 * font_height / 5;
3105 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3107 text[0] = ucsdata.unitab_xterm['q'];
3108 if (attr & ATTR_UNDER) {
3109 attr &= ~ATTR_UNDER;
3110 force_manual_underline = 1;
3114 /* Anything left as an original character set is unprintable. */
3115 if (DIRECT_CHAR(text[0])) {
3117 for (i = 0; i < len; i++)
3122 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3125 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3126 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3127 if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
3129 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3130 nfont |= FONT_UNDERLINE;
3131 another_font(nfont);
3132 if (!fonts[nfont]) {
3133 if (nfont & FONT_UNDERLINE)
3134 force_manual_underline = 1;
3135 /* Don't do the same for manual bold, it could be bad news. */
3137 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3139 another_font(nfont);
3141 nfont = FONT_NORMAL;
3142 if (attr & ATTR_REVERSE) {
3147 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD)) {
3148 if (nfg < 16) nfg |= 8;
3149 else if (nfg >= 256) nfg |= 1;
3151 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK)) {
3152 if (nbg < 16) nbg |= 8;
3153 else if (nbg >= 256) nbg |= 1;
3157 SelectObject(hdc, fonts[nfont]);
3158 SetTextColor(hdc, fg);
3159 SetBkColor(hdc, bg);
3160 if (attr & TATTR_COMBINING)
3161 SetBkMode(hdc, TRANSPARENT);
3163 SetBkMode(hdc, OPAQUE);
3166 line_box.right = x + char_width * len;
3167 line_box.bottom = y + font_height;
3169 /* Only want the left half of double width lines */
3170 if (line_box.right > font_width*term->cols+offset_width)
3171 line_box.right = font_width*term->cols+offset_width;
3173 /* We're using a private area for direct to font. (512 chars.) */
3174 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3175 /* Ho Hum, dbcs fonts are a PITA! */
3176 /* To display on W9x I have to convert to UCS */
3177 static wchar_t *uni_buf = 0;
3178 static int uni_len = 0;
3180 if (len > uni_len) {
3183 uni_buf = snewn(uni_len, wchar_t);
3186 for(nlen = mptr = 0; mptr<len; mptr++) {
3187 uni_buf[nlen] = 0xFFFD;
3188 if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
3190 dbcstext[0] = text[mptr] & 0xFF;
3191 dbcstext[1] = text[mptr+1] & 0xFF;
3192 IpDx[nlen] += char_width;
3193 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3194 dbcstext, 2, uni_buf+nlen, 1);
3200 dbcstext[0] = text[mptr] & 0xFF;
3201 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3202 dbcstext, 1, uni_buf+nlen, 1);
3210 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3211 ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
3212 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3213 SetBkMode(hdc, TRANSPARENT);
3214 ExtTextOutW(hdc, x - 1,
3215 y - font_height * (lattr ==
3216 LATTR_BOT) + text_adjust,
3217 ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
3221 } else if (DIRECT_FONT(text[0])) {
3222 static char *directbuf = NULL;
3223 static int directlen = 0;
3225 if (len > directlen) {
3227 directbuf = sresize(directbuf, directlen, char);
3230 for (i = 0; i < len; i++)
3231 directbuf[i] = text[i] & 0xFF;
3234 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3235 ETO_CLIPPED | ETO_OPAQUE, &line_box, directbuf, len, IpDx);
3236 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3237 SetBkMode(hdc, TRANSPARENT);
3239 /* GRR: This draws the character outside it's box and can leave
3240 * 'droppings' even with the clip box! I suppose I could loop it
3241 * one character at a time ... yuk.
3243 * Or ... I could do a test print with "W", and use +1 or -1 for this
3244 * shift depending on if the leftmost column is blank...
3246 ExtTextOut(hdc, x - 1,
3247 y - font_height * (lattr ==
3248 LATTR_BOT) + text_adjust,
3249 ETO_CLIPPED, &line_box, directbuf, len, IpDx);
3252 /* And 'normal' unicode characters */
3253 static WCHAR *wbuf = NULL;
3254 static int wlen = 0;
3260 wbuf = snewn(wlen, WCHAR);
3263 for (i = 0; i < len; i++)
3266 /* print Glyphs as they are, without Windows' Shaping*/
3267 exact_textout(hdc, x, y - font_height * (lattr == LATTR_BOT) + text_adjust,
3268 &line_box, wbuf, len, IpDx, !(attr & TATTR_COMBINING));
3269 /* ExtTextOutW(hdc, x,
3270 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3271 ETO_CLIPPED | ETO_OPAQUE, &line_box, wbuf, len, IpDx);
3274 /* And the shadow bold hack. */
3275 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3276 SetBkMode(hdc, TRANSPARENT);
3277 ExtTextOutW(hdc, x - 1,
3278 y - font_height * (lattr ==
3279 LATTR_BOT) + text_adjust,
3280 ETO_CLIPPED, &line_box, wbuf, len, IpDx);
3283 if (lattr != LATTR_TOP && (force_manual_underline ||
3284 (und_mode == UND_LINE
3285 && (attr & ATTR_UNDER)))) {
3288 if (lattr == LATTR_BOT)
3289 dec = dec * 2 - font_height;
3291 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3292 MoveToEx(hdc, x, y + dec, NULL);
3293 LineTo(hdc, x + len * char_width, y + dec);
3294 oldpen = SelectObject(hdc, oldpen);
3295 DeleteObject(oldpen);
3300 * Wrapper that handles combining characters.
3302 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3303 unsigned long attr, int lattr)
3305 if (attr & TATTR_COMBINING) {
3306 unsigned long a = 0;
3307 attr &= ~TATTR_COMBINING;
3309 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3311 a = TATTR_COMBINING;
3314 do_text_internal(ctx, x, y, text, len, attr, lattr);
3317 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3318 unsigned long attr, int lattr)
3324 int ctype = cfg.cursor_type;
3326 lattr &= LATTR_MODE;
3328 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3329 if (*text != UCSWIDE) {
3330 do_text(ctx, x, y, text, len, attr, lattr);
3334 attr |= TATTR_RIGHTCURS;
3337 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3338 if (attr & ATTR_WIDE)
3345 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3348 pts[0].x = pts[1].x = pts[4].x = x;
3349 pts[2].x = pts[3].x = x + char_width - 1;
3350 pts[0].y = pts[3].y = pts[4].y = y;
3351 pts[1].y = pts[2].y = y + font_height - 1;
3352 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3353 Polyline(hdc, pts, 5);
3354 oldpen = SelectObject(hdc, oldpen);
3355 DeleteObject(oldpen);
3356 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3357 int startx, starty, dx, dy, length, i;
3360 starty = y + descent;
3363 length = char_width;
3366 if (attr & TATTR_RIGHTCURS)
3367 xadjust = char_width - 1;
3368 startx = x + xadjust;
3372 length = font_height;
3374 if (attr & TATTR_ACTCURS) {
3377 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3378 MoveToEx(hdc, startx, starty, NULL);
3379 LineTo(hdc, startx + dx * length, starty + dy * length);
3380 oldpen = SelectObject(hdc, oldpen);
3381 DeleteObject(oldpen);
3383 for (i = 0; i < length; i++) {
3385 SetPixel(hdc, startx, starty, colours[261]);
3394 /* This function gets the actual width of a character in the normal font.
3396 int char_width(Context ctx, int uc) {
3400 /* If the font max is the same as the font ave width then this
3401 * function is a no-op.
3403 if (!font_dualwidth) return 1;
3405 switch (uc & CSET_MASK) {
3407 uc = ucsdata.unitab_line[uc & 0xFF];
3410 uc = ucsdata.unitab_xterm[uc & 0xFF];
3413 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3416 if (DIRECT_FONT(uc)) {
3417 if (ucsdata.dbcs_screenfont) return 1;
3419 /* Speedup, I know of no font where ascii is the wrong width */
3420 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3423 if ( (uc & CSET_MASK) == CSET_ACP ) {
3424 SelectObject(hdc, fonts[FONT_NORMAL]);
3425 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3426 another_font(FONT_OEM);
3427 if (!fonts[FONT_OEM]) return 0;
3429 SelectObject(hdc, fonts[FONT_OEM]);
3433 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3434 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3437 /* Speedup, I know of no font where ascii is the wrong width */
3438 if (uc >= ' ' && uc <= '~') return 1;
3440 SelectObject(hdc, fonts[FONT_NORMAL]);
3441 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3442 /* Okay that one worked */ ;
3443 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3444 /* This should work on 9x too, but it's "less accurate" */ ;
3449 ibuf += font_width / 2 -1;
3456 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3457 * codes. Returns number of bytes used or zero to drop the message
3458 * or -1 to forward the message to windows.
3460 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3461 unsigned char *output)
3464 int scan, left_alt = 0, key_down, shift_state;
3466 unsigned char *p = output;
3467 static int alt_sum = 0;
3469 HKL kbd_layout = GetKeyboardLayout(0);
3471 /* keys is for ToAsciiEx. There's some ick here, see below. */
3472 static WORD keys[3];
3473 static int compose_char = 0;
3474 static WPARAM compose_key = 0;
3476 r = GetKeyboardState(keystate);
3478 memset(keystate, 0, sizeof(keystate));
3481 #define SHOW_TOASCII_RESULT
3482 { /* Tell us all about key events */
3483 static BYTE oldstate[256];
3484 static int first = 1;
3488 memcpy(oldstate, keystate, sizeof(oldstate));
3491 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3493 } else if ((HIWORD(lParam) & KF_UP)
3494 && scan == (HIWORD(lParam) & 0xFF)) {
3498 if (wParam >= VK_F1 && wParam <= VK_F20)
3499 debug(("K_F%d", wParam + 1 - VK_F1));
3512 debug(("VK_%02x", wParam));
3514 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3516 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3518 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3519 if (ch >= ' ' && ch <= '~')
3520 debug((", '%c'", ch));
3522 debug((", $%02x", ch));
3525 debug((", KB0=%02x", keys[0]));
3527 debug((", KB1=%02x", keys[1]));
3529 debug((", KB2=%02x", keys[2]));
3531 if ((keystate[VK_SHIFT] & 0x80) != 0)
3533 if ((keystate[VK_CONTROL] & 0x80) != 0)
3535 if ((HIWORD(lParam) & KF_EXTENDED))
3537 if ((HIWORD(lParam) & KF_UP))
3541 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3542 else if ((HIWORD(lParam) & KF_UP))
3543 oldstate[wParam & 0xFF] ^= 0x80;
3545 oldstate[wParam & 0xFF] ^= 0x81;
3547 for (ch = 0; ch < 256; ch++)
3548 if (oldstate[ch] != keystate[ch])
3549 debug((", M%02x=%02x", ch, keystate[ch]));
3551 memcpy(oldstate, keystate, sizeof(oldstate));
3555 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
3556 keystate[VK_RMENU] = keystate[VK_MENU];
3560 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
3561 if ((cfg.funky_type == FUNKY_VT400 ||
3562 (cfg.funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
3564 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
3566 wParam = VK_EXECUTE;
3568 /* UnToggle NUMLock */
3569 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3570 keystate[VK_NUMLOCK] ^= 1;
3573 /* And write back the 'adjusted' state */
3574 SetKeyboardState(keystate);
3577 /* Disable Auto repeat if required */
3578 if (term->repeat_off &&
3579 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
3582 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
3585 key_down = ((HIWORD(lParam) & KF_UP) == 0);
3587 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
3588 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
3589 if (cfg.ctrlaltkeys)
3590 keystate[VK_MENU] = 0;
3592 keystate[VK_RMENU] = 0x80;
3597 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
3598 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3599 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
3601 /* Note if AltGr was pressed and if it was used as a compose key */
3602 if (!compose_state) {
3603 compose_key = 0x100;
3604 if (cfg.compose_key) {
3605 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
3606 compose_key = wParam;
3608 if (wParam == VK_APPS)
3609 compose_key = wParam;
3612 if (wParam == compose_key) {
3613 if (compose_state == 0
3614 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3616 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
3620 } else if (compose_state == 1 && wParam != VK_CONTROL)
3623 if (compose_state > 1 && left_alt)
3626 /* Sanitize the number pad if not using a PC NumPad */
3627 if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
3628 && cfg.funky_type != FUNKY_XTERM)
3629 || cfg.funky_type == FUNKY_VT400 || cfg.nethack_keypad || compose_state) {
3630 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
3634 nParam = VK_NUMPAD0;
3637 nParam = VK_NUMPAD1;
3640 nParam = VK_NUMPAD2;
3643 nParam = VK_NUMPAD3;
3646 nParam = VK_NUMPAD4;
3649 nParam = VK_NUMPAD5;
3652 nParam = VK_NUMPAD6;
3655 nParam = VK_NUMPAD7;
3658 nParam = VK_NUMPAD8;
3661 nParam = VK_NUMPAD9;
3664 nParam = VK_DECIMAL;
3668 if (keystate[VK_NUMLOCK] & 1)
3675 /* If a key is pressed and AltGr is not active */
3676 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3677 /* Okay, prepare for most alts then ... */
3681 /* Lets see if it's a pattern we know all about ... */
3682 if (wParam == VK_PRIOR && shift_state == 1) {
3683 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3686 if (wParam == VK_PRIOR && shift_state == 2) {
3687 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3690 if (wParam == VK_NEXT && shift_state == 1) {
3691 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3694 if (wParam == VK_NEXT && shift_state == 2) {
3695 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3698 if (wParam == VK_INSERT && shift_state == 1) {
3699 term_do_paste(term);
3702 if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
3705 if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
3706 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3709 if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3710 (cfg.resize_action != RESIZE_DISABLED)) {
3711 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3715 /* Control-Numlock for app-keypad mode switch */
3716 if (wParam == VK_PAUSE && shift_state == 2) {
3717 term->app_keypad_keys ^= 1;
3721 /* Nethack keypad */
3722 if (cfg.nethack_keypad && !left_alt) {
3725 *p++ = shift_state ? 'B' : 'b';
3728 *p++ = shift_state ? 'J' : 'j';
3731 *p++ = shift_state ? 'N' : 'n';
3734 *p++ = shift_state ? 'H' : 'h';
3737 *p++ = shift_state ? '.' : '.';
3740 *p++ = shift_state ? 'L' : 'l';
3743 *p++ = shift_state ? 'Y' : 'y';
3746 *p++ = shift_state ? 'K' : 'k';
3749 *p++ = shift_state ? 'U' : 'u';
3754 /* Application Keypad */
3758 if (cfg.funky_type == FUNKY_VT400 ||
3759 (cfg.funky_type <= FUNKY_LINUX &&
3760 term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
3774 if (term->app_keypad_keys && !cfg.no_applic_k)
3811 if (cfg.funky_type == FUNKY_XTERM) {
3816 } else if (shift_state)
3823 if (cfg.funky_type == FUNKY_XTERM)
3827 if (cfg.funky_type == FUNKY_XTERM)
3831 if (cfg.funky_type == FUNKY_XTERM)
3836 if (HIWORD(lParam) & KF_EXTENDED)
3841 if (term->vt52_mode) {
3842 if (xkey >= 'P' && xkey <= 'S')
3843 p += sprintf((char *) p, "\x1B%c", xkey);
3845 p += sprintf((char *) p, "\x1B?%c", xkey);
3847 p += sprintf((char *) p, "\x1BO%c", xkey);
3852 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
3853 *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
3857 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
3858 /* We do the opposite of what is configured */
3859 *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
3863 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
3869 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
3873 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
3877 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
3882 if (wParam == VK_PAUSE) { /* Break/Pause */
3887 /* Control-2 to Control-8 are special */
3888 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
3889 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
3892 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
3896 if (shift_state == 2 && wParam == 0xDF) {
3900 if (shift_state == 3 && wParam == 0xDE) {
3901 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
3904 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
3911 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
3912 * for integer decimal nn.)
3914 * We also deal with the weird ones here. Linux VCs replace F1
3915 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
3916 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
3922 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
3925 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
3928 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
3931 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
3934 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
3937 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
3940 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
3943 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
3946 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
3949 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
3982 if ((shift_state&2) == 0) switch (wParam) {
4002 /* Reorder edit keys to physical order */
4003 if (cfg.funky_type == FUNKY_VT400 && code <= 6)
4004 code = "\0\2\1\4\5\3\6"[code];
4006 if (term->vt52_mode && code > 0 && code <= 6) {
4007 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4011 if (cfg.funky_type == FUNKY_SCO && /* SCO function keys */
4012 code >= 11 && code <= 34) {
4013 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4016 case VK_F1: index = 0; break;
4017 case VK_F2: index = 1; break;
4018 case VK_F3: index = 2; break;
4019 case VK_F4: index = 3; break;
4020 case VK_F5: index = 4; break;
4021 case VK_F6: index = 5; break;
4022 case VK_F7: index = 6; break;
4023 case VK_F8: index = 7; break;
4024 case VK_F9: index = 8; break;
4025 case VK_F10: index = 9; break;
4026 case VK_F11: index = 10; break;
4027 case VK_F12: index = 11; break;
4029 if (keystate[VK_SHIFT] & 0x80) index += 12;
4030 if (keystate[VK_CONTROL] & 0x80) index += 24;
4031 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4034 if (cfg.funky_type == FUNKY_SCO && /* SCO small keypad */
4035 code >= 1 && code <= 6) {
4036 char codes[] = "HL.FIG";
4040 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4044 if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4050 if (term->vt52_mode)
4051 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4054 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4057 if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4058 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4061 if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4062 if (term->vt52_mode)
4063 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4065 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4068 if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
4069 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4073 p += sprintf((char *) p, "\x1B[%d~", code);
4078 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4079 * some reason seems to send VK_CLEAR to Windows...).
4101 if (term->vt52_mode)
4102 p += sprintf((char *) p, "\x1B%c", xkey);
4104 int app_flg = (term->app_cursor_keys && !cfg.no_applic_c);
4107 * RDB: VT100 & VT102 manuals both state the
4108 * app cursor keys only work if the app keypad
4111 * SGT: That may well be true, but xterm
4112 * disagrees and so does at least one
4113 * application, so I've #if'ed this out and the
4114 * behaviour is back to PuTTY's original: app
4115 * cursor and app keypad are independently
4116 * switchable modes. If anyone complains about
4117 * _this_ I'll have to put in a configurable
4120 if (!term->app_keypad_keys)
4123 /* Useful mapping of Ctrl-arrows */
4124 if (shift_state == 2)
4128 p += sprintf((char *) p, "\x1BO%c", xkey);
4130 p += sprintf((char *) p, "\x1B[%c", xkey);
4137 * Finally, deal with Return ourselves. (Win95 seems to
4138 * foul it up when Alt is pressed, for some reason.)
4140 if (wParam == VK_RETURN) { /* Return */
4146 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4147 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4152 /* Okay we've done everything interesting; let windows deal with
4153 * the boring stuff */
4157 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4158 if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
4160 keystate[VK_CAPITAL] = 0;
4163 /* XXX how do we know what the max size of the keys array should
4164 * be is? There's indication on MS' website of an Inquire/InquireEx
4165 * functioning returning a KBINFO structure which tells us. */
4166 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4167 /* XXX 'keys' parameter is declared in MSDN documentation as
4169 * The experience of a French user indicates that on
4170 * Win98, WORD[] should be passed in, but on Win2K, it should
4171 * be BYTE[]. German WinXP and my Win2K with "US International"
4172 * driver corroborate this.
4173 * Experimentally I've conditionalised the behaviour on the
4174 * Win9x/NT split, but I suspect it's worse than that.
4175 * See wishlist item `win-dead-keys' for more horrible detail
4176 * and speculations. */
4179 r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
4180 for (i=0; i<3; i++) keys[i] = keybs[i];
4182 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4184 #ifdef SHOW_TOASCII_RESULT
4185 if (r == 1 && !key_down) {
4187 if (in_utf(term) || ucsdata.dbcs_screenfont)
4188 debug((", (U+%04x)", alt_sum));
4190 debug((", LCH(%d)", alt_sum));
4192 debug((", ACH(%d)", keys[0]));
4197 for (r1 = 0; r1 < r; r1++) {
4198 debug(("%s%d", r1 ? "," : "", keys[r1]));
4207 * Interrupt an ongoing paste. I'm not sure this is
4208 * sensible, but for the moment it's preferable to
4209 * having to faff about buffering things.
4214 for (i = 0; i < r; i++) {
4215 unsigned char ch = (unsigned char) keys[i];
4217 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
4222 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
4226 if ((nc = check_compose(compose_char, ch)) == -1) {
4227 MessageBeep(MB_ICONHAND);
4231 term_seen_key_event(term);
4233 luni_send(ldisc, &keybuf, 1, 1);
4241 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4243 term_seen_key_event(term);
4245 luni_send(ldisc, &keybuf, 1, 1);
4247 ch = (char) alt_sum;
4249 * We need not bother about stdin
4250 * backlogs here, because in GUI PuTTY
4251 * we can't do anything about it
4252 * anyway; there's no means of asking
4253 * Windows to hold off on KEYDOWN
4254 * messages. We _have_ to buffer
4255 * everything we're sent.
4257 term_seen_key_event(term);
4259 ldisc_send(ldisc, &ch, 1, 1);
4263 term_seen_key_event(term);
4265 lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
4268 if(capsOn && ch < 0x80) {
4271 cbuf[1] = xlat_uskbd2cyrllic(ch);
4272 term_seen_key_event(term);
4274 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4279 term_seen_key_event(term);
4281 lpage_send(ldisc, kbd_codepage,
4282 cbuf+!left_alt, 1+!!left_alt, 1);
4288 /* This is so the ALT-Numpad and dead keys work correctly. */
4293 /* If we're definitly not building up an ALT-54321 then clear it */
4296 /* If we will be using alt_sum fix the 256s */
4297 else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4302 * ALT alone may or may not want to bring up the System menu.
4303 * If it's not meant to, we return 0 on presses or releases of
4304 * ALT, to show that we've swallowed the keystroke. Otherwise
4305 * we return -1, which means Windows will give the keystroke
4306 * its default handling (i.e. bring up the System menu).
4308 if (wParam == VK_MENU && !cfg.alt_only)
4314 void request_paste(void *frontend)
4317 * In Windows, pasting is synchronous: we can read the
4318 * clipboard with no difficulty, so request_paste() can just go
4321 term_do_paste(term);
4324 void set_title(void *frontend, char *title)
4327 window_name = snewn(1 + strlen(title), char);
4328 strcpy(window_name, title);
4329 if (cfg.win_name_always || !IsIconic(hwnd))
4330 SetWindowText(hwnd, title);
4333 void set_icon(void *frontend, char *title)
4336 icon_name = snewn(1 + strlen(title), char);
4337 strcpy(icon_name, title);
4338 if (!cfg.win_name_always && IsIconic(hwnd))
4339 SetWindowText(hwnd, title);
4342 void set_sbar(void *frontend, int total, int start, int page)
4346 if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
4349 si.cbSize = sizeof(si);
4350 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4352 si.nMax = total - 1;
4356 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4359 Context get_ctx(void *frontend)
4365 SelectPalette(hdc, pal, FALSE);
4371 void free_ctx(Context ctx)
4373 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4374 ReleaseDC(hwnd, ctx);
4377 static void real_palette_set(int n, int r, int g, int b)
4380 logpal->palPalEntry[n].peRed = r;
4381 logpal->palPalEntry[n].peGreen = g;
4382 logpal->palPalEntry[n].peBlue = b;
4383 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4384 colours[n] = PALETTERGB(r, g, b);
4385 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4387 colours[n] = RGB(r, g, b);
4390 void palette_set(void *frontend, int n, int r, int g, int b)
4394 if (n > NALLCOLOURS)
4396 real_palette_set(n, r, g, b);
4398 HDC hdc = get_ctx(frontend);
4399 UnrealizeObject(pal);
4400 RealizePalette(hdc);
4405 void palette_reset(void *frontend)
4410 for (i = 0; i < NALLCOLOURS; i++) {
4412 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4413 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4414 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4415 logpal->palPalEntry[i].peFlags = 0;
4416 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4417 defpal[i].rgbtGreen,
4418 defpal[i].rgbtBlue);
4420 colours[i] = RGB(defpal[i].rgbtRed,
4421 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4426 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4427 hdc = get_ctx(frontend);
4428 RealizePalette(hdc);
4433 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4438 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4441 lock = GlobalLock(clipdata);
4444 memcpy(lock, data, len);
4445 ((unsigned char *) lock)[len] = 0;
4446 GlobalUnlock(clipdata);
4449 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4451 if (OpenClipboard(hwnd)) {
4453 SetClipboardData(CF_TEXT, clipdata);
4456 GlobalFree(clipdata);
4459 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4463 * Note: unlike write_aclip() this will not append a nul.
4465 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
4467 HGLOBAL clipdata, clipdata2, clipdata3;
4469 void *lock, *lock2, *lock3;
4471 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4473 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4474 len * sizeof(wchar_t));
4475 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4477 if (!clipdata || !clipdata2) {
4479 GlobalFree(clipdata);
4481 GlobalFree(clipdata2);
4484 if (!(lock = GlobalLock(clipdata)))
4486 if (!(lock2 = GlobalLock(clipdata2)))
4489 memcpy(lock, data, len * sizeof(wchar_t));
4490 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4492 if (cfg.rtf_paste) {
4493 wchar_t unitab[256];
4495 unsigned char *tdata = (unsigned char *)lock2;
4496 wchar_t *udata = (wchar_t *)lock;
4497 int rtflen = 0, uindex = 0, tindex = 0;
4499 int multilen, blen, alen, totallen, i;
4500 char before[16], after[4];
4501 int fgcolour, lastfgcolour = 0;
4502 int bgcolour, lastbgcolour = 0;
4503 int attrBold, lastAttrBold = 0;
4504 int attrUnder, lastAttrUnder = 0;
4505 int palette[NALLCOLOURS];
4508 get_unitab(CP_ACP, unitab, 0);
4510 rtfsize = 100 + strlen(cfg.font.name);
4511 rtf = snewn(rtfsize, char);
4512 rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
4513 cfg.font.name, cfg.font.height*2);
4516 * Add colour palette
4517 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
4521 * First - Determine all colours in use
4522 * o Foregound and background colours share the same palette
4525 memset(palette, 0, sizeof(palette));
4526 for (i = 0; i < (len-1); i++) {
4527 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
4528 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
4530 if (attr[i] & ATTR_REVERSE) {
4531 int tmpcolour = fgcolour; /* Swap foreground and background */
4532 fgcolour = bgcolour;
4533 bgcolour = tmpcolour;
4536 if (bold_mode == BOLD_COLOURS && (attr[i] & ATTR_BOLD)) {
4537 if (fgcolour < 8) /* ANSI colours */
4539 else if (fgcolour >= 256) /* Default colours */
4543 if (attr[i] & ATTR_BLINK) {
4544 if (bgcolour < 8) /* ANSI colours */
4546 else if (bgcolour >= 256) /* Default colours */
4550 palette[fgcolour]++;
4551 palette[bgcolour]++;
4555 * Next - Create a reduced palette
4558 for (i = 0; i < NALLCOLOURS; i++) {
4559 if (palette[i] != 0)
4560 palette[i] = ++numcolours;
4564 * Finally - Write the colour table
4566 rtf = sresize(rtf, rtfsize + (numcolours * 25), char);
4567 strcat(rtf, "{\\colortbl ;");
4568 rtflen = strlen(rtf);
4570 for (i = 0; i < NALLCOLOURS; i++) {
4571 if (palette[i] != 0) {
4572 rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4575 strcpy(&rtf[rtflen], "}");
4580 * We want to construct a piece of RTF that specifies the
4581 * same Unicode text. To do this we will read back in
4582 * parallel from the Unicode data in `udata' and the
4583 * non-Unicode data in `tdata'. For each character in
4584 * `tdata' which becomes the right thing in `udata' when
4585 * looked up in `unitab', we just copy straight over from
4586 * tdata. For each one that doesn't, we must WCToMB it
4587 * individually and produce a \u escape sequence.
4589 * It would probably be more robust to just bite the bullet
4590 * and WCToMB each individual Unicode character one by one,
4591 * then MBToWC each one back to see if it was an accurate
4592 * translation; but that strikes me as a horrifying number
4593 * of Windows API calls so I want to see if this faster way
4594 * will work. If it screws up badly we can always revert to
4595 * the simple and slow way.
4597 while (tindex < len2 && uindex < len &&
4598 tdata[tindex] && udata[uindex]) {
4599 if (tindex + 1 < len2 &&
4600 tdata[tindex] == '\r' &&
4601 tdata[tindex+1] == '\n') {
4607 * Set text attributes
4610 if (rtfsize < rtflen + 64) {
4611 rtfsize = rtflen + 512;
4612 rtf = sresize(rtf, rtfsize, char);
4616 * Determine foreground and background colours
4618 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
4619 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
4621 if (attr[tindex] & ATTR_REVERSE) {
4622 int tmpcolour = fgcolour; /* Swap foreground and background */
4623 fgcolour = bgcolour;
4624 bgcolour = tmpcolour;
4627 if (bold_mode == BOLD_COLOURS && (attr[tindex] & ATTR_BOLD)) {
4628 if (fgcolour < 8) /* ANSI colours */
4630 else if (fgcolour >= 256) /* Default colours */
4634 if (attr[tindex] & ATTR_BLINK) {
4635 if (bgcolour < 8) /* ANSI colours */
4637 else if (bgcolour >= 256) /* Default colours */
4642 * Collect other attributes
4644 if (bold_mode != BOLD_COLOURS)
4645 attrBold = attr[tindex] & ATTR_BOLD;
4649 attrUnder = attr[tindex] & ATTR_UNDER;
4653 * o If video isn't reversed, ignore colour attributes for default foregound
4655 * o Special case where bolded text is displayed using the default foregound
4656 * and background colours - force to bolded RTF.
4658 if (!(attr[tindex] & ATTR_REVERSE)) {
4659 if (bgcolour >= 256) /* Default color */
4660 bgcolour = -1; /* No coloring */
4662 if (fgcolour >= 256) { /* Default colour */
4663 if (bold_mode == BOLD_COLOURS && (fgcolour & 1) && bgcolour == -1)
4664 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
4666 fgcolour = -1; /* No coloring */
4671 * Write RTF text attributes
4673 if (lastfgcolour != fgcolour) {
4674 lastfgcolour = fgcolour;
4675 rtflen += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
4678 if (lastbgcolour != bgcolour) {
4679 lastbgcolour = bgcolour;
4680 rtflen += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
4683 if (lastAttrBold != attrBold) {
4684 lastAttrBold = attrBold;
4685 rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
4688 if (lastAttrUnder != attrUnder) {
4689 lastAttrUnder = attrUnder;
4690 rtflen += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
4694 if (unitab[tdata[tindex]] == udata[uindex]) {
4700 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4701 NULL, 0, NULL, NULL);
4702 if (multilen != 1) {
4703 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4705 alen = 1; strcpy(after, "}");
4707 blen = sprintf(before, "\\u%d", udata[uindex]);
4708 alen = 0; after[0] = '\0';
4711 assert(tindex + multilen <= len2);
4712 totallen = blen + alen;
4713 for (i = 0; i < multilen; i++) {
4714 if (tdata[tindex+i] == '\\' ||
4715 tdata[tindex+i] == '{' ||
4716 tdata[tindex+i] == '}')
4718 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4719 totallen += 6; /* \par\r\n */
4720 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4726 if (rtfsize < rtflen + totallen + 3) {
4727 rtfsize = rtflen + totallen + 512;
4728 rtf = sresize(rtf, rtfsize, char);
4731 strcpy(rtf + rtflen, before); rtflen += blen;
4732 for (i = 0; i < multilen; i++) {
4733 if (tdata[tindex+i] == '\\' ||
4734 tdata[tindex+i] == '{' ||
4735 tdata[tindex+i] == '}') {
4736 rtf[rtflen++] = '\\';
4737 rtf[rtflen++] = tdata[tindex+i];
4738 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4739 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4740 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4741 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4743 rtf[rtflen++] = tdata[tindex+i];
4746 strcpy(rtf + rtflen, after); rtflen += alen;
4752 rtf[rtflen++] = '}'; /* Terminate RTF stream */
4753 rtf[rtflen++] = '\0';
4754 rtf[rtflen++] = '\0';
4756 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4757 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
4758 memcpy(lock3, rtf, rtflen);
4759 GlobalUnlock(clipdata3);
4765 GlobalUnlock(clipdata);
4766 GlobalUnlock(clipdata2);
4769 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4771 if (OpenClipboard(hwnd)) {
4773 SetClipboardData(CF_UNICODETEXT, clipdata);
4774 SetClipboardData(CF_TEXT, clipdata2);
4776 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4779 GlobalFree(clipdata);
4780 GlobalFree(clipdata2);
4784 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4787 void get_clip(void *frontend, wchar_t ** p, int *len)
4789 static HGLOBAL clipdata = NULL;
4790 static wchar_t *converted = 0;
4799 GlobalUnlock(clipdata);
4802 } else if (OpenClipboard(NULL)) {
4803 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
4805 *p = GlobalLock(clipdata);
4807 for (p2 = *p; *p2; p2++);
4811 } else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
4815 s = GlobalLock(clipdata);
4816 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
4817 *p = converted = snewn(i, wchar_t);
4818 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
4831 * Move `lines' lines from position `from' to position `to' in the
4834 void optimised_move(void *frontend, int to, int from, int lines)
4839 min = (to < from ? to : from);
4840 max = to + from - min;
4842 r.left = offset_width;
4843 r.right = offset_width + term->cols * font_width;
4844 r.top = offset_height + min * font_height;
4845 r.bottom = offset_height + (max + lines) * font_height;
4846 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
4851 * Print a message box and perform a fatal exit.
4853 void fatalbox(char *fmt, ...)
4856 char *stuff, morestuff[100];
4859 stuff = dupvprintf(fmt, ap);
4861 sprintf(morestuff, "%.70s Fatal Error", appname);
4862 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
4868 * Print a modal (Really Bad) message box and perform a fatal exit.
4870 void modalfatalbox(char *fmt, ...)
4873 char *stuff, morestuff[100];
4876 stuff = dupvprintf(fmt, ap);
4878 sprintf(morestuff, "%.70s Fatal Error", appname);
4879 MessageBox(hwnd, stuff, morestuff,
4880 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
4885 static void flash_window(int mode);
4886 static long next_flash;
4887 static int flashing = 0;
4889 static void flash_window_timer(void *ctx, long now)
4891 if (flashing && now - next_flash >= 0) {
4897 * Manage window caption / taskbar flashing, if enabled.
4898 * 0 = stop, 1 = maintain, 2 = start
4900 static void flash_window(int mode)
4902 if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
4905 FlashWindow(hwnd, FALSE);
4909 } else if (mode == 2) {
4913 FlashWindow(hwnd, TRUE);
4914 next_flash = schedule_timer(450, flash_window_timer, hwnd);
4917 } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
4920 FlashWindow(hwnd, TRUE); /* toggle */
4921 next_flash = schedule_timer(450, flash_window_timer, hwnd);
4929 void do_beep(void *frontend, int mode)
4931 if (mode == BELL_DEFAULT) {
4933 * For MessageBeep style bells, we want to be careful of
4934 * timing, because they don't have the nice property of
4935 * PlaySound bells that each one cancels the previous
4936 * active one. So we limit the rate to one per 50ms or so.
4938 static long lastbeep = 0;
4941 beepdiff = GetTickCount() - lastbeep;
4942 if (beepdiff >= 0 && beepdiff < 50)
4946 * The above MessageBeep call takes time, so we record the
4947 * time _after_ it finishes rather than before it starts.
4949 lastbeep = GetTickCount();
4950 } else if (mode == BELL_WAVEFILE) {
4951 if (!PlaySound(cfg.bell_wavefile.path, NULL,
4952 SND_ASYNC | SND_FILENAME)) {
4953 char buf[sizeof(cfg.bell_wavefile.path) + 80];
4955 sprintf(buf, "Unable to play sound file\n%s\n"
4956 "Using default sound instead", cfg.bell_wavefile.path);
4957 sprintf(otherbuf, "%.70s Sound Error", appname);
4958 MessageBox(hwnd, buf, otherbuf,
4959 MB_OK | MB_ICONEXCLAMATION);
4960 cfg.beep = BELL_DEFAULT;
4962 } else if (mode == BELL_PCSPEAKER) {
4963 static long lastbeep = 0;
4966 beepdiff = GetTickCount() - lastbeep;
4967 if (beepdiff >= 0 && beepdiff < 50)
4971 * We must beep in different ways depending on whether this
4972 * is a 95-series or NT-series OS.
4974 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
4978 lastbeep = GetTickCount();
4980 /* Otherwise, either visual bell or disabled; do nothing here */
4981 if (!term->has_focus) {
4982 flash_window(2); /* start */
4987 * Minimise or restore the window in response to a server-side
4990 void set_iconic(void *frontend, int iconic)
4992 if (IsIconic(hwnd)) {
4994 ShowWindow(hwnd, SW_RESTORE);
4997 ShowWindow(hwnd, SW_MINIMIZE);
5002 * Move the window in response to a server-side request.
5004 void move_window(void *frontend, int x, int y)
5006 if (cfg.resize_action == RESIZE_DISABLED ||
5007 cfg.resize_action == RESIZE_FONT ||
5011 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5015 * Move the window to the top or bottom of the z-order in response
5016 * to a server-side request.
5018 void set_zorder(void *frontend, int top)
5020 if (cfg.alwaysontop)
5021 return; /* ignore */
5022 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5023 SWP_NOMOVE | SWP_NOSIZE);
5027 * Refresh the window in response to a server-side request.
5029 void refresh_window(void *frontend)
5031 InvalidateRect(hwnd, NULL, TRUE);
5035 * Maximise or restore the window in response to a server-side
5038 void set_zoomed(void *frontend, int zoomed)
5040 if (IsZoomed(hwnd)) {
5042 ShowWindow(hwnd, SW_RESTORE);
5045 ShowWindow(hwnd, SW_MAXIMIZE);
5050 * Report whether the window is iconic, for terminal reports.
5052 int is_iconic(void *frontend)
5054 return IsIconic(hwnd);
5058 * Report the window's position, for terminal reports.
5060 void get_window_pos(void *frontend, int *x, int *y)
5063 GetWindowRect(hwnd, &r);
5069 * Report the window's pixel size, for terminal reports.
5071 void get_window_pixels(void *frontend, int *x, int *y)
5074 GetWindowRect(hwnd, &r);
5075 *x = r.right - r.left;
5076 *y = r.bottom - r.top;
5080 * Return the window or icon title.
5082 char *get_window_title(void *frontend, int icon)
5084 return icon ? icon_name : window_name;
5088 * See if we're in full-screen mode.
5090 static int is_full_screen()
5092 if (!IsZoomed(hwnd))
5094 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
5099 /* Get the rect/size of a full screen window using the nearest available
5100 * monitor in multimon systems; default to something sensible if only
5101 * one monitor is present. */
5102 static int get_fullscreen_rect(RECT * ss)
5104 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
5107 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
5108 mi.cbSize = sizeof(mi);
5109 GetMonitorInfo(mon, &mi);
5111 /* structure copy */
5115 /* could also use code like this:
5116 ss->left = ss->top = 0;
5117 ss->right = GetSystemMetrics(SM_CXSCREEN);
5118 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5120 return GetClientRect(GetDesktopWindow(), ss);
5126 * Go full-screen. This should only be called when we are already
5129 static void make_full_screen()
5134 assert(IsZoomed(hwnd));
5136 if (is_full_screen())
5139 /* Remove the window furniture. */
5140 style = GetWindowLongPtr(hwnd, GWL_STYLE);
5141 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5142 if (cfg.scrollbar_in_fullscreen)
5143 style |= WS_VSCROLL;
5145 style &= ~WS_VSCROLL;
5146 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5148 /* Resize ourselves to exactly cover the nearest monitor. */
5149 get_fullscreen_rect(&ss);
5150 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5155 /* Tick the menu item in the System menu. */
5156 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
5161 * Clear the full-screen attributes.
5163 static void clear_full_screen()
5165 DWORD oldstyle, style;
5167 /* Reinstate the window furniture. */
5168 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
5169 style |= WS_CAPTION | WS_BORDER;
5170 if (cfg.resize_action == RESIZE_DISABLED)
5171 style &= ~WS_THICKFRAME;
5173 style |= WS_THICKFRAME;
5175 style |= WS_VSCROLL;
5177 style &= ~WS_VSCROLL;
5178 if (style != oldstyle) {
5179 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5180 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5181 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5185 /* Untick the menu item in the System menu. */
5186 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
5191 * Toggle full-screen mode.
5193 static void flip_full_screen()
5195 if (is_full_screen()) {
5196 ShowWindow(hwnd, SW_RESTORE);
5197 } else if (IsZoomed(hwnd)) {
5200 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5201 ShowWindow(hwnd, SW_MAXIMIZE);
5205 void frontend_keypress(void *handle)
5208 * Keypress termination in non-Close-On-Exit mode is not
5209 * currently supported in PuTTY proper, because the window
5210 * always has a perfectly good Close button anyway. So we do
5216 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5218 return term_data(term, is_stderr, data, len);
5221 int from_backend_untrusted(void *frontend, const char *data, int len)
5223 return term_data_untrusted(term, data, len);
5226 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
5229 ret = cmdline_get_passwd_input(p, in, inlen);
5231 ret = term_get_userpass_input(term, p, in, inlen);
5235 void agent_schedule_callback(void (*callback)(void *, void *, int),
5236 void *callback_ctx, void *data, int len)
5238 struct agent_callback *c = snew(struct agent_callback);
5239 c->callback = callback;
5240 c->callback_ctx = callback_ctx;
5243 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);