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_APP + 2)
54 #define WM_FULLSCR_ON_MAX (WM_APP + 3)
55 #define WM_AGENT_CALLBACK (WM_APP + 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);
81 static void update_savedsess_menu(void);
83 static int is_full_screen(void);
84 static void make_full_screen(void);
85 static void clear_full_screen(void);
86 static void flip_full_screen(void);
88 /* Window layout information */
89 static void reset_window(int);
90 static int extra_width, extra_height;
91 static int font_width, font_height, font_dualwidth;
92 static int offset_width, offset_height;
93 static int was_zoomed = 0;
94 static int prev_rows, prev_cols;
96 static void enact_netevent(WPARAM, LPARAM);
97 static void flash_window(int mode);
98 static void sys_cursor_update(void);
99 static int is_shift_pressed(void);
100 static int get_fullscreen_rect(RECT * ss);
102 static int caret_x = -1, caret_y = -1;
104 static int kbd_codepage;
107 static Backend *back;
108 static void *backhandle;
110 static struct unicode_data ucsdata;
111 static int session_closed;
112 static int reconfiguring = FALSE;
114 static const struct telnet_special *specials;
115 static int n_specials;
117 #define TIMING_TIMER_ID 1234
118 static long timing_next_time;
122 int specials_submenu_pos;
124 enum { SYSMENU, CTXMENU };
125 static HMENU savedsess_menu;
127 Config cfg; /* exported to windlg.c */
129 static struct sesslist sesslist; /* for saved-session menu */
131 struct agent_callback {
132 void (*callback)(void *, void *, int);
138 #define FONT_NORMAL 0
140 #define FONT_UNDERLINE 2
141 #define FONT_BOLDUND 3
142 #define FONT_WIDE 0x04
143 #define FONT_HIGH 0x08
144 #define FONT_NARROW 0x10
146 #define FONT_OEM 0x20
147 #define FONT_OEMBOLD 0x21
148 #define FONT_OEMUND 0x22
149 #define FONT_OEMBOLDUND 0x23
151 #define FONT_MAXNO 0x2F
153 static HFONT fonts[FONT_MAXNO];
154 static LOGFONT lfont;
155 static int fontflag[FONT_MAXNO];
157 BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT
164 #define NCFGCOLOURS 22
165 #define NEXTCOLOURS 240
166 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
167 static COLORREF colours[NALLCOLOURS];
169 static LPLOGPALETTE logpal;
170 static RGBTRIPLE defpal[NALLCOLOURS];
172 static HBITMAP caretbm;
174 static int dbltime, lasttime, lastact;
175 static Mouse_Button lastbtn;
177 /* this allows xterm-style mouse handling. */
178 static int send_raw_mouse = 0;
179 static int wheel_accumulator = 0;
181 static int busy_status = BUSY_NOT;
183 static char *window_name, *icon_name;
185 static int compose_state = 0;
187 static UINT wm_mousewheel = WM_MOUSEWHEEL;
189 /* Dummy routine, only required in plink. */
190 void ldisc_update(void *frontend, int echo, int edit)
194 char *get_ttymode(void *frontend, const char *mode)
196 return term_get_ttymode(term, mode);
199 static void start_backend(void)
202 char msg[1024], *title;
207 * Select protocol. This is farmed out into a table in a
208 * separate file to enable an ssh-free variant.
211 for (i = 0; backends[i].backend != NULL; i++)
212 if (backends[i].protocol == cfg.protocol) {
213 back = backends[i].backend;
217 char *str = dupprintf("%s Internal Error", appname);
218 MessageBox(NULL, "Unsupported protocol number found",
219 str, MB_OK | MB_ICONEXCLAMATION);
224 error = back->init(NULL, &backhandle, &cfg,
225 cfg.host, cfg.port, &realhost, cfg.tcp_nodelay,
227 back->provide_logctx(backhandle, logctx);
229 char *str = dupprintf("%s Error", appname);
230 sprintf(msg, "Unable to open connection to\n"
231 "%.800s\n" "%s", cfg.host, error);
232 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
236 window_name = icon_name = NULL;
238 title = cfg.wintitle;
240 sprintf(msg, "%s - %s", realhost, appname);
244 set_title(NULL, title);
245 set_icon(NULL, title);
248 * Connect the terminal to the backend for resize purposes.
250 term_provide_resize_fn(term, back->size, backhandle);
253 * Set up a line discipline.
255 ldisc = ldisc_create(&cfg, term, back, backhandle, NULL);
258 * Destroy the Restart Session menu item. (This will return
259 * failure if it's already absent, as it will be the very first
260 * time we call this function. We ignore that, because as long
261 * as the menu item ends up not being there, we don't care
262 * whether it was us who removed it or not!)
264 for (i = 0; i < lenof(popup_menus); i++) {
265 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
268 session_closed = FALSE;
271 static void close_session(void)
276 session_closed = TRUE;
277 sprintf(morestuff, "%.70s (inactive)", appname);
278 set_icon(NULL, morestuff);
279 set_title(NULL, morestuff);
286 back->free(backhandle);
289 update_specials_menu(NULL);
293 * Show the Restart Session menu item. Do a precautionary
294 * delete first to ensure we never end up with more than one.
296 for (i = 0; i < lenof(popup_menus); i++) {
297 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
298 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
299 IDM_RESTART, "&Restart Session");
303 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
307 int guess_width, guess_height;
311 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
315 InitCommonControls();
317 /* Ensure a Maximize setting in Explorer doesn't maximise the
323 char *str = dupprintf("%s Fatal Error", appname);
324 MessageBox(NULL, "Windows refuses to report a version",
325 str, MB_OK | MB_ICONEXCLAMATION);
331 * If we're running a version of Windows that doesn't support
332 * WM_MOUSEWHEEL, find out what message number we should be
335 if (osVersion.dwMajorVersion < 4 ||
336 (osVersion.dwMajorVersion == 4 &&
337 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
338 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
341 * See if we can find our Help file.
344 char b[2048], *p, *q, *r;
346 GetModuleFileName(NULL, b, sizeof(b) - 1);
348 p = strrchr(b, '\\');
349 if (p && p >= r) r = p+1;
351 if (q && q >= r) r = q+1;
352 strcpy(r, PUTTY_HELP_FILE);
353 if ( (fp = fopen(b, "r")) != NULL) {
354 help_path = dupstr(b);
358 strcpy(r, PUTTY_HELP_CONTENTS);
359 if ( (fp = fopen(b, "r")) != NULL) {
360 help_has_contents = TRUE;
363 help_has_contents = FALSE;
367 * Process the command line.
373 default_protocol = be_default_protocol;
374 /* Find the appropriate default port. */
377 default_port = 0; /* illegal */
378 for (i = 0; backends[i].backend != NULL; i++)
379 if (backends[i].protocol == default_protocol) {
380 default_port = backends[i].backend->default_port;
384 cfg.logtype = LGTYP_NONE;
386 do_defaults(NULL, &cfg);
391 * Process a couple of command-line options which are more
392 * easily dealt with before the line is broken up into
393 * words. These are the soon-to-be-defunct @sessionname and
394 * the internal-use-only &sharedmemoryhandle, neither of
395 * which are combined with anything else.
397 while (*p && isspace(*p))
401 while (i > 1 && isspace(p[i - 1]))
404 do_defaults(p + 1, &cfg);
405 if (!*cfg.host && !do_config()) {
408 } else if (*p == '&') {
410 * An initial & means we've been given a command line
411 * containing the hex value of a HANDLE for a file
412 * mapping object, which we must then extract as a
417 if (sscanf(p + 1, "%p", &filemap) == 1 &&
418 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
419 0, 0, sizeof(Config))) != NULL) {
422 CloseHandle(filemap);
423 } else if (!do_config()) {
428 * Otherwise, break up the command line and deal with
434 split_into_argv(cmdline, &argc, &argv, NULL);
436 for (i = 0; i < argc; i++) {
440 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
443 cmdline_error("option \"%s\" requires an argument", p);
444 } else if (ret == 2) {
445 i++; /* skip next argument */
446 } else if (ret == 1) {
447 continue; /* nothing further needs doing */
448 } else if (!strcmp(p, "-cleanup") ||
449 !strcmp(p, "-cleanup-during-uninstall")) {
451 * `putty -cleanup'. Remove all registry
452 * entries associated with PuTTY, and also find
453 * and delete the random seed file.
456 /* Are we being invoked from an uninstaller? */
457 if (!strcmp(p, "-cleanup-during-uninstall")) {
458 s1 = dupprintf("Remove saved sessions and random seed file?\n"
460 "If you hit Yes, ALL Registry entries associated\n"
461 "with %s will be removed, as well as the\n"
462 "random seed file. THIS PROCESS WILL\n"
463 "DESTROY YOUR SAVED SESSIONS.\n"
464 "(This only affects the currently logged-in user.)\n"
466 "If you hit No, uninstallation will proceed, but\n"
467 "saved sessions etc will be left on the machine.",
469 s2 = dupprintf("%s Uninstallation", appname);
471 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
472 "associated with %s, and will also remove\n"
473 "the random seed file. (This only affects the\n"
474 "currently logged-in user.)\n"
476 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
477 "Are you really sure you want to continue?",
479 s2 = dupprintf("%s Warning", appname);
481 if (message_box(s1, s2,
482 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
483 HELPCTXID(option_cleanup)) == IDYES) {
489 } else if (!strcmp(p, "-pgpfp")) {
492 } else if (*p != '-') {
496 * If we already have a host name, treat
497 * this argument as a port number. NB we
498 * have to treat this as a saved -P
499 * argument, so that it will be deferred
500 * until it's a good moment to run it.
502 int ret = cmdline_process_param("-P", p, 1, &cfg);
504 } else if (!strncmp(q, "telnet:", 7)) {
506 * If the hostname starts with "telnet:",
507 * set the protocol to Telnet and process
508 * the string as a Telnet URL.
513 if (q[0] == '/' && q[1] == '/')
515 cfg.protocol = PROT_TELNET;
517 while (*p && *p != ':' && *p != '/')
526 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
527 cfg.host[sizeof(cfg.host) - 1] = '\0';
531 * Otherwise, treat this argument as a host
534 while (*p && !isspace(*p))
538 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
539 cfg.host[sizeof(cfg.host) - 1] = '\0';
543 cmdline_error("unknown option \"%s\"", p);
548 cmdline_run_saved(&cfg);
550 if (!*cfg.host && !do_config()) {
555 * Trim leading whitespace off the hostname if it's there.
558 int space = strspn(cfg.host, " \t");
559 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
562 /* See if host is of the form user@host */
563 if (cfg.host[0] != '\0') {
564 char *atsign = strrchr(cfg.host, '@');
565 /* Make sure we're not overflowing the user field */
567 if (atsign - cfg.host < sizeof cfg.username) {
568 strncpy(cfg.username, cfg.host, atsign - cfg.host);
569 cfg.username[atsign - cfg.host] = '\0';
571 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
576 * Trim a colon suffix off the hostname if it's there. In
577 * order to protect IPv6 address literals against this
578 * treatment, we do not do this if there's _more_ than one
582 char *c = strchr(cfg.host, ':');
585 char *d = strchr(c+1, ':');
592 * Remove any remaining whitespace from the hostname.
596 while (cfg.host[p2] != '\0') {
597 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
598 cfg.host[p1] = cfg.host[p2];
607 /* Check for invalid Port number (i.e. zero) */
609 char *str = dupprintf("%s Internal Error", appname);
610 MessageBox(NULL, "Invalid Port Number",
611 str, MB_OK | MB_ICONEXCLAMATION);
618 wndclass.lpfnWndProc = WndProc;
619 wndclass.cbClsExtra = 0;
620 wndclass.cbWndExtra = 0;
621 wndclass.hInstance = inst;
622 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
623 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
624 wndclass.hbrBackground = NULL;
625 wndclass.lpszMenuName = NULL;
626 wndclass.lpszClassName = appname;
628 RegisterClass(&wndclass);
631 memset(&ucsdata, 0, sizeof(ucsdata));
636 * Guess some defaults for the window size. This all gets
637 * updated later, so we don't really care too much. However, we
638 * do want the font width/height guesses to correspond to a
639 * large font rather than a small one...
646 guess_width = extra_width + font_width * cfg.width;
647 guess_height = extra_height + font_height * cfg.height;
650 get_fullscreen_rect(&r);
651 if (guess_width > r.right - r.left)
652 guess_width = r.right - r.left;
653 if (guess_height > r.bottom - r.top)
654 guess_height = r.bottom - r.top;
658 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
661 winmode &= ~(WS_VSCROLL);
662 if (cfg.resize_action == RESIZE_DISABLED)
663 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
665 exwinmode |= WS_EX_TOPMOST;
667 exwinmode |= WS_EX_CLIENTEDGE;
668 hwnd = CreateWindowEx(exwinmode, appname, appname,
669 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
670 guess_width, guess_height,
671 NULL, NULL, inst, NULL);
675 * Initialise the terminal. (We have to do this _after_
676 * creating the window, since the terminal is the first thing
677 * which will call schedule_timer(), which will in turn call
678 * timer_change_notify() which will expect hwnd to exist.)
680 term = term_init(&cfg, &ucsdata, NULL);
681 logctx = log_init(NULL, &cfg);
682 term_provide_logctx(term, logctx);
683 term_size(term, cfg.height, cfg.width, cfg.savelines);
686 * Initialise the fonts, simultaneously correcting the guesses
687 * for font_{width,height}.
692 * Correct the guesses for extra_{width,height}.
696 GetWindowRect(hwnd, &wr);
697 GetClientRect(hwnd, &cr);
698 offset_width = offset_height = cfg.window_border;
699 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
700 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
704 * Resize the window, now we know what size we _really_ want it
707 guess_width = extra_width + font_width * term->cols;
708 guess_height = extra_height + font_height * term->rows;
709 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
710 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
713 * Set up a caret bitmap, with no content.
717 int size = (font_width + 15) / 16 * 2 * font_height;
718 bits = snewn(size, char);
719 memset(bits, 0, size);
720 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
723 CreateCaret(hwnd, caretbm, font_width, font_height);
726 * Initialise the scroll bar.
731 si.cbSize = sizeof(si);
732 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
734 si.nMax = term->rows - 1;
735 si.nPage = term->rows;
737 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
741 * Prepare the mouse handler.
743 lastact = MA_NOTHING;
744 lastbtn = MBT_NOTHING;
745 dbltime = GetDoubleClickTime();
748 * Set up the session-control options on the system menu.
755 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
756 popup_menus[CTXMENU].menu = CreatePopupMenu();
757 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
759 savedsess_menu = CreateMenu();
760 get_sesslist(&sesslist, TRUE);
761 update_savedsess_menu();
763 for (j = 0; j < lenof(popup_menus); j++) {
764 m = popup_menus[j].menu;
766 AppendMenu(m, MF_SEPARATOR, 0, 0);
767 popup_menus[j].specials_submenu_pos = GetMenuItemCount(m);
768 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
769 AppendMenu(m, MF_SEPARATOR, 0, 0);
770 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
771 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
772 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) savedsess_menu,
774 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
775 AppendMenu(m, MF_SEPARATOR, 0, 0);
776 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
777 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
778 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
779 AppendMenu(m, MF_SEPARATOR, 0, 0);
780 AppendMenu(m, (cfg.resize_action == RESIZE_DISABLED) ?
781 MF_GRAYED : MF_ENABLED, IDM_FULLSCREEN, "&Full Screen");
782 AppendMenu(m, MF_SEPARATOR, 0, 0);
784 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
785 str = dupprintf("&About %s", appname);
786 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
794 * Set up the initial input locale.
796 set_input_locale(GetKeyboardLayout(0));
799 * Finally show the window!
801 ShowWindow(hwnd, show);
802 SetForegroundWindow(hwnd);
805 * Set the palette up.
811 term_set_focus(term, GetForegroundWindow() == hwnd);
814 if (GetMessage(&msg, NULL, 0, 0) == 1) {
815 while (msg.message != WM_QUIT) {
816 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
817 DispatchMessage(&msg);
818 /* Send the paste buffer if there's anything to send */
820 /* If there's nothing new in the queue then we can do everything
821 * we've delayed, reading the socket, writing, and repainting
824 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
827 /* The messages seem unreliable; especially if we're being tricky */
828 term_set_focus(term, GetForegroundWindow() == hwnd);
830 net_pending_errors();
832 /* There's no point rescanning everything in the message queue
833 * so we do an apparently unnecessary wait here
836 if (GetMessage(&msg, NULL, 0, 0) != 1)
841 cleanup_exit(msg.wParam); /* this doesn't return... */
842 return msg.wParam; /* ... but optimiser doesn't know */
848 void cleanup_exit(int code)
859 if (cfg.protocol == PROT_SSH) {
870 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
872 char *do_select(SOCKET skt, int startup)
877 events = (FD_CONNECT | FD_READ | FD_WRITE |
878 FD_OOB | FD_CLOSE | FD_ACCEPT);
883 return "do_select(): internal error (hwnd==NULL)";
884 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
885 switch (p_WSAGetLastError()) {
887 return "Network is down";
889 return "WSAAsyncSelect(): unknown error";
896 * Refresh the saved-session submenu from `sesslist'.
898 static void update_savedsess_menu(void)
901 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
902 /* skip sesslist.sessions[0] == Default Settings */
904 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
907 AppendMenu(savedsess_menu, MF_ENABLED,
908 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
909 sesslist.sessions[i]);
913 * Update the Special Commands submenu.
915 void update_specials_menu(void *frontend)
918 int menu_already_exists = (specials != NULL);
922 specials = back->get_specials(backhandle);
927 /* We can't use Windows to provide a stack for submenus, so
928 * here's a lame "stack" that will do for now. */
929 HMENU saved_menu = NULL;
931 p = CreatePopupMenu();
932 for (i = 0; nesting > 0; i++) {
933 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
934 switch (specials[i].code) {
936 AppendMenu(p, MF_SEPARATOR, 0, 0);
941 saved_menu = p; /* XXX lame stacking */
942 p = CreatePopupMenu();
943 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
944 (UINT) p, specials[i].name);
949 p = saved_menu; /* XXX lame stacking */
954 AppendMenu(p, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
959 /* Squirrel the highest special. */
966 for (j = 0; j < lenof(popup_menus); j++) {
967 if (menu_already_exists) {
968 /* XXX does this free up all submenus? */
969 DeleteMenu(popup_menus[j].menu,
970 popup_menus[j].specials_submenu_pos,
972 DeleteMenu(popup_menus[j].menu,
973 popup_menus[j].specials_submenu_pos,
977 InsertMenu(popup_menus[j].menu,
978 popup_menus[j].specials_submenu_pos,
979 MF_BYPOSITION | MF_SEPARATOR, 0, 0);
980 InsertMenu(popup_menus[j].menu,
981 popup_menus[j].specials_submenu_pos,
982 MF_BYPOSITION | MF_POPUP | MF_ENABLED,
983 (UINT) p, "S&pecial Command");
988 static void update_mouse_pointer(void)
991 int force_visible = FALSE;
992 static int forced_visible = FALSE;
993 switch (busy_status) {
996 curstype = IDC_ARROW;
998 curstype = IDC_IBEAM;
1001 curstype = IDC_APPSTARTING; /* this may be an abuse */
1002 force_visible = TRUE;
1005 curstype = IDC_WAIT;
1006 force_visible = TRUE;
1012 HCURSOR cursor = LoadCursor(NULL, curstype);
1013 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1014 SetCursor(cursor); /* force redraw of cursor at current posn */
1016 if (force_visible != forced_visible) {
1017 /* We want some cursor shapes to be visible always.
1018 * Along with show_mouseptr(), this manages the ShowCursor()
1019 * counter such that if we switch back to a non-force_visible
1020 * cursor, the previous visibility state is restored. */
1021 ShowCursor(force_visible);
1022 forced_visible = force_visible;
1026 void set_busy_status(void *frontend, int status)
1028 busy_status = status;
1029 update_mouse_pointer();
1033 * set or clear the "raw mouse message" mode
1035 void set_raw_mouse_mode(void *frontend, int activate)
1037 activate = activate && !cfg.no_mouse_rep;
1038 send_raw_mouse = activate;
1039 update_mouse_pointer();
1043 * Print a message box and close the connection.
1045 void connection_fatal(void *frontend, char *fmt, ...)
1048 char *stuff, morestuff[100];
1051 stuff = dupvprintf(fmt, ap);
1053 sprintf(morestuff, "%.70s Fatal Error", appname);
1054 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1057 if (cfg.close_on_exit == FORCE_ON)
1065 * Report an error at the command-line parsing stage.
1067 void cmdline_error(char *fmt, ...)
1070 char *stuff, morestuff[100];
1073 stuff = dupvprintf(fmt, ap);
1075 sprintf(morestuff, "%.70s Command Line Error", appname);
1076 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1082 * Actually do the job requested by a WM_NETEVENT
1084 static void enact_netevent(WPARAM wParam, LPARAM lParam)
1086 static int reentering = 0;
1087 extern int select_result(WPARAM, LPARAM);
1091 return; /* don't unpend the pending */
1094 ret = select_result(wParam, lParam);
1097 if (ret == 0 && !session_closed) {
1098 /* Abnormal exits will already have set session_closed and taken
1099 * appropriate action. */
1100 if (cfg.close_on_exit == FORCE_ON ||
1101 cfg.close_on_exit == AUTO) PostQuitMessage(0);
1104 session_closed = TRUE;
1105 MessageBox(hwnd, "Connection closed by remote host",
1106 appname, MB_OK | MB_ICONINFORMATION);
1112 * Copy the colour palette from the configuration data into defpal.
1113 * This is non-trivial because the colour indices are different.
1115 static void cfgtopalette(void)
1118 static const int ww[] = {
1119 256, 257, 258, 259, 260, 261,
1120 0, 8, 1, 9, 2, 10, 3, 11,
1121 4, 12, 5, 13, 6, 14, 7, 15
1124 for (i = 0; i < 22; i++) {
1126 defpal[w].rgbtRed = cfg.colours[i][0];
1127 defpal[w].rgbtGreen = cfg.colours[i][1];
1128 defpal[w].rgbtBlue = cfg.colours[i][2];
1130 for (i = 0; i < NEXTCOLOURS; i++) {
1132 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1133 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1134 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1135 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
1137 int shade = i - 216;
1138 shade = shade * 10 + 8;
1139 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1140 defpal[i+16].rgbtBlue = shade;
1144 /* Override with system colours if appropriate */
1145 if (cfg.system_colour)
1150 * Override bit of defpal with colours from the system.
1151 * (NB that this takes a copy the system colours at the time this is called,
1152 * so subsequent colour scheme changes don't take effect. To fix that we'd
1153 * probably want to be using GetSysColorBrush() and the like.)
1155 static void systopalette(void)
1158 static const struct { int nIndex; int norm; int bold; } or[] =
1160 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1161 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1162 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1163 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1166 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1167 COLORREF colour = GetSysColor(or[i].nIndex);
1168 defpal[or[i].norm].rgbtRed =
1169 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1170 defpal[or[i].norm].rgbtGreen =
1171 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1172 defpal[or[i].norm].rgbtBlue =
1173 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1178 * Set up the colour palette.
1180 static void init_palette(void)
1183 HDC hdc = GetDC(hwnd);
1185 if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1187 * This is a genuine case where we must use smalloc
1188 * because the snew macros can't cope.
1190 logpal = smalloc(sizeof(*logpal)
1191 - sizeof(logpal->palPalEntry)
1192 + NALLCOLOURS * sizeof(PALETTEENTRY));
1193 logpal->palVersion = 0x300;
1194 logpal->palNumEntries = NALLCOLOURS;
1195 for (i = 0; i < NALLCOLOURS; i++) {
1196 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1197 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1198 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1199 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1201 pal = CreatePalette(logpal);
1203 SelectPalette(hdc, pal, FALSE);
1204 RealizePalette(hdc);
1205 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1208 ReleaseDC(hwnd, hdc);
1211 for (i = 0; i < NALLCOLOURS; i++)
1212 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1213 defpal[i].rgbtGreen,
1214 defpal[i].rgbtBlue);
1216 for (i = 0; i < NALLCOLOURS; i++)
1217 colours[i] = RGB(defpal[i].rgbtRed,
1218 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1222 * This is a wrapper to ExtTextOut() to force Windows to display
1223 * the precise glyphs we give it. Otherwise it would do its own
1224 * bidi and Arabic shaping, and we would end up uncertain which
1225 * characters it had put where.
1227 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1228 unsigned short *lpString, UINT cbCount,
1229 CONST INT *lpDx, int opaque)
1233 * The LCC include files apparently don't supply the
1234 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1235 * proper: the differences aren't important to us (the only
1236 * variable-width string parameter is one we don't use anyway).
1242 char *buffer = snewn(cbCount*2+2, char);
1243 char *classbuffer = snewn(cbCount, char);
1244 memset(&gcpr, 0, sizeof(gcpr));
1245 memset(buffer, 0, cbCount*2+2);
1246 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1248 gcpr.lStructSize = sizeof(gcpr);
1249 gcpr.lpGlyphs = (void *)buffer;
1250 gcpr.lpClass = classbuffer;
1251 gcpr.nGlyphs = cbCount;
1253 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1254 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1256 ExtTextOut(hdc, x, y,
1257 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1258 lprc, buffer, cbCount, lpDx);
1262 * Initialise all the fonts we will need initially. There may be as many as
1263 * three or as few as one. The other (poentially) twentyone fonts are done
1264 * if/when they are needed.
1268 * - check the font width and height, correcting our guesses if
1271 * - verify that the bold font is the same width as the ordinary
1272 * one, and engage shadow bolding if not.
1274 * - verify that the underlined font is the same width as the
1275 * ordinary one (manual underlining by means of line drawing can
1276 * be done in a pinch).
1278 static void init_fonts(int pick_width, int pick_height)
1285 int fw_dontcare, fw_bold;
1287 for (i = 0; i < FONT_MAXNO; i++)
1290 bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
1291 und_mode = UND_FONT;
1293 if (cfg.font.isbold) {
1294 fw_dontcare = FW_BOLD;
1297 fw_dontcare = FW_DONTCARE;
1304 font_height = pick_height;
1306 font_height = cfg.font.height;
1307 if (font_height > 0) {
1309 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1312 font_width = pick_width;
1314 #define f(i,c,w,u) \
1315 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1316 c, OUT_DEFAULT_PRECIS, \
1317 CLIP_DEFAULT_PRECIS, FONT_QUALITY(cfg.font_quality), \
1318 FIXED_PITCH | FF_DONTCARE, cfg.font.name)
1320 f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);
1322 SelectObject(hdc, fonts[FONT_NORMAL]);
1323 GetTextMetrics(hdc, &tm);
1325 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1327 if (pick_width == 0 || pick_height == 0) {
1328 font_height = tm.tmHeight;
1329 font_width = tm.tmAveCharWidth;
1331 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1333 #ifdef RDB_DEBUG_PATCH
1334 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1335 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1340 DWORD cset = tm.tmCharSet;
1341 memset(&info, 0xFF, sizeof(info));
1343 /* !!! Yes the next line is right */
1344 if (cset == OEM_CHARSET)
1345 ucsdata.font_codepage = GetOEMCP();
1347 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1348 ucsdata.font_codepage = info.ciACP;
1350 ucsdata.font_codepage = -1;
1352 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1353 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1356 f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);
1359 * Some fonts, e.g. 9-pt Courier, draw their underlines
1360 * outside their character cell. We successfully prevent
1361 * screen corruption by clipping the text output, but then
1362 * we lose the underline completely. Here we try to work
1363 * out whether this is such a font, and if it is, we set a
1364 * flag that causes underlines to be drawn by hand.
1366 * Having tried other more sophisticated approaches (such
1367 * as examining the TEXTMETRIC structure or requesting the
1368 * height of a string), I think we'll do this the brute
1369 * force way: we create a small bitmap, draw an underlined
1370 * space on it, and test to see whether any pixels are
1371 * foreground-coloured. (Since we expect the underline to
1372 * go all the way across the character cell, we only search
1373 * down a single column of the bitmap, half way across.)
1377 HBITMAP und_bm, und_oldbm;
1381 und_dc = CreateCompatibleDC(hdc);
1382 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1383 und_oldbm = SelectObject(und_dc, und_bm);
1384 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1385 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1386 SetTextColor(und_dc, RGB(255, 255, 255));
1387 SetBkColor(und_dc, RGB(0, 0, 0));
1388 SetBkMode(und_dc, OPAQUE);
1389 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1391 for (i = 0; i < font_height; i++) {
1392 c = GetPixel(und_dc, font_width / 2, i);
1393 if (c != RGB(0, 0, 0))
1396 SelectObject(und_dc, und_oldbm);
1397 DeleteObject(und_bm);
1400 und_mode = UND_LINE;
1401 DeleteObject(fonts[FONT_UNDERLINE]);
1402 fonts[FONT_UNDERLINE] = 0;
1406 if (bold_mode == BOLD_FONT) {
1407 f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);
1411 descent = tm.tmAscent + 1;
1412 if (descent >= font_height)
1413 descent = font_height - 1;
1415 for (i = 0; i < 3; i++) {
1417 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1418 fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
1425 ReleaseDC(hwnd, hdc);
1427 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1428 und_mode = UND_LINE;
1429 DeleteObject(fonts[FONT_UNDERLINE]);
1430 fonts[FONT_UNDERLINE] = 0;
1433 if (bold_mode == BOLD_FONT &&
1434 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1435 bold_mode = BOLD_SHADOW;
1436 DeleteObject(fonts[FONT_BOLD]);
1437 fonts[FONT_BOLD] = 0;
1439 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1441 init_ucs(&cfg, &ucsdata);
1444 static void another_font(int fontno)
1447 int fw_dontcare, fw_bold;
1451 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1454 basefont = (fontno & ~(FONT_BOLDUND));
1455 if (basefont != fontno && !fontflag[basefont])
1456 another_font(basefont);
1458 if (cfg.font.isbold) {
1459 fw_dontcare = FW_BOLD;
1462 fw_dontcare = FW_DONTCARE;
1466 c = cfg.font.charset;
1472 if (fontno & FONT_WIDE)
1474 if (fontno & FONT_NARROW)
1476 if (fontno & FONT_OEM)
1478 if (fontno & FONT_BOLD)
1480 if (fontno & FONT_UNDERLINE)
1484 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1485 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1486 CLIP_DEFAULT_PRECIS, FONT_QUALITY(cfg.font_quality),
1487 FIXED_PITCH | FF_DONTCARE, s);
1489 fontflag[fontno] = 1;
1492 static void deinit_fonts(void)
1495 for (i = 0; i < FONT_MAXNO; i++) {
1497 DeleteObject(fonts[i]);
1503 void request_resize(void *frontend, int w, int h)
1507 /* If the window is maximized supress resizing attempts */
1508 if (IsZoomed(hwnd)) {
1509 if (cfg.resize_action == RESIZE_TERM)
1513 if (cfg.resize_action == RESIZE_DISABLED) return;
1514 if (h == term->rows && w == term->cols) return;
1516 /* Sanity checks ... */
1518 static int first_time = 1;
1521 switch (first_time) {
1523 /* Get the size of the screen */
1524 if (get_fullscreen_rect(&ss))
1525 /* first_time = 0 */ ;
1531 /* Make sure the values are sane */
1532 width = (ss.right - ss.left - extra_width) / 4;
1533 height = (ss.bottom - ss.top - extra_height) / 6;
1535 if (w > width || h > height)
1544 term_size(term, h, w, cfg.savelines);
1546 if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {
1547 width = extra_width + font_width * w;
1548 height = extra_height + font_height * h;
1550 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1551 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1552 SWP_NOMOVE | SWP_NOZORDER);
1556 InvalidateRect(hwnd, NULL, TRUE);
1559 static void reset_window(int reinit) {
1561 * This function decides how to resize or redraw when the
1562 * user changes something.
1564 * This function doesn't like to change the terminal size but if the
1565 * font size is locked that may be it's only soluion.
1567 int win_width, win_height;
1570 #ifdef RDB_DEBUG_PATCH
1571 debug((27, "reset_window()"));
1574 /* Current window sizes ... */
1575 GetWindowRect(hwnd, &wr);
1576 GetClientRect(hwnd, &cr);
1578 win_width = cr.right - cr.left;
1579 win_height = cr.bottom - cr.top;
1581 if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;
1583 /* Are we being forced to reload the fonts ? */
1585 #ifdef RDB_DEBUG_PATCH
1586 debug((27, "reset_window() -- Forced deinit"));
1592 /* Oh, looks like we're minimised */
1593 if (win_width == 0 || win_height == 0)
1596 /* Is the window out of position ? */
1598 (offset_width != (win_width-font_width*term->cols)/2 ||
1599 offset_height != (win_height-font_height*term->rows)/2) ){
1600 offset_width = (win_width-font_width*term->cols)/2;
1601 offset_height = (win_height-font_height*term->rows)/2;
1602 InvalidateRect(hwnd, NULL, TRUE);
1603 #ifdef RDB_DEBUG_PATCH
1604 debug((27, "reset_window() -> Reposition terminal"));
1608 if (IsZoomed(hwnd)) {
1609 /* We're fullscreen, this means we must not change the size of
1610 * the window so it's the font size or the terminal itself.
1613 extra_width = wr.right - wr.left - cr.right + cr.left;
1614 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1616 if (cfg.resize_action != RESIZE_TERM) {
1617 if ( font_width != win_width/term->cols ||
1618 font_height != win_height/term->rows) {
1620 init_fonts(win_width/term->cols, win_height/term->rows);
1621 offset_width = (win_width-font_width*term->cols)/2;
1622 offset_height = (win_height-font_height*term->rows)/2;
1623 InvalidateRect(hwnd, NULL, TRUE);
1624 #ifdef RDB_DEBUG_PATCH
1625 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1626 font_width, font_height));
1630 if ( font_width != win_width/term->cols ||
1631 font_height != win_height/term->rows) {
1632 /* Our only choice at this point is to change the
1633 * size of the terminal; Oh well.
1635 term_size(term, win_height/font_height, win_width/font_width,
1637 offset_width = (win_width-font_width*term->cols)/2;
1638 offset_height = (win_height-font_height*term->rows)/2;
1639 InvalidateRect(hwnd, NULL, TRUE);
1640 #ifdef RDB_DEBUG_PATCH
1641 debug((27, "reset_window() -> Zoomed term_size"));
1648 /* Hmm, a force re-init means we should ignore the current window
1649 * so we resize to the default font size.
1652 #ifdef RDB_DEBUG_PATCH
1653 debug((27, "reset_window() -> Forced re-init"));
1656 offset_width = offset_height = cfg.window_border;
1657 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1658 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1660 if (win_width != font_width*term->cols + offset_width*2 ||
1661 win_height != font_height*term->rows + offset_height*2) {
1663 /* If this is too large windows will resize it to the maximum
1664 * allowed window size, we will then be back in here and resize
1665 * the font or terminal to fit.
1667 SetWindowPos(hwnd, NULL, 0, 0,
1668 font_width*term->cols + extra_width,
1669 font_height*term->rows + extra_height,
1670 SWP_NOMOVE | SWP_NOZORDER);
1673 InvalidateRect(hwnd, NULL, TRUE);
1677 /* Okay the user doesn't want us to change the font so we try the
1678 * window. But that may be too big for the screen which forces us
1679 * to change the terminal.
1681 if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||
1682 (cfg.resize_action == RESIZE_EITHER && reinit<0) ||
1684 offset_width = offset_height = cfg.window_border;
1685 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1686 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1688 if (win_width != font_width*term->cols + offset_width*2 ||
1689 win_height != font_height*term->rows + offset_height*2) {
1694 get_fullscreen_rect(&ss);
1696 width = (ss.right - ss.left - extra_width) / font_width;
1697 height = (ss.bottom - ss.top - extra_height) / font_height;
1700 if ( term->rows > height || term->cols > width ) {
1701 if (cfg.resize_action == RESIZE_EITHER) {
1702 /* Make the font the biggest we can */
1703 if (term->cols > width)
1704 font_width = (ss.right - ss.left - extra_width)
1706 if (term->rows > height)
1707 font_height = (ss.bottom - ss.top - extra_height)
1711 init_fonts(font_width, font_height);
1713 width = (ss.right - ss.left - extra_width) / font_width;
1714 height = (ss.bottom - ss.top - extra_height) / font_height;
1716 if ( height > term->rows ) height = term->rows;
1717 if ( width > term->cols ) width = term->cols;
1718 term_size(term, height, width, cfg.savelines);
1719 #ifdef RDB_DEBUG_PATCH
1720 debug((27, "reset_window() -> term resize to (%d,%d)",
1726 SetWindowPos(hwnd, NULL, 0, 0,
1727 font_width*term->cols + extra_width,
1728 font_height*term->rows + extra_height,
1729 SWP_NOMOVE | SWP_NOZORDER);
1731 InvalidateRect(hwnd, NULL, TRUE);
1732 #ifdef RDB_DEBUG_PATCH
1733 debug((27, "reset_window() -> window resize to (%d,%d)",
1734 font_width*term->cols + extra_width,
1735 font_height*term->rows + extra_height));
1741 /* We're allowed to or must change the font but do we want to ? */
1743 if (font_width != (win_width-cfg.window_border*2)/term->cols ||
1744 font_height != (win_height-cfg.window_border*2)/term->rows) {
1747 init_fonts((win_width-cfg.window_border*2)/term->cols,
1748 (win_height-cfg.window_border*2)/term->rows);
1749 offset_width = (win_width-font_width*term->cols)/2;
1750 offset_height = (win_height-font_height*term->rows)/2;
1752 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1753 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1755 InvalidateRect(hwnd, NULL, TRUE);
1756 #ifdef RDB_DEBUG_PATCH
1757 debug((25, "reset_window() -> font resize to (%d,%d)",
1758 font_width, font_height));
1763 static void set_input_locale(HKL kl)
1767 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1768 lbuf, sizeof(lbuf));
1770 kbd_codepage = atoi(lbuf);
1773 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1775 int thistime = GetMessageTime();
1777 if (send_raw_mouse && !(cfg.mouse_override && shift)) {
1778 lastbtn = MBT_NOTHING;
1779 term_mouse(term, b, translate_button(b), MA_CLICK,
1780 x, y, shift, ctrl, alt);
1784 if (lastbtn == b && thistime - lasttime < dbltime) {
1785 lastact = (lastact == MA_CLICK ? MA_2CLK :
1786 lastact == MA_2CLK ? MA_3CLK :
1787 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1792 if (lastact != MA_NOTHING)
1793 term_mouse(term, b, translate_button(b), lastact,
1794 x, y, shift, ctrl, alt);
1795 lasttime = thistime;
1799 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1800 * into a cooked one (SELECT, EXTEND, PASTE).
1802 static Mouse_Button translate_button(Mouse_Button button)
1804 if (button == MBT_LEFT)
1806 if (button == MBT_MIDDLE)
1807 return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
1808 if (button == MBT_RIGHT)
1809 return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
1810 return 0; /* shouldn't happen */
1813 static void show_mouseptr(int show)
1815 /* NB that the counter in ShowCursor() is also frobbed by
1816 * update_mouse_pointer() */
1817 static int cursor_visible = 1;
1818 if (!cfg.hide_mouseptr) /* override if this feature disabled */
1820 if (cursor_visible && !show)
1822 else if (!cursor_visible && show)
1824 cursor_visible = show;
1827 static int is_alt_pressed(void)
1830 int r = GetKeyboardState(keystate);
1833 if (keystate[VK_MENU] & 0x80)
1835 if (keystate[VK_RMENU] & 0x80)
1840 static int is_shift_pressed(void)
1843 int r = GetKeyboardState(keystate);
1846 if (keystate[VK_SHIFT] & 0x80)
1851 static int resizing;
1853 void notify_remote_exit(void *fe) { /* stub not needed in this frontend */ }
1855 void timer_change_notify(long next)
1857 long ticks = next - GETTICKCOUNT();
1858 if (ticks <= 0) ticks = 1; /* just in case */
1859 KillTimer(hwnd, TIMING_TIMER_ID);
1860 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
1861 timing_next_time = next;
1864 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1865 WPARAM wParam, LPARAM lParam)
1868 static int ignore_clip = FALSE;
1869 static int need_backend_resize = FALSE;
1870 static int fullscr_on_max = FALSE;
1871 static UINT last_mousemove = 0;
1875 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
1878 KillTimer(hwnd, TIMING_TIMER_ID);
1879 if (run_timers(timing_next_time, &next)) {
1880 timer_change_notify(next);
1891 str = dupprintf("%s Exit Confirmation", appname);
1892 if (!cfg.warn_on_close || session_closed ||
1894 "Are you sure you want to close this session?",
1895 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
1897 DestroyWindow(hwnd);
1905 case WM_INITMENUPOPUP:
1906 if ((HMENU)wParam == savedsess_menu) {
1907 /* About to pop up Saved Sessions sub-menu.
1908 * Refresh the session list. */
1909 get_sesslist(&sesslist, FALSE); /* free */
1910 get_sesslist(&sesslist, TRUE);
1911 update_savedsess_menu();
1917 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
1928 BOOL inherit_handles;
1930 PROCESS_INFORMATION pi;
1931 HANDLE filemap = NULL;
1933 if (wParam == IDM_DUPSESS) {
1935 * Allocate a file-mapping memory chunk for the
1938 SECURITY_ATTRIBUTES sa;
1941 sa.nLength = sizeof(sa);
1942 sa.lpSecurityDescriptor = NULL;
1943 sa.bInheritHandle = TRUE;
1944 filemap = CreateFileMapping((HANDLE) 0xFFFFFFFF,
1947 0, sizeof(Config), NULL);
1949 p = (Config *) MapViewOfFile(filemap,
1951 0, 0, sizeof(Config));
1953 *p = cfg; /* structure copy */
1957 inherit_handles = TRUE;
1958 sprintf(c, "putty &%p", filemap);
1960 } else if (wParam == IDM_SAVEDSESS) {
1961 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
1962 / MENU_SAVED_STEP) + 1;
1963 if (sessno < sesslist.nsessions) {
1964 char *session = sesslist.sessions[sessno];
1965 /* XXX spaces? quotes? "-load"? */
1966 cl = dupprintf("putty @%s", session);
1967 inherit_handles = FALSE;
1971 } else /* IDM_NEWSESS */ {
1973 inherit_handles = FALSE;
1976 GetModuleFileName(NULL, b, sizeof(b) - 1);
1978 si.lpReserved = NULL;
1979 si.lpDesktop = NULL;
1983 si.lpReserved2 = NULL;
1984 CreateProcess(b, cl, NULL, NULL, inherit_handles,
1985 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
1988 CloseHandle(filemap);
1995 logevent(NULL, "----- Session restarted -----");
2004 int reconfig_result;
2009 reconfiguring = TRUE;
2011 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
2015 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2016 reconfiguring = FALSE;
2017 if (!reconfig_result)
2021 /* Disable full-screen if resizing forbidden */
2022 HMENU m = GetSystemMenu (hwnd, FALSE);
2023 EnableMenuItem(m, IDM_FULLSCREEN, MF_BYCOMMAND |
2024 (cfg.resize_action == RESIZE_DISABLED)
2025 ? MF_GRAYED : MF_ENABLED);
2026 /* Gracefully unzoom if necessary */
2027 if (IsZoomed(hwnd) &&
2028 (cfg.resize_action == RESIZE_DISABLED)) {
2029 ShowWindow(hwnd, SW_RESTORE);
2033 /* Pass new config data to the logging module */
2034 log_reconfig(logctx, &cfg);
2038 * Flush the line discipline's edit buffer in the
2039 * case where local editing has just been disabled.
2042 ldisc_send(ldisc, NULL, 0, 0);
2050 /* Pass new config data to the terminal */
2051 term_reconfig(term, &cfg);
2053 /* Pass new config data to the back end */
2055 back->reconfig(backhandle, &cfg);
2057 /* Screen size changed ? */
2058 if (cfg.height != prev_cfg.height ||
2059 cfg.width != prev_cfg.width ||
2060 cfg.savelines != prev_cfg.savelines ||
2061 cfg.resize_action == RESIZE_FONT ||
2062 (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2063 cfg.resize_action == RESIZE_DISABLED)
2064 term_size(term, cfg.height, cfg.width, cfg.savelines);
2066 /* Enable or disable the scroll bar, etc */
2068 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2069 LONG nexflag, exflag =
2070 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2073 if (cfg.alwaysontop != prev_cfg.alwaysontop) {
2074 if (cfg.alwaysontop) {
2075 nexflag |= WS_EX_TOPMOST;
2076 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2077 SWP_NOMOVE | SWP_NOSIZE);
2079 nexflag &= ~(WS_EX_TOPMOST);
2080 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2081 SWP_NOMOVE | SWP_NOSIZE);
2084 if (cfg.sunken_edge)
2085 nexflag |= WS_EX_CLIENTEDGE;
2087 nexflag &= ~(WS_EX_CLIENTEDGE);
2090 if (is_full_screen() ?
2091 cfg.scrollbar_in_fullscreen : cfg.scrollbar)
2094 nflg &= ~WS_VSCROLL;
2096 if (cfg.resize_action == RESIZE_DISABLED ||
2098 nflg &= ~WS_THICKFRAME;
2100 nflg |= WS_THICKFRAME;
2102 if (cfg.resize_action == RESIZE_DISABLED)
2103 nflg &= ~WS_MAXIMIZEBOX;
2105 nflg |= WS_MAXIMIZEBOX;
2107 if (nflg != flag || nexflag != exflag) {
2109 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2110 if (nexflag != exflag)
2111 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2113 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2114 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2115 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2123 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2128 set_title(NULL, cfg.wintitle);
2129 if (IsIconic(hwnd)) {
2131 cfg.win_name_always ? window_name :
2135 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
2136 strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
2137 cfg.font.isbold != prev_cfg.font.isbold ||
2138 cfg.font.height != prev_cfg.font.height ||
2139 cfg.font.charset != prev_cfg.font.charset ||
2140 cfg.font_quality != prev_cfg.font_quality ||
2141 cfg.vtmode != prev_cfg.vtmode ||
2142 cfg.bold_colour != prev_cfg.bold_colour ||
2143 cfg.resize_action == RESIZE_DISABLED ||
2144 cfg.resize_action == RESIZE_EITHER ||
2145 (cfg.resize_action != prev_cfg.resize_action))
2148 InvalidateRect(hwnd, NULL, TRUE);
2149 reset_window(init_lvl);
2150 net_pending_errors();
2157 term_do_paste(term);
2165 ldisc_send(ldisc, NULL, 0, 0);
2171 WinHelp(hwnd, help_path,
2172 help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
2176 * We get this if the System menu has been activated
2183 * We get this if the System menu has been activated
2184 * using the keyboard. This might happen from within
2185 * TranslateKey, in which case it really wants to be
2186 * followed by a `space' character to actually _bring
2187 * the menu up_ rather than just sitting there in
2188 * `ready to appear' state.
2190 show_mouseptr(1); /* make sure pointer is visible */
2192 PostMessage(hwnd, WM_CHAR, ' ', 0);
2194 case IDM_FULLSCREEN:
2198 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2199 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2201 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2202 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2204 * Ensure we haven't been sent a bogus SYSCOMMAND
2205 * which would cause us to reference invalid memory
2206 * and crash. Perhaps I'm just too paranoid here.
2208 if (i >= n_specials)
2211 back->special(backhandle, specials[i].code);
2212 net_pending_errors();
2217 #define X_POS(l) ((int)(short)LOWORD(l))
2218 #define Y_POS(l) ((int)(short)HIWORD(l))
2220 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2221 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2222 case WM_LBUTTONDOWN:
2223 case WM_MBUTTONDOWN:
2224 case WM_RBUTTONDOWN:
2228 if (message == WM_RBUTTONDOWN &&
2229 ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
2232 show_mouseptr(1); /* make sure pointer is visible */
2233 GetCursorPos(&cursorpos);
2234 TrackPopupMenu(popup_menus[CTXMENU].menu,
2235 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2236 cursorpos.x, cursorpos.y,
2244 case WM_LBUTTONDOWN:
2248 case WM_MBUTTONDOWN:
2249 button = MBT_MIDDLE;
2252 case WM_RBUTTONDOWN:
2261 button = MBT_MIDDLE;
2269 button = press = 0; /* shouldn't happen */
2273 * Special case: in full-screen mode, if the left
2274 * button is clicked in the very top left corner of the
2275 * window, we put up the System menu instead of doing
2279 char mouse_on_hotspot = 0;
2288 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2291 mi.cbSize = sizeof(MONITORINFO);
2292 GetMonitorInfo(mon, &mi);
2294 if (mi.rcMonitor.left == pt.x &&
2295 mi.rcMonitor.top == pt.y) {
2296 mouse_on_hotspot = 1;
2301 if (pt.x == 0 && pt.y == 0) {
2302 mouse_on_hotspot = 1;
2305 if (is_full_screen() && press &&
2306 button == MBT_LEFT && mouse_on_hotspot) {
2307 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2308 MAKELPARAM(pt.x, pt.y));
2315 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2316 wParam & MK_SHIFT, wParam & MK_CONTROL,
2320 term_mouse(term, button, translate_button(button), MA_RELEASE,
2321 TO_CHR_X(X_POS(lParam)),
2322 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2323 wParam & MK_CONTROL, is_alt_pressed());
2331 * Windows seems to like to occasionally send MOUSEMOVE
2332 * events even if the mouse hasn't moved. Don't unhide
2333 * the mouse pointer in this case.
2335 static WPARAM wp = 0;
2336 static LPARAM lp = 0;
2337 if (wParam != wp || lParam != lp ||
2338 last_mousemove != WM_MOUSEMOVE) {
2340 wp = wParam; lp = lParam;
2341 last_mousemove = WM_MOUSEMOVE;
2345 * Add the mouse position and message time to the random
2348 noise_ultralight(lParam);
2350 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2351 GetCapture() == hwnd) {
2353 if (wParam & MK_LBUTTON)
2355 else if (wParam & MK_MBUTTON)
2359 term_mouse(term, b, translate_button(b), MA_DRAG,
2360 TO_CHR_X(X_POS(lParam)),
2361 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2362 wParam & MK_CONTROL, is_alt_pressed());
2365 case WM_NCMOUSEMOVE:
2367 static WPARAM wp = 0;
2368 static LPARAM lp = 0;
2369 if (wParam != wp || lParam != lp ||
2370 last_mousemove != WM_NCMOUSEMOVE) {
2372 wp = wParam; lp = lParam;
2373 last_mousemove = WM_NCMOUSEMOVE;
2376 noise_ultralight(lParam);
2378 case WM_IGNORE_CLIP:
2379 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2381 case WM_DESTROYCLIPBOARD:
2383 term_deselect(term);
2384 ignore_clip = FALSE;
2391 hdc = BeginPaint(hwnd, &p);
2393 SelectPalette(hdc, pal, TRUE);
2394 RealizePalette(hdc);
2398 * We have to be careful about term_paint(). It will
2399 * set a bunch of character cells to INVALID and then
2400 * call do_paint(), which will redraw those cells and
2401 * _then mark them as done_. This may not be accurate:
2402 * when painting in WM_PAINT context we are restricted
2403 * to the rectangle which has just been exposed - so if
2404 * that only covers _part_ of a character cell and the
2405 * rest of it was already visible, that remainder will
2406 * not be redrawn at all. Accordingly, we must not
2407 * paint any character cell in a WM_PAINT context which
2408 * already has a pending update due to terminal output.
2409 * The simplest solution to this - and many, many
2410 * thanks to Hung-Te Lin for working all this out - is
2411 * not to do any actual painting at _all_ if there's a
2412 * pending terminal update: just mark the relevant
2413 * character cells as INVALID and wait for the
2414 * scheduled full update to sort it out.
2416 * I have a suspicion this isn't the _right_ solution.
2417 * An alternative approach would be to have terminal.c
2418 * separately track what _should_ be on the terminal
2419 * screen and what _is_ on the terminal screen, and
2420 * have two completely different types of redraw (one
2421 * for full updates, which syncs the former with the
2422 * terminal itself, and one for WM_PAINT which syncs
2423 * the latter with the former); yet another possibility
2424 * would be to have the Windows front end do what the
2425 * GTK one already does, and maintain a bitmap of the
2426 * current terminal appearance so that WM_PAINT becomes
2427 * completely trivial. However, this should do for now.
2429 term_paint(term, hdc,
2430 (p.rcPaint.left-offset_width)/font_width,
2431 (p.rcPaint.top-offset_height)/font_height,
2432 (p.rcPaint.right-offset_width-1)/font_width,
2433 (p.rcPaint.bottom-offset_height-1)/font_height,
2434 !term->window_update_pending);
2437 p.rcPaint.left < offset_width ||
2438 p.rcPaint.top < offset_height ||
2439 p.rcPaint.right >= offset_width + font_width*term->cols ||
2440 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2442 HBRUSH fillcolour, oldbrush;
2444 fillcolour = CreateSolidBrush (
2445 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2446 oldbrush = SelectObject(hdc, fillcolour);
2447 edge = CreatePen(PS_SOLID, 0,
2448 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2449 oldpen = SelectObject(hdc, edge);
2452 * Jordan Russell reports that this apparently
2453 * ineffectual IntersectClipRect() call masks a
2454 * Windows NT/2K bug causing strange display
2455 * problems when the PuTTY window is taller than
2456 * the primary monitor. It seems harmless enough...
2458 IntersectClipRect(hdc,
2459 p.rcPaint.left, p.rcPaint.top,
2460 p.rcPaint.right, p.rcPaint.bottom);
2462 ExcludeClipRect(hdc,
2463 offset_width, offset_height,
2464 offset_width+font_width*term->cols,
2465 offset_height+font_height*term->rows);
2467 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2468 p.rcPaint.right, p.rcPaint.bottom);
2470 /* SelectClipRgn(hdc, NULL); */
2472 SelectObject(hdc, oldbrush);
2473 DeleteObject(fillcolour);
2474 SelectObject(hdc, oldpen);
2477 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2478 SelectObject(hdc, GetStockObject(WHITE_PEN));
2484 enact_netevent(wParam, lParam);
2485 net_pending_errors();
2488 term_set_focus(term, TRUE);
2489 CreateCaret(hwnd, caretbm, font_width, font_height);
2491 flash_window(0); /* stop */
2497 term_set_focus(term, FALSE);
2499 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2502 case WM_ENTERSIZEMOVE:
2503 #ifdef RDB_DEBUG_PATCH
2504 debug((27, "WM_ENTERSIZEMOVE"));
2508 need_backend_resize = FALSE;
2510 case WM_EXITSIZEMOVE:
2513 #ifdef RDB_DEBUG_PATCH
2514 debug((27, "WM_EXITSIZEMOVE"));
2516 if (need_backend_resize) {
2517 term_size(term, cfg.height, cfg.width, cfg.savelines);
2518 InvalidateRect(hwnd, NULL, TRUE);
2523 * This does two jobs:
2524 * 1) Keep the sizetip uptodate
2525 * 2) Make sure the window size is _stepped_ in units of the font size.
2527 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2528 int width, height, w, h, ew, eh;
2529 LPRECT r = (LPRECT) lParam;
2531 if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
2532 (cfg.height != term->rows || cfg.width != term->cols )) {
2534 * Great! It seems that both the terminal size and the
2535 * font size have been changed and the user is now dragging.
2537 * It will now be difficult to get back to the configured
2540 * This would be easier but it seems to be too confusing.
2542 term_size(term, cfg.height, cfg.width, cfg.savelines);
2545 cfg.height=term->rows; cfg.width=term->cols;
2547 InvalidateRect(hwnd, NULL, TRUE);
2548 need_backend_resize = TRUE;
2551 width = r->right - r->left - extra_width;
2552 height = r->bottom - r->top - extra_height;
2553 w = (width + font_width / 2) / font_width;
2556 h = (height + font_height / 2) / font_height;
2559 UpdateSizeTip(hwnd, w, h);
2560 ew = width - w * font_width;
2561 eh = height - h * font_height;
2563 if (wParam == WMSZ_LEFT ||
2564 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2570 if (wParam == WMSZ_TOP ||
2571 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2581 int width, height, w, h, rv = 0;
2582 int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2583 int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2584 LPRECT r = (LPRECT) lParam;
2586 width = r->right - r->left - ex_width;
2587 height = r->bottom - r->top - ex_height;
2589 w = (width + term->cols/2)/term->cols;
2590 h = (height + term->rows/2)/term->rows;
2591 if ( r->right != r->left + w*term->cols + ex_width)
2594 if (wParam == WMSZ_LEFT ||
2595 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2596 r->left = r->right - w*term->cols - ex_width;
2598 r->right = r->left + w*term->cols + ex_width;
2600 if (r->bottom != r->top + h*term->rows + ex_height)
2603 if (wParam == WMSZ_TOP ||
2604 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2605 r->top = r->bottom - h*term->rows - ex_height;
2607 r->bottom = r->top + h*term->rows + ex_height;
2611 /* break; (never reached) */
2612 case WM_FULLSCR_ON_MAX:
2613 fullscr_on_max = TRUE;
2616 sys_cursor_update();
2619 #ifdef RDB_DEBUG_PATCH
2620 debug((27, "WM_SIZE %s (%d,%d)",
2621 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2622 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2623 (wParam == SIZE_RESTORED && resizing) ? "to":
2624 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2626 LOWORD(lParam), HIWORD(lParam)));
2628 if (wParam == SIZE_MINIMIZED)
2630 cfg.win_name_always ? window_name : icon_name);
2631 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2632 SetWindowText(hwnd, window_name);
2633 if (wParam == SIZE_RESTORED)
2634 clear_full_screen();
2635 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2636 fullscr_on_max = FALSE;
2640 if (cfg.resize_action == RESIZE_DISABLED) {
2641 /* A resize, well it better be a minimize. */
2645 int width, height, w, h;
2647 width = LOWORD(lParam);
2648 height = HIWORD(lParam);
2651 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2653 prev_rows = term->rows;
2654 prev_cols = term->cols;
2655 if (cfg.resize_action == RESIZE_TERM) {
2656 w = width / font_width;
2658 h = height / font_height;
2661 term_size(term, h, w, cfg.savelines);
2664 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2666 if (cfg.resize_action == RESIZE_TERM)
2667 term_size(term, prev_rows, prev_cols, cfg.savelines);
2668 if (cfg.resize_action != RESIZE_FONT)
2673 /* This is an unexpected resize, these will normally happen
2674 * if the window is too large. Probably either the user
2675 * selected a huge font or the screen size has changed.
2677 * This is also called with minimize.
2679 else reset_window(-1);
2683 * Don't call back->size in mid-resize. (To prevent
2684 * massive numbers of resize events getting sent
2685 * down the connection during an NT opaque drag.)
2688 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2689 need_backend_resize = TRUE;
2690 w = (width-cfg.window_border*2) / font_width;
2692 h = (height-cfg.window_border*2) / font_height;
2701 sys_cursor_update();
2704 switch (LOWORD(wParam)) {
2706 term_scroll(term, -1, 0);
2709 term_scroll(term, +1, 0);
2712 term_scroll(term, 0, +1);
2715 term_scroll(term, 0, -1);
2718 term_scroll(term, 0, +term->rows / 2);
2721 term_scroll(term, 0, -term->rows / 2);
2723 case SB_THUMBPOSITION:
2725 term_scroll(term, 1, HIWORD(wParam));
2729 case WM_PALETTECHANGED:
2730 if ((HWND) wParam != hwnd && pal != NULL) {
2731 HDC hdc = get_ctx(NULL);
2733 if (RealizePalette(hdc) > 0)
2739 case WM_QUERYNEWPALETTE:
2741 HDC hdc = get_ctx(NULL);
2743 if (RealizePalette(hdc) > 0)
2755 * Add the scan code and keypress timing to the random
2758 noise_ultralight(lParam);
2761 * We don't do TranslateMessage since it disassociates the
2762 * resulting CHAR message from the KEYDOWN that sparked it,
2763 * which we occasionally don't want. Instead, we process
2764 * KEYDOWN, and call the Win32 translator functions so that
2765 * we get the translations under _our_ control.
2768 unsigned char buf[20];
2771 if (wParam == VK_PROCESSKEY) { /* IME PROCESS key */
2772 if (message == WM_KEYDOWN) {
2775 m.message = WM_KEYDOWN;
2777 m.lParam = lParam & 0xdfff;
2778 TranslateMessage(&m);
2779 } else break; /* pass to Windows for default processing */
2781 len = TranslateKey(message, wParam, lParam, buf);
2783 return DefWindowProc(hwnd, message, wParam, lParam);
2787 * Interrupt an ongoing paste. I'm not sure
2788 * this is sensible, but for the moment it's
2789 * preferable to having to faff about buffering
2795 * We need not bother about stdin backlogs
2796 * here, because in GUI PuTTY we can't do
2797 * anything about it anyway; there's no means
2798 * of asking Windows to hold off on KEYDOWN
2799 * messages. We _have_ to buffer everything
2802 term_seen_key_event(term);
2804 ldisc_send(ldisc, buf, len, 1);
2809 net_pending_errors();
2811 case WM_INPUTLANGCHANGE:
2812 /* wParam == Font number */
2813 /* lParam == Locale */
2814 set_input_locale((HKL)lParam);
2815 sys_cursor_update();
2817 case WM_IME_STARTCOMPOSITION:
2819 HIMC hImc = ImmGetContext(hwnd);
2820 ImmSetCompositionFont(hImc, &lfont);
2821 ImmReleaseContext(hwnd, hImc);
2824 case WM_IME_COMPOSITION:
2830 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
2831 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2833 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2834 break; /* fall back to DefWindowProc */
2836 hIMC = ImmGetContext(hwnd);
2837 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2841 buff = snewn(n, char);
2842 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
2844 * Jaeyoun Chung reports that Korean character
2845 * input doesn't work correctly if we do a single
2846 * luni_send() covering the whole of buff. So
2847 * instead we luni_send the characters one by one.
2849 term_seen_key_event(term);
2850 for (i = 0; i < n; i += 2) {
2852 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2856 ImmReleaseContext(hwnd, hIMC);
2861 if (wParam & 0xFF00) {
2862 unsigned char buf[2];
2865 buf[0] = wParam >> 8;
2866 term_seen_key_event(term);
2868 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
2870 char c = (unsigned char) wParam;
2871 term_seen_key_event(term);
2873 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
2879 * Nevertheless, we are prepared to deal with WM_CHAR
2880 * messages, should they crop up. So if someone wants to
2881 * post the things to us as part of a macro manoeuvre,
2882 * we're ready to cope.
2885 char c = (unsigned char)wParam;
2886 term_seen_key_event(term);
2888 lpage_send(ldisc, CP_ACP, &c, 1, 1);
2891 case WM_SYSCOLORCHANGE:
2892 if (cfg.system_colour) {
2893 /* Refresh palette from system colours. */
2894 /* XXX actually this zaps the entire palette. */
2897 /* Force a repaint of the terminal window. */
2898 term_invalidate(term);
2901 case WM_AGENT_CALLBACK:
2903 struct agent_callback *c = (struct agent_callback *)lParam;
2904 c->callback(c->callback_ctx, c->data, c->len);
2909 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
2910 int shift_pressed=0, control_pressed=0;
2912 if (message == WM_MOUSEWHEEL) {
2913 wheel_accumulator += (short)HIWORD(wParam);
2914 shift_pressed=LOWORD(wParam) & MK_SHIFT;
2915 control_pressed=LOWORD(wParam) & MK_CONTROL;
2918 wheel_accumulator += (int)wParam;
2919 if (GetKeyboardState(keys)!=0) {
2920 shift_pressed=keys[VK_SHIFT]&0x80;
2921 control_pressed=keys[VK_CONTROL]&0x80;
2925 /* process events when the threshold is reached */
2926 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
2929 /* reduce amount for next time */
2930 if (wheel_accumulator > 0) {
2932 wheel_accumulator -= WHEEL_DELTA;
2933 } else if (wheel_accumulator < 0) {
2935 wheel_accumulator += WHEEL_DELTA;
2939 if (send_raw_mouse &&
2940 !(cfg.mouse_override && shift_pressed)) {
2941 /* send a mouse-down followed by a mouse up */
2942 term_mouse(term, b, translate_button(b),
2944 TO_CHR_X(X_POS(lParam)),
2945 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2946 control_pressed, is_alt_pressed());
2947 term_mouse(term, b, translate_button(b),
2948 MA_RELEASE, TO_CHR_X(X_POS(lParam)),
2949 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2950 control_pressed, is_alt_pressed());
2952 /* trigger a scroll */
2953 term_scroll(term, 0,
2955 -term->rows / 2 : term->rows / 2);
2963 * Any messages we don't process completely above are passed through to
2964 * DefWindowProc() for default processing.
2966 return DefWindowProc(hwnd, message, wParam, lParam);
2970 * Move the system caret. (We maintain one, even though it's
2971 * invisible, for the benefit of blind people: apparently some
2972 * helper software tracks the system caret, so we should arrange to
2975 void sys_cursor(void *frontend, int x, int y)
2979 if (!term->has_focus) return;
2982 * Avoid gratuitously re-updating the cursor position and IMM
2983 * window if there's no actual change required.
2985 cx = x * font_width + offset_width;
2986 cy = y * font_height + offset_height;
2987 if (cx == caret_x && cy == caret_y)
2992 sys_cursor_update();
2995 static void sys_cursor_update(void)
3000 if (!term->has_focus) return;
3002 if (caret_x < 0 || caret_y < 0)
3005 SetCaretPos(caret_x, caret_y);
3007 /* IMM calls on Win98 and beyond only */
3008 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3010 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3011 osVersion.dwMinorVersion == 0) return; /* 95 */
3013 /* we should have the IMM functions */
3014 hIMC = ImmGetContext(hwnd);
3015 cf.dwStyle = CFS_POINT;
3016 cf.ptCurrentPos.x = caret_x;
3017 cf.ptCurrentPos.y = caret_y;
3018 ImmSetCompositionWindow(hIMC, &cf);
3020 ImmReleaseContext(hwnd, hIMC);
3024 * Draw a line of text in the window, at given character
3025 * coordinates, in given attributes.
3027 * We are allowed to fiddle with the contents of `text'.
3029 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3030 unsigned long attr, int lattr)
3033 int nfg, nbg, nfont;
3036 int force_manual_underline = 0;
3037 int fnt_width, char_width;
3038 int text_adjust = 0;
3039 static int *IpDx = 0, IpDxLEN = 0;
3041 lattr &= LATTR_MODE;
3043 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3045 if (attr & ATTR_WIDE)
3048 if (len > IpDxLEN || IpDx[0] != char_width) {
3050 if (len > IpDxLEN) {
3052 IpDx = snewn(len + 16, int);
3053 IpDxLEN = (len + 16);
3055 for (i = 0; i < IpDxLEN; i++)
3056 IpDx[i] = char_width;
3059 /* Only want the left half of double width lines */
3060 if (lattr != LATTR_NORM && x*2 >= term->cols)
3068 if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
3069 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3070 if (bold_mode == BOLD_COLOURS)
3073 /* cursor fg and bg */
3074 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3078 if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3079 /* Assume a poorman font is borken in other ways too. */
3089 nfont |= FONT_WIDE + FONT_HIGH;
3092 if (attr & ATTR_NARROW)
3093 nfont |= FONT_NARROW;
3095 /* Special hack for the VT100 linedraw glyphs. */
3096 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3097 switch ((unsigned char) (text[0])) {
3099 text_adjust = -2 * font_height / 5;
3102 text_adjust = -1 * font_height / 5;
3105 text_adjust = font_height / 5;
3108 text_adjust = 2 * font_height / 5;
3111 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3113 text[0] = ucsdata.unitab_xterm['q'];
3114 if (attr & ATTR_UNDER) {
3115 attr &= ~ATTR_UNDER;
3116 force_manual_underline = 1;
3120 /* Anything left as an original character set is unprintable. */
3121 if (DIRECT_CHAR(text[0])) {
3123 for (i = 0; i < len; i++)
3128 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3131 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3132 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3133 if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
3135 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3136 nfont |= FONT_UNDERLINE;
3137 another_font(nfont);
3138 if (!fonts[nfont]) {
3139 if (nfont & FONT_UNDERLINE)
3140 force_manual_underline = 1;
3141 /* Don't do the same for manual bold, it could be bad news. */
3143 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3145 another_font(nfont);
3147 nfont = FONT_NORMAL;
3148 if (attr & ATTR_REVERSE) {
3153 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD)) {
3154 if (nfg < 16) nfg |= 8;
3155 else if (nfg >= 256) nfg |= 1;
3157 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK)) {
3158 if (nbg < 16) nbg |= 8;
3159 else if (nbg >= 256) nbg |= 1;
3163 SelectObject(hdc, fonts[nfont]);
3164 SetTextColor(hdc, fg);
3165 SetBkColor(hdc, bg);
3166 if (attr & TATTR_COMBINING)
3167 SetBkMode(hdc, TRANSPARENT);
3169 SetBkMode(hdc, OPAQUE);
3172 line_box.right = x + char_width * len;
3173 line_box.bottom = y + font_height;
3175 /* Only want the left half of double width lines */
3176 if (line_box.right > font_width*term->cols+offset_width)
3177 line_box.right = font_width*term->cols+offset_width;
3179 /* We're using a private area for direct to font. (512 chars.) */
3180 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3181 /* Ho Hum, dbcs fonts are a PITA! */
3182 /* To display on W9x I have to convert to UCS */
3183 static wchar_t *uni_buf = 0;
3184 static int uni_len = 0;
3186 if (len > uni_len) {
3189 uni_buf = snewn(uni_len, wchar_t);
3192 for(nlen = mptr = 0; mptr<len; mptr++) {
3193 uni_buf[nlen] = 0xFFFD;
3194 if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
3196 dbcstext[0] = text[mptr] & 0xFF;
3197 dbcstext[1] = text[mptr+1] & 0xFF;
3198 IpDx[nlen] += char_width;
3199 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3200 dbcstext, 2, uni_buf+nlen, 1);
3206 dbcstext[0] = text[mptr] & 0xFF;
3207 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3208 dbcstext, 1, uni_buf+nlen, 1);
3216 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3217 ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
3218 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3219 SetBkMode(hdc, TRANSPARENT);
3220 ExtTextOutW(hdc, x - 1,
3221 y - font_height * (lattr ==
3222 LATTR_BOT) + text_adjust,
3223 ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
3227 } else if (DIRECT_FONT(text[0])) {
3228 static char *directbuf = NULL;
3229 static int directlen = 0;
3231 if (len > directlen) {
3233 directbuf = sresize(directbuf, directlen, char);
3236 for (i = 0; i < len; i++)
3237 directbuf[i] = text[i] & 0xFF;
3240 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3241 ETO_CLIPPED | ETO_OPAQUE, &line_box, directbuf, len, IpDx);
3242 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3243 SetBkMode(hdc, TRANSPARENT);
3245 /* GRR: This draws the character outside it's box and can leave
3246 * 'droppings' even with the clip box! I suppose I could loop it
3247 * one character at a time ... yuk.
3249 * Or ... I could do a test print with "W", and use +1 or -1 for this
3250 * shift depending on if the leftmost column is blank...
3252 ExtTextOut(hdc, x - 1,
3253 y - font_height * (lattr ==
3254 LATTR_BOT) + text_adjust,
3255 ETO_CLIPPED, &line_box, directbuf, len, IpDx);
3258 /* And 'normal' unicode characters */
3259 static WCHAR *wbuf = NULL;
3260 static int wlen = 0;
3266 wbuf = snewn(wlen, WCHAR);
3269 for (i = 0; i < len; i++)
3272 /* print Glyphs as they are, without Windows' Shaping*/
3273 exact_textout(hdc, x, y - font_height * (lattr == LATTR_BOT) + text_adjust,
3274 &line_box, wbuf, len, IpDx, !(attr & TATTR_COMBINING));
3275 /* ExtTextOutW(hdc, x,
3276 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3277 ETO_CLIPPED | ETO_OPAQUE, &line_box, wbuf, len, IpDx);
3280 /* And the shadow bold hack. */
3281 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3282 SetBkMode(hdc, TRANSPARENT);
3283 ExtTextOutW(hdc, x - 1,
3284 y - font_height * (lattr ==
3285 LATTR_BOT) + text_adjust,
3286 ETO_CLIPPED, &line_box, wbuf, len, IpDx);
3289 if (lattr != LATTR_TOP && (force_manual_underline ||
3290 (und_mode == UND_LINE
3291 && (attr & ATTR_UNDER)))) {
3294 if (lattr == LATTR_BOT)
3295 dec = dec * 2 - font_height;
3297 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3298 MoveToEx(hdc, x, y + dec, NULL);
3299 LineTo(hdc, x + len * char_width, y + dec);
3300 oldpen = SelectObject(hdc, oldpen);
3301 DeleteObject(oldpen);
3306 * Wrapper that handles combining characters.
3308 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3309 unsigned long attr, int lattr)
3311 if (attr & TATTR_COMBINING) {
3312 unsigned long a = 0;
3313 attr &= ~TATTR_COMBINING;
3315 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3317 a = TATTR_COMBINING;
3320 do_text_internal(ctx, x, y, text, len, attr, lattr);
3323 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3324 unsigned long attr, int lattr)
3330 int ctype = cfg.cursor_type;
3332 lattr &= LATTR_MODE;
3334 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3335 if (*text != UCSWIDE) {
3336 do_text(ctx, x, y, text, len, attr, lattr);
3340 attr |= TATTR_RIGHTCURS;
3343 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3344 if (attr & ATTR_WIDE)
3351 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3354 pts[0].x = pts[1].x = pts[4].x = x;
3355 pts[2].x = pts[3].x = x + char_width - 1;
3356 pts[0].y = pts[3].y = pts[4].y = y;
3357 pts[1].y = pts[2].y = y + font_height - 1;
3358 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3359 Polyline(hdc, pts, 5);
3360 oldpen = SelectObject(hdc, oldpen);
3361 DeleteObject(oldpen);
3362 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3363 int startx, starty, dx, dy, length, i;
3366 starty = y + descent;
3369 length = char_width;
3372 if (attr & TATTR_RIGHTCURS)
3373 xadjust = char_width - 1;
3374 startx = x + xadjust;
3378 length = font_height;
3380 if (attr & TATTR_ACTCURS) {
3383 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3384 MoveToEx(hdc, startx, starty, NULL);
3385 LineTo(hdc, startx + dx * length, starty + dy * length);
3386 oldpen = SelectObject(hdc, oldpen);
3387 DeleteObject(oldpen);
3389 for (i = 0; i < length; i++) {
3391 SetPixel(hdc, startx, starty, colours[261]);
3400 /* This function gets the actual width of a character in the normal font.
3402 int char_width(Context ctx, int uc) {
3406 /* If the font max is the same as the font ave width then this
3407 * function is a no-op.
3409 if (!font_dualwidth) return 1;
3411 switch (uc & CSET_MASK) {
3413 uc = ucsdata.unitab_line[uc & 0xFF];
3416 uc = ucsdata.unitab_xterm[uc & 0xFF];
3419 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3422 if (DIRECT_FONT(uc)) {
3423 if (ucsdata.dbcs_screenfont) return 1;
3425 /* Speedup, I know of no font where ascii is the wrong width */
3426 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3429 if ( (uc & CSET_MASK) == CSET_ACP ) {
3430 SelectObject(hdc, fonts[FONT_NORMAL]);
3431 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3432 another_font(FONT_OEM);
3433 if (!fonts[FONT_OEM]) return 0;
3435 SelectObject(hdc, fonts[FONT_OEM]);
3439 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3440 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3443 /* Speedup, I know of no font where ascii is the wrong width */
3444 if (uc >= ' ' && uc <= '~') return 1;
3446 SelectObject(hdc, fonts[FONT_NORMAL]);
3447 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3448 /* Okay that one worked */ ;
3449 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3450 /* This should work on 9x too, but it's "less accurate" */ ;
3455 ibuf += font_width / 2 -1;
3462 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3463 * codes. Returns number of bytes used or zero to drop the message
3464 * or -1 to forward the message to windows.
3466 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3467 unsigned char *output)
3470 int scan, left_alt = 0, key_down, shift_state;
3472 unsigned char *p = output;
3473 static int alt_sum = 0;
3475 HKL kbd_layout = GetKeyboardLayout(0);
3477 /* keys is for ToAsciiEx. There's some ick here, see below. */
3478 static WORD keys[3];
3479 static int compose_char = 0;
3480 static WPARAM compose_key = 0;
3482 r = GetKeyboardState(keystate);
3484 memset(keystate, 0, sizeof(keystate));
3487 #define SHOW_TOASCII_RESULT
3488 { /* Tell us all about key events */
3489 static BYTE oldstate[256];
3490 static int first = 1;
3494 memcpy(oldstate, keystate, sizeof(oldstate));
3497 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3499 } else if ((HIWORD(lParam) & KF_UP)
3500 && scan == (HIWORD(lParam) & 0xFF)) {
3504 if (wParam >= VK_F1 && wParam <= VK_F20)
3505 debug(("K_F%d", wParam + 1 - VK_F1));
3518 debug(("VK_%02x", wParam));
3520 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3522 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3524 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3525 if (ch >= ' ' && ch <= '~')
3526 debug((", '%c'", ch));
3528 debug((", $%02x", ch));
3531 debug((", KB0=%02x", keys[0]));
3533 debug((", KB1=%02x", keys[1]));
3535 debug((", KB2=%02x", keys[2]));
3537 if ((keystate[VK_SHIFT] & 0x80) != 0)
3539 if ((keystate[VK_CONTROL] & 0x80) != 0)
3541 if ((HIWORD(lParam) & KF_EXTENDED))
3543 if ((HIWORD(lParam) & KF_UP))
3547 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3548 else if ((HIWORD(lParam) & KF_UP))
3549 oldstate[wParam & 0xFF] ^= 0x80;
3551 oldstate[wParam & 0xFF] ^= 0x81;
3553 for (ch = 0; ch < 256; ch++)
3554 if (oldstate[ch] != keystate[ch])
3555 debug((", M%02x=%02x", ch, keystate[ch]));
3557 memcpy(oldstate, keystate, sizeof(oldstate));
3561 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
3562 keystate[VK_RMENU] = keystate[VK_MENU];
3566 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
3567 if ((cfg.funky_type == FUNKY_VT400 ||
3568 (cfg.funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
3570 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
3572 wParam = VK_EXECUTE;
3574 /* UnToggle NUMLock */
3575 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3576 keystate[VK_NUMLOCK] ^= 1;
3579 /* And write back the 'adjusted' state */
3580 SetKeyboardState(keystate);
3583 /* Disable Auto repeat if required */
3584 if (term->repeat_off &&
3585 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
3588 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
3591 key_down = ((HIWORD(lParam) & KF_UP) == 0);
3593 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
3594 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
3595 if (cfg.ctrlaltkeys)
3596 keystate[VK_MENU] = 0;
3598 keystate[VK_RMENU] = 0x80;
3603 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
3604 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3605 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
3607 /* Note if AltGr was pressed and if it was used as a compose key */
3608 if (!compose_state) {
3609 compose_key = 0x100;
3610 if (cfg.compose_key) {
3611 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
3612 compose_key = wParam;
3614 if (wParam == VK_APPS)
3615 compose_key = wParam;
3618 if (wParam == compose_key) {
3619 if (compose_state == 0
3620 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3622 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
3626 } else if (compose_state == 1 && wParam != VK_CONTROL)
3629 if (compose_state > 1 && left_alt)
3632 /* Sanitize the number pad if not using a PC NumPad */
3633 if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
3634 && cfg.funky_type != FUNKY_XTERM)
3635 || cfg.funky_type == FUNKY_VT400 || cfg.nethack_keypad || compose_state) {
3636 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
3640 nParam = VK_NUMPAD0;
3643 nParam = VK_NUMPAD1;
3646 nParam = VK_NUMPAD2;
3649 nParam = VK_NUMPAD3;
3652 nParam = VK_NUMPAD4;
3655 nParam = VK_NUMPAD5;
3658 nParam = VK_NUMPAD6;
3661 nParam = VK_NUMPAD7;
3664 nParam = VK_NUMPAD8;
3667 nParam = VK_NUMPAD9;
3670 nParam = VK_DECIMAL;
3674 if (keystate[VK_NUMLOCK] & 1)
3681 /* If a key is pressed and AltGr is not active */
3682 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3683 /* Okay, prepare for most alts then ... */
3687 /* Lets see if it's a pattern we know all about ... */
3688 if (wParam == VK_PRIOR && shift_state == 1) {
3689 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3692 if (wParam == VK_PRIOR && shift_state == 2) {
3693 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3696 if (wParam == VK_NEXT && shift_state == 1) {
3697 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3700 if (wParam == VK_NEXT && shift_state == 2) {
3701 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3704 if (wParam == VK_INSERT && shift_state == 1) {
3705 term_do_paste(term);
3708 if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
3711 if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
3712 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3715 if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3716 (cfg.resize_action != RESIZE_DISABLED)) {
3717 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3721 /* Control-Numlock for app-keypad mode switch */
3722 if (wParam == VK_PAUSE && shift_state == 2) {
3723 term->app_keypad_keys ^= 1;
3727 /* Nethack keypad */
3728 if (cfg.nethack_keypad && !left_alt) {
3731 *p++ = shift_state ? 'B' : 'b';
3734 *p++ = shift_state ? 'J' : 'j';
3737 *p++ = shift_state ? 'N' : 'n';
3740 *p++ = shift_state ? 'H' : 'h';
3743 *p++ = shift_state ? '.' : '.';
3746 *p++ = shift_state ? 'L' : 'l';
3749 *p++ = shift_state ? 'Y' : 'y';
3752 *p++ = shift_state ? 'K' : 'k';
3755 *p++ = shift_state ? 'U' : 'u';
3760 /* Application Keypad */
3764 if (cfg.funky_type == FUNKY_VT400 ||
3765 (cfg.funky_type <= FUNKY_LINUX &&
3766 term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
3780 if (term->app_keypad_keys && !cfg.no_applic_k)
3817 if (cfg.funky_type == FUNKY_XTERM) {
3822 } else if (shift_state)
3829 if (cfg.funky_type == FUNKY_XTERM)
3833 if (cfg.funky_type == FUNKY_XTERM)
3837 if (cfg.funky_type == FUNKY_XTERM)
3842 if (HIWORD(lParam) & KF_EXTENDED)
3847 if (term->vt52_mode) {
3848 if (xkey >= 'P' && xkey <= 'S')
3849 p += sprintf((char *) p, "\x1B%c", xkey);
3851 p += sprintf((char *) p, "\x1B?%c", xkey);
3853 p += sprintf((char *) p, "\x1BO%c", xkey);
3858 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
3859 *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
3863 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
3864 /* We do the opposite of what is configured */
3865 *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
3869 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
3875 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
3879 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
3883 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
3888 if (wParam == VK_PAUSE) { /* Break/Pause */
3893 /* Control-2 to Control-8 are special */
3894 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
3895 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
3898 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
3902 if (shift_state == 2 && wParam == 0xDF) {
3906 if (shift_state == 3 && wParam == 0xDE) {
3907 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
3910 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
3917 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
3918 * for integer decimal nn.)
3920 * We also deal with the weird ones here. Linux VCs replace F1
3921 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
3922 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
3928 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
3931 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
3934 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
3937 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
3940 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
3943 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
3946 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
3949 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
3952 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
3955 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
3988 if ((shift_state&2) == 0) switch (wParam) {
4008 /* Reorder edit keys to physical order */
4009 if (cfg.funky_type == FUNKY_VT400 && code <= 6)
4010 code = "\0\2\1\4\5\3\6"[code];
4012 if (term->vt52_mode && code > 0 && code <= 6) {
4013 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4017 if (cfg.funky_type == FUNKY_SCO && /* SCO function keys */
4018 code >= 11 && code <= 34) {
4019 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4022 case VK_F1: index = 0; break;
4023 case VK_F2: index = 1; break;
4024 case VK_F3: index = 2; break;
4025 case VK_F4: index = 3; break;
4026 case VK_F5: index = 4; break;
4027 case VK_F6: index = 5; break;
4028 case VK_F7: index = 6; break;
4029 case VK_F8: index = 7; break;
4030 case VK_F9: index = 8; break;
4031 case VK_F10: index = 9; break;
4032 case VK_F11: index = 10; break;
4033 case VK_F12: index = 11; break;
4035 if (keystate[VK_SHIFT] & 0x80) index += 12;
4036 if (keystate[VK_CONTROL] & 0x80) index += 24;
4037 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4040 if (cfg.funky_type == FUNKY_SCO && /* SCO small keypad */
4041 code >= 1 && code <= 6) {
4042 char codes[] = "HL.FIG";
4046 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4050 if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4056 if (term->vt52_mode)
4057 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4060 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4063 if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4064 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4067 if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4068 if (term->vt52_mode)
4069 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4071 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4074 if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
4075 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4079 p += sprintf((char *) p, "\x1B[%d~", code);
4084 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4085 * some reason seems to send VK_CLEAR to Windows...).
4107 if (term->vt52_mode)
4108 p += sprintf((char *) p, "\x1B%c", xkey);
4110 int app_flg = (term->app_cursor_keys && !cfg.no_applic_c);
4113 * RDB: VT100 & VT102 manuals both state the
4114 * app cursor keys only work if the app keypad
4117 * SGT: That may well be true, but xterm
4118 * disagrees and so does at least one
4119 * application, so I've #if'ed this out and the
4120 * behaviour is back to PuTTY's original: app
4121 * cursor and app keypad are independently
4122 * switchable modes. If anyone complains about
4123 * _this_ I'll have to put in a configurable
4126 if (!term->app_keypad_keys)
4129 /* Useful mapping of Ctrl-arrows */
4130 if (shift_state == 2)
4134 p += sprintf((char *) p, "\x1BO%c", xkey);
4136 p += sprintf((char *) p, "\x1B[%c", xkey);
4143 * Finally, deal with Return ourselves. (Win95 seems to
4144 * foul it up when Alt is pressed, for some reason.)
4146 if (wParam == VK_RETURN) { /* Return */
4152 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4153 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4158 /* Okay we've done everything interesting; let windows deal with
4159 * the boring stuff */
4163 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4164 if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
4166 keystate[VK_CAPITAL] = 0;
4169 /* XXX how do we know what the max size of the keys array should
4170 * be is? There's indication on MS' website of an Inquire/InquireEx
4171 * functioning returning a KBINFO structure which tells us. */
4172 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4173 /* XXX 'keys' parameter is declared in MSDN documentation as
4175 * The experience of a French user indicates that on
4176 * Win98, WORD[] should be passed in, but on Win2K, it should
4177 * be BYTE[]. German WinXP and my Win2K with "US International"
4178 * driver corroborate this.
4179 * Experimentally I've conditionalised the behaviour on the
4180 * Win9x/NT split, but I suspect it's worse than that.
4181 * See wishlist item `win-dead-keys' for more horrible detail
4182 * and speculations. */
4185 r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
4186 for (i=0; i<3; i++) keys[i] = keybs[i];
4188 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4190 #ifdef SHOW_TOASCII_RESULT
4191 if (r == 1 && !key_down) {
4193 if (in_utf(term) || ucsdata.dbcs_screenfont)
4194 debug((", (U+%04x)", alt_sum));
4196 debug((", LCH(%d)", alt_sum));
4198 debug((", ACH(%d)", keys[0]));
4203 for (r1 = 0; r1 < r; r1++) {
4204 debug(("%s%d", r1 ? "," : "", keys[r1]));
4213 * Interrupt an ongoing paste. I'm not sure this is
4214 * sensible, but for the moment it's preferable to
4215 * having to faff about buffering things.
4220 for (i = 0; i < r; i++) {
4221 unsigned char ch = (unsigned char) keys[i];
4223 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
4228 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
4232 if ((nc = check_compose(compose_char, ch)) == -1) {
4233 MessageBeep(MB_ICONHAND);
4237 term_seen_key_event(term);
4239 luni_send(ldisc, &keybuf, 1, 1);
4247 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4249 term_seen_key_event(term);
4251 luni_send(ldisc, &keybuf, 1, 1);
4253 ch = (char) alt_sum;
4255 * We need not bother about stdin
4256 * backlogs here, because in GUI PuTTY
4257 * we can't do anything about it
4258 * anyway; there's no means of asking
4259 * Windows to hold off on KEYDOWN
4260 * messages. We _have_ to buffer
4261 * everything we're sent.
4263 term_seen_key_event(term);
4265 ldisc_send(ldisc, &ch, 1, 1);
4269 term_seen_key_event(term);
4271 lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
4274 if(capsOn && ch < 0x80) {
4277 cbuf[1] = xlat_uskbd2cyrllic(ch);
4278 term_seen_key_event(term);
4280 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4285 term_seen_key_event(term);
4287 lpage_send(ldisc, kbd_codepage,
4288 cbuf+!left_alt, 1+!!left_alt, 1);
4294 /* This is so the ALT-Numpad and dead keys work correctly. */
4299 /* If we're definitly not building up an ALT-54321 then clear it */
4302 /* If we will be using alt_sum fix the 256s */
4303 else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4308 * ALT alone may or may not want to bring up the System menu.
4309 * If it's not meant to, we return 0 on presses or releases of
4310 * ALT, to show that we've swallowed the keystroke. Otherwise
4311 * we return -1, which means Windows will give the keystroke
4312 * its default handling (i.e. bring up the System menu).
4314 if (wParam == VK_MENU && !cfg.alt_only)
4320 void request_paste(void *frontend)
4323 * In Windows, pasting is synchronous: we can read the
4324 * clipboard with no difficulty, so request_paste() can just go
4327 term_do_paste(term);
4330 void set_title(void *frontend, char *title)
4333 window_name = snewn(1 + strlen(title), char);
4334 strcpy(window_name, title);
4335 if (cfg.win_name_always || !IsIconic(hwnd))
4336 SetWindowText(hwnd, title);
4339 void set_icon(void *frontend, char *title)
4342 icon_name = snewn(1 + strlen(title), char);
4343 strcpy(icon_name, title);
4344 if (!cfg.win_name_always && IsIconic(hwnd))
4345 SetWindowText(hwnd, title);
4348 void set_sbar(void *frontend, int total, int start, int page)
4352 if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
4355 si.cbSize = sizeof(si);
4356 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4358 si.nMax = total - 1;
4362 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4365 Context get_ctx(void *frontend)
4371 SelectPalette(hdc, pal, FALSE);
4377 void free_ctx(Context ctx)
4379 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4380 ReleaseDC(hwnd, ctx);
4383 static void real_palette_set(int n, int r, int g, int b)
4386 logpal->palPalEntry[n].peRed = r;
4387 logpal->palPalEntry[n].peGreen = g;
4388 logpal->palPalEntry[n].peBlue = b;
4389 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4390 colours[n] = PALETTERGB(r, g, b);
4391 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4393 colours[n] = RGB(r, g, b);
4396 void palette_set(void *frontend, int n, int r, int g, int b)
4400 if (n > NALLCOLOURS)
4402 real_palette_set(n, r, g, b);
4404 HDC hdc = get_ctx(frontend);
4405 UnrealizeObject(pal);
4406 RealizePalette(hdc);
4411 void palette_reset(void *frontend)
4416 for (i = 0; i < NALLCOLOURS; i++) {
4418 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4419 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4420 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4421 logpal->palPalEntry[i].peFlags = 0;
4422 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4423 defpal[i].rgbtGreen,
4424 defpal[i].rgbtBlue);
4426 colours[i] = RGB(defpal[i].rgbtRed,
4427 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4432 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4433 hdc = get_ctx(frontend);
4434 RealizePalette(hdc);
4439 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4444 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4447 lock = GlobalLock(clipdata);
4450 memcpy(lock, data, len);
4451 ((unsigned char *) lock)[len] = 0;
4452 GlobalUnlock(clipdata);
4455 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4457 if (OpenClipboard(hwnd)) {
4459 SetClipboardData(CF_TEXT, clipdata);
4462 GlobalFree(clipdata);
4465 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4469 * Note: unlike write_aclip() this will not append a nul.
4471 void write_clip(void *frontend, wchar_t * data, int len, int must_deselect)
4473 HGLOBAL clipdata, clipdata2, clipdata3;
4475 void *lock, *lock2, *lock3;
4477 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4479 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4480 len * sizeof(wchar_t));
4481 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4483 if (!clipdata || !clipdata2) {
4485 GlobalFree(clipdata);
4487 GlobalFree(clipdata2);
4490 if (!(lock = GlobalLock(clipdata)))
4492 if (!(lock2 = GlobalLock(clipdata2)))
4495 memcpy(lock, data, len * sizeof(wchar_t));
4496 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4498 if (cfg.rtf_paste) {
4499 wchar_t unitab[256];
4501 unsigned char *tdata = (unsigned char *)lock2;
4502 wchar_t *udata = (wchar_t *)lock;
4503 int rtflen = 0, uindex = 0, tindex = 0;
4505 int multilen, blen, alen, totallen, i;
4506 char before[16], after[4];
4508 get_unitab(CP_ACP, unitab, 0);
4510 rtfsize = 100 + strlen(cfg.font.name);
4511 rtf = snewn(rtfsize, char);
4512 sprintf(rtf, "{\\rtf1\\ansi%d{\\fonttbl\\f0\\fmodern %s;}\\f0 ",
4513 GetACP(), cfg.font.name);
4514 rtflen = strlen(rtf);
4517 * We want to construct a piece of RTF that specifies the
4518 * same Unicode text. To do this we will read back in
4519 * parallel from the Unicode data in `udata' and the
4520 * non-Unicode data in `tdata'. For each character in
4521 * `tdata' which becomes the right thing in `udata' when
4522 * looked up in `unitab', we just copy straight over from
4523 * tdata. For each one that doesn't, we must WCToMB it
4524 * individually and produce a \u escape sequence.
4526 * It would probably be more robust to just bite the bullet
4527 * and WCToMB each individual Unicode character one by one,
4528 * then MBToWC each one back to see if it was an accurate
4529 * translation; but that strikes me as a horrifying number
4530 * of Windows API calls so I want to see if this faster way
4531 * will work. If it screws up badly we can always revert to
4532 * the simple and slow way.
4534 while (tindex < len2 && uindex < len &&
4535 tdata[tindex] && udata[uindex]) {
4536 if (tindex + 1 < len2 &&
4537 tdata[tindex] == '\r' &&
4538 tdata[tindex+1] == '\n') {
4542 if (unitab[tdata[tindex]] == udata[uindex]) {
4548 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4549 NULL, 0, NULL, NULL);
4550 if (multilen != 1) {
4551 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4553 alen = 1; strcpy(after, "}");
4555 blen = sprintf(before, "\\u%d", udata[uindex]);
4556 alen = 0; after[0] = '\0';
4559 assert(tindex + multilen <= len2);
4560 totallen = blen + alen;
4561 for (i = 0; i < multilen; i++) {
4562 if (tdata[tindex+i] == '\\' ||
4563 tdata[tindex+i] == '{' ||
4564 tdata[tindex+i] == '}')
4566 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4567 totallen += 6; /* \par\r\n */
4568 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4574 if (rtfsize < rtflen + totallen + 3) {
4575 rtfsize = rtflen + totallen + 512;
4576 rtf = sresize(rtf, rtfsize, char);
4579 strcpy(rtf + rtflen, before); rtflen += blen;
4580 for (i = 0; i < multilen; i++) {
4581 if (tdata[tindex+i] == '\\' ||
4582 tdata[tindex+i] == '{' ||
4583 tdata[tindex+i] == '}') {
4584 rtf[rtflen++] = '\\';
4585 rtf[rtflen++] = tdata[tindex+i];
4586 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4587 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4588 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4589 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4591 rtf[rtflen++] = tdata[tindex+i];
4594 strcpy(rtf + rtflen, after); rtflen += alen;
4600 strcpy(rtf + rtflen, "}");
4603 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4604 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
4606 GlobalUnlock(clipdata3);
4612 GlobalUnlock(clipdata);
4613 GlobalUnlock(clipdata2);
4616 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4618 if (OpenClipboard(hwnd)) {
4620 SetClipboardData(CF_UNICODETEXT, clipdata);
4621 SetClipboardData(CF_TEXT, clipdata2);
4623 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4626 GlobalFree(clipdata);
4627 GlobalFree(clipdata2);
4631 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4634 void get_clip(void *frontend, wchar_t ** p, int *len)
4636 static HGLOBAL clipdata = NULL;
4637 static wchar_t *converted = 0;
4646 GlobalUnlock(clipdata);
4649 } else if (OpenClipboard(NULL)) {
4650 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
4652 *p = GlobalLock(clipdata);
4654 for (p2 = *p; *p2; p2++);
4658 } else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
4662 s = GlobalLock(clipdata);
4663 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
4664 *p = converted = snewn(i, wchar_t);
4665 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
4678 * Move `lines' lines from position `from' to position `to' in the
4681 void optimised_move(void *frontend, int to, int from, int lines)
4686 min = (to < from ? to : from);
4687 max = to + from - min;
4689 r.left = offset_width;
4690 r.right = offset_width + term->cols * font_width;
4691 r.top = offset_height + min * font_height;
4692 r.bottom = offset_height + (max + lines) * font_height;
4693 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
4698 * Print a message box and perform a fatal exit.
4700 void fatalbox(char *fmt, ...)
4703 char *stuff, morestuff[100];
4706 stuff = dupvprintf(fmt, ap);
4708 sprintf(morestuff, "%.70s Fatal Error", appname);
4709 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
4715 * Print a modal (Really Bad) message box and perform a fatal exit.
4717 void modalfatalbox(char *fmt, ...)
4720 char *stuff, morestuff[100];
4723 stuff = dupvprintf(fmt, ap);
4725 sprintf(morestuff, "%.70s Fatal Error", appname);
4726 MessageBox(hwnd, stuff, morestuff,
4727 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
4732 static void flash_window(int mode);
4733 static long next_flash;
4734 static int flashing = 0;
4736 static void flash_window_timer(void *ctx, long now)
4738 if (flashing && now - next_flash >= 0) {
4744 * Manage window caption / taskbar flashing, if enabled.
4745 * 0 = stop, 1 = maintain, 2 = start
4747 static void flash_window(int mode)
4749 if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
4752 FlashWindow(hwnd, FALSE);
4756 } else if (mode == 2) {
4760 FlashWindow(hwnd, TRUE);
4761 next_flash = schedule_timer(450, flash_window_timer, hwnd);
4764 } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
4767 FlashWindow(hwnd, TRUE); /* toggle */
4768 next_flash = schedule_timer(450, flash_window_timer, hwnd);
4776 void do_beep(void *frontend, int mode)
4778 if (mode == BELL_DEFAULT) {
4780 * For MessageBeep style bells, we want to be careful of
4781 * timing, because they don't have the nice property of
4782 * PlaySound bells that each one cancels the previous
4783 * active one. So we limit the rate to one per 50ms or so.
4785 static long lastbeep = 0;
4788 beepdiff = GetTickCount() - lastbeep;
4789 if (beepdiff >= 0 && beepdiff < 50)
4793 * The above MessageBeep call takes time, so we record the
4794 * time _after_ it finishes rather than before it starts.
4796 lastbeep = GetTickCount();
4797 } else if (mode == BELL_WAVEFILE) {
4798 if (!PlaySound(cfg.bell_wavefile.path, NULL,
4799 SND_ASYNC | SND_FILENAME)) {
4800 char buf[sizeof(cfg.bell_wavefile.path) + 80];
4802 sprintf(buf, "Unable to play sound file\n%s\n"
4803 "Using default sound instead", cfg.bell_wavefile.path);
4804 sprintf(otherbuf, "%.70s Sound Error", appname);
4805 MessageBox(hwnd, buf, otherbuf,
4806 MB_OK | MB_ICONEXCLAMATION);
4807 cfg.beep = BELL_DEFAULT;
4809 } else if (mode == BELL_PCSPEAKER) {
4810 static long lastbeep = 0;
4813 beepdiff = GetTickCount() - lastbeep;
4814 if (beepdiff >= 0 && beepdiff < 50)
4818 * We must beep in different ways depending on whether this
4819 * is a 95-series or NT-series OS.
4821 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
4825 lastbeep = GetTickCount();
4827 /* Otherwise, either visual bell or disabled; do nothing here */
4828 if (!term->has_focus) {
4829 flash_window(2); /* start */
4834 * Minimise or restore the window in response to a server-side
4837 void set_iconic(void *frontend, int iconic)
4839 if (IsIconic(hwnd)) {
4841 ShowWindow(hwnd, SW_RESTORE);
4844 ShowWindow(hwnd, SW_MINIMIZE);
4849 * Move the window in response to a server-side request.
4851 void move_window(void *frontend, int x, int y)
4853 if (cfg.resize_action == RESIZE_DISABLED ||
4854 cfg.resize_action == RESIZE_FONT ||
4858 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
4862 * Move the window to the top or bottom of the z-order in response
4863 * to a server-side request.
4865 void set_zorder(void *frontend, int top)
4867 if (cfg.alwaysontop)
4868 return; /* ignore */
4869 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
4870 SWP_NOMOVE | SWP_NOSIZE);
4874 * Refresh the window in response to a server-side request.
4876 void refresh_window(void *frontend)
4878 InvalidateRect(hwnd, NULL, TRUE);
4882 * Maximise or restore the window in response to a server-side
4885 void set_zoomed(void *frontend, int zoomed)
4887 if (IsZoomed(hwnd)) {
4889 ShowWindow(hwnd, SW_RESTORE);
4892 ShowWindow(hwnd, SW_MAXIMIZE);
4897 * Report whether the window is iconic, for terminal reports.
4899 int is_iconic(void *frontend)
4901 return IsIconic(hwnd);
4905 * Report the window's position, for terminal reports.
4907 void get_window_pos(void *frontend, int *x, int *y)
4910 GetWindowRect(hwnd, &r);
4916 * Report the window's pixel size, for terminal reports.
4918 void get_window_pixels(void *frontend, int *x, int *y)
4921 GetWindowRect(hwnd, &r);
4922 *x = r.right - r.left;
4923 *y = r.bottom - r.top;
4927 * Return the window or icon title.
4929 char *get_window_title(void *frontend, int icon)
4931 return icon ? icon_name : window_name;
4935 * See if we're in full-screen mode.
4937 static int is_full_screen()
4939 if (!IsZoomed(hwnd))
4941 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
4946 /* Get the rect/size of a full screen window using the nearest available
4947 * monitor in multimon systems; default to something sensible if only
4948 * one monitor is present. */
4949 static int get_fullscreen_rect(RECT * ss)
4951 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
4954 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
4955 mi.cbSize = sizeof(mi);
4956 GetMonitorInfo(mon, &mi);
4958 /* structure copy */
4962 /* could also use code like this:
4963 ss->left = ss->top = 0;
4964 ss->right = GetSystemMetrics(SM_CXSCREEN);
4965 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
4967 return GetClientRect(GetDesktopWindow(), ss);
4973 * Go full-screen. This should only be called when we are already
4976 static void make_full_screen()
4981 assert(IsZoomed(hwnd));
4983 if (is_full_screen())
4986 /* Remove the window furniture. */
4987 style = GetWindowLongPtr(hwnd, GWL_STYLE);
4988 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
4989 if (cfg.scrollbar_in_fullscreen)
4990 style |= WS_VSCROLL;
4992 style &= ~WS_VSCROLL;
4993 SetWindowLongPtr(hwnd, GWL_STYLE, style);
4995 /* Resize ourselves to exactly cover the nearest monitor. */
4996 get_fullscreen_rect(&ss);
4997 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5002 /* Tick the menu item in the System menu. */
5003 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
5008 * Clear the full-screen attributes.
5010 static void clear_full_screen()
5012 DWORD oldstyle, style;
5014 /* Reinstate the window furniture. */
5015 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
5016 style |= WS_CAPTION | WS_BORDER;
5017 if (cfg.resize_action == RESIZE_DISABLED)
5018 style &= ~WS_THICKFRAME;
5020 style |= WS_THICKFRAME;
5022 style |= WS_VSCROLL;
5024 style &= ~WS_VSCROLL;
5025 if (style != oldstyle) {
5026 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5027 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5028 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5032 /* Untick the menu item in the System menu. */
5033 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
5038 * Toggle full-screen mode.
5040 static void flip_full_screen()
5042 if (is_full_screen()) {
5043 ShowWindow(hwnd, SW_RESTORE);
5044 } else if (IsZoomed(hwnd)) {
5047 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5048 ShowWindow(hwnd, SW_MAXIMIZE);
5052 void frontend_keypress(void *handle)
5055 * Keypress termination in non-Close-On-Exit mode is not
5056 * currently supported in PuTTY proper, because the window
5057 * always has a perfectly good Close button anyway. So we do
5063 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5065 return term_data(term, is_stderr, data, len);
5068 int from_backend_untrusted(void *frontend, const char *data, int len)
5070 return term_data_untrusted(term, data, len);
5073 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
5076 ret = cmdline_get_passwd_input(p, in, inlen);
5078 ret = term_get_userpass_input(term, p, in, inlen);
5082 void agent_schedule_callback(void (*callback)(void *, void *, int),
5083 void *callback_ctx, void *data, int len)
5085 struct agent_callback *c = snew(struct agent_callback);
5086 c->callback = callback;
5087 c->callback_ctx = callback_ctx;
5090 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);