7 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
15 #define COMPILE_MULTIMON_STUBS
25 #define IDM_SHOWLOG 0x0010
26 #define IDM_NEWSESS 0x0020
27 #define IDM_DUPSESS 0x0030
28 #define IDM_RESTART 0x0040
29 #define IDM_RECONF 0x0050
30 #define IDM_CLRSB 0x0060
31 #define IDM_RESET 0x0070
32 #define IDM_HELP 0x0140
33 #define IDM_ABOUT 0x0150
34 #define IDM_SAVEDSESS 0x0160
35 #define IDM_COPYALL 0x0170
36 #define IDM_FULLSCREEN 0x0180
37 #define IDM_PASTE 0x0190
39 #define IDM_SESSLGP 0x0250 /* log type printable */
40 #define IDM_SESSLGA 0x0260 /* log type all chars */
41 #define IDM_SESSLGE 0x0270 /* log end */
43 #define IDM_SPECIAL_MIN 0x0400
44 #define IDM_SPECIAL_MAX 0x0800
46 #define IDM_SAVED_MIN 0x1000
47 #define IDM_SAVED_MAX 0x2000
49 #define WM_IGNORE_CLIP (WM_XUSER + 2)
50 #define WM_FULLSCR_ON_MAX (WM_XUSER + 3)
51 #define WM_AGENT_CALLBACK (WM_XUSER + 4)
53 /* Needed for Chinese support and apparently not always defined. */
55 #define VK_PROCESSKEY 0xE5
58 /* Mouse wheel support. */
60 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
63 #define WHEEL_DELTA 120
66 static Mouse_Button translate_button(Mouse_Button button);
67 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
68 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
69 unsigned char *output);
70 static void cfgtopalette(void);
71 static void systopalette(void);
72 static void init_palette(void);
73 static void init_fonts(int, int);
74 static void another_font(int);
75 static void deinit_fonts(void);
76 static void set_input_locale(HKL);
78 static int is_full_screen(void);
79 static void make_full_screen(void);
80 static void clear_full_screen(void);
81 static void flip_full_screen(void);
83 /* Window layout information */
84 static void reset_window(int);
85 static int extra_width, extra_height;
86 static int font_width, font_height, font_dualwidth;
87 static int offset_width, offset_height;
88 static int was_zoomed = 0;
89 static int prev_rows, prev_cols;
91 static int pending_netevent = 0;
92 static WPARAM pend_netevent_wParam = 0;
93 static LPARAM pend_netevent_lParam = 0;
94 static void enact_pending_netevent(void);
95 static void flash_window(int mode);
96 static void sys_cursor_update(void);
97 static int is_shift_pressed(void);
98 static int get_fullscreen_rect(RECT * ss);
100 static time_t last_movement = 0;
102 static int caret_x = -1, caret_y = -1;
104 static int kbd_codepage;
107 static Backend *back;
108 static void *backhandle;
110 static struct unicode_data ucsdata;
111 static int session_closed;
113 static const struct telnet_special *specials;
114 static int n_specials;
118 int specials_submenu_pos;
120 enum { SYSMENU, CTXMENU };
122 Config cfg; /* exported to windlg.c */
124 extern struct sesslist sesslist; /* imported from windlg.c */
126 struct agent_callback {
127 void (*callback)(void *, void *, int);
133 #define FONT_NORMAL 0
135 #define FONT_UNDERLINE 2
136 #define FONT_BOLDUND 3
137 #define FONT_WIDE 0x04
138 #define FONT_HIGH 0x08
139 #define FONT_NARROW 0x10
141 #define FONT_OEM 0x20
142 #define FONT_OEMBOLD 0x21
143 #define FONT_OEMUND 0x22
144 #define FONT_OEMBOLDUND 0x23
146 #define FONT_MAXNO 0x2F
148 static HFONT fonts[FONT_MAXNO];
149 static LOGFONT lfont;
150 static int fontflag[FONT_MAXNO];
152 BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT
160 static COLORREF colours[NCOLOURS];
162 static LPLOGPALETTE logpal;
163 static RGBTRIPLE defpal[NCOLOURS];
167 static HBITMAP caretbm;
169 static int dbltime, lasttime, lastact;
170 static Mouse_Button lastbtn;
172 /* this allows xterm-style mouse handling. */
173 static int send_raw_mouse = 0;
174 static int wheel_accumulator = 0;
176 static char *window_name, *icon_name;
178 static int compose_state = 0;
180 static UINT wm_mousewheel = WM_MOUSEWHEEL;
182 /* Dummy routine, only required in plink. */
183 void ldisc_update(void *frontend, int echo, int edit)
187 static void start_backend(void)
190 char msg[1024], *title;
195 * Select protocol. This is farmed out into a table in a
196 * separate file to enable an ssh-free variant.
199 for (i = 0; backends[i].backend != NULL; i++)
200 if (backends[i].protocol == cfg.protocol) {
201 back = backends[i].backend;
205 char *str = dupprintf("%s Internal Error", appname);
206 MessageBox(NULL, "Unsupported protocol number found",
207 str, MB_OK | MB_ICONEXCLAMATION);
212 error = back->init(NULL, &backhandle, &cfg,
213 cfg.host, cfg.port, &realhost, cfg.tcp_nodelay,
215 back->provide_logctx(backhandle, logctx);
217 char *str = dupprintf("%s Error", appname);
218 sprintf(msg, "Unable to open connection to\n"
219 "%.800s\n" "%s", cfg.host, error);
220 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
224 window_name = icon_name = NULL;
226 title = cfg.wintitle;
228 sprintf(msg, "%s - %s", realhost, appname);
232 set_title(NULL, title);
233 set_icon(NULL, title);
236 * Connect the terminal to the backend for resize purposes.
238 term_provide_resize_fn(term, back->size, backhandle);
241 * Set up a line discipline.
243 ldisc = ldisc_create(&cfg, term, back, backhandle, NULL);
246 * Destroy the Restart Session menu item. (This will return
247 * failure if it's already absent, as it will be the very first
248 * time we call this function. We ignore that, because as long
249 * as the menu item ends up not being there, we don't care
250 * whether it was us who removed it or not!)
252 for (i = 0; i < lenof(popup_menus); i++) {
253 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
256 session_closed = FALSE;
259 static void close_session(void)
264 session_closed = TRUE;
265 sprintf(morestuff, "%.70s (inactive)", appname);
266 set_icon(NULL, morestuff);
267 set_title(NULL, morestuff);
274 back->free(backhandle);
277 update_specials_menu(NULL);
281 * Show the Restart Session menu item. Do a precautionary
282 * delete first to ensure we never end up with more than one.
284 for (i = 0; i < lenof(popup_menus); i++) {
285 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
286 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
287 IDM_RESTART, "&Restart Session");
291 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
295 int guess_width, guess_height;
298 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
302 InitCommonControls();
304 /* Ensure a Maximize setting in Explorer doesn't maximise the
310 char *str = dupprintf("%s Fatal Error", appname);
311 MessageBox(NULL, "Windows refuses to report a version",
312 str, MB_OK | MB_ICONEXCLAMATION);
318 * If we're running a version of Windows that doesn't support
319 * WM_MOUSEWHEEL, find out what message number we should be
322 if (osVersion.dwMajorVersion < 4 ||
323 (osVersion.dwMajorVersion == 4 &&
324 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
325 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
328 * See if we can find our Help file.
331 char b[2048], *p, *q, *r;
333 GetModuleFileName(NULL, b, sizeof(b) - 1);
335 p = strrchr(b, '\\');
336 if (p && p >= r) r = p+1;
338 if (q && q >= r) r = q+1;
339 strcpy(r, "putty.hlp");
340 if ( (fp = fopen(b, "r")) != NULL) {
341 help_path = dupstr(b);
345 strcpy(r, "putty.cnt");
346 if ( (fp = fopen(b, "r")) != NULL) {
347 help_has_contents = TRUE;
350 help_has_contents = FALSE;
354 * Process the command line.
360 default_protocol = be_default_protocol;
361 /* Find the appropriate default port. */
364 default_port = 0; /* illegal */
365 for (i = 0; backends[i].backend != NULL; i++)
366 if (backends[i].protocol == default_protocol) {
367 default_port = backends[i].backend->default_port;
371 cfg.logtype = LGTYP_NONE;
373 do_defaults(NULL, &cfg);
378 * Process a couple of command-line options which are more
379 * easily dealt with before the line is broken up into
380 * words. These are the soon-to-be-defunct @sessionname and
381 * the internal-use-only &sharedmemoryhandle, neither of
382 * which are combined with anything else.
384 while (*p && isspace(*p))
388 while (i > 1 && isspace(p[i - 1]))
391 do_defaults(p + 1, &cfg);
392 if (!*cfg.host && !do_config()) {
395 } else if (*p == '&') {
397 * An initial & means we've been given a command line
398 * containing the hex value of a HANDLE for a file
399 * mapping object, which we must then extract as a
404 if (sscanf(p + 1, "%p", &filemap) == 1 &&
405 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
406 0, 0, sizeof(Config))) != NULL) {
409 CloseHandle(filemap);
410 } else if (!do_config()) {
415 * Otherwise, break up the command line and deal with
421 split_into_argv(cmdline, &argc, &argv, NULL);
423 for (i = 0; i < argc; i++) {
427 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
430 cmdline_error("option \"%s\" requires an argument", p);
431 } else if (ret == 2) {
432 i++; /* skip next argument */
433 } else if (ret == 1) {
434 continue; /* nothing further needs doing */
435 } else if (!strcmp(p, "-cleanup")) {
437 * `putty -cleanup'. Remove all registry
438 * entries associated with PuTTY, and also find
439 * and delete the random seed file.
442 s1 = dupprintf("This procedure will remove ALL Registry\n"
443 "entries associated with %s, and will\n"
444 "also remove the random seed file.\n"
446 "THIS PROCESS WILL DESTROY YOUR SAVED\n"
447 "SESSIONS. Are you really sure you want\n"
448 "to continue?", appname);
449 s2 = dupprintf("%s Warning", appname);
450 if (MessageBox(NULL, s1, s2,
451 MB_YESNO | MB_ICONWARNING) == IDYES) {
457 } else if (*p != '-') {
461 * If we already have a host name, treat
462 * this argument as a port number. NB we
463 * have to treat this as a saved -P
464 * argument, so that it will be deferred
465 * until it's a good moment to run it.
467 int ret = cmdline_process_param("-P", p, 1, &cfg);
469 } else if (!strncmp(q, "telnet:", 7)) {
471 * If the hostname starts with "telnet:",
472 * set the protocol to Telnet and process
473 * the string as a Telnet URL.
478 if (q[0] == '/' && q[1] == '/')
480 cfg.protocol = PROT_TELNET;
482 while (*p && *p != ':' && *p != '/')
491 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
492 cfg.host[sizeof(cfg.host) - 1] = '\0';
496 * Otherwise, treat this argument as a host
499 while (*p && !isspace(*p))
503 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
504 cfg.host[sizeof(cfg.host) - 1] = '\0';
508 cmdline_error("unknown option \"%s\"", p);
513 cmdline_run_saved(&cfg);
515 if (!*cfg.host && !do_config()) {
520 * Trim leading whitespace off the hostname if it's there.
523 int space = strspn(cfg.host, " \t");
524 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
527 /* See if host is of the form user@host */
528 if (cfg.host[0] != '\0') {
529 char *atsign = strrchr(cfg.host, '@');
530 /* Make sure we're not overflowing the user field */
532 if (atsign - cfg.host < sizeof cfg.username) {
533 strncpy(cfg.username, cfg.host, atsign - cfg.host);
534 cfg.username[atsign - cfg.host] = '\0';
536 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
541 * Trim a colon suffix off the hostname if it's there.
543 cfg.host[strcspn(cfg.host, ":")] = '\0';
546 * Remove any remaining whitespace from the hostname.
550 while (cfg.host[p2] != '\0') {
551 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
552 cfg.host[p1] = cfg.host[p2];
561 /* Check for invalid Port number (i.e. zero) */
563 char *str = dupprintf("%s Internal Error", appname);
564 MessageBox(NULL, "Invalid Port Number",
565 str, MB_OK | MB_ICONEXCLAMATION);
572 wndclass.lpfnWndProc = WndProc;
573 wndclass.cbClsExtra = 0;
574 wndclass.cbWndExtra = 0;
575 wndclass.hInstance = inst;
576 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
577 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
578 wndclass.hbrBackground = NULL;
579 wndclass.lpszMenuName = NULL;
580 wndclass.lpszClassName = appname;
582 RegisterClass(&wndclass);
587 memset(&ucsdata, 0, sizeof(ucsdata));
589 term = term_init(&cfg, &ucsdata, NULL);
590 logctx = log_init(NULL, &cfg);
591 term_provide_logctx(term, logctx);
596 * Guess some defaults for the window size. This all gets
597 * updated later, so we don't really care too much. However, we
598 * do want the font width/height guesses to correspond to a
599 * large font rather than a small one...
606 term_size(term, cfg.height, cfg.width, cfg.savelines);
607 guess_width = extra_width + font_width * term->cols;
608 guess_height = extra_height + font_height * term->rows;
611 get_fullscreen_rect(&r);
612 if (guess_width > r.right - r.left)
613 guess_width = r.right - r.left;
614 if (guess_height > r.bottom - r.top)
615 guess_height = r.bottom - r.top;
619 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
622 winmode &= ~(WS_VSCROLL);
623 if (cfg.resize_action == RESIZE_DISABLED)
624 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
626 exwinmode |= WS_EX_TOPMOST;
628 exwinmode |= WS_EX_CLIENTEDGE;
629 hwnd = CreateWindowEx(exwinmode, appname, appname,
630 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
631 guess_width, guess_height,
632 NULL, NULL, inst, NULL);
636 * Initialise the fonts, simultaneously correcting the guesses
637 * for font_{width,height}.
642 * Correct the guesses for extra_{width,height}.
646 GetWindowRect(hwnd, &wr);
647 GetClientRect(hwnd, &cr);
648 offset_width = offset_height = cfg.window_border;
649 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
650 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
654 * Resize the window, now we know what size we _really_ want it
657 guess_width = extra_width + font_width * term->cols;
658 guess_height = extra_height + font_height * term->rows;
659 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
660 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
663 * Set up a caret bitmap, with no content.
667 int size = (font_width + 15) / 16 * 2 * font_height;
668 bits = snewn(size, char);
669 memset(bits, 0, size);
670 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
673 CreateCaret(hwnd, caretbm, font_width, font_height);
676 * Initialise the scroll bar.
681 si.cbSize = sizeof(si);
682 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
684 si.nMax = term->rows - 1;
685 si.nPage = term->rows;
687 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
691 * Prepare the mouse handler.
693 lastact = MA_NOTHING;
694 lastbtn = MBT_NOTHING;
695 dbltime = GetDoubleClickTime();
698 * Set up the session-control options on the system menu.
705 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
706 popup_menus[CTXMENU].menu = CreatePopupMenu();
707 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
710 get_sesslist(&sesslist, TRUE);
712 i < ((sesslist.nsessions < 256) ? sesslist.nsessions : 256);
714 AppendMenu(s, MF_ENABLED, IDM_SAVED_MIN + (16 * i),
715 sesslist.sessions[i]);
717 for (j = 0; j < lenof(popup_menus); j++) {
718 m = popup_menus[j].menu;
720 AppendMenu(m, MF_SEPARATOR, 0, 0);
721 popup_menus[j].specials_submenu_pos = GetMenuItemCount(m);
722 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
723 AppendMenu(m, MF_SEPARATOR, 0, 0);
724 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
725 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
726 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) s, "Sa&ved Sessions");
727 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
728 AppendMenu(m, MF_SEPARATOR, 0, 0);
729 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
730 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
731 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
732 AppendMenu(m, MF_SEPARATOR, 0, 0);
733 AppendMenu(m, (cfg.resize_action == RESIZE_DISABLED) ?
734 MF_GRAYED : MF_ENABLED, IDM_FULLSCREEN, "&Full Screen");
735 AppendMenu(m, MF_SEPARATOR, 0, 0);
737 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
738 str = dupprintf("&About %s", appname);
739 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
747 * Set up the initial input locale.
749 set_input_locale(GetKeyboardLayout(0));
752 * Open the initial log file if there is one.
757 * Finally show the window!
759 ShowWindow(hwnd, show);
760 SetForegroundWindow(hwnd);
763 * Set the palette up.
769 term->has_focus = (GetForegroundWindow() == hwnd);
772 if (GetMessage(&msg, NULL, 0, 0) == 1) {
773 int timer_id = 0, long_timer = 0;
775 while (msg.message != WM_QUIT) {
776 /* Sometimes DispatchMessage calls routines that use their own
777 * GetMessage loop, setup this timer so we get some control back.
779 * Also call term_update() from the timer so that if the host
780 * is sending data flat out we still do redraws.
782 if (timer_id && long_timer) {
783 KillTimer(hwnd, timer_id);
784 long_timer = timer_id = 0;
787 timer_id = SetTimer(hwnd, 1, 20, NULL);
788 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
789 DispatchMessage(&msg);
791 /* Make sure we blink everything that needs it. */
794 /* Send the paste buffer if there's anything to send */
797 /* If there's nothing new in the queue then we can do everything
798 * we've delayed, reading the socket, writing, and repainting
801 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
804 if (pending_netevent) {
805 enact_pending_netevent();
807 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
811 /* Okay there is now nothing to do so we make sure the screen is
812 * completely up to date then tell windows to call us in a little
816 KillTimer(hwnd, timer_id);
820 if (GetCapture() != hwnd ||
822 !(cfg.mouse_override && is_shift_pressed())))
827 flash_window(1); /* maintain */
829 /* The messages seem unreliable; especially if we're being tricky */
830 term->has_focus = (GetForegroundWindow() == hwnd);
833 /* Hmm, term_update didn't want to do an update too soon ... */
834 timer_id = SetTimer(hwnd, 1, 50, NULL);
835 else if (!term->has_focus)
836 timer_id = SetTimer(hwnd, 1, 500, NULL);
838 timer_id = SetTimer(hwnd, 1, 100, NULL);
841 /* There's no point rescanning everything in the message queue
842 * so we do an apparently unnecessary wait here
845 if (GetMessage(&msg, NULL, 0, 0) != 1)
850 cleanup_exit(msg.wParam); /* this doesn't return... */
851 return msg.wParam; /* ... but optimiser doesn't know */
857 void cleanup_exit(int code)
868 if (cfg.protocol == PROT_SSH) {
879 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
881 char *do_select(SOCKET skt, int startup)
886 events = (FD_CONNECT | FD_READ | FD_WRITE |
887 FD_OOB | FD_CLOSE | FD_ACCEPT);
892 return "do_select(): internal error (hwnd==NULL)";
893 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
894 switch (p_WSAGetLastError()) {
896 return "Network is down";
898 return "WSAAsyncSelect(): unknown error";
905 * Update the Special Commands submenu.
907 void update_specials_menu(void *frontend)
910 int menu_already_exists = (specials != NULL);
914 specials = back->get_specials(backhandle);
919 /* We can't use Windows to provide a stack for submenus, so
920 * here's a lame "stack" that will do for now. */
921 HMENU saved_menu = NULL;
923 p = CreatePopupMenu();
924 for (i = 0; nesting > 0; i++) {
925 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
926 switch (specials[i].code) {
928 AppendMenu(p, MF_SEPARATOR, 0, 0);
933 saved_menu = p; /* XXX lame stacking */
934 p = CreatePopupMenu();
935 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
936 (UINT) p, specials[i].name);
941 p = saved_menu; /* XXX lame stacking */
946 AppendMenu(p, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
951 /* Squirrel the highest special. */
958 for (j = 0; j < lenof(popup_menus); j++) {
959 if (menu_already_exists) {
960 /* XXX does this free up all submenus? */
961 DeleteMenu(popup_menus[j].menu,
962 popup_menus[j].specials_submenu_pos,
964 DeleteMenu(popup_menus[j].menu,
965 popup_menus[j].specials_submenu_pos,
969 InsertMenu(popup_menus[j].menu,
970 popup_menus[j].specials_submenu_pos,
971 MF_BYPOSITION | MF_SEPARATOR, 0, 0);
972 InsertMenu(popup_menus[j].menu,
973 popup_menus[j].specials_submenu_pos,
974 MF_BYPOSITION | MF_POPUP | MF_ENABLED,
975 (UINT) p, "S&pecial Command");
981 * set or clear the "raw mouse message" mode
983 void set_raw_mouse_mode(void *frontend, int activate)
985 activate = activate && !cfg.no_mouse_rep;
986 send_raw_mouse = activate;
987 SetCursor(LoadCursor(NULL, activate ? IDC_ARROW : IDC_IBEAM));
991 * Print a message box and close the connection.
993 void connection_fatal(void *frontend, char *fmt, ...)
996 char *stuff, morestuff[100];
999 stuff = dupvprintf(fmt, ap);
1001 sprintf(morestuff, "%.70s Fatal Error", appname);
1002 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1005 if (cfg.close_on_exit == FORCE_ON)
1013 * Report an error at the command-line parsing stage.
1015 void cmdline_error(char *fmt, ...)
1018 char *stuff, morestuff[100];
1021 stuff = dupvprintf(fmt, ap);
1023 sprintf(morestuff, "%.70s Command Line Error", appname);
1024 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1030 * Actually do the job requested by a WM_NETEVENT
1032 static void enact_pending_netevent(void)
1034 static int reentering = 0;
1035 extern int select_result(WPARAM, LPARAM);
1039 return; /* don't unpend the pending */
1041 pending_netevent = FALSE;
1044 ret = select_result(pend_netevent_wParam, pend_netevent_lParam);
1047 if (ret == 0 && !session_closed) {
1048 /* Abnormal exits will already have set session_closed and taken
1049 * appropriate action. */
1050 if (cfg.close_on_exit == FORCE_ON ||
1051 cfg.close_on_exit == AUTO) PostQuitMessage(0);
1054 session_closed = TRUE;
1055 MessageBox(hwnd, "Connection closed by remote host",
1056 appname, MB_OK | MB_ICONINFORMATION);
1062 * Copy the colour palette from the configuration data into defpal.
1063 * This is non-trivial because the colour indices are different.
1065 static void cfgtopalette(void)
1068 static const int ww[] = {
1069 6, 7, 8, 9, 10, 11, 12, 13,
1070 14, 15, 16, 17, 18, 19, 20, 21,
1071 0, 1, 2, 3, 4, 4, 5, 5
1074 for (i = 0; i < 24; i++) {
1076 defpal[i].rgbtRed = cfg.colours[w][0];
1077 defpal[i].rgbtGreen = cfg.colours[w][1];
1078 defpal[i].rgbtBlue = cfg.colours[w][2];
1081 /* Override with system colours if appropriate */
1082 if (cfg.system_colour)
1087 * Override bit of defpal with colours from the system.
1088 * (NB that this takes a copy the system colours at the time this is called,
1089 * so subsequent colour scheme changes don't take effect. To fix that we'd
1090 * probably want to be using GetSysColorBrush() and the like.)
1092 static void systopalette(void)
1095 static const struct { int nIndex; int norm; int bold; } or[] =
1097 { COLOR_WINDOWTEXT, 16, 17 }, /* Default Foreground */
1098 { COLOR_WINDOW, 18, 19 }, /* Default Background */
1099 { COLOR_HIGHLIGHTTEXT, 20, 21 }, /* Cursor Text */
1100 { COLOR_HIGHLIGHT, 22, 23 }, /* Cursor Colour */
1103 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1104 COLORREF colour = GetSysColor(or[i].nIndex);
1105 defpal[or[i].norm].rgbtRed =
1106 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1107 defpal[or[i].norm].rgbtGreen =
1108 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1109 defpal[or[i].norm].rgbtBlue =
1110 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1115 * Set up the colour palette.
1117 static void init_palette(void)
1120 HDC hdc = GetDC(hwnd);
1122 if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1124 * This is a genuine case where we must use smalloc
1125 * because the snew macros can't cope.
1127 logpal = smalloc(sizeof(*logpal)
1128 - sizeof(logpal->palPalEntry)
1129 + NCOLOURS * sizeof(PALETTEENTRY));
1130 logpal->palVersion = 0x300;
1131 logpal->palNumEntries = NCOLOURS;
1132 for (i = 0; i < NCOLOURS; i++) {
1133 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1134 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1135 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1136 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1138 pal = CreatePalette(logpal);
1140 SelectPalette(hdc, pal, FALSE);
1141 RealizePalette(hdc);
1142 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1145 ReleaseDC(hwnd, hdc);
1148 for (i = 0; i < NCOLOURS; i++)
1149 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1150 defpal[i].rgbtGreen,
1151 defpal[i].rgbtBlue);
1153 for (i = 0; i < NCOLOURS; i++)
1154 colours[i] = RGB(defpal[i].rgbtRed,
1155 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1159 * This is a wrapper to ExtTextOut() to force Windows to display
1160 * the precise glyphs we give it. Otherwise it would do its own
1161 * bidi and Arabic shaping, and we would end up uncertain which
1162 * characters it had put where.
1164 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1165 unsigned short *lpString, UINT cbCount,
1166 CONST INT *lpDx, int opaque)
1170 char *buffer = snewn(cbCount*2+2, char);
1171 char *classbuffer = snewn(cbCount, char);
1172 memset(&gcpr, 0, sizeof(gcpr));
1173 memset(buffer, 0, cbCount*2+2);
1174 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1176 gcpr.lStructSize = sizeof(gcpr);
1177 gcpr.lpGlyphs = (void *)buffer;
1178 gcpr.lpClass = classbuffer;
1179 gcpr.nGlyphs = cbCount;
1181 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1182 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1184 ExtTextOut(hdc, x, y,
1185 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1186 lprc, buffer, cbCount, lpDx);
1190 * Initialise all the fonts we will need initially. There may be as many as
1191 * three or as few as one. The other (poentially) twentyone fonts are done
1192 * if/when they are needed.
1196 * - check the font width and height, correcting our guesses if
1199 * - verify that the bold font is the same width as the ordinary
1200 * one, and engage shadow bolding if not.
1202 * - verify that the underlined font is the same width as the
1203 * ordinary one (manual underlining by means of line drawing can
1204 * be done in a pinch).
1206 static void init_fonts(int pick_width, int pick_height)
1213 int fw_dontcare, fw_bold;
1215 for (i = 0; i < FONT_MAXNO; i++)
1218 bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
1219 und_mode = UND_FONT;
1221 if (cfg.font.isbold) {
1222 fw_dontcare = FW_BOLD;
1225 fw_dontcare = FW_DONTCARE;
1232 font_height = pick_height;
1234 font_height = cfg.font.height;
1235 if (font_height > 0) {
1237 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1240 font_width = pick_width;
1242 #define f(i,c,w,u) \
1243 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1244 c, OUT_DEFAULT_PRECIS, \
1245 CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, \
1246 FIXED_PITCH | FF_DONTCARE, cfg.font.name)
1248 f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);
1250 lfont.lfHeight = font_height;
1251 lfont.lfWidth = font_width;
1252 lfont.lfEscapement = 0;
1253 lfont.lfOrientation = 0;
1254 lfont.lfWeight = fw_dontcare;
1255 lfont.lfItalic = FALSE;
1256 lfont.lfUnderline = FALSE;
1257 lfont.lfStrikeOut = FALSE;
1258 lfont.lfCharSet = cfg.font.charset;
1259 lfont.lfOutPrecision = OUT_DEFAULT_PRECIS;
1260 lfont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1261 lfont.lfQuality = DEFAULT_QUALITY;
1262 lfont.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE;
1263 strncpy(lfont.lfFaceName, cfg.font.name, LF_FACESIZE);
1265 SelectObject(hdc, fonts[FONT_NORMAL]);
1266 GetTextMetrics(hdc, &tm);
1268 if (pick_width == 0 || pick_height == 0) {
1269 font_height = tm.tmHeight;
1270 font_width = tm.tmAveCharWidth;
1272 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1274 #ifdef RDB_DEBUG_PATCH
1275 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1276 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1281 DWORD cset = tm.tmCharSet;
1282 memset(&info, 0xFF, sizeof(info));
1284 /* !!! Yes the next line is right */
1285 if (cset == OEM_CHARSET)
1286 ucsdata.font_codepage = GetOEMCP();
1288 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1289 ucsdata.font_codepage = info.ciACP;
1291 ucsdata.font_codepage = -1;
1293 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1294 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1297 f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);
1300 * Some fonts, e.g. 9-pt Courier, draw their underlines
1301 * outside their character cell. We successfully prevent
1302 * screen corruption by clipping the text output, but then
1303 * we lose the underline completely. Here we try to work
1304 * out whether this is such a font, and if it is, we set a
1305 * flag that causes underlines to be drawn by hand.
1307 * Having tried other more sophisticated approaches (such
1308 * as examining the TEXTMETRIC structure or requesting the
1309 * height of a string), I think we'll do this the brute
1310 * force way: we create a small bitmap, draw an underlined
1311 * space on it, and test to see whether any pixels are
1312 * foreground-coloured. (Since we expect the underline to
1313 * go all the way across the character cell, we only search
1314 * down a single column of the bitmap, half way across.)
1318 HBITMAP und_bm, und_oldbm;
1322 und_dc = CreateCompatibleDC(hdc);
1323 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1324 und_oldbm = SelectObject(und_dc, und_bm);
1325 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1326 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1327 SetTextColor(und_dc, RGB(255, 255, 255));
1328 SetBkColor(und_dc, RGB(0, 0, 0));
1329 SetBkMode(und_dc, OPAQUE);
1330 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1332 for (i = 0; i < font_height; i++) {
1333 c = GetPixel(und_dc, font_width / 2, i);
1334 if (c != RGB(0, 0, 0))
1337 SelectObject(und_dc, und_oldbm);
1338 DeleteObject(und_bm);
1341 und_mode = UND_LINE;
1342 DeleteObject(fonts[FONT_UNDERLINE]);
1343 fonts[FONT_UNDERLINE] = 0;
1347 if (bold_mode == BOLD_FONT) {
1348 f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);
1352 descent = tm.tmAscent + 1;
1353 if (descent >= font_height)
1354 descent = font_height - 1;
1356 for (i = 0; i < 3; i++) {
1358 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1359 fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
1366 ReleaseDC(hwnd, hdc);
1368 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1369 und_mode = UND_LINE;
1370 DeleteObject(fonts[FONT_UNDERLINE]);
1371 fonts[FONT_UNDERLINE] = 0;
1374 if (bold_mode == BOLD_FONT &&
1375 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1376 bold_mode = BOLD_SHADOW;
1377 DeleteObject(fonts[FONT_BOLD]);
1378 fonts[FONT_BOLD] = 0;
1380 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1382 init_ucs(&cfg, &ucsdata);
1385 static void another_font(int fontno)
1388 int fw_dontcare, fw_bold;
1392 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1395 basefont = (fontno & ~(FONT_BOLDUND));
1396 if (basefont != fontno && !fontflag[basefont])
1397 another_font(basefont);
1399 if (cfg.font.isbold) {
1400 fw_dontcare = FW_BOLD;
1403 fw_dontcare = FW_DONTCARE;
1407 c = cfg.font.charset;
1413 if (fontno & FONT_WIDE)
1415 if (fontno & FONT_NARROW)
1417 if (fontno & FONT_OEM)
1419 if (fontno & FONT_BOLD)
1421 if (fontno & FONT_UNDERLINE)
1425 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1426 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1427 CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
1428 FIXED_PITCH | FF_DONTCARE, s);
1430 fontflag[fontno] = 1;
1433 static void deinit_fonts(void)
1436 for (i = 0; i < FONT_MAXNO; i++) {
1438 DeleteObject(fonts[i]);
1444 void request_resize(void *frontend, int w, int h)
1448 /* If the window is maximized supress resizing attempts */
1449 if (IsZoomed(hwnd)) {
1450 if (cfg.resize_action == RESIZE_TERM)
1454 if (cfg.resize_action == RESIZE_DISABLED) return;
1455 if (h == term->rows && w == term->cols) return;
1457 /* Sanity checks ... */
1459 static int first_time = 1;
1462 switch (first_time) {
1464 /* Get the size of the screen */
1465 if (get_fullscreen_rect(&ss))
1466 /* first_time = 0 */ ;
1472 /* Make sure the values are sane */
1473 width = (ss.right - ss.left - extra_width) / 4;
1474 height = (ss.bottom - ss.top - extra_height) / 6;
1476 if (w > width || h > height)
1485 term_size(term, h, w, cfg.savelines);
1487 if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {
1488 width = extra_width + font_width * w;
1489 height = extra_height + font_height * h;
1491 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1492 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1493 SWP_NOMOVE | SWP_NOZORDER);
1497 InvalidateRect(hwnd, NULL, TRUE);
1500 static void reset_window(int reinit) {
1502 * This function decides how to resize or redraw when the
1503 * user changes something.
1505 * This function doesn't like to change the terminal size but if the
1506 * font size is locked that may be it's only soluion.
1508 int win_width, win_height;
1511 #ifdef RDB_DEBUG_PATCH
1512 debug((27, "reset_window()"));
1515 /* Current window sizes ... */
1516 GetWindowRect(hwnd, &wr);
1517 GetClientRect(hwnd, &cr);
1519 win_width = cr.right - cr.left;
1520 win_height = cr.bottom - cr.top;
1522 if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;
1524 /* Are we being forced to reload the fonts ? */
1526 #ifdef RDB_DEBUG_PATCH
1527 debug((27, "reset_window() -- Forced deinit"));
1533 /* Oh, looks like we're minimised */
1534 if (win_width == 0 || win_height == 0)
1537 /* Is the window out of position ? */
1539 (offset_width != (win_width-font_width*term->cols)/2 ||
1540 offset_height != (win_height-font_height*term->rows)/2) ){
1541 offset_width = (win_width-font_width*term->cols)/2;
1542 offset_height = (win_height-font_height*term->rows)/2;
1543 InvalidateRect(hwnd, NULL, TRUE);
1544 #ifdef RDB_DEBUG_PATCH
1545 debug((27, "reset_window() -> Reposition terminal"));
1549 if (IsZoomed(hwnd)) {
1550 /* We're fullscreen, this means we must not change the size of
1551 * the window so it's the font size or the terminal itself.
1554 extra_width = wr.right - wr.left - cr.right + cr.left;
1555 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1557 if (cfg.resize_action != RESIZE_TERM) {
1558 if ( font_width != win_width/term->cols ||
1559 font_height != win_height/term->rows) {
1561 init_fonts(win_width/term->cols, win_height/term->rows);
1562 offset_width = (win_width-font_width*term->cols)/2;
1563 offset_height = (win_height-font_height*term->rows)/2;
1564 InvalidateRect(hwnd, NULL, TRUE);
1565 #ifdef RDB_DEBUG_PATCH
1566 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1567 font_width, font_height));
1571 if ( font_width != win_width/term->cols ||
1572 font_height != win_height/term->rows) {
1573 /* Our only choice at this point is to change the
1574 * size of the terminal; Oh well.
1576 term_size(term, win_height/font_height, win_width/font_width,
1578 offset_width = (win_width-font_width*term->cols)/2;
1579 offset_height = (win_height-font_height*term->rows)/2;
1580 InvalidateRect(hwnd, NULL, TRUE);
1581 #ifdef RDB_DEBUG_PATCH
1582 debug((27, "reset_window() -> Zoomed term_size"));
1589 /* Hmm, a force re-init means we should ignore the current window
1590 * so we resize to the default font size.
1593 #ifdef RDB_DEBUG_PATCH
1594 debug((27, "reset_window() -> Forced re-init"));
1597 offset_width = offset_height = cfg.window_border;
1598 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1599 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1601 if (win_width != font_width*term->cols + offset_width*2 ||
1602 win_height != font_height*term->rows + offset_height*2) {
1604 /* If this is too large windows will resize it to the maximum
1605 * allowed window size, we will then be back in here and resize
1606 * the font or terminal to fit.
1608 SetWindowPos(hwnd, NULL, 0, 0,
1609 font_width*term->cols + extra_width,
1610 font_height*term->rows + extra_height,
1611 SWP_NOMOVE | SWP_NOZORDER);
1614 InvalidateRect(hwnd, NULL, TRUE);
1618 /* Okay the user doesn't want us to change the font so we try the
1619 * window. But that may be too big for the screen which forces us
1620 * to change the terminal.
1622 if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||
1623 (cfg.resize_action == RESIZE_EITHER && reinit<0) ||
1625 offset_width = offset_height = cfg.window_border;
1626 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1627 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1629 if (win_width != font_width*term->cols + offset_width*2 ||
1630 win_height != font_height*term->rows + offset_height*2) {
1635 get_fullscreen_rect(&ss);
1637 width = (ss.right - ss.left - extra_width) / font_width;
1638 height = (ss.bottom - ss.top - extra_height) / font_height;
1641 if ( term->rows > height || term->cols > width ) {
1642 if (cfg.resize_action == RESIZE_EITHER) {
1643 /* Make the font the biggest we can */
1644 if (term->cols > width)
1645 font_width = (ss.right - ss.left - extra_width)
1647 if (term->rows > height)
1648 font_height = (ss.bottom - ss.top - extra_height)
1652 init_fonts(font_width, font_height);
1654 width = (ss.right - ss.left - extra_width) / font_width;
1655 height = (ss.bottom - ss.top - extra_height) / font_height;
1657 if ( height > term->rows ) height = term->rows;
1658 if ( width > term->cols ) width = term->cols;
1659 term_size(term, height, width, cfg.savelines);
1660 #ifdef RDB_DEBUG_PATCH
1661 debug((27, "reset_window() -> term resize to (%d,%d)",
1667 SetWindowPos(hwnd, NULL, 0, 0,
1668 font_width*term->cols + extra_width,
1669 font_height*term->rows + extra_height,
1670 SWP_NOMOVE | SWP_NOZORDER);
1672 InvalidateRect(hwnd, NULL, TRUE);
1673 #ifdef RDB_DEBUG_PATCH
1674 debug((27, "reset_window() -> window resize to (%d,%d)",
1675 font_width*term->cols + extra_width,
1676 font_height*term->rows + extra_height));
1682 /* We're allowed to or must change the font but do we want to ? */
1684 if (font_width != (win_width-cfg.window_border*2)/term->cols ||
1685 font_height != (win_height-cfg.window_border*2)/term->rows) {
1688 init_fonts((win_width-cfg.window_border*2)/term->cols,
1689 (win_height-cfg.window_border*2)/term->rows);
1690 offset_width = (win_width-font_width*term->cols)/2;
1691 offset_height = (win_height-font_height*term->rows)/2;
1693 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1694 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1696 InvalidateRect(hwnd, NULL, TRUE);
1697 #ifdef RDB_DEBUG_PATCH
1698 debug((25, "reset_window() -> font resize to (%d,%d)",
1699 font_width, font_height));
1704 static void set_input_locale(HKL kl)
1708 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1709 lbuf, sizeof(lbuf));
1711 kbd_codepage = atoi(lbuf);
1714 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1716 int thistime = GetMessageTime();
1718 if (send_raw_mouse && !(cfg.mouse_override && shift)) {
1719 lastbtn = MBT_NOTHING;
1720 term_mouse(term, b, translate_button(b), MA_CLICK,
1721 x, y, shift, ctrl, alt);
1725 if (lastbtn == b && thistime - lasttime < dbltime) {
1726 lastact = (lastact == MA_CLICK ? MA_2CLK :
1727 lastact == MA_2CLK ? MA_3CLK :
1728 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1733 if (lastact != MA_NOTHING)
1734 term_mouse(term, b, translate_button(b), lastact,
1735 x, y, shift, ctrl, alt);
1736 lasttime = thistime;
1740 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1741 * into a cooked one (SELECT, EXTEND, PASTE).
1743 static Mouse_Button translate_button(Mouse_Button button)
1745 if (button == MBT_LEFT)
1747 if (button == MBT_MIDDLE)
1748 return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
1749 if (button == MBT_RIGHT)
1750 return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
1751 return 0; /* shouldn't happen */
1754 static void show_mouseptr(int show)
1756 static int cursor_visible = 1;
1757 if (!cfg.hide_mouseptr) /* override if this feature disabled */
1759 if (cursor_visible && !show)
1761 else if (!cursor_visible && show)
1763 cursor_visible = show;
1766 static int is_alt_pressed(void)
1769 int r = GetKeyboardState(keystate);
1772 if (keystate[VK_MENU] & 0x80)
1774 if (keystate[VK_RMENU] & 0x80)
1779 static int is_shift_pressed(void)
1782 int r = GetKeyboardState(keystate);
1785 if (keystate[VK_SHIFT] & 0x80)
1790 static int resizing;
1792 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1793 WPARAM wParam, LPARAM lParam)
1796 static int ignore_clip = FALSE;
1797 static int need_backend_resize = FALSE;
1798 static int fullscr_on_max = FALSE;
1799 static UINT last_mousemove = 0;
1803 if (pending_netevent)
1804 enact_pending_netevent();
1805 if (GetCapture() != hwnd ||
1806 (send_raw_mouse && !(cfg.mouse_override && is_shift_pressed())))
1812 if (cfg.ping_interval > 0) {
1815 if (now - last_movement > cfg.ping_interval) {
1817 back->special(backhandle, TS_PING);
1818 last_movement = now;
1821 net_pending_errors();
1829 str = dupprintf("%s Exit Confirmation", appname);
1830 if (!cfg.warn_on_close || session_closed ||
1832 "Are you sure you want to close this session?",
1833 str, MB_ICONWARNING | MB_OKCANCEL) == IDOK)
1834 DestroyWindow(hwnd);
1844 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
1856 PROCESS_INFORMATION pi;
1857 HANDLE filemap = NULL;
1859 if (wParam == IDM_DUPSESS) {
1861 * Allocate a file-mapping memory chunk for the
1864 SECURITY_ATTRIBUTES sa;
1867 sa.nLength = sizeof(sa);
1868 sa.lpSecurityDescriptor = NULL;
1869 sa.bInheritHandle = TRUE;
1870 filemap = CreateFileMapping((HANDLE) 0xFFFFFFFF,
1873 0, sizeof(Config), NULL);
1875 p = (Config *) MapViewOfFile(filemap,
1877 0, 0, sizeof(Config));
1879 *p = cfg; /* structure copy */
1883 sprintf(c, "putty &%p", filemap);
1885 } else if (wParam == IDM_SAVEDSESS) {
1886 if ((lParam - IDM_SAVED_MIN) / 16 < sesslist.nsessions) {
1888 sesslist.sessions[(lParam - IDM_SAVED_MIN) / 16];
1889 cl = snewn(16 + strlen(session), char);
1890 /* 8, but play safe */
1893 /* not a very important failure mode */
1895 sprintf(cl, "putty @%s", session);
1903 GetModuleFileName(NULL, b, sizeof(b) - 1);
1905 si.lpReserved = NULL;
1906 si.lpDesktop = NULL;
1910 si.lpReserved2 = NULL;
1911 CreateProcess(b, cl, NULL, NULL, TRUE,
1912 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
1915 CloseHandle(filemap);
1922 logevent(NULL, "----- Session restarted -----");
1932 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
1935 if (!do_reconfig(hwnd))
1939 /* Disable full-screen if resizing forbidden */
1940 HMENU m = GetSystemMenu (hwnd, FALSE);
1941 EnableMenuItem(m, IDM_FULLSCREEN, MF_BYCOMMAND |
1942 (cfg.resize_action == RESIZE_DISABLED)
1943 ? MF_GRAYED : MF_ENABLED);
1944 /* Gracefully unzoom if necessary */
1945 if (IsZoomed(hwnd) &&
1946 (cfg.resize_action == RESIZE_DISABLED)) {
1947 ShowWindow(hwnd, SW_RESTORE);
1951 /* Pass new config data to the logging module */
1952 log_reconfig(logctx, &cfg);
1956 * Flush the line discipline's edit buffer in the
1957 * case where local editing has just been disabled.
1960 ldisc_send(ldisc, NULL, 0, 0);
1968 /* Pass new config data to the terminal */
1969 term_reconfig(term, &cfg);
1971 /* Pass new config data to the back end */
1973 back->reconfig(backhandle, &cfg);
1975 /* Screen size changed ? */
1976 if (cfg.height != prev_cfg.height ||
1977 cfg.width != prev_cfg.width ||
1978 cfg.savelines != prev_cfg.savelines ||
1979 cfg.resize_action == RESIZE_FONT ||
1980 (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
1981 cfg.resize_action == RESIZE_DISABLED)
1982 term_size(term, cfg.height, cfg.width, cfg.savelines);
1984 /* Enable or disable the scroll bar, etc */
1986 LONG nflg, flag = GetWindowLong(hwnd, GWL_STYLE);
1987 LONG nexflag, exflag =
1988 GetWindowLong(hwnd, GWL_EXSTYLE);
1991 if (cfg.alwaysontop != prev_cfg.alwaysontop) {
1992 if (cfg.alwaysontop) {
1993 nexflag |= WS_EX_TOPMOST;
1994 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
1995 SWP_NOMOVE | SWP_NOSIZE);
1997 nexflag &= ~(WS_EX_TOPMOST);
1998 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
1999 SWP_NOMOVE | SWP_NOSIZE);
2002 if (cfg.sunken_edge)
2003 nexflag |= WS_EX_CLIENTEDGE;
2005 nexflag &= ~(WS_EX_CLIENTEDGE);
2008 if (is_full_screen() ?
2009 cfg.scrollbar_in_fullscreen : cfg.scrollbar)
2012 nflg &= ~WS_VSCROLL;
2014 if (cfg.resize_action == RESIZE_DISABLED ||
2016 nflg &= ~WS_THICKFRAME;
2018 nflg |= WS_THICKFRAME;
2020 if (cfg.resize_action == RESIZE_DISABLED)
2021 nflg &= ~WS_MAXIMIZEBOX;
2023 nflg |= WS_MAXIMIZEBOX;
2025 if (nflg != flag || nexflag != exflag) {
2027 SetWindowLong(hwnd, GWL_STYLE, nflg);
2028 if (nexflag != exflag)
2029 SetWindowLong(hwnd, GWL_EXSTYLE, nexflag);
2031 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2032 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2033 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2041 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2046 set_title(NULL, cfg.wintitle);
2047 if (IsIconic(hwnd)) {
2049 cfg.win_name_always ? window_name :
2053 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
2054 strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
2055 cfg.font.isbold != prev_cfg.font.isbold ||
2056 cfg.font.height != prev_cfg.font.height ||
2057 cfg.font.charset != prev_cfg.font.charset ||
2058 cfg.vtmode != prev_cfg.vtmode ||
2059 cfg.bold_colour != prev_cfg.bold_colour ||
2060 cfg.resize_action == RESIZE_DISABLED ||
2061 cfg.resize_action == RESIZE_EITHER ||
2062 (cfg.resize_action != prev_cfg.resize_action))
2065 InvalidateRect(hwnd, NULL, TRUE);
2066 reset_window(init_lvl);
2067 net_pending_errors();
2074 term_do_paste(term);
2082 ldisc_send(ldisc, NULL, 0, 0);
2088 WinHelp(hwnd, help_path,
2089 help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
2093 * We get this if the System menu has been activated
2100 * We get this if the System menu has been activated
2101 * using the keyboard. This might happen from within
2102 * TranslateKey, in which case it really wants to be
2103 * followed by a `space' character to actually _bring
2104 * the menu up_ rather than just sitting there in
2105 * `ready to appear' state.
2107 show_mouseptr(1); /* make sure pointer is visible */
2109 PostMessage(hwnd, WM_CHAR, ' ', 0);
2111 case IDM_FULLSCREEN:
2115 if (wParam >= IDM_SAVED_MIN && wParam <= IDM_SAVED_MAX) {
2116 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2118 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2119 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2121 * Ensure we haven't been sent a bogus SYSCOMMAND
2122 * which would cause us to reference invalid memory
2123 * and crash. Perhaps I'm just too paranoid here.
2125 if (i >= n_specials)
2128 back->special(backhandle, specials[i].code);
2129 net_pending_errors();
2134 #define X_POS(l) ((int)(short)LOWORD(l))
2135 #define Y_POS(l) ((int)(short)HIWORD(l))
2137 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2138 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2139 case WM_LBUTTONDOWN:
2140 case WM_MBUTTONDOWN:
2141 case WM_RBUTTONDOWN:
2145 if (message == WM_RBUTTONDOWN &&
2146 ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
2149 show_mouseptr(1); /* make sure pointer is visible */
2150 GetCursorPos(&cursorpos);
2151 TrackPopupMenu(popup_menus[CTXMENU].menu,
2152 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2153 cursorpos.x, cursorpos.y,
2161 case WM_LBUTTONDOWN:
2165 case WM_MBUTTONDOWN:
2166 button = MBT_MIDDLE;
2169 case WM_RBUTTONDOWN:
2178 button = MBT_MIDDLE;
2186 button = press = 0; /* shouldn't happen */
2190 * Special case: in full-screen mode, if the left
2191 * button is clicked in the very top left corner of the
2192 * window, we put up the System menu instead of doing
2196 char mouse_on_hotspot = 0;
2205 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2208 mi.cbSize = sizeof(MONITORINFO);
2209 GetMonitorInfo(mon, &mi);
2211 if (mi.rcMonitor.left == pt.x &&
2212 mi.rcMonitor.top == pt.y) {
2213 mouse_on_hotspot = 1;
2218 if (pt.x == 0 && pt.y == 0) {
2219 mouse_on_hotspot = 1;
2222 if (is_full_screen() && press &&
2223 button == MBT_LEFT && mouse_on_hotspot) {
2224 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2225 MAKELPARAM(pt.x, pt.y));
2232 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2233 wParam & MK_SHIFT, wParam & MK_CONTROL,
2237 term_mouse(term, button, translate_button(button), MA_RELEASE,
2238 TO_CHR_X(X_POS(lParam)),
2239 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2240 wParam & MK_CONTROL, is_alt_pressed());
2248 * Windows seems to like to occasionally send MOUSEMOVE
2249 * events even if the mouse hasn't moved. Don't unhide
2250 * the mouse pointer in this case.
2252 static WPARAM wp = 0;
2253 static LPARAM lp = 0;
2254 if (wParam != wp || lParam != lp ||
2255 last_mousemove != WM_MOUSEMOVE) {
2257 wp = wParam; lp = lParam;
2258 last_mousemove = WM_MOUSEMOVE;
2262 * Add the mouse position and message time to the random
2265 noise_ultralight(lParam);
2267 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2268 GetCapture() == hwnd) {
2270 if (wParam & MK_LBUTTON)
2272 else if (wParam & MK_MBUTTON)
2276 term_mouse(term, b, translate_button(b), MA_DRAG,
2277 TO_CHR_X(X_POS(lParam)),
2278 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2279 wParam & MK_CONTROL, is_alt_pressed());
2282 case WM_NCMOUSEMOVE:
2284 static WPARAM wp = 0;
2285 static LPARAM lp = 0;
2286 if (wParam != wp || lParam != lp ||
2287 last_mousemove != WM_NCMOUSEMOVE) {
2289 wp = wParam; lp = lParam;
2290 last_mousemove = WM_NCMOUSEMOVE;
2293 noise_ultralight(lParam);
2295 case WM_IGNORE_CLIP:
2296 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2298 case WM_DESTROYCLIPBOARD:
2300 term_deselect(term);
2301 ignore_clip = FALSE;
2307 hdc = BeginPaint(hwnd, &p);
2309 SelectPalette(hdc, pal, TRUE);
2310 RealizePalette(hdc);
2312 term_paint(term, hdc,
2313 (p.rcPaint.left-offset_width)/font_width,
2314 (p.rcPaint.top-offset_height)/font_height,
2315 (p.rcPaint.right-offset_width-1)/font_width,
2316 (p.rcPaint.bottom-offset_height-1)/font_height,
2320 p.rcPaint.left < offset_width ||
2321 p.rcPaint.top < offset_height ||
2322 p.rcPaint.right >= offset_width + font_width*term->cols ||
2323 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2325 HBRUSH fillcolour, oldbrush;
2327 fillcolour = CreateSolidBrush (
2328 colours[(ATTR_DEFBG>>ATTR_BGSHIFT)*2]);
2329 oldbrush = SelectObject(hdc, fillcolour);
2330 edge = CreatePen(PS_SOLID, 0,
2331 colours[(ATTR_DEFBG>>ATTR_BGSHIFT)*2]);
2332 oldpen = SelectObject(hdc, edge);
2335 * Jordan Russell reports that this apparently
2336 * ineffectual IntersectClipRect() call masks a
2337 * Windows NT/2K bug causing strange display
2338 * problems when the PuTTY window is taller than
2339 * the primary monitor. It seems harmless enough...
2341 IntersectClipRect(hdc,
2342 p.rcPaint.left, p.rcPaint.top,
2343 p.rcPaint.right, p.rcPaint.bottom);
2345 ExcludeClipRect(hdc,
2346 offset_width, offset_height,
2347 offset_width+font_width*term->cols,
2348 offset_height+font_height*term->rows);
2350 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2351 p.rcPaint.right, p.rcPaint.bottom);
2353 // SelectClipRgn(hdc, NULL);
2355 SelectObject(hdc, oldbrush);
2356 DeleteObject(fillcolour);
2357 SelectObject(hdc, oldpen);
2360 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2361 SelectObject(hdc, GetStockObject(WHITE_PEN));
2367 /* Notice we can get multiple netevents, FD_READ, FD_WRITE etc
2368 * but the only one that's likely to try to overload us is FD_READ.
2369 * This means buffering just one is fine.
2371 if (pending_netevent)
2372 enact_pending_netevent();
2374 pending_netevent = TRUE;
2375 pend_netevent_wParam = wParam;
2376 pend_netevent_lParam = lParam;
2377 if (WSAGETSELECTEVENT(lParam) != FD_READ)
2378 enact_pending_netevent();
2380 time(&last_movement);
2383 term->has_focus = TRUE;
2384 CreateCaret(hwnd, caretbm, font_width, font_height);
2386 flash_window(0); /* stop */
2393 term->has_focus = FALSE;
2395 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2399 case WM_ENTERSIZEMOVE:
2400 #ifdef RDB_DEBUG_PATCH
2401 debug((27, "WM_ENTERSIZEMOVE"));
2405 need_backend_resize = FALSE;
2407 case WM_EXITSIZEMOVE:
2410 #ifdef RDB_DEBUG_PATCH
2411 debug((27, "WM_EXITSIZEMOVE"));
2413 if (need_backend_resize) {
2414 term_size(term, cfg.height, cfg.width, cfg.savelines);
2415 InvalidateRect(hwnd, NULL, TRUE);
2420 * This does two jobs:
2421 * 1) Keep the sizetip uptodate
2422 * 2) Make sure the window size is _stepped_ in units of the font size.
2424 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2425 int width, height, w, h, ew, eh;
2426 LPRECT r = (LPRECT) lParam;
2428 if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
2429 (cfg.height != term->rows || cfg.width != term->cols )) {
2431 * Great! It seems that both the terminal size and the
2432 * font size have been changed and the user is now dragging.
2434 * It will now be difficult to get back to the configured
2437 * This would be easier but it seems to be too confusing.
2439 term_size(term, cfg.height, cfg.width, cfg.savelines);
2442 cfg.height=term->rows; cfg.width=term->cols;
2444 InvalidateRect(hwnd, NULL, TRUE);
2445 need_backend_resize = TRUE;
2448 width = r->right - r->left - extra_width;
2449 height = r->bottom - r->top - extra_height;
2450 w = (width + font_width / 2) / font_width;
2453 h = (height + font_height / 2) / font_height;
2456 UpdateSizeTip(hwnd, w, h);
2457 ew = width - w * font_width;
2458 eh = height - h * font_height;
2460 if (wParam == WMSZ_LEFT ||
2461 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2467 if (wParam == WMSZ_TOP ||
2468 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2478 int width, height, w, h, rv = 0;
2479 int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2480 int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2481 LPRECT r = (LPRECT) lParam;
2483 width = r->right - r->left - ex_width;
2484 height = r->bottom - r->top - ex_height;
2486 w = (width + term->cols/2)/term->cols;
2487 h = (height + term->rows/2)/term->rows;
2488 if ( r->right != r->left + w*term->cols + ex_width)
2491 if (wParam == WMSZ_LEFT ||
2492 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2493 r->left = r->right - w*term->cols - ex_width;
2495 r->right = r->left + w*term->cols + ex_width;
2497 if (r->bottom != r->top + h*term->rows + ex_height)
2500 if (wParam == WMSZ_TOP ||
2501 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2502 r->top = r->bottom - h*term->rows - ex_height;
2504 r->bottom = r->top + h*term->rows + ex_height;
2508 /* break; (never reached) */
2509 case WM_FULLSCR_ON_MAX:
2510 fullscr_on_max = TRUE;
2513 sys_cursor_update();
2516 #ifdef RDB_DEBUG_PATCH
2517 debug((27, "WM_SIZE %s (%d,%d)",
2518 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2519 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2520 (wParam == SIZE_RESTORED && resizing) ? "to":
2521 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2523 LOWORD(lParam), HIWORD(lParam)));
2525 if (wParam == SIZE_MINIMIZED)
2527 cfg.win_name_always ? window_name : icon_name);
2528 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2529 SetWindowText(hwnd, window_name);
2530 if (wParam == SIZE_RESTORED)
2531 clear_full_screen();
2532 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2533 fullscr_on_max = FALSE;
2537 if (cfg.resize_action == RESIZE_DISABLED) {
2538 /* A resize, well it better be a minimize. */
2542 int width, height, w, h;
2544 width = LOWORD(lParam);
2545 height = HIWORD(lParam);
2548 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2550 prev_rows = term->rows;
2551 prev_cols = term->cols;
2552 if (cfg.resize_action == RESIZE_TERM) {
2553 w = width / font_width;
2555 h = height / font_height;
2558 term_size(term, h, w, cfg.savelines);
2561 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2563 if (cfg.resize_action == RESIZE_TERM)
2564 term_size(term, prev_rows, prev_cols, cfg.savelines);
2565 if (cfg.resize_action != RESIZE_FONT)
2570 /* This is an unexpected resize, these will normally happen
2571 * if the window is too large. Probably either the user
2572 * selected a huge font or the screen size has changed.
2574 * This is also called with minimize.
2576 else reset_window(-1);
2580 * Don't call back->size in mid-resize. (To prevent
2581 * massive numbers of resize events getting sent
2582 * down the connection during an NT opaque drag.)
2585 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2586 need_backend_resize = TRUE;
2587 w = (width-cfg.window_border*2) / font_width;
2589 h = (height-cfg.window_border*2) / font_height;
2598 sys_cursor_update();
2601 switch (LOWORD(wParam)) {
2603 term_scroll(term, -1, 0);
2606 term_scroll(term, +1, 0);
2609 term_scroll(term, 0, +1);
2612 term_scroll(term, 0, -1);
2615 term_scroll(term, 0, +term->rows / 2);
2618 term_scroll(term, 0, -term->rows / 2);
2620 case SB_THUMBPOSITION:
2622 term_scroll(term, 1, HIWORD(wParam));
2626 case WM_PALETTECHANGED:
2627 if ((HWND) wParam != hwnd && pal != NULL) {
2628 HDC hdc = get_ctx(NULL);
2630 if (RealizePalette(hdc) > 0)
2636 case WM_QUERYNEWPALETTE:
2638 HDC hdc = get_ctx(NULL);
2640 if (RealizePalette(hdc) > 0)
2652 * Add the scan code and keypress timing to the random
2655 noise_ultralight(lParam);
2658 * We don't do TranslateMessage since it disassociates the
2659 * resulting CHAR message from the KEYDOWN that sparked it,
2660 * which we occasionally don't want. Instead, we process
2661 * KEYDOWN, and call the Win32 translator functions so that
2662 * we get the translations under _our_ control.
2665 unsigned char buf[20];
2668 if (wParam == VK_PROCESSKEY) {
2671 m.message = WM_KEYDOWN;
2673 m.lParam = lParam & 0xdfff;
2674 TranslateMessage(&m);
2676 len = TranslateKey(message, wParam, lParam, buf);
2678 return DefWindowProc(hwnd, message, wParam, lParam);
2682 * Interrupt an ongoing paste. I'm not sure
2683 * this is sensible, but for the moment it's
2684 * preferable to having to faff about buffering
2690 * We need not bother about stdin backlogs
2691 * here, because in GUI PuTTY we can't do
2692 * anything about it anyway; there's no means
2693 * of asking Windows to hold off on KEYDOWN
2694 * messages. We _have_ to buffer everything
2697 term_seen_key_event(term);
2699 ldisc_send(ldisc, buf, len, 1);
2704 net_pending_errors();
2706 case WM_INPUTLANGCHANGE:
2707 /* wParam == Font number */
2708 /* lParam == Locale */
2709 set_input_locale((HKL)lParam);
2710 sys_cursor_update();
2713 if(wParam == IMN_SETOPENSTATUS) {
2714 HIMC hImc = ImmGetContext(hwnd);
2715 ImmSetCompositionFont(hImc, &lfont);
2716 ImmReleaseContext(hwnd, hImc);
2720 case WM_IME_COMPOSITION:
2726 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
2727 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2729 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2730 break; /* fall back to DefWindowProc */
2732 hIMC = ImmGetContext(hwnd);
2733 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2737 buff = snewn(n, char);
2738 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
2740 * Jaeyoun Chung reports that Korean character
2741 * input doesn't work correctly if we do a single
2742 * luni_send() covering the whole of buff. So
2743 * instead we luni_send the characters one by one.
2745 term_seen_key_event(term);
2746 for (i = 0; i < n; i += 2) {
2748 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2752 ImmReleaseContext(hwnd, hIMC);
2757 if (wParam & 0xFF00) {
2758 unsigned char buf[2];
2761 buf[0] = wParam >> 8;
2762 term_seen_key_event(term);
2764 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
2766 char c = (unsigned char) wParam;
2767 term_seen_key_event(term);
2769 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
2775 * Nevertheless, we are prepared to deal with WM_CHAR
2776 * messages, should they crop up. So if someone wants to
2777 * post the things to us as part of a macro manoeuvre,
2778 * we're ready to cope.
2781 char c = (unsigned char)wParam;
2782 term_seen_key_event(term);
2784 lpage_send(ldisc, CP_ACP, &c, 1, 1);
2788 if (send_raw_mouse && LOWORD(lParam) == HTCLIENT) {
2789 SetCursor(LoadCursor(NULL, IDC_ARROW));
2793 case WM_SYSCOLORCHANGE:
2794 if (cfg.system_colour) {
2795 /* Refresh palette from system colours. */
2796 /* XXX actually this zaps the entire palette. */
2799 /* Force a repaint of the terminal window. */
2800 term_invalidate(term);
2803 case WM_AGENT_CALLBACK:
2805 struct agent_callback *c = (struct agent_callback *)lParam;
2806 c->callback(c->callback_ctx, c->data, c->len);
2811 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
2812 int shift_pressed=0, control_pressed=0;
2814 if (message == WM_MOUSEWHEEL) {
2815 wheel_accumulator += (short)HIWORD(wParam);
2816 shift_pressed=LOWORD(wParam) & MK_SHIFT;
2817 control_pressed=LOWORD(wParam) & MK_CONTROL;
2820 wheel_accumulator += (int)wParam;
2821 if (GetKeyboardState(keys)!=0) {
2822 shift_pressed=keys[VK_SHIFT]&0x80;
2823 control_pressed=keys[VK_CONTROL]&0x80;
2827 /* process events when the threshold is reached */
2828 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
2831 /* reduce amount for next time */
2832 if (wheel_accumulator > 0) {
2834 wheel_accumulator -= WHEEL_DELTA;
2835 } else if (wheel_accumulator < 0) {
2837 wheel_accumulator += WHEEL_DELTA;
2841 if (send_raw_mouse &&
2842 !(cfg.mouse_override && shift_pressed)) {
2843 /* send a mouse-down followed by a mouse up */
2844 term_mouse(term, b, translate_button(b),
2846 TO_CHR_X(X_POS(lParam)),
2847 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2848 control_pressed, is_alt_pressed());
2849 term_mouse(term, b, translate_button(b),
2850 MA_RELEASE, TO_CHR_X(X_POS(lParam)),
2851 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2852 control_pressed, is_alt_pressed());
2854 /* trigger a scroll */
2855 term_scroll(term, 0,
2857 -term->rows / 2 : term->rows / 2);
2864 return DefWindowProc(hwnd, message, wParam, lParam);
2868 * Move the system caret. (We maintain one, even though it's
2869 * invisible, for the benefit of blind people: apparently some
2870 * helper software tracks the system caret, so we should arrange to
2873 void sys_cursor(void *frontend, int x, int y)
2877 if (!term->has_focus) return;
2880 * Avoid gratuitously re-updating the cursor position and IMM
2881 * window if there's no actual change required.
2883 cx = x * font_width + offset_width;
2884 cy = y * font_height + offset_height;
2885 if (cx == caret_x && cy == caret_y)
2890 sys_cursor_update();
2893 static void sys_cursor_update(void)
2898 if (!term->has_focus) return;
2900 if (caret_x < 0 || caret_y < 0)
2903 SetCaretPos(caret_x, caret_y);
2905 /* IMM calls on Win98 and beyond only */
2906 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
2908 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
2909 osVersion.dwMinorVersion == 0) return; /* 95 */
2911 /* we should have the IMM functions */
2912 hIMC = ImmGetContext(hwnd);
2913 cf.dwStyle = CFS_POINT;
2914 cf.ptCurrentPos.x = caret_x;
2915 cf.ptCurrentPos.y = caret_y;
2916 ImmSetCompositionWindow(hIMC, &cf);
2918 ImmReleaseContext(hwnd, hIMC);
2922 * Draw a line of text in the window, at given character
2923 * coordinates, in given attributes.
2925 * We are allowed to fiddle with the contents of `text'.
2927 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
2928 unsigned long attr, int lattr)
2931 int nfg, nbg, nfont;
2934 int force_manual_underline = 0;
2935 int fnt_width, char_width;
2936 int text_adjust = 0;
2937 static int *IpDx = 0, IpDxLEN = 0;
2939 lattr &= LATTR_MODE;
2941 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
2943 if (attr & ATTR_WIDE)
2946 if (len > IpDxLEN || IpDx[0] != char_width) {
2948 if (len > IpDxLEN) {
2950 IpDx = snewn(len + 16, int);
2951 IpDxLEN = (len + 16);
2953 for (i = 0; i < IpDxLEN; i++)
2954 IpDx[i] = char_width;
2957 /* Only want the left half of double width lines */
2958 if (lattr != LATTR_NORM && x*2 >= term->cols)
2966 if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
2967 attr &= ATTR_CUR_AND | (bold_mode != BOLD_COLOURS ? ATTR_BOLD : 0);
2968 attr ^= ATTR_CUR_XOR;
2972 if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
2973 /* Assume a poorman font is borken in other ways too. */
2983 nfont |= FONT_WIDE + FONT_HIGH;
2986 if (attr & ATTR_NARROW)
2987 nfont |= FONT_NARROW;
2989 /* Special hack for the VT100 linedraw glyphs. */
2990 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
2991 switch ((unsigned char) (text[0])) {
2993 text_adjust = -2 * font_height / 5;
2996 text_adjust = -1 * font_height / 5;
2999 text_adjust = font_height / 5;
3002 text_adjust = 2 * font_height / 5;
3005 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3007 text[0] = ucsdata.unitab_xterm['q'];
3008 if (attr & ATTR_UNDER) {
3009 attr &= ~ATTR_UNDER;
3010 force_manual_underline = 1;
3014 /* Anything left as an original character set is unprintable. */
3015 if (DIRECT_CHAR(text[0])) {
3017 for (i = 0; i < len; i++)
3022 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3025 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3026 nfg = 2 * (nfg & 0xF) + (nfg & 0x10 ? 1 : 0);
3027 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3028 nbg = 2 * (nbg & 0xF) + (nbg & 0x10 ? 1 : 0);
3029 if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
3031 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3032 nfont |= FONT_UNDERLINE;
3033 another_font(nfont);
3034 if (!fonts[nfont]) {
3035 if (nfont & FONT_UNDERLINE)
3036 force_manual_underline = 1;
3037 /* Don't do the same for manual bold, it could be bad news. */
3039 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3041 another_font(nfont);
3043 nfont = FONT_NORMAL;
3044 if (attr & ATTR_REVERSE) {
3049 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD))
3051 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK))
3055 SelectObject(hdc, fonts[nfont]);
3056 SetTextColor(hdc, fg);
3057 SetBkColor(hdc, bg);
3058 if (attr & TATTR_COMBINING)
3059 SetBkMode(hdc, TRANSPARENT);
3061 SetBkMode(hdc, OPAQUE);
3064 line_box.right = x + char_width * len;
3065 line_box.bottom = y + font_height;
3067 /* Only want the left half of double width lines */
3068 if (line_box.right > font_width*term->cols+offset_width)
3069 line_box.right = font_width*term->cols+offset_width;
3071 /* We're using a private area for direct to font. (512 chars.) */
3072 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3073 /* Ho Hum, dbcs fonts are a PITA! */
3074 /* To display on W9x I have to convert to UCS */
3075 static wchar_t *uni_buf = 0;
3076 static int uni_len = 0;
3078 if (len > uni_len) {
3081 uni_buf = snewn(uni_len, wchar_t);
3084 for(nlen = mptr = 0; mptr<len; mptr++) {
3085 uni_buf[nlen] = 0xFFFD;
3086 if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
3088 dbcstext[0] = text[mptr] & 0xFF;
3089 dbcstext[1] = text[mptr+1] & 0xFF;
3090 IpDx[nlen] += char_width;
3091 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3092 dbcstext, 2, uni_buf+nlen, 1);
3098 dbcstext[0] = text[mptr] & 0xFF;
3099 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3100 dbcstext, 1, uni_buf+nlen, 1);
3108 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3109 ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
3110 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3111 SetBkMode(hdc, TRANSPARENT);
3112 ExtTextOutW(hdc, x - 1,
3113 y - font_height * (lattr ==
3114 LATTR_BOT) + text_adjust,
3115 ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
3119 } else if (DIRECT_FONT(text[0])) {
3120 static char *directbuf = NULL;
3121 static int directlen = 0;
3123 if (len > directlen) {
3125 directbuf = sresize(directbuf, directlen, char);
3128 for (i = 0; i < len; i++)
3129 directbuf[i] = text[i] & 0xFF;
3132 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3133 ETO_CLIPPED | ETO_OPAQUE, &line_box, directbuf, len, IpDx);
3134 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3135 SetBkMode(hdc, TRANSPARENT);
3137 /* GRR: This draws the character outside it's box and can leave
3138 * 'droppings' even with the clip box! I suppose I could loop it
3139 * one character at a time ... yuk.
3141 * Or ... I could do a test print with "W", and use +1 or -1 for this
3142 * shift depending on if the leftmost column is blank...
3144 ExtTextOut(hdc, x - 1,
3145 y - font_height * (lattr ==
3146 LATTR_BOT) + text_adjust,
3147 ETO_CLIPPED, &line_box, directbuf, len, IpDx);
3150 /* And 'normal' unicode characters */
3151 static WCHAR *wbuf = NULL;
3152 static int wlen = 0;
3158 wbuf = snewn(wlen, WCHAR);
3161 for (i = 0; i < len; i++)
3164 /* print Glyphs as they are, without Windows' Shaping*/
3165 exact_textout(hdc, x, y - font_height * (lattr == LATTR_BOT) + text_adjust,
3166 &line_box, wbuf, len, IpDx, !(attr & TATTR_COMBINING));
3167 /* ExtTextOutW(hdc, x,
3168 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3169 ETO_CLIPPED | ETO_OPAQUE, &line_box, wbuf, len, IpDx);
3172 /* And the shadow bold hack. */
3173 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3174 SetBkMode(hdc, TRANSPARENT);
3175 ExtTextOutW(hdc, x - 1,
3176 y - font_height * (lattr ==
3177 LATTR_BOT) + text_adjust,
3178 ETO_CLIPPED, &line_box, wbuf, len, IpDx);
3181 if (lattr != LATTR_TOP && (force_manual_underline ||
3182 (und_mode == UND_LINE
3183 && (attr & ATTR_UNDER)))) {
3186 if (lattr == LATTR_BOT)
3187 dec = dec * 2 - font_height;
3189 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3190 MoveToEx(hdc, x, y + dec, NULL);
3191 LineTo(hdc, x + len * char_width, y + dec);
3192 oldpen = SelectObject(hdc, oldpen);
3193 DeleteObject(oldpen);
3198 * Wrapper that handles combining characters.
3200 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3201 unsigned long attr, int lattr)
3203 if (attr & TATTR_COMBINING) {
3204 unsigned long a = 0;
3205 attr &= ~TATTR_COMBINING;
3207 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3209 a = TATTR_COMBINING;
3212 do_text_internal(ctx, x, y, text, len, attr, lattr);
3215 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3216 unsigned long attr, int lattr)
3222 int ctype = cfg.cursor_type;
3224 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3225 if (*text != UCSWIDE) {
3226 do_text(ctx, x, y, text, len, attr, lattr);
3230 attr |= TATTR_RIGHTCURS;
3233 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3234 if (attr & ATTR_WIDE)
3241 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3244 pts[0].x = pts[1].x = pts[4].x = x;
3245 pts[2].x = pts[3].x = x + char_width - 1;
3246 pts[0].y = pts[3].y = pts[4].y = y;
3247 pts[1].y = pts[2].y = y + font_height - 1;
3248 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
3249 Polyline(hdc, pts, 5);
3250 oldpen = SelectObject(hdc, oldpen);
3251 DeleteObject(oldpen);
3252 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3253 int startx, starty, dx, dy, length, i;
3256 starty = y + descent;
3259 length = char_width;
3262 if (attr & TATTR_RIGHTCURS)
3263 xadjust = char_width - 1;
3264 startx = x + xadjust;
3268 length = font_height;
3270 if (attr & TATTR_ACTCURS) {
3273 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
3274 MoveToEx(hdc, startx, starty, NULL);
3275 LineTo(hdc, startx + dx * length, starty + dy * length);
3276 oldpen = SelectObject(hdc, oldpen);
3277 DeleteObject(oldpen);
3279 for (i = 0; i < length; i++) {
3281 SetPixel(hdc, startx, starty, colours[23]);
3290 /* This function gets the actual width of a character in the normal font.
3292 int char_width(Context ctx, int uc) {
3296 /* If the font max is the same as the font ave width then this
3297 * function is a no-op.
3299 if (!font_dualwidth) return 1;
3301 switch (uc & CSET_MASK) {
3303 uc = ucsdata.unitab_line[uc & 0xFF];
3306 uc = ucsdata.unitab_xterm[uc & 0xFF];
3309 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3312 if (DIRECT_FONT(uc)) {
3313 if (ucsdata.dbcs_screenfont) return 1;
3315 /* Speedup, I know of no font where ascii is the wrong width */
3316 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3319 if ( (uc & CSET_MASK) == CSET_ACP ) {
3320 SelectObject(hdc, fonts[FONT_NORMAL]);
3321 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3322 another_font(FONT_OEM);
3323 if (!fonts[FONT_OEM]) return 0;
3325 SelectObject(hdc, fonts[FONT_OEM]);
3329 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3330 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3333 /* Speedup, I know of no font where ascii is the wrong width */
3334 if (uc >= ' ' && uc <= '~') return 1;
3336 SelectObject(hdc, fonts[FONT_NORMAL]);
3337 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3338 /* Okay that one worked */ ;
3339 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3340 /* This should work on 9x too, but it's "less accurate" */ ;
3345 ibuf += font_width / 2 -1;
3352 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3353 * codes. Returns number of bytes used or zero to drop the message
3354 * or -1 to forward the message to windows.
3356 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3357 unsigned char *output)
3360 int scan, left_alt = 0, key_down, shift_state;
3362 unsigned char *p = output;
3363 static int alt_sum = 0;
3365 HKL kbd_layout = GetKeyboardLayout(0);
3367 /* keys is for ToAsciiEx. There's some ick here, see below. */
3368 static WORD keys[3];
3369 static int compose_char = 0;
3370 static WPARAM compose_key = 0;
3372 r = GetKeyboardState(keystate);
3374 memset(keystate, 0, sizeof(keystate));
3377 #define SHOW_TOASCII_RESULT
3378 { /* Tell us all about key events */
3379 static BYTE oldstate[256];
3380 static int first = 1;
3384 memcpy(oldstate, keystate, sizeof(oldstate));
3387 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3389 } else if ((HIWORD(lParam) & KF_UP)
3390 && scan == (HIWORD(lParam) & 0xFF)) {
3394 if (wParam >= VK_F1 && wParam <= VK_F20)
3395 debug(("K_F%d", wParam + 1 - VK_F1));
3408 debug(("VK_%02x", wParam));
3410 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3412 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3414 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3415 if (ch >= ' ' && ch <= '~')
3416 debug((", '%c'", ch));
3418 debug((", $%02x", ch));
3421 debug((", KB0=%02x", keys[0]));
3423 debug((", KB1=%02x", keys[1]));
3425 debug((", KB2=%02x", keys[2]));
3427 if ((keystate[VK_SHIFT] & 0x80) != 0)
3429 if ((keystate[VK_CONTROL] & 0x80) != 0)
3431 if ((HIWORD(lParam) & KF_EXTENDED))
3433 if ((HIWORD(lParam) & KF_UP))
3437 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3438 else if ((HIWORD(lParam) & KF_UP))
3439 oldstate[wParam & 0xFF] ^= 0x80;
3441 oldstate[wParam & 0xFF] ^= 0x81;
3443 for (ch = 0; ch < 256; ch++)
3444 if (oldstate[ch] != keystate[ch])
3445 debug((", M%02x=%02x", ch, keystate[ch]));
3447 memcpy(oldstate, keystate, sizeof(oldstate));
3451 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
3452 keystate[VK_RMENU] = keystate[VK_MENU];
3456 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
3457 if ((cfg.funky_type == FUNKY_VT400 ||
3458 (cfg.funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
3460 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
3462 wParam = VK_EXECUTE;
3464 /* UnToggle NUMLock */
3465 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3466 keystate[VK_NUMLOCK] ^= 1;
3469 /* And write back the 'adjusted' state */
3470 SetKeyboardState(keystate);
3473 /* Disable Auto repeat if required */
3474 if (term->repeat_off &&
3475 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
3478 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
3481 key_down = ((HIWORD(lParam) & KF_UP) == 0);
3483 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
3484 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
3485 if (cfg.ctrlaltkeys)
3486 keystate[VK_MENU] = 0;
3488 keystate[VK_RMENU] = 0x80;
3493 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
3494 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3495 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
3497 /* Note if AltGr was pressed and if it was used as a compose key */
3498 if (!compose_state) {
3499 compose_key = 0x100;
3500 if (cfg.compose_key) {
3501 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
3502 compose_key = wParam;
3504 if (wParam == VK_APPS)
3505 compose_key = wParam;
3508 if (wParam == compose_key) {
3509 if (compose_state == 0
3510 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3512 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
3516 } else if (compose_state == 1 && wParam != VK_CONTROL)
3519 if (compose_state > 1 && left_alt)
3522 /* Sanitize the number pad if not using a PC NumPad */
3523 if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
3524 && cfg.funky_type != FUNKY_XTERM)
3525 || cfg.funky_type == FUNKY_VT400 || cfg.nethack_keypad || compose_state) {
3526 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
3530 nParam = VK_NUMPAD0;
3533 nParam = VK_NUMPAD1;
3536 nParam = VK_NUMPAD2;
3539 nParam = VK_NUMPAD3;
3542 nParam = VK_NUMPAD4;
3545 nParam = VK_NUMPAD5;
3548 nParam = VK_NUMPAD6;
3551 nParam = VK_NUMPAD7;
3554 nParam = VK_NUMPAD8;
3557 nParam = VK_NUMPAD9;
3560 nParam = VK_DECIMAL;
3564 if (keystate[VK_NUMLOCK] & 1)
3571 /* If a key is pressed and AltGr is not active */
3572 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3573 /* Okay, prepare for most alts then ... */
3577 /* Lets see if it's a pattern we know all about ... */
3578 if (wParam == VK_PRIOR && shift_state == 1) {
3579 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3582 if (wParam == VK_PRIOR && shift_state == 2) {
3583 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3586 if (wParam == VK_NEXT && shift_state == 1) {
3587 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3590 if (wParam == VK_NEXT && shift_state == 2) {
3591 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3594 if (wParam == VK_INSERT && shift_state == 1) {
3595 term_do_paste(term);
3598 if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
3601 if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
3602 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3605 if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3606 (cfg.resize_action != RESIZE_DISABLED)) {
3607 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3611 /* Control-Numlock for app-keypad mode switch */
3612 if (wParam == VK_PAUSE && shift_state == 2) {
3613 term->app_keypad_keys ^= 1;
3617 /* Nethack keypad */
3618 if (cfg.nethack_keypad && !left_alt) {
3621 *p++ = shift_state ? 'B' : 'b';
3624 *p++ = shift_state ? 'J' : 'j';
3627 *p++ = shift_state ? 'N' : 'n';
3630 *p++ = shift_state ? 'H' : 'h';
3633 *p++ = shift_state ? '.' : '.';
3636 *p++ = shift_state ? 'L' : 'l';
3639 *p++ = shift_state ? 'Y' : 'y';
3642 *p++ = shift_state ? 'K' : 'k';
3645 *p++ = shift_state ? 'U' : 'u';
3650 /* Application Keypad */
3654 if (cfg.funky_type == FUNKY_VT400 ||
3655 (cfg.funky_type <= FUNKY_LINUX &&
3656 term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
3670 if (term->app_keypad_keys && !cfg.no_applic_k)
3707 if (cfg.funky_type == FUNKY_XTERM) {
3712 } else if (shift_state)
3719 if (cfg.funky_type == FUNKY_XTERM)
3723 if (cfg.funky_type == FUNKY_XTERM)
3727 if (cfg.funky_type == FUNKY_XTERM)
3732 if (HIWORD(lParam) & KF_EXTENDED)
3737 if (term->vt52_mode) {
3738 if (xkey >= 'P' && xkey <= 'S')
3739 p += sprintf((char *) p, "\x1B%c", xkey);
3741 p += sprintf((char *) p, "\x1B?%c", xkey);
3743 p += sprintf((char *) p, "\x1BO%c", xkey);
3748 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
3749 *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
3753 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
3754 /* We do the opposite of what is configured */
3755 *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
3759 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
3765 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
3769 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
3773 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
3778 if (wParam == VK_PAUSE) { /* Break/Pause */
3783 /* Control-2 to Control-8 are special */
3784 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
3785 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
3788 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
3792 if (shift_state == 2 && wParam == 0xDF) {
3796 if (shift_state == 3 && wParam == 0xDE) {
3797 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
3800 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
3807 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
3808 * for integer decimal nn.)
3810 * We also deal with the weird ones here. Linux VCs replace F1
3811 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
3812 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
3818 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
3821 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
3824 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
3827 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
3830 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
3833 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
3836 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
3839 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
3842 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
3845 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
3878 if ((shift_state&2) == 0) switch (wParam) {
3898 /* Reorder edit keys to physical order */
3899 if (cfg.funky_type == FUNKY_VT400 && code <= 6)
3900 code = "\0\2\1\4\5\3\6"[code];
3902 if (term->vt52_mode && code > 0 && code <= 6) {
3903 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
3907 if (cfg.funky_type == FUNKY_SCO && /* SCO function keys */
3908 code >= 11 && code <= 34) {
3909 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
3912 case VK_F1: index = 0; break;
3913 case VK_F2: index = 1; break;
3914 case VK_F3: index = 2; break;
3915 case VK_F4: index = 3; break;
3916 case VK_F5: index = 4; break;
3917 case VK_F6: index = 5; break;
3918 case VK_F7: index = 6; break;
3919 case VK_F8: index = 7; break;
3920 case VK_F9: index = 8; break;
3921 case VK_F10: index = 9; break;
3922 case VK_F11: index = 10; break;
3923 case VK_F12: index = 11; break;
3925 if (keystate[VK_SHIFT] & 0x80) index += 12;
3926 if (keystate[VK_CONTROL] & 0x80) index += 24;
3927 p += sprintf((char *) p, "\x1B[%c", codes[index]);
3930 if (cfg.funky_type == FUNKY_SCO && /* SCO small keypad */
3931 code >= 1 && code <= 6) {
3932 char codes[] = "HL.FIG";
3936 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
3940 if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
3946 if (term->vt52_mode)
3947 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
3950 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
3953 if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
3954 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
3957 if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
3958 if (term->vt52_mode)
3959 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
3961 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
3964 if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
3965 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
3969 p += sprintf((char *) p, "\x1B[%d~", code);
3974 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
3975 * some reason seems to send VK_CLEAR to Windows...).
3997 if (term->vt52_mode)
3998 p += sprintf((char *) p, "\x1B%c", xkey);
4000 int app_flg = (term->app_cursor_keys && !cfg.no_applic_c);
4003 * RDB: VT100 & VT102 manuals both state the
4004 * app cursor keys only work if the app keypad
4007 * SGT: That may well be true, but xterm
4008 * disagrees and so does at least one
4009 * application, so I've #if'ed this out and the
4010 * behaviour is back to PuTTY's original: app
4011 * cursor and app keypad are independently
4012 * switchable modes. If anyone complains about
4013 * _this_ I'll have to put in a configurable
4016 if (!term->app_keypad_keys)
4019 /* Useful mapping of Ctrl-arrows */
4020 if (shift_state == 2)
4024 p += sprintf((char *) p, "\x1BO%c", xkey);
4026 p += sprintf((char *) p, "\x1B[%c", xkey);
4033 * Finally, deal with Return ourselves. (Win95 seems to
4034 * foul it up when Alt is pressed, for some reason.)
4036 if (wParam == VK_RETURN) { /* Return */
4042 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4043 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4048 /* Okay we've done everything interesting; let windows deal with
4049 * the boring stuff */
4053 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4054 if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
4056 keystate[VK_CAPITAL] = 0;
4059 /* XXX how do we know what the max size of the keys array should
4060 * be is? There's indication on MS' website of an Inquire/InquireEx
4061 * functioning returning a KBINFO structure which tells us. */
4062 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4063 /* XXX 'keys' parameter is declared in MSDN documentation as
4065 * The experience of a French user indicates that on
4066 * Win98, WORD[] should be passed in, but on Win2K, it should
4067 * be BYTE[]. German WinXP and my Win2K with "US International"
4068 * driver corroborate this.
4069 * Experimentally I've conditionalised the behaviour on the
4070 * Win9x/NT split, but I suspect it's worse than that.
4071 * See wishlist item `win-dead-keys' for more horrible detail
4072 * and speculations. */
4075 r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
4076 for (i=0; i<3; i++) keys[i] = keybs[i];
4078 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4080 #ifdef SHOW_TOASCII_RESULT
4081 if (r == 1 && !key_down) {
4083 if (in_utf(term) || ucsdata.dbcs_screenfont)
4084 debug((", (U+%04x)", alt_sum));
4086 debug((", LCH(%d)", alt_sum));
4088 debug((", ACH(%d)", keys[0]));
4093 for (r1 = 0; r1 < r; r1++) {
4094 debug(("%s%d", r1 ? "," : "", keys[r1]));
4103 * Interrupt an ongoing paste. I'm not sure this is
4104 * sensible, but for the moment it's preferable to
4105 * having to faff about buffering things.
4110 for (i = 0; i < r; i++) {
4111 unsigned char ch = (unsigned char) keys[i];
4113 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
4118 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
4122 if ((nc = check_compose(compose_char, ch)) == -1) {
4123 MessageBeep(MB_ICONHAND);
4127 term_seen_key_event(term);
4129 luni_send(ldisc, &keybuf, 1, 1);
4137 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4139 term_seen_key_event(term);
4141 luni_send(ldisc, &keybuf, 1, 1);
4143 ch = (char) alt_sum;
4145 * We need not bother about stdin
4146 * backlogs here, because in GUI PuTTY
4147 * we can't do anything about it
4148 * anyway; there's no means of asking
4149 * Windows to hold off on KEYDOWN
4150 * messages. We _have_ to buffer
4151 * everything we're sent.
4153 term_seen_key_event(term);
4155 ldisc_send(ldisc, &ch, 1, 1);
4159 term_seen_key_event(term);
4161 lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
4164 if(capsOn && ch < 0x80) {
4167 cbuf[1] = xlat_uskbd2cyrllic(ch);
4168 term_seen_key_event(term);
4170 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4175 term_seen_key_event(term);
4177 lpage_send(ldisc, kbd_codepage,
4178 cbuf+!left_alt, 1+!!left_alt, 1);
4184 /* This is so the ALT-Numpad and dead keys work correctly. */
4189 /* If we're definitly not building up an ALT-54321 then clear it */
4192 /* If we will be using alt_sum fix the 256s */
4193 else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4198 * ALT alone may or may not want to bring up the System menu.
4199 * If it's not meant to, we return 0 on presses or releases of
4200 * ALT, to show that we've swallowed the keystroke. Otherwise
4201 * we return -1, which means Windows will give the keystroke
4202 * its default handling (i.e. bring up the System menu).
4204 if (wParam == VK_MENU && !cfg.alt_only)
4210 void request_paste(void *frontend)
4213 * In Windows, pasting is synchronous: we can read the
4214 * clipboard with no difficulty, so request_paste() can just go
4217 term_do_paste(term);
4220 void set_title(void *frontend, char *title)
4223 window_name = snewn(1 + strlen(title), char);
4224 strcpy(window_name, title);
4225 if (cfg.win_name_always || !IsIconic(hwnd))
4226 SetWindowText(hwnd, title);
4229 void set_icon(void *frontend, char *title)
4232 icon_name = snewn(1 + strlen(title), char);
4233 strcpy(icon_name, title);
4234 if (!cfg.win_name_always && IsIconic(hwnd))
4235 SetWindowText(hwnd, title);
4238 void set_sbar(void *frontend, int total, int start, int page)
4242 if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
4245 si.cbSize = sizeof(si);
4246 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4248 si.nMax = total - 1;
4252 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4255 Context get_ctx(void *frontend)
4261 SelectPalette(hdc, pal, FALSE);
4267 void free_ctx(Context ctx)
4269 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4270 ReleaseDC(hwnd, ctx);
4273 static void real_palette_set(int n, int r, int g, int b)
4276 logpal->palPalEntry[n].peRed = r;
4277 logpal->palPalEntry[n].peGreen = g;
4278 logpal->palPalEntry[n].peBlue = b;
4279 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4280 colours[n] = PALETTERGB(r, g, b);
4281 SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
4283 colours[n] = RGB(r, g, b);
4286 void palette_set(void *frontend, int n, int r, int g, int b)
4288 static const int first[21] = {
4289 0, 2, 4, 6, 8, 10, 12, 14,
4290 1, 3, 5, 7, 9, 11, 13, 15,
4293 real_palette_set(first[n], r, g, b);
4295 real_palette_set(first[n] + 1, r, g, b);
4297 HDC hdc = get_ctx(frontend);
4298 UnrealizeObject(pal);
4299 RealizePalette(hdc);
4304 void palette_reset(void *frontend)
4308 for (i = 0; i < NCOLOURS; i++) {
4310 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4311 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4312 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4313 logpal->palPalEntry[i].peFlags = 0;
4314 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4315 defpal[i].rgbtGreen,
4316 defpal[i].rgbtBlue);
4318 colours[i] = RGB(defpal[i].rgbtRed,
4319 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4324 SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
4325 hdc = get_ctx(frontend);
4326 RealizePalette(hdc);
4331 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4336 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4339 lock = GlobalLock(clipdata);
4342 memcpy(lock, data, len);
4343 ((unsigned char *) lock)[len] = 0;
4344 GlobalUnlock(clipdata);
4347 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4349 if (OpenClipboard(hwnd)) {
4351 SetClipboardData(CF_TEXT, clipdata);
4354 GlobalFree(clipdata);
4357 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4361 * Note: unlike write_aclip() this will not append a nul.
4363 void write_clip(void *frontend, wchar_t * data, int len, int must_deselect)
4365 HGLOBAL clipdata, clipdata2, clipdata3;
4367 void *lock, *lock2, *lock3;
4369 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4371 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4372 len * sizeof(wchar_t));
4373 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4375 if (!clipdata || !clipdata2) {
4377 GlobalFree(clipdata);
4379 GlobalFree(clipdata2);
4382 if (!(lock = GlobalLock(clipdata)))
4384 if (!(lock2 = GlobalLock(clipdata2)))
4387 memcpy(lock, data, len * sizeof(wchar_t));
4388 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4390 if (cfg.rtf_paste) {
4391 wchar_t unitab[256];
4393 unsigned char *tdata = (unsigned char *)lock2;
4394 wchar_t *udata = (wchar_t *)lock;
4395 int rtflen = 0, uindex = 0, tindex = 0;
4397 int multilen, blen, alen, totallen, i;
4398 char before[16], after[4];
4400 get_unitab(CP_ACP, unitab, 0);
4402 rtfsize = 100 + strlen(cfg.font.name);
4403 rtf = snewn(rtfsize, char);
4404 sprintf(rtf, "{\\rtf1\\ansi%d{\\fonttbl\\f0\\fmodern %s;}\\f0",
4405 GetACP(), cfg.font.name);
4406 rtflen = strlen(rtf);
4409 * We want to construct a piece of RTF that specifies the
4410 * same Unicode text. To do this we will read back in
4411 * parallel from the Unicode data in `udata' and the
4412 * non-Unicode data in `tdata'. For each character in
4413 * `tdata' which becomes the right thing in `udata' when
4414 * looked up in `unitab', we just copy straight over from
4415 * tdata. For each one that doesn't, we must WCToMB it
4416 * individually and produce a \u escape sequence.
4418 * It would probably be more robust to just bite the bullet
4419 * and WCToMB each individual Unicode character one by one,
4420 * then MBToWC each one back to see if it was an accurate
4421 * translation; but that strikes me as a horrifying number
4422 * of Windows API calls so I want to see if this faster way
4423 * will work. If it screws up badly we can always revert to
4424 * the simple and slow way.
4426 while (tindex < len2 && uindex < len &&
4427 tdata[tindex] && udata[uindex]) {
4428 if (tindex + 1 < len2 &&
4429 tdata[tindex] == '\r' &&
4430 tdata[tindex+1] == '\n') {
4434 if (unitab[tdata[tindex]] == udata[uindex]) {
4440 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4441 NULL, 0, NULL, NULL);
4442 if (multilen != 1) {
4443 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4445 alen = 1; strcpy(after, "}");
4447 blen = sprintf(before, "\\u%d", udata[uindex]);
4448 alen = 0; after[0] = '\0';
4451 assert(tindex + multilen <= len2);
4452 totallen = blen + alen;
4453 for (i = 0; i < multilen; i++) {
4454 if (tdata[tindex+i] == '\\' ||
4455 tdata[tindex+i] == '{' ||
4456 tdata[tindex+i] == '}')
4458 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4459 totallen += 6; /* \par\r\n */
4460 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4466 if (rtfsize < rtflen + totallen + 3) {
4467 rtfsize = rtflen + totallen + 512;
4468 rtf = sresize(rtf, rtfsize, char);
4471 strcpy(rtf + rtflen, before); rtflen += blen;
4472 for (i = 0; i < multilen; i++) {
4473 if (tdata[tindex+i] == '\\' ||
4474 tdata[tindex+i] == '{' ||
4475 tdata[tindex+i] == '}') {
4476 rtf[rtflen++] = '\\';
4477 rtf[rtflen++] = tdata[tindex+i];
4478 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4479 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4480 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4481 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4483 rtf[rtflen++] = tdata[tindex+i];
4486 strcpy(rtf + rtflen, after); rtflen += alen;
4492 strcpy(rtf + rtflen, "}");
4495 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4496 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
4498 GlobalUnlock(clipdata3);
4504 GlobalUnlock(clipdata);
4505 GlobalUnlock(clipdata2);
4508 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4510 if (OpenClipboard(hwnd)) {
4512 SetClipboardData(CF_UNICODETEXT, clipdata);
4513 SetClipboardData(CF_TEXT, clipdata2);
4515 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4518 GlobalFree(clipdata);
4519 GlobalFree(clipdata2);
4523 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4526 void get_clip(void *frontend, wchar_t ** p, int *len)
4528 static HGLOBAL clipdata = NULL;
4529 static wchar_t *converted = 0;
4538 GlobalUnlock(clipdata);
4541 } else if (OpenClipboard(NULL)) {
4542 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
4544 *p = GlobalLock(clipdata);
4546 for (p2 = *p; *p2; p2++);
4550 } else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
4554 s = GlobalLock(clipdata);
4555 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
4556 *p = converted = snewn(i, wchar_t);
4557 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
4570 * Move `lines' lines from position `from' to position `to' in the
4573 void optimised_move(void *frontend, int to, int from, int lines)
4578 min = (to < from ? to : from);
4579 max = to + from - min;
4581 r.left = offset_width;
4582 r.right = offset_width + term->cols * font_width;
4583 r.top = offset_height + min * font_height;
4584 r.bottom = offset_height + (max + lines) * font_height;
4585 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
4590 * Print a message box and perform a fatal exit.
4592 void fatalbox(char *fmt, ...)
4595 char *stuff, morestuff[100];
4598 stuff = dupvprintf(fmt, ap);
4600 sprintf(morestuff, "%.70s Fatal Error", appname);
4601 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
4607 * Print a modal (Really Bad) message box and perform a fatal exit.
4609 void modalfatalbox(char *fmt, ...)
4612 char *stuff, morestuff[100];
4615 stuff = dupvprintf(fmt, ap);
4617 sprintf(morestuff, "%.70s Fatal Error", appname);
4618 MessageBox(hwnd, stuff, morestuff,
4619 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
4625 * Manage window caption / taskbar flashing, if enabled.
4626 * 0 = stop, 1 = maintain, 2 = start
4628 static void flash_window(int mode)
4630 static long last_flash = 0;
4631 static int flashing = 0;
4632 if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
4635 FlashWindow(hwnd, FALSE);
4639 } else if (mode == 2) {
4642 last_flash = GetTickCount();
4644 FlashWindow(hwnd, TRUE);
4647 } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
4650 long now = GetTickCount();
4651 long fdiff = now - last_flash;
4652 if (fdiff < 0 || fdiff > 450) {
4654 FlashWindow(hwnd, TRUE); /* toggle */
4663 void beep(void *frontend, int mode)
4665 if (mode == BELL_DEFAULT) {
4667 * For MessageBeep style bells, we want to be careful of
4668 * timing, because they don't have the nice property of
4669 * PlaySound bells that each one cancels the previous
4670 * active one. So we limit the rate to one per 50ms or so.
4672 static long lastbeep = 0;
4675 beepdiff = GetTickCount() - lastbeep;
4676 if (beepdiff >= 0 && beepdiff < 50)
4680 * The above MessageBeep call takes time, so we record the
4681 * time _after_ it finishes rather than before it starts.
4683 lastbeep = GetTickCount();
4684 } else if (mode == BELL_WAVEFILE) {
4685 if (!PlaySound(cfg.bell_wavefile.path, NULL,
4686 SND_ASYNC | SND_FILENAME)) {
4687 char buf[sizeof(cfg.bell_wavefile.path) + 80];
4689 sprintf(buf, "Unable to play sound file\n%s\n"
4690 "Using default sound instead", cfg.bell_wavefile.path);
4691 sprintf(otherbuf, "%.70s Sound Error", appname);
4692 MessageBox(hwnd, buf, otherbuf,
4693 MB_OK | MB_ICONEXCLAMATION);
4694 cfg.beep = BELL_DEFAULT;
4696 } else if (mode == BELL_PCSPEAKER) {
4697 static long lastbeep = 0;
4700 beepdiff = GetTickCount() - lastbeep;
4701 if (beepdiff >= 0 && beepdiff < 50)
4705 * We must beep in different ways depending on whether this
4706 * is a 95-series or NT-series OS.
4708 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
4712 lastbeep = GetTickCount();
4714 /* Otherwise, either visual bell or disabled; do nothing here */
4715 if (!term->has_focus) {
4716 flash_window(2); /* start */
4721 * Minimise or restore the window in response to a server-side
4724 void set_iconic(void *frontend, int iconic)
4726 if (IsIconic(hwnd)) {
4728 ShowWindow(hwnd, SW_RESTORE);
4731 ShowWindow(hwnd, SW_MINIMIZE);
4736 * Move the window in response to a server-side request.
4738 void move_window(void *frontend, int x, int y)
4740 if (cfg.resize_action == RESIZE_DISABLED ||
4741 cfg.resize_action == RESIZE_FONT ||
4745 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
4749 * Move the window to the top or bottom of the z-order in response
4750 * to a server-side request.
4752 void set_zorder(void *frontend, int top)
4754 if (cfg.alwaysontop)
4755 return; /* ignore */
4756 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
4757 SWP_NOMOVE | SWP_NOSIZE);
4761 * Refresh the window in response to a server-side request.
4763 void refresh_window(void *frontend)
4765 InvalidateRect(hwnd, NULL, TRUE);
4769 * Maximise or restore the window in response to a server-side
4772 void set_zoomed(void *frontend, int zoomed)
4774 if (IsZoomed(hwnd)) {
4776 ShowWindow(hwnd, SW_RESTORE);
4779 ShowWindow(hwnd, SW_MAXIMIZE);
4784 * Report whether the window is iconic, for terminal reports.
4786 int is_iconic(void *frontend)
4788 return IsIconic(hwnd);
4792 * Report the window's position, for terminal reports.
4794 void get_window_pos(void *frontend, int *x, int *y)
4797 GetWindowRect(hwnd, &r);
4803 * Report the window's pixel size, for terminal reports.
4805 void get_window_pixels(void *frontend, int *x, int *y)
4808 GetWindowRect(hwnd, &r);
4809 *x = r.right - r.left;
4810 *y = r.bottom - r.top;
4814 * Return the window or icon title.
4816 char *get_window_title(void *frontend, int icon)
4818 return icon ? icon_name : window_name;
4822 * See if we're in full-screen mode.
4824 static int is_full_screen()
4826 if (!IsZoomed(hwnd))
4828 if (GetWindowLong(hwnd, GWL_STYLE) & WS_CAPTION)
4833 /* Get the rect/size of a full screen window using the nearest available
4834 * monitor in multimon systems; default to something sensible if only
4835 * one monitor is present. */
4836 static int get_fullscreen_rect(RECT * ss)
4838 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
4841 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
4842 mi.cbSize = sizeof(mi);
4843 GetMonitorInfo(mon, &mi);
4845 /* structure copy */
4849 /* could also use code like this:
4850 ss->left = ss->top = 0;
4851 ss->right = GetSystemMetrics(SM_CXSCREEN);
4852 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
4854 return GetClientRect(GetDesktopWindow(), ss);
4860 * Go full-screen. This should only be called when we are already
4863 static void make_full_screen()
4868 assert(IsZoomed(hwnd));
4870 if (is_full_screen())
4873 /* Remove the window furniture. */
4874 style = GetWindowLong(hwnd, GWL_STYLE);
4875 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
4876 if (cfg.scrollbar_in_fullscreen)
4877 style |= WS_VSCROLL;
4879 style &= ~WS_VSCROLL;
4880 SetWindowLong(hwnd, GWL_STYLE, style);
4882 /* Resize ourselves to exactly cover the nearest monitor. */
4883 get_fullscreen_rect(&ss);
4884 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
4889 /* Tick the menu item in the System menu. */
4890 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4895 * Clear the full-screen attributes.
4897 static void clear_full_screen()
4899 DWORD oldstyle, style;
4901 /* Reinstate the window furniture. */
4902 style = oldstyle = GetWindowLong(hwnd, GWL_STYLE);
4903 style |= WS_CAPTION | WS_BORDER;
4904 if (cfg.resize_action == RESIZE_DISABLED)
4905 style &= ~WS_THICKFRAME;
4907 style |= WS_THICKFRAME;
4909 style |= WS_VSCROLL;
4911 style &= ~WS_VSCROLL;
4912 if (style != oldstyle) {
4913 SetWindowLong(hwnd, GWL_STYLE, style);
4914 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
4915 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
4919 /* Untick the menu item in the System menu. */
4920 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4925 * Toggle full-screen mode.
4927 static void flip_full_screen()
4929 if (is_full_screen()) {
4930 ShowWindow(hwnd, SW_RESTORE);
4931 } else if (IsZoomed(hwnd)) {
4934 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
4935 ShowWindow(hwnd, SW_MAXIMIZE);
4939 void frontend_keypress(void *handle)
4942 * Keypress termination in non-Close-On-Exit mode is not
4943 * currently supported in PuTTY proper, because the window
4944 * always has a perfectly good Close button anyway. So we do
4950 int from_backend(void *frontend, int is_stderr, const char *data, int len)
4952 return term_data(term, is_stderr, data, len);
4955 void agent_schedule_callback(void (*callback)(void *, void *, int),
4956 void *callback_ctx, void *data, int len)
4958 struct agent_callback *c = snew(struct agent_callback);
4959 c->callback = callback;
4960 c->callback_ctx = callback_ctx;
4963 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);