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
44 #define IDM_SPECIAL_MIN 0x0400
45 #define IDM_SPECIAL_MAX 0x0800
47 #define IDM_SAVED_MIN 0x1000
48 #define IDM_SAVED_MAX 0x5000
49 #define MENU_SAVED_STEP 16
50 /* Maximum number of sessions on saved-session submenu */
51 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
53 #define WM_IGNORE_CLIP (WM_XUSER + 2)
54 #define WM_FULLSCR_ON_MAX (WM_XUSER + 3)
55 #define WM_AGENT_CALLBACK (WM_XUSER + 4)
57 /* Needed for Chinese support and apparently not always defined. */
59 #define VK_PROCESSKEY 0xE5
62 /* Mouse wheel support. */
64 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
67 #define WHEEL_DELTA 120
70 static Mouse_Button translate_button(Mouse_Button button);
71 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
72 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
73 unsigned char *output);
74 static void cfgtopalette(void);
75 static void systopalette(void);
76 static void init_palette(void);
77 static void init_fonts(int, int);
78 static void another_font(int);
79 static void deinit_fonts(void);
80 static void set_input_locale(HKL);
82 static int is_full_screen(void);
83 static void make_full_screen(void);
84 static void clear_full_screen(void);
85 static void flip_full_screen(void);
87 /* Window layout information */
88 static void reset_window(int);
89 static int extra_width, extra_height;
90 static int font_width, font_height, font_dualwidth;
91 static int offset_width, offset_height;
92 static int was_zoomed = 0;
93 static int prev_rows, prev_cols;
95 static void enact_netevent(WPARAM, LPARAM);
96 static void flash_window(int mode);
97 static void sys_cursor_update(void);
98 static int is_shift_pressed(void);
99 static int get_fullscreen_rect(RECT * ss);
101 static int caret_x = -1, caret_y = -1;
103 static int kbd_codepage;
106 static Backend *back;
107 static void *backhandle;
109 static struct unicode_data ucsdata;
110 static int session_closed;
112 static const struct telnet_special *specials;
113 static int n_specials;
115 #define TIMING_TIMER_ID 1234
116 static long timing_next_time;
120 int specials_submenu_pos;
122 enum { SYSMENU, CTXMENU };
124 Config cfg; /* exported to windlg.c */
126 extern struct sesslist sesslist; /* imported from windlg.c */
128 struct agent_callback {
129 void (*callback)(void *, void *, int);
135 #define FONT_NORMAL 0
137 #define FONT_UNDERLINE 2
138 #define FONT_BOLDUND 3
139 #define FONT_WIDE 0x04
140 #define FONT_HIGH 0x08
141 #define FONT_NARROW 0x10
143 #define FONT_OEM 0x20
144 #define FONT_OEMBOLD 0x21
145 #define FONT_OEMUND 0x22
146 #define FONT_OEMBOLDUND 0x23
148 #define FONT_MAXNO 0x2F
150 static HFONT fonts[FONT_MAXNO];
151 static LOGFONT lfont;
152 static int fontflag[FONT_MAXNO];
154 BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT
162 static COLORREF colours[NCOLOURS];
164 static LPLOGPALETTE logpal;
165 static RGBTRIPLE defpal[NCOLOURS];
169 static HBITMAP caretbm;
171 static int dbltime, lasttime, lastact;
172 static Mouse_Button lastbtn;
174 /* this allows xterm-style mouse handling. */
175 static int send_raw_mouse = 0;
176 static int wheel_accumulator = 0;
178 static char *window_name, *icon_name;
180 static int compose_state = 0;
182 static UINT wm_mousewheel = WM_MOUSEWHEEL;
184 /* Dummy routine, only required in plink. */
185 void ldisc_update(void *frontend, int echo, int edit)
189 static void start_backend(void)
192 char msg[1024], *title;
197 * Select protocol. This is farmed out into a table in a
198 * separate file to enable an ssh-free variant.
201 for (i = 0; backends[i].backend != NULL; i++)
202 if (backends[i].protocol == cfg.protocol) {
203 back = backends[i].backend;
207 char *str = dupprintf("%s Internal Error", appname);
208 MessageBox(NULL, "Unsupported protocol number found",
209 str, MB_OK | MB_ICONEXCLAMATION);
214 error = back->init(NULL, &backhandle, &cfg,
215 cfg.host, cfg.port, &realhost, cfg.tcp_nodelay,
217 back->provide_logctx(backhandle, logctx);
219 char *str = dupprintf("%s Error", appname);
220 sprintf(msg, "Unable to open connection to\n"
221 "%.800s\n" "%s", cfg.host, error);
222 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
226 window_name = icon_name = NULL;
228 title = cfg.wintitle;
230 sprintf(msg, "%s - %s", realhost, appname);
234 set_title(NULL, title);
235 set_icon(NULL, title);
238 * Connect the terminal to the backend for resize purposes.
240 term_provide_resize_fn(term, back->size, backhandle);
243 * Set up a line discipline.
245 ldisc = ldisc_create(&cfg, term, back, backhandle, NULL);
248 * Destroy the Restart Session menu item. (This will return
249 * failure if it's already absent, as it will be the very first
250 * time we call this function. We ignore that, because as long
251 * as the menu item ends up not being there, we don't care
252 * whether it was us who removed it or not!)
254 for (i = 0; i < lenof(popup_menus); i++) {
255 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
258 session_closed = FALSE;
261 static void close_session(void)
266 session_closed = TRUE;
267 sprintf(morestuff, "%.70s (inactive)", appname);
268 set_icon(NULL, morestuff);
269 set_title(NULL, morestuff);
276 back->free(backhandle);
279 update_specials_menu(NULL);
283 * Show the Restart Session menu item. Do a precautionary
284 * delete first to ensure we never end up with more than one.
286 for (i = 0; i < lenof(popup_menus); i++) {
287 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
288 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
289 IDM_RESTART, "&Restart Session");
293 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
297 int guess_width, guess_height;
300 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
304 InitCommonControls();
306 /* Ensure a Maximize setting in Explorer doesn't maximise the
312 char *str = dupprintf("%s Fatal Error", appname);
313 MessageBox(NULL, "Windows refuses to report a version",
314 str, MB_OK | MB_ICONEXCLAMATION);
320 * If we're running a version of Windows that doesn't support
321 * WM_MOUSEWHEEL, find out what message number we should be
324 if (osVersion.dwMajorVersion < 4 ||
325 (osVersion.dwMajorVersion == 4 &&
326 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
327 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
330 * See if we can find our Help file.
333 char b[2048], *p, *q, *r;
335 GetModuleFileName(NULL, b, sizeof(b) - 1);
337 p = strrchr(b, '\\');
338 if (p && p >= r) r = p+1;
340 if (q && q >= r) r = q+1;
341 strcpy(r, "putty.hlp");
342 if ( (fp = fopen(b, "r")) != NULL) {
343 help_path = dupstr(b);
347 strcpy(r, "putty.cnt");
348 if ( (fp = fopen(b, "r")) != NULL) {
349 help_has_contents = TRUE;
352 help_has_contents = FALSE;
356 * Process the command line.
362 default_protocol = be_default_protocol;
363 /* Find the appropriate default port. */
366 default_port = 0; /* illegal */
367 for (i = 0; backends[i].backend != NULL; i++)
368 if (backends[i].protocol == default_protocol) {
369 default_port = backends[i].backend->default_port;
373 cfg.logtype = LGTYP_NONE;
375 do_defaults(NULL, &cfg);
380 * Process a couple of command-line options which are more
381 * easily dealt with before the line is broken up into
382 * words. These are the soon-to-be-defunct @sessionname and
383 * the internal-use-only &sharedmemoryhandle, neither of
384 * which are combined with anything else.
386 while (*p && isspace(*p))
390 while (i > 1 && isspace(p[i - 1]))
393 do_defaults(p + 1, &cfg);
394 if (!*cfg.host && !do_config()) {
397 } else if (*p == '&') {
399 * An initial & means we've been given a command line
400 * containing the hex value of a HANDLE for a file
401 * mapping object, which we must then extract as a
406 if (sscanf(p + 1, "%p", &filemap) == 1 &&
407 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
408 0, 0, sizeof(Config))) != NULL) {
411 CloseHandle(filemap);
412 } else if (!do_config()) {
417 * Otherwise, break up the command line and deal with
423 split_into_argv(cmdline, &argc, &argv, NULL);
425 for (i = 0; i < argc; i++) {
429 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
432 cmdline_error("option \"%s\" requires an argument", p);
433 } else if (ret == 2) {
434 i++; /* skip next argument */
435 } else if (ret == 1) {
436 continue; /* nothing further needs doing */
437 } else if (!strcmp(p, "-cleanup")) {
439 * `putty -cleanup'. Remove all registry
440 * entries associated with PuTTY, and also find
441 * and delete the random seed file.
444 s1 = dupprintf("This procedure will remove ALL Registry\n"
445 "entries associated with %s, and will\n"
446 "also remove the random seed file.\n"
448 "THIS PROCESS WILL DESTROY YOUR SAVED\n"
449 "SESSIONS. Are you really sure you want\n"
450 "to continue?", appname);
451 s2 = dupprintf("%s Warning", appname);
452 if (MessageBox(NULL, s1, s2,
453 MB_YESNO | MB_ICONWARNING) == IDYES) {
459 } else if (*p != '-') {
463 * If we already have a host name, treat
464 * this argument as a port number. NB we
465 * have to treat this as a saved -P
466 * argument, so that it will be deferred
467 * until it's a good moment to run it.
469 int ret = cmdline_process_param("-P", p, 1, &cfg);
471 } else if (!strncmp(q, "telnet:", 7)) {
473 * If the hostname starts with "telnet:",
474 * set the protocol to Telnet and process
475 * the string as a Telnet URL.
480 if (q[0] == '/' && q[1] == '/')
482 cfg.protocol = PROT_TELNET;
484 while (*p && *p != ':' && *p != '/')
493 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
494 cfg.host[sizeof(cfg.host) - 1] = '\0';
498 * Otherwise, treat this argument as a host
501 while (*p && !isspace(*p))
505 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
506 cfg.host[sizeof(cfg.host) - 1] = '\0';
510 cmdline_error("unknown option \"%s\"", p);
515 cmdline_run_saved(&cfg);
517 if (!*cfg.host && !do_config()) {
522 * Trim leading whitespace off the hostname if it's there.
525 int space = strspn(cfg.host, " \t");
526 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
529 /* See if host is of the form user@host */
530 if (cfg.host[0] != '\0') {
531 char *atsign = strrchr(cfg.host, '@');
532 /* Make sure we're not overflowing the user field */
534 if (atsign - cfg.host < sizeof cfg.username) {
535 strncpy(cfg.username, cfg.host, atsign - cfg.host);
536 cfg.username[atsign - cfg.host] = '\0';
538 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
543 * Trim a colon suffix off the hostname if it's there.
545 cfg.host[strcspn(cfg.host, ":")] = '\0';
548 * Remove any remaining whitespace from the hostname.
552 while (cfg.host[p2] != '\0') {
553 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
554 cfg.host[p1] = cfg.host[p2];
563 /* Check for invalid Port number (i.e. zero) */
565 char *str = dupprintf("%s Internal Error", appname);
566 MessageBox(NULL, "Invalid Port Number",
567 str, MB_OK | MB_ICONEXCLAMATION);
574 wndclass.lpfnWndProc = WndProc;
575 wndclass.cbClsExtra = 0;
576 wndclass.cbWndExtra = 0;
577 wndclass.hInstance = inst;
578 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
579 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
580 wndclass.hbrBackground = NULL;
581 wndclass.lpszMenuName = NULL;
582 wndclass.lpszClassName = appname;
584 RegisterClass(&wndclass);
589 memset(&ucsdata, 0, sizeof(ucsdata));
591 term = term_init(&cfg, &ucsdata, NULL);
592 logctx = log_init(NULL, &cfg);
593 term_provide_logctx(term, logctx);
598 * Guess some defaults for the window size. This all gets
599 * updated later, so we don't really care too much. However, we
600 * do want the font width/height guesses to correspond to a
601 * large font rather than a small one...
608 term_size(term, cfg.height, cfg.width, cfg.savelines);
609 guess_width = extra_width + font_width * term->cols;
610 guess_height = extra_height + font_height * term->rows;
613 get_fullscreen_rect(&r);
614 if (guess_width > r.right - r.left)
615 guess_width = r.right - r.left;
616 if (guess_height > r.bottom - r.top)
617 guess_height = r.bottom - r.top;
621 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
624 winmode &= ~(WS_VSCROLL);
625 if (cfg.resize_action == RESIZE_DISABLED)
626 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
628 exwinmode |= WS_EX_TOPMOST;
630 exwinmode |= WS_EX_CLIENTEDGE;
631 hwnd = CreateWindowEx(exwinmode, appname, appname,
632 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
633 guess_width, guess_height,
634 NULL, NULL, inst, NULL);
638 * Initialise the fonts, simultaneously correcting the guesses
639 * for font_{width,height}.
644 * Correct the guesses for extra_{width,height}.
648 GetWindowRect(hwnd, &wr);
649 GetClientRect(hwnd, &cr);
650 offset_width = offset_height = cfg.window_border;
651 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
652 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
656 * Resize the window, now we know what size we _really_ want it
659 guess_width = extra_width + font_width * term->cols;
660 guess_height = extra_height + font_height * term->rows;
661 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
662 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
665 * Set up a caret bitmap, with no content.
669 int size = (font_width + 15) / 16 * 2 * font_height;
670 bits = snewn(size, char);
671 memset(bits, 0, size);
672 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
675 CreateCaret(hwnd, caretbm, font_width, font_height);
678 * Initialise the scroll bar.
683 si.cbSize = sizeof(si);
684 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
686 si.nMax = term->rows - 1;
687 si.nPage = term->rows;
689 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
693 * Prepare the mouse handler.
695 lastact = MA_NOTHING;
696 lastbtn = MBT_NOTHING;
697 dbltime = GetDoubleClickTime();
700 * Set up the session-control options on the system menu.
707 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
708 popup_menus[CTXMENU].menu = CreatePopupMenu();
709 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
712 get_sesslist(&sesslist, TRUE);
713 /* skip sesslist.sessions[0] == Default Settings */
715 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
718 AppendMenu(s, MF_ENABLED, IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
719 sesslist.sessions[i]);
721 for (j = 0; j < lenof(popup_menus); j++) {
722 m = popup_menus[j].menu;
724 AppendMenu(m, MF_SEPARATOR, 0, 0);
725 popup_menus[j].specials_submenu_pos = GetMenuItemCount(m);
726 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
727 AppendMenu(m, MF_SEPARATOR, 0, 0);
728 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
729 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
730 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) s, "Sa&ved Sessions");
731 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
732 AppendMenu(m, MF_SEPARATOR, 0, 0);
733 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
734 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
735 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
736 AppendMenu(m, MF_SEPARATOR, 0, 0);
737 AppendMenu(m, (cfg.resize_action == RESIZE_DISABLED) ?
738 MF_GRAYED : MF_ENABLED, IDM_FULLSCREEN, "&Full Screen");
739 AppendMenu(m, MF_SEPARATOR, 0, 0);
741 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
742 str = dupprintf("&About %s", appname);
743 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
751 * Set up the initial input locale.
753 set_input_locale(GetKeyboardLayout(0));
756 * Open the initial log file if there is one.
761 * Finally show the window!
763 ShowWindow(hwnd, show);
764 SetForegroundWindow(hwnd);
767 * Set the palette up.
773 term->has_focus = (GetForegroundWindow() == hwnd);
776 if (GetMessage(&msg, NULL, 0, 0) == 1) {
777 while (msg.message != WM_QUIT) {
778 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
779 DispatchMessage(&msg);
780 /* Send the paste buffer if there's anything to send */
782 /* If there's nothing new in the queue then we can do everything
783 * we've delayed, reading the socket, writing, and repainting
786 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
789 /* The messages seem unreliable; especially if we're being tricky */
790 term->has_focus = (GetForegroundWindow() == hwnd);
792 net_pending_errors();
794 /* There's no point rescanning everything in the message queue
795 * so we do an apparently unnecessary wait here
798 if (GetMessage(&msg, NULL, 0, 0) != 1)
803 cleanup_exit(msg.wParam); /* this doesn't return... */
804 return msg.wParam; /* ... but optimiser doesn't know */
810 void cleanup_exit(int code)
821 if (cfg.protocol == PROT_SSH) {
832 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
834 char *do_select(SOCKET skt, int startup)
839 events = (FD_CONNECT | FD_READ | FD_WRITE |
840 FD_OOB | FD_CLOSE | FD_ACCEPT);
845 return "do_select(): internal error (hwnd==NULL)";
846 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
847 switch (p_WSAGetLastError()) {
849 return "Network is down";
851 return "WSAAsyncSelect(): unknown error";
858 * Update the Special Commands submenu.
860 void update_specials_menu(void *frontend)
863 int menu_already_exists = (specials != NULL);
867 specials = back->get_specials(backhandle);
872 /* We can't use Windows to provide a stack for submenus, so
873 * here's a lame "stack" that will do for now. */
874 HMENU saved_menu = NULL;
876 p = CreatePopupMenu();
877 for (i = 0; nesting > 0; i++) {
878 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
879 switch (specials[i].code) {
881 AppendMenu(p, MF_SEPARATOR, 0, 0);
886 saved_menu = p; /* XXX lame stacking */
887 p = CreatePopupMenu();
888 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
889 (UINT) p, specials[i].name);
894 p = saved_menu; /* XXX lame stacking */
899 AppendMenu(p, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
904 /* Squirrel the highest special. */
911 for (j = 0; j < lenof(popup_menus); j++) {
912 if (menu_already_exists) {
913 /* XXX does this free up all submenus? */
914 DeleteMenu(popup_menus[j].menu,
915 popup_menus[j].specials_submenu_pos,
917 DeleteMenu(popup_menus[j].menu,
918 popup_menus[j].specials_submenu_pos,
922 InsertMenu(popup_menus[j].menu,
923 popup_menus[j].specials_submenu_pos,
924 MF_BYPOSITION | MF_SEPARATOR, 0, 0);
925 InsertMenu(popup_menus[j].menu,
926 popup_menus[j].specials_submenu_pos,
927 MF_BYPOSITION | MF_POPUP | MF_ENABLED,
928 (UINT) p, "S&pecial Command");
934 * set or clear the "raw mouse message" mode
936 void set_raw_mouse_mode(void *frontend, int activate)
938 activate = activate && !cfg.no_mouse_rep;
939 send_raw_mouse = activate;
940 SetCursor(LoadCursor(NULL, activate ? IDC_ARROW : IDC_IBEAM));
944 * Print a message box and close the connection.
946 void connection_fatal(void *frontend, char *fmt, ...)
949 char *stuff, morestuff[100];
952 stuff = dupvprintf(fmt, ap);
954 sprintf(morestuff, "%.70s Fatal Error", appname);
955 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
958 if (cfg.close_on_exit == FORCE_ON)
966 * Report an error at the command-line parsing stage.
968 void cmdline_error(char *fmt, ...)
971 char *stuff, morestuff[100];
974 stuff = dupvprintf(fmt, ap);
976 sprintf(morestuff, "%.70s Command Line Error", appname);
977 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
983 * Actually do the job requested by a WM_NETEVENT
985 static void enact_netevent(WPARAM wParam, LPARAM lParam)
987 static int reentering = 0;
988 extern int select_result(WPARAM, LPARAM);
992 return; /* don't unpend the pending */
995 ret = select_result(wParam, lParam);
998 if (ret == 0 && !session_closed) {
999 /* Abnormal exits will already have set session_closed and taken
1000 * appropriate action. */
1001 if (cfg.close_on_exit == FORCE_ON ||
1002 cfg.close_on_exit == AUTO) PostQuitMessage(0);
1005 session_closed = TRUE;
1006 MessageBox(hwnd, "Connection closed by remote host",
1007 appname, MB_OK | MB_ICONINFORMATION);
1013 * Copy the colour palette from the configuration data into defpal.
1014 * This is non-trivial because the colour indices are different.
1016 static void cfgtopalette(void)
1019 static const int ww[] = {
1020 6, 7, 8, 9, 10, 11, 12, 13,
1021 14, 15, 16, 17, 18, 19, 20, 21,
1022 0, 1, 2, 3, 4, 4, 5, 5
1025 for (i = 0; i < 24; i++) {
1027 defpal[i].rgbtRed = cfg.colours[w][0];
1028 defpal[i].rgbtGreen = cfg.colours[w][1];
1029 defpal[i].rgbtBlue = cfg.colours[w][2];
1032 /* Override with system colours if appropriate */
1033 if (cfg.system_colour)
1038 * Override bit of defpal with colours from the system.
1039 * (NB that this takes a copy the system colours at the time this is called,
1040 * so subsequent colour scheme changes don't take effect. To fix that we'd
1041 * probably want to be using GetSysColorBrush() and the like.)
1043 static void systopalette(void)
1046 static const struct { int nIndex; int norm; int bold; } or[] =
1048 { COLOR_WINDOWTEXT, 16, 17 }, /* Default Foreground */
1049 { COLOR_WINDOW, 18, 19 }, /* Default Background */
1050 { COLOR_HIGHLIGHTTEXT, 20, 21 }, /* Cursor Text */
1051 { COLOR_HIGHLIGHT, 22, 23 }, /* Cursor Colour */
1054 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1055 COLORREF colour = GetSysColor(or[i].nIndex);
1056 defpal[or[i].norm].rgbtRed =
1057 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1058 defpal[or[i].norm].rgbtGreen =
1059 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1060 defpal[or[i].norm].rgbtBlue =
1061 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1066 * Set up the colour palette.
1068 static void init_palette(void)
1071 HDC hdc = GetDC(hwnd);
1073 if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1075 * This is a genuine case where we must use smalloc
1076 * because the snew macros can't cope.
1078 logpal = smalloc(sizeof(*logpal)
1079 - sizeof(logpal->palPalEntry)
1080 + NCOLOURS * sizeof(PALETTEENTRY));
1081 logpal->palVersion = 0x300;
1082 logpal->palNumEntries = NCOLOURS;
1083 for (i = 0; i < NCOLOURS; i++) {
1084 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1085 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1086 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1087 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1089 pal = CreatePalette(logpal);
1091 SelectPalette(hdc, pal, FALSE);
1092 RealizePalette(hdc);
1093 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1096 ReleaseDC(hwnd, hdc);
1099 for (i = 0; i < NCOLOURS; i++)
1100 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1101 defpal[i].rgbtGreen,
1102 defpal[i].rgbtBlue);
1104 for (i = 0; i < NCOLOURS; i++)
1105 colours[i] = RGB(defpal[i].rgbtRed,
1106 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1110 * This is a wrapper to ExtTextOut() to force Windows to display
1111 * the precise glyphs we give it. Otherwise it would do its own
1112 * bidi and Arabic shaping, and we would end up uncertain which
1113 * characters it had put where.
1115 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1116 unsigned short *lpString, UINT cbCount,
1117 CONST INT *lpDx, int opaque)
1121 char *buffer = snewn(cbCount*2+2, char);
1122 char *classbuffer = snewn(cbCount, char);
1123 memset(&gcpr, 0, sizeof(gcpr));
1124 memset(buffer, 0, cbCount*2+2);
1125 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1127 gcpr.lStructSize = sizeof(gcpr);
1128 gcpr.lpGlyphs = (void *)buffer;
1129 gcpr.lpClass = classbuffer;
1130 gcpr.nGlyphs = cbCount;
1132 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1133 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1135 ExtTextOut(hdc, x, y,
1136 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1137 lprc, buffer, cbCount, lpDx);
1141 * Initialise all the fonts we will need initially. There may be as many as
1142 * three or as few as one. The other (poentially) twentyone fonts are done
1143 * if/when they are needed.
1147 * - check the font width and height, correcting our guesses if
1150 * - verify that the bold font is the same width as the ordinary
1151 * one, and engage shadow bolding if not.
1153 * - verify that the underlined font is the same width as the
1154 * ordinary one (manual underlining by means of line drawing can
1155 * be done in a pinch).
1157 static void init_fonts(int pick_width, int pick_height)
1164 int fw_dontcare, fw_bold;
1166 for (i = 0; i < FONT_MAXNO; i++)
1169 bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
1170 und_mode = UND_FONT;
1172 if (cfg.font.isbold) {
1173 fw_dontcare = FW_BOLD;
1176 fw_dontcare = FW_DONTCARE;
1183 font_height = pick_height;
1185 font_height = cfg.font.height;
1186 if (font_height > 0) {
1188 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1191 font_width = pick_width;
1193 #define f(i,c,w,u) \
1194 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1195 c, OUT_DEFAULT_PRECIS, \
1196 CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, \
1197 FIXED_PITCH | FF_DONTCARE, cfg.font.name)
1199 f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);
1201 lfont.lfHeight = font_height;
1202 lfont.lfWidth = font_width;
1203 lfont.lfEscapement = 0;
1204 lfont.lfOrientation = 0;
1205 lfont.lfWeight = fw_dontcare;
1206 lfont.lfItalic = FALSE;
1207 lfont.lfUnderline = FALSE;
1208 lfont.lfStrikeOut = FALSE;
1209 lfont.lfCharSet = cfg.font.charset;
1210 lfont.lfOutPrecision = OUT_DEFAULT_PRECIS;
1211 lfont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1212 lfont.lfQuality = DEFAULT_QUALITY;
1213 lfont.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE;
1214 strncpy(lfont.lfFaceName, cfg.font.name, LF_FACESIZE);
1216 SelectObject(hdc, fonts[FONT_NORMAL]);
1217 GetTextMetrics(hdc, &tm);
1219 if (pick_width == 0 || pick_height == 0) {
1220 font_height = tm.tmHeight;
1221 font_width = tm.tmAveCharWidth;
1223 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1225 #ifdef RDB_DEBUG_PATCH
1226 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1227 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1232 DWORD cset = tm.tmCharSet;
1233 memset(&info, 0xFF, sizeof(info));
1235 /* !!! Yes the next line is right */
1236 if (cset == OEM_CHARSET)
1237 ucsdata.font_codepage = GetOEMCP();
1239 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1240 ucsdata.font_codepage = info.ciACP;
1242 ucsdata.font_codepage = -1;
1244 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1245 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1248 f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);
1251 * Some fonts, e.g. 9-pt Courier, draw their underlines
1252 * outside their character cell. We successfully prevent
1253 * screen corruption by clipping the text output, but then
1254 * we lose the underline completely. Here we try to work
1255 * out whether this is such a font, and if it is, we set a
1256 * flag that causes underlines to be drawn by hand.
1258 * Having tried other more sophisticated approaches (such
1259 * as examining the TEXTMETRIC structure or requesting the
1260 * height of a string), I think we'll do this the brute
1261 * force way: we create a small bitmap, draw an underlined
1262 * space on it, and test to see whether any pixels are
1263 * foreground-coloured. (Since we expect the underline to
1264 * go all the way across the character cell, we only search
1265 * down a single column of the bitmap, half way across.)
1269 HBITMAP und_bm, und_oldbm;
1273 und_dc = CreateCompatibleDC(hdc);
1274 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1275 und_oldbm = SelectObject(und_dc, und_bm);
1276 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1277 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1278 SetTextColor(und_dc, RGB(255, 255, 255));
1279 SetBkColor(und_dc, RGB(0, 0, 0));
1280 SetBkMode(und_dc, OPAQUE);
1281 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1283 for (i = 0; i < font_height; i++) {
1284 c = GetPixel(und_dc, font_width / 2, i);
1285 if (c != RGB(0, 0, 0))
1288 SelectObject(und_dc, und_oldbm);
1289 DeleteObject(und_bm);
1292 und_mode = UND_LINE;
1293 DeleteObject(fonts[FONT_UNDERLINE]);
1294 fonts[FONT_UNDERLINE] = 0;
1298 if (bold_mode == BOLD_FONT) {
1299 f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);
1303 descent = tm.tmAscent + 1;
1304 if (descent >= font_height)
1305 descent = font_height - 1;
1307 for (i = 0; i < 3; i++) {
1309 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1310 fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
1317 ReleaseDC(hwnd, hdc);
1319 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1320 und_mode = UND_LINE;
1321 DeleteObject(fonts[FONT_UNDERLINE]);
1322 fonts[FONT_UNDERLINE] = 0;
1325 if (bold_mode == BOLD_FONT &&
1326 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1327 bold_mode = BOLD_SHADOW;
1328 DeleteObject(fonts[FONT_BOLD]);
1329 fonts[FONT_BOLD] = 0;
1331 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1333 init_ucs(&cfg, &ucsdata);
1336 static void another_font(int fontno)
1339 int fw_dontcare, fw_bold;
1343 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1346 basefont = (fontno & ~(FONT_BOLDUND));
1347 if (basefont != fontno && !fontflag[basefont])
1348 another_font(basefont);
1350 if (cfg.font.isbold) {
1351 fw_dontcare = FW_BOLD;
1354 fw_dontcare = FW_DONTCARE;
1358 c = cfg.font.charset;
1364 if (fontno & FONT_WIDE)
1366 if (fontno & FONT_NARROW)
1368 if (fontno & FONT_OEM)
1370 if (fontno & FONT_BOLD)
1372 if (fontno & FONT_UNDERLINE)
1376 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1377 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1378 CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
1379 FIXED_PITCH | FF_DONTCARE, s);
1381 fontflag[fontno] = 1;
1384 static void deinit_fonts(void)
1387 for (i = 0; i < FONT_MAXNO; i++) {
1389 DeleteObject(fonts[i]);
1395 void request_resize(void *frontend, int w, int h)
1399 /* If the window is maximized supress resizing attempts */
1400 if (IsZoomed(hwnd)) {
1401 if (cfg.resize_action == RESIZE_TERM)
1405 if (cfg.resize_action == RESIZE_DISABLED) return;
1406 if (h == term->rows && w == term->cols) return;
1408 /* Sanity checks ... */
1410 static int first_time = 1;
1413 switch (first_time) {
1415 /* Get the size of the screen */
1416 if (get_fullscreen_rect(&ss))
1417 /* first_time = 0 */ ;
1423 /* Make sure the values are sane */
1424 width = (ss.right - ss.left - extra_width) / 4;
1425 height = (ss.bottom - ss.top - extra_height) / 6;
1427 if (w > width || h > height)
1436 term_size(term, h, w, cfg.savelines);
1438 if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {
1439 width = extra_width + font_width * w;
1440 height = extra_height + font_height * h;
1442 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1443 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1444 SWP_NOMOVE | SWP_NOZORDER);
1448 InvalidateRect(hwnd, NULL, TRUE);
1451 static void reset_window(int reinit) {
1453 * This function decides how to resize or redraw when the
1454 * user changes something.
1456 * This function doesn't like to change the terminal size but if the
1457 * font size is locked that may be it's only soluion.
1459 int win_width, win_height;
1462 #ifdef RDB_DEBUG_PATCH
1463 debug((27, "reset_window()"));
1466 /* Current window sizes ... */
1467 GetWindowRect(hwnd, &wr);
1468 GetClientRect(hwnd, &cr);
1470 win_width = cr.right - cr.left;
1471 win_height = cr.bottom - cr.top;
1473 if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;
1475 /* Are we being forced to reload the fonts ? */
1477 #ifdef RDB_DEBUG_PATCH
1478 debug((27, "reset_window() -- Forced deinit"));
1484 /* Oh, looks like we're minimised */
1485 if (win_width == 0 || win_height == 0)
1488 /* Is the window out of position ? */
1490 (offset_width != (win_width-font_width*term->cols)/2 ||
1491 offset_height != (win_height-font_height*term->rows)/2) ){
1492 offset_width = (win_width-font_width*term->cols)/2;
1493 offset_height = (win_height-font_height*term->rows)/2;
1494 InvalidateRect(hwnd, NULL, TRUE);
1495 #ifdef RDB_DEBUG_PATCH
1496 debug((27, "reset_window() -> Reposition terminal"));
1500 if (IsZoomed(hwnd)) {
1501 /* We're fullscreen, this means we must not change the size of
1502 * the window so it's the font size or the terminal itself.
1505 extra_width = wr.right - wr.left - cr.right + cr.left;
1506 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1508 if (cfg.resize_action != RESIZE_TERM) {
1509 if ( font_width != win_width/term->cols ||
1510 font_height != win_height/term->rows) {
1512 init_fonts(win_width/term->cols, win_height/term->rows);
1513 offset_width = (win_width-font_width*term->cols)/2;
1514 offset_height = (win_height-font_height*term->rows)/2;
1515 InvalidateRect(hwnd, NULL, TRUE);
1516 #ifdef RDB_DEBUG_PATCH
1517 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1518 font_width, font_height));
1522 if ( font_width != win_width/term->cols ||
1523 font_height != win_height/term->rows) {
1524 /* Our only choice at this point is to change the
1525 * size of the terminal; Oh well.
1527 term_size(term, win_height/font_height, win_width/font_width,
1529 offset_width = (win_width-font_width*term->cols)/2;
1530 offset_height = (win_height-font_height*term->rows)/2;
1531 InvalidateRect(hwnd, NULL, TRUE);
1532 #ifdef RDB_DEBUG_PATCH
1533 debug((27, "reset_window() -> Zoomed term_size"));
1540 /* Hmm, a force re-init means we should ignore the current window
1541 * so we resize to the default font size.
1544 #ifdef RDB_DEBUG_PATCH
1545 debug((27, "reset_window() -> Forced re-init"));
1548 offset_width = offset_height = cfg.window_border;
1549 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1550 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1552 if (win_width != font_width*term->cols + offset_width*2 ||
1553 win_height != font_height*term->rows + offset_height*2) {
1555 /* If this is too large windows will resize it to the maximum
1556 * allowed window size, we will then be back in here and resize
1557 * the font or terminal to fit.
1559 SetWindowPos(hwnd, NULL, 0, 0,
1560 font_width*term->cols + extra_width,
1561 font_height*term->rows + extra_height,
1562 SWP_NOMOVE | SWP_NOZORDER);
1565 InvalidateRect(hwnd, NULL, TRUE);
1569 /* Okay the user doesn't want us to change the font so we try the
1570 * window. But that may be too big for the screen which forces us
1571 * to change the terminal.
1573 if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||
1574 (cfg.resize_action == RESIZE_EITHER && reinit<0) ||
1576 offset_width = offset_height = cfg.window_border;
1577 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1578 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1580 if (win_width != font_width*term->cols + offset_width*2 ||
1581 win_height != font_height*term->rows + offset_height*2) {
1586 get_fullscreen_rect(&ss);
1588 width = (ss.right - ss.left - extra_width) / font_width;
1589 height = (ss.bottom - ss.top - extra_height) / font_height;
1592 if ( term->rows > height || term->cols > width ) {
1593 if (cfg.resize_action == RESIZE_EITHER) {
1594 /* Make the font the biggest we can */
1595 if (term->cols > width)
1596 font_width = (ss.right - ss.left - extra_width)
1598 if (term->rows > height)
1599 font_height = (ss.bottom - ss.top - extra_height)
1603 init_fonts(font_width, font_height);
1605 width = (ss.right - ss.left - extra_width) / font_width;
1606 height = (ss.bottom - ss.top - extra_height) / font_height;
1608 if ( height > term->rows ) height = term->rows;
1609 if ( width > term->cols ) width = term->cols;
1610 term_size(term, height, width, cfg.savelines);
1611 #ifdef RDB_DEBUG_PATCH
1612 debug((27, "reset_window() -> term resize to (%d,%d)",
1618 SetWindowPos(hwnd, NULL, 0, 0,
1619 font_width*term->cols + extra_width,
1620 font_height*term->rows + extra_height,
1621 SWP_NOMOVE | SWP_NOZORDER);
1623 InvalidateRect(hwnd, NULL, TRUE);
1624 #ifdef RDB_DEBUG_PATCH
1625 debug((27, "reset_window() -> window resize to (%d,%d)",
1626 font_width*term->cols + extra_width,
1627 font_height*term->rows + extra_height));
1633 /* We're allowed to or must change the font but do we want to ? */
1635 if (font_width != (win_width-cfg.window_border*2)/term->cols ||
1636 font_height != (win_height-cfg.window_border*2)/term->rows) {
1639 init_fonts((win_width-cfg.window_border*2)/term->cols,
1640 (win_height-cfg.window_border*2)/term->rows);
1641 offset_width = (win_width-font_width*term->cols)/2;
1642 offset_height = (win_height-font_height*term->rows)/2;
1644 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1645 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1647 InvalidateRect(hwnd, NULL, TRUE);
1648 #ifdef RDB_DEBUG_PATCH
1649 debug((25, "reset_window() -> font resize to (%d,%d)",
1650 font_width, font_height));
1655 static void set_input_locale(HKL kl)
1659 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1660 lbuf, sizeof(lbuf));
1662 kbd_codepage = atoi(lbuf);
1665 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1667 int thistime = GetMessageTime();
1669 if (send_raw_mouse && !(cfg.mouse_override && shift)) {
1670 lastbtn = MBT_NOTHING;
1671 term_mouse(term, b, translate_button(b), MA_CLICK,
1672 x, y, shift, ctrl, alt);
1676 if (lastbtn == b && thistime - lasttime < dbltime) {
1677 lastact = (lastact == MA_CLICK ? MA_2CLK :
1678 lastact == MA_2CLK ? MA_3CLK :
1679 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1684 if (lastact != MA_NOTHING)
1685 term_mouse(term, b, translate_button(b), lastact,
1686 x, y, shift, ctrl, alt);
1687 lasttime = thistime;
1691 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1692 * into a cooked one (SELECT, EXTEND, PASTE).
1694 static Mouse_Button translate_button(Mouse_Button button)
1696 if (button == MBT_LEFT)
1698 if (button == MBT_MIDDLE)
1699 return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
1700 if (button == MBT_RIGHT)
1701 return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
1702 return 0; /* shouldn't happen */
1705 static void show_mouseptr(int show)
1707 static int cursor_visible = 1;
1708 if (!cfg.hide_mouseptr) /* override if this feature disabled */
1710 if (cursor_visible && !show)
1712 else if (!cursor_visible && show)
1714 cursor_visible = show;
1717 static int is_alt_pressed(void)
1720 int r = GetKeyboardState(keystate);
1723 if (keystate[VK_MENU] & 0x80)
1725 if (keystate[VK_RMENU] & 0x80)
1730 static int is_shift_pressed(void)
1733 int r = GetKeyboardState(keystate);
1736 if (keystate[VK_SHIFT] & 0x80)
1741 static int resizing;
1743 void notify_remote_exit(void *fe) { /* stub not needed in this frontend */ }
1745 void timer_change_notify(long next)
1747 long ticks = next - GETTICKCOUNT();
1748 if (ticks <= 0) ticks = 1; /* just in case */
1749 KillTimer(hwnd, TIMING_TIMER_ID);
1750 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
1751 timing_next_time = next;
1754 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1755 WPARAM wParam, LPARAM lParam)
1758 static int ignore_clip = FALSE;
1759 static int need_backend_resize = FALSE;
1760 static int fullscr_on_max = FALSE;
1761 static UINT last_mousemove = 0;
1765 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
1768 KillTimer(hwnd, TIMING_TIMER_ID);
1769 if (run_timers(timing_next_time, &next)) {
1770 timer_change_notify(next);
1781 str = dupprintf("%s Exit Confirmation", appname);
1782 if (!cfg.warn_on_close || session_closed ||
1784 "Are you sure you want to close this session?",
1785 str, MB_ICONWARNING | MB_OKCANCEL) == IDOK)
1786 DestroyWindow(hwnd);
1796 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
1808 PROCESS_INFORMATION pi;
1809 HANDLE filemap = NULL;
1811 if (wParam == IDM_DUPSESS) {
1813 * Allocate a file-mapping memory chunk for the
1816 SECURITY_ATTRIBUTES sa;
1819 sa.nLength = sizeof(sa);
1820 sa.lpSecurityDescriptor = NULL;
1821 sa.bInheritHandle = TRUE;
1822 filemap = CreateFileMapping((HANDLE) 0xFFFFFFFF,
1825 0, sizeof(Config), NULL);
1827 p = (Config *) MapViewOfFile(filemap,
1829 0, 0, sizeof(Config));
1831 *p = cfg; /* structure copy */
1835 sprintf(c, "putty &%p", filemap);
1837 } else if (wParam == IDM_SAVEDSESS) {
1838 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
1839 / MENU_SAVED_STEP) + 1;
1840 if (sessno < sesslist.nsessions) {
1841 char *session = sesslist.sessions[sessno];
1842 /* XXX spaces? quotes? "-load"? */
1843 cl = dupprintf("putty @%s", session);
1850 GetModuleFileName(NULL, b, sizeof(b) - 1);
1852 si.lpReserved = NULL;
1853 si.lpDesktop = NULL;
1857 si.lpReserved2 = NULL;
1858 CreateProcess(b, cl, NULL, NULL, TRUE,
1859 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
1862 CloseHandle(filemap);
1869 logevent(NULL, "----- Session restarted -----");
1879 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
1882 if (!do_reconfig(hwnd))
1886 /* Disable full-screen if resizing forbidden */
1887 HMENU m = GetSystemMenu (hwnd, FALSE);
1888 EnableMenuItem(m, IDM_FULLSCREEN, MF_BYCOMMAND |
1889 (cfg.resize_action == RESIZE_DISABLED)
1890 ? MF_GRAYED : MF_ENABLED);
1891 /* Gracefully unzoom if necessary */
1892 if (IsZoomed(hwnd) &&
1893 (cfg.resize_action == RESIZE_DISABLED)) {
1894 ShowWindow(hwnd, SW_RESTORE);
1898 /* Pass new config data to the logging module */
1899 log_reconfig(logctx, &cfg);
1903 * Flush the line discipline's edit buffer in the
1904 * case where local editing has just been disabled.
1907 ldisc_send(ldisc, NULL, 0, 0);
1915 /* Pass new config data to the terminal */
1916 term_reconfig(term, &cfg);
1918 /* Pass new config data to the back end */
1920 back->reconfig(backhandle, &cfg);
1922 /* Screen size changed ? */
1923 if (cfg.height != prev_cfg.height ||
1924 cfg.width != prev_cfg.width ||
1925 cfg.savelines != prev_cfg.savelines ||
1926 cfg.resize_action == RESIZE_FONT ||
1927 (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
1928 cfg.resize_action == RESIZE_DISABLED)
1929 term_size(term, cfg.height, cfg.width, cfg.savelines);
1931 /* Enable or disable the scroll bar, etc */
1933 LONG nflg, flag = GetWindowLong(hwnd, GWL_STYLE);
1934 LONG nexflag, exflag =
1935 GetWindowLong(hwnd, GWL_EXSTYLE);
1938 if (cfg.alwaysontop != prev_cfg.alwaysontop) {
1939 if (cfg.alwaysontop) {
1940 nexflag |= WS_EX_TOPMOST;
1941 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
1942 SWP_NOMOVE | SWP_NOSIZE);
1944 nexflag &= ~(WS_EX_TOPMOST);
1945 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
1946 SWP_NOMOVE | SWP_NOSIZE);
1949 if (cfg.sunken_edge)
1950 nexflag |= WS_EX_CLIENTEDGE;
1952 nexflag &= ~(WS_EX_CLIENTEDGE);
1955 if (is_full_screen() ?
1956 cfg.scrollbar_in_fullscreen : cfg.scrollbar)
1959 nflg &= ~WS_VSCROLL;
1961 if (cfg.resize_action == RESIZE_DISABLED ||
1963 nflg &= ~WS_THICKFRAME;
1965 nflg |= WS_THICKFRAME;
1967 if (cfg.resize_action == RESIZE_DISABLED)
1968 nflg &= ~WS_MAXIMIZEBOX;
1970 nflg |= WS_MAXIMIZEBOX;
1972 if (nflg != flag || nexflag != exflag) {
1974 SetWindowLong(hwnd, GWL_STYLE, nflg);
1975 if (nexflag != exflag)
1976 SetWindowLong(hwnd, GWL_EXSTYLE, nexflag);
1978 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
1979 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1980 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
1988 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
1993 set_title(NULL, cfg.wintitle);
1994 if (IsIconic(hwnd)) {
1996 cfg.win_name_always ? window_name :
2000 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
2001 strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
2002 cfg.font.isbold != prev_cfg.font.isbold ||
2003 cfg.font.height != prev_cfg.font.height ||
2004 cfg.font.charset != prev_cfg.font.charset ||
2005 cfg.vtmode != prev_cfg.vtmode ||
2006 cfg.bold_colour != prev_cfg.bold_colour ||
2007 cfg.resize_action == RESIZE_DISABLED ||
2008 cfg.resize_action == RESIZE_EITHER ||
2009 (cfg.resize_action != prev_cfg.resize_action))
2012 InvalidateRect(hwnd, NULL, TRUE);
2013 reset_window(init_lvl);
2014 net_pending_errors();
2021 term_do_paste(term);
2029 ldisc_send(ldisc, NULL, 0, 0);
2035 WinHelp(hwnd, help_path,
2036 help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
2040 * We get this if the System menu has been activated
2047 * We get this if the System menu has been activated
2048 * using the keyboard. This might happen from within
2049 * TranslateKey, in which case it really wants to be
2050 * followed by a `space' character to actually _bring
2051 * the menu up_ rather than just sitting there in
2052 * `ready to appear' state.
2054 show_mouseptr(1); /* make sure pointer is visible */
2056 PostMessage(hwnd, WM_CHAR, ' ', 0);
2058 case IDM_FULLSCREEN:
2062 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2063 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2065 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2066 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2068 * Ensure we haven't been sent a bogus SYSCOMMAND
2069 * which would cause us to reference invalid memory
2070 * and crash. Perhaps I'm just too paranoid here.
2072 if (i >= n_specials)
2075 back->special(backhandle, specials[i].code);
2076 net_pending_errors();
2081 #define X_POS(l) ((int)(short)LOWORD(l))
2082 #define Y_POS(l) ((int)(short)HIWORD(l))
2084 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2085 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2086 case WM_LBUTTONDOWN:
2087 case WM_MBUTTONDOWN:
2088 case WM_RBUTTONDOWN:
2092 if (message == WM_RBUTTONDOWN &&
2093 ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
2096 show_mouseptr(1); /* make sure pointer is visible */
2097 GetCursorPos(&cursorpos);
2098 TrackPopupMenu(popup_menus[CTXMENU].menu,
2099 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2100 cursorpos.x, cursorpos.y,
2108 case WM_LBUTTONDOWN:
2112 case WM_MBUTTONDOWN:
2113 button = MBT_MIDDLE;
2116 case WM_RBUTTONDOWN:
2125 button = MBT_MIDDLE;
2133 button = press = 0; /* shouldn't happen */
2137 * Special case: in full-screen mode, if the left
2138 * button is clicked in the very top left corner of the
2139 * window, we put up the System menu instead of doing
2143 char mouse_on_hotspot = 0;
2152 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2155 mi.cbSize = sizeof(MONITORINFO);
2156 GetMonitorInfo(mon, &mi);
2158 if (mi.rcMonitor.left == pt.x &&
2159 mi.rcMonitor.top == pt.y) {
2160 mouse_on_hotspot = 1;
2165 if (pt.x == 0 && pt.y == 0) {
2166 mouse_on_hotspot = 1;
2169 if (is_full_screen() && press &&
2170 button == MBT_LEFT && mouse_on_hotspot) {
2171 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2172 MAKELPARAM(pt.x, pt.y));
2179 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2180 wParam & MK_SHIFT, wParam & MK_CONTROL,
2184 term_mouse(term, button, translate_button(button), MA_RELEASE,
2185 TO_CHR_X(X_POS(lParam)),
2186 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2187 wParam & MK_CONTROL, is_alt_pressed());
2195 * Windows seems to like to occasionally send MOUSEMOVE
2196 * events even if the mouse hasn't moved. Don't unhide
2197 * the mouse pointer in this case.
2199 static WPARAM wp = 0;
2200 static LPARAM lp = 0;
2201 if (wParam != wp || lParam != lp ||
2202 last_mousemove != WM_MOUSEMOVE) {
2204 wp = wParam; lp = lParam;
2205 last_mousemove = WM_MOUSEMOVE;
2209 * Add the mouse position and message time to the random
2212 noise_ultralight(lParam);
2214 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2215 GetCapture() == hwnd) {
2217 if (wParam & MK_LBUTTON)
2219 else if (wParam & MK_MBUTTON)
2223 term_mouse(term, b, translate_button(b), MA_DRAG,
2224 TO_CHR_X(X_POS(lParam)),
2225 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2226 wParam & MK_CONTROL, is_alt_pressed());
2229 case WM_NCMOUSEMOVE:
2231 static WPARAM wp = 0;
2232 static LPARAM lp = 0;
2233 if (wParam != wp || lParam != lp ||
2234 last_mousemove != WM_NCMOUSEMOVE) {
2236 wp = wParam; lp = lParam;
2237 last_mousemove = WM_NCMOUSEMOVE;
2240 noise_ultralight(lParam);
2242 case WM_IGNORE_CLIP:
2243 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2245 case WM_DESTROYCLIPBOARD:
2247 term_deselect(term);
2248 ignore_clip = FALSE;
2255 hdc = BeginPaint(hwnd, &p);
2257 SelectPalette(hdc, pal, TRUE);
2258 RealizePalette(hdc);
2261 term_paint(term, hdc,
2262 (p.rcPaint.left-offset_width)/font_width,
2263 (p.rcPaint.top-offset_height)/font_height,
2264 (p.rcPaint.right-offset_width-1)/font_width,
2265 (p.rcPaint.bottom-offset_height-1)/font_height,
2269 p.rcPaint.left < offset_width ||
2270 p.rcPaint.top < offset_height ||
2271 p.rcPaint.right >= offset_width + font_width*term->cols ||
2272 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2274 HBRUSH fillcolour, oldbrush;
2276 fillcolour = CreateSolidBrush (
2277 colours[(ATTR_DEFBG>>ATTR_BGSHIFT)*2]);
2278 oldbrush = SelectObject(hdc, fillcolour);
2279 edge = CreatePen(PS_SOLID, 0,
2280 colours[(ATTR_DEFBG>>ATTR_BGSHIFT)*2]);
2281 oldpen = SelectObject(hdc, edge);
2284 * Jordan Russell reports that this apparently
2285 * ineffectual IntersectClipRect() call masks a
2286 * Windows NT/2K bug causing strange display
2287 * problems when the PuTTY window is taller than
2288 * the primary monitor. It seems harmless enough...
2290 IntersectClipRect(hdc,
2291 p.rcPaint.left, p.rcPaint.top,
2292 p.rcPaint.right, p.rcPaint.bottom);
2294 ExcludeClipRect(hdc,
2295 offset_width, offset_height,
2296 offset_width+font_width*term->cols,
2297 offset_height+font_height*term->rows);
2299 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2300 p.rcPaint.right, p.rcPaint.bottom);
2302 // SelectClipRgn(hdc, NULL);
2304 SelectObject(hdc, oldbrush);
2305 DeleteObject(fillcolour);
2306 SelectObject(hdc, oldpen);
2309 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2310 SelectObject(hdc, GetStockObject(WHITE_PEN));
2316 enact_netevent(wParam, lParam);
2317 net_pending_errors();
2320 term->has_focus = TRUE;
2321 CreateCaret(hwnd, caretbm, font_width, font_height);
2323 flash_window(0); /* stop */
2329 term->has_focus = FALSE;
2331 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2334 case WM_ENTERSIZEMOVE:
2335 #ifdef RDB_DEBUG_PATCH
2336 debug((27, "WM_ENTERSIZEMOVE"));
2340 need_backend_resize = FALSE;
2342 case WM_EXITSIZEMOVE:
2345 #ifdef RDB_DEBUG_PATCH
2346 debug((27, "WM_EXITSIZEMOVE"));
2348 if (need_backend_resize) {
2349 term_size(term, cfg.height, cfg.width, cfg.savelines);
2350 InvalidateRect(hwnd, NULL, TRUE);
2355 * This does two jobs:
2356 * 1) Keep the sizetip uptodate
2357 * 2) Make sure the window size is _stepped_ in units of the font size.
2359 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2360 int width, height, w, h, ew, eh;
2361 LPRECT r = (LPRECT) lParam;
2363 if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
2364 (cfg.height != term->rows || cfg.width != term->cols )) {
2366 * Great! It seems that both the terminal size and the
2367 * font size have been changed and the user is now dragging.
2369 * It will now be difficult to get back to the configured
2372 * This would be easier but it seems to be too confusing.
2374 term_size(term, cfg.height, cfg.width, cfg.savelines);
2377 cfg.height=term->rows; cfg.width=term->cols;
2379 InvalidateRect(hwnd, NULL, TRUE);
2380 need_backend_resize = TRUE;
2383 width = r->right - r->left - extra_width;
2384 height = r->bottom - r->top - extra_height;
2385 w = (width + font_width / 2) / font_width;
2388 h = (height + font_height / 2) / font_height;
2391 UpdateSizeTip(hwnd, w, h);
2392 ew = width - w * font_width;
2393 eh = height - h * font_height;
2395 if (wParam == WMSZ_LEFT ||
2396 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2402 if (wParam == WMSZ_TOP ||
2403 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2413 int width, height, w, h, rv = 0;
2414 int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2415 int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2416 LPRECT r = (LPRECT) lParam;
2418 width = r->right - r->left - ex_width;
2419 height = r->bottom - r->top - ex_height;
2421 w = (width + term->cols/2)/term->cols;
2422 h = (height + term->rows/2)/term->rows;
2423 if ( r->right != r->left + w*term->cols + ex_width)
2426 if (wParam == WMSZ_LEFT ||
2427 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2428 r->left = r->right - w*term->cols - ex_width;
2430 r->right = r->left + w*term->cols + ex_width;
2432 if (r->bottom != r->top + h*term->rows + ex_height)
2435 if (wParam == WMSZ_TOP ||
2436 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2437 r->top = r->bottom - h*term->rows - ex_height;
2439 r->bottom = r->top + h*term->rows + ex_height;
2443 /* break; (never reached) */
2444 case WM_FULLSCR_ON_MAX:
2445 fullscr_on_max = TRUE;
2448 sys_cursor_update();
2451 #ifdef RDB_DEBUG_PATCH
2452 debug((27, "WM_SIZE %s (%d,%d)",
2453 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2454 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2455 (wParam == SIZE_RESTORED && resizing) ? "to":
2456 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2458 LOWORD(lParam), HIWORD(lParam)));
2460 if (wParam == SIZE_MINIMIZED)
2462 cfg.win_name_always ? window_name : icon_name);
2463 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2464 SetWindowText(hwnd, window_name);
2465 if (wParam == SIZE_RESTORED)
2466 clear_full_screen();
2467 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2468 fullscr_on_max = FALSE;
2472 if (cfg.resize_action == RESIZE_DISABLED) {
2473 /* A resize, well it better be a minimize. */
2477 int width, height, w, h;
2479 width = LOWORD(lParam);
2480 height = HIWORD(lParam);
2483 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2485 prev_rows = term->rows;
2486 prev_cols = term->cols;
2487 if (cfg.resize_action == RESIZE_TERM) {
2488 w = width / font_width;
2490 h = height / font_height;
2493 term_size(term, h, w, cfg.savelines);
2496 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2498 if (cfg.resize_action == RESIZE_TERM)
2499 term_size(term, prev_rows, prev_cols, cfg.savelines);
2500 if (cfg.resize_action != RESIZE_FONT)
2505 /* This is an unexpected resize, these will normally happen
2506 * if the window is too large. Probably either the user
2507 * selected a huge font or the screen size has changed.
2509 * This is also called with minimize.
2511 else reset_window(-1);
2515 * Don't call back->size in mid-resize. (To prevent
2516 * massive numbers of resize events getting sent
2517 * down the connection during an NT opaque drag.)
2520 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2521 need_backend_resize = TRUE;
2522 w = (width-cfg.window_border*2) / font_width;
2524 h = (height-cfg.window_border*2) / font_height;
2533 sys_cursor_update();
2536 switch (LOWORD(wParam)) {
2538 term_scroll(term, -1, 0);
2541 term_scroll(term, +1, 0);
2544 term_scroll(term, 0, +1);
2547 term_scroll(term, 0, -1);
2550 term_scroll(term, 0, +term->rows / 2);
2553 term_scroll(term, 0, -term->rows / 2);
2555 case SB_THUMBPOSITION:
2557 term_scroll(term, 1, HIWORD(wParam));
2561 case WM_PALETTECHANGED:
2562 if ((HWND) wParam != hwnd && pal != NULL) {
2563 HDC hdc = get_ctx(NULL);
2565 if (RealizePalette(hdc) > 0)
2571 case WM_QUERYNEWPALETTE:
2573 HDC hdc = get_ctx(NULL);
2575 if (RealizePalette(hdc) > 0)
2587 * Add the scan code and keypress timing to the random
2590 noise_ultralight(lParam);
2593 * We don't do TranslateMessage since it disassociates the
2594 * resulting CHAR message from the KEYDOWN that sparked it,
2595 * which we occasionally don't want. Instead, we process
2596 * KEYDOWN, and call the Win32 translator functions so that
2597 * we get the translations under _our_ control.
2600 unsigned char buf[20];
2603 if (wParam == VK_PROCESSKEY) {
2606 m.message = WM_KEYDOWN;
2608 m.lParam = lParam & 0xdfff;
2609 TranslateMessage(&m);
2611 len = TranslateKey(message, wParam, lParam, buf);
2613 return DefWindowProc(hwnd, message, wParam, lParam);
2617 * Interrupt an ongoing paste. I'm not sure
2618 * this is sensible, but for the moment it's
2619 * preferable to having to faff about buffering
2625 * We need not bother about stdin backlogs
2626 * here, because in GUI PuTTY we can't do
2627 * anything about it anyway; there's no means
2628 * of asking Windows to hold off on KEYDOWN
2629 * messages. We _have_ to buffer everything
2632 term_seen_key_event(term);
2634 ldisc_send(ldisc, buf, len, 1);
2639 net_pending_errors();
2641 case WM_INPUTLANGCHANGE:
2642 /* wParam == Font number */
2643 /* lParam == Locale */
2644 set_input_locale((HKL)lParam);
2645 sys_cursor_update();
2648 if(wParam == IMN_SETOPENSTATUS) {
2649 HIMC hImc = ImmGetContext(hwnd);
2650 ImmSetCompositionFont(hImc, &lfont);
2651 ImmReleaseContext(hwnd, hImc);
2655 case WM_IME_COMPOSITION:
2661 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
2662 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2664 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2665 break; /* fall back to DefWindowProc */
2667 hIMC = ImmGetContext(hwnd);
2668 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2672 buff = snewn(n, char);
2673 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
2675 * Jaeyoun Chung reports that Korean character
2676 * input doesn't work correctly if we do a single
2677 * luni_send() covering the whole of buff. So
2678 * instead we luni_send the characters one by one.
2680 term_seen_key_event(term);
2681 for (i = 0; i < n; i += 2) {
2683 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2687 ImmReleaseContext(hwnd, hIMC);
2692 if (wParam & 0xFF00) {
2693 unsigned char buf[2];
2696 buf[0] = wParam >> 8;
2697 term_seen_key_event(term);
2699 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
2701 char c = (unsigned char) wParam;
2702 term_seen_key_event(term);
2704 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
2710 * Nevertheless, we are prepared to deal with WM_CHAR
2711 * messages, should they crop up. So if someone wants to
2712 * post the things to us as part of a macro manoeuvre,
2713 * we're ready to cope.
2716 char c = (unsigned char)wParam;
2717 term_seen_key_event(term);
2719 lpage_send(ldisc, CP_ACP, &c, 1, 1);
2723 if (send_raw_mouse && LOWORD(lParam) == HTCLIENT) {
2724 SetCursor(LoadCursor(NULL, IDC_ARROW));
2728 case WM_SYSCOLORCHANGE:
2729 if (cfg.system_colour) {
2730 /* Refresh palette from system colours. */
2731 /* XXX actually this zaps the entire palette. */
2734 /* Force a repaint of the terminal window. */
2735 term_invalidate(term);
2738 case WM_AGENT_CALLBACK:
2740 struct agent_callback *c = (struct agent_callback *)lParam;
2741 c->callback(c->callback_ctx, c->data, c->len);
2746 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
2747 int shift_pressed=0, control_pressed=0;
2749 if (message == WM_MOUSEWHEEL) {
2750 wheel_accumulator += (short)HIWORD(wParam);
2751 shift_pressed=LOWORD(wParam) & MK_SHIFT;
2752 control_pressed=LOWORD(wParam) & MK_CONTROL;
2755 wheel_accumulator += (int)wParam;
2756 if (GetKeyboardState(keys)!=0) {
2757 shift_pressed=keys[VK_SHIFT]&0x80;
2758 control_pressed=keys[VK_CONTROL]&0x80;
2762 /* process events when the threshold is reached */
2763 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
2766 /* reduce amount for next time */
2767 if (wheel_accumulator > 0) {
2769 wheel_accumulator -= WHEEL_DELTA;
2770 } else if (wheel_accumulator < 0) {
2772 wheel_accumulator += WHEEL_DELTA;
2776 if (send_raw_mouse &&
2777 !(cfg.mouse_override && shift_pressed)) {
2778 /* send a mouse-down followed by a mouse up */
2779 term_mouse(term, b, translate_button(b),
2781 TO_CHR_X(X_POS(lParam)),
2782 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2783 control_pressed, is_alt_pressed());
2784 term_mouse(term, b, translate_button(b),
2785 MA_RELEASE, TO_CHR_X(X_POS(lParam)),
2786 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2787 control_pressed, is_alt_pressed());
2789 /* trigger a scroll */
2790 term_scroll(term, 0,
2792 -term->rows / 2 : term->rows / 2);
2799 return DefWindowProc(hwnd, message, wParam, lParam);
2803 * Move the system caret. (We maintain one, even though it's
2804 * invisible, for the benefit of blind people: apparently some
2805 * helper software tracks the system caret, so we should arrange to
2808 void sys_cursor(void *frontend, int x, int y)
2812 if (!term->has_focus) return;
2815 * Avoid gratuitously re-updating the cursor position and IMM
2816 * window if there's no actual change required.
2818 cx = x * font_width + offset_width;
2819 cy = y * font_height + offset_height;
2820 if (cx == caret_x && cy == caret_y)
2825 sys_cursor_update();
2828 static void sys_cursor_update(void)
2833 if (!term->has_focus) return;
2835 if (caret_x < 0 || caret_y < 0)
2838 SetCaretPos(caret_x, caret_y);
2840 /* IMM calls on Win98 and beyond only */
2841 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
2843 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
2844 osVersion.dwMinorVersion == 0) return; /* 95 */
2846 /* we should have the IMM functions */
2847 hIMC = ImmGetContext(hwnd);
2848 cf.dwStyle = CFS_POINT;
2849 cf.ptCurrentPos.x = caret_x;
2850 cf.ptCurrentPos.y = caret_y;
2851 ImmSetCompositionWindow(hIMC, &cf);
2853 ImmReleaseContext(hwnd, hIMC);
2857 * Draw a line of text in the window, at given character
2858 * coordinates, in given attributes.
2860 * We are allowed to fiddle with the contents of `text'.
2862 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
2863 unsigned long attr, int lattr)
2866 int nfg, nbg, nfont;
2869 int force_manual_underline = 0;
2870 int fnt_width, char_width;
2871 int text_adjust = 0;
2872 static int *IpDx = 0, IpDxLEN = 0;
2874 lattr &= LATTR_MODE;
2876 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
2878 if (attr & ATTR_WIDE)
2881 if (len > IpDxLEN || IpDx[0] != char_width) {
2883 if (len > IpDxLEN) {
2885 IpDx = snewn(len + 16, int);
2886 IpDxLEN = (len + 16);
2888 for (i = 0; i < IpDxLEN; i++)
2889 IpDx[i] = char_width;
2892 /* Only want the left half of double width lines */
2893 if (lattr != LATTR_NORM && x*2 >= term->cols)
2901 if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
2902 attr &= ATTR_CUR_AND | (bold_mode != BOLD_COLOURS ? ATTR_BOLD : 0);
2903 attr ^= ATTR_CUR_XOR;
2907 if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
2908 /* Assume a poorman font is borken in other ways too. */
2918 nfont |= FONT_WIDE + FONT_HIGH;
2921 if (attr & ATTR_NARROW)
2922 nfont |= FONT_NARROW;
2924 /* Special hack for the VT100 linedraw glyphs. */
2925 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
2926 switch ((unsigned char) (text[0])) {
2928 text_adjust = -2 * font_height / 5;
2931 text_adjust = -1 * font_height / 5;
2934 text_adjust = font_height / 5;
2937 text_adjust = 2 * font_height / 5;
2940 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
2942 text[0] = ucsdata.unitab_xterm['q'];
2943 if (attr & ATTR_UNDER) {
2944 attr &= ~ATTR_UNDER;
2945 force_manual_underline = 1;
2949 /* Anything left as an original character set is unprintable. */
2950 if (DIRECT_CHAR(text[0])) {
2952 for (i = 0; i < len; i++)
2957 if ((text[0] & CSET_MASK) == CSET_OEMCP)
2960 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
2961 nfg = 2 * (nfg & 0xF) + (nfg & 0x10 ? 1 : 0);
2962 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
2963 nbg = 2 * (nbg & 0xF) + (nbg & 0x10 ? 1 : 0);
2964 if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
2966 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
2967 nfont |= FONT_UNDERLINE;
2968 another_font(nfont);
2969 if (!fonts[nfont]) {
2970 if (nfont & FONT_UNDERLINE)
2971 force_manual_underline = 1;
2972 /* Don't do the same for manual bold, it could be bad news. */
2974 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
2976 another_font(nfont);
2978 nfont = FONT_NORMAL;
2979 if (attr & ATTR_REVERSE) {
2984 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD))
2986 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK))
2990 SelectObject(hdc, fonts[nfont]);
2991 SetTextColor(hdc, fg);
2992 SetBkColor(hdc, bg);
2993 if (attr & TATTR_COMBINING)
2994 SetBkMode(hdc, TRANSPARENT);
2996 SetBkMode(hdc, OPAQUE);
2999 line_box.right = x + char_width * len;
3000 line_box.bottom = y + font_height;
3002 /* Only want the left half of double width lines */
3003 if (line_box.right > font_width*term->cols+offset_width)
3004 line_box.right = font_width*term->cols+offset_width;
3006 /* We're using a private area for direct to font. (512 chars.) */
3007 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3008 /* Ho Hum, dbcs fonts are a PITA! */
3009 /* To display on W9x I have to convert to UCS */
3010 static wchar_t *uni_buf = 0;
3011 static int uni_len = 0;
3013 if (len > uni_len) {
3016 uni_buf = snewn(uni_len, wchar_t);
3019 for(nlen = mptr = 0; mptr<len; mptr++) {
3020 uni_buf[nlen] = 0xFFFD;
3021 if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
3023 dbcstext[0] = text[mptr] & 0xFF;
3024 dbcstext[1] = text[mptr+1] & 0xFF;
3025 IpDx[nlen] += char_width;
3026 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3027 dbcstext, 2, uni_buf+nlen, 1);
3033 dbcstext[0] = text[mptr] & 0xFF;
3034 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3035 dbcstext, 1, uni_buf+nlen, 1);
3043 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3044 ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
3045 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3046 SetBkMode(hdc, TRANSPARENT);
3047 ExtTextOutW(hdc, x - 1,
3048 y - font_height * (lattr ==
3049 LATTR_BOT) + text_adjust,
3050 ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
3054 } else if (DIRECT_FONT(text[0])) {
3055 static char *directbuf = NULL;
3056 static int directlen = 0;
3058 if (len > directlen) {
3060 directbuf = sresize(directbuf, directlen, char);
3063 for (i = 0; i < len; i++)
3064 directbuf[i] = text[i] & 0xFF;
3067 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3068 ETO_CLIPPED | ETO_OPAQUE, &line_box, directbuf, len, IpDx);
3069 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3070 SetBkMode(hdc, TRANSPARENT);
3072 /* GRR: This draws the character outside it's box and can leave
3073 * 'droppings' even with the clip box! I suppose I could loop it
3074 * one character at a time ... yuk.
3076 * Or ... I could do a test print with "W", and use +1 or -1 for this
3077 * shift depending on if the leftmost column is blank...
3079 ExtTextOut(hdc, x - 1,
3080 y - font_height * (lattr ==
3081 LATTR_BOT) + text_adjust,
3082 ETO_CLIPPED, &line_box, directbuf, len, IpDx);
3085 /* And 'normal' unicode characters */
3086 static WCHAR *wbuf = NULL;
3087 static int wlen = 0;
3093 wbuf = snewn(wlen, WCHAR);
3096 for (i = 0; i < len; i++)
3099 /* print Glyphs as they are, without Windows' Shaping*/
3100 exact_textout(hdc, x, y - font_height * (lattr == LATTR_BOT) + text_adjust,
3101 &line_box, wbuf, len, IpDx, !(attr & TATTR_COMBINING));
3102 /* ExtTextOutW(hdc, x,
3103 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3104 ETO_CLIPPED | ETO_OPAQUE, &line_box, wbuf, len, IpDx);
3107 /* And the shadow bold hack. */
3108 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3109 SetBkMode(hdc, TRANSPARENT);
3110 ExtTextOutW(hdc, x - 1,
3111 y - font_height * (lattr ==
3112 LATTR_BOT) + text_adjust,
3113 ETO_CLIPPED, &line_box, wbuf, len, IpDx);
3116 if (lattr != LATTR_TOP && (force_manual_underline ||
3117 (und_mode == UND_LINE
3118 && (attr & ATTR_UNDER)))) {
3121 if (lattr == LATTR_BOT)
3122 dec = dec * 2 - font_height;
3124 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3125 MoveToEx(hdc, x, y + dec, NULL);
3126 LineTo(hdc, x + len * char_width, y + dec);
3127 oldpen = SelectObject(hdc, oldpen);
3128 DeleteObject(oldpen);
3133 * Wrapper that handles combining characters.
3135 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3136 unsigned long attr, int lattr)
3138 if (attr & TATTR_COMBINING) {
3139 unsigned long a = 0;
3140 attr &= ~TATTR_COMBINING;
3142 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3144 a = TATTR_COMBINING;
3147 do_text_internal(ctx, x, y, text, len, attr, lattr);
3150 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3151 unsigned long attr, int lattr)
3157 int ctype = cfg.cursor_type;
3159 lattr &= LATTR_MODE;
3161 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3162 if (*text != UCSWIDE) {
3163 do_text(ctx, x, y, text, len, attr, lattr);
3167 attr |= TATTR_RIGHTCURS;
3170 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3171 if (attr & ATTR_WIDE)
3178 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3181 pts[0].x = pts[1].x = pts[4].x = x;
3182 pts[2].x = pts[3].x = x + char_width - 1;
3183 pts[0].y = pts[3].y = pts[4].y = y;
3184 pts[1].y = pts[2].y = y + font_height - 1;
3185 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
3186 Polyline(hdc, pts, 5);
3187 oldpen = SelectObject(hdc, oldpen);
3188 DeleteObject(oldpen);
3189 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3190 int startx, starty, dx, dy, length, i;
3193 starty = y + descent;
3196 length = char_width;
3199 if (attr & TATTR_RIGHTCURS)
3200 xadjust = char_width - 1;
3201 startx = x + xadjust;
3205 length = font_height;
3207 if (attr & TATTR_ACTCURS) {
3210 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
3211 MoveToEx(hdc, startx, starty, NULL);
3212 LineTo(hdc, startx + dx * length, starty + dy * length);
3213 oldpen = SelectObject(hdc, oldpen);
3214 DeleteObject(oldpen);
3216 for (i = 0; i < length; i++) {
3218 SetPixel(hdc, startx, starty, colours[23]);
3227 /* This function gets the actual width of a character in the normal font.
3229 int char_width(Context ctx, int uc) {
3233 /* If the font max is the same as the font ave width then this
3234 * function is a no-op.
3236 if (!font_dualwidth) return 1;
3238 switch (uc & CSET_MASK) {
3240 uc = ucsdata.unitab_line[uc & 0xFF];
3243 uc = ucsdata.unitab_xterm[uc & 0xFF];
3246 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3249 if (DIRECT_FONT(uc)) {
3250 if (ucsdata.dbcs_screenfont) return 1;
3252 /* Speedup, I know of no font where ascii is the wrong width */
3253 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3256 if ( (uc & CSET_MASK) == CSET_ACP ) {
3257 SelectObject(hdc, fonts[FONT_NORMAL]);
3258 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3259 another_font(FONT_OEM);
3260 if (!fonts[FONT_OEM]) return 0;
3262 SelectObject(hdc, fonts[FONT_OEM]);
3266 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3267 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3270 /* Speedup, I know of no font where ascii is the wrong width */
3271 if (uc >= ' ' && uc <= '~') return 1;
3273 SelectObject(hdc, fonts[FONT_NORMAL]);
3274 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3275 /* Okay that one worked */ ;
3276 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3277 /* This should work on 9x too, but it's "less accurate" */ ;
3282 ibuf += font_width / 2 -1;
3289 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3290 * codes. Returns number of bytes used or zero to drop the message
3291 * or -1 to forward the message to windows.
3293 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3294 unsigned char *output)
3297 int scan, left_alt = 0, key_down, shift_state;
3299 unsigned char *p = output;
3300 static int alt_sum = 0;
3302 HKL kbd_layout = GetKeyboardLayout(0);
3304 /* keys is for ToAsciiEx. There's some ick here, see below. */
3305 static WORD keys[3];
3306 static int compose_char = 0;
3307 static WPARAM compose_key = 0;
3309 r = GetKeyboardState(keystate);
3311 memset(keystate, 0, sizeof(keystate));
3314 #define SHOW_TOASCII_RESULT
3315 { /* Tell us all about key events */
3316 static BYTE oldstate[256];
3317 static int first = 1;
3321 memcpy(oldstate, keystate, sizeof(oldstate));
3324 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3326 } else if ((HIWORD(lParam) & KF_UP)
3327 && scan == (HIWORD(lParam) & 0xFF)) {
3331 if (wParam >= VK_F1 && wParam <= VK_F20)
3332 debug(("K_F%d", wParam + 1 - VK_F1));
3345 debug(("VK_%02x", wParam));
3347 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3349 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3351 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3352 if (ch >= ' ' && ch <= '~')
3353 debug((", '%c'", ch));
3355 debug((", $%02x", ch));
3358 debug((", KB0=%02x", keys[0]));
3360 debug((", KB1=%02x", keys[1]));
3362 debug((", KB2=%02x", keys[2]));
3364 if ((keystate[VK_SHIFT] & 0x80) != 0)
3366 if ((keystate[VK_CONTROL] & 0x80) != 0)
3368 if ((HIWORD(lParam) & KF_EXTENDED))
3370 if ((HIWORD(lParam) & KF_UP))
3374 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3375 else if ((HIWORD(lParam) & KF_UP))
3376 oldstate[wParam & 0xFF] ^= 0x80;
3378 oldstate[wParam & 0xFF] ^= 0x81;
3380 for (ch = 0; ch < 256; ch++)
3381 if (oldstate[ch] != keystate[ch])
3382 debug((", M%02x=%02x", ch, keystate[ch]));
3384 memcpy(oldstate, keystate, sizeof(oldstate));
3388 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
3389 keystate[VK_RMENU] = keystate[VK_MENU];
3393 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
3394 if ((cfg.funky_type == FUNKY_VT400 ||
3395 (cfg.funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
3397 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
3399 wParam = VK_EXECUTE;
3401 /* UnToggle NUMLock */
3402 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3403 keystate[VK_NUMLOCK] ^= 1;
3406 /* And write back the 'adjusted' state */
3407 SetKeyboardState(keystate);
3410 /* Disable Auto repeat if required */
3411 if (term->repeat_off &&
3412 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
3415 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
3418 key_down = ((HIWORD(lParam) & KF_UP) == 0);
3420 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
3421 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
3422 if (cfg.ctrlaltkeys)
3423 keystate[VK_MENU] = 0;
3425 keystate[VK_RMENU] = 0x80;
3430 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
3431 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3432 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
3434 /* Note if AltGr was pressed and if it was used as a compose key */
3435 if (!compose_state) {
3436 compose_key = 0x100;
3437 if (cfg.compose_key) {
3438 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
3439 compose_key = wParam;
3441 if (wParam == VK_APPS)
3442 compose_key = wParam;
3445 if (wParam == compose_key) {
3446 if (compose_state == 0
3447 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3449 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
3453 } else if (compose_state == 1 && wParam != VK_CONTROL)
3456 if (compose_state > 1 && left_alt)
3459 /* Sanitize the number pad if not using a PC NumPad */
3460 if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
3461 && cfg.funky_type != FUNKY_XTERM)
3462 || cfg.funky_type == FUNKY_VT400 || cfg.nethack_keypad || compose_state) {
3463 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
3467 nParam = VK_NUMPAD0;
3470 nParam = VK_NUMPAD1;
3473 nParam = VK_NUMPAD2;
3476 nParam = VK_NUMPAD3;
3479 nParam = VK_NUMPAD4;
3482 nParam = VK_NUMPAD5;
3485 nParam = VK_NUMPAD6;
3488 nParam = VK_NUMPAD7;
3491 nParam = VK_NUMPAD8;
3494 nParam = VK_NUMPAD9;
3497 nParam = VK_DECIMAL;
3501 if (keystate[VK_NUMLOCK] & 1)
3508 /* If a key is pressed and AltGr is not active */
3509 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3510 /* Okay, prepare for most alts then ... */
3514 /* Lets see if it's a pattern we know all about ... */
3515 if (wParam == VK_PRIOR && shift_state == 1) {
3516 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3519 if (wParam == VK_PRIOR && shift_state == 2) {
3520 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3523 if (wParam == VK_NEXT && shift_state == 1) {
3524 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3527 if (wParam == VK_NEXT && shift_state == 2) {
3528 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3531 if (wParam == VK_INSERT && shift_state == 1) {
3532 term_do_paste(term);
3535 if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
3538 if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
3539 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3542 if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3543 (cfg.resize_action != RESIZE_DISABLED)) {
3544 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3548 /* Control-Numlock for app-keypad mode switch */
3549 if (wParam == VK_PAUSE && shift_state == 2) {
3550 term->app_keypad_keys ^= 1;
3554 /* Nethack keypad */
3555 if (cfg.nethack_keypad && !left_alt) {
3558 *p++ = shift_state ? 'B' : 'b';
3561 *p++ = shift_state ? 'J' : 'j';
3564 *p++ = shift_state ? 'N' : 'n';
3567 *p++ = shift_state ? 'H' : 'h';
3570 *p++ = shift_state ? '.' : '.';
3573 *p++ = shift_state ? 'L' : 'l';
3576 *p++ = shift_state ? 'Y' : 'y';
3579 *p++ = shift_state ? 'K' : 'k';
3582 *p++ = shift_state ? 'U' : 'u';
3587 /* Application Keypad */
3591 if (cfg.funky_type == FUNKY_VT400 ||
3592 (cfg.funky_type <= FUNKY_LINUX &&
3593 term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
3607 if (term->app_keypad_keys && !cfg.no_applic_k)
3644 if (cfg.funky_type == FUNKY_XTERM) {
3649 } else if (shift_state)
3656 if (cfg.funky_type == FUNKY_XTERM)
3660 if (cfg.funky_type == FUNKY_XTERM)
3664 if (cfg.funky_type == FUNKY_XTERM)
3669 if (HIWORD(lParam) & KF_EXTENDED)
3674 if (term->vt52_mode) {
3675 if (xkey >= 'P' && xkey <= 'S')
3676 p += sprintf((char *) p, "\x1B%c", xkey);
3678 p += sprintf((char *) p, "\x1B?%c", xkey);
3680 p += sprintf((char *) p, "\x1BO%c", xkey);
3685 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
3686 *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
3690 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
3691 /* We do the opposite of what is configured */
3692 *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
3696 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
3702 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
3706 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
3710 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
3715 if (wParam == VK_PAUSE) { /* Break/Pause */
3720 /* Control-2 to Control-8 are special */
3721 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
3722 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
3725 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
3729 if (shift_state == 2 && wParam == 0xDF) {
3733 if (shift_state == 3 && wParam == 0xDE) {
3734 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
3737 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
3744 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
3745 * for integer decimal nn.)
3747 * We also deal with the weird ones here. Linux VCs replace F1
3748 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
3749 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
3755 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
3758 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
3761 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
3764 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
3767 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
3770 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
3773 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
3776 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
3779 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
3782 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
3815 if ((shift_state&2) == 0) switch (wParam) {
3835 /* Reorder edit keys to physical order */
3836 if (cfg.funky_type == FUNKY_VT400 && code <= 6)
3837 code = "\0\2\1\4\5\3\6"[code];
3839 if (term->vt52_mode && code > 0 && code <= 6) {
3840 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
3844 if (cfg.funky_type == FUNKY_SCO && /* SCO function keys */
3845 code >= 11 && code <= 34) {
3846 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
3849 case VK_F1: index = 0; break;
3850 case VK_F2: index = 1; break;
3851 case VK_F3: index = 2; break;
3852 case VK_F4: index = 3; break;
3853 case VK_F5: index = 4; break;
3854 case VK_F6: index = 5; break;
3855 case VK_F7: index = 6; break;
3856 case VK_F8: index = 7; break;
3857 case VK_F9: index = 8; break;
3858 case VK_F10: index = 9; break;
3859 case VK_F11: index = 10; break;
3860 case VK_F12: index = 11; break;
3862 if (keystate[VK_SHIFT] & 0x80) index += 12;
3863 if (keystate[VK_CONTROL] & 0x80) index += 24;
3864 p += sprintf((char *) p, "\x1B[%c", codes[index]);
3867 if (cfg.funky_type == FUNKY_SCO && /* SCO small keypad */
3868 code >= 1 && code <= 6) {
3869 char codes[] = "HL.FIG";
3873 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
3877 if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
3883 if (term->vt52_mode)
3884 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
3887 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
3890 if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
3891 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
3894 if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
3895 if (term->vt52_mode)
3896 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
3898 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
3901 if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
3902 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
3906 p += sprintf((char *) p, "\x1B[%d~", code);
3911 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
3912 * some reason seems to send VK_CLEAR to Windows...).
3934 if (term->vt52_mode)
3935 p += sprintf((char *) p, "\x1B%c", xkey);
3937 int app_flg = (term->app_cursor_keys && !cfg.no_applic_c);
3940 * RDB: VT100 & VT102 manuals both state the
3941 * app cursor keys only work if the app keypad
3944 * SGT: That may well be true, but xterm
3945 * disagrees and so does at least one
3946 * application, so I've #if'ed this out and the
3947 * behaviour is back to PuTTY's original: app
3948 * cursor and app keypad are independently
3949 * switchable modes. If anyone complains about
3950 * _this_ I'll have to put in a configurable
3953 if (!term->app_keypad_keys)
3956 /* Useful mapping of Ctrl-arrows */
3957 if (shift_state == 2)
3961 p += sprintf((char *) p, "\x1BO%c", xkey);
3963 p += sprintf((char *) p, "\x1B[%c", xkey);
3970 * Finally, deal with Return ourselves. (Win95 seems to
3971 * foul it up when Alt is pressed, for some reason.)
3973 if (wParam == VK_RETURN) { /* Return */
3979 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
3980 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
3985 /* Okay we've done everything interesting; let windows deal with
3986 * the boring stuff */
3990 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
3991 if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
3993 keystate[VK_CAPITAL] = 0;
3996 /* XXX how do we know what the max size of the keys array should
3997 * be is? There's indication on MS' website of an Inquire/InquireEx
3998 * functioning returning a KBINFO structure which tells us. */
3999 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4000 /* XXX 'keys' parameter is declared in MSDN documentation as
4002 * The experience of a French user indicates that on
4003 * Win98, WORD[] should be passed in, but on Win2K, it should
4004 * be BYTE[]. German WinXP and my Win2K with "US International"
4005 * driver corroborate this.
4006 * Experimentally I've conditionalised the behaviour on the
4007 * Win9x/NT split, but I suspect it's worse than that.
4008 * See wishlist item `win-dead-keys' for more horrible detail
4009 * and speculations. */
4012 r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
4013 for (i=0; i<3; i++) keys[i] = keybs[i];
4015 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4017 #ifdef SHOW_TOASCII_RESULT
4018 if (r == 1 && !key_down) {
4020 if (in_utf(term) || ucsdata.dbcs_screenfont)
4021 debug((", (U+%04x)", alt_sum));
4023 debug((", LCH(%d)", alt_sum));
4025 debug((", ACH(%d)", keys[0]));
4030 for (r1 = 0; r1 < r; r1++) {
4031 debug(("%s%d", r1 ? "," : "", keys[r1]));
4040 * Interrupt an ongoing paste. I'm not sure this is
4041 * sensible, but for the moment it's preferable to
4042 * having to faff about buffering things.
4047 for (i = 0; i < r; i++) {
4048 unsigned char ch = (unsigned char) keys[i];
4050 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
4055 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
4059 if ((nc = check_compose(compose_char, ch)) == -1) {
4060 MessageBeep(MB_ICONHAND);
4064 term_seen_key_event(term);
4066 luni_send(ldisc, &keybuf, 1, 1);
4074 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4076 term_seen_key_event(term);
4078 luni_send(ldisc, &keybuf, 1, 1);
4080 ch = (char) alt_sum;
4082 * We need not bother about stdin
4083 * backlogs here, because in GUI PuTTY
4084 * we can't do anything about it
4085 * anyway; there's no means of asking
4086 * Windows to hold off on KEYDOWN
4087 * messages. We _have_ to buffer
4088 * everything we're sent.
4090 term_seen_key_event(term);
4092 ldisc_send(ldisc, &ch, 1, 1);
4096 term_seen_key_event(term);
4098 lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
4101 if(capsOn && ch < 0x80) {
4104 cbuf[1] = xlat_uskbd2cyrllic(ch);
4105 term_seen_key_event(term);
4107 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4112 term_seen_key_event(term);
4114 lpage_send(ldisc, kbd_codepage,
4115 cbuf+!left_alt, 1+!!left_alt, 1);
4121 /* This is so the ALT-Numpad and dead keys work correctly. */
4126 /* If we're definitly not building up an ALT-54321 then clear it */
4129 /* If we will be using alt_sum fix the 256s */
4130 else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4135 * ALT alone may or may not want to bring up the System menu.
4136 * If it's not meant to, we return 0 on presses or releases of
4137 * ALT, to show that we've swallowed the keystroke. Otherwise
4138 * we return -1, which means Windows will give the keystroke
4139 * its default handling (i.e. bring up the System menu).
4141 if (wParam == VK_MENU && !cfg.alt_only)
4147 void request_paste(void *frontend)
4150 * In Windows, pasting is synchronous: we can read the
4151 * clipboard with no difficulty, so request_paste() can just go
4154 term_do_paste(term);
4157 void set_title(void *frontend, char *title)
4160 window_name = snewn(1 + strlen(title), char);
4161 strcpy(window_name, title);
4162 if (cfg.win_name_always || !IsIconic(hwnd))
4163 SetWindowText(hwnd, title);
4166 void set_icon(void *frontend, char *title)
4169 icon_name = snewn(1 + strlen(title), char);
4170 strcpy(icon_name, title);
4171 if (!cfg.win_name_always && IsIconic(hwnd))
4172 SetWindowText(hwnd, title);
4175 void set_sbar(void *frontend, int total, int start, int page)
4179 if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
4182 si.cbSize = sizeof(si);
4183 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4185 si.nMax = total - 1;
4189 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4192 Context get_ctx(void *frontend)
4198 SelectPalette(hdc, pal, FALSE);
4204 void free_ctx(Context ctx)
4206 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4207 ReleaseDC(hwnd, ctx);
4210 static void real_palette_set(int n, int r, int g, int b)
4213 logpal->palPalEntry[n].peRed = r;
4214 logpal->palPalEntry[n].peGreen = g;
4215 logpal->palPalEntry[n].peBlue = b;
4216 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4217 colours[n] = PALETTERGB(r, g, b);
4218 SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
4220 colours[n] = RGB(r, g, b);
4223 void palette_set(void *frontend, int n, int r, int g, int b)
4225 static const int first[21] = {
4226 0, 2, 4, 6, 8, 10, 12, 14,
4227 1, 3, 5, 7, 9, 11, 13, 15,
4230 real_palette_set(first[n], r, g, b);
4232 real_palette_set(first[n] + 1, r, g, b);
4234 HDC hdc = get_ctx(frontend);
4235 UnrealizeObject(pal);
4236 RealizePalette(hdc);
4241 void palette_reset(void *frontend)
4245 for (i = 0; i < NCOLOURS; i++) {
4247 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4248 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4249 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4250 logpal->palPalEntry[i].peFlags = 0;
4251 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4252 defpal[i].rgbtGreen,
4253 defpal[i].rgbtBlue);
4255 colours[i] = RGB(defpal[i].rgbtRed,
4256 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4261 SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
4262 hdc = get_ctx(frontend);
4263 RealizePalette(hdc);
4268 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4273 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4276 lock = GlobalLock(clipdata);
4279 memcpy(lock, data, len);
4280 ((unsigned char *) lock)[len] = 0;
4281 GlobalUnlock(clipdata);
4284 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4286 if (OpenClipboard(hwnd)) {
4288 SetClipboardData(CF_TEXT, clipdata);
4291 GlobalFree(clipdata);
4294 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4298 * Note: unlike write_aclip() this will not append a nul.
4300 void write_clip(void *frontend, wchar_t * data, int len, int must_deselect)
4302 HGLOBAL clipdata, clipdata2, clipdata3;
4304 void *lock, *lock2, *lock3;
4306 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4308 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4309 len * sizeof(wchar_t));
4310 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4312 if (!clipdata || !clipdata2) {
4314 GlobalFree(clipdata);
4316 GlobalFree(clipdata2);
4319 if (!(lock = GlobalLock(clipdata)))
4321 if (!(lock2 = GlobalLock(clipdata2)))
4324 memcpy(lock, data, len * sizeof(wchar_t));
4325 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4327 if (cfg.rtf_paste) {
4328 wchar_t unitab[256];
4330 unsigned char *tdata = (unsigned char *)lock2;
4331 wchar_t *udata = (wchar_t *)lock;
4332 int rtflen = 0, uindex = 0, tindex = 0;
4334 int multilen, blen, alen, totallen, i;
4335 char before[16], after[4];
4337 get_unitab(CP_ACP, unitab, 0);
4339 rtfsize = 100 + strlen(cfg.font.name);
4340 rtf = snewn(rtfsize, char);
4341 sprintf(rtf, "{\\rtf1\\ansi%d{\\fonttbl\\f0\\fmodern %s;}\\f0",
4342 GetACP(), cfg.font.name);
4343 rtflen = strlen(rtf);
4346 * We want to construct a piece of RTF that specifies the
4347 * same Unicode text. To do this we will read back in
4348 * parallel from the Unicode data in `udata' and the
4349 * non-Unicode data in `tdata'. For each character in
4350 * `tdata' which becomes the right thing in `udata' when
4351 * looked up in `unitab', we just copy straight over from
4352 * tdata. For each one that doesn't, we must WCToMB it
4353 * individually and produce a \u escape sequence.
4355 * It would probably be more robust to just bite the bullet
4356 * and WCToMB each individual Unicode character one by one,
4357 * then MBToWC each one back to see if it was an accurate
4358 * translation; but that strikes me as a horrifying number
4359 * of Windows API calls so I want to see if this faster way
4360 * will work. If it screws up badly we can always revert to
4361 * the simple and slow way.
4363 while (tindex < len2 && uindex < len &&
4364 tdata[tindex] && udata[uindex]) {
4365 if (tindex + 1 < len2 &&
4366 tdata[tindex] == '\r' &&
4367 tdata[tindex+1] == '\n') {
4371 if (unitab[tdata[tindex]] == udata[uindex]) {
4377 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4378 NULL, 0, NULL, NULL);
4379 if (multilen != 1) {
4380 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4382 alen = 1; strcpy(after, "}");
4384 blen = sprintf(before, "\\u%d", udata[uindex]);
4385 alen = 0; after[0] = '\0';
4388 assert(tindex + multilen <= len2);
4389 totallen = blen + alen;
4390 for (i = 0; i < multilen; i++) {
4391 if (tdata[tindex+i] == '\\' ||
4392 tdata[tindex+i] == '{' ||
4393 tdata[tindex+i] == '}')
4395 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4396 totallen += 6; /* \par\r\n */
4397 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4403 if (rtfsize < rtflen + totallen + 3) {
4404 rtfsize = rtflen + totallen + 512;
4405 rtf = sresize(rtf, rtfsize, char);
4408 strcpy(rtf + rtflen, before); rtflen += blen;
4409 for (i = 0; i < multilen; i++) {
4410 if (tdata[tindex+i] == '\\' ||
4411 tdata[tindex+i] == '{' ||
4412 tdata[tindex+i] == '}') {
4413 rtf[rtflen++] = '\\';
4414 rtf[rtflen++] = tdata[tindex+i];
4415 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4416 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4417 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4418 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4420 rtf[rtflen++] = tdata[tindex+i];
4423 strcpy(rtf + rtflen, after); rtflen += alen;
4429 strcpy(rtf + rtflen, "}");
4432 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4433 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
4435 GlobalUnlock(clipdata3);
4441 GlobalUnlock(clipdata);
4442 GlobalUnlock(clipdata2);
4445 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4447 if (OpenClipboard(hwnd)) {
4449 SetClipboardData(CF_UNICODETEXT, clipdata);
4450 SetClipboardData(CF_TEXT, clipdata2);
4452 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4455 GlobalFree(clipdata);
4456 GlobalFree(clipdata2);
4460 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4463 void get_clip(void *frontend, wchar_t ** p, int *len)
4465 static HGLOBAL clipdata = NULL;
4466 static wchar_t *converted = 0;
4475 GlobalUnlock(clipdata);
4478 } else if (OpenClipboard(NULL)) {
4479 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
4481 *p = GlobalLock(clipdata);
4483 for (p2 = *p; *p2; p2++);
4487 } else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
4491 s = GlobalLock(clipdata);
4492 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
4493 *p = converted = snewn(i, wchar_t);
4494 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
4507 * Move `lines' lines from position `from' to position `to' in the
4510 void optimised_move(void *frontend, int to, int from, int lines)
4515 min = (to < from ? to : from);
4516 max = to + from - min;
4518 r.left = offset_width;
4519 r.right = offset_width + term->cols * font_width;
4520 r.top = offset_height + min * font_height;
4521 r.bottom = offset_height + (max + lines) * font_height;
4522 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
4527 * Print a message box and perform a fatal exit.
4529 void fatalbox(char *fmt, ...)
4532 char *stuff, morestuff[100];
4535 stuff = dupvprintf(fmt, ap);
4537 sprintf(morestuff, "%.70s Fatal Error", appname);
4538 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
4544 * Print a modal (Really Bad) message box and perform a fatal exit.
4546 void modalfatalbox(char *fmt, ...)
4549 char *stuff, morestuff[100];
4552 stuff = dupvprintf(fmt, ap);
4554 sprintf(morestuff, "%.70s Fatal Error", appname);
4555 MessageBox(hwnd, stuff, morestuff,
4556 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
4561 static void flash_window(int mode);
4562 static long next_flash;
4563 static int flashing = 0;
4565 static void flash_window_timer(void *ctx, long now)
4567 if (flashing && now - next_flash >= 0) {
4573 * Manage window caption / taskbar flashing, if enabled.
4574 * 0 = stop, 1 = maintain, 2 = start
4576 static void flash_window(int mode)
4578 if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
4581 FlashWindow(hwnd, FALSE);
4585 } else if (mode == 2) {
4589 FlashWindow(hwnd, TRUE);
4590 next_flash = schedule_timer(450, flash_window_timer, hwnd);
4593 } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
4596 FlashWindow(hwnd, TRUE); /* toggle */
4597 next_flash = schedule_timer(450, flash_window_timer, hwnd);
4605 void beep(void *frontend, int mode)
4607 if (mode == BELL_DEFAULT) {
4609 * For MessageBeep style bells, we want to be careful of
4610 * timing, because they don't have the nice property of
4611 * PlaySound bells that each one cancels the previous
4612 * active one. So we limit the rate to one per 50ms or so.
4614 static long lastbeep = 0;
4617 beepdiff = GetTickCount() - lastbeep;
4618 if (beepdiff >= 0 && beepdiff < 50)
4622 * The above MessageBeep call takes time, so we record the
4623 * time _after_ it finishes rather than before it starts.
4625 lastbeep = GetTickCount();
4626 } else if (mode == BELL_WAVEFILE) {
4627 if (!PlaySound(cfg.bell_wavefile.path, NULL,
4628 SND_ASYNC | SND_FILENAME)) {
4629 char buf[sizeof(cfg.bell_wavefile.path) + 80];
4631 sprintf(buf, "Unable to play sound file\n%s\n"
4632 "Using default sound instead", cfg.bell_wavefile.path);
4633 sprintf(otherbuf, "%.70s Sound Error", appname);
4634 MessageBox(hwnd, buf, otherbuf,
4635 MB_OK | MB_ICONEXCLAMATION);
4636 cfg.beep = BELL_DEFAULT;
4638 } else if (mode == BELL_PCSPEAKER) {
4639 static long lastbeep = 0;
4642 beepdiff = GetTickCount() - lastbeep;
4643 if (beepdiff >= 0 && beepdiff < 50)
4647 * We must beep in different ways depending on whether this
4648 * is a 95-series or NT-series OS.
4650 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
4654 lastbeep = GetTickCount();
4656 /* Otherwise, either visual bell or disabled; do nothing here */
4657 if (!term->has_focus) {
4658 flash_window(2); /* start */
4663 * Minimise or restore the window in response to a server-side
4666 void set_iconic(void *frontend, int iconic)
4668 if (IsIconic(hwnd)) {
4670 ShowWindow(hwnd, SW_RESTORE);
4673 ShowWindow(hwnd, SW_MINIMIZE);
4678 * Move the window in response to a server-side request.
4680 void move_window(void *frontend, int x, int y)
4682 if (cfg.resize_action == RESIZE_DISABLED ||
4683 cfg.resize_action == RESIZE_FONT ||
4687 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
4691 * Move the window to the top or bottom of the z-order in response
4692 * to a server-side request.
4694 void set_zorder(void *frontend, int top)
4696 if (cfg.alwaysontop)
4697 return; /* ignore */
4698 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
4699 SWP_NOMOVE | SWP_NOSIZE);
4703 * Refresh the window in response to a server-side request.
4705 void refresh_window(void *frontend)
4707 InvalidateRect(hwnd, NULL, TRUE);
4711 * Maximise or restore the window in response to a server-side
4714 void set_zoomed(void *frontend, int zoomed)
4716 if (IsZoomed(hwnd)) {
4718 ShowWindow(hwnd, SW_RESTORE);
4721 ShowWindow(hwnd, SW_MAXIMIZE);
4726 * Report whether the window is iconic, for terminal reports.
4728 int is_iconic(void *frontend)
4730 return IsIconic(hwnd);
4734 * Report the window's position, for terminal reports.
4736 void get_window_pos(void *frontend, int *x, int *y)
4739 GetWindowRect(hwnd, &r);
4745 * Report the window's pixel size, for terminal reports.
4747 void get_window_pixels(void *frontend, int *x, int *y)
4750 GetWindowRect(hwnd, &r);
4751 *x = r.right - r.left;
4752 *y = r.bottom - r.top;
4756 * Return the window or icon title.
4758 char *get_window_title(void *frontend, int icon)
4760 return icon ? icon_name : window_name;
4764 * See if we're in full-screen mode.
4766 static int is_full_screen()
4768 if (!IsZoomed(hwnd))
4770 if (GetWindowLong(hwnd, GWL_STYLE) & WS_CAPTION)
4775 /* Get the rect/size of a full screen window using the nearest available
4776 * monitor in multimon systems; default to something sensible if only
4777 * one monitor is present. */
4778 static int get_fullscreen_rect(RECT * ss)
4780 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
4783 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
4784 mi.cbSize = sizeof(mi);
4785 GetMonitorInfo(mon, &mi);
4787 /* structure copy */
4791 /* could also use code like this:
4792 ss->left = ss->top = 0;
4793 ss->right = GetSystemMetrics(SM_CXSCREEN);
4794 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
4796 return GetClientRect(GetDesktopWindow(), ss);
4802 * Go full-screen. This should only be called when we are already
4805 static void make_full_screen()
4810 assert(IsZoomed(hwnd));
4812 if (is_full_screen())
4815 /* Remove the window furniture. */
4816 style = GetWindowLong(hwnd, GWL_STYLE);
4817 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
4818 if (cfg.scrollbar_in_fullscreen)
4819 style |= WS_VSCROLL;
4821 style &= ~WS_VSCROLL;
4822 SetWindowLong(hwnd, GWL_STYLE, style);
4824 /* Resize ourselves to exactly cover the nearest monitor. */
4825 get_fullscreen_rect(&ss);
4826 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
4831 /* Tick the menu item in the System menu. */
4832 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4837 * Clear the full-screen attributes.
4839 static void clear_full_screen()
4841 DWORD oldstyle, style;
4843 /* Reinstate the window furniture. */
4844 style = oldstyle = GetWindowLong(hwnd, GWL_STYLE);
4845 style |= WS_CAPTION | WS_BORDER;
4846 if (cfg.resize_action == RESIZE_DISABLED)
4847 style &= ~WS_THICKFRAME;
4849 style |= WS_THICKFRAME;
4851 style |= WS_VSCROLL;
4853 style &= ~WS_VSCROLL;
4854 if (style != oldstyle) {
4855 SetWindowLong(hwnd, GWL_STYLE, style);
4856 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
4857 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
4861 /* Untick the menu item in the System menu. */
4862 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4867 * Toggle full-screen mode.
4869 static void flip_full_screen()
4871 if (is_full_screen()) {
4872 ShowWindow(hwnd, SW_RESTORE);
4873 } else if (IsZoomed(hwnd)) {
4876 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
4877 ShowWindow(hwnd, SW_MAXIMIZE);
4881 void frontend_keypress(void *handle)
4884 * Keypress termination in non-Close-On-Exit mode is not
4885 * currently supported in PuTTY proper, because the window
4886 * always has a perfectly good Close button anyway. So we do
4892 int from_backend(void *frontend, int is_stderr, const char *data, int len)
4894 return term_data(term, is_stderr, data, len);
4897 void agent_schedule_callback(void (*callback)(void *, void *, int),
4898 void *callback_ctx, void *data, int len)
4900 struct agent_callback *c = snew(struct agent_callback);
4901 c->callback = callback;
4902 c->callback_ctx = callback_ctx;
4905 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);