2 * window.c - the PuTTY(tel) main program, which runs a PuTTY terminal
3 * emulator and backend in a window.
13 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
21 #define COMPILE_MULTIMON_STUBS
31 /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
32 * wParam are used by Windows, and should be masked off, so we shouldn't
33 * attempt to store information in them. Hence all these identifiers have
34 * the low 4 bits clear. Also, identifiers should < 0xF000. */
36 #define IDM_SHOWLOG 0x0010
37 #define IDM_NEWSESS 0x0020
38 #define IDM_DUPSESS 0x0030
39 #define IDM_RESTART 0x0040
40 #define IDM_RECONF 0x0050
41 #define IDM_CLRSB 0x0060
42 #define IDM_RESET 0x0070
43 #define IDM_HELP 0x0140
44 #define IDM_ABOUT 0x0150
45 #define IDM_SAVEDSESS 0x0160
46 #define IDM_COPYALL 0x0170
47 #define IDM_FULLSCREEN 0x0180
48 #define IDM_PASTE 0x0190
49 #define IDM_SPECIALSEP 0x0200
51 #define IDM_SPECIAL_MIN 0x0400
52 #define IDM_SPECIAL_MAX 0x0800
54 #define IDM_SAVED_MIN 0x1000
55 #define IDM_SAVED_MAX 0x5000
56 #define MENU_SAVED_STEP 16
57 /* Maximum number of sessions on saved-session submenu */
58 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
60 #define WM_IGNORE_CLIP (WM_APP + 2)
61 #define WM_FULLSCR_ON_MAX (WM_APP + 3)
62 #define WM_AGENT_CALLBACK (WM_APP + 4)
64 /* Needed for Chinese support and apparently not always defined. */
66 #define VK_PROCESSKEY 0xE5
69 /* Mouse wheel support. */
71 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
74 #define WHEEL_DELTA 120
77 static Mouse_Button translate_button(Mouse_Button button);
78 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
79 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
80 unsigned char *output);
81 static void cfgtopalette(void);
82 static void systopalette(void);
83 static void init_palette(void);
84 static void init_fonts(int, int);
85 static void another_font(int);
86 static void deinit_fonts(void);
87 static void set_input_locale(HKL);
88 static void update_savedsess_menu(void);
90 static int is_full_screen(void);
91 static void make_full_screen(void);
92 static void clear_full_screen(void);
93 static void flip_full_screen(void);
95 /* Window layout information */
96 static void reset_window(int);
97 static int extra_width, extra_height;
98 static int font_width, font_height, font_dualwidth;
99 static int offset_width, offset_height;
100 static int was_zoomed = 0;
101 static int prev_rows, prev_cols;
103 static void enact_netevent(WPARAM, LPARAM);
104 static void flash_window(int mode);
105 static void sys_cursor_update(void);
106 static int is_shift_pressed(void);
107 static int get_fullscreen_rect(RECT * ss);
109 static int caret_x = -1, caret_y = -1;
111 static int kbd_codepage;
114 static Backend *back;
115 static void *backhandle;
117 static struct unicode_data ucsdata;
118 static int must_close_session, session_closed;
119 static int reconfiguring = FALSE;
121 static const struct telnet_special *specials = NULL;
122 static HMENU specials_menu = NULL;
123 static int n_specials = 0;
125 #define TIMING_TIMER_ID 1234
126 static long timing_next_time;
131 enum { SYSMENU, CTXMENU };
132 static HMENU savedsess_menu;
134 Config cfg; /* exported to windlg.c */
136 static struct sesslist sesslist; /* for saved-session menu */
138 struct agent_callback {
139 void (*callback)(void *, void *, int);
145 #define FONT_NORMAL 0
147 #define FONT_UNDERLINE 2
148 #define FONT_BOLDUND 3
149 #define FONT_WIDE 0x04
150 #define FONT_HIGH 0x08
151 #define FONT_NARROW 0x10
153 #define FONT_OEM 0x20
154 #define FONT_OEMBOLD 0x21
155 #define FONT_OEMUND 0x22
156 #define FONT_OEMBOLDUND 0x23
158 #define FONT_MAXNO 0x2F
160 static HFONT fonts[FONT_MAXNO];
161 static LOGFONT lfont;
162 static int fontflag[FONT_MAXNO];
164 BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT
171 #define NCFGCOLOURS 22
172 #define NEXTCOLOURS 240
173 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
174 static COLORREF colours[NALLCOLOURS];
176 static LPLOGPALETTE logpal;
177 static RGBTRIPLE defpal[NALLCOLOURS];
179 static HBITMAP caretbm;
181 static int dbltime, lasttime, lastact;
182 static Mouse_Button lastbtn;
184 /* this allows xterm-style mouse handling. */
185 static int send_raw_mouse = 0;
186 static int wheel_accumulator = 0;
188 static int busy_status = BUSY_NOT;
190 static char *window_name, *icon_name;
192 static int compose_state = 0;
194 static UINT wm_mousewheel = WM_MOUSEWHEEL;
196 /* Dummy routine, only required in plink. */
197 void ldisc_update(void *frontend, int echo, int edit)
201 char *get_ttymode(void *frontend, const char *mode)
203 return term_get_ttymode(term, mode);
206 static void start_backend(void)
209 char msg[1024], *title;
214 * Select protocol. This is farmed out into a table in a
215 * separate file to enable an ssh-free variant.
218 for (i = 0; backends[i].backend != NULL; i++)
219 if (backends[i].protocol == cfg.protocol) {
220 back = backends[i].backend;
224 char *str = dupprintf("%s Internal Error", appname);
225 MessageBox(NULL, "Unsupported protocol number found",
226 str, MB_OK | MB_ICONEXCLAMATION);
231 error = back->init(NULL, &backhandle, &cfg,
232 cfg.host, cfg.port, &realhost, cfg.tcp_nodelay,
234 back->provide_logctx(backhandle, logctx);
236 char *str = dupprintf("%s Error", appname);
237 sprintf(msg, "Unable to open connection to\n"
238 "%.800s\n" "%s", cfg_dest(&cfg), error);
239 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
243 window_name = icon_name = NULL;
245 title = cfg.wintitle;
247 sprintf(msg, "%s - %s", realhost, appname);
251 set_title(NULL, title);
252 set_icon(NULL, title);
255 * Connect the terminal to the backend for resize purposes.
257 term_provide_resize_fn(term, back->size, backhandle);
260 * Set up a line discipline.
262 ldisc = ldisc_create(&cfg, term, back, backhandle, NULL);
265 * Destroy the Restart Session menu item. (This will return
266 * failure if it's already absent, as it will be the very first
267 * time we call this function. We ignore that, because as long
268 * as the menu item ends up not being there, we don't care
269 * whether it was us who removed it or not!)
271 for (i = 0; i < lenof(popup_menus); i++) {
272 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
275 must_close_session = FALSE;
276 session_closed = FALSE;
279 static void close_session(void)
284 session_closed = TRUE;
285 sprintf(morestuff, "%.70s (inactive)", appname);
286 set_icon(NULL, morestuff);
287 set_title(NULL, morestuff);
294 back->free(backhandle);
297 update_specials_menu(NULL);
301 * Show the Restart Session menu item. Do a precautionary
302 * delete first to ensure we never end up with more than one.
304 for (i = 0; i < lenof(popup_menus); i++) {
305 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
306 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
307 IDM_RESTART, "&Restart Session");
311 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
315 int guess_width, guess_height;
319 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
323 InitCommonControls();
325 /* Ensure a Maximize setting in Explorer doesn't maximise the
331 char *str = dupprintf("%s Fatal Error", appname);
332 MessageBox(NULL, "Windows refuses to report a version",
333 str, MB_OK | MB_ICONEXCLAMATION);
339 * If we're running a version of Windows that doesn't support
340 * WM_MOUSEWHEEL, find out what message number we should be
343 if (osVersion.dwMajorVersion < 4 ||
344 (osVersion.dwMajorVersion == 4 &&
345 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
346 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
351 * Process the command line.
357 default_protocol = be_default_protocol;
358 /* Find the appropriate default port. */
361 default_port = 0; /* illegal */
362 for (i = 0; backends[i].backend != NULL; i++)
363 if (backends[i].protocol == default_protocol) {
364 default_port = backends[i].backend->default_port;
368 cfg.logtype = LGTYP_NONE;
370 do_defaults(NULL, &cfg);
375 * Process a couple of command-line options which are more
376 * easily dealt with before the line is broken up into
377 * words. These are the soon-to-be-defunct @sessionname and
378 * the internal-use-only &sharedmemoryhandle, neither of
379 * which are combined with anything else.
381 while (*p && isspace(*p))
385 while (i > 1 && isspace(p[i - 1]))
388 do_defaults(p + 1, &cfg);
389 if (!cfg_launchable(&cfg) && !do_config()) {
392 } else if (*p == '&') {
394 * An initial & means we've been given a command line
395 * containing the hex value of a HANDLE for a file
396 * mapping object, which we must then extract as a
401 if (sscanf(p + 1, "%p", &filemap) == 1 &&
402 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
403 0, 0, sizeof(Config))) != NULL) {
406 CloseHandle(filemap);
407 } else if (!do_config()) {
412 * Otherwise, break up the command line and deal with
418 split_into_argv(cmdline, &argc, &argv, NULL);
420 for (i = 0; i < argc; i++) {
424 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
427 cmdline_error("option \"%s\" requires an argument", p);
428 } else if (ret == 2) {
429 i++; /* skip next argument */
430 } else if (ret == 1) {
431 continue; /* nothing further needs doing */
432 } else if (!strcmp(p, "-cleanup") ||
433 !strcmp(p, "-cleanup-during-uninstall")) {
435 * `putty -cleanup'. Remove all registry
436 * entries associated with PuTTY, and also find
437 * and delete the random seed file.
440 /* Are we being invoked from an uninstaller? */
441 if (!strcmp(p, "-cleanup-during-uninstall")) {
442 s1 = dupprintf("Remove saved sessions and random seed file?\n"
444 "If you hit Yes, ALL Registry entries associated\n"
445 "with %s will be removed, as well as the\n"
446 "random seed file. THIS PROCESS WILL\n"
447 "DESTROY YOUR SAVED SESSIONS.\n"
448 "(This only affects the currently logged-in user.)\n"
450 "If you hit No, uninstallation will proceed, but\n"
451 "saved sessions etc will be left on the machine.",
453 s2 = dupprintf("%s Uninstallation", appname);
455 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
456 "associated with %s, and will also remove\n"
457 "the random seed file. (This only affects the\n"
458 "currently logged-in user.)\n"
460 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
461 "Are you really sure you want to continue?",
463 s2 = dupprintf("%s Warning", appname);
465 if (message_box(s1, s2,
466 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
467 HELPCTXID(option_cleanup)) == IDYES) {
473 } else if (!strcmp(p, "-pgpfp")) {
476 } else if (*p != '-') {
480 * If we already have a host name, treat
481 * this argument as a port number. NB we
482 * have to treat this as a saved -P
483 * argument, so that it will be deferred
484 * until it's a good moment to run it.
486 int ret = cmdline_process_param("-P", p, 1, &cfg);
488 } else if (!strncmp(q, "telnet:", 7)) {
490 * If the hostname starts with "telnet:",
491 * set the protocol to Telnet and process
492 * the string as a Telnet URL.
497 if (q[0] == '/' && q[1] == '/')
499 cfg.protocol = PROT_TELNET;
501 while (*p && *p != ':' && *p != '/')
510 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
511 cfg.host[sizeof(cfg.host) - 1] = '\0';
515 * Otherwise, treat this argument as a host
518 while (*p && !isspace(*p))
522 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
523 cfg.host[sizeof(cfg.host) - 1] = '\0';
527 cmdline_error("unknown option \"%s\"", p);
532 cmdline_run_saved(&cfg);
534 if (!cfg_launchable(&cfg) && !do_config()) {
539 * Trim leading whitespace off the hostname if it's there.
542 int space = strspn(cfg.host, " \t");
543 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
546 /* See if host is of the form user@host */
547 if (cfg.host[0] != '\0') {
548 char *atsign = strrchr(cfg.host, '@');
549 /* Make sure we're not overflowing the user field */
551 if (atsign - cfg.host < sizeof cfg.username) {
552 strncpy(cfg.username, cfg.host, atsign - cfg.host);
553 cfg.username[atsign - cfg.host] = '\0';
555 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
560 * Trim a colon suffix off the hostname if it's there. In
561 * order to protect IPv6 address literals against this
562 * treatment, we do not do this if there's _more_ than one
566 char *c = strchr(cfg.host, ':');
569 char *d = strchr(c+1, ':');
576 * Remove any remaining whitespace from the hostname.
580 while (cfg.host[p2] != '\0') {
581 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
582 cfg.host[p1] = cfg.host[p2];
591 /* Check for invalid Port number (i.e. zero) */
593 char *str = dupprintf("%s Internal Error", appname);
594 MessageBox(NULL, "Invalid Port Number",
595 str, MB_OK | MB_ICONEXCLAMATION);
602 wndclass.lpfnWndProc = WndProc;
603 wndclass.cbClsExtra = 0;
604 wndclass.cbWndExtra = 0;
605 wndclass.hInstance = inst;
606 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
607 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
608 wndclass.hbrBackground = NULL;
609 wndclass.lpszMenuName = NULL;
610 wndclass.lpszClassName = appname;
612 RegisterClass(&wndclass);
615 memset(&ucsdata, 0, sizeof(ucsdata));
620 * Guess some defaults for the window size. This all gets
621 * updated later, so we don't really care too much. However, we
622 * do want the font width/height guesses to correspond to a
623 * large font rather than a small one...
630 guess_width = extra_width + font_width * cfg.width;
631 guess_height = extra_height + font_height * cfg.height;
634 get_fullscreen_rect(&r);
635 if (guess_width > r.right - r.left)
636 guess_width = r.right - r.left;
637 if (guess_height > r.bottom - r.top)
638 guess_height = r.bottom - r.top;
642 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
645 winmode &= ~(WS_VSCROLL);
646 if (cfg.resize_action == RESIZE_DISABLED)
647 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
649 exwinmode |= WS_EX_TOPMOST;
651 exwinmode |= WS_EX_CLIENTEDGE;
652 hwnd = CreateWindowEx(exwinmode, appname, appname,
653 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
654 guess_width, guess_height,
655 NULL, NULL, inst, NULL);
659 * Initialise the terminal. (We have to do this _after_
660 * creating the window, since the terminal is the first thing
661 * which will call schedule_timer(), which will in turn call
662 * timer_change_notify() which will expect hwnd to exist.)
664 term = term_init(&cfg, &ucsdata, NULL);
665 logctx = log_init(NULL, &cfg);
666 term_provide_logctx(term, logctx);
667 term_size(term, cfg.height, cfg.width, cfg.savelines);
670 * Initialise the fonts, simultaneously correcting the guesses
671 * for font_{width,height}.
676 * Correct the guesses for extra_{width,height}.
680 GetWindowRect(hwnd, &wr);
681 GetClientRect(hwnd, &cr);
682 offset_width = offset_height = cfg.window_border;
683 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
684 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
688 * Resize the window, now we know what size we _really_ want it
691 guess_width = extra_width + font_width * term->cols;
692 guess_height = extra_height + font_height * term->rows;
693 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
694 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
697 * Set up a caret bitmap, with no content.
701 int size = (font_width + 15) / 16 * 2 * font_height;
702 bits = snewn(size, char);
703 memset(bits, 0, size);
704 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
707 CreateCaret(hwnd, caretbm, font_width, font_height);
710 * Initialise the scroll bar.
715 si.cbSize = sizeof(si);
716 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
718 si.nMax = term->rows - 1;
719 si.nPage = term->rows;
721 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
725 * Prepare the mouse handler.
727 lastact = MA_NOTHING;
728 lastbtn = MBT_NOTHING;
729 dbltime = GetDoubleClickTime();
732 * Set up the session-control options on the system menu.
739 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
740 popup_menus[CTXMENU].menu = CreatePopupMenu();
741 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
743 savedsess_menu = CreateMenu();
744 get_sesslist(&sesslist, TRUE);
745 update_savedsess_menu();
747 for (j = 0; j < lenof(popup_menus); j++) {
748 m = popup_menus[j].menu;
750 AppendMenu(m, MF_SEPARATOR, 0, 0);
751 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
752 AppendMenu(m, MF_SEPARATOR, 0, 0);
753 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
754 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
755 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) savedsess_menu,
757 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
758 AppendMenu(m, MF_SEPARATOR, 0, 0);
759 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
760 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
761 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
762 AppendMenu(m, MF_SEPARATOR, 0, 0);
763 AppendMenu(m, (cfg.resize_action == RESIZE_DISABLED) ?
764 MF_GRAYED : MF_ENABLED, IDM_FULLSCREEN, "&Full Screen");
765 AppendMenu(m, MF_SEPARATOR, 0, 0);
767 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
768 str = dupprintf("&About %s", appname);
769 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
777 * Set up the initial input locale.
779 set_input_locale(GetKeyboardLayout(0));
782 * Finally show the window!
784 ShowWindow(hwnd, show);
785 SetForegroundWindow(hwnd);
788 * Set the palette up.
794 term_set_focus(term, GetForegroundWindow() == hwnd);
801 handles = handle_get_events(&nhandles);
803 n = MsgWaitForMultipleObjects(nhandles, handles, FALSE, INFINITE,
806 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
807 handle_got_event(handles[n - WAIT_OBJECT_0]);
809 if (must_close_session)
816 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
817 if (msg.message == WM_QUIT)
818 goto finished; /* two-level break */
820 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
821 DispatchMessage(&msg);
822 /* Send the paste buffer if there's anything to send */
824 /* If there's nothing new in the queue then we can do everything
825 * we've delayed, reading the socket, writing, and repainting
828 if (must_close_session)
832 /* The messages seem unreliable; especially if we're being tricky */
833 term_set_focus(term, GetForegroundWindow() == hwnd);
835 net_pending_errors();
839 cleanup_exit(msg.wParam); /* this doesn't return... */
840 return msg.wParam; /* ... but optimiser doesn't know */
846 void cleanup_exit(int code)
857 if (cfg.protocol == PROT_SSH) {
869 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
871 char *do_select(SOCKET skt, int startup)
876 events = (FD_CONNECT | FD_READ | FD_WRITE |
877 FD_OOB | FD_CLOSE | FD_ACCEPT);
882 return "do_select(): internal error (hwnd==NULL)";
883 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
884 switch (p_WSAGetLastError()) {
886 return "Network is down";
888 return "WSAAsyncSelect(): unknown error";
895 * Refresh the saved-session submenu from `sesslist'.
897 static void update_savedsess_menu(void)
900 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
901 /* skip sesslist.sessions[0] == Default Settings */
903 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
906 AppendMenu(savedsess_menu, MF_ENABLED,
907 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
908 sesslist.sessions[i]);
912 * Update the Special Commands submenu.
914 void update_specials_menu(void *frontend)
920 specials = back->get_specials(backhandle);
925 /* We can't use Windows to provide a stack for submenus, so
926 * here's a lame "stack" that will do for now. */
927 HMENU saved_menu = NULL;
929 new_menu = CreatePopupMenu();
930 for (i = 0; nesting > 0; i++) {
931 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
932 switch (specials[i].code) {
934 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
939 saved_menu = new_menu; /* XXX lame stacking */
940 new_menu = CreatePopupMenu();
941 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
942 (UINT) new_menu, specials[i].name);
947 new_menu = saved_menu; /* XXX lame stacking */
952 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
957 /* Squirrel the highest special. */
964 for (j = 0; j < lenof(popup_menus); j++) {
966 /* XXX does this free up all submenus? */
967 DeleteMenu(popup_menus[j].menu, specials_menu, MF_BYCOMMAND);
968 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
971 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
972 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
973 (UINT) new_menu, "S&pecial Command");
974 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
975 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
978 specials_menu = new_menu;
981 static void update_mouse_pointer(void)
984 int force_visible = FALSE;
985 static int forced_visible = FALSE;
986 switch (busy_status) {
989 curstype = IDC_ARROW;
991 curstype = IDC_IBEAM;
994 curstype = IDC_APPSTARTING; /* this may be an abuse */
995 force_visible = TRUE;
999 force_visible = TRUE;
1005 HCURSOR cursor = LoadCursor(NULL, curstype);
1006 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1007 SetCursor(cursor); /* force redraw of cursor at current posn */
1009 if (force_visible != forced_visible) {
1010 /* We want some cursor shapes to be visible always.
1011 * Along with show_mouseptr(), this manages the ShowCursor()
1012 * counter such that if we switch back to a non-force_visible
1013 * cursor, the previous visibility state is restored. */
1014 ShowCursor(force_visible);
1015 forced_visible = force_visible;
1019 void set_busy_status(void *frontend, int status)
1021 busy_status = status;
1022 update_mouse_pointer();
1026 * set or clear the "raw mouse message" mode
1028 void set_raw_mouse_mode(void *frontend, int activate)
1030 activate = activate && !cfg.no_mouse_rep;
1031 send_raw_mouse = activate;
1032 update_mouse_pointer();
1036 * Print a message box and close the connection.
1038 void connection_fatal(void *frontend, char *fmt, ...)
1041 char *stuff, morestuff[100];
1044 stuff = dupvprintf(fmt, ap);
1046 sprintf(morestuff, "%.70s Fatal Error", appname);
1047 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1050 if (cfg.close_on_exit == FORCE_ON)
1053 must_close_session = TRUE;
1058 * Report an error at the command-line parsing stage.
1060 void cmdline_error(char *fmt, ...)
1063 char *stuff, morestuff[100];
1066 stuff = dupvprintf(fmt, ap);
1068 sprintf(morestuff, "%.70s Command Line Error", appname);
1069 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1075 * Actually do the job requested by a WM_NETEVENT
1077 static void enact_netevent(WPARAM wParam, LPARAM lParam)
1079 static int reentering = 0;
1080 extern int select_result(WPARAM, LPARAM);
1083 return; /* don't unpend the pending */
1086 select_result(wParam, lParam);
1091 * Copy the colour palette from the configuration data into defpal.
1092 * This is non-trivial because the colour indices are different.
1094 static void cfgtopalette(void)
1097 static const int ww[] = {
1098 256, 257, 258, 259, 260, 261,
1099 0, 8, 1, 9, 2, 10, 3, 11,
1100 4, 12, 5, 13, 6, 14, 7, 15
1103 for (i = 0; i < 22; i++) {
1105 defpal[w].rgbtRed = cfg.colours[i][0];
1106 defpal[w].rgbtGreen = cfg.colours[i][1];
1107 defpal[w].rgbtBlue = cfg.colours[i][2];
1109 for (i = 0; i < NEXTCOLOURS; i++) {
1111 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1112 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1113 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1114 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
1116 int shade = i - 216;
1117 shade = shade * 10 + 8;
1118 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1119 defpal[i+16].rgbtBlue = shade;
1123 /* Override with system colours if appropriate */
1124 if (cfg.system_colour)
1129 * Override bit of defpal with colours from the system.
1130 * (NB that this takes a copy the system colours at the time this is called,
1131 * so subsequent colour scheme changes don't take effect. To fix that we'd
1132 * probably want to be using GetSysColorBrush() and the like.)
1134 static void systopalette(void)
1137 static const struct { int nIndex; int norm; int bold; } or[] =
1139 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1140 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1141 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1142 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1145 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1146 COLORREF colour = GetSysColor(or[i].nIndex);
1147 defpal[or[i].norm].rgbtRed =
1148 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1149 defpal[or[i].norm].rgbtGreen =
1150 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1151 defpal[or[i].norm].rgbtBlue =
1152 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1157 * Set up the colour palette.
1159 static void init_palette(void)
1162 HDC hdc = GetDC(hwnd);
1164 if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1166 * This is a genuine case where we must use smalloc
1167 * because the snew macros can't cope.
1169 logpal = smalloc(sizeof(*logpal)
1170 - sizeof(logpal->palPalEntry)
1171 + NALLCOLOURS * sizeof(PALETTEENTRY));
1172 logpal->palVersion = 0x300;
1173 logpal->palNumEntries = NALLCOLOURS;
1174 for (i = 0; i < NALLCOLOURS; i++) {
1175 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1176 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1177 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1178 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1180 pal = CreatePalette(logpal);
1182 SelectPalette(hdc, pal, FALSE);
1183 RealizePalette(hdc);
1184 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1187 ReleaseDC(hwnd, hdc);
1190 for (i = 0; i < NALLCOLOURS; i++)
1191 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1192 defpal[i].rgbtGreen,
1193 defpal[i].rgbtBlue);
1195 for (i = 0; i < NALLCOLOURS; i++)
1196 colours[i] = RGB(defpal[i].rgbtRed,
1197 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1201 * This is a wrapper to ExtTextOut() to force Windows to display
1202 * the precise glyphs we give it. Otherwise it would do its own
1203 * bidi and Arabic shaping, and we would end up uncertain which
1204 * characters it had put where.
1206 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1207 unsigned short *lpString, UINT cbCount,
1208 CONST INT *lpDx, int opaque)
1212 * The LCC include files apparently don't supply the
1213 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1214 * proper: the differences aren't important to us (the only
1215 * variable-width string parameter is one we don't use anyway).
1221 char *buffer = snewn(cbCount*2+2, char);
1222 char *classbuffer = snewn(cbCount, char);
1223 memset(&gcpr, 0, sizeof(gcpr));
1224 memset(buffer, 0, cbCount*2+2);
1225 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1227 gcpr.lStructSize = sizeof(gcpr);
1228 gcpr.lpGlyphs = (void *)buffer;
1229 gcpr.lpClass = classbuffer;
1230 gcpr.nGlyphs = cbCount;
1232 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1233 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1235 ExtTextOut(hdc, x, y,
1236 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1237 lprc, buffer, cbCount, lpDx);
1241 * The exact_textout() wrapper, unfortunately, destroys the useful
1242 * Windows `font linking' behaviour: automatic handling of Unicode
1243 * code points not supported in this font by falling back to a font
1244 * which does contain them. Therefore, we adopt a multi-layered
1245 * approach: for any potentially-bidi text, we use exact_textout(),
1246 * and for everything else we use a simple ExtTextOut as we did
1247 * before exact_textout() was introduced.
1249 static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1250 unsigned short *lpString, UINT cbCount,
1251 CONST INT *lpDx, int opaque)
1256 #ifdef FIXME_REMOVE_BEFORE_CHECKIN
1258 debug(("general_textout: %d,%d", x, y));
1259 for(k=0;k<cbCount;k++)debug((" U+%04X", lpString[k]));
1260 debug(("\n rect: [%d,%d %d,%d]", lprc->left, lprc->top, lprc->right, lprc->bottom));
1266 for (i = 0; i < cbCount ;) {
1267 int rtl = is_rtl(lpString[i]);
1271 for (j = i+1; j < cbCount; j++) {
1272 if (rtl != is_rtl(lpString[j]))
1278 * Now [i,j) indicates a maximal substring of lpString
1279 * which should be displayed using the same textout
1283 newrc.left = lprc->left + xp - x;
1284 newrc.right = lprc->left + xn - x;
1285 newrc.top = lprc->top;
1286 newrc.bottom = lprc->bottom;
1287 #ifdef FIXME_REMOVE_BEFORE_CHECKIN
1290 debug((" exact_textout: %d,%d", xp, y));
1291 for(k=0;k<j-i;k++)debug((" U+%04X", lpString[i+k]));
1292 debug(("\n rect: [%d,%d %d,%d]\n", newrc.left, newrc.top, newrc.right, newrc.bottom));
1295 exact_textout(hdc, xp, y, &newrc, lpString+i, j-i, lpDx+i, opaque);
1297 #ifdef FIXME_REMOVE_BEFORE_CHECKIN
1300 debug((" ExtTextOut : %d,%d", xp, y));
1301 for(k=0;k<j-i;k++)debug((" U+%04X", lpString[i+k]));
1302 debug(("\n rect: [%d,%d %d,%d]\n", newrc.left, newrc.top, newrc.right, newrc.bottom));
1305 newrc.left = lprc->left + xp - x;
1306 newrc.right = lprc->left + xn - x;
1307 newrc.top = lprc->top;
1308 newrc.bottom = lprc->bottom;
1309 ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1310 &newrc, lpString+i, j-i, lpDx+i);
1317 #ifdef FIXME_REMOVE_BEFORE_CHECKIN
1318 debug(("general_textout: done, xn=%d\n", xn));
1320 assert(xn - x == lprc->right - lprc->left);
1324 * Initialise all the fonts we will need initially. There may be as many as
1325 * three or as few as one. The other (poentially) twentyone fonts are done
1326 * if/when they are needed.
1330 * - check the font width and height, correcting our guesses if
1333 * - verify that the bold font is the same width as the ordinary
1334 * one, and engage shadow bolding if not.
1336 * - verify that the underlined font is the same width as the
1337 * ordinary one (manual underlining by means of line drawing can
1338 * be done in a pinch).
1340 static void init_fonts(int pick_width, int pick_height)
1347 int fw_dontcare, fw_bold;
1349 for (i = 0; i < FONT_MAXNO; i++)
1352 bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
1353 und_mode = UND_FONT;
1355 if (cfg.font.isbold) {
1356 fw_dontcare = FW_BOLD;
1359 fw_dontcare = FW_DONTCARE;
1366 font_height = pick_height;
1368 font_height = cfg.font.height;
1369 if (font_height > 0) {
1371 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1374 font_width = pick_width;
1376 #define f(i,c,w,u) \
1377 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1378 c, OUT_DEFAULT_PRECIS, \
1379 CLIP_DEFAULT_PRECIS, FONT_QUALITY(cfg.font_quality), \
1380 FIXED_PITCH | FF_DONTCARE, cfg.font.name)
1382 f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);
1384 SelectObject(hdc, fonts[FONT_NORMAL]);
1385 GetTextMetrics(hdc, &tm);
1387 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1389 if (pick_width == 0 || pick_height == 0) {
1390 font_height = tm.tmHeight;
1391 font_width = tm.tmAveCharWidth;
1393 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1395 #ifdef RDB_DEBUG_PATCH
1396 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1397 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1402 DWORD cset = tm.tmCharSet;
1403 memset(&info, 0xFF, sizeof(info));
1405 /* !!! Yes the next line is right */
1406 if (cset == OEM_CHARSET)
1407 ucsdata.font_codepage = GetOEMCP();
1409 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1410 ucsdata.font_codepage = info.ciACP;
1412 ucsdata.font_codepage = -1;
1414 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1415 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1418 f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);
1421 * Some fonts, e.g. 9-pt Courier, draw their underlines
1422 * outside their character cell. We successfully prevent
1423 * screen corruption by clipping the text output, but then
1424 * we lose the underline completely. Here we try to work
1425 * out whether this is such a font, and if it is, we set a
1426 * flag that causes underlines to be drawn by hand.
1428 * Having tried other more sophisticated approaches (such
1429 * as examining the TEXTMETRIC structure or requesting the
1430 * height of a string), I think we'll do this the brute
1431 * force way: we create a small bitmap, draw an underlined
1432 * space on it, and test to see whether any pixels are
1433 * foreground-coloured. (Since we expect the underline to
1434 * go all the way across the character cell, we only search
1435 * down a single column of the bitmap, half way across.)
1439 HBITMAP und_bm, und_oldbm;
1443 und_dc = CreateCompatibleDC(hdc);
1444 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1445 und_oldbm = SelectObject(und_dc, und_bm);
1446 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1447 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1448 SetTextColor(und_dc, RGB(255, 255, 255));
1449 SetBkColor(und_dc, RGB(0, 0, 0));
1450 SetBkMode(und_dc, OPAQUE);
1451 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1453 for (i = 0; i < font_height; i++) {
1454 c = GetPixel(und_dc, font_width / 2, i);
1455 if (c != RGB(0, 0, 0))
1458 SelectObject(und_dc, und_oldbm);
1459 DeleteObject(und_bm);
1462 und_mode = UND_LINE;
1463 DeleteObject(fonts[FONT_UNDERLINE]);
1464 fonts[FONT_UNDERLINE] = 0;
1468 if (bold_mode == BOLD_FONT) {
1469 f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);
1473 descent = tm.tmAscent + 1;
1474 if (descent >= font_height)
1475 descent = font_height - 1;
1477 for (i = 0; i < 3; i++) {
1479 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1480 fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
1487 ReleaseDC(hwnd, hdc);
1489 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1490 und_mode = UND_LINE;
1491 DeleteObject(fonts[FONT_UNDERLINE]);
1492 fonts[FONT_UNDERLINE] = 0;
1495 if (bold_mode == BOLD_FONT &&
1496 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1497 bold_mode = BOLD_SHADOW;
1498 DeleteObject(fonts[FONT_BOLD]);
1499 fonts[FONT_BOLD] = 0;
1501 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1503 init_ucs(&cfg, &ucsdata);
1506 static void another_font(int fontno)
1509 int fw_dontcare, fw_bold;
1513 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1516 basefont = (fontno & ~(FONT_BOLDUND));
1517 if (basefont != fontno && !fontflag[basefont])
1518 another_font(basefont);
1520 if (cfg.font.isbold) {
1521 fw_dontcare = FW_BOLD;
1524 fw_dontcare = FW_DONTCARE;
1528 c = cfg.font.charset;
1534 if (fontno & FONT_WIDE)
1536 if (fontno & FONT_NARROW)
1538 if (fontno & FONT_OEM)
1540 if (fontno & FONT_BOLD)
1542 if (fontno & FONT_UNDERLINE)
1546 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1547 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1548 CLIP_DEFAULT_PRECIS, FONT_QUALITY(cfg.font_quality),
1549 FIXED_PITCH | FF_DONTCARE, s);
1551 fontflag[fontno] = 1;
1554 static void deinit_fonts(void)
1557 for (i = 0; i < FONT_MAXNO; i++) {
1559 DeleteObject(fonts[i]);
1565 void request_resize(void *frontend, int w, int h)
1569 /* If the window is maximized supress resizing attempts */
1570 if (IsZoomed(hwnd)) {
1571 if (cfg.resize_action == RESIZE_TERM)
1575 if (cfg.resize_action == RESIZE_DISABLED) return;
1576 if (h == term->rows && w == term->cols) return;
1578 /* Sanity checks ... */
1580 static int first_time = 1;
1583 switch (first_time) {
1585 /* Get the size of the screen */
1586 if (get_fullscreen_rect(&ss))
1587 /* first_time = 0 */ ;
1593 /* Make sure the values are sane */
1594 width = (ss.right - ss.left - extra_width) / 4;
1595 height = (ss.bottom - ss.top - extra_height) / 6;
1597 if (w > width || h > height)
1606 term_size(term, h, w, cfg.savelines);
1608 if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {
1609 width = extra_width + font_width * w;
1610 height = extra_height + font_height * h;
1612 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1613 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1614 SWP_NOMOVE | SWP_NOZORDER);
1618 InvalidateRect(hwnd, NULL, TRUE);
1621 static void reset_window(int reinit) {
1623 * This function decides how to resize or redraw when the
1624 * user changes something.
1626 * This function doesn't like to change the terminal size but if the
1627 * font size is locked that may be it's only soluion.
1629 int win_width, win_height;
1632 #ifdef RDB_DEBUG_PATCH
1633 debug((27, "reset_window()"));
1636 /* Current window sizes ... */
1637 GetWindowRect(hwnd, &wr);
1638 GetClientRect(hwnd, &cr);
1640 win_width = cr.right - cr.left;
1641 win_height = cr.bottom - cr.top;
1643 if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;
1645 /* Are we being forced to reload the fonts ? */
1647 #ifdef RDB_DEBUG_PATCH
1648 debug((27, "reset_window() -- Forced deinit"));
1654 /* Oh, looks like we're minimised */
1655 if (win_width == 0 || win_height == 0)
1658 /* Is the window out of position ? */
1660 (offset_width != (win_width-font_width*term->cols)/2 ||
1661 offset_height != (win_height-font_height*term->rows)/2) ){
1662 offset_width = (win_width-font_width*term->cols)/2;
1663 offset_height = (win_height-font_height*term->rows)/2;
1664 InvalidateRect(hwnd, NULL, TRUE);
1665 #ifdef RDB_DEBUG_PATCH
1666 debug((27, "reset_window() -> Reposition terminal"));
1670 if (IsZoomed(hwnd)) {
1671 /* We're fullscreen, this means we must not change the size of
1672 * the window so it's the font size or the terminal itself.
1675 extra_width = wr.right - wr.left - cr.right + cr.left;
1676 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1678 if (cfg.resize_action != RESIZE_TERM) {
1679 if ( font_width != win_width/term->cols ||
1680 font_height != win_height/term->rows) {
1682 init_fonts(win_width/term->cols, win_height/term->rows);
1683 offset_width = (win_width-font_width*term->cols)/2;
1684 offset_height = (win_height-font_height*term->rows)/2;
1685 InvalidateRect(hwnd, NULL, TRUE);
1686 #ifdef RDB_DEBUG_PATCH
1687 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1688 font_width, font_height));
1692 if ( font_width * term->cols != win_width ||
1693 font_height * term->rows != win_height) {
1694 /* Our only choice at this point is to change the
1695 * size of the terminal; Oh well.
1697 term_size(term, win_height/font_height, win_width/font_width,
1699 offset_width = (win_width-font_width*term->cols)/2;
1700 offset_height = (win_height-font_height*term->rows)/2;
1701 InvalidateRect(hwnd, NULL, TRUE);
1702 #ifdef RDB_DEBUG_PATCH
1703 debug((27, "reset_window() -> Zoomed term_size"));
1710 /* Hmm, a force re-init means we should ignore the current window
1711 * so we resize to the default font size.
1714 #ifdef RDB_DEBUG_PATCH
1715 debug((27, "reset_window() -> Forced re-init"));
1718 offset_width = offset_height = cfg.window_border;
1719 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1720 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1722 if (win_width != font_width*term->cols + offset_width*2 ||
1723 win_height != font_height*term->rows + offset_height*2) {
1725 /* If this is too large windows will resize it to the maximum
1726 * allowed window size, we will then be back in here and resize
1727 * the font or terminal to fit.
1729 SetWindowPos(hwnd, NULL, 0, 0,
1730 font_width*term->cols + extra_width,
1731 font_height*term->rows + extra_height,
1732 SWP_NOMOVE | SWP_NOZORDER);
1735 InvalidateRect(hwnd, NULL, TRUE);
1739 /* Okay the user doesn't want us to change the font so we try the
1740 * window. But that may be too big for the screen which forces us
1741 * to change the terminal.
1743 if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||
1744 (cfg.resize_action == RESIZE_EITHER && reinit<0) ||
1746 offset_width = offset_height = cfg.window_border;
1747 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1748 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1750 if (win_width != font_width*term->cols + offset_width*2 ||
1751 win_height != font_height*term->rows + offset_height*2) {
1756 get_fullscreen_rect(&ss);
1758 width = (ss.right - ss.left - extra_width) / font_width;
1759 height = (ss.bottom - ss.top - extra_height) / font_height;
1762 if ( term->rows > height || term->cols > width ) {
1763 if (cfg.resize_action == RESIZE_EITHER) {
1764 /* Make the font the biggest we can */
1765 if (term->cols > width)
1766 font_width = (ss.right - ss.left - extra_width)
1768 if (term->rows > height)
1769 font_height = (ss.bottom - ss.top - extra_height)
1773 init_fonts(font_width, font_height);
1775 width = (ss.right - ss.left - extra_width) / font_width;
1776 height = (ss.bottom - ss.top - extra_height) / font_height;
1778 if ( height > term->rows ) height = term->rows;
1779 if ( width > term->cols ) width = term->cols;
1780 term_size(term, height, width, cfg.savelines);
1781 #ifdef RDB_DEBUG_PATCH
1782 debug((27, "reset_window() -> term resize to (%d,%d)",
1788 SetWindowPos(hwnd, NULL, 0, 0,
1789 font_width*term->cols + extra_width,
1790 font_height*term->rows + extra_height,
1791 SWP_NOMOVE | SWP_NOZORDER);
1793 InvalidateRect(hwnd, NULL, TRUE);
1794 #ifdef RDB_DEBUG_PATCH
1795 debug((27, "reset_window() -> window resize to (%d,%d)",
1796 font_width*term->cols + extra_width,
1797 font_height*term->rows + extra_height));
1803 /* We're allowed to or must change the font but do we want to ? */
1805 if (font_width != (win_width-cfg.window_border*2)/term->cols ||
1806 font_height != (win_height-cfg.window_border*2)/term->rows) {
1809 init_fonts((win_width-cfg.window_border*2)/term->cols,
1810 (win_height-cfg.window_border*2)/term->rows);
1811 offset_width = (win_width-font_width*term->cols)/2;
1812 offset_height = (win_height-font_height*term->rows)/2;
1814 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1815 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1817 InvalidateRect(hwnd, NULL, TRUE);
1818 #ifdef RDB_DEBUG_PATCH
1819 debug((25, "reset_window() -> font resize to (%d,%d)",
1820 font_width, font_height));
1825 static void set_input_locale(HKL kl)
1829 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1830 lbuf, sizeof(lbuf));
1832 kbd_codepage = atoi(lbuf);
1835 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1837 int thistime = GetMessageTime();
1839 if (send_raw_mouse && !(cfg.mouse_override && shift)) {
1840 lastbtn = MBT_NOTHING;
1841 term_mouse(term, b, translate_button(b), MA_CLICK,
1842 x, y, shift, ctrl, alt);
1846 if (lastbtn == b && thistime - lasttime < dbltime) {
1847 lastact = (lastact == MA_CLICK ? MA_2CLK :
1848 lastact == MA_2CLK ? MA_3CLK :
1849 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1854 if (lastact != MA_NOTHING)
1855 term_mouse(term, b, translate_button(b), lastact,
1856 x, y, shift, ctrl, alt);
1857 lasttime = thistime;
1861 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1862 * into a cooked one (SELECT, EXTEND, PASTE).
1864 static Mouse_Button translate_button(Mouse_Button button)
1866 if (button == MBT_LEFT)
1868 if (button == MBT_MIDDLE)
1869 return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
1870 if (button == MBT_RIGHT)
1871 return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
1872 return 0; /* shouldn't happen */
1875 static void show_mouseptr(int show)
1877 /* NB that the counter in ShowCursor() is also frobbed by
1878 * update_mouse_pointer() */
1879 static int cursor_visible = 1;
1880 if (!cfg.hide_mouseptr) /* override if this feature disabled */
1882 if (cursor_visible && !show)
1884 else if (!cursor_visible && show)
1886 cursor_visible = show;
1889 static int is_alt_pressed(void)
1892 int r = GetKeyboardState(keystate);
1895 if (keystate[VK_MENU] & 0x80)
1897 if (keystate[VK_RMENU] & 0x80)
1902 static int is_shift_pressed(void)
1905 int r = GetKeyboardState(keystate);
1908 if (keystate[VK_SHIFT] & 0x80)
1913 static int resizing;
1915 void notify_remote_exit(void *fe)
1919 if (!session_closed &&
1920 (exitcode = back->exitcode(backhandle)) >= 0) {
1921 /* Abnormal exits will already have set session_closed and taken
1922 * appropriate action. */
1923 if (cfg.close_on_exit == FORCE_ON ||
1924 (cfg.close_on_exit == AUTO && exitcode != INT_MAX)) {
1927 must_close_session = TRUE;
1928 session_closed = TRUE;
1929 /* exitcode == INT_MAX indicates that the connection was closed
1930 * by a fatal error, so an error box will be coming our way and
1931 * we should not generate this informational one. */
1932 if (exitcode != INT_MAX)
1933 MessageBox(hwnd, "Connection closed by remote host",
1934 appname, MB_OK | MB_ICONINFORMATION);
1939 void timer_change_notify(long next)
1941 long ticks = next - GETTICKCOUNT();
1942 if (ticks <= 0) ticks = 1; /* just in case */
1943 KillTimer(hwnd, TIMING_TIMER_ID);
1944 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
1945 timing_next_time = next;
1948 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1949 WPARAM wParam, LPARAM lParam)
1952 static int ignore_clip = FALSE;
1953 static int need_backend_resize = FALSE;
1954 static int fullscr_on_max = FALSE;
1955 static UINT last_mousemove = 0;
1959 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
1962 KillTimer(hwnd, TIMING_TIMER_ID);
1963 if (run_timers(timing_next_time, &next)) {
1964 timer_change_notify(next);
1975 str = dupprintf("%s Exit Confirmation", appname);
1976 if (!cfg.warn_on_close || session_closed ||
1978 "Are you sure you want to close this session?",
1979 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
1981 DestroyWindow(hwnd);
1989 case WM_INITMENUPOPUP:
1990 if ((HMENU)wParam == savedsess_menu) {
1991 /* About to pop up Saved Sessions sub-menu.
1992 * Refresh the session list. */
1993 get_sesslist(&sesslist, FALSE); /* free */
1994 get_sesslist(&sesslist, TRUE);
1995 update_savedsess_menu();
2001 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
2012 BOOL inherit_handles;
2014 PROCESS_INFORMATION pi;
2015 HANDLE filemap = NULL;
2017 if (wParam == IDM_DUPSESS) {
2019 * Allocate a file-mapping memory chunk for the
2022 SECURITY_ATTRIBUTES sa;
2025 sa.nLength = sizeof(sa);
2026 sa.lpSecurityDescriptor = NULL;
2027 sa.bInheritHandle = TRUE;
2028 filemap = CreateFileMapping(INVALID_HANDLE_VALUE,
2031 0, sizeof(Config), NULL);
2032 if (filemap && filemap != INVALID_HANDLE_VALUE) {
2033 p = (Config *) MapViewOfFile(filemap,
2035 0, 0, sizeof(Config));
2037 *p = cfg; /* structure copy */
2041 inherit_handles = TRUE;
2042 sprintf(c, "putty &%p", filemap);
2044 } else if (wParam == IDM_SAVEDSESS) {
2045 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
2046 / MENU_SAVED_STEP) + 1;
2047 if (sessno < sesslist.nsessions) {
2048 char *session = sesslist.sessions[sessno];
2049 /* XXX spaces? quotes? "-load"? */
2050 cl = dupprintf("putty @%s", session);
2051 inherit_handles = FALSE;
2055 } else /* IDM_NEWSESS */ {
2057 inherit_handles = FALSE;
2060 GetModuleFileName(NULL, b, sizeof(b) - 1);
2062 si.lpReserved = NULL;
2063 si.lpDesktop = NULL;
2067 si.lpReserved2 = NULL;
2068 CreateProcess(b, cl, NULL, NULL, inherit_handles,
2069 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
2072 CloseHandle(filemap);
2079 logevent(NULL, "----- Session restarted -----");
2080 term_pwron(term, FALSE);
2089 int reconfig_result;
2094 reconfiguring = TRUE;
2096 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
2100 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2101 reconfiguring = FALSE;
2102 if (!reconfig_result)
2106 /* Disable full-screen if resizing forbidden */
2107 HMENU m = GetSystemMenu (hwnd, FALSE);
2108 EnableMenuItem(m, IDM_FULLSCREEN, MF_BYCOMMAND |
2109 (cfg.resize_action == RESIZE_DISABLED)
2110 ? MF_GRAYED : MF_ENABLED);
2111 /* Gracefully unzoom if necessary */
2112 if (IsZoomed(hwnd) &&
2113 (cfg.resize_action == RESIZE_DISABLED)) {
2114 ShowWindow(hwnd, SW_RESTORE);
2118 /* Pass new config data to the logging module */
2119 log_reconfig(logctx, &cfg);
2123 * Flush the line discipline's edit buffer in the
2124 * case where local editing has just been disabled.
2127 ldisc_send(ldisc, NULL, 0, 0);
2135 /* Pass new config data to the terminal */
2136 term_reconfig(term, &cfg);
2138 /* Pass new config data to the back end */
2140 back->reconfig(backhandle, &cfg);
2142 /* Screen size changed ? */
2143 if (cfg.height != prev_cfg.height ||
2144 cfg.width != prev_cfg.width ||
2145 cfg.savelines != prev_cfg.savelines ||
2146 cfg.resize_action == RESIZE_FONT ||
2147 (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2148 cfg.resize_action == RESIZE_DISABLED)
2149 term_size(term, cfg.height, cfg.width, cfg.savelines);
2151 /* Enable or disable the scroll bar, etc */
2153 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2154 LONG nexflag, exflag =
2155 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2158 if (cfg.alwaysontop != prev_cfg.alwaysontop) {
2159 if (cfg.alwaysontop) {
2160 nexflag |= WS_EX_TOPMOST;
2161 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2162 SWP_NOMOVE | SWP_NOSIZE);
2164 nexflag &= ~(WS_EX_TOPMOST);
2165 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2166 SWP_NOMOVE | SWP_NOSIZE);
2169 if (cfg.sunken_edge)
2170 nexflag |= WS_EX_CLIENTEDGE;
2172 nexflag &= ~(WS_EX_CLIENTEDGE);
2175 if (is_full_screen() ?
2176 cfg.scrollbar_in_fullscreen : cfg.scrollbar)
2179 nflg &= ~WS_VSCROLL;
2181 if (cfg.resize_action == RESIZE_DISABLED ||
2183 nflg &= ~WS_THICKFRAME;
2185 nflg |= WS_THICKFRAME;
2187 if (cfg.resize_action == RESIZE_DISABLED)
2188 nflg &= ~WS_MAXIMIZEBOX;
2190 nflg |= WS_MAXIMIZEBOX;
2192 if (nflg != flag || nexflag != exflag) {
2194 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2195 if (nexflag != exflag)
2196 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2198 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2199 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2200 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2208 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2213 set_title(NULL, cfg.wintitle);
2214 if (IsIconic(hwnd)) {
2216 cfg.win_name_always ? window_name :
2220 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
2221 strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
2222 cfg.font.isbold != prev_cfg.font.isbold ||
2223 cfg.font.height != prev_cfg.font.height ||
2224 cfg.font.charset != prev_cfg.font.charset ||
2225 cfg.font_quality != prev_cfg.font_quality ||
2226 cfg.vtmode != prev_cfg.vtmode ||
2227 cfg.bold_colour != prev_cfg.bold_colour ||
2228 cfg.resize_action == RESIZE_DISABLED ||
2229 cfg.resize_action == RESIZE_EITHER ||
2230 (cfg.resize_action != prev_cfg.resize_action))
2233 InvalidateRect(hwnd, NULL, TRUE);
2234 reset_window(init_lvl);
2235 net_pending_errors();
2242 term_do_paste(term);
2248 term_pwron(term, TRUE);
2250 ldisc_send(ldisc, NULL, 0, 0);
2256 launch_help(hwnd, NULL);
2260 * We get this if the System menu has been activated
2267 * We get this if the System menu has been activated
2268 * using the keyboard. This might happen from within
2269 * TranslateKey, in which case it really wants to be
2270 * followed by a `space' character to actually _bring
2271 * the menu up_ rather than just sitting there in
2272 * `ready to appear' state.
2274 show_mouseptr(1); /* make sure pointer is visible */
2276 PostMessage(hwnd, WM_CHAR, ' ', 0);
2278 case IDM_FULLSCREEN:
2282 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2283 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2285 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2286 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2288 * Ensure we haven't been sent a bogus SYSCOMMAND
2289 * which would cause us to reference invalid memory
2290 * and crash. Perhaps I'm just too paranoid here.
2292 if (i >= n_specials)
2295 back->special(backhandle, specials[i].code);
2296 net_pending_errors();
2301 #define X_POS(l) ((int)(short)LOWORD(l))
2302 #define Y_POS(l) ((int)(short)HIWORD(l))
2304 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2305 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2306 case WM_LBUTTONDOWN:
2307 case WM_MBUTTONDOWN:
2308 case WM_RBUTTONDOWN:
2312 if (message == WM_RBUTTONDOWN &&
2313 ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
2316 show_mouseptr(1); /* make sure pointer is visible */
2317 GetCursorPos(&cursorpos);
2318 TrackPopupMenu(popup_menus[CTXMENU].menu,
2319 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2320 cursorpos.x, cursorpos.y,
2328 case WM_LBUTTONDOWN:
2332 case WM_MBUTTONDOWN:
2333 button = MBT_MIDDLE;
2336 case WM_RBUTTONDOWN:
2345 button = MBT_MIDDLE;
2353 button = press = 0; /* shouldn't happen */
2357 * Special case: in full-screen mode, if the left
2358 * button is clicked in the very top left corner of the
2359 * window, we put up the System menu instead of doing
2363 char mouse_on_hotspot = 0;
2372 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2375 mi.cbSize = sizeof(MONITORINFO);
2376 GetMonitorInfo(mon, &mi);
2378 if (mi.rcMonitor.left == pt.x &&
2379 mi.rcMonitor.top == pt.y) {
2380 mouse_on_hotspot = 1;
2385 if (pt.x == 0 && pt.y == 0) {
2386 mouse_on_hotspot = 1;
2389 if (is_full_screen() && press &&
2390 button == MBT_LEFT && mouse_on_hotspot) {
2391 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2392 MAKELPARAM(pt.x, pt.y));
2399 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2400 wParam & MK_SHIFT, wParam & MK_CONTROL,
2404 term_mouse(term, button, translate_button(button), MA_RELEASE,
2405 TO_CHR_X(X_POS(lParam)),
2406 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2407 wParam & MK_CONTROL, is_alt_pressed());
2415 * Windows seems to like to occasionally send MOUSEMOVE
2416 * events even if the mouse hasn't moved. Don't unhide
2417 * the mouse pointer in this case.
2419 static WPARAM wp = 0;
2420 static LPARAM lp = 0;
2421 if (wParam != wp || lParam != lp ||
2422 last_mousemove != WM_MOUSEMOVE) {
2424 wp = wParam; lp = lParam;
2425 last_mousemove = WM_MOUSEMOVE;
2429 * Add the mouse position and message time to the random
2432 noise_ultralight(lParam);
2434 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2435 GetCapture() == hwnd) {
2437 if (wParam & MK_LBUTTON)
2439 else if (wParam & MK_MBUTTON)
2443 term_mouse(term, b, translate_button(b), MA_DRAG,
2444 TO_CHR_X(X_POS(lParam)),
2445 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2446 wParam & MK_CONTROL, is_alt_pressed());
2449 case WM_NCMOUSEMOVE:
2451 static WPARAM wp = 0;
2452 static LPARAM lp = 0;
2453 if (wParam != wp || lParam != lp ||
2454 last_mousemove != WM_NCMOUSEMOVE) {
2456 wp = wParam; lp = lParam;
2457 last_mousemove = WM_NCMOUSEMOVE;
2460 noise_ultralight(lParam);
2462 case WM_IGNORE_CLIP:
2463 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2465 case WM_DESTROYCLIPBOARD:
2467 term_deselect(term);
2468 ignore_clip = FALSE;
2475 hdc = BeginPaint(hwnd, &p);
2477 SelectPalette(hdc, pal, TRUE);
2478 RealizePalette(hdc);
2482 * We have to be careful about term_paint(). It will
2483 * set a bunch of character cells to INVALID and then
2484 * call do_paint(), which will redraw those cells and
2485 * _then mark them as done_. This may not be accurate:
2486 * when painting in WM_PAINT context we are restricted
2487 * to the rectangle which has just been exposed - so if
2488 * that only covers _part_ of a character cell and the
2489 * rest of it was already visible, that remainder will
2490 * not be redrawn at all. Accordingly, we must not
2491 * paint any character cell in a WM_PAINT context which
2492 * already has a pending update due to terminal output.
2493 * The simplest solution to this - and many, many
2494 * thanks to Hung-Te Lin for working all this out - is
2495 * not to do any actual painting at _all_ if there's a
2496 * pending terminal update: just mark the relevant
2497 * character cells as INVALID and wait for the
2498 * scheduled full update to sort it out.
2500 * I have a suspicion this isn't the _right_ solution.
2501 * An alternative approach would be to have terminal.c
2502 * separately track what _should_ be on the terminal
2503 * screen and what _is_ on the terminal screen, and
2504 * have two completely different types of redraw (one
2505 * for full updates, which syncs the former with the
2506 * terminal itself, and one for WM_PAINT which syncs
2507 * the latter with the former); yet another possibility
2508 * would be to have the Windows front end do what the
2509 * GTK one already does, and maintain a bitmap of the
2510 * current terminal appearance so that WM_PAINT becomes
2511 * completely trivial. However, this should do for now.
2513 term_paint(term, hdc,
2514 (p.rcPaint.left-offset_width)/font_width,
2515 (p.rcPaint.top-offset_height)/font_height,
2516 (p.rcPaint.right-offset_width-1)/font_width,
2517 (p.rcPaint.bottom-offset_height-1)/font_height,
2518 !term->window_update_pending);
2521 p.rcPaint.left < offset_width ||
2522 p.rcPaint.top < offset_height ||
2523 p.rcPaint.right >= offset_width + font_width*term->cols ||
2524 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2526 HBRUSH fillcolour, oldbrush;
2528 fillcolour = CreateSolidBrush (
2529 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2530 oldbrush = SelectObject(hdc, fillcolour);
2531 edge = CreatePen(PS_SOLID, 0,
2532 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2533 oldpen = SelectObject(hdc, edge);
2536 * Jordan Russell reports that this apparently
2537 * ineffectual IntersectClipRect() call masks a
2538 * Windows NT/2K bug causing strange display
2539 * problems when the PuTTY window is taller than
2540 * the primary monitor. It seems harmless enough...
2542 IntersectClipRect(hdc,
2543 p.rcPaint.left, p.rcPaint.top,
2544 p.rcPaint.right, p.rcPaint.bottom);
2546 ExcludeClipRect(hdc,
2547 offset_width, offset_height,
2548 offset_width+font_width*term->cols,
2549 offset_height+font_height*term->rows);
2551 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2552 p.rcPaint.right, p.rcPaint.bottom);
2554 /* SelectClipRgn(hdc, NULL); */
2556 SelectObject(hdc, oldbrush);
2557 DeleteObject(fillcolour);
2558 SelectObject(hdc, oldpen);
2561 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2562 SelectObject(hdc, GetStockObject(WHITE_PEN));
2568 enact_netevent(wParam, lParam);
2569 net_pending_errors();
2572 term_set_focus(term, TRUE);
2573 CreateCaret(hwnd, caretbm, font_width, font_height);
2575 flash_window(0); /* stop */
2581 term_set_focus(term, FALSE);
2583 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2586 case WM_ENTERSIZEMOVE:
2587 #ifdef RDB_DEBUG_PATCH
2588 debug((27, "WM_ENTERSIZEMOVE"));
2592 need_backend_resize = FALSE;
2594 case WM_EXITSIZEMOVE:
2597 #ifdef RDB_DEBUG_PATCH
2598 debug((27, "WM_EXITSIZEMOVE"));
2600 if (need_backend_resize) {
2601 term_size(term, cfg.height, cfg.width, cfg.savelines);
2602 InvalidateRect(hwnd, NULL, TRUE);
2607 * This does two jobs:
2608 * 1) Keep the sizetip uptodate
2609 * 2) Make sure the window size is _stepped_ in units of the font size.
2611 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2612 int width, height, w, h, ew, eh;
2613 LPRECT r = (LPRECT) lParam;
2615 if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
2616 (cfg.height != term->rows || cfg.width != term->cols )) {
2618 * Great! It seems that both the terminal size and the
2619 * font size have been changed and the user is now dragging.
2621 * It will now be difficult to get back to the configured
2624 * This would be easier but it seems to be too confusing.
2626 term_size(term, cfg.height, cfg.width, cfg.savelines);
2629 cfg.height=term->rows; cfg.width=term->cols;
2631 InvalidateRect(hwnd, NULL, TRUE);
2632 need_backend_resize = TRUE;
2635 width = r->right - r->left - extra_width;
2636 height = r->bottom - r->top - extra_height;
2637 w = (width + font_width / 2) / font_width;
2640 h = (height + font_height / 2) / font_height;
2643 UpdateSizeTip(hwnd, w, h);
2644 ew = width - w * font_width;
2645 eh = height - h * font_height;
2647 if (wParam == WMSZ_LEFT ||
2648 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2654 if (wParam == WMSZ_TOP ||
2655 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2665 int width, height, w, h, rv = 0;
2666 int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2667 int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2668 LPRECT r = (LPRECT) lParam;
2670 width = r->right - r->left - ex_width;
2671 height = r->bottom - r->top - ex_height;
2673 w = (width + term->cols/2)/term->cols;
2674 h = (height + term->rows/2)/term->rows;
2675 if ( r->right != r->left + w*term->cols + ex_width)
2678 if (wParam == WMSZ_LEFT ||
2679 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2680 r->left = r->right - w*term->cols - ex_width;
2682 r->right = r->left + w*term->cols + ex_width;
2684 if (r->bottom != r->top + h*term->rows + ex_height)
2687 if (wParam == WMSZ_TOP ||
2688 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2689 r->top = r->bottom - h*term->rows - ex_height;
2691 r->bottom = r->top + h*term->rows + ex_height;
2695 /* break; (never reached) */
2696 case WM_FULLSCR_ON_MAX:
2697 fullscr_on_max = TRUE;
2700 sys_cursor_update();
2703 #ifdef RDB_DEBUG_PATCH
2704 debug((27, "WM_SIZE %s (%d,%d)",
2705 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2706 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2707 (wParam == SIZE_RESTORED && resizing) ? "to":
2708 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2710 LOWORD(lParam), HIWORD(lParam)));
2712 if (wParam == SIZE_MINIMIZED)
2714 cfg.win_name_always ? window_name : icon_name);
2715 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2716 SetWindowText(hwnd, window_name);
2717 if (wParam == SIZE_RESTORED)
2718 clear_full_screen();
2719 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2720 fullscr_on_max = FALSE;
2724 if (cfg.resize_action == RESIZE_DISABLED) {
2725 /* A resize, well it better be a minimize. */
2729 int width, height, w, h;
2731 width = LOWORD(lParam);
2732 height = HIWORD(lParam);
2735 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2737 prev_rows = term->rows;
2738 prev_cols = term->cols;
2739 if (cfg.resize_action == RESIZE_TERM) {
2740 w = width / font_width;
2742 h = height / font_height;
2745 term_size(term, h, w, cfg.savelines);
2748 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2750 if (cfg.resize_action == RESIZE_TERM)
2751 term_size(term, prev_rows, prev_cols, cfg.savelines);
2752 if (cfg.resize_action != RESIZE_FONT)
2757 /* This is an unexpected resize, these will normally happen
2758 * if the window is too large. Probably either the user
2759 * selected a huge font or the screen size has changed.
2761 * This is also called with minimize.
2763 else reset_window(-1);
2767 * Don't call back->size in mid-resize. (To prevent
2768 * massive numbers of resize events getting sent
2769 * down the connection during an NT opaque drag.)
2772 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2773 need_backend_resize = TRUE;
2774 w = (width-cfg.window_border*2) / font_width;
2776 h = (height-cfg.window_border*2) / font_height;
2785 sys_cursor_update();
2788 switch (LOWORD(wParam)) {
2790 term_scroll(term, -1, 0);
2793 term_scroll(term, +1, 0);
2796 term_scroll(term, 0, +1);
2799 term_scroll(term, 0, -1);
2802 term_scroll(term, 0, +term->rows / 2);
2805 term_scroll(term, 0, -term->rows / 2);
2807 case SB_THUMBPOSITION:
2809 term_scroll(term, 1, HIWORD(wParam));
2813 case WM_PALETTECHANGED:
2814 if ((HWND) wParam != hwnd && pal != NULL) {
2815 HDC hdc = get_ctx(NULL);
2817 if (RealizePalette(hdc) > 0)
2823 case WM_QUERYNEWPALETTE:
2825 HDC hdc = get_ctx(NULL);
2827 if (RealizePalette(hdc) > 0)
2839 * Add the scan code and keypress timing to the random
2842 noise_ultralight(lParam);
2845 * We don't do TranslateMessage since it disassociates the
2846 * resulting CHAR message from the KEYDOWN that sparked it,
2847 * which we occasionally don't want. Instead, we process
2848 * KEYDOWN, and call the Win32 translator functions so that
2849 * we get the translations under _our_ control.
2852 unsigned char buf[20];
2855 if (wParam == VK_PROCESSKEY) { /* IME PROCESS key */
2856 if (message == WM_KEYDOWN) {
2859 m.message = WM_KEYDOWN;
2861 m.lParam = lParam & 0xdfff;
2862 TranslateMessage(&m);
2863 } else break; /* pass to Windows for default processing */
2865 len = TranslateKey(message, wParam, lParam, buf);
2867 return DefWindowProc(hwnd, message, wParam, lParam);
2871 * Interrupt an ongoing paste. I'm not sure
2872 * this is sensible, but for the moment it's
2873 * preferable to having to faff about buffering
2879 * We need not bother about stdin backlogs
2880 * here, because in GUI PuTTY we can't do
2881 * anything about it anyway; there's no means
2882 * of asking Windows to hold off on KEYDOWN
2883 * messages. We _have_ to buffer everything
2886 term_seen_key_event(term);
2888 ldisc_send(ldisc, buf, len, 1);
2893 net_pending_errors();
2895 case WM_INPUTLANGCHANGE:
2896 /* wParam == Font number */
2897 /* lParam == Locale */
2898 set_input_locale((HKL)lParam);
2899 sys_cursor_update();
2901 case WM_IME_STARTCOMPOSITION:
2903 HIMC hImc = ImmGetContext(hwnd);
2904 ImmSetCompositionFont(hImc, &lfont);
2905 ImmReleaseContext(hwnd, hImc);
2908 case WM_IME_COMPOSITION:
2914 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
2915 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2917 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2918 break; /* fall back to DefWindowProc */
2920 hIMC = ImmGetContext(hwnd);
2921 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2925 buff = snewn(n, char);
2926 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
2928 * Jaeyoun Chung reports that Korean character
2929 * input doesn't work correctly if we do a single
2930 * luni_send() covering the whole of buff. So
2931 * instead we luni_send the characters one by one.
2933 term_seen_key_event(term);
2934 for (i = 0; i < n; i += 2) {
2936 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2940 ImmReleaseContext(hwnd, hIMC);
2945 if (wParam & 0xFF00) {
2946 unsigned char buf[2];
2949 buf[0] = wParam >> 8;
2950 term_seen_key_event(term);
2952 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
2954 char c = (unsigned char) wParam;
2955 term_seen_key_event(term);
2957 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
2963 * Nevertheless, we are prepared to deal with WM_CHAR
2964 * messages, should they crop up. So if someone wants to
2965 * post the things to us as part of a macro manoeuvre,
2966 * we're ready to cope.
2969 char c = (unsigned char)wParam;
2970 term_seen_key_event(term);
2972 lpage_send(ldisc, CP_ACP, &c, 1, 1);
2975 case WM_SYSCOLORCHANGE:
2976 if (cfg.system_colour) {
2977 /* Refresh palette from system colours. */
2978 /* XXX actually this zaps the entire palette. */
2981 /* Force a repaint of the terminal window. */
2982 term_invalidate(term);
2985 case WM_AGENT_CALLBACK:
2987 struct agent_callback *c = (struct agent_callback *)lParam;
2988 c->callback(c->callback_ctx, c->data, c->len);
2993 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
2994 int shift_pressed=0, control_pressed=0;
2996 if (message == WM_MOUSEWHEEL) {
2997 wheel_accumulator += (short)HIWORD(wParam);
2998 shift_pressed=LOWORD(wParam) & MK_SHIFT;
2999 control_pressed=LOWORD(wParam) & MK_CONTROL;
3002 wheel_accumulator += (int)wParam;
3003 if (GetKeyboardState(keys)!=0) {
3004 shift_pressed=keys[VK_SHIFT]&0x80;
3005 control_pressed=keys[VK_CONTROL]&0x80;
3009 /* process events when the threshold is reached */
3010 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
3013 /* reduce amount for next time */
3014 if (wheel_accumulator > 0) {
3016 wheel_accumulator -= WHEEL_DELTA;
3017 } else if (wheel_accumulator < 0) {
3019 wheel_accumulator += WHEEL_DELTA;
3023 if (send_raw_mouse &&
3024 !(cfg.mouse_override && shift_pressed)) {
3025 /* send a mouse-down followed by a mouse up */
3026 term_mouse(term, b, translate_button(b),
3028 TO_CHR_X(X_POS(lParam)),
3029 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
3030 control_pressed, is_alt_pressed());
3031 term_mouse(term, b, translate_button(b),
3032 MA_RELEASE, TO_CHR_X(X_POS(lParam)),
3033 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
3034 control_pressed, is_alt_pressed());
3036 /* trigger a scroll */
3037 term_scroll(term, 0,
3039 -term->rows / 2 : term->rows / 2);
3047 * Any messages we don't process completely above are passed through to
3048 * DefWindowProc() for default processing.
3050 return DefWindowProc(hwnd, message, wParam, lParam);
3054 * Move the system caret. (We maintain one, even though it's
3055 * invisible, for the benefit of blind people: apparently some
3056 * helper software tracks the system caret, so we should arrange to
3059 void sys_cursor(void *frontend, int x, int y)
3063 if (!term->has_focus) return;
3066 * Avoid gratuitously re-updating the cursor position and IMM
3067 * window if there's no actual change required.
3069 cx = x * font_width + offset_width;
3070 cy = y * font_height + offset_height;
3071 if (cx == caret_x && cy == caret_y)
3076 sys_cursor_update();
3079 static void sys_cursor_update(void)
3084 if (!term->has_focus) return;
3086 if (caret_x < 0 || caret_y < 0)
3089 SetCaretPos(caret_x, caret_y);
3091 /* IMM calls on Win98 and beyond only */
3092 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3094 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3095 osVersion.dwMinorVersion == 0) return; /* 95 */
3097 /* we should have the IMM functions */
3098 hIMC = ImmGetContext(hwnd);
3099 cf.dwStyle = CFS_POINT;
3100 cf.ptCurrentPos.x = caret_x;
3101 cf.ptCurrentPos.y = caret_y;
3102 ImmSetCompositionWindow(hIMC, &cf);
3104 ImmReleaseContext(hwnd, hIMC);
3108 * Draw a line of text in the window, at given character
3109 * coordinates, in given attributes.
3111 * We are allowed to fiddle with the contents of `text'.
3113 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3114 unsigned long attr, int lattr)
3117 int nfg, nbg, nfont;
3120 int force_manual_underline = 0;
3121 int fnt_width, char_width;
3122 int text_adjust = 0;
3123 static int *IpDx = 0, IpDxLEN = 0;
3125 lattr &= LATTR_MODE;
3127 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3129 if (attr & ATTR_WIDE)
3132 if (len > IpDxLEN || IpDx[0] != char_width) {
3134 if (len > IpDxLEN) {
3136 IpDx = snewn(len + 16, int);
3137 IpDxLEN = (len + 16);
3139 for (i = 0; i < IpDxLEN; i++)
3140 IpDx[i] = char_width;
3143 /* Only want the left half of double width lines */
3144 if (lattr != LATTR_NORM && x*2 >= term->cols)
3152 if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
3153 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3154 if (bold_mode == BOLD_COLOURS)
3157 /* cursor fg and bg */
3158 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3162 if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3163 /* Assume a poorman font is borken in other ways too. */
3173 nfont |= FONT_WIDE + FONT_HIGH;
3176 if (attr & ATTR_NARROW)
3177 nfont |= FONT_NARROW;
3179 /* Special hack for the VT100 linedraw glyphs. */
3180 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3181 switch ((unsigned char) (text[0])) {
3183 text_adjust = -2 * font_height / 5;
3186 text_adjust = -1 * font_height / 5;
3189 text_adjust = font_height / 5;
3192 text_adjust = 2 * font_height / 5;
3195 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3197 text[0] = ucsdata.unitab_xterm['q'];
3198 if (attr & ATTR_UNDER) {
3199 attr &= ~ATTR_UNDER;
3200 force_manual_underline = 1;
3204 /* Anything left as an original character set is unprintable. */
3205 if (DIRECT_CHAR(text[0])) {
3207 for (i = 0; i < len; i++)
3212 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3215 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3216 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3217 if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
3219 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3220 nfont |= FONT_UNDERLINE;
3221 another_font(nfont);
3222 if (!fonts[nfont]) {
3223 if (nfont & FONT_UNDERLINE)
3224 force_manual_underline = 1;
3225 /* Don't do the same for manual bold, it could be bad news. */
3227 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3229 another_font(nfont);
3231 nfont = FONT_NORMAL;
3232 if (attr & ATTR_REVERSE) {
3237 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD)) {
3238 if (nfg < 16) nfg |= 8;
3239 else if (nfg >= 256) nfg |= 1;
3241 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK)) {
3242 if (nbg < 16) nbg |= 8;
3243 else if (nbg >= 256) nbg |= 1;
3247 SelectObject(hdc, fonts[nfont]);
3248 SetTextColor(hdc, fg);
3249 SetBkColor(hdc, bg);
3250 if (attr & TATTR_COMBINING)
3251 SetBkMode(hdc, TRANSPARENT);
3253 SetBkMode(hdc, OPAQUE);
3256 line_box.right = x + char_width * len;
3257 line_box.bottom = y + font_height;
3259 /* Only want the left half of double width lines */
3260 if (line_box.right > font_width*term->cols+offset_width)
3261 line_box.right = font_width*term->cols+offset_width;
3263 /* We're using a private area for direct to font. (512 chars.) */
3264 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3265 /* Ho Hum, dbcs fonts are a PITA! */
3266 /* To display on W9x I have to convert to UCS */
3267 static wchar_t *uni_buf = 0;
3268 static int uni_len = 0;
3270 if (len > uni_len) {
3273 uni_buf = snewn(uni_len, wchar_t);
3276 for(nlen = mptr = 0; mptr<len; mptr++) {
3277 uni_buf[nlen] = 0xFFFD;
3278 if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
3280 dbcstext[0] = text[mptr] & 0xFF;
3281 dbcstext[1] = text[mptr+1] & 0xFF;
3282 IpDx[nlen] += char_width;
3283 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3284 dbcstext, 2, uni_buf+nlen, 1);
3290 dbcstext[0] = text[mptr] & 0xFF;
3291 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3292 dbcstext, 1, uni_buf+nlen, 1);
3300 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3301 ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
3302 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3303 SetBkMode(hdc, TRANSPARENT);
3304 ExtTextOutW(hdc, x - 1,
3305 y - font_height * (lattr ==
3306 LATTR_BOT) + text_adjust,
3307 ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
3311 } else if (DIRECT_FONT(text[0])) {
3312 static char *directbuf = NULL;
3313 static int directlen = 0;
3315 if (len > directlen) {
3317 directbuf = sresize(directbuf, directlen, char);
3320 for (i = 0; i < len; i++)
3321 directbuf[i] = text[i] & 0xFF;
3324 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3325 ETO_CLIPPED | ETO_OPAQUE, &line_box, directbuf, len, IpDx);
3326 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3327 SetBkMode(hdc, TRANSPARENT);
3329 /* GRR: This draws the character outside it's box and can leave
3330 * 'droppings' even with the clip box! I suppose I could loop it
3331 * one character at a time ... yuk.
3333 * Or ... I could do a test print with "W", and use +1 or -1 for this
3334 * shift depending on if the leftmost column is blank...
3336 ExtTextOut(hdc, x - 1,
3337 y - font_height * (lattr ==
3338 LATTR_BOT) + text_adjust,
3339 ETO_CLIPPED, &line_box, directbuf, len, IpDx);
3342 /* And 'normal' unicode characters */
3343 static WCHAR *wbuf = NULL;
3344 static int wlen = 0;
3350 wbuf = snewn(wlen, WCHAR);
3353 for (i = 0; i < len; i++)
3356 /* print Glyphs as they are, without Windows' Shaping*/
3357 general_textout(hdc, x, y - font_height * (lattr == LATTR_BOT) + text_adjust,
3358 &line_box, wbuf, len, IpDx, !(attr & TATTR_COMBINING));
3360 /* And the shadow bold hack. */
3361 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3362 SetBkMode(hdc, TRANSPARENT);
3363 ExtTextOutW(hdc, x - 1,
3364 y - font_height * (lattr ==
3365 LATTR_BOT) + text_adjust,
3366 ETO_CLIPPED, &line_box, wbuf, len, IpDx);
3369 if (lattr != LATTR_TOP && (force_manual_underline ||
3370 (und_mode == UND_LINE
3371 && (attr & ATTR_UNDER)))) {
3374 if (lattr == LATTR_BOT)
3375 dec = dec * 2 - font_height;
3377 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3378 MoveToEx(hdc, x, y + dec, NULL);
3379 LineTo(hdc, x + len * char_width, y + dec);
3380 oldpen = SelectObject(hdc, oldpen);
3381 DeleteObject(oldpen);
3386 * Wrapper that handles combining characters.
3388 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3389 unsigned long attr, int lattr)
3391 if (attr & TATTR_COMBINING) {
3392 unsigned long a = 0;
3393 attr &= ~TATTR_COMBINING;
3395 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3397 a = TATTR_COMBINING;
3400 do_text_internal(ctx, x, y, text, len, attr, lattr);
3403 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3404 unsigned long attr, int lattr)
3410 int ctype = cfg.cursor_type;
3412 lattr &= LATTR_MODE;
3414 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3415 if (*text != UCSWIDE) {
3416 do_text(ctx, x, y, text, len, attr, lattr);
3420 attr |= TATTR_RIGHTCURS;
3423 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3424 if (attr & ATTR_WIDE)
3431 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3434 pts[0].x = pts[1].x = pts[4].x = x;
3435 pts[2].x = pts[3].x = x + char_width - 1;
3436 pts[0].y = pts[3].y = pts[4].y = y;
3437 pts[1].y = pts[2].y = y + font_height - 1;
3438 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3439 Polyline(hdc, pts, 5);
3440 oldpen = SelectObject(hdc, oldpen);
3441 DeleteObject(oldpen);
3442 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3443 int startx, starty, dx, dy, length, i;
3446 starty = y + descent;
3449 length = char_width;
3452 if (attr & TATTR_RIGHTCURS)
3453 xadjust = char_width - 1;
3454 startx = x + xadjust;
3458 length = font_height;
3460 if (attr & TATTR_ACTCURS) {
3463 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3464 MoveToEx(hdc, startx, starty, NULL);
3465 LineTo(hdc, startx + dx * length, starty + dy * length);
3466 oldpen = SelectObject(hdc, oldpen);
3467 DeleteObject(oldpen);
3469 for (i = 0; i < length; i++) {
3471 SetPixel(hdc, startx, starty, colours[261]);
3480 /* This function gets the actual width of a character in the normal font.
3482 int char_width(Context ctx, int uc) {
3486 /* If the font max is the same as the font ave width then this
3487 * function is a no-op.
3489 if (!font_dualwidth) return 1;
3491 switch (uc & CSET_MASK) {
3493 uc = ucsdata.unitab_line[uc & 0xFF];
3496 uc = ucsdata.unitab_xterm[uc & 0xFF];
3499 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3502 if (DIRECT_FONT(uc)) {
3503 if (ucsdata.dbcs_screenfont) return 1;
3505 /* Speedup, I know of no font where ascii is the wrong width */
3506 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3509 if ( (uc & CSET_MASK) == CSET_ACP ) {
3510 SelectObject(hdc, fonts[FONT_NORMAL]);
3511 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3512 another_font(FONT_OEM);
3513 if (!fonts[FONT_OEM]) return 0;
3515 SelectObject(hdc, fonts[FONT_OEM]);
3519 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3520 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3523 /* Speedup, I know of no font where ascii is the wrong width */
3524 if (uc >= ' ' && uc <= '~') return 1;
3526 SelectObject(hdc, fonts[FONT_NORMAL]);
3527 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3528 /* Okay that one worked */ ;
3529 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3530 /* This should work on 9x too, but it's "less accurate" */ ;
3535 ibuf += font_width / 2 -1;
3542 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3543 * codes. Returns number of bytes used or zero to drop the message
3544 * or -1 to forward the message to windows.
3546 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3547 unsigned char *output)
3550 int scan, left_alt = 0, key_down, shift_state;
3552 unsigned char *p = output;
3553 static int alt_sum = 0;
3555 HKL kbd_layout = GetKeyboardLayout(0);
3557 /* keys is for ToAsciiEx. There's some ick here, see below. */
3558 static WORD keys[3];
3559 static int compose_char = 0;
3560 static WPARAM compose_key = 0;
3562 r = GetKeyboardState(keystate);
3564 memset(keystate, 0, sizeof(keystate));
3567 #define SHOW_TOASCII_RESULT
3568 { /* Tell us all about key events */
3569 static BYTE oldstate[256];
3570 static int first = 1;
3574 memcpy(oldstate, keystate, sizeof(oldstate));
3577 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3579 } else if ((HIWORD(lParam) & KF_UP)
3580 && scan == (HIWORD(lParam) & 0xFF)) {
3584 if (wParam >= VK_F1 && wParam <= VK_F20)
3585 debug(("K_F%d", wParam + 1 - VK_F1));
3598 debug(("VK_%02x", wParam));
3600 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3602 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3604 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3605 if (ch >= ' ' && ch <= '~')
3606 debug((", '%c'", ch));
3608 debug((", $%02x", ch));
3611 debug((", KB0=%02x", keys[0]));
3613 debug((", KB1=%02x", keys[1]));
3615 debug((", KB2=%02x", keys[2]));
3617 if ((keystate[VK_SHIFT] & 0x80) != 0)
3619 if ((keystate[VK_CONTROL] & 0x80) != 0)
3621 if ((HIWORD(lParam) & KF_EXTENDED))
3623 if ((HIWORD(lParam) & KF_UP))
3627 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3628 else if ((HIWORD(lParam) & KF_UP))
3629 oldstate[wParam & 0xFF] ^= 0x80;
3631 oldstate[wParam & 0xFF] ^= 0x81;
3633 for (ch = 0; ch < 256; ch++)
3634 if (oldstate[ch] != keystate[ch])
3635 debug((", M%02x=%02x", ch, keystate[ch]));
3637 memcpy(oldstate, keystate, sizeof(oldstate));
3641 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
3642 keystate[VK_RMENU] = keystate[VK_MENU];
3646 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
3647 if ((cfg.funky_type == FUNKY_VT400 ||
3648 (cfg.funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
3650 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
3652 wParam = VK_EXECUTE;
3654 /* UnToggle NUMLock */
3655 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3656 keystate[VK_NUMLOCK] ^= 1;
3659 /* And write back the 'adjusted' state */
3660 SetKeyboardState(keystate);
3663 /* Disable Auto repeat if required */
3664 if (term->repeat_off &&
3665 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
3668 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
3671 key_down = ((HIWORD(lParam) & KF_UP) == 0);
3673 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
3674 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
3675 if (cfg.ctrlaltkeys)
3676 keystate[VK_MENU] = 0;
3678 keystate[VK_RMENU] = 0x80;
3683 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
3684 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3685 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
3687 /* Note if AltGr was pressed and if it was used as a compose key */
3688 if (!compose_state) {
3689 compose_key = 0x100;
3690 if (cfg.compose_key) {
3691 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
3692 compose_key = wParam;
3694 if (wParam == VK_APPS)
3695 compose_key = wParam;
3698 if (wParam == compose_key) {
3699 if (compose_state == 0
3700 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3702 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
3706 } else if (compose_state == 1 && wParam != VK_CONTROL)
3709 if (compose_state > 1 && left_alt)
3712 /* Sanitize the number pad if not using a PC NumPad */
3713 if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
3714 && cfg.funky_type != FUNKY_XTERM)
3715 || cfg.funky_type == FUNKY_VT400 || cfg.nethack_keypad || compose_state) {
3716 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
3720 nParam = VK_NUMPAD0;
3723 nParam = VK_NUMPAD1;
3726 nParam = VK_NUMPAD2;
3729 nParam = VK_NUMPAD3;
3732 nParam = VK_NUMPAD4;
3735 nParam = VK_NUMPAD5;
3738 nParam = VK_NUMPAD6;
3741 nParam = VK_NUMPAD7;
3744 nParam = VK_NUMPAD8;
3747 nParam = VK_NUMPAD9;
3750 nParam = VK_DECIMAL;
3754 if (keystate[VK_NUMLOCK] & 1)
3761 /* If a key is pressed and AltGr is not active */
3762 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3763 /* Okay, prepare for most alts then ... */
3767 /* Lets see if it's a pattern we know all about ... */
3768 if (wParam == VK_PRIOR && shift_state == 1) {
3769 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3772 if (wParam == VK_PRIOR && shift_state == 2) {
3773 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3776 if (wParam == VK_NEXT && shift_state == 1) {
3777 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3780 if (wParam == VK_NEXT && shift_state == 2) {
3781 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3784 if (wParam == VK_INSERT && shift_state == 1) {
3785 term_do_paste(term);
3788 if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
3791 if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
3792 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3795 if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3796 (cfg.resize_action != RESIZE_DISABLED)) {
3797 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3801 /* Control-Numlock for app-keypad mode switch */
3802 if (wParam == VK_PAUSE && shift_state == 2) {
3803 term->app_keypad_keys ^= 1;
3807 /* Nethack keypad */
3808 if (cfg.nethack_keypad && !left_alt) {
3811 *p++ = "bB\002\002"[shift_state & 3];
3814 *p++ = "jJ\012\012"[shift_state & 3];
3817 *p++ = "nN\016\016"[shift_state & 3];
3820 *p++ = "hH\010\010"[shift_state & 3];
3823 *p++ = shift_state ? '.' : '.';
3826 *p++ = "lL\014\014"[shift_state & 3];
3829 *p++ = "yY\031\031"[shift_state & 3];
3832 *p++ = "kK\013\013"[shift_state & 3];
3835 *p++ = "uU\025\025"[shift_state & 3];
3840 /* Application Keypad */
3844 if (cfg.funky_type == FUNKY_VT400 ||
3845 (cfg.funky_type <= FUNKY_LINUX &&
3846 term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
3860 if (term->app_keypad_keys && !cfg.no_applic_k)
3897 if (cfg.funky_type == FUNKY_XTERM) {
3902 } else if (shift_state)
3909 if (cfg.funky_type == FUNKY_XTERM)
3913 if (cfg.funky_type == FUNKY_XTERM)
3917 if (cfg.funky_type == FUNKY_XTERM)
3922 if (HIWORD(lParam) & KF_EXTENDED)
3927 if (term->vt52_mode) {
3928 if (xkey >= 'P' && xkey <= 'S')
3929 p += sprintf((char *) p, "\x1B%c", xkey);
3931 p += sprintf((char *) p, "\x1B?%c", xkey);
3933 p += sprintf((char *) p, "\x1BO%c", xkey);
3938 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
3939 *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
3943 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
3944 /* We do the opposite of what is configured */
3945 *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
3949 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
3955 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
3959 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
3963 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
3968 if (wParam == VK_PAUSE) { /* Break/Pause */
3973 /* Control-2 to Control-8 are special */
3974 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
3975 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
3978 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
3982 if (shift_state == 2 && wParam == 0xDF) {
3986 if (shift_state == 3 && wParam == 0xDE) {
3987 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
3990 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
3997 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
3998 * for integer decimal nn.)
4000 * We also deal with the weird ones here. Linux VCs replace F1
4001 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
4002 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
4008 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
4011 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
4014 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
4017 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
4020 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
4023 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
4026 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
4029 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
4032 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
4035 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
4068 if ((shift_state&2) == 0) switch (wParam) {
4088 /* Reorder edit keys to physical order */
4089 if (cfg.funky_type == FUNKY_VT400 && code <= 6)
4090 code = "\0\2\1\4\5\3\6"[code];
4092 if (term->vt52_mode && code > 0 && code <= 6) {
4093 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4097 if (cfg.funky_type == FUNKY_SCO && /* SCO function keys */
4098 code >= 11 && code <= 34) {
4099 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4102 case VK_F1: index = 0; break;
4103 case VK_F2: index = 1; break;
4104 case VK_F3: index = 2; break;
4105 case VK_F4: index = 3; break;
4106 case VK_F5: index = 4; break;
4107 case VK_F6: index = 5; break;
4108 case VK_F7: index = 6; break;
4109 case VK_F8: index = 7; break;
4110 case VK_F9: index = 8; break;
4111 case VK_F10: index = 9; break;
4112 case VK_F11: index = 10; break;
4113 case VK_F12: index = 11; break;
4115 if (keystate[VK_SHIFT] & 0x80) index += 12;
4116 if (keystate[VK_CONTROL] & 0x80) index += 24;
4117 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4120 if (cfg.funky_type == FUNKY_SCO && /* SCO small keypad */
4121 code >= 1 && code <= 6) {
4122 char codes[] = "HL.FIG";
4126 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4130 if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4136 if (term->vt52_mode)
4137 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4140 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4143 if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4144 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4147 if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4148 if (term->vt52_mode)
4149 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4151 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4154 if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
4155 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4159 p += sprintf((char *) p, "\x1B[%d~", code);
4164 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4165 * some reason seems to send VK_CLEAR to Windows...).
4187 if (term->vt52_mode)
4188 p += sprintf((char *) p, "\x1B%c", xkey);
4190 int app_flg = (term->app_cursor_keys && !cfg.no_applic_c);
4193 * RDB: VT100 & VT102 manuals both state the
4194 * app cursor keys only work if the app keypad
4197 * SGT: That may well be true, but xterm
4198 * disagrees and so does at least one
4199 * application, so I've #if'ed this out and the
4200 * behaviour is back to PuTTY's original: app
4201 * cursor and app keypad are independently
4202 * switchable modes. If anyone complains about
4203 * _this_ I'll have to put in a configurable
4206 if (!term->app_keypad_keys)
4209 /* Useful mapping of Ctrl-arrows */
4210 if (shift_state == 2)
4214 p += sprintf((char *) p, "\x1BO%c", xkey);
4216 p += sprintf((char *) p, "\x1B[%c", xkey);
4223 * Finally, deal with Return ourselves. (Win95 seems to
4224 * foul it up when Alt is pressed, for some reason.)
4226 if (wParam == VK_RETURN) { /* Return */
4232 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4233 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4238 /* Okay we've done everything interesting; let windows deal with
4239 * the boring stuff */
4243 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4244 if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
4246 keystate[VK_CAPITAL] = 0;
4249 /* XXX how do we know what the max size of the keys array should
4250 * be is? There's indication on MS' website of an Inquire/InquireEx
4251 * functioning returning a KBINFO structure which tells us. */
4252 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4253 /* XXX 'keys' parameter is declared in MSDN documentation as
4255 * The experience of a French user indicates that on
4256 * Win98, WORD[] should be passed in, but on Win2K, it should
4257 * be BYTE[]. German WinXP and my Win2K with "US International"
4258 * driver corroborate this.
4259 * Experimentally I've conditionalised the behaviour on the
4260 * Win9x/NT split, but I suspect it's worse than that.
4261 * See wishlist item `win-dead-keys' for more horrible detail
4262 * and speculations. */
4265 r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
4266 for (i=0; i<3; i++) keys[i] = keybs[i];
4268 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4270 #ifdef SHOW_TOASCII_RESULT
4271 if (r == 1 && !key_down) {
4273 if (in_utf(term) || ucsdata.dbcs_screenfont)
4274 debug((", (U+%04x)", alt_sum));
4276 debug((", LCH(%d)", alt_sum));
4278 debug((", ACH(%d)", keys[0]));
4283 for (r1 = 0; r1 < r; r1++) {
4284 debug(("%s%d", r1 ? "," : "", keys[r1]));
4293 * Interrupt an ongoing paste. I'm not sure this is
4294 * sensible, but for the moment it's preferable to
4295 * having to faff about buffering things.
4300 for (i = 0; i < r; i++) {
4301 unsigned char ch = (unsigned char) keys[i];
4303 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
4308 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
4312 if ((nc = check_compose(compose_char, ch)) == -1) {
4313 MessageBeep(MB_ICONHAND);
4317 term_seen_key_event(term);
4319 luni_send(ldisc, &keybuf, 1, 1);
4327 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4329 term_seen_key_event(term);
4331 luni_send(ldisc, &keybuf, 1, 1);
4333 ch = (char) alt_sum;
4335 * We need not bother about stdin
4336 * backlogs here, because in GUI PuTTY
4337 * we can't do anything about it
4338 * anyway; there's no means of asking
4339 * Windows to hold off on KEYDOWN
4340 * messages. We _have_ to buffer
4341 * everything we're sent.
4343 term_seen_key_event(term);
4345 ldisc_send(ldisc, &ch, 1, 1);
4349 term_seen_key_event(term);
4351 lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
4354 if(capsOn && ch < 0x80) {
4357 cbuf[1] = xlat_uskbd2cyrllic(ch);
4358 term_seen_key_event(term);
4360 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4365 term_seen_key_event(term);
4367 lpage_send(ldisc, kbd_codepage,
4368 cbuf+!left_alt, 1+!!left_alt, 1);
4374 /* This is so the ALT-Numpad and dead keys work correctly. */
4379 /* If we're definitly not building up an ALT-54321 then clear it */
4382 /* If we will be using alt_sum fix the 256s */
4383 else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4388 * ALT alone may or may not want to bring up the System menu.
4389 * If it's not meant to, we return 0 on presses or releases of
4390 * ALT, to show that we've swallowed the keystroke. Otherwise
4391 * we return -1, which means Windows will give the keystroke
4392 * its default handling (i.e. bring up the System menu).
4394 if (wParam == VK_MENU && !cfg.alt_only)
4400 void request_paste(void *frontend)
4403 * In Windows, pasting is synchronous: we can read the
4404 * clipboard with no difficulty, so request_paste() can just go
4407 term_do_paste(term);
4410 void set_title(void *frontend, char *title)
4413 window_name = snewn(1 + strlen(title), char);
4414 strcpy(window_name, title);
4415 if (cfg.win_name_always || !IsIconic(hwnd))
4416 SetWindowText(hwnd, title);
4419 void set_icon(void *frontend, char *title)
4422 icon_name = snewn(1 + strlen(title), char);
4423 strcpy(icon_name, title);
4424 if (!cfg.win_name_always && IsIconic(hwnd))
4425 SetWindowText(hwnd, title);
4428 void set_sbar(void *frontend, int total, int start, int page)
4432 if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
4435 si.cbSize = sizeof(si);
4436 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4438 si.nMax = total - 1;
4442 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4445 Context get_ctx(void *frontend)
4451 SelectPalette(hdc, pal, FALSE);
4457 void free_ctx(Context ctx)
4459 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4460 ReleaseDC(hwnd, ctx);
4463 static void real_palette_set(int n, int r, int g, int b)
4466 logpal->palPalEntry[n].peRed = r;
4467 logpal->palPalEntry[n].peGreen = g;
4468 logpal->palPalEntry[n].peBlue = b;
4469 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4470 colours[n] = PALETTERGB(r, g, b);
4471 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4473 colours[n] = RGB(r, g, b);
4476 void palette_set(void *frontend, int n, int r, int g, int b)
4480 if (n > NALLCOLOURS)
4482 real_palette_set(n, r, g, b);
4484 HDC hdc = get_ctx(frontend);
4485 UnrealizeObject(pal);
4486 RealizePalette(hdc);
4489 if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))
4490 /* If Default Background changes, we need to ensure any
4491 * space between the text area and the window border is
4493 InvalidateRect(hwnd, NULL, TRUE);
4497 void palette_reset(void *frontend)
4502 for (i = 0; i < NALLCOLOURS; i++) {
4504 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4505 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4506 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4507 logpal->palPalEntry[i].peFlags = 0;
4508 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4509 defpal[i].rgbtGreen,
4510 defpal[i].rgbtBlue);
4512 colours[i] = RGB(defpal[i].rgbtRed,
4513 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4518 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4519 hdc = get_ctx(frontend);
4520 RealizePalette(hdc);
4523 /* Default Background may have changed. Ensure any space between
4524 * text area and window border is redrawn. */
4525 InvalidateRect(hwnd, NULL, TRUE);
4529 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4534 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4537 lock = GlobalLock(clipdata);
4540 memcpy(lock, data, len);
4541 ((unsigned char *) lock)[len] = 0;
4542 GlobalUnlock(clipdata);
4545 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4547 if (OpenClipboard(hwnd)) {
4549 SetClipboardData(CF_TEXT, clipdata);
4552 GlobalFree(clipdata);
4555 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4559 * Note: unlike write_aclip() this will not append a nul.
4561 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
4563 HGLOBAL clipdata, clipdata2, clipdata3;
4565 void *lock, *lock2, *lock3;
4567 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4569 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4570 len * sizeof(wchar_t));
4571 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4573 if (!clipdata || !clipdata2) {
4575 GlobalFree(clipdata);
4577 GlobalFree(clipdata2);
4580 if (!(lock = GlobalLock(clipdata)))
4582 if (!(lock2 = GlobalLock(clipdata2)))
4585 memcpy(lock, data, len * sizeof(wchar_t));
4586 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4588 if (cfg.rtf_paste) {
4589 wchar_t unitab[256];
4591 unsigned char *tdata = (unsigned char *)lock2;
4592 wchar_t *udata = (wchar_t *)lock;
4593 int rtflen = 0, uindex = 0, tindex = 0;
4595 int multilen, blen, alen, totallen, i;
4596 char before[16], after[4];
4597 int fgcolour, lastfgcolour = 0;
4598 int bgcolour, lastbgcolour = 0;
4599 int attrBold, lastAttrBold = 0;
4600 int attrUnder, lastAttrUnder = 0;
4601 int palette[NALLCOLOURS];
4604 get_unitab(CP_ACP, unitab, 0);
4606 rtfsize = 100 + strlen(cfg.font.name);
4607 rtf = snewn(rtfsize, char);
4608 rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
4609 cfg.font.name, cfg.font.height*2);
4612 * Add colour palette
4613 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
4617 * First - Determine all colours in use
4618 * o Foregound and background colours share the same palette
4621 memset(palette, 0, sizeof(palette));
4622 for (i = 0; i < (len-1); i++) {
4623 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
4624 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
4626 if (attr[i] & ATTR_REVERSE) {
4627 int tmpcolour = fgcolour; /* Swap foreground and background */
4628 fgcolour = bgcolour;
4629 bgcolour = tmpcolour;
4632 if (bold_mode == BOLD_COLOURS && (attr[i] & ATTR_BOLD)) {
4633 if (fgcolour < 8) /* ANSI colours */
4635 else if (fgcolour >= 256) /* Default colours */
4639 if (attr[i] & ATTR_BLINK) {
4640 if (bgcolour < 8) /* ANSI colours */
4642 else if (bgcolour >= 256) /* Default colours */
4646 palette[fgcolour]++;
4647 palette[bgcolour]++;
4651 * Next - Create a reduced palette
4654 for (i = 0; i < NALLCOLOURS; i++) {
4655 if (palette[i] != 0)
4656 palette[i] = ++numcolours;
4660 * Finally - Write the colour table
4662 rtf = sresize(rtf, rtfsize + (numcolours * 25), char);
4663 strcat(rtf, "{\\colortbl ;");
4664 rtflen = strlen(rtf);
4666 for (i = 0; i < NALLCOLOURS; i++) {
4667 if (palette[i] != 0) {
4668 rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4671 strcpy(&rtf[rtflen], "}");
4676 * We want to construct a piece of RTF that specifies the
4677 * same Unicode text. To do this we will read back in
4678 * parallel from the Unicode data in `udata' and the
4679 * non-Unicode data in `tdata'. For each character in
4680 * `tdata' which becomes the right thing in `udata' when
4681 * looked up in `unitab', we just copy straight over from
4682 * tdata. For each one that doesn't, we must WCToMB it
4683 * individually and produce a \u escape sequence.
4685 * It would probably be more robust to just bite the bullet
4686 * and WCToMB each individual Unicode character one by one,
4687 * then MBToWC each one back to see if it was an accurate
4688 * translation; but that strikes me as a horrifying number
4689 * of Windows API calls so I want to see if this faster way
4690 * will work. If it screws up badly we can always revert to
4691 * the simple and slow way.
4693 while (tindex < len2 && uindex < len &&
4694 tdata[tindex] && udata[uindex]) {
4695 if (tindex + 1 < len2 &&
4696 tdata[tindex] == '\r' &&
4697 tdata[tindex+1] == '\n') {
4703 * Set text attributes
4706 if (rtfsize < rtflen + 64) {
4707 rtfsize = rtflen + 512;
4708 rtf = sresize(rtf, rtfsize, char);
4712 * Determine foreground and background colours
4714 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
4715 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
4717 if (attr[tindex] & ATTR_REVERSE) {
4718 int tmpcolour = fgcolour; /* Swap foreground and background */
4719 fgcolour = bgcolour;
4720 bgcolour = tmpcolour;
4723 if (bold_mode == BOLD_COLOURS && (attr[tindex] & ATTR_BOLD)) {
4724 if (fgcolour < 8) /* ANSI colours */
4726 else if (fgcolour >= 256) /* Default colours */
4730 if (attr[tindex] & ATTR_BLINK) {
4731 if (bgcolour < 8) /* ANSI colours */
4733 else if (bgcolour >= 256) /* Default colours */
4738 * Collect other attributes
4740 if (bold_mode != BOLD_COLOURS)
4741 attrBold = attr[tindex] & ATTR_BOLD;
4745 attrUnder = attr[tindex] & ATTR_UNDER;
4749 * o If video isn't reversed, ignore colour attributes for default foregound
4751 * o Special case where bolded text is displayed using the default foregound
4752 * and background colours - force to bolded RTF.
4754 if (!(attr[tindex] & ATTR_REVERSE)) {
4755 if (bgcolour >= 256) /* Default color */
4756 bgcolour = -1; /* No coloring */
4758 if (fgcolour >= 256) { /* Default colour */
4759 if (bold_mode == BOLD_COLOURS && (fgcolour & 1) && bgcolour == -1)
4760 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
4762 fgcolour = -1; /* No coloring */
4767 * Write RTF text attributes
4769 if (lastfgcolour != fgcolour) {
4770 lastfgcolour = fgcolour;
4771 rtflen += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
4774 if (lastbgcolour != bgcolour) {
4775 lastbgcolour = bgcolour;
4776 rtflen += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
4779 if (lastAttrBold != attrBold) {
4780 lastAttrBold = attrBold;
4781 rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
4784 if (lastAttrUnder != attrUnder) {
4785 lastAttrUnder = attrUnder;
4786 rtflen += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
4790 if (unitab[tdata[tindex]] == udata[uindex]) {
4796 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4797 NULL, 0, NULL, NULL);
4798 if (multilen != 1) {
4799 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4801 alen = 1; strcpy(after, "}");
4803 blen = sprintf(before, "\\u%d", udata[uindex]);
4804 alen = 0; after[0] = '\0';
4807 assert(tindex + multilen <= len2);
4808 totallen = blen + alen;
4809 for (i = 0; i < multilen; i++) {
4810 if (tdata[tindex+i] == '\\' ||
4811 tdata[tindex+i] == '{' ||
4812 tdata[tindex+i] == '}')
4814 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4815 totallen += 6; /* \par\r\n */
4816 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4822 if (rtfsize < rtflen + totallen + 3) {
4823 rtfsize = rtflen + totallen + 512;
4824 rtf = sresize(rtf, rtfsize, char);
4827 strcpy(rtf + rtflen, before); rtflen += blen;
4828 for (i = 0; i < multilen; i++) {
4829 if (tdata[tindex+i] == '\\' ||
4830 tdata[tindex+i] == '{' ||
4831 tdata[tindex+i] == '}') {
4832 rtf[rtflen++] = '\\';
4833 rtf[rtflen++] = tdata[tindex+i];
4834 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4835 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4836 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4837 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4839 rtf[rtflen++] = tdata[tindex+i];
4842 strcpy(rtf + rtflen, after); rtflen += alen;
4848 rtf[rtflen++] = '}'; /* Terminate RTF stream */
4849 rtf[rtflen++] = '\0';
4850 rtf[rtflen++] = '\0';
4852 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4853 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
4854 memcpy(lock3, rtf, rtflen);
4855 GlobalUnlock(clipdata3);
4861 GlobalUnlock(clipdata);
4862 GlobalUnlock(clipdata2);
4865 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4867 if (OpenClipboard(hwnd)) {
4869 SetClipboardData(CF_UNICODETEXT, clipdata);
4870 SetClipboardData(CF_TEXT, clipdata2);
4872 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4875 GlobalFree(clipdata);
4876 GlobalFree(clipdata2);
4880 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4883 void get_clip(void *frontend, wchar_t ** p, int *len)
4885 static HGLOBAL clipdata = NULL;
4886 static wchar_t *converted = 0;
4895 GlobalUnlock(clipdata);
4898 } else if (OpenClipboard(NULL)) {
4899 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
4901 *p = GlobalLock(clipdata);
4903 for (p2 = *p; *p2; p2++);
4907 } else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
4911 s = GlobalLock(clipdata);
4912 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
4913 *p = converted = snewn(i, wchar_t);
4914 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
4927 * Move `lines' lines from position `from' to position `to' in the
4930 void optimised_move(void *frontend, int to, int from, int lines)
4935 min = (to < from ? to : from);
4936 max = to + from - min;
4938 r.left = offset_width;
4939 r.right = offset_width + term->cols * font_width;
4940 r.top = offset_height + min * font_height;
4941 r.bottom = offset_height + (max + lines) * font_height;
4942 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
4947 * Print a message box and perform a fatal exit.
4949 void fatalbox(char *fmt, ...)
4952 char *stuff, morestuff[100];
4955 stuff = dupvprintf(fmt, ap);
4957 sprintf(morestuff, "%.70s Fatal Error", appname);
4958 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
4964 * Print a modal (Really Bad) message box and perform a fatal exit.
4966 void modalfatalbox(char *fmt, ...)
4969 char *stuff, morestuff[100];
4972 stuff = dupvprintf(fmt, ap);
4974 sprintf(morestuff, "%.70s Fatal Error", appname);
4975 MessageBox(hwnd, stuff, morestuff,
4976 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
4981 static void flash_window(int mode);
4982 static long next_flash;
4983 static int flashing = 0;
4985 static void flash_window_timer(void *ctx, long now)
4987 if (flashing && now - next_flash >= 0) {
4993 * Manage window caption / taskbar flashing, if enabled.
4994 * 0 = stop, 1 = maintain, 2 = start
4996 static void flash_window(int mode)
4998 if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
5001 FlashWindow(hwnd, FALSE);
5005 } else if (mode == 2) {
5009 FlashWindow(hwnd, TRUE);
5010 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5013 } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
5016 FlashWindow(hwnd, TRUE); /* toggle */
5017 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5025 void do_beep(void *frontend, int mode)
5027 if (mode == BELL_DEFAULT) {
5029 * For MessageBeep style bells, we want to be careful of
5030 * timing, because they don't have the nice property of
5031 * PlaySound bells that each one cancels the previous
5032 * active one. So we limit the rate to one per 50ms or so.
5034 static long lastbeep = 0;
5037 beepdiff = GetTickCount() - lastbeep;
5038 if (beepdiff >= 0 && beepdiff < 50)
5042 * The above MessageBeep call takes time, so we record the
5043 * time _after_ it finishes rather than before it starts.
5045 lastbeep = GetTickCount();
5046 } else if (mode == BELL_WAVEFILE) {
5047 if (!PlaySound(cfg.bell_wavefile.path, NULL,
5048 SND_ASYNC | SND_FILENAME)) {
5049 char buf[sizeof(cfg.bell_wavefile.path) + 80];
5051 sprintf(buf, "Unable to play sound file\n%s\n"
5052 "Using default sound instead", cfg.bell_wavefile.path);
5053 sprintf(otherbuf, "%.70s Sound Error", appname);
5054 MessageBox(hwnd, buf, otherbuf,
5055 MB_OK | MB_ICONEXCLAMATION);
5056 cfg.beep = BELL_DEFAULT;
5058 } else if (mode == BELL_PCSPEAKER) {
5059 static long lastbeep = 0;
5062 beepdiff = GetTickCount() - lastbeep;
5063 if (beepdiff >= 0 && beepdiff < 50)
5067 * We must beep in different ways depending on whether this
5068 * is a 95-series or NT-series OS.
5070 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
5074 lastbeep = GetTickCount();
5076 /* Otherwise, either visual bell or disabled; do nothing here */
5077 if (!term->has_focus) {
5078 flash_window(2); /* start */
5083 * Minimise or restore the window in response to a server-side
5086 void set_iconic(void *frontend, int iconic)
5088 if (IsIconic(hwnd)) {
5090 ShowWindow(hwnd, SW_RESTORE);
5093 ShowWindow(hwnd, SW_MINIMIZE);
5098 * Move the window in response to a server-side request.
5100 void move_window(void *frontend, int x, int y)
5102 if (cfg.resize_action == RESIZE_DISABLED ||
5103 cfg.resize_action == RESIZE_FONT ||
5107 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5111 * Move the window to the top or bottom of the z-order in response
5112 * to a server-side request.
5114 void set_zorder(void *frontend, int top)
5116 if (cfg.alwaysontop)
5117 return; /* ignore */
5118 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5119 SWP_NOMOVE | SWP_NOSIZE);
5123 * Refresh the window in response to a server-side request.
5125 void refresh_window(void *frontend)
5127 InvalidateRect(hwnd, NULL, TRUE);
5131 * Maximise or restore the window in response to a server-side
5134 void set_zoomed(void *frontend, int zoomed)
5136 if (IsZoomed(hwnd)) {
5138 ShowWindow(hwnd, SW_RESTORE);
5141 ShowWindow(hwnd, SW_MAXIMIZE);
5146 * Report whether the window is iconic, for terminal reports.
5148 int is_iconic(void *frontend)
5150 return IsIconic(hwnd);
5154 * Report the window's position, for terminal reports.
5156 void get_window_pos(void *frontend, int *x, int *y)
5159 GetWindowRect(hwnd, &r);
5165 * Report the window's pixel size, for terminal reports.
5167 void get_window_pixels(void *frontend, int *x, int *y)
5170 GetWindowRect(hwnd, &r);
5171 *x = r.right - r.left;
5172 *y = r.bottom - r.top;
5176 * Return the window or icon title.
5178 char *get_window_title(void *frontend, int icon)
5180 return icon ? icon_name : window_name;
5184 * See if we're in full-screen mode.
5186 static int is_full_screen()
5188 if (!IsZoomed(hwnd))
5190 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
5195 /* Get the rect/size of a full screen window using the nearest available
5196 * monitor in multimon systems; default to something sensible if only
5197 * one monitor is present. */
5198 static int get_fullscreen_rect(RECT * ss)
5200 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
5203 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
5204 mi.cbSize = sizeof(mi);
5205 GetMonitorInfo(mon, &mi);
5207 /* structure copy */
5211 /* could also use code like this:
5212 ss->left = ss->top = 0;
5213 ss->right = GetSystemMetrics(SM_CXSCREEN);
5214 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5216 return GetClientRect(GetDesktopWindow(), ss);
5222 * Go full-screen. This should only be called when we are already
5225 static void make_full_screen()
5230 assert(IsZoomed(hwnd));
5232 if (is_full_screen())
5235 /* Remove the window furniture. */
5236 style = GetWindowLongPtr(hwnd, GWL_STYLE);
5237 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5238 if (cfg.scrollbar_in_fullscreen)
5239 style |= WS_VSCROLL;
5241 style &= ~WS_VSCROLL;
5242 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5244 /* Resize ourselves to exactly cover the nearest monitor. */
5245 get_fullscreen_rect(&ss);
5246 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5251 /* We may have changed size as a result */
5255 /* Tick the menu item in the System menu. */
5256 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
5261 * Clear the full-screen attributes.
5263 static void clear_full_screen()
5265 DWORD oldstyle, style;
5267 /* Reinstate the window furniture. */
5268 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
5269 style |= WS_CAPTION | WS_BORDER;
5270 if (cfg.resize_action == RESIZE_DISABLED)
5271 style &= ~WS_THICKFRAME;
5273 style |= WS_THICKFRAME;
5275 style |= WS_VSCROLL;
5277 style &= ~WS_VSCROLL;
5278 if (style != oldstyle) {
5279 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5280 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5281 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5285 /* Untick the menu item in the System menu. */
5286 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
5291 * Toggle full-screen mode.
5293 static void flip_full_screen()
5295 if (is_full_screen()) {
5296 ShowWindow(hwnd, SW_RESTORE);
5297 } else if (IsZoomed(hwnd)) {
5300 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5301 ShowWindow(hwnd, SW_MAXIMIZE);
5305 void frontend_keypress(void *handle)
5308 * Keypress termination in non-Close-On-Exit mode is not
5309 * currently supported in PuTTY proper, because the window
5310 * always has a perfectly good Close button anyway. So we do
5316 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5318 return term_data(term, is_stderr, data, len);
5321 int from_backend_untrusted(void *frontend, const char *data, int len)
5323 return term_data_untrusted(term, data, len);
5326 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
5329 ret = cmdline_get_passwd_input(p, in, inlen);
5331 ret = term_get_userpass_input(term, p, in, inlen);
5335 void agent_schedule_callback(void (*callback)(void *, void *, int),
5336 void *callback_ctx, void *data, int len)
5338 struct agent_callback *c = snew(struct agent_callback);
5339 c->callback = callback;
5340 c->callback_ctx = callback_ctx;
5343 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);