7 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
15 #define COMPILE_MULTIMON_STUBS
25 /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
26 * wParam are used by Windows, and should be masked off, so we shouldn't
27 * attempt to store information in them. Hence all these identifiers have
28 * the low 4 bits clear. Also, identifiers should < 0xF000. */
30 #define IDM_SHOWLOG 0x0010
31 #define IDM_NEWSESS 0x0020
32 #define IDM_DUPSESS 0x0030
33 #define IDM_RESTART 0x0040
34 #define IDM_RECONF 0x0050
35 #define IDM_CLRSB 0x0060
36 #define IDM_RESET 0x0070
37 #define IDM_HELP 0x0140
38 #define IDM_ABOUT 0x0150
39 #define IDM_SAVEDSESS 0x0160
40 #define IDM_COPYALL 0x0170
41 #define IDM_FULLSCREEN 0x0180
42 #define IDM_PASTE 0x0190
44 #define IDM_SPECIAL_MIN 0x0400
45 #define IDM_SPECIAL_MAX 0x0800
47 #define IDM_SAVED_MIN 0x1000
48 #define IDM_SAVED_MAX 0x5000
49 #define MENU_SAVED_STEP 16
50 /* Maximum number of sessions on saved-session submenu */
51 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
53 #define WM_IGNORE_CLIP (WM_XUSER + 2)
54 #define WM_FULLSCR_ON_MAX (WM_XUSER + 3)
55 #define WM_AGENT_CALLBACK (WM_XUSER + 4)
57 /* Needed for Chinese support and apparently not always defined. */
59 #define VK_PROCESSKEY 0xE5
62 /* Mouse wheel support. */
64 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
67 #define WHEEL_DELTA 120
70 static Mouse_Button translate_button(Mouse_Button button);
71 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
72 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
73 unsigned char *output);
74 static void cfgtopalette(void);
75 static void systopalette(void);
76 static void init_palette(void);
77 static void init_fonts(int, int);
78 static void another_font(int);
79 static void deinit_fonts(void);
80 static void set_input_locale(HKL);
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 * Open the initial log file if there is one.
804 * Finally show the window!
806 ShowWindow(hwnd, show);
807 SetForegroundWindow(hwnd);
810 * Set the palette up.
816 term_set_focus(term, GetForegroundWindow() == hwnd);
819 if (GetMessage(&msg, NULL, 0, 0) == 1) {
820 while (msg.message != WM_QUIT) {
821 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
822 DispatchMessage(&msg);
823 /* Send the paste buffer if there's anything to send */
825 /* If there's nothing new in the queue then we can do everything
826 * we've delayed, reading the socket, writing, and repainting
829 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
832 /* The messages seem unreliable; especially if we're being tricky */
833 term_set_focus(term, GetForegroundWindow() == hwnd);
835 net_pending_errors();
837 /* There's no point rescanning everything in the message queue
838 * so we do an apparently unnecessary wait here
841 if (GetMessage(&msg, NULL, 0, 0) != 1)
846 cleanup_exit(msg.wParam); /* this doesn't return... */
847 return msg.wParam; /* ... but optimiser doesn't know */
853 void cleanup_exit(int code)
864 if (cfg.protocol == PROT_SSH) {
875 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
877 char *do_select(SOCKET skt, int startup)
882 events = (FD_CONNECT | FD_READ | FD_WRITE |
883 FD_OOB | FD_CLOSE | FD_ACCEPT);
888 return "do_select(): internal error (hwnd==NULL)";
889 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
890 switch (p_WSAGetLastError()) {
892 return "Network is down";
894 return "WSAAsyncSelect(): unknown error";
901 * Refresh the saved-session submenu from `sesslist'.
903 static void update_savedsess_menu(void)
906 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
907 /* skip sesslist.sessions[0] == Default Settings */
909 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
912 AppendMenu(savedsess_menu, MF_ENABLED,
913 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
914 sesslist.sessions[i]);
918 * Update the Special Commands submenu.
920 void update_specials_menu(void *frontend)
923 int menu_already_exists = (specials != NULL);
927 specials = back->get_specials(backhandle);
932 /* We can't use Windows to provide a stack for submenus, so
933 * here's a lame "stack" that will do for now. */
934 HMENU saved_menu = NULL;
936 p = CreatePopupMenu();
937 for (i = 0; nesting > 0; i++) {
938 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
939 switch (specials[i].code) {
941 AppendMenu(p, MF_SEPARATOR, 0, 0);
946 saved_menu = p; /* XXX lame stacking */
947 p = CreatePopupMenu();
948 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
949 (UINT) p, specials[i].name);
954 p = saved_menu; /* XXX lame stacking */
959 AppendMenu(p, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
964 /* Squirrel the highest special. */
971 for (j = 0; j < lenof(popup_menus); j++) {
972 if (menu_already_exists) {
973 /* XXX does this free up all submenus? */
974 DeleteMenu(popup_menus[j].menu,
975 popup_menus[j].specials_submenu_pos,
977 DeleteMenu(popup_menus[j].menu,
978 popup_menus[j].specials_submenu_pos,
982 InsertMenu(popup_menus[j].menu,
983 popup_menus[j].specials_submenu_pos,
984 MF_BYPOSITION | MF_SEPARATOR, 0, 0);
985 InsertMenu(popup_menus[j].menu,
986 popup_menus[j].specials_submenu_pos,
987 MF_BYPOSITION | MF_POPUP | MF_ENABLED,
988 (UINT) p, "S&pecial Command");
993 static void update_mouse_pointer(void)
996 int force_visible = FALSE;
997 static int forced_visible = FALSE;
998 switch (busy_status) {
1001 curstype = IDC_ARROW;
1003 curstype = IDC_IBEAM;
1006 curstype = IDC_APPSTARTING; /* this may be an abuse */
1007 force_visible = TRUE;
1010 curstype = IDC_WAIT;
1011 force_visible = TRUE;
1017 HCURSOR cursor = LoadCursor(NULL, curstype);
1018 SetClassLong(hwnd, GCL_HCURSOR, (LONG)cursor);
1019 SetCursor(cursor); /* force redraw of cursor at current posn */
1021 if (force_visible != forced_visible) {
1022 /* We want some cursor shapes to be visible always.
1023 * Along with show_mouseptr(), this manages the ShowCursor()
1024 * counter such that if we switch back to a non-force_visible
1025 * cursor, the previous visibility state is restored. */
1026 ShowCursor(force_visible);
1027 forced_visible = force_visible;
1031 void set_busy_status(void *frontend, int status)
1033 busy_status = status;
1034 update_mouse_pointer();
1038 * set or clear the "raw mouse message" mode
1040 void set_raw_mouse_mode(void *frontend, int activate)
1042 activate = activate && !cfg.no_mouse_rep;
1043 send_raw_mouse = activate;
1044 update_mouse_pointer();
1048 * Print a message box and close the connection.
1050 void connection_fatal(void *frontend, char *fmt, ...)
1053 char *stuff, morestuff[100];
1056 stuff = dupvprintf(fmt, ap);
1058 sprintf(morestuff, "%.70s Fatal Error", appname);
1059 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1062 if (cfg.close_on_exit == FORCE_ON)
1070 * Report an error at the command-line parsing stage.
1072 void cmdline_error(char *fmt, ...)
1075 char *stuff, morestuff[100];
1078 stuff = dupvprintf(fmt, ap);
1080 sprintf(morestuff, "%.70s Command Line Error", appname);
1081 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1087 * Actually do the job requested by a WM_NETEVENT
1089 static void enact_netevent(WPARAM wParam, LPARAM lParam)
1091 static int reentering = 0;
1092 extern int select_result(WPARAM, LPARAM);
1096 return; /* don't unpend the pending */
1099 ret = select_result(wParam, lParam);
1102 if (ret == 0 && !session_closed) {
1103 /* Abnormal exits will already have set session_closed and taken
1104 * appropriate action. */
1105 if (cfg.close_on_exit == FORCE_ON ||
1106 cfg.close_on_exit == AUTO) PostQuitMessage(0);
1109 session_closed = TRUE;
1110 MessageBox(hwnd, "Connection closed by remote host",
1111 appname, MB_OK | MB_ICONINFORMATION);
1117 * Copy the colour palette from the configuration data into defpal.
1118 * This is non-trivial because the colour indices are different.
1120 static void cfgtopalette(void)
1123 static const int ww[] = {
1124 256, 257, 258, 259, 260, 261,
1125 0, 8, 1, 9, 2, 10, 3, 11,
1126 4, 12, 5, 13, 6, 14, 7, 15
1129 for (i = 0; i < 22; i++) {
1131 defpal[w].rgbtRed = cfg.colours[i][0];
1132 defpal[w].rgbtGreen = cfg.colours[i][1];
1133 defpal[w].rgbtBlue = cfg.colours[i][2];
1135 for (i = 0; i < NEXTCOLOURS; i++) {
1137 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1138 defpal[i+16].rgbtRed = r * 0x33;
1139 defpal[i+16].rgbtGreen = g * 0x33;
1140 defpal[i+16].rgbtBlue = b * 0x33;
1142 int shade = i - 216;
1143 shade = (shade + 1) * 0xFF / (NEXTCOLOURS - 216 + 1);
1144 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1145 defpal[i+16].rgbtBlue = shade;
1149 /* Override with system colours if appropriate */
1150 if (cfg.system_colour)
1155 * Override bit of defpal with colours from the system.
1156 * (NB that this takes a copy the system colours at the time this is called,
1157 * so subsequent colour scheme changes don't take effect. To fix that we'd
1158 * probably want to be using GetSysColorBrush() and the like.)
1160 static void systopalette(void)
1163 static const struct { int nIndex; int norm; int bold; } or[] =
1165 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1166 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1167 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1168 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1171 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1172 COLORREF colour = GetSysColor(or[i].nIndex);
1173 defpal[or[i].norm].rgbtRed =
1174 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1175 defpal[or[i].norm].rgbtGreen =
1176 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1177 defpal[or[i].norm].rgbtBlue =
1178 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1183 * Set up the colour palette.
1185 static void init_palette(void)
1188 HDC hdc = GetDC(hwnd);
1190 if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1192 * This is a genuine case where we must use smalloc
1193 * because the snew macros can't cope.
1195 logpal = smalloc(sizeof(*logpal)
1196 - sizeof(logpal->palPalEntry)
1197 + NALLCOLOURS * sizeof(PALETTEENTRY));
1198 logpal->palVersion = 0x300;
1199 logpal->palNumEntries = NALLCOLOURS;
1200 for (i = 0; i < NALLCOLOURS; i++) {
1201 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1202 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1203 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1204 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1206 pal = CreatePalette(logpal);
1208 SelectPalette(hdc, pal, FALSE);
1209 RealizePalette(hdc);
1210 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1213 ReleaseDC(hwnd, hdc);
1216 for (i = 0; i < NALLCOLOURS; i++)
1217 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1218 defpal[i].rgbtGreen,
1219 defpal[i].rgbtBlue);
1221 for (i = 0; i < NALLCOLOURS; i++)
1222 colours[i] = RGB(defpal[i].rgbtRed,
1223 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1227 * This is a wrapper to ExtTextOut() to force Windows to display
1228 * the precise glyphs we give it. Otherwise it would do its own
1229 * bidi and Arabic shaping, and we would end up uncertain which
1230 * characters it had put where.
1232 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1233 unsigned short *lpString, UINT cbCount,
1234 CONST INT *lpDx, int opaque)
1238 * The LCC include files apparently don't supply the
1239 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1240 * proper: the differences aren't important to us (the only
1241 * variable-width string parameter is one we don't use anyway).
1247 char *buffer = snewn(cbCount*2+2, char);
1248 char *classbuffer = snewn(cbCount, char);
1249 memset(&gcpr, 0, sizeof(gcpr));
1250 memset(buffer, 0, cbCount*2+2);
1251 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1253 gcpr.lStructSize = sizeof(gcpr);
1254 gcpr.lpGlyphs = (void *)buffer;
1255 gcpr.lpClass = classbuffer;
1256 gcpr.nGlyphs = cbCount;
1258 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1259 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1261 ExtTextOut(hdc, x, y,
1262 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1263 lprc, buffer, cbCount, lpDx);
1267 * Initialise all the fonts we will need initially. There may be as many as
1268 * three or as few as one. The other (poentially) twentyone fonts are done
1269 * if/when they are needed.
1273 * - check the font width and height, correcting our guesses if
1276 * - verify that the bold font is the same width as the ordinary
1277 * one, and engage shadow bolding if not.
1279 * - verify that the underlined font is the same width as the
1280 * ordinary one (manual underlining by means of line drawing can
1281 * be done in a pinch).
1283 static void init_fonts(int pick_width, int pick_height)
1290 int fw_dontcare, fw_bold;
1292 for (i = 0; i < FONT_MAXNO; i++)
1295 bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
1296 und_mode = UND_FONT;
1298 if (cfg.font.isbold) {
1299 fw_dontcare = FW_BOLD;
1302 fw_dontcare = FW_DONTCARE;
1309 font_height = pick_height;
1311 font_height = cfg.font.height;
1312 if (font_height > 0) {
1314 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1317 font_width = pick_width;
1319 #define f(i,c,w,u) \
1320 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1321 c, OUT_DEFAULT_PRECIS, \
1322 CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, \
1323 FIXED_PITCH | FF_DONTCARE, cfg.font.name)
1325 f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);
1327 SelectObject(hdc, fonts[FONT_NORMAL]);
1328 GetTextMetrics(hdc, &tm);
1330 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1332 if (pick_width == 0 || pick_height == 0) {
1333 font_height = tm.tmHeight;
1334 font_width = tm.tmAveCharWidth;
1336 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1338 #ifdef RDB_DEBUG_PATCH
1339 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1340 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1345 DWORD cset = tm.tmCharSet;
1346 memset(&info, 0xFF, sizeof(info));
1348 /* !!! Yes the next line is right */
1349 if (cset == OEM_CHARSET)
1350 ucsdata.font_codepage = GetOEMCP();
1352 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1353 ucsdata.font_codepage = info.ciACP;
1355 ucsdata.font_codepage = -1;
1357 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1358 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1361 f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);
1364 * Some fonts, e.g. 9-pt Courier, draw their underlines
1365 * outside their character cell. We successfully prevent
1366 * screen corruption by clipping the text output, but then
1367 * we lose the underline completely. Here we try to work
1368 * out whether this is such a font, and if it is, we set a
1369 * flag that causes underlines to be drawn by hand.
1371 * Having tried other more sophisticated approaches (such
1372 * as examining the TEXTMETRIC structure or requesting the
1373 * height of a string), I think we'll do this the brute
1374 * force way: we create a small bitmap, draw an underlined
1375 * space on it, and test to see whether any pixels are
1376 * foreground-coloured. (Since we expect the underline to
1377 * go all the way across the character cell, we only search
1378 * down a single column of the bitmap, half way across.)
1382 HBITMAP und_bm, und_oldbm;
1386 und_dc = CreateCompatibleDC(hdc);
1387 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1388 und_oldbm = SelectObject(und_dc, und_bm);
1389 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1390 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1391 SetTextColor(und_dc, RGB(255, 255, 255));
1392 SetBkColor(und_dc, RGB(0, 0, 0));
1393 SetBkMode(und_dc, OPAQUE);
1394 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1396 for (i = 0; i < font_height; i++) {
1397 c = GetPixel(und_dc, font_width / 2, i);
1398 if (c != RGB(0, 0, 0))
1401 SelectObject(und_dc, und_oldbm);
1402 DeleteObject(und_bm);
1405 und_mode = UND_LINE;
1406 DeleteObject(fonts[FONT_UNDERLINE]);
1407 fonts[FONT_UNDERLINE] = 0;
1411 if (bold_mode == BOLD_FONT) {
1412 f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);
1416 descent = tm.tmAscent + 1;
1417 if (descent >= font_height)
1418 descent = font_height - 1;
1420 for (i = 0; i < 3; i++) {
1422 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1423 fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
1430 ReleaseDC(hwnd, hdc);
1432 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1433 und_mode = UND_LINE;
1434 DeleteObject(fonts[FONT_UNDERLINE]);
1435 fonts[FONT_UNDERLINE] = 0;
1438 if (bold_mode == BOLD_FONT &&
1439 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1440 bold_mode = BOLD_SHADOW;
1441 DeleteObject(fonts[FONT_BOLD]);
1442 fonts[FONT_BOLD] = 0;
1444 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1446 init_ucs(&cfg, &ucsdata);
1449 static void another_font(int fontno)
1452 int fw_dontcare, fw_bold;
1456 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1459 basefont = (fontno & ~(FONT_BOLDUND));
1460 if (basefont != fontno && !fontflag[basefont])
1461 another_font(basefont);
1463 if (cfg.font.isbold) {
1464 fw_dontcare = FW_BOLD;
1467 fw_dontcare = FW_DONTCARE;
1471 c = cfg.font.charset;
1477 if (fontno & FONT_WIDE)
1479 if (fontno & FONT_NARROW)
1481 if (fontno & FONT_OEM)
1483 if (fontno & FONT_BOLD)
1485 if (fontno & FONT_UNDERLINE)
1489 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1490 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1491 CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
1492 FIXED_PITCH | FF_DONTCARE, s);
1494 fontflag[fontno] = 1;
1497 static void deinit_fonts(void)
1500 for (i = 0; i < FONT_MAXNO; i++) {
1502 DeleteObject(fonts[i]);
1508 void request_resize(void *frontend, int w, int h)
1512 /* If the window is maximized supress resizing attempts */
1513 if (IsZoomed(hwnd)) {
1514 if (cfg.resize_action == RESIZE_TERM)
1518 if (cfg.resize_action == RESIZE_DISABLED) return;
1519 if (h == term->rows && w == term->cols) return;
1521 /* Sanity checks ... */
1523 static int first_time = 1;
1526 switch (first_time) {
1528 /* Get the size of the screen */
1529 if (get_fullscreen_rect(&ss))
1530 /* first_time = 0 */ ;
1536 /* Make sure the values are sane */
1537 width = (ss.right - ss.left - extra_width) / 4;
1538 height = (ss.bottom - ss.top - extra_height) / 6;
1540 if (w > width || h > height)
1549 term_size(term, h, w, cfg.savelines);
1551 if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {
1552 width = extra_width + font_width * w;
1553 height = extra_height + font_height * h;
1555 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1556 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1557 SWP_NOMOVE | SWP_NOZORDER);
1561 InvalidateRect(hwnd, NULL, TRUE);
1564 static void reset_window(int reinit) {
1566 * This function decides how to resize or redraw when the
1567 * user changes something.
1569 * This function doesn't like to change the terminal size but if the
1570 * font size is locked that may be it's only soluion.
1572 int win_width, win_height;
1575 #ifdef RDB_DEBUG_PATCH
1576 debug((27, "reset_window()"));
1579 /* Current window sizes ... */
1580 GetWindowRect(hwnd, &wr);
1581 GetClientRect(hwnd, &cr);
1583 win_width = cr.right - cr.left;
1584 win_height = cr.bottom - cr.top;
1586 if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;
1588 /* Are we being forced to reload the fonts ? */
1590 #ifdef RDB_DEBUG_PATCH
1591 debug((27, "reset_window() -- Forced deinit"));
1597 /* Oh, looks like we're minimised */
1598 if (win_width == 0 || win_height == 0)
1601 /* Is the window out of position ? */
1603 (offset_width != (win_width-font_width*term->cols)/2 ||
1604 offset_height != (win_height-font_height*term->rows)/2) ){
1605 offset_width = (win_width-font_width*term->cols)/2;
1606 offset_height = (win_height-font_height*term->rows)/2;
1607 InvalidateRect(hwnd, NULL, TRUE);
1608 #ifdef RDB_DEBUG_PATCH
1609 debug((27, "reset_window() -> Reposition terminal"));
1613 if (IsZoomed(hwnd)) {
1614 /* We're fullscreen, this means we must not change the size of
1615 * the window so it's the font size or the terminal itself.
1618 extra_width = wr.right - wr.left - cr.right + cr.left;
1619 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1621 if (cfg.resize_action != RESIZE_TERM) {
1622 if ( font_width != win_width/term->cols ||
1623 font_height != win_height/term->rows) {
1625 init_fonts(win_width/term->cols, win_height/term->rows);
1626 offset_width = (win_width-font_width*term->cols)/2;
1627 offset_height = (win_height-font_height*term->rows)/2;
1628 InvalidateRect(hwnd, NULL, TRUE);
1629 #ifdef RDB_DEBUG_PATCH
1630 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1631 font_width, font_height));
1635 if ( font_width != win_width/term->cols ||
1636 font_height != win_height/term->rows) {
1637 /* Our only choice at this point is to change the
1638 * size of the terminal; Oh well.
1640 term_size(term, win_height/font_height, win_width/font_width,
1642 offset_width = (win_width-font_width*term->cols)/2;
1643 offset_height = (win_height-font_height*term->rows)/2;
1644 InvalidateRect(hwnd, NULL, TRUE);
1645 #ifdef RDB_DEBUG_PATCH
1646 debug((27, "reset_window() -> Zoomed term_size"));
1653 /* Hmm, a force re-init means we should ignore the current window
1654 * so we resize to the default font size.
1657 #ifdef RDB_DEBUG_PATCH
1658 debug((27, "reset_window() -> Forced re-init"));
1661 offset_width = offset_height = cfg.window_border;
1662 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1663 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1665 if (win_width != font_width*term->cols + offset_width*2 ||
1666 win_height != font_height*term->rows + offset_height*2) {
1668 /* If this is too large windows will resize it to the maximum
1669 * allowed window size, we will then be back in here and resize
1670 * the font or terminal to fit.
1672 SetWindowPos(hwnd, NULL, 0, 0,
1673 font_width*term->cols + extra_width,
1674 font_height*term->rows + extra_height,
1675 SWP_NOMOVE | SWP_NOZORDER);
1678 InvalidateRect(hwnd, NULL, TRUE);
1682 /* Okay the user doesn't want us to change the font so we try the
1683 * window. But that may be too big for the screen which forces us
1684 * to change the terminal.
1686 if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||
1687 (cfg.resize_action == RESIZE_EITHER && reinit<0) ||
1689 offset_width = offset_height = cfg.window_border;
1690 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1691 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1693 if (win_width != font_width*term->cols + offset_width*2 ||
1694 win_height != font_height*term->rows + offset_height*2) {
1699 get_fullscreen_rect(&ss);
1701 width = (ss.right - ss.left - extra_width) / font_width;
1702 height = (ss.bottom - ss.top - extra_height) / font_height;
1705 if ( term->rows > height || term->cols > width ) {
1706 if (cfg.resize_action == RESIZE_EITHER) {
1707 /* Make the font the biggest we can */
1708 if (term->cols > width)
1709 font_width = (ss.right - ss.left - extra_width)
1711 if (term->rows > height)
1712 font_height = (ss.bottom - ss.top - extra_height)
1716 init_fonts(font_width, font_height);
1718 width = (ss.right - ss.left - extra_width) / font_width;
1719 height = (ss.bottom - ss.top - extra_height) / font_height;
1721 if ( height > term->rows ) height = term->rows;
1722 if ( width > term->cols ) width = term->cols;
1723 term_size(term, height, width, cfg.savelines);
1724 #ifdef RDB_DEBUG_PATCH
1725 debug((27, "reset_window() -> term resize to (%d,%d)",
1731 SetWindowPos(hwnd, NULL, 0, 0,
1732 font_width*term->cols + extra_width,
1733 font_height*term->rows + extra_height,
1734 SWP_NOMOVE | SWP_NOZORDER);
1736 InvalidateRect(hwnd, NULL, TRUE);
1737 #ifdef RDB_DEBUG_PATCH
1738 debug((27, "reset_window() -> window resize to (%d,%d)",
1739 font_width*term->cols + extra_width,
1740 font_height*term->rows + extra_height));
1746 /* We're allowed to or must change the font but do we want to ? */
1748 if (font_width != (win_width-cfg.window_border*2)/term->cols ||
1749 font_height != (win_height-cfg.window_border*2)/term->rows) {
1752 init_fonts((win_width-cfg.window_border*2)/term->cols,
1753 (win_height-cfg.window_border*2)/term->rows);
1754 offset_width = (win_width-font_width*term->cols)/2;
1755 offset_height = (win_height-font_height*term->rows)/2;
1757 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1758 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1760 InvalidateRect(hwnd, NULL, TRUE);
1761 #ifdef RDB_DEBUG_PATCH
1762 debug((25, "reset_window() -> font resize to (%d,%d)",
1763 font_width, font_height));
1768 static void set_input_locale(HKL kl)
1772 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1773 lbuf, sizeof(lbuf));
1775 kbd_codepage = atoi(lbuf);
1778 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1780 int thistime = GetMessageTime();
1782 if (send_raw_mouse && !(cfg.mouse_override && shift)) {
1783 lastbtn = MBT_NOTHING;
1784 term_mouse(term, b, translate_button(b), MA_CLICK,
1785 x, y, shift, ctrl, alt);
1789 if (lastbtn == b && thistime - lasttime < dbltime) {
1790 lastact = (lastact == MA_CLICK ? MA_2CLK :
1791 lastact == MA_2CLK ? MA_3CLK :
1792 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1797 if (lastact != MA_NOTHING)
1798 term_mouse(term, b, translate_button(b), lastact,
1799 x, y, shift, ctrl, alt);
1800 lasttime = thistime;
1804 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1805 * into a cooked one (SELECT, EXTEND, PASTE).
1807 static Mouse_Button translate_button(Mouse_Button button)
1809 if (button == MBT_LEFT)
1811 if (button == MBT_MIDDLE)
1812 return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
1813 if (button == MBT_RIGHT)
1814 return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
1815 return 0; /* shouldn't happen */
1818 static void show_mouseptr(int show)
1820 /* NB that the counter in ShowCursor() is also frobbed by
1821 * update_mouse_pointer() */
1822 static int cursor_visible = 1;
1823 if (!cfg.hide_mouseptr) /* override if this feature disabled */
1825 if (cursor_visible && !show)
1827 else if (!cursor_visible && show)
1829 cursor_visible = show;
1832 static int is_alt_pressed(void)
1835 int r = GetKeyboardState(keystate);
1838 if (keystate[VK_MENU] & 0x80)
1840 if (keystate[VK_RMENU] & 0x80)
1845 static int is_shift_pressed(void)
1848 int r = GetKeyboardState(keystate);
1851 if (keystate[VK_SHIFT] & 0x80)
1856 static int resizing;
1858 void notify_remote_exit(void *fe) { /* stub not needed in this frontend */ }
1860 void timer_change_notify(long next)
1862 long ticks = next - GETTICKCOUNT();
1863 if (ticks <= 0) ticks = 1; /* just in case */
1864 KillTimer(hwnd, TIMING_TIMER_ID);
1865 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
1866 timing_next_time = next;
1869 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1870 WPARAM wParam, LPARAM lParam)
1873 static int ignore_clip = FALSE;
1874 static int need_backend_resize = FALSE;
1875 static int fullscr_on_max = FALSE;
1876 static UINT last_mousemove = 0;
1880 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
1883 KillTimer(hwnd, TIMING_TIMER_ID);
1884 if (run_timers(timing_next_time, &next)) {
1885 timer_change_notify(next);
1896 str = dupprintf("%s Exit Confirmation", appname);
1897 if (!cfg.warn_on_close || session_closed ||
1899 "Are you sure you want to close this session?",
1900 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
1902 DestroyWindow(hwnd);
1910 case WM_INITMENUPOPUP:
1911 if ((HMENU)wParam == savedsess_menu) {
1912 /* About to pop up Saved Sessions sub-menu.
1913 * Refresh the session list. */
1914 get_sesslist(&sesslist, FALSE); /* free */
1915 get_sesslist(&sesslist, TRUE);
1916 update_savedsess_menu();
1922 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
1933 BOOL inherit_handles;
1935 PROCESS_INFORMATION pi;
1936 HANDLE filemap = NULL;
1938 if (wParam == IDM_DUPSESS) {
1940 * Allocate a file-mapping memory chunk for the
1943 SECURITY_ATTRIBUTES sa;
1946 sa.nLength = sizeof(sa);
1947 sa.lpSecurityDescriptor = NULL;
1948 sa.bInheritHandle = TRUE;
1949 filemap = CreateFileMapping((HANDLE) 0xFFFFFFFF,
1952 0, sizeof(Config), NULL);
1954 p = (Config *) MapViewOfFile(filemap,
1956 0, 0, sizeof(Config));
1958 *p = cfg; /* structure copy */
1962 inherit_handles = TRUE;
1963 sprintf(c, "putty &%p", filemap);
1965 } else if (wParam == IDM_SAVEDSESS) {
1966 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
1967 / MENU_SAVED_STEP) + 1;
1968 if (sessno < sesslist.nsessions) {
1969 char *session = sesslist.sessions[sessno];
1970 /* XXX spaces? quotes? "-load"? */
1971 cl = dupprintf("putty @%s", session);
1972 inherit_handles = FALSE;
1976 } else /* IDM_NEWSESS */ {
1978 inherit_handles = FALSE;
1981 GetModuleFileName(NULL, b, sizeof(b) - 1);
1983 si.lpReserved = NULL;
1984 si.lpDesktop = NULL;
1988 si.lpReserved2 = NULL;
1989 CreateProcess(b, cl, NULL, NULL, inherit_handles,
1990 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
1993 CloseHandle(filemap);
2000 logevent(NULL, "----- Session restarted -----");
2009 int reconfig_result;
2014 reconfiguring = TRUE;
2016 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
2020 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2021 reconfiguring = FALSE;
2022 if (!reconfig_result)
2026 /* Disable full-screen if resizing forbidden */
2027 HMENU m = GetSystemMenu (hwnd, FALSE);
2028 EnableMenuItem(m, IDM_FULLSCREEN, MF_BYCOMMAND |
2029 (cfg.resize_action == RESIZE_DISABLED)
2030 ? MF_GRAYED : MF_ENABLED);
2031 /* Gracefully unzoom if necessary */
2032 if (IsZoomed(hwnd) &&
2033 (cfg.resize_action == RESIZE_DISABLED)) {
2034 ShowWindow(hwnd, SW_RESTORE);
2038 /* Pass new config data to the logging module */
2039 log_reconfig(logctx, &cfg);
2043 * Flush the line discipline's edit buffer in the
2044 * case where local editing has just been disabled.
2047 ldisc_send(ldisc, NULL, 0, 0);
2055 /* Pass new config data to the terminal */
2056 term_reconfig(term, &cfg);
2058 /* Pass new config data to the back end */
2060 back->reconfig(backhandle, &cfg);
2062 /* Screen size changed ? */
2063 if (cfg.height != prev_cfg.height ||
2064 cfg.width != prev_cfg.width ||
2065 cfg.savelines != prev_cfg.savelines ||
2066 cfg.resize_action == RESIZE_FONT ||
2067 (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2068 cfg.resize_action == RESIZE_DISABLED)
2069 term_size(term, cfg.height, cfg.width, cfg.savelines);
2071 /* Enable or disable the scroll bar, etc */
2073 LONG nflg, flag = GetWindowLong(hwnd, GWL_STYLE);
2074 LONG nexflag, exflag =
2075 GetWindowLong(hwnd, GWL_EXSTYLE);
2078 if (cfg.alwaysontop != prev_cfg.alwaysontop) {
2079 if (cfg.alwaysontop) {
2080 nexflag |= WS_EX_TOPMOST;
2081 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2082 SWP_NOMOVE | SWP_NOSIZE);
2084 nexflag &= ~(WS_EX_TOPMOST);
2085 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2086 SWP_NOMOVE | SWP_NOSIZE);
2089 if (cfg.sunken_edge)
2090 nexflag |= WS_EX_CLIENTEDGE;
2092 nexflag &= ~(WS_EX_CLIENTEDGE);
2095 if (is_full_screen() ?
2096 cfg.scrollbar_in_fullscreen : cfg.scrollbar)
2099 nflg &= ~WS_VSCROLL;
2101 if (cfg.resize_action == RESIZE_DISABLED ||
2103 nflg &= ~WS_THICKFRAME;
2105 nflg |= WS_THICKFRAME;
2107 if (cfg.resize_action == RESIZE_DISABLED)
2108 nflg &= ~WS_MAXIMIZEBOX;
2110 nflg |= WS_MAXIMIZEBOX;
2112 if (nflg != flag || nexflag != exflag) {
2114 SetWindowLong(hwnd, GWL_STYLE, nflg);
2115 if (nexflag != exflag)
2116 SetWindowLong(hwnd, GWL_EXSTYLE, nexflag);
2118 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2119 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2120 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2128 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2133 set_title(NULL, cfg.wintitle);
2134 if (IsIconic(hwnd)) {
2136 cfg.win_name_always ? window_name :
2140 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
2141 strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
2142 cfg.font.isbold != prev_cfg.font.isbold ||
2143 cfg.font.height != prev_cfg.font.height ||
2144 cfg.font.charset != prev_cfg.font.charset ||
2145 cfg.vtmode != prev_cfg.vtmode ||
2146 cfg.bold_colour != prev_cfg.bold_colour ||
2147 cfg.resize_action == RESIZE_DISABLED ||
2148 cfg.resize_action == RESIZE_EITHER ||
2149 (cfg.resize_action != prev_cfg.resize_action))
2152 InvalidateRect(hwnd, NULL, TRUE);
2153 reset_window(init_lvl);
2154 net_pending_errors();
2161 term_do_paste(term);
2169 ldisc_send(ldisc, NULL, 0, 0);
2175 WinHelp(hwnd, help_path,
2176 help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
2180 * We get this if the System menu has been activated
2187 * We get this if the System menu has been activated
2188 * using the keyboard. This might happen from within
2189 * TranslateKey, in which case it really wants to be
2190 * followed by a `space' character to actually _bring
2191 * the menu up_ rather than just sitting there in
2192 * `ready to appear' state.
2194 show_mouseptr(1); /* make sure pointer is visible */
2196 PostMessage(hwnd, WM_CHAR, ' ', 0);
2198 case IDM_FULLSCREEN:
2202 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2203 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2205 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2206 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2208 * Ensure we haven't been sent a bogus SYSCOMMAND
2209 * which would cause us to reference invalid memory
2210 * and crash. Perhaps I'm just too paranoid here.
2212 if (i >= n_specials)
2215 back->special(backhandle, specials[i].code);
2216 net_pending_errors();
2221 #define X_POS(l) ((int)(short)LOWORD(l))
2222 #define Y_POS(l) ((int)(short)HIWORD(l))
2224 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2225 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2226 case WM_LBUTTONDOWN:
2227 case WM_MBUTTONDOWN:
2228 case WM_RBUTTONDOWN:
2232 if (message == WM_RBUTTONDOWN &&
2233 ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
2236 show_mouseptr(1); /* make sure pointer is visible */
2237 GetCursorPos(&cursorpos);
2238 TrackPopupMenu(popup_menus[CTXMENU].menu,
2239 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2240 cursorpos.x, cursorpos.y,
2248 case WM_LBUTTONDOWN:
2252 case WM_MBUTTONDOWN:
2253 button = MBT_MIDDLE;
2256 case WM_RBUTTONDOWN:
2265 button = MBT_MIDDLE;
2273 button = press = 0; /* shouldn't happen */
2277 * Special case: in full-screen mode, if the left
2278 * button is clicked in the very top left corner of the
2279 * window, we put up the System menu instead of doing
2283 char mouse_on_hotspot = 0;
2292 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2295 mi.cbSize = sizeof(MONITORINFO);
2296 GetMonitorInfo(mon, &mi);
2298 if (mi.rcMonitor.left == pt.x &&
2299 mi.rcMonitor.top == pt.y) {
2300 mouse_on_hotspot = 1;
2305 if (pt.x == 0 && pt.y == 0) {
2306 mouse_on_hotspot = 1;
2309 if (is_full_screen() && press &&
2310 button == MBT_LEFT && mouse_on_hotspot) {
2311 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2312 MAKELPARAM(pt.x, pt.y));
2319 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2320 wParam & MK_SHIFT, wParam & MK_CONTROL,
2324 term_mouse(term, button, translate_button(button), MA_RELEASE,
2325 TO_CHR_X(X_POS(lParam)),
2326 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2327 wParam & MK_CONTROL, is_alt_pressed());
2335 * Windows seems to like to occasionally send MOUSEMOVE
2336 * events even if the mouse hasn't moved. Don't unhide
2337 * the mouse pointer in this case.
2339 static WPARAM wp = 0;
2340 static LPARAM lp = 0;
2341 if (wParam != wp || lParam != lp ||
2342 last_mousemove != WM_MOUSEMOVE) {
2344 wp = wParam; lp = lParam;
2345 last_mousemove = WM_MOUSEMOVE;
2349 * Add the mouse position and message time to the random
2352 noise_ultralight(lParam);
2354 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2355 GetCapture() == hwnd) {
2357 if (wParam & MK_LBUTTON)
2359 else if (wParam & MK_MBUTTON)
2363 term_mouse(term, b, translate_button(b), MA_DRAG,
2364 TO_CHR_X(X_POS(lParam)),
2365 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2366 wParam & MK_CONTROL, is_alt_pressed());
2369 case WM_NCMOUSEMOVE:
2371 static WPARAM wp = 0;
2372 static LPARAM lp = 0;
2373 if (wParam != wp || lParam != lp ||
2374 last_mousemove != WM_NCMOUSEMOVE) {
2376 wp = wParam; lp = lParam;
2377 last_mousemove = WM_NCMOUSEMOVE;
2380 noise_ultralight(lParam);
2382 case WM_IGNORE_CLIP:
2383 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2385 case WM_DESTROYCLIPBOARD:
2387 term_deselect(term);
2388 ignore_clip = FALSE;
2395 hdc = BeginPaint(hwnd, &p);
2397 SelectPalette(hdc, pal, TRUE);
2398 RealizePalette(hdc);
2402 * We have to be careful about term_paint(). It will
2403 * set a bunch of character cells to INVALID and then
2404 * call do_paint(), which will redraw those cells and
2405 * _then mark them as done_. This may not be accurate:
2406 * when painting in WM_PAINT context we are restricted
2407 * to the rectangle which has just been exposed - so if
2408 * that only covers _part_ of a character cell and the
2409 * rest of it was already visible, that remainder will
2410 * not be redrawn at all. Accordingly, we must not
2411 * paint any character cell in a WM_PAINT context which
2412 * already has a pending update due to terminal output.
2413 * The simplest solution to this - and many, many
2414 * thanks to Hung-Te Lin for working all this out - is
2415 * not to do any actual painting at _all_ if there's a
2416 * pending terminal update: just mark the relevant
2417 * character cells as INVALID and wait for the
2418 * scheduled full update to sort it out.
2420 * I have a suspicion this isn't the _right_ solution.
2421 * An alternative approach would be to have terminal.c
2422 * separately track what _should_ be on the terminal
2423 * screen and what _is_ on the terminal screen, and
2424 * have two completely different types of redraw (one
2425 * for full updates, which syncs the former with the
2426 * terminal itself, and one for WM_PAINT which syncs
2427 * the latter with the former); yet another possibility
2428 * would be to have the Windows front end do what the
2429 * GTK one already does, and maintain a bitmap of the
2430 * current terminal appearance so that WM_PAINT becomes
2431 * completely trivial. However, this should do for now.
2433 term_paint(term, hdc,
2434 (p.rcPaint.left-offset_width)/font_width,
2435 (p.rcPaint.top-offset_height)/font_height,
2436 (p.rcPaint.right-offset_width-1)/font_width,
2437 (p.rcPaint.bottom-offset_height-1)/font_height,
2438 !term->window_update_pending);
2441 p.rcPaint.left < offset_width ||
2442 p.rcPaint.top < offset_height ||
2443 p.rcPaint.right >= offset_width + font_width*term->cols ||
2444 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2446 HBRUSH fillcolour, oldbrush;
2448 fillcolour = CreateSolidBrush (
2449 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2450 oldbrush = SelectObject(hdc, fillcolour);
2451 edge = CreatePen(PS_SOLID, 0,
2452 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2453 oldpen = SelectObject(hdc, edge);
2456 * Jordan Russell reports that this apparently
2457 * ineffectual IntersectClipRect() call masks a
2458 * Windows NT/2K bug causing strange display
2459 * problems when the PuTTY window is taller than
2460 * the primary monitor. It seems harmless enough...
2462 IntersectClipRect(hdc,
2463 p.rcPaint.left, p.rcPaint.top,
2464 p.rcPaint.right, p.rcPaint.bottom);
2466 ExcludeClipRect(hdc,
2467 offset_width, offset_height,
2468 offset_width+font_width*term->cols,
2469 offset_height+font_height*term->rows);
2471 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2472 p.rcPaint.right, p.rcPaint.bottom);
2474 /* SelectClipRgn(hdc, NULL); */
2476 SelectObject(hdc, oldbrush);
2477 DeleteObject(fillcolour);
2478 SelectObject(hdc, oldpen);
2481 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2482 SelectObject(hdc, GetStockObject(WHITE_PEN));
2488 enact_netevent(wParam, lParam);
2489 net_pending_errors();
2492 term_set_focus(term, TRUE);
2493 CreateCaret(hwnd, caretbm, font_width, font_height);
2495 flash_window(0); /* stop */
2501 term_set_focus(term, FALSE);
2503 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2506 case WM_ENTERSIZEMOVE:
2507 #ifdef RDB_DEBUG_PATCH
2508 debug((27, "WM_ENTERSIZEMOVE"));
2512 need_backend_resize = FALSE;
2514 case WM_EXITSIZEMOVE:
2517 #ifdef RDB_DEBUG_PATCH
2518 debug((27, "WM_EXITSIZEMOVE"));
2520 if (need_backend_resize) {
2521 term_size(term, cfg.height, cfg.width, cfg.savelines);
2522 InvalidateRect(hwnd, NULL, TRUE);
2527 * This does two jobs:
2528 * 1) Keep the sizetip uptodate
2529 * 2) Make sure the window size is _stepped_ in units of the font size.
2531 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2532 int width, height, w, h, ew, eh;
2533 LPRECT r = (LPRECT) lParam;
2535 if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
2536 (cfg.height != term->rows || cfg.width != term->cols )) {
2538 * Great! It seems that both the terminal size and the
2539 * font size have been changed and the user is now dragging.
2541 * It will now be difficult to get back to the configured
2544 * This would be easier but it seems to be too confusing.
2546 term_size(term, cfg.height, cfg.width, cfg.savelines);
2549 cfg.height=term->rows; cfg.width=term->cols;
2551 InvalidateRect(hwnd, NULL, TRUE);
2552 need_backend_resize = TRUE;
2555 width = r->right - r->left - extra_width;
2556 height = r->bottom - r->top - extra_height;
2557 w = (width + font_width / 2) / font_width;
2560 h = (height + font_height / 2) / font_height;
2563 UpdateSizeTip(hwnd, w, h);
2564 ew = width - w * font_width;
2565 eh = height - h * font_height;
2567 if (wParam == WMSZ_LEFT ||
2568 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2574 if (wParam == WMSZ_TOP ||
2575 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2585 int width, height, w, h, rv = 0;
2586 int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2587 int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2588 LPRECT r = (LPRECT) lParam;
2590 width = r->right - r->left - ex_width;
2591 height = r->bottom - r->top - ex_height;
2593 w = (width + term->cols/2)/term->cols;
2594 h = (height + term->rows/2)/term->rows;
2595 if ( r->right != r->left + w*term->cols + ex_width)
2598 if (wParam == WMSZ_LEFT ||
2599 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2600 r->left = r->right - w*term->cols - ex_width;
2602 r->right = r->left + w*term->cols + ex_width;
2604 if (r->bottom != r->top + h*term->rows + ex_height)
2607 if (wParam == WMSZ_TOP ||
2608 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2609 r->top = r->bottom - h*term->rows - ex_height;
2611 r->bottom = r->top + h*term->rows + ex_height;
2615 /* break; (never reached) */
2616 case WM_FULLSCR_ON_MAX:
2617 fullscr_on_max = TRUE;
2620 sys_cursor_update();
2623 #ifdef RDB_DEBUG_PATCH
2624 debug((27, "WM_SIZE %s (%d,%d)",
2625 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2626 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2627 (wParam == SIZE_RESTORED && resizing) ? "to":
2628 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2630 LOWORD(lParam), HIWORD(lParam)));
2632 if (wParam == SIZE_MINIMIZED)
2634 cfg.win_name_always ? window_name : icon_name);
2635 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2636 SetWindowText(hwnd, window_name);
2637 if (wParam == SIZE_RESTORED)
2638 clear_full_screen();
2639 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2640 fullscr_on_max = FALSE;
2644 if (cfg.resize_action == RESIZE_DISABLED) {
2645 /* A resize, well it better be a minimize. */
2649 int width, height, w, h;
2651 width = LOWORD(lParam);
2652 height = HIWORD(lParam);
2655 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2657 prev_rows = term->rows;
2658 prev_cols = term->cols;
2659 if (cfg.resize_action == RESIZE_TERM) {
2660 w = width / font_width;
2662 h = height / font_height;
2665 term_size(term, h, w, cfg.savelines);
2668 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2670 if (cfg.resize_action == RESIZE_TERM)
2671 term_size(term, prev_rows, prev_cols, cfg.savelines);
2672 if (cfg.resize_action != RESIZE_FONT)
2677 /* This is an unexpected resize, these will normally happen
2678 * if the window is too large. Probably either the user
2679 * selected a huge font or the screen size has changed.
2681 * This is also called with minimize.
2683 else reset_window(-1);
2687 * Don't call back->size in mid-resize. (To prevent
2688 * massive numbers of resize events getting sent
2689 * down the connection during an NT opaque drag.)
2692 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2693 need_backend_resize = TRUE;
2694 w = (width-cfg.window_border*2) / font_width;
2696 h = (height-cfg.window_border*2) / font_height;
2705 sys_cursor_update();
2708 switch (LOWORD(wParam)) {
2710 term_scroll(term, -1, 0);
2713 term_scroll(term, +1, 0);
2716 term_scroll(term, 0, +1);
2719 term_scroll(term, 0, -1);
2722 term_scroll(term, 0, +term->rows / 2);
2725 term_scroll(term, 0, -term->rows / 2);
2727 case SB_THUMBPOSITION:
2729 term_scroll(term, 1, HIWORD(wParam));
2733 case WM_PALETTECHANGED:
2734 if ((HWND) wParam != hwnd && pal != NULL) {
2735 HDC hdc = get_ctx(NULL);
2737 if (RealizePalette(hdc) > 0)
2743 case WM_QUERYNEWPALETTE:
2745 HDC hdc = get_ctx(NULL);
2747 if (RealizePalette(hdc) > 0)
2759 * Add the scan code and keypress timing to the random
2762 noise_ultralight(lParam);
2765 * We don't do TranslateMessage since it disassociates the
2766 * resulting CHAR message from the KEYDOWN that sparked it,
2767 * which we occasionally don't want. Instead, we process
2768 * KEYDOWN, and call the Win32 translator functions so that
2769 * we get the translations under _our_ control.
2772 unsigned char buf[20];
2775 if (wParam == VK_PROCESSKEY) { /* IME PROCESS key */
2776 if (message == WM_KEYDOWN) {
2779 m.message = WM_KEYDOWN;
2781 m.lParam = lParam & 0xdfff;
2782 TranslateMessage(&m);
2783 } else break; /* pass to Windows for default processing */
2785 len = TranslateKey(message, wParam, lParam, buf);
2787 return DefWindowProc(hwnd, message, wParam, lParam);
2791 * Interrupt an ongoing paste. I'm not sure
2792 * this is sensible, but for the moment it's
2793 * preferable to having to faff about buffering
2799 * We need not bother about stdin backlogs
2800 * here, because in GUI PuTTY we can't do
2801 * anything about it anyway; there's no means
2802 * of asking Windows to hold off on KEYDOWN
2803 * messages. We _have_ to buffer everything
2806 term_seen_key_event(term);
2808 ldisc_send(ldisc, buf, len, 1);
2813 net_pending_errors();
2815 case WM_INPUTLANGCHANGE:
2816 /* wParam == Font number */
2817 /* lParam == Locale */
2818 set_input_locale((HKL)lParam);
2819 sys_cursor_update();
2821 case WM_IME_STARTCOMPOSITION:
2823 HIMC hImc = ImmGetContext(hwnd);
2824 ImmSetCompositionFont(hImc, &lfont);
2825 ImmReleaseContext(hwnd, hImc);
2828 case WM_IME_COMPOSITION:
2834 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
2835 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2837 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2838 break; /* fall back to DefWindowProc */
2840 hIMC = ImmGetContext(hwnd);
2841 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2845 buff = snewn(n, char);
2846 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
2848 * Jaeyoun Chung reports that Korean character
2849 * input doesn't work correctly if we do a single
2850 * luni_send() covering the whole of buff. So
2851 * instead we luni_send the characters one by one.
2853 term_seen_key_event(term);
2854 for (i = 0; i < n; i += 2) {
2856 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2860 ImmReleaseContext(hwnd, hIMC);
2865 if (wParam & 0xFF00) {
2866 unsigned char buf[2];
2869 buf[0] = wParam >> 8;
2870 term_seen_key_event(term);
2872 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
2874 char c = (unsigned char) wParam;
2875 term_seen_key_event(term);
2877 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
2883 * Nevertheless, we are prepared to deal with WM_CHAR
2884 * messages, should they crop up. So if someone wants to
2885 * post the things to us as part of a macro manoeuvre,
2886 * we're ready to cope.
2889 char c = (unsigned char)wParam;
2890 term_seen_key_event(term);
2892 lpage_send(ldisc, CP_ACP, &c, 1, 1);
2895 case WM_SYSCOLORCHANGE:
2896 if (cfg.system_colour) {
2897 /* Refresh palette from system colours. */
2898 /* XXX actually this zaps the entire palette. */
2901 /* Force a repaint of the terminal window. */
2902 term_invalidate(term);
2905 case WM_AGENT_CALLBACK:
2907 struct agent_callback *c = (struct agent_callback *)lParam;
2908 c->callback(c->callback_ctx, c->data, c->len);
2913 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
2914 int shift_pressed=0, control_pressed=0;
2916 if (message == WM_MOUSEWHEEL) {
2917 wheel_accumulator += (short)HIWORD(wParam);
2918 shift_pressed=LOWORD(wParam) & MK_SHIFT;
2919 control_pressed=LOWORD(wParam) & MK_CONTROL;
2922 wheel_accumulator += (int)wParam;
2923 if (GetKeyboardState(keys)!=0) {
2924 shift_pressed=keys[VK_SHIFT]&0x80;
2925 control_pressed=keys[VK_CONTROL]&0x80;
2929 /* process events when the threshold is reached */
2930 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
2933 /* reduce amount for next time */
2934 if (wheel_accumulator > 0) {
2936 wheel_accumulator -= WHEEL_DELTA;
2937 } else if (wheel_accumulator < 0) {
2939 wheel_accumulator += WHEEL_DELTA;
2943 if (send_raw_mouse &&
2944 !(cfg.mouse_override && shift_pressed)) {
2945 /* send a mouse-down followed by a mouse up */
2946 term_mouse(term, b, translate_button(b),
2948 TO_CHR_X(X_POS(lParam)),
2949 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2950 control_pressed, is_alt_pressed());
2951 term_mouse(term, b, translate_button(b),
2952 MA_RELEASE, TO_CHR_X(X_POS(lParam)),
2953 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2954 control_pressed, is_alt_pressed());
2956 /* trigger a scroll */
2957 term_scroll(term, 0,
2959 -term->rows / 2 : term->rows / 2);
2967 * Any messages we don't process completely above are passed through to
2968 * DefWindowProc() for default processing.
2970 return DefWindowProc(hwnd, message, wParam, lParam);
2974 * Move the system caret. (We maintain one, even though it's
2975 * invisible, for the benefit of blind people: apparently some
2976 * helper software tracks the system caret, so we should arrange to
2979 void sys_cursor(void *frontend, int x, int y)
2983 if (!term->has_focus) return;
2986 * Avoid gratuitously re-updating the cursor position and IMM
2987 * window if there's no actual change required.
2989 cx = x * font_width + offset_width;
2990 cy = y * font_height + offset_height;
2991 if (cx == caret_x && cy == caret_y)
2996 sys_cursor_update();
2999 static void sys_cursor_update(void)
3004 if (!term->has_focus) return;
3006 if (caret_x < 0 || caret_y < 0)
3009 SetCaretPos(caret_x, caret_y);
3011 /* IMM calls on Win98 and beyond only */
3012 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3014 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3015 osVersion.dwMinorVersion == 0) return; /* 95 */
3017 /* we should have the IMM functions */
3018 hIMC = ImmGetContext(hwnd);
3019 cf.dwStyle = CFS_POINT;
3020 cf.ptCurrentPos.x = caret_x;
3021 cf.ptCurrentPos.y = caret_y;
3022 ImmSetCompositionWindow(hIMC, &cf);
3024 ImmReleaseContext(hwnd, hIMC);
3028 * Draw a line of text in the window, at given character
3029 * coordinates, in given attributes.
3031 * We are allowed to fiddle with the contents of `text'.
3033 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3034 unsigned long attr, int lattr)
3037 int nfg, nbg, nfont;
3040 int force_manual_underline = 0;
3041 int fnt_width, char_width;
3042 int text_adjust = 0;
3043 static int *IpDx = 0, IpDxLEN = 0;
3045 lattr &= LATTR_MODE;
3047 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3049 if (attr & ATTR_WIDE)
3052 if (len > IpDxLEN || IpDx[0] != char_width) {
3054 if (len > IpDxLEN) {
3056 IpDx = snewn(len + 16, int);
3057 IpDxLEN = (len + 16);
3059 for (i = 0; i < IpDxLEN; i++)
3060 IpDx[i] = char_width;
3063 /* Only want the left half of double width lines */
3064 if (lattr != LATTR_NORM && x*2 >= term->cols)
3072 if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
3073 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3074 if (bold_mode == BOLD_COLOURS)
3077 /* cursor fg and bg */
3078 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3082 if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3083 /* Assume a poorman font is borken in other ways too. */
3093 nfont |= FONT_WIDE + FONT_HIGH;
3096 if (attr & ATTR_NARROW)
3097 nfont |= FONT_NARROW;
3099 /* Special hack for the VT100 linedraw glyphs. */
3100 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3101 switch ((unsigned char) (text[0])) {
3103 text_adjust = -2 * font_height / 5;
3106 text_adjust = -1 * font_height / 5;
3109 text_adjust = font_height / 5;
3112 text_adjust = 2 * font_height / 5;
3115 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3117 text[0] = ucsdata.unitab_xterm['q'];
3118 if (attr & ATTR_UNDER) {
3119 attr &= ~ATTR_UNDER;
3120 force_manual_underline = 1;
3124 /* Anything left as an original character set is unprintable. */
3125 if (DIRECT_CHAR(text[0])) {
3127 for (i = 0; i < len; i++)
3132 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3135 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3136 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3137 if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
3139 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3140 nfont |= FONT_UNDERLINE;
3141 another_font(nfont);
3142 if (!fonts[nfont]) {
3143 if (nfont & FONT_UNDERLINE)
3144 force_manual_underline = 1;
3145 /* Don't do the same for manual bold, it could be bad news. */
3147 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3149 another_font(nfont);
3151 nfont = FONT_NORMAL;
3152 if (attr & ATTR_REVERSE) {
3157 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD)) {
3158 if (nfg < 16) nfg |= 8;
3159 else if (nfg >= 256) nfg |= 1;
3161 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK)) {
3162 if (nbg < 16) nbg |= 8;
3163 else if (nbg >= 256) nbg |= 1;
3167 SelectObject(hdc, fonts[nfont]);
3168 SetTextColor(hdc, fg);
3169 SetBkColor(hdc, bg);
3170 if (attr & TATTR_COMBINING)
3171 SetBkMode(hdc, TRANSPARENT);
3173 SetBkMode(hdc, OPAQUE);
3176 line_box.right = x + char_width * len;
3177 line_box.bottom = y + font_height;
3179 /* Only want the left half of double width lines */
3180 if (line_box.right > font_width*term->cols+offset_width)
3181 line_box.right = font_width*term->cols+offset_width;
3183 /* We're using a private area for direct to font. (512 chars.) */
3184 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3185 /* Ho Hum, dbcs fonts are a PITA! */
3186 /* To display on W9x I have to convert to UCS */
3187 static wchar_t *uni_buf = 0;
3188 static int uni_len = 0;
3190 if (len > uni_len) {
3193 uni_buf = snewn(uni_len, wchar_t);
3196 for(nlen = mptr = 0; mptr<len; mptr++) {
3197 uni_buf[nlen] = 0xFFFD;
3198 if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
3200 dbcstext[0] = text[mptr] & 0xFF;
3201 dbcstext[1] = text[mptr+1] & 0xFF;
3202 IpDx[nlen] += char_width;
3203 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3204 dbcstext, 2, uni_buf+nlen, 1);
3210 dbcstext[0] = text[mptr] & 0xFF;
3211 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3212 dbcstext, 1, uni_buf+nlen, 1);
3220 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3221 ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
3222 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3223 SetBkMode(hdc, TRANSPARENT);
3224 ExtTextOutW(hdc, x - 1,
3225 y - font_height * (lattr ==
3226 LATTR_BOT) + text_adjust,
3227 ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
3231 } else if (DIRECT_FONT(text[0])) {
3232 static char *directbuf = NULL;
3233 static int directlen = 0;
3235 if (len > directlen) {
3237 directbuf = sresize(directbuf, directlen, char);
3240 for (i = 0; i < len; i++)
3241 directbuf[i] = text[i] & 0xFF;
3244 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3245 ETO_CLIPPED | ETO_OPAQUE, &line_box, directbuf, len, IpDx);
3246 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3247 SetBkMode(hdc, TRANSPARENT);
3249 /* GRR: This draws the character outside it's box and can leave
3250 * 'droppings' even with the clip box! I suppose I could loop it
3251 * one character at a time ... yuk.
3253 * Or ... I could do a test print with "W", and use +1 or -1 for this
3254 * shift depending on if the leftmost column is blank...
3256 ExtTextOut(hdc, x - 1,
3257 y - font_height * (lattr ==
3258 LATTR_BOT) + text_adjust,
3259 ETO_CLIPPED, &line_box, directbuf, len, IpDx);
3262 /* And 'normal' unicode characters */
3263 static WCHAR *wbuf = NULL;
3264 static int wlen = 0;
3270 wbuf = snewn(wlen, WCHAR);
3273 for (i = 0; i < len; i++)
3276 /* print Glyphs as they are, without Windows' Shaping*/
3277 exact_textout(hdc, x, y - font_height * (lattr == LATTR_BOT) + text_adjust,
3278 &line_box, wbuf, len, IpDx, !(attr & TATTR_COMBINING));
3279 /* ExtTextOutW(hdc, x,
3280 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3281 ETO_CLIPPED | ETO_OPAQUE, &line_box, wbuf, len, IpDx);
3284 /* And the shadow bold hack. */
3285 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3286 SetBkMode(hdc, TRANSPARENT);
3287 ExtTextOutW(hdc, x - 1,
3288 y - font_height * (lattr ==
3289 LATTR_BOT) + text_adjust,
3290 ETO_CLIPPED, &line_box, wbuf, len, IpDx);
3293 if (lattr != LATTR_TOP && (force_manual_underline ||
3294 (und_mode == UND_LINE
3295 && (attr & ATTR_UNDER)))) {
3298 if (lattr == LATTR_BOT)
3299 dec = dec * 2 - font_height;
3301 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3302 MoveToEx(hdc, x, y + dec, NULL);
3303 LineTo(hdc, x + len * char_width, y + dec);
3304 oldpen = SelectObject(hdc, oldpen);
3305 DeleteObject(oldpen);
3310 * Wrapper that handles combining characters.
3312 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3313 unsigned long attr, int lattr)
3315 if (attr & TATTR_COMBINING) {
3316 unsigned long a = 0;
3317 attr &= ~TATTR_COMBINING;
3319 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3321 a = TATTR_COMBINING;
3324 do_text_internal(ctx, x, y, text, len, attr, lattr);
3327 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3328 unsigned long attr, int lattr)
3334 int ctype = cfg.cursor_type;
3336 lattr &= LATTR_MODE;
3338 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3339 if (*text != UCSWIDE) {
3340 do_text(ctx, x, y, text, len, attr, lattr);
3344 attr |= TATTR_RIGHTCURS;
3347 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3348 if (attr & ATTR_WIDE)
3355 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3358 pts[0].x = pts[1].x = pts[4].x = x;
3359 pts[2].x = pts[3].x = x + char_width - 1;
3360 pts[0].y = pts[3].y = pts[4].y = y;
3361 pts[1].y = pts[2].y = y + font_height - 1;
3362 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3363 Polyline(hdc, pts, 5);
3364 oldpen = SelectObject(hdc, oldpen);
3365 DeleteObject(oldpen);
3366 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3367 int startx, starty, dx, dy, length, i;
3370 starty = y + descent;
3373 length = char_width;
3376 if (attr & TATTR_RIGHTCURS)
3377 xadjust = char_width - 1;
3378 startx = x + xadjust;
3382 length = font_height;
3384 if (attr & TATTR_ACTCURS) {
3387 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3388 MoveToEx(hdc, startx, starty, NULL);
3389 LineTo(hdc, startx + dx * length, starty + dy * length);
3390 oldpen = SelectObject(hdc, oldpen);
3391 DeleteObject(oldpen);
3393 for (i = 0; i < length; i++) {
3395 SetPixel(hdc, startx, starty, colours[261]);
3404 /* This function gets the actual width of a character in the normal font.
3406 int char_width(Context ctx, int uc) {
3410 /* If the font max is the same as the font ave width then this
3411 * function is a no-op.
3413 if (!font_dualwidth) return 1;
3415 switch (uc & CSET_MASK) {
3417 uc = ucsdata.unitab_line[uc & 0xFF];
3420 uc = ucsdata.unitab_xterm[uc & 0xFF];
3423 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3426 if (DIRECT_FONT(uc)) {
3427 if (ucsdata.dbcs_screenfont) return 1;
3429 /* Speedup, I know of no font where ascii is the wrong width */
3430 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3433 if ( (uc & CSET_MASK) == CSET_ACP ) {
3434 SelectObject(hdc, fonts[FONT_NORMAL]);
3435 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3436 another_font(FONT_OEM);
3437 if (!fonts[FONT_OEM]) return 0;
3439 SelectObject(hdc, fonts[FONT_OEM]);
3443 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3444 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3447 /* Speedup, I know of no font where ascii is the wrong width */
3448 if (uc >= ' ' && uc <= '~') return 1;
3450 SelectObject(hdc, fonts[FONT_NORMAL]);
3451 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3452 /* Okay that one worked */ ;
3453 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3454 /* This should work on 9x too, but it's "less accurate" */ ;
3459 ibuf += font_width / 2 -1;
3466 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3467 * codes. Returns number of bytes used or zero to drop the message
3468 * or -1 to forward the message to windows.
3470 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3471 unsigned char *output)
3474 int scan, left_alt = 0, key_down, shift_state;
3476 unsigned char *p = output;
3477 static int alt_sum = 0;
3479 HKL kbd_layout = GetKeyboardLayout(0);
3481 /* keys is for ToAsciiEx. There's some ick here, see below. */
3482 static WORD keys[3];
3483 static int compose_char = 0;
3484 static WPARAM compose_key = 0;
3486 r = GetKeyboardState(keystate);
3488 memset(keystate, 0, sizeof(keystate));
3491 #define SHOW_TOASCII_RESULT
3492 { /* Tell us all about key events */
3493 static BYTE oldstate[256];
3494 static int first = 1;
3498 memcpy(oldstate, keystate, sizeof(oldstate));
3501 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3503 } else if ((HIWORD(lParam) & KF_UP)
3504 && scan == (HIWORD(lParam) & 0xFF)) {
3508 if (wParam >= VK_F1 && wParam <= VK_F20)
3509 debug(("K_F%d", wParam + 1 - VK_F1));
3522 debug(("VK_%02x", wParam));
3524 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3526 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3528 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3529 if (ch >= ' ' && ch <= '~')
3530 debug((", '%c'", ch));
3532 debug((", $%02x", ch));
3535 debug((", KB0=%02x", keys[0]));
3537 debug((", KB1=%02x", keys[1]));
3539 debug((", KB2=%02x", keys[2]));
3541 if ((keystate[VK_SHIFT] & 0x80) != 0)
3543 if ((keystate[VK_CONTROL] & 0x80) != 0)
3545 if ((HIWORD(lParam) & KF_EXTENDED))
3547 if ((HIWORD(lParam) & KF_UP))
3551 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3552 else if ((HIWORD(lParam) & KF_UP))
3553 oldstate[wParam & 0xFF] ^= 0x80;
3555 oldstate[wParam & 0xFF] ^= 0x81;
3557 for (ch = 0; ch < 256; ch++)
3558 if (oldstate[ch] != keystate[ch])
3559 debug((", M%02x=%02x", ch, keystate[ch]));
3561 memcpy(oldstate, keystate, sizeof(oldstate));
3565 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
3566 keystate[VK_RMENU] = keystate[VK_MENU];
3570 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
3571 if ((cfg.funky_type == FUNKY_VT400 ||
3572 (cfg.funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
3574 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
3576 wParam = VK_EXECUTE;
3578 /* UnToggle NUMLock */
3579 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3580 keystate[VK_NUMLOCK] ^= 1;
3583 /* And write back the 'adjusted' state */
3584 SetKeyboardState(keystate);
3587 /* Disable Auto repeat if required */
3588 if (term->repeat_off &&
3589 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
3592 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
3595 key_down = ((HIWORD(lParam) & KF_UP) == 0);
3597 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
3598 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
3599 if (cfg.ctrlaltkeys)
3600 keystate[VK_MENU] = 0;
3602 keystate[VK_RMENU] = 0x80;
3607 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
3608 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3609 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
3611 /* Note if AltGr was pressed and if it was used as a compose key */
3612 if (!compose_state) {
3613 compose_key = 0x100;
3614 if (cfg.compose_key) {
3615 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
3616 compose_key = wParam;
3618 if (wParam == VK_APPS)
3619 compose_key = wParam;
3622 if (wParam == compose_key) {
3623 if (compose_state == 0
3624 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3626 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
3630 } else if (compose_state == 1 && wParam != VK_CONTROL)
3633 if (compose_state > 1 && left_alt)
3636 /* Sanitize the number pad if not using a PC NumPad */
3637 if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
3638 && cfg.funky_type != FUNKY_XTERM)
3639 || cfg.funky_type == FUNKY_VT400 || cfg.nethack_keypad || compose_state) {
3640 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
3644 nParam = VK_NUMPAD0;
3647 nParam = VK_NUMPAD1;
3650 nParam = VK_NUMPAD2;
3653 nParam = VK_NUMPAD3;
3656 nParam = VK_NUMPAD4;
3659 nParam = VK_NUMPAD5;
3662 nParam = VK_NUMPAD6;
3665 nParam = VK_NUMPAD7;
3668 nParam = VK_NUMPAD8;
3671 nParam = VK_NUMPAD9;
3674 nParam = VK_DECIMAL;
3678 if (keystate[VK_NUMLOCK] & 1)
3685 /* If a key is pressed and AltGr is not active */
3686 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3687 /* Okay, prepare for most alts then ... */
3691 /* Lets see if it's a pattern we know all about ... */
3692 if (wParam == VK_PRIOR && shift_state == 1) {
3693 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3696 if (wParam == VK_PRIOR && shift_state == 2) {
3697 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3700 if (wParam == VK_NEXT && shift_state == 1) {
3701 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3704 if (wParam == VK_NEXT && shift_state == 2) {
3705 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3708 if (wParam == VK_INSERT && shift_state == 1) {
3709 term_do_paste(term);
3712 if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
3715 if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
3716 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3719 if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3720 (cfg.resize_action != RESIZE_DISABLED)) {
3721 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3725 /* Control-Numlock for app-keypad mode switch */
3726 if (wParam == VK_PAUSE && shift_state == 2) {
3727 term->app_keypad_keys ^= 1;
3731 /* Nethack keypad */
3732 if (cfg.nethack_keypad && !left_alt) {
3735 *p++ = shift_state ? 'B' : 'b';
3738 *p++ = shift_state ? 'J' : 'j';
3741 *p++ = shift_state ? 'N' : 'n';
3744 *p++ = shift_state ? 'H' : 'h';
3747 *p++ = shift_state ? '.' : '.';
3750 *p++ = shift_state ? 'L' : 'l';
3753 *p++ = shift_state ? 'Y' : 'y';
3756 *p++ = shift_state ? 'K' : 'k';
3759 *p++ = shift_state ? 'U' : 'u';
3764 /* Application Keypad */
3768 if (cfg.funky_type == FUNKY_VT400 ||
3769 (cfg.funky_type <= FUNKY_LINUX &&
3770 term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
3784 if (term->app_keypad_keys && !cfg.no_applic_k)
3821 if (cfg.funky_type == FUNKY_XTERM) {
3826 } else if (shift_state)
3833 if (cfg.funky_type == FUNKY_XTERM)
3837 if (cfg.funky_type == FUNKY_XTERM)
3841 if (cfg.funky_type == FUNKY_XTERM)
3846 if (HIWORD(lParam) & KF_EXTENDED)
3851 if (term->vt52_mode) {
3852 if (xkey >= 'P' && xkey <= 'S')
3853 p += sprintf((char *) p, "\x1B%c", xkey);
3855 p += sprintf((char *) p, "\x1B?%c", xkey);
3857 p += sprintf((char *) p, "\x1BO%c", xkey);
3862 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
3863 *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
3867 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
3868 /* We do the opposite of what is configured */
3869 *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
3873 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
3879 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
3883 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
3887 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
3892 if (wParam == VK_PAUSE) { /* Break/Pause */
3897 /* Control-2 to Control-8 are special */
3898 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
3899 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
3902 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
3906 if (shift_state == 2 && wParam == 0xDF) {
3910 if (shift_state == 3 && wParam == 0xDE) {
3911 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
3914 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
3921 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
3922 * for integer decimal nn.)
3924 * We also deal with the weird ones here. Linux VCs replace F1
3925 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
3926 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
3932 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
3935 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
3938 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
3941 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
3944 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
3947 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
3950 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
3953 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
3956 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
3959 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
3992 if ((shift_state&2) == 0) switch (wParam) {
4012 /* Reorder edit keys to physical order */
4013 if (cfg.funky_type == FUNKY_VT400 && code <= 6)
4014 code = "\0\2\1\4\5\3\6"[code];
4016 if (term->vt52_mode && code > 0 && code <= 6) {
4017 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4021 if (cfg.funky_type == FUNKY_SCO && /* SCO function keys */
4022 code >= 11 && code <= 34) {
4023 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4026 case VK_F1: index = 0; break;
4027 case VK_F2: index = 1; break;
4028 case VK_F3: index = 2; break;
4029 case VK_F4: index = 3; break;
4030 case VK_F5: index = 4; break;
4031 case VK_F6: index = 5; break;
4032 case VK_F7: index = 6; break;
4033 case VK_F8: index = 7; break;
4034 case VK_F9: index = 8; break;
4035 case VK_F10: index = 9; break;
4036 case VK_F11: index = 10; break;
4037 case VK_F12: index = 11; break;
4039 if (keystate[VK_SHIFT] & 0x80) index += 12;
4040 if (keystate[VK_CONTROL] & 0x80) index += 24;
4041 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4044 if (cfg.funky_type == FUNKY_SCO && /* SCO small keypad */
4045 code >= 1 && code <= 6) {
4046 char codes[] = "HL.FIG";
4050 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4054 if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4060 if (term->vt52_mode)
4061 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4064 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4067 if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4068 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4071 if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4072 if (term->vt52_mode)
4073 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4075 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4078 if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
4079 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4083 p += sprintf((char *) p, "\x1B[%d~", code);
4088 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4089 * some reason seems to send VK_CLEAR to Windows...).
4111 if (term->vt52_mode)
4112 p += sprintf((char *) p, "\x1B%c", xkey);
4114 int app_flg = (term->app_cursor_keys && !cfg.no_applic_c);
4117 * RDB: VT100 & VT102 manuals both state the
4118 * app cursor keys only work if the app keypad
4121 * SGT: That may well be true, but xterm
4122 * disagrees and so does at least one
4123 * application, so I've #if'ed this out and the
4124 * behaviour is back to PuTTY's original: app
4125 * cursor and app keypad are independently
4126 * switchable modes. If anyone complains about
4127 * _this_ I'll have to put in a configurable
4130 if (!term->app_keypad_keys)
4133 /* Useful mapping of Ctrl-arrows */
4134 if (shift_state == 2)
4138 p += sprintf((char *) p, "\x1BO%c", xkey);
4140 p += sprintf((char *) p, "\x1B[%c", xkey);
4147 * Finally, deal with Return ourselves. (Win95 seems to
4148 * foul it up when Alt is pressed, for some reason.)
4150 if (wParam == VK_RETURN) { /* Return */
4156 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4157 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4162 /* Okay we've done everything interesting; let windows deal with
4163 * the boring stuff */
4167 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4168 if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
4170 keystate[VK_CAPITAL] = 0;
4173 /* XXX how do we know what the max size of the keys array should
4174 * be is? There's indication on MS' website of an Inquire/InquireEx
4175 * functioning returning a KBINFO structure which tells us. */
4176 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4177 /* XXX 'keys' parameter is declared in MSDN documentation as
4179 * The experience of a French user indicates that on
4180 * Win98, WORD[] should be passed in, but on Win2K, it should
4181 * be BYTE[]. German WinXP and my Win2K with "US International"
4182 * driver corroborate this.
4183 * Experimentally I've conditionalised the behaviour on the
4184 * Win9x/NT split, but I suspect it's worse than that.
4185 * See wishlist item `win-dead-keys' for more horrible detail
4186 * and speculations. */
4189 r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
4190 for (i=0; i<3; i++) keys[i] = keybs[i];
4192 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4194 #ifdef SHOW_TOASCII_RESULT
4195 if (r == 1 && !key_down) {
4197 if (in_utf(term) || ucsdata.dbcs_screenfont)
4198 debug((", (U+%04x)", alt_sum));
4200 debug((", LCH(%d)", alt_sum));
4202 debug((", ACH(%d)", keys[0]));
4207 for (r1 = 0; r1 < r; r1++) {
4208 debug(("%s%d", r1 ? "," : "", keys[r1]));
4217 * Interrupt an ongoing paste. I'm not sure this is
4218 * sensible, but for the moment it's preferable to
4219 * having to faff about buffering things.
4224 for (i = 0; i < r; i++) {
4225 unsigned char ch = (unsigned char) keys[i];
4227 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
4232 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
4236 if ((nc = check_compose(compose_char, ch)) == -1) {
4237 MessageBeep(MB_ICONHAND);
4241 term_seen_key_event(term);
4243 luni_send(ldisc, &keybuf, 1, 1);
4251 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4253 term_seen_key_event(term);
4255 luni_send(ldisc, &keybuf, 1, 1);
4257 ch = (char) alt_sum;
4259 * We need not bother about stdin
4260 * backlogs here, because in GUI PuTTY
4261 * we can't do anything about it
4262 * anyway; there's no means of asking
4263 * Windows to hold off on KEYDOWN
4264 * messages. We _have_ to buffer
4265 * everything we're sent.
4267 term_seen_key_event(term);
4269 ldisc_send(ldisc, &ch, 1, 1);
4273 term_seen_key_event(term);
4275 lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
4278 if(capsOn && ch < 0x80) {
4281 cbuf[1] = xlat_uskbd2cyrllic(ch);
4282 term_seen_key_event(term);
4284 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4289 term_seen_key_event(term);
4291 lpage_send(ldisc, kbd_codepage,
4292 cbuf+!left_alt, 1+!!left_alt, 1);
4298 /* This is so the ALT-Numpad and dead keys work correctly. */
4303 /* If we're definitly not building up an ALT-54321 then clear it */
4306 /* If we will be using alt_sum fix the 256s */
4307 else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4312 * ALT alone may or may not want to bring up the System menu.
4313 * If it's not meant to, we return 0 on presses or releases of
4314 * ALT, to show that we've swallowed the keystroke. Otherwise
4315 * we return -1, which means Windows will give the keystroke
4316 * its default handling (i.e. bring up the System menu).
4318 if (wParam == VK_MENU && !cfg.alt_only)
4324 void request_paste(void *frontend)
4327 * In Windows, pasting is synchronous: we can read the
4328 * clipboard with no difficulty, so request_paste() can just go
4331 term_do_paste(term);
4334 void set_title(void *frontend, char *title)
4337 window_name = snewn(1 + strlen(title), char);
4338 strcpy(window_name, title);
4339 if (cfg.win_name_always || !IsIconic(hwnd))
4340 SetWindowText(hwnd, title);
4343 void set_icon(void *frontend, char *title)
4346 icon_name = snewn(1 + strlen(title), char);
4347 strcpy(icon_name, title);
4348 if (!cfg.win_name_always && IsIconic(hwnd))
4349 SetWindowText(hwnd, title);
4352 void set_sbar(void *frontend, int total, int start, int page)
4356 if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
4359 si.cbSize = sizeof(si);
4360 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4362 si.nMax = total - 1;
4366 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4369 Context get_ctx(void *frontend)
4375 SelectPalette(hdc, pal, FALSE);
4381 void free_ctx(Context ctx)
4383 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4384 ReleaseDC(hwnd, ctx);
4387 static void real_palette_set(int n, int r, int g, int b)
4390 logpal->palPalEntry[n].peRed = r;
4391 logpal->palPalEntry[n].peGreen = g;
4392 logpal->palPalEntry[n].peBlue = b;
4393 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4394 colours[n] = PALETTERGB(r, g, b);
4395 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4397 colours[n] = RGB(r, g, b);
4400 void palette_set(void *frontend, int n, int r, int g, int b)
4404 if (n > NALLCOLOURS)
4406 real_palette_set(n, r, g, b);
4408 HDC hdc = get_ctx(frontend);
4409 UnrealizeObject(pal);
4410 RealizePalette(hdc);
4415 void palette_reset(void *frontend)
4420 for (i = 0; i < NALLCOLOURS; i++) {
4422 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4423 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4424 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4425 logpal->palPalEntry[i].peFlags = 0;
4426 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4427 defpal[i].rgbtGreen,
4428 defpal[i].rgbtBlue);
4430 colours[i] = RGB(defpal[i].rgbtRed,
4431 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4436 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4437 hdc = get_ctx(frontend);
4438 RealizePalette(hdc);
4443 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4448 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4451 lock = GlobalLock(clipdata);
4454 memcpy(lock, data, len);
4455 ((unsigned char *) lock)[len] = 0;
4456 GlobalUnlock(clipdata);
4459 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4461 if (OpenClipboard(hwnd)) {
4463 SetClipboardData(CF_TEXT, clipdata);
4466 GlobalFree(clipdata);
4469 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4473 * Note: unlike write_aclip() this will not append a nul.
4475 void write_clip(void *frontend, wchar_t * data, int len, int must_deselect)
4477 HGLOBAL clipdata, clipdata2, clipdata3;
4479 void *lock, *lock2, *lock3;
4481 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4483 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4484 len * sizeof(wchar_t));
4485 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4487 if (!clipdata || !clipdata2) {
4489 GlobalFree(clipdata);
4491 GlobalFree(clipdata2);
4494 if (!(lock = GlobalLock(clipdata)))
4496 if (!(lock2 = GlobalLock(clipdata2)))
4499 memcpy(lock, data, len * sizeof(wchar_t));
4500 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4502 if (cfg.rtf_paste) {
4503 wchar_t unitab[256];
4505 unsigned char *tdata = (unsigned char *)lock2;
4506 wchar_t *udata = (wchar_t *)lock;
4507 int rtflen = 0, uindex = 0, tindex = 0;
4509 int multilen, blen, alen, totallen, i;
4510 char before[16], after[4];
4512 get_unitab(CP_ACP, unitab, 0);
4514 rtfsize = 100 + strlen(cfg.font.name);
4515 rtf = snewn(rtfsize, char);
4516 sprintf(rtf, "{\\rtf1\\ansi%d{\\fonttbl\\f0\\fmodern %s;}\\f0",
4517 GetACP(), cfg.font.name);
4518 rtflen = strlen(rtf);
4521 * We want to construct a piece of RTF that specifies the
4522 * same Unicode text. To do this we will read back in
4523 * parallel from the Unicode data in `udata' and the
4524 * non-Unicode data in `tdata'. For each character in
4525 * `tdata' which becomes the right thing in `udata' when
4526 * looked up in `unitab', we just copy straight over from
4527 * tdata. For each one that doesn't, we must WCToMB it
4528 * individually and produce a \u escape sequence.
4530 * It would probably be more robust to just bite the bullet
4531 * and WCToMB each individual Unicode character one by one,
4532 * then MBToWC each one back to see if it was an accurate
4533 * translation; but that strikes me as a horrifying number
4534 * of Windows API calls so I want to see if this faster way
4535 * will work. If it screws up badly we can always revert to
4536 * the simple and slow way.
4538 while (tindex < len2 && uindex < len &&
4539 tdata[tindex] && udata[uindex]) {
4540 if (tindex + 1 < len2 &&
4541 tdata[tindex] == '\r' &&
4542 tdata[tindex+1] == '\n') {
4546 if (unitab[tdata[tindex]] == udata[uindex]) {
4552 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4553 NULL, 0, NULL, NULL);
4554 if (multilen != 1) {
4555 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4557 alen = 1; strcpy(after, "}");
4559 blen = sprintf(before, "\\u%d", udata[uindex]);
4560 alen = 0; after[0] = '\0';
4563 assert(tindex + multilen <= len2);
4564 totallen = blen + alen;
4565 for (i = 0; i < multilen; i++) {
4566 if (tdata[tindex+i] == '\\' ||
4567 tdata[tindex+i] == '{' ||
4568 tdata[tindex+i] == '}')
4570 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4571 totallen += 6; /* \par\r\n */
4572 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4578 if (rtfsize < rtflen + totallen + 3) {
4579 rtfsize = rtflen + totallen + 512;
4580 rtf = sresize(rtf, rtfsize, char);
4583 strcpy(rtf + rtflen, before); rtflen += blen;
4584 for (i = 0; i < multilen; i++) {
4585 if (tdata[tindex+i] == '\\' ||
4586 tdata[tindex+i] == '{' ||
4587 tdata[tindex+i] == '}') {
4588 rtf[rtflen++] = '\\';
4589 rtf[rtflen++] = tdata[tindex+i];
4590 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4591 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4592 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4593 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4595 rtf[rtflen++] = tdata[tindex+i];
4598 strcpy(rtf + rtflen, after); rtflen += alen;
4604 strcpy(rtf + rtflen, "}");
4607 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4608 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
4610 GlobalUnlock(clipdata3);
4616 GlobalUnlock(clipdata);
4617 GlobalUnlock(clipdata2);
4620 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4622 if (OpenClipboard(hwnd)) {
4624 SetClipboardData(CF_UNICODETEXT, clipdata);
4625 SetClipboardData(CF_TEXT, clipdata2);
4627 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4630 GlobalFree(clipdata);
4631 GlobalFree(clipdata2);
4635 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4638 void get_clip(void *frontend, wchar_t ** p, int *len)
4640 static HGLOBAL clipdata = NULL;
4641 static wchar_t *converted = 0;
4650 GlobalUnlock(clipdata);
4653 } else if (OpenClipboard(NULL)) {
4654 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
4656 *p = GlobalLock(clipdata);
4658 for (p2 = *p; *p2; p2++);
4662 } else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
4666 s = GlobalLock(clipdata);
4667 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
4668 *p = converted = snewn(i, wchar_t);
4669 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
4682 * Move `lines' lines from position `from' to position `to' in the
4685 void optimised_move(void *frontend, int to, int from, int lines)
4690 min = (to < from ? to : from);
4691 max = to + from - min;
4693 r.left = offset_width;
4694 r.right = offset_width + term->cols * font_width;
4695 r.top = offset_height + min * font_height;
4696 r.bottom = offset_height + (max + lines) * font_height;
4697 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
4702 * Print a message box and perform a fatal exit.
4704 void fatalbox(char *fmt, ...)
4707 char *stuff, morestuff[100];
4710 stuff = dupvprintf(fmt, ap);
4712 sprintf(morestuff, "%.70s Fatal Error", appname);
4713 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
4719 * Print a modal (Really Bad) message box and perform a fatal exit.
4721 void modalfatalbox(char *fmt, ...)
4724 char *stuff, morestuff[100];
4727 stuff = dupvprintf(fmt, ap);
4729 sprintf(morestuff, "%.70s Fatal Error", appname);
4730 MessageBox(hwnd, stuff, morestuff,
4731 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
4736 static void flash_window(int mode);
4737 static long next_flash;
4738 static int flashing = 0;
4740 static void flash_window_timer(void *ctx, long now)
4742 if (flashing && now - next_flash >= 0) {
4748 * Manage window caption / taskbar flashing, if enabled.
4749 * 0 = stop, 1 = maintain, 2 = start
4751 static void flash_window(int mode)
4753 if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
4756 FlashWindow(hwnd, FALSE);
4760 } else if (mode == 2) {
4764 FlashWindow(hwnd, TRUE);
4765 next_flash = schedule_timer(450, flash_window_timer, hwnd);
4768 } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
4771 FlashWindow(hwnd, TRUE); /* toggle */
4772 next_flash = schedule_timer(450, flash_window_timer, hwnd);
4780 void beep(void *frontend, int mode)
4782 if (mode == BELL_DEFAULT) {
4784 * For MessageBeep style bells, we want to be careful of
4785 * timing, because they don't have the nice property of
4786 * PlaySound bells that each one cancels the previous
4787 * active one. So we limit the rate to one per 50ms or so.
4789 static long lastbeep = 0;
4792 beepdiff = GetTickCount() - lastbeep;
4793 if (beepdiff >= 0 && beepdiff < 50)
4797 * The above MessageBeep call takes time, so we record the
4798 * time _after_ it finishes rather than before it starts.
4800 lastbeep = GetTickCount();
4801 } else if (mode == BELL_WAVEFILE) {
4802 if (!PlaySound(cfg.bell_wavefile.path, NULL,
4803 SND_ASYNC | SND_FILENAME)) {
4804 char buf[sizeof(cfg.bell_wavefile.path) + 80];
4806 sprintf(buf, "Unable to play sound file\n%s\n"
4807 "Using default sound instead", cfg.bell_wavefile.path);
4808 sprintf(otherbuf, "%.70s Sound Error", appname);
4809 MessageBox(hwnd, buf, otherbuf,
4810 MB_OK | MB_ICONEXCLAMATION);
4811 cfg.beep = BELL_DEFAULT;
4813 } else if (mode == BELL_PCSPEAKER) {
4814 static long lastbeep = 0;
4817 beepdiff = GetTickCount() - lastbeep;
4818 if (beepdiff >= 0 && beepdiff < 50)
4822 * We must beep in different ways depending on whether this
4823 * is a 95-series or NT-series OS.
4825 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
4829 lastbeep = GetTickCount();
4831 /* Otherwise, either visual bell or disabled; do nothing here */
4832 if (!term->has_focus) {
4833 flash_window(2); /* start */
4838 * Minimise or restore the window in response to a server-side
4841 void set_iconic(void *frontend, int iconic)
4843 if (IsIconic(hwnd)) {
4845 ShowWindow(hwnd, SW_RESTORE);
4848 ShowWindow(hwnd, SW_MINIMIZE);
4853 * Move the window in response to a server-side request.
4855 void move_window(void *frontend, int x, int y)
4857 if (cfg.resize_action == RESIZE_DISABLED ||
4858 cfg.resize_action == RESIZE_FONT ||
4862 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
4866 * Move the window to the top or bottom of the z-order in response
4867 * to a server-side request.
4869 void set_zorder(void *frontend, int top)
4871 if (cfg.alwaysontop)
4872 return; /* ignore */
4873 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
4874 SWP_NOMOVE | SWP_NOSIZE);
4878 * Refresh the window in response to a server-side request.
4880 void refresh_window(void *frontend)
4882 InvalidateRect(hwnd, NULL, TRUE);
4886 * Maximise or restore the window in response to a server-side
4889 void set_zoomed(void *frontend, int zoomed)
4891 if (IsZoomed(hwnd)) {
4893 ShowWindow(hwnd, SW_RESTORE);
4896 ShowWindow(hwnd, SW_MAXIMIZE);
4901 * Report whether the window is iconic, for terminal reports.
4903 int is_iconic(void *frontend)
4905 return IsIconic(hwnd);
4909 * Report the window's position, for terminal reports.
4911 void get_window_pos(void *frontend, int *x, int *y)
4914 GetWindowRect(hwnd, &r);
4920 * Report the window's pixel size, for terminal reports.
4922 void get_window_pixels(void *frontend, int *x, int *y)
4925 GetWindowRect(hwnd, &r);
4926 *x = r.right - r.left;
4927 *y = r.bottom - r.top;
4931 * Return the window or icon title.
4933 char *get_window_title(void *frontend, int icon)
4935 return icon ? icon_name : window_name;
4939 * See if we're in full-screen mode.
4941 static int is_full_screen()
4943 if (!IsZoomed(hwnd))
4945 if (GetWindowLong(hwnd, GWL_STYLE) & WS_CAPTION)
4950 /* Get the rect/size of a full screen window using the nearest available
4951 * monitor in multimon systems; default to something sensible if only
4952 * one monitor is present. */
4953 static int get_fullscreen_rect(RECT * ss)
4955 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
4958 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
4959 mi.cbSize = sizeof(mi);
4960 GetMonitorInfo(mon, &mi);
4962 /* structure copy */
4966 /* could also use code like this:
4967 ss->left = ss->top = 0;
4968 ss->right = GetSystemMetrics(SM_CXSCREEN);
4969 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
4971 return GetClientRect(GetDesktopWindow(), ss);
4977 * Go full-screen. This should only be called when we are already
4980 static void make_full_screen()
4985 assert(IsZoomed(hwnd));
4987 if (is_full_screen())
4990 /* Remove the window furniture. */
4991 style = GetWindowLong(hwnd, GWL_STYLE);
4992 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
4993 if (cfg.scrollbar_in_fullscreen)
4994 style |= WS_VSCROLL;
4996 style &= ~WS_VSCROLL;
4997 SetWindowLong(hwnd, GWL_STYLE, style);
4999 /* Resize ourselves to exactly cover the nearest monitor. */
5000 get_fullscreen_rect(&ss);
5001 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5006 /* Tick the menu item in the System menu. */
5007 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
5012 * Clear the full-screen attributes.
5014 static void clear_full_screen()
5016 DWORD oldstyle, style;
5018 /* Reinstate the window furniture. */
5019 style = oldstyle = GetWindowLong(hwnd, GWL_STYLE);
5020 style |= WS_CAPTION | WS_BORDER;
5021 if (cfg.resize_action == RESIZE_DISABLED)
5022 style &= ~WS_THICKFRAME;
5024 style |= WS_THICKFRAME;
5026 style |= WS_VSCROLL;
5028 style &= ~WS_VSCROLL;
5029 if (style != oldstyle) {
5030 SetWindowLong(hwnd, GWL_STYLE, style);
5031 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5032 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5036 /* Untick the menu item in the System menu. */
5037 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
5042 * Toggle full-screen mode.
5044 static void flip_full_screen()
5046 if (is_full_screen()) {
5047 ShowWindow(hwnd, SW_RESTORE);
5048 } else if (IsZoomed(hwnd)) {
5051 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5052 ShowWindow(hwnd, SW_MAXIMIZE);
5056 void frontend_keypress(void *handle)
5059 * Keypress termination in non-Close-On-Exit mode is not
5060 * currently supported in PuTTY proper, because the window
5061 * always has a perfectly good Close button anyway. So we do
5067 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5069 return term_data(term, is_stderr, data, len);
5072 void agent_schedule_callback(void (*callback)(void *, void *, int),
5073 void *callback_ctx, void *data, int len)
5075 struct agent_callback *c = snew(struct agent_callback);
5076 c->callback = callback;
5077 c->callback_ctx = callback_ctx;
5080 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);