7 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
15 #define COMPILE_MULTIMON_STUBS
25 /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
26 * wParam are used by Windows, and should be masked off, so we shouldn't
27 * attempt to store information in them. Hence all these identifiers have
28 * the low 4 bits clear. Also, identifiers should < 0xF000. */
30 #define IDM_SHOWLOG 0x0010
31 #define IDM_NEWSESS 0x0020
32 #define IDM_DUPSESS 0x0030
33 #define IDM_RESTART 0x0040
34 #define IDM_RECONF 0x0050
35 #define IDM_CLRSB 0x0060
36 #define IDM_RESET 0x0070
37 #define IDM_HELP 0x0140
38 #define IDM_ABOUT 0x0150
39 #define IDM_SAVEDSESS 0x0160
40 #define IDM_COPYALL 0x0170
41 #define IDM_FULLSCREEN 0x0180
42 #define IDM_PASTE 0x0190
44 #define IDM_SPECIAL_MIN 0x0400
45 #define IDM_SPECIAL_MAX 0x0800
47 #define IDM_SAVED_MIN 0x1000
48 #define IDM_SAVED_MAX 0x5000
49 #define MENU_SAVED_STEP 16
50 /* Maximum number of sessions on saved-session submenu */
51 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
53 #define WM_IGNORE_CLIP (WM_XUSER + 2)
54 #define WM_FULLSCR_ON_MAX (WM_XUSER + 3)
55 #define WM_AGENT_CALLBACK (WM_XUSER + 4)
57 /* Needed for Chinese support and apparently not always defined. */
59 #define VK_PROCESSKEY 0xE5
62 /* Mouse wheel support. */
64 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
67 #define WHEEL_DELTA 120
70 static Mouse_Button translate_button(Mouse_Button button);
71 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
72 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
73 unsigned char *output);
74 static void cfgtopalette(void);
75 static void systopalette(void);
76 static void init_palette(void);
77 static void init_fonts(int, int);
78 static void another_font(int);
79 static void deinit_fonts(void);
80 static void set_input_locale(HKL);
82 static int is_full_screen(void);
83 static void make_full_screen(void);
84 static void clear_full_screen(void);
85 static void flip_full_screen(void);
87 /* Window layout information */
88 static void reset_window(int);
89 static int extra_width, extra_height;
90 static int font_width, font_height, font_dualwidth;
91 static int offset_width, offset_height;
92 static int was_zoomed = 0;
93 static int prev_rows, prev_cols;
95 static void enact_netevent(WPARAM, LPARAM);
96 static void flash_window(int mode);
97 static void sys_cursor_update(void);
98 static int is_shift_pressed(void);
99 static int get_fullscreen_rect(RECT * ss);
101 static int caret_x = -1, caret_y = -1;
103 static int kbd_codepage;
106 static Backend *back;
107 static void *backhandle;
109 static struct unicode_data ucsdata;
110 static int session_closed;
112 static const struct telnet_special *specials;
113 static int n_specials;
115 #define TIMING_TIMER_ID 1234
116 static long timing_next_time;
120 int specials_submenu_pos;
122 enum { SYSMENU, CTXMENU };
124 Config cfg; /* exported to windlg.c */
126 extern struct sesslist sesslist; /* imported from windlg.c */
128 struct agent_callback {
129 void (*callback)(void *, void *, int);
135 #define FONT_NORMAL 0
137 #define FONT_UNDERLINE 2
138 #define FONT_BOLDUND 3
139 #define FONT_WIDE 0x04
140 #define FONT_HIGH 0x08
141 #define FONT_NARROW 0x10
143 #define FONT_OEM 0x20
144 #define FONT_OEMBOLD 0x21
145 #define FONT_OEMUND 0x22
146 #define FONT_OEMBOLDUND 0x23
148 #define FONT_MAXNO 0x2F
150 static HFONT fonts[FONT_MAXNO];
151 static LOGFONT lfont;
152 static int fontflag[FONT_MAXNO];
154 BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT
161 #define NCFGCOLOURS 22
162 #define NEXTCOLOURS 240
163 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
164 static COLORREF colours[NALLCOLOURS];
166 static LPLOGPALETTE logpal;
167 static RGBTRIPLE defpal[NALLCOLOURS];
171 static HBITMAP caretbm;
173 static int dbltime, lasttime, lastact;
174 static Mouse_Button lastbtn;
176 /* this allows xterm-style mouse handling. */
177 static int send_raw_mouse = 0;
178 static int wheel_accumulator = 0;
180 static char *window_name, *icon_name;
182 static int compose_state = 0;
184 static UINT wm_mousewheel = WM_MOUSEWHEEL;
186 /* Dummy routine, only required in plink. */
187 void ldisc_update(void *frontend, int echo, int edit)
191 static void start_backend(void)
194 char msg[1024], *title;
199 * Select protocol. This is farmed out into a table in a
200 * separate file to enable an ssh-free variant.
203 for (i = 0; backends[i].backend != NULL; i++)
204 if (backends[i].protocol == cfg.protocol) {
205 back = backends[i].backend;
209 char *str = dupprintf("%s Internal Error", appname);
210 MessageBox(NULL, "Unsupported protocol number found",
211 str, MB_OK | MB_ICONEXCLAMATION);
216 error = back->init(NULL, &backhandle, &cfg,
217 cfg.host, cfg.port, &realhost, cfg.tcp_nodelay,
219 back->provide_logctx(backhandle, logctx);
221 char *str = dupprintf("%s Error", appname);
222 sprintf(msg, "Unable to open connection to\n"
223 "%.800s\n" "%s", cfg.host, error);
224 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
228 window_name = icon_name = NULL;
230 title = cfg.wintitle;
232 sprintf(msg, "%s - %s", realhost, appname);
236 set_title(NULL, title);
237 set_icon(NULL, title);
240 * Connect the terminal to the backend for resize purposes.
242 term_provide_resize_fn(term, back->size, backhandle);
245 * Set up a line discipline.
247 ldisc = ldisc_create(&cfg, term, back, backhandle, NULL);
250 * Destroy the Restart Session menu item. (This will return
251 * failure if it's already absent, as it will be the very first
252 * time we call this function. We ignore that, because as long
253 * as the menu item ends up not being there, we don't care
254 * whether it was us who removed it or not!)
256 for (i = 0; i < lenof(popup_menus); i++) {
257 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
260 session_closed = FALSE;
263 static void close_session(void)
268 session_closed = TRUE;
269 sprintf(morestuff, "%.70s (inactive)", appname);
270 set_icon(NULL, morestuff);
271 set_title(NULL, morestuff);
278 back->free(backhandle);
281 update_specials_menu(NULL);
285 * Show the Restart Session menu item. Do a precautionary
286 * delete first to ensure we never end up with more than one.
288 for (i = 0; i < lenof(popup_menus); i++) {
289 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
290 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
291 IDM_RESTART, "&Restart Session");
295 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
299 int guess_width, guess_height;
302 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
306 InitCommonControls();
308 /* Ensure a Maximize setting in Explorer doesn't maximise the
314 char *str = dupprintf("%s Fatal Error", appname);
315 MessageBox(NULL, "Windows refuses to report a version",
316 str, MB_OK | MB_ICONEXCLAMATION);
322 * If we're running a version of Windows that doesn't support
323 * WM_MOUSEWHEEL, find out what message number we should be
326 if (osVersion.dwMajorVersion < 4 ||
327 (osVersion.dwMajorVersion == 4 &&
328 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
329 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
332 * See if we can find our Help file.
335 char b[2048], *p, *q, *r;
337 GetModuleFileName(NULL, b, sizeof(b) - 1);
339 p = strrchr(b, '\\');
340 if (p && p >= r) r = p+1;
342 if (q && q >= r) r = q+1;
343 strcpy(r, "putty.hlp");
344 if ( (fp = fopen(b, "r")) != NULL) {
345 help_path = dupstr(b);
349 strcpy(r, "putty.cnt");
350 if ( (fp = fopen(b, "r")) != NULL) {
351 help_has_contents = TRUE;
354 help_has_contents = FALSE;
358 * Process the command line.
364 default_protocol = be_default_protocol;
365 /* Find the appropriate default port. */
368 default_port = 0; /* illegal */
369 for (i = 0; backends[i].backend != NULL; i++)
370 if (backends[i].protocol == default_protocol) {
371 default_port = backends[i].backend->default_port;
375 cfg.logtype = LGTYP_NONE;
377 do_defaults(NULL, &cfg);
382 * Process a couple of command-line options which are more
383 * easily dealt with before the line is broken up into
384 * words. These are the soon-to-be-defunct @sessionname and
385 * the internal-use-only &sharedmemoryhandle, neither of
386 * which are combined with anything else.
388 while (*p && isspace(*p))
392 while (i > 1 && isspace(p[i - 1]))
395 do_defaults(p + 1, &cfg);
396 if (!*cfg.host && !do_config()) {
399 } else if (*p == '&') {
401 * An initial & means we've been given a command line
402 * containing the hex value of a HANDLE for a file
403 * mapping object, which we must then extract as a
408 if (sscanf(p + 1, "%p", &filemap) == 1 &&
409 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
410 0, 0, sizeof(Config))) != NULL) {
413 CloseHandle(filemap);
414 } else if (!do_config()) {
419 * Otherwise, break up the command line and deal with
425 split_into_argv(cmdline, &argc, &argv, NULL);
427 for (i = 0; i < argc; i++) {
431 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
434 cmdline_error("option \"%s\" requires an argument", p);
435 } else if (ret == 2) {
436 i++; /* skip next argument */
437 } else if (ret == 1) {
438 continue; /* nothing further needs doing */
439 } else if (!strcmp(p, "-cleanup")) {
441 * `putty -cleanup'. Remove all registry
442 * entries associated with PuTTY, and also find
443 * and delete the random seed file.
446 s1 = dupprintf("This procedure will remove ALL Registry\n"
447 "entries associated with %s, and will\n"
448 "also remove the random seed file.\n"
450 "THIS PROCESS WILL DESTROY YOUR SAVED\n"
451 "SESSIONS. Are you really sure you want\n"
452 "to continue?", appname);
453 s2 = dupprintf("%s Warning", appname);
454 if (MessageBox(NULL, s1, s2,
455 MB_YESNO | MB_ICONWARNING) == IDYES) {
461 } else if (*p != '-') {
465 * If we already have a host name, treat
466 * this argument as a port number. NB we
467 * have to treat this as a saved -P
468 * argument, so that it will be deferred
469 * until it's a good moment to run it.
471 int ret = cmdline_process_param("-P", p, 1, &cfg);
473 } else if (!strncmp(q, "telnet:", 7)) {
475 * If the hostname starts with "telnet:",
476 * set the protocol to Telnet and process
477 * the string as a Telnet URL.
482 if (q[0] == '/' && q[1] == '/')
484 cfg.protocol = PROT_TELNET;
486 while (*p && *p != ':' && *p != '/')
495 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
496 cfg.host[sizeof(cfg.host) - 1] = '\0';
500 * Otherwise, treat this argument as a host
503 while (*p && !isspace(*p))
507 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
508 cfg.host[sizeof(cfg.host) - 1] = '\0';
512 cmdline_error("unknown option \"%s\"", p);
517 cmdline_run_saved(&cfg);
519 if (!*cfg.host && !do_config()) {
524 * Trim leading whitespace off the hostname if it's there.
527 int space = strspn(cfg.host, " \t");
528 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
531 /* See if host is of the form user@host */
532 if (cfg.host[0] != '\0') {
533 char *atsign = strrchr(cfg.host, '@');
534 /* Make sure we're not overflowing the user field */
536 if (atsign - cfg.host < sizeof cfg.username) {
537 strncpy(cfg.username, cfg.host, atsign - cfg.host);
538 cfg.username[atsign - cfg.host] = '\0';
540 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
545 * Trim a colon suffix off the hostname if it's there.
547 cfg.host[strcspn(cfg.host, ":")] = '\0';
550 * Remove any remaining whitespace from the hostname.
554 while (cfg.host[p2] != '\0') {
555 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
556 cfg.host[p1] = cfg.host[p2];
565 /* Check for invalid Port number (i.e. zero) */
567 char *str = dupprintf("%s Internal Error", appname);
568 MessageBox(NULL, "Invalid Port Number",
569 str, MB_OK | MB_ICONEXCLAMATION);
576 wndclass.lpfnWndProc = WndProc;
577 wndclass.cbClsExtra = 0;
578 wndclass.cbWndExtra = 0;
579 wndclass.hInstance = inst;
580 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
581 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
582 wndclass.hbrBackground = NULL;
583 wndclass.lpszMenuName = NULL;
584 wndclass.lpszClassName = appname;
586 RegisterClass(&wndclass);
591 memset(&ucsdata, 0, sizeof(ucsdata));
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 guess_width = extra_width + font_width * cfg.width;
607 guess_height = extra_height + font_height * cfg.height;
610 get_fullscreen_rect(&r);
611 if (guess_width > r.right - r.left)
612 guess_width = r.right - r.left;
613 if (guess_height > r.bottom - r.top)
614 guess_height = r.bottom - r.top;
618 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
621 winmode &= ~(WS_VSCROLL);
622 if (cfg.resize_action == RESIZE_DISABLED)
623 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
625 exwinmode |= WS_EX_TOPMOST;
627 exwinmode |= WS_EX_CLIENTEDGE;
628 hwnd = CreateWindowEx(exwinmode, appname, appname,
629 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
630 guess_width, guess_height,
631 NULL, NULL, inst, NULL);
635 * Initialise the terminal. (We have to do this _after_
636 * creating the window, since the terminal is the first thing
637 * which will call schedule_timer(), which will in turn call
638 * timer_change_notify() which will expect hwnd to exist.)
640 term = term_init(&cfg, &ucsdata, NULL);
641 logctx = log_init(NULL, &cfg);
642 term_provide_logctx(term, logctx);
643 term_size(term, cfg.height, cfg.width, cfg.savelines);
646 * Initialise the fonts, simultaneously correcting the guesses
647 * for font_{width,height}.
652 * Correct the guesses for extra_{width,height}.
656 GetWindowRect(hwnd, &wr);
657 GetClientRect(hwnd, &cr);
658 offset_width = offset_height = cfg.window_border;
659 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
660 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
664 * Resize the window, now we know what size we _really_ want it
667 guess_width = extra_width + font_width * term->cols;
668 guess_height = extra_height + font_height * term->rows;
669 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
670 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
673 * Set up a caret bitmap, with no content.
677 int size = (font_width + 15) / 16 * 2 * font_height;
678 bits = snewn(size, char);
679 memset(bits, 0, size);
680 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
683 CreateCaret(hwnd, caretbm, font_width, font_height);
686 * Initialise the scroll bar.
691 si.cbSize = sizeof(si);
692 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
694 si.nMax = term->rows - 1;
695 si.nPage = term->rows;
697 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
701 * Prepare the mouse handler.
703 lastact = MA_NOTHING;
704 lastbtn = MBT_NOTHING;
705 dbltime = GetDoubleClickTime();
708 * Set up the session-control options on the system menu.
715 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
716 popup_menus[CTXMENU].menu = CreatePopupMenu();
717 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
720 get_sesslist(&sesslist, TRUE);
721 /* skip sesslist.sessions[0] == Default Settings */
723 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
726 AppendMenu(s, MF_ENABLED, IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
727 sesslist.sessions[i]);
729 for (j = 0; j < lenof(popup_menus); j++) {
730 m = popup_menus[j].menu;
732 AppendMenu(m, MF_SEPARATOR, 0, 0);
733 popup_menus[j].specials_submenu_pos = GetMenuItemCount(m);
734 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
735 AppendMenu(m, MF_SEPARATOR, 0, 0);
736 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
737 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
738 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) s, "Sa&ved Sessions");
739 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
740 AppendMenu(m, MF_SEPARATOR, 0, 0);
741 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
742 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
743 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
744 AppendMenu(m, MF_SEPARATOR, 0, 0);
745 AppendMenu(m, (cfg.resize_action == RESIZE_DISABLED) ?
746 MF_GRAYED : MF_ENABLED, IDM_FULLSCREEN, "&Full Screen");
747 AppendMenu(m, MF_SEPARATOR, 0, 0);
749 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
750 str = dupprintf("&About %s", appname);
751 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
759 * Set up the initial input locale.
761 set_input_locale(GetKeyboardLayout(0));
764 * Open the initial log file if there is one.
769 * Finally show the window!
771 ShowWindow(hwnd, show);
772 SetForegroundWindow(hwnd);
775 * Set the palette up.
781 term_set_focus(term, GetForegroundWindow() == hwnd);
784 if (GetMessage(&msg, NULL, 0, 0) == 1) {
785 while (msg.message != WM_QUIT) {
786 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
787 DispatchMessage(&msg);
788 /* Send the paste buffer if there's anything to send */
790 /* If there's nothing new in the queue then we can do everything
791 * we've delayed, reading the socket, writing, and repainting
794 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
797 /* The messages seem unreliable; especially if we're being tricky */
798 term_set_focus(term, GetForegroundWindow() == hwnd);
800 net_pending_errors();
802 /* There's no point rescanning everything in the message queue
803 * so we do an apparently unnecessary wait here
806 if (GetMessage(&msg, NULL, 0, 0) != 1)
811 cleanup_exit(msg.wParam); /* this doesn't return... */
812 return msg.wParam; /* ... but optimiser doesn't know */
818 void cleanup_exit(int code)
829 if (cfg.protocol == PROT_SSH) {
840 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
842 char *do_select(SOCKET skt, int startup)
847 events = (FD_CONNECT | FD_READ | FD_WRITE |
848 FD_OOB | FD_CLOSE | FD_ACCEPT);
853 return "do_select(): internal error (hwnd==NULL)";
854 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
855 switch (p_WSAGetLastError()) {
857 return "Network is down";
859 return "WSAAsyncSelect(): unknown error";
866 * Update the Special Commands submenu.
868 void update_specials_menu(void *frontend)
871 int menu_already_exists = (specials != NULL);
875 specials = back->get_specials(backhandle);
880 /* We can't use Windows to provide a stack for submenus, so
881 * here's a lame "stack" that will do for now. */
882 HMENU saved_menu = NULL;
884 p = CreatePopupMenu();
885 for (i = 0; nesting > 0; i++) {
886 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
887 switch (specials[i].code) {
889 AppendMenu(p, MF_SEPARATOR, 0, 0);
894 saved_menu = p; /* XXX lame stacking */
895 p = CreatePopupMenu();
896 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
897 (UINT) p, specials[i].name);
902 p = saved_menu; /* XXX lame stacking */
907 AppendMenu(p, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
912 /* Squirrel the highest special. */
919 for (j = 0; j < lenof(popup_menus); j++) {
920 if (menu_already_exists) {
921 /* XXX does this free up all submenus? */
922 DeleteMenu(popup_menus[j].menu,
923 popup_menus[j].specials_submenu_pos,
925 DeleteMenu(popup_menus[j].menu,
926 popup_menus[j].specials_submenu_pos,
930 InsertMenu(popup_menus[j].menu,
931 popup_menus[j].specials_submenu_pos,
932 MF_BYPOSITION | MF_SEPARATOR, 0, 0);
933 InsertMenu(popup_menus[j].menu,
934 popup_menus[j].specials_submenu_pos,
935 MF_BYPOSITION | MF_POPUP | MF_ENABLED,
936 (UINT) p, "S&pecial Command");
942 * set or clear the "raw mouse message" mode
944 void set_raw_mouse_mode(void *frontend, int activate)
946 activate = activate && !cfg.no_mouse_rep;
947 send_raw_mouse = activate;
948 SetCursor(LoadCursor(NULL, activate ? IDC_ARROW : IDC_IBEAM));
952 * Print a message box and close the connection.
954 void connection_fatal(void *frontend, char *fmt, ...)
957 char *stuff, morestuff[100];
960 stuff = dupvprintf(fmt, ap);
962 sprintf(morestuff, "%.70s Fatal Error", appname);
963 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
966 if (cfg.close_on_exit == FORCE_ON)
974 * Report an error at the command-line parsing stage.
976 void cmdline_error(char *fmt, ...)
979 char *stuff, morestuff[100];
982 stuff = dupvprintf(fmt, ap);
984 sprintf(morestuff, "%.70s Command Line Error", appname);
985 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
991 * Actually do the job requested by a WM_NETEVENT
993 static void enact_netevent(WPARAM wParam, LPARAM lParam)
995 static int reentering = 0;
996 extern int select_result(WPARAM, LPARAM);
1000 return; /* don't unpend the pending */
1003 ret = select_result(wParam, lParam);
1006 if (ret == 0 && !session_closed) {
1007 /* Abnormal exits will already have set session_closed and taken
1008 * appropriate action. */
1009 if (cfg.close_on_exit == FORCE_ON ||
1010 cfg.close_on_exit == AUTO) PostQuitMessage(0);
1013 session_closed = TRUE;
1014 MessageBox(hwnd, "Connection closed by remote host",
1015 appname, MB_OK | MB_ICONINFORMATION);
1021 * Copy the colour palette from the configuration data into defpal.
1022 * This is non-trivial because the colour indices are different.
1024 static void cfgtopalette(void)
1027 static const int ww[] = {
1028 256, 257, 258, 259, 260, 261,
1029 0, 8, 1, 9, 2, 10, 3, 11,
1030 4, 12, 5, 13, 6, 14, 7, 15
1033 for (i = 0; i < 22; i++) {
1035 defpal[w].rgbtRed = cfg.colours[i][0];
1036 defpal[w].rgbtGreen = cfg.colours[i][1];
1037 defpal[w].rgbtBlue = cfg.colours[i][2];
1039 for (i = 0; i < NEXTCOLOURS; i++) {
1041 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1042 defpal[i+16].rgbtRed = r * 0x33;
1043 defpal[i+16].rgbtGreen = g * 0x33;
1044 defpal[i+16].rgbtBlue = b * 0x33;
1046 int shade = i - 216;
1047 shade = (shade + 1) * 0xFF / (NEXTCOLOURS - 216 + 1);
1048 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1049 defpal[i+16].rgbtBlue = shade;
1053 /* Override with system colours if appropriate */
1054 if (cfg.system_colour)
1059 * Override bit of defpal with colours from the system.
1060 * (NB that this takes a copy the system colours at the time this is called,
1061 * so subsequent colour scheme changes don't take effect. To fix that we'd
1062 * probably want to be using GetSysColorBrush() and the like.)
1064 static void systopalette(void)
1067 static const struct { int nIndex; int norm; int bold; } or[] =
1069 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1070 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1071 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1072 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1075 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1076 COLORREF colour = GetSysColor(or[i].nIndex);
1077 defpal[or[i].norm].rgbtRed =
1078 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1079 defpal[or[i].norm].rgbtGreen =
1080 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1081 defpal[or[i].norm].rgbtBlue =
1082 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1087 * Set up the colour palette.
1089 static void init_palette(void)
1092 HDC hdc = GetDC(hwnd);
1094 if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1096 * This is a genuine case where we must use smalloc
1097 * because the snew macros can't cope.
1099 logpal = smalloc(sizeof(*logpal)
1100 - sizeof(logpal->palPalEntry)
1101 + NALLCOLOURS * sizeof(PALETTEENTRY));
1102 logpal->palVersion = 0x300;
1103 logpal->palNumEntries = NALLCOLOURS;
1104 for (i = 0; i < NALLCOLOURS; i++) {
1105 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1106 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1107 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1108 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1110 pal = CreatePalette(logpal);
1112 SelectPalette(hdc, pal, FALSE);
1113 RealizePalette(hdc);
1114 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1117 ReleaseDC(hwnd, hdc);
1120 for (i = 0; i < NALLCOLOURS; i++)
1121 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1122 defpal[i].rgbtGreen,
1123 defpal[i].rgbtBlue);
1125 for (i = 0; i < NALLCOLOURS; i++)
1126 colours[i] = RGB(defpal[i].rgbtRed,
1127 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1131 * This is a wrapper to ExtTextOut() to force Windows to display
1132 * the precise glyphs we give it. Otherwise it would do its own
1133 * bidi and Arabic shaping, and we would end up uncertain which
1134 * characters it had put where.
1136 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1137 unsigned short *lpString, UINT cbCount,
1138 CONST INT *lpDx, int opaque)
1142 char *buffer = snewn(cbCount*2+2, char);
1143 char *classbuffer = snewn(cbCount, char);
1144 memset(&gcpr, 0, sizeof(gcpr));
1145 memset(buffer, 0, cbCount*2+2);
1146 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1148 gcpr.lStructSize = sizeof(gcpr);
1149 gcpr.lpGlyphs = (void *)buffer;
1150 gcpr.lpClass = classbuffer;
1151 gcpr.nGlyphs = cbCount;
1153 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1154 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1156 ExtTextOut(hdc, x, y,
1157 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1158 lprc, buffer, cbCount, lpDx);
1162 * Initialise all the fonts we will need initially. There may be as many as
1163 * three or as few as one. The other (poentially) twentyone fonts are done
1164 * if/when they are needed.
1168 * - check the font width and height, correcting our guesses if
1171 * - verify that the bold font is the same width as the ordinary
1172 * one, and engage shadow bolding if not.
1174 * - verify that the underlined font is the same width as the
1175 * ordinary one (manual underlining by means of line drawing can
1176 * be done in a pinch).
1178 static void init_fonts(int pick_width, int pick_height)
1185 int fw_dontcare, fw_bold;
1187 for (i = 0; i < FONT_MAXNO; i++)
1190 bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
1191 und_mode = UND_FONT;
1193 if (cfg.font.isbold) {
1194 fw_dontcare = FW_BOLD;
1197 fw_dontcare = FW_DONTCARE;
1204 font_height = pick_height;
1206 font_height = cfg.font.height;
1207 if (font_height > 0) {
1209 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1212 font_width = pick_width;
1214 #define f(i,c,w,u) \
1215 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1216 c, OUT_DEFAULT_PRECIS, \
1217 CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, \
1218 FIXED_PITCH | FF_DONTCARE, cfg.font.name)
1220 f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);
1222 lfont.lfHeight = font_height;
1223 lfont.lfWidth = font_width;
1224 lfont.lfEscapement = 0;
1225 lfont.lfOrientation = 0;
1226 lfont.lfWeight = fw_dontcare;
1227 lfont.lfItalic = FALSE;
1228 lfont.lfUnderline = FALSE;
1229 lfont.lfStrikeOut = FALSE;
1230 lfont.lfCharSet = cfg.font.charset;
1231 lfont.lfOutPrecision = OUT_DEFAULT_PRECIS;
1232 lfont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1233 lfont.lfQuality = DEFAULT_QUALITY;
1234 lfont.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE;
1235 strncpy(lfont.lfFaceName, cfg.font.name, LF_FACESIZE);
1237 SelectObject(hdc, fonts[FONT_NORMAL]);
1238 GetTextMetrics(hdc, &tm);
1240 if (pick_width == 0 || pick_height == 0) {
1241 font_height = tm.tmHeight;
1242 font_width = tm.tmAveCharWidth;
1244 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1246 #ifdef RDB_DEBUG_PATCH
1247 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1248 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1253 DWORD cset = tm.tmCharSet;
1254 memset(&info, 0xFF, sizeof(info));
1256 /* !!! Yes the next line is right */
1257 if (cset == OEM_CHARSET)
1258 ucsdata.font_codepage = GetOEMCP();
1260 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1261 ucsdata.font_codepage = info.ciACP;
1263 ucsdata.font_codepage = -1;
1265 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1266 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1269 f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);
1272 * Some fonts, e.g. 9-pt Courier, draw their underlines
1273 * outside their character cell. We successfully prevent
1274 * screen corruption by clipping the text output, but then
1275 * we lose the underline completely. Here we try to work
1276 * out whether this is such a font, and if it is, we set a
1277 * flag that causes underlines to be drawn by hand.
1279 * Having tried other more sophisticated approaches (such
1280 * as examining the TEXTMETRIC structure or requesting the
1281 * height of a string), I think we'll do this the brute
1282 * force way: we create a small bitmap, draw an underlined
1283 * space on it, and test to see whether any pixels are
1284 * foreground-coloured. (Since we expect the underline to
1285 * go all the way across the character cell, we only search
1286 * down a single column of the bitmap, half way across.)
1290 HBITMAP und_bm, und_oldbm;
1294 und_dc = CreateCompatibleDC(hdc);
1295 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1296 und_oldbm = SelectObject(und_dc, und_bm);
1297 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1298 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1299 SetTextColor(und_dc, RGB(255, 255, 255));
1300 SetBkColor(und_dc, RGB(0, 0, 0));
1301 SetBkMode(und_dc, OPAQUE);
1302 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1304 for (i = 0; i < font_height; i++) {
1305 c = GetPixel(und_dc, font_width / 2, i);
1306 if (c != RGB(0, 0, 0))
1309 SelectObject(und_dc, und_oldbm);
1310 DeleteObject(und_bm);
1313 und_mode = UND_LINE;
1314 DeleteObject(fonts[FONT_UNDERLINE]);
1315 fonts[FONT_UNDERLINE] = 0;
1319 if (bold_mode == BOLD_FONT) {
1320 f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);
1324 descent = tm.tmAscent + 1;
1325 if (descent >= font_height)
1326 descent = font_height - 1;
1328 for (i = 0; i < 3; i++) {
1330 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1331 fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
1338 ReleaseDC(hwnd, hdc);
1340 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1341 und_mode = UND_LINE;
1342 DeleteObject(fonts[FONT_UNDERLINE]);
1343 fonts[FONT_UNDERLINE] = 0;
1346 if (bold_mode == BOLD_FONT &&
1347 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1348 bold_mode = BOLD_SHADOW;
1349 DeleteObject(fonts[FONT_BOLD]);
1350 fonts[FONT_BOLD] = 0;
1352 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1354 init_ucs(&cfg, &ucsdata);
1357 static void another_font(int fontno)
1360 int fw_dontcare, fw_bold;
1364 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1367 basefont = (fontno & ~(FONT_BOLDUND));
1368 if (basefont != fontno && !fontflag[basefont])
1369 another_font(basefont);
1371 if (cfg.font.isbold) {
1372 fw_dontcare = FW_BOLD;
1375 fw_dontcare = FW_DONTCARE;
1379 c = cfg.font.charset;
1385 if (fontno & FONT_WIDE)
1387 if (fontno & FONT_NARROW)
1389 if (fontno & FONT_OEM)
1391 if (fontno & FONT_BOLD)
1393 if (fontno & FONT_UNDERLINE)
1397 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1398 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1399 CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
1400 FIXED_PITCH | FF_DONTCARE, s);
1402 fontflag[fontno] = 1;
1405 static void deinit_fonts(void)
1408 for (i = 0; i < FONT_MAXNO; i++) {
1410 DeleteObject(fonts[i]);
1416 void request_resize(void *frontend, int w, int h)
1420 /* If the window is maximized supress resizing attempts */
1421 if (IsZoomed(hwnd)) {
1422 if (cfg.resize_action == RESIZE_TERM)
1426 if (cfg.resize_action == RESIZE_DISABLED) return;
1427 if (h == term->rows && w == term->cols) return;
1429 /* Sanity checks ... */
1431 static int first_time = 1;
1434 switch (first_time) {
1436 /* Get the size of the screen */
1437 if (get_fullscreen_rect(&ss))
1438 /* first_time = 0 */ ;
1444 /* Make sure the values are sane */
1445 width = (ss.right - ss.left - extra_width) / 4;
1446 height = (ss.bottom - ss.top - extra_height) / 6;
1448 if (w > width || h > height)
1457 term_size(term, h, w, cfg.savelines);
1459 if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {
1460 width = extra_width + font_width * w;
1461 height = extra_height + font_height * h;
1463 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1464 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1465 SWP_NOMOVE | SWP_NOZORDER);
1469 InvalidateRect(hwnd, NULL, TRUE);
1472 static void reset_window(int reinit) {
1474 * This function decides how to resize or redraw when the
1475 * user changes something.
1477 * This function doesn't like to change the terminal size but if the
1478 * font size is locked that may be it's only soluion.
1480 int win_width, win_height;
1483 #ifdef RDB_DEBUG_PATCH
1484 debug((27, "reset_window()"));
1487 /* Current window sizes ... */
1488 GetWindowRect(hwnd, &wr);
1489 GetClientRect(hwnd, &cr);
1491 win_width = cr.right - cr.left;
1492 win_height = cr.bottom - cr.top;
1494 if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;
1496 /* Are we being forced to reload the fonts ? */
1498 #ifdef RDB_DEBUG_PATCH
1499 debug((27, "reset_window() -- Forced deinit"));
1505 /* Oh, looks like we're minimised */
1506 if (win_width == 0 || win_height == 0)
1509 /* Is the window out of position ? */
1511 (offset_width != (win_width-font_width*term->cols)/2 ||
1512 offset_height != (win_height-font_height*term->rows)/2) ){
1513 offset_width = (win_width-font_width*term->cols)/2;
1514 offset_height = (win_height-font_height*term->rows)/2;
1515 InvalidateRect(hwnd, NULL, TRUE);
1516 #ifdef RDB_DEBUG_PATCH
1517 debug((27, "reset_window() -> Reposition terminal"));
1521 if (IsZoomed(hwnd)) {
1522 /* We're fullscreen, this means we must not change the size of
1523 * the window so it's the font size or the terminal itself.
1526 extra_width = wr.right - wr.left - cr.right + cr.left;
1527 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1529 if (cfg.resize_action != RESIZE_TERM) {
1530 if ( font_width != win_width/term->cols ||
1531 font_height != win_height/term->rows) {
1533 init_fonts(win_width/term->cols, win_height/term->rows);
1534 offset_width = (win_width-font_width*term->cols)/2;
1535 offset_height = (win_height-font_height*term->rows)/2;
1536 InvalidateRect(hwnd, NULL, TRUE);
1537 #ifdef RDB_DEBUG_PATCH
1538 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1539 font_width, font_height));
1543 if ( font_width != win_width/term->cols ||
1544 font_height != win_height/term->rows) {
1545 /* Our only choice at this point is to change the
1546 * size of the terminal; Oh well.
1548 term_size(term, win_height/font_height, win_width/font_width,
1550 offset_width = (win_width-font_width*term->cols)/2;
1551 offset_height = (win_height-font_height*term->rows)/2;
1552 InvalidateRect(hwnd, NULL, TRUE);
1553 #ifdef RDB_DEBUG_PATCH
1554 debug((27, "reset_window() -> Zoomed term_size"));
1561 /* Hmm, a force re-init means we should ignore the current window
1562 * so we resize to the default font size.
1565 #ifdef RDB_DEBUG_PATCH
1566 debug((27, "reset_window() -> Forced re-init"));
1569 offset_width = offset_height = cfg.window_border;
1570 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1571 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1573 if (win_width != font_width*term->cols + offset_width*2 ||
1574 win_height != font_height*term->rows + offset_height*2) {
1576 /* If this is too large windows will resize it to the maximum
1577 * allowed window size, we will then be back in here and resize
1578 * the font or terminal to fit.
1580 SetWindowPos(hwnd, NULL, 0, 0,
1581 font_width*term->cols + extra_width,
1582 font_height*term->rows + extra_height,
1583 SWP_NOMOVE | SWP_NOZORDER);
1586 InvalidateRect(hwnd, NULL, TRUE);
1590 /* Okay the user doesn't want us to change the font so we try the
1591 * window. But that may be too big for the screen which forces us
1592 * to change the terminal.
1594 if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||
1595 (cfg.resize_action == RESIZE_EITHER && reinit<0) ||
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) {
1607 get_fullscreen_rect(&ss);
1609 width = (ss.right - ss.left - extra_width) / font_width;
1610 height = (ss.bottom - ss.top - extra_height) / font_height;
1613 if ( term->rows > height || term->cols > width ) {
1614 if (cfg.resize_action == RESIZE_EITHER) {
1615 /* Make the font the biggest we can */
1616 if (term->cols > width)
1617 font_width = (ss.right - ss.left - extra_width)
1619 if (term->rows > height)
1620 font_height = (ss.bottom - ss.top - extra_height)
1624 init_fonts(font_width, font_height);
1626 width = (ss.right - ss.left - extra_width) / font_width;
1627 height = (ss.bottom - ss.top - extra_height) / font_height;
1629 if ( height > term->rows ) height = term->rows;
1630 if ( width > term->cols ) width = term->cols;
1631 term_size(term, height, width, cfg.savelines);
1632 #ifdef RDB_DEBUG_PATCH
1633 debug((27, "reset_window() -> term resize to (%d,%d)",
1639 SetWindowPos(hwnd, NULL, 0, 0,
1640 font_width*term->cols + extra_width,
1641 font_height*term->rows + extra_height,
1642 SWP_NOMOVE | SWP_NOZORDER);
1644 InvalidateRect(hwnd, NULL, TRUE);
1645 #ifdef RDB_DEBUG_PATCH
1646 debug((27, "reset_window() -> window resize to (%d,%d)",
1647 font_width*term->cols + extra_width,
1648 font_height*term->rows + extra_height));
1654 /* We're allowed to or must change the font but do we want to ? */
1656 if (font_width != (win_width-cfg.window_border*2)/term->cols ||
1657 font_height != (win_height-cfg.window_border*2)/term->rows) {
1660 init_fonts((win_width-cfg.window_border*2)/term->cols,
1661 (win_height-cfg.window_border*2)/term->rows);
1662 offset_width = (win_width-font_width*term->cols)/2;
1663 offset_height = (win_height-font_height*term->rows)/2;
1665 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1666 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1668 InvalidateRect(hwnd, NULL, TRUE);
1669 #ifdef RDB_DEBUG_PATCH
1670 debug((25, "reset_window() -> font resize to (%d,%d)",
1671 font_width, font_height));
1676 static void set_input_locale(HKL kl)
1680 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1681 lbuf, sizeof(lbuf));
1683 kbd_codepage = atoi(lbuf);
1686 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1688 int thistime = GetMessageTime();
1690 if (send_raw_mouse && !(cfg.mouse_override && shift)) {
1691 lastbtn = MBT_NOTHING;
1692 term_mouse(term, b, translate_button(b), MA_CLICK,
1693 x, y, shift, ctrl, alt);
1697 if (lastbtn == b && thistime - lasttime < dbltime) {
1698 lastact = (lastact == MA_CLICK ? MA_2CLK :
1699 lastact == MA_2CLK ? MA_3CLK :
1700 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1705 if (lastact != MA_NOTHING)
1706 term_mouse(term, b, translate_button(b), lastact,
1707 x, y, shift, ctrl, alt);
1708 lasttime = thistime;
1712 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1713 * into a cooked one (SELECT, EXTEND, PASTE).
1715 static Mouse_Button translate_button(Mouse_Button button)
1717 if (button == MBT_LEFT)
1719 if (button == MBT_MIDDLE)
1720 return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
1721 if (button == MBT_RIGHT)
1722 return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
1723 return 0; /* shouldn't happen */
1726 static void show_mouseptr(int show)
1728 static int cursor_visible = 1;
1729 if (!cfg.hide_mouseptr) /* override if this feature disabled */
1731 if (cursor_visible && !show)
1733 else if (!cursor_visible && show)
1735 cursor_visible = show;
1738 static int is_alt_pressed(void)
1741 int r = GetKeyboardState(keystate);
1744 if (keystate[VK_MENU] & 0x80)
1746 if (keystate[VK_RMENU] & 0x80)
1751 static int is_shift_pressed(void)
1754 int r = GetKeyboardState(keystate);
1757 if (keystate[VK_SHIFT] & 0x80)
1762 static int resizing;
1764 void notify_remote_exit(void *fe) { /* stub not needed in this frontend */ }
1766 void timer_change_notify(long next)
1768 long ticks = next - GETTICKCOUNT();
1769 if (ticks <= 0) ticks = 1; /* just in case */
1770 KillTimer(hwnd, TIMING_TIMER_ID);
1771 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
1772 timing_next_time = next;
1775 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1776 WPARAM wParam, LPARAM lParam)
1779 static int ignore_clip = FALSE;
1780 static int need_backend_resize = FALSE;
1781 static int fullscr_on_max = FALSE;
1782 static UINT last_mousemove = 0;
1786 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
1789 KillTimer(hwnd, TIMING_TIMER_ID);
1790 if (run_timers(timing_next_time, &next)) {
1791 timer_change_notify(next);
1802 str = dupprintf("%s Exit Confirmation", appname);
1803 if (!cfg.warn_on_close || session_closed ||
1805 "Are you sure you want to close this session?",
1806 str, MB_ICONWARNING | MB_OKCANCEL) == IDOK)
1807 DestroyWindow(hwnd);
1817 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
1829 PROCESS_INFORMATION pi;
1830 HANDLE filemap = NULL;
1832 if (wParam == IDM_DUPSESS) {
1834 * Allocate a file-mapping memory chunk for the
1837 SECURITY_ATTRIBUTES sa;
1840 sa.nLength = sizeof(sa);
1841 sa.lpSecurityDescriptor = NULL;
1842 sa.bInheritHandle = TRUE;
1843 filemap = CreateFileMapping((HANDLE) 0xFFFFFFFF,
1846 0, sizeof(Config), NULL);
1848 p = (Config *) MapViewOfFile(filemap,
1850 0, 0, sizeof(Config));
1852 *p = cfg; /* structure copy */
1856 sprintf(c, "putty &%p", filemap);
1858 } else if (wParam == IDM_SAVEDSESS) {
1859 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
1860 / MENU_SAVED_STEP) + 1;
1861 if (sessno < sesslist.nsessions) {
1862 char *session = sesslist.sessions[sessno];
1863 /* XXX spaces? quotes? "-load"? */
1864 cl = dupprintf("putty @%s", session);
1871 GetModuleFileName(NULL, b, sizeof(b) - 1);
1873 si.lpReserved = NULL;
1874 si.lpDesktop = NULL;
1878 si.lpReserved2 = NULL;
1879 CreateProcess(b, cl, NULL, NULL, TRUE,
1880 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
1883 CloseHandle(filemap);
1890 logevent(NULL, "----- Session restarted -----");
1900 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
1903 if (!do_reconfig(hwnd))
1907 /* Disable full-screen if resizing forbidden */
1908 HMENU m = GetSystemMenu (hwnd, FALSE);
1909 EnableMenuItem(m, IDM_FULLSCREEN, MF_BYCOMMAND |
1910 (cfg.resize_action == RESIZE_DISABLED)
1911 ? MF_GRAYED : MF_ENABLED);
1912 /* Gracefully unzoom if necessary */
1913 if (IsZoomed(hwnd) &&
1914 (cfg.resize_action == RESIZE_DISABLED)) {
1915 ShowWindow(hwnd, SW_RESTORE);
1919 /* Pass new config data to the logging module */
1920 log_reconfig(logctx, &cfg);
1924 * Flush the line discipline's edit buffer in the
1925 * case where local editing has just been disabled.
1928 ldisc_send(ldisc, NULL, 0, 0);
1936 /* Pass new config data to the terminal */
1937 term_reconfig(term, &cfg);
1939 /* Pass new config data to the back end */
1941 back->reconfig(backhandle, &cfg);
1943 /* Screen size changed ? */
1944 if (cfg.height != prev_cfg.height ||
1945 cfg.width != prev_cfg.width ||
1946 cfg.savelines != prev_cfg.savelines ||
1947 cfg.resize_action == RESIZE_FONT ||
1948 (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
1949 cfg.resize_action == RESIZE_DISABLED)
1950 term_size(term, cfg.height, cfg.width, cfg.savelines);
1952 /* Enable or disable the scroll bar, etc */
1954 LONG nflg, flag = GetWindowLong(hwnd, GWL_STYLE);
1955 LONG nexflag, exflag =
1956 GetWindowLong(hwnd, GWL_EXSTYLE);
1959 if (cfg.alwaysontop != prev_cfg.alwaysontop) {
1960 if (cfg.alwaysontop) {
1961 nexflag |= WS_EX_TOPMOST;
1962 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
1963 SWP_NOMOVE | SWP_NOSIZE);
1965 nexflag &= ~(WS_EX_TOPMOST);
1966 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
1967 SWP_NOMOVE | SWP_NOSIZE);
1970 if (cfg.sunken_edge)
1971 nexflag |= WS_EX_CLIENTEDGE;
1973 nexflag &= ~(WS_EX_CLIENTEDGE);
1976 if (is_full_screen() ?
1977 cfg.scrollbar_in_fullscreen : cfg.scrollbar)
1980 nflg &= ~WS_VSCROLL;
1982 if (cfg.resize_action == RESIZE_DISABLED ||
1984 nflg &= ~WS_THICKFRAME;
1986 nflg |= WS_THICKFRAME;
1988 if (cfg.resize_action == RESIZE_DISABLED)
1989 nflg &= ~WS_MAXIMIZEBOX;
1991 nflg |= WS_MAXIMIZEBOX;
1993 if (nflg != flag || nexflag != exflag) {
1995 SetWindowLong(hwnd, GWL_STYLE, nflg);
1996 if (nexflag != exflag)
1997 SetWindowLong(hwnd, GWL_EXSTYLE, nexflag);
1999 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2000 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2001 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2009 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2014 set_title(NULL, cfg.wintitle);
2015 if (IsIconic(hwnd)) {
2017 cfg.win_name_always ? window_name :
2021 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
2022 strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
2023 cfg.font.isbold != prev_cfg.font.isbold ||
2024 cfg.font.height != prev_cfg.font.height ||
2025 cfg.font.charset != prev_cfg.font.charset ||
2026 cfg.vtmode != prev_cfg.vtmode ||
2027 cfg.bold_colour != prev_cfg.bold_colour ||
2028 cfg.resize_action == RESIZE_DISABLED ||
2029 cfg.resize_action == RESIZE_EITHER ||
2030 (cfg.resize_action != prev_cfg.resize_action))
2033 InvalidateRect(hwnd, NULL, TRUE);
2034 reset_window(init_lvl);
2035 net_pending_errors();
2042 term_do_paste(term);
2050 ldisc_send(ldisc, NULL, 0, 0);
2056 WinHelp(hwnd, help_path,
2057 help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
2061 * We get this if the System menu has been activated
2068 * We get this if the System menu has been activated
2069 * using the keyboard. This might happen from within
2070 * TranslateKey, in which case it really wants to be
2071 * followed by a `space' character to actually _bring
2072 * the menu up_ rather than just sitting there in
2073 * `ready to appear' state.
2075 show_mouseptr(1); /* make sure pointer is visible */
2077 PostMessage(hwnd, WM_CHAR, ' ', 0);
2079 case IDM_FULLSCREEN:
2083 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2084 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2086 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2087 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2089 * Ensure we haven't been sent a bogus SYSCOMMAND
2090 * which would cause us to reference invalid memory
2091 * and crash. Perhaps I'm just too paranoid here.
2093 if (i >= n_specials)
2096 back->special(backhandle, specials[i].code);
2097 net_pending_errors();
2102 #define X_POS(l) ((int)(short)LOWORD(l))
2103 #define Y_POS(l) ((int)(short)HIWORD(l))
2105 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2106 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2107 case WM_LBUTTONDOWN:
2108 case WM_MBUTTONDOWN:
2109 case WM_RBUTTONDOWN:
2113 if (message == WM_RBUTTONDOWN &&
2114 ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
2117 show_mouseptr(1); /* make sure pointer is visible */
2118 GetCursorPos(&cursorpos);
2119 TrackPopupMenu(popup_menus[CTXMENU].menu,
2120 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2121 cursorpos.x, cursorpos.y,
2129 case WM_LBUTTONDOWN:
2133 case WM_MBUTTONDOWN:
2134 button = MBT_MIDDLE;
2137 case WM_RBUTTONDOWN:
2146 button = MBT_MIDDLE;
2154 button = press = 0; /* shouldn't happen */
2158 * Special case: in full-screen mode, if the left
2159 * button is clicked in the very top left corner of the
2160 * window, we put up the System menu instead of doing
2164 char mouse_on_hotspot = 0;
2173 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2176 mi.cbSize = sizeof(MONITORINFO);
2177 GetMonitorInfo(mon, &mi);
2179 if (mi.rcMonitor.left == pt.x &&
2180 mi.rcMonitor.top == pt.y) {
2181 mouse_on_hotspot = 1;
2186 if (pt.x == 0 && pt.y == 0) {
2187 mouse_on_hotspot = 1;
2190 if (is_full_screen() && press &&
2191 button == MBT_LEFT && mouse_on_hotspot) {
2192 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2193 MAKELPARAM(pt.x, pt.y));
2200 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2201 wParam & MK_SHIFT, wParam & MK_CONTROL,
2205 term_mouse(term, button, translate_button(button), MA_RELEASE,
2206 TO_CHR_X(X_POS(lParam)),
2207 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2208 wParam & MK_CONTROL, is_alt_pressed());
2216 * Windows seems to like to occasionally send MOUSEMOVE
2217 * events even if the mouse hasn't moved. Don't unhide
2218 * the mouse pointer in this case.
2220 static WPARAM wp = 0;
2221 static LPARAM lp = 0;
2222 if (wParam != wp || lParam != lp ||
2223 last_mousemove != WM_MOUSEMOVE) {
2225 wp = wParam; lp = lParam;
2226 last_mousemove = WM_MOUSEMOVE;
2230 * Add the mouse position and message time to the random
2233 noise_ultralight(lParam);
2235 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2236 GetCapture() == hwnd) {
2238 if (wParam & MK_LBUTTON)
2240 else if (wParam & MK_MBUTTON)
2244 term_mouse(term, b, translate_button(b), MA_DRAG,
2245 TO_CHR_X(X_POS(lParam)),
2246 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2247 wParam & MK_CONTROL, is_alt_pressed());
2250 case WM_NCMOUSEMOVE:
2252 static WPARAM wp = 0;
2253 static LPARAM lp = 0;
2254 if (wParam != wp || lParam != lp ||
2255 last_mousemove != WM_NCMOUSEMOVE) {
2257 wp = wParam; lp = lParam;
2258 last_mousemove = WM_NCMOUSEMOVE;
2261 noise_ultralight(lParam);
2263 case WM_IGNORE_CLIP:
2264 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2266 case WM_DESTROYCLIPBOARD:
2268 term_deselect(term);
2269 ignore_clip = FALSE;
2276 hdc = BeginPaint(hwnd, &p);
2278 SelectPalette(hdc, pal, TRUE);
2279 RealizePalette(hdc);
2282 term_paint(term, hdc,
2283 (p.rcPaint.left-offset_width)/font_width,
2284 (p.rcPaint.top-offset_height)/font_height,
2285 (p.rcPaint.right-offset_width-1)/font_width,
2286 (p.rcPaint.bottom-offset_height-1)/font_height,
2290 p.rcPaint.left < offset_width ||
2291 p.rcPaint.top < offset_height ||
2292 p.rcPaint.right >= offset_width + font_width*term->cols ||
2293 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2295 HBRUSH fillcolour, oldbrush;
2297 fillcolour = CreateSolidBrush (
2298 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2299 oldbrush = SelectObject(hdc, fillcolour);
2300 edge = CreatePen(PS_SOLID, 0,
2301 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2302 oldpen = SelectObject(hdc, edge);
2305 * Jordan Russell reports that this apparently
2306 * ineffectual IntersectClipRect() call masks a
2307 * Windows NT/2K bug causing strange display
2308 * problems when the PuTTY window is taller than
2309 * the primary monitor. It seems harmless enough...
2311 IntersectClipRect(hdc,
2312 p.rcPaint.left, p.rcPaint.top,
2313 p.rcPaint.right, p.rcPaint.bottom);
2315 ExcludeClipRect(hdc,
2316 offset_width, offset_height,
2317 offset_width+font_width*term->cols,
2318 offset_height+font_height*term->rows);
2320 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2321 p.rcPaint.right, p.rcPaint.bottom);
2323 // SelectClipRgn(hdc, NULL);
2325 SelectObject(hdc, oldbrush);
2326 DeleteObject(fillcolour);
2327 SelectObject(hdc, oldpen);
2330 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2331 SelectObject(hdc, GetStockObject(WHITE_PEN));
2337 enact_netevent(wParam, lParam);
2338 net_pending_errors();
2341 term_set_focus(term, TRUE);
2342 CreateCaret(hwnd, caretbm, font_width, font_height);
2344 flash_window(0); /* stop */
2350 term_set_focus(term, FALSE);
2352 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2355 case WM_ENTERSIZEMOVE:
2356 #ifdef RDB_DEBUG_PATCH
2357 debug((27, "WM_ENTERSIZEMOVE"));
2361 need_backend_resize = FALSE;
2363 case WM_EXITSIZEMOVE:
2366 #ifdef RDB_DEBUG_PATCH
2367 debug((27, "WM_EXITSIZEMOVE"));
2369 if (need_backend_resize) {
2370 term_size(term, cfg.height, cfg.width, cfg.savelines);
2371 InvalidateRect(hwnd, NULL, TRUE);
2376 * This does two jobs:
2377 * 1) Keep the sizetip uptodate
2378 * 2) Make sure the window size is _stepped_ in units of the font size.
2380 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2381 int width, height, w, h, ew, eh;
2382 LPRECT r = (LPRECT) lParam;
2384 if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
2385 (cfg.height != term->rows || cfg.width != term->cols )) {
2387 * Great! It seems that both the terminal size and the
2388 * font size have been changed and the user is now dragging.
2390 * It will now be difficult to get back to the configured
2393 * This would be easier but it seems to be too confusing.
2395 term_size(term, cfg.height, cfg.width, cfg.savelines);
2398 cfg.height=term->rows; cfg.width=term->cols;
2400 InvalidateRect(hwnd, NULL, TRUE);
2401 need_backend_resize = TRUE;
2404 width = r->right - r->left - extra_width;
2405 height = r->bottom - r->top - extra_height;
2406 w = (width + font_width / 2) / font_width;
2409 h = (height + font_height / 2) / font_height;
2412 UpdateSizeTip(hwnd, w, h);
2413 ew = width - w * font_width;
2414 eh = height - h * font_height;
2416 if (wParam == WMSZ_LEFT ||
2417 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2423 if (wParam == WMSZ_TOP ||
2424 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2434 int width, height, w, h, rv = 0;
2435 int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2436 int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2437 LPRECT r = (LPRECT) lParam;
2439 width = r->right - r->left - ex_width;
2440 height = r->bottom - r->top - ex_height;
2442 w = (width + term->cols/2)/term->cols;
2443 h = (height + term->rows/2)/term->rows;
2444 if ( r->right != r->left + w*term->cols + ex_width)
2447 if (wParam == WMSZ_LEFT ||
2448 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2449 r->left = r->right - w*term->cols - ex_width;
2451 r->right = r->left + w*term->cols + ex_width;
2453 if (r->bottom != r->top + h*term->rows + ex_height)
2456 if (wParam == WMSZ_TOP ||
2457 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2458 r->top = r->bottom - h*term->rows - ex_height;
2460 r->bottom = r->top + h*term->rows + ex_height;
2464 /* break; (never reached) */
2465 case WM_FULLSCR_ON_MAX:
2466 fullscr_on_max = TRUE;
2469 sys_cursor_update();
2472 #ifdef RDB_DEBUG_PATCH
2473 debug((27, "WM_SIZE %s (%d,%d)",
2474 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2475 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2476 (wParam == SIZE_RESTORED && resizing) ? "to":
2477 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2479 LOWORD(lParam), HIWORD(lParam)));
2481 if (wParam == SIZE_MINIMIZED)
2483 cfg.win_name_always ? window_name : icon_name);
2484 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2485 SetWindowText(hwnd, window_name);
2486 if (wParam == SIZE_RESTORED)
2487 clear_full_screen();
2488 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2489 fullscr_on_max = FALSE;
2493 if (cfg.resize_action == RESIZE_DISABLED) {
2494 /* A resize, well it better be a minimize. */
2498 int width, height, w, h;
2500 width = LOWORD(lParam);
2501 height = HIWORD(lParam);
2504 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2506 prev_rows = term->rows;
2507 prev_cols = term->cols;
2508 if (cfg.resize_action == RESIZE_TERM) {
2509 w = width / font_width;
2511 h = height / font_height;
2514 term_size(term, h, w, cfg.savelines);
2517 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2519 if (cfg.resize_action == RESIZE_TERM)
2520 term_size(term, prev_rows, prev_cols, cfg.savelines);
2521 if (cfg.resize_action != RESIZE_FONT)
2526 /* This is an unexpected resize, these will normally happen
2527 * if the window is too large. Probably either the user
2528 * selected a huge font or the screen size has changed.
2530 * This is also called with minimize.
2532 else reset_window(-1);
2536 * Don't call back->size in mid-resize. (To prevent
2537 * massive numbers of resize events getting sent
2538 * down the connection during an NT opaque drag.)
2541 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2542 need_backend_resize = TRUE;
2543 w = (width-cfg.window_border*2) / font_width;
2545 h = (height-cfg.window_border*2) / font_height;
2554 sys_cursor_update();
2557 switch (LOWORD(wParam)) {
2559 term_scroll(term, -1, 0);
2562 term_scroll(term, +1, 0);
2565 term_scroll(term, 0, +1);
2568 term_scroll(term, 0, -1);
2571 term_scroll(term, 0, +term->rows / 2);
2574 term_scroll(term, 0, -term->rows / 2);
2576 case SB_THUMBPOSITION:
2578 term_scroll(term, 1, HIWORD(wParam));
2582 case WM_PALETTECHANGED:
2583 if ((HWND) wParam != hwnd && pal != NULL) {
2584 HDC hdc = get_ctx(NULL);
2586 if (RealizePalette(hdc) > 0)
2592 case WM_QUERYNEWPALETTE:
2594 HDC hdc = get_ctx(NULL);
2596 if (RealizePalette(hdc) > 0)
2608 * Add the scan code and keypress timing to the random
2611 noise_ultralight(lParam);
2614 * We don't do TranslateMessage since it disassociates the
2615 * resulting CHAR message from the KEYDOWN that sparked it,
2616 * which we occasionally don't want. Instead, we process
2617 * KEYDOWN, and call the Win32 translator functions so that
2618 * we get the translations under _our_ control.
2621 unsigned char buf[20];
2624 if (wParam == VK_PROCESSKEY) {
2627 m.message = WM_KEYDOWN;
2629 m.lParam = lParam & 0xdfff;
2630 TranslateMessage(&m);
2632 len = TranslateKey(message, wParam, lParam, buf);
2634 return DefWindowProc(hwnd, message, wParam, lParam);
2638 * Interrupt an ongoing paste. I'm not sure
2639 * this is sensible, but for the moment it's
2640 * preferable to having to faff about buffering
2646 * We need not bother about stdin backlogs
2647 * here, because in GUI PuTTY we can't do
2648 * anything about it anyway; there's no means
2649 * of asking Windows to hold off on KEYDOWN
2650 * messages. We _have_ to buffer everything
2653 term_seen_key_event(term);
2655 ldisc_send(ldisc, buf, len, 1);
2660 net_pending_errors();
2662 case WM_INPUTLANGCHANGE:
2663 /* wParam == Font number */
2664 /* lParam == Locale */
2665 set_input_locale((HKL)lParam);
2666 sys_cursor_update();
2669 if(wParam == IMN_SETOPENSTATUS) {
2670 HIMC hImc = ImmGetContext(hwnd);
2671 ImmSetCompositionFont(hImc, &lfont);
2672 ImmReleaseContext(hwnd, hImc);
2676 case WM_IME_COMPOSITION:
2682 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
2683 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2685 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2686 break; /* fall back to DefWindowProc */
2688 hIMC = ImmGetContext(hwnd);
2689 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2693 buff = snewn(n, char);
2694 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
2696 * Jaeyoun Chung reports that Korean character
2697 * input doesn't work correctly if we do a single
2698 * luni_send() covering the whole of buff. So
2699 * instead we luni_send the characters one by one.
2701 term_seen_key_event(term);
2702 for (i = 0; i < n; i += 2) {
2704 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2708 ImmReleaseContext(hwnd, hIMC);
2713 if (wParam & 0xFF00) {
2714 unsigned char buf[2];
2717 buf[0] = wParam >> 8;
2718 term_seen_key_event(term);
2720 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
2722 char c = (unsigned char) wParam;
2723 term_seen_key_event(term);
2725 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
2731 * Nevertheless, we are prepared to deal with WM_CHAR
2732 * messages, should they crop up. So if someone wants to
2733 * post the things to us as part of a macro manoeuvre,
2734 * we're ready to cope.
2737 char c = (unsigned char)wParam;
2738 term_seen_key_event(term);
2740 lpage_send(ldisc, CP_ACP, &c, 1, 1);
2744 if (send_raw_mouse && LOWORD(lParam) == HTCLIENT) {
2745 SetCursor(LoadCursor(NULL, IDC_ARROW));
2749 case WM_SYSCOLORCHANGE:
2750 if (cfg.system_colour) {
2751 /* Refresh palette from system colours. */
2752 /* XXX actually this zaps the entire palette. */
2755 /* Force a repaint of the terminal window. */
2756 term_invalidate(term);
2759 case WM_AGENT_CALLBACK:
2761 struct agent_callback *c = (struct agent_callback *)lParam;
2762 c->callback(c->callback_ctx, c->data, c->len);
2767 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
2768 int shift_pressed=0, control_pressed=0;
2770 if (message == WM_MOUSEWHEEL) {
2771 wheel_accumulator += (short)HIWORD(wParam);
2772 shift_pressed=LOWORD(wParam) & MK_SHIFT;
2773 control_pressed=LOWORD(wParam) & MK_CONTROL;
2776 wheel_accumulator += (int)wParam;
2777 if (GetKeyboardState(keys)!=0) {
2778 shift_pressed=keys[VK_SHIFT]&0x80;
2779 control_pressed=keys[VK_CONTROL]&0x80;
2783 /* process events when the threshold is reached */
2784 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
2787 /* reduce amount for next time */
2788 if (wheel_accumulator > 0) {
2790 wheel_accumulator -= WHEEL_DELTA;
2791 } else if (wheel_accumulator < 0) {
2793 wheel_accumulator += WHEEL_DELTA;
2797 if (send_raw_mouse &&
2798 !(cfg.mouse_override && shift_pressed)) {
2799 /* send a mouse-down followed by a mouse up */
2800 term_mouse(term, b, translate_button(b),
2802 TO_CHR_X(X_POS(lParam)),
2803 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2804 control_pressed, is_alt_pressed());
2805 term_mouse(term, b, translate_button(b),
2806 MA_RELEASE, TO_CHR_X(X_POS(lParam)),
2807 TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2808 control_pressed, is_alt_pressed());
2810 /* trigger a scroll */
2811 term_scroll(term, 0,
2813 -term->rows / 2 : term->rows / 2);
2820 return DefWindowProc(hwnd, message, wParam, lParam);
2824 * Move the system caret. (We maintain one, even though it's
2825 * invisible, for the benefit of blind people: apparently some
2826 * helper software tracks the system caret, so we should arrange to
2829 void sys_cursor(void *frontend, int x, int y)
2833 if (!term->has_focus) return;
2836 * Avoid gratuitously re-updating the cursor position and IMM
2837 * window if there's no actual change required.
2839 cx = x * font_width + offset_width;
2840 cy = y * font_height + offset_height;
2841 if (cx == caret_x && cy == caret_y)
2846 sys_cursor_update();
2849 static void sys_cursor_update(void)
2854 if (!term->has_focus) return;
2856 if (caret_x < 0 || caret_y < 0)
2859 SetCaretPos(caret_x, caret_y);
2861 /* IMM calls on Win98 and beyond only */
2862 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
2864 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
2865 osVersion.dwMinorVersion == 0) return; /* 95 */
2867 /* we should have the IMM functions */
2868 hIMC = ImmGetContext(hwnd);
2869 cf.dwStyle = CFS_POINT;
2870 cf.ptCurrentPos.x = caret_x;
2871 cf.ptCurrentPos.y = caret_y;
2872 ImmSetCompositionWindow(hIMC, &cf);
2874 ImmReleaseContext(hwnd, hIMC);
2878 * Draw a line of text in the window, at given character
2879 * coordinates, in given attributes.
2881 * We are allowed to fiddle with the contents of `text'.
2883 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
2884 unsigned long attr, int lattr)
2887 int nfg, nbg, nfont;
2890 int force_manual_underline = 0;
2891 int fnt_width, char_width;
2892 int text_adjust = 0;
2893 static int *IpDx = 0, IpDxLEN = 0;
2895 lattr &= LATTR_MODE;
2897 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
2899 if (attr & ATTR_WIDE)
2902 if (len > IpDxLEN || IpDx[0] != char_width) {
2904 if (len > IpDxLEN) {
2906 IpDx = snewn(len + 16, int);
2907 IpDxLEN = (len + 16);
2909 for (i = 0; i < IpDxLEN; i++)
2910 IpDx[i] = char_width;
2913 /* Only want the left half of double width lines */
2914 if (lattr != LATTR_NORM && x*2 >= term->cols)
2922 if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
2923 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
2924 if (bold_mode == BOLD_COLOURS)
2927 /* cursor fg and bg */
2928 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
2932 if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
2933 /* Assume a poorman font is borken in other ways too. */
2943 nfont |= FONT_WIDE + FONT_HIGH;
2946 if (attr & ATTR_NARROW)
2947 nfont |= FONT_NARROW;
2949 /* Special hack for the VT100 linedraw glyphs. */
2950 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
2951 switch ((unsigned char) (text[0])) {
2953 text_adjust = -2 * font_height / 5;
2956 text_adjust = -1 * font_height / 5;
2959 text_adjust = font_height / 5;
2962 text_adjust = 2 * font_height / 5;
2965 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
2967 text[0] = ucsdata.unitab_xterm['q'];
2968 if (attr & ATTR_UNDER) {
2969 attr &= ~ATTR_UNDER;
2970 force_manual_underline = 1;
2974 /* Anything left as an original character set is unprintable. */
2975 if (DIRECT_CHAR(text[0])) {
2977 for (i = 0; i < len; i++)
2982 if ((text[0] & CSET_MASK) == CSET_OEMCP)
2985 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
2986 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
2987 if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
2989 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
2990 nfont |= FONT_UNDERLINE;
2991 another_font(nfont);
2992 if (!fonts[nfont]) {
2993 if (nfont & FONT_UNDERLINE)
2994 force_manual_underline = 1;
2995 /* Don't do the same for manual bold, it could be bad news. */
2997 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
2999 another_font(nfont);
3001 nfont = FONT_NORMAL;
3002 if (attr & ATTR_REVERSE) {
3007 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD)) {
3008 if (nfg < 16) nfg |= 8;
3009 else if (nfg >= 256) nfg |= 1;
3011 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK)) {
3012 if (nbg < 16) nbg |= 8;
3013 else if (nbg >= 256) nbg |= 1;
3017 SelectObject(hdc, fonts[nfont]);
3018 SetTextColor(hdc, fg);
3019 SetBkColor(hdc, bg);
3020 if (attr & TATTR_COMBINING)
3021 SetBkMode(hdc, TRANSPARENT);
3023 SetBkMode(hdc, OPAQUE);
3026 line_box.right = x + char_width * len;
3027 line_box.bottom = y + font_height;
3029 /* Only want the left half of double width lines */
3030 if (line_box.right > font_width*term->cols+offset_width)
3031 line_box.right = font_width*term->cols+offset_width;
3033 /* We're using a private area for direct to font. (512 chars.) */
3034 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3035 /* Ho Hum, dbcs fonts are a PITA! */
3036 /* To display on W9x I have to convert to UCS */
3037 static wchar_t *uni_buf = 0;
3038 static int uni_len = 0;
3040 if (len > uni_len) {
3043 uni_buf = snewn(uni_len, wchar_t);
3046 for(nlen = mptr = 0; mptr<len; mptr++) {
3047 uni_buf[nlen] = 0xFFFD;
3048 if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
3050 dbcstext[0] = text[mptr] & 0xFF;
3051 dbcstext[1] = text[mptr+1] & 0xFF;
3052 IpDx[nlen] += char_width;
3053 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3054 dbcstext, 2, uni_buf+nlen, 1);
3060 dbcstext[0] = text[mptr] & 0xFF;
3061 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3062 dbcstext, 1, uni_buf+nlen, 1);
3070 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3071 ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
3072 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3073 SetBkMode(hdc, TRANSPARENT);
3074 ExtTextOutW(hdc, x - 1,
3075 y - font_height * (lattr ==
3076 LATTR_BOT) + text_adjust,
3077 ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
3081 } else if (DIRECT_FONT(text[0])) {
3082 static char *directbuf = NULL;
3083 static int directlen = 0;
3085 if (len > directlen) {
3087 directbuf = sresize(directbuf, directlen, char);
3090 for (i = 0; i < len; i++)
3091 directbuf[i] = text[i] & 0xFF;
3094 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3095 ETO_CLIPPED | ETO_OPAQUE, &line_box, directbuf, len, IpDx);
3096 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3097 SetBkMode(hdc, TRANSPARENT);
3099 /* GRR: This draws the character outside it's box and can leave
3100 * 'droppings' even with the clip box! I suppose I could loop it
3101 * one character at a time ... yuk.
3103 * Or ... I could do a test print with "W", and use +1 or -1 for this
3104 * shift depending on if the leftmost column is blank...
3106 ExtTextOut(hdc, x - 1,
3107 y - font_height * (lattr ==
3108 LATTR_BOT) + text_adjust,
3109 ETO_CLIPPED, &line_box, directbuf, len, IpDx);
3112 /* And 'normal' unicode characters */
3113 static WCHAR *wbuf = NULL;
3114 static int wlen = 0;
3120 wbuf = snewn(wlen, WCHAR);
3123 for (i = 0; i < len; i++)
3126 /* print Glyphs as they are, without Windows' Shaping*/
3127 exact_textout(hdc, x, y - font_height * (lattr == LATTR_BOT) + text_adjust,
3128 &line_box, wbuf, len, IpDx, !(attr & TATTR_COMBINING));
3129 /* ExtTextOutW(hdc, x,
3130 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3131 ETO_CLIPPED | ETO_OPAQUE, &line_box, wbuf, len, IpDx);
3134 /* And the shadow bold hack. */
3135 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3136 SetBkMode(hdc, TRANSPARENT);
3137 ExtTextOutW(hdc, x - 1,
3138 y - font_height * (lattr ==
3139 LATTR_BOT) + text_adjust,
3140 ETO_CLIPPED, &line_box, wbuf, len, IpDx);
3143 if (lattr != LATTR_TOP && (force_manual_underline ||
3144 (und_mode == UND_LINE
3145 && (attr & ATTR_UNDER)))) {
3148 if (lattr == LATTR_BOT)
3149 dec = dec * 2 - font_height;
3151 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3152 MoveToEx(hdc, x, y + dec, NULL);
3153 LineTo(hdc, x + len * char_width, y + dec);
3154 oldpen = SelectObject(hdc, oldpen);
3155 DeleteObject(oldpen);
3160 * Wrapper that handles combining characters.
3162 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3163 unsigned long attr, int lattr)
3165 if (attr & TATTR_COMBINING) {
3166 unsigned long a = 0;
3167 attr &= ~TATTR_COMBINING;
3169 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3171 a = TATTR_COMBINING;
3174 do_text_internal(ctx, x, y, text, len, attr, lattr);
3177 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3178 unsigned long attr, int lattr)
3184 int ctype = cfg.cursor_type;
3186 lattr &= LATTR_MODE;
3188 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3189 if (*text != UCSWIDE) {
3190 do_text(ctx, x, y, text, len, attr, lattr);
3194 attr |= TATTR_RIGHTCURS;
3197 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3198 if (attr & ATTR_WIDE)
3205 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3208 pts[0].x = pts[1].x = pts[4].x = x;
3209 pts[2].x = pts[3].x = x + char_width - 1;
3210 pts[0].y = pts[3].y = pts[4].y = y;
3211 pts[1].y = pts[2].y = y + font_height - 1;
3212 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3213 Polyline(hdc, pts, 5);
3214 oldpen = SelectObject(hdc, oldpen);
3215 DeleteObject(oldpen);
3216 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3217 int startx, starty, dx, dy, length, i;
3220 starty = y + descent;
3223 length = char_width;
3226 if (attr & TATTR_RIGHTCURS)
3227 xadjust = char_width - 1;
3228 startx = x + xadjust;
3232 length = font_height;
3234 if (attr & TATTR_ACTCURS) {
3237 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3238 MoveToEx(hdc, startx, starty, NULL);
3239 LineTo(hdc, startx + dx * length, starty + dy * length);
3240 oldpen = SelectObject(hdc, oldpen);
3241 DeleteObject(oldpen);
3243 for (i = 0; i < length; i++) {
3245 SetPixel(hdc, startx, starty, colours[261]);
3254 /* This function gets the actual width of a character in the normal font.
3256 int char_width(Context ctx, int uc) {
3260 /* If the font max is the same as the font ave width then this
3261 * function is a no-op.
3263 if (!font_dualwidth) return 1;
3265 switch (uc & CSET_MASK) {
3267 uc = ucsdata.unitab_line[uc & 0xFF];
3270 uc = ucsdata.unitab_xterm[uc & 0xFF];
3273 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3276 if (DIRECT_FONT(uc)) {
3277 if (ucsdata.dbcs_screenfont) return 1;
3279 /* Speedup, I know of no font where ascii is the wrong width */
3280 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3283 if ( (uc & CSET_MASK) == CSET_ACP ) {
3284 SelectObject(hdc, fonts[FONT_NORMAL]);
3285 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3286 another_font(FONT_OEM);
3287 if (!fonts[FONT_OEM]) return 0;
3289 SelectObject(hdc, fonts[FONT_OEM]);
3293 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3294 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3297 /* Speedup, I know of no font where ascii is the wrong width */
3298 if (uc >= ' ' && uc <= '~') return 1;
3300 SelectObject(hdc, fonts[FONT_NORMAL]);
3301 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3302 /* Okay that one worked */ ;
3303 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3304 /* This should work on 9x too, but it's "less accurate" */ ;
3309 ibuf += font_width / 2 -1;
3316 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3317 * codes. Returns number of bytes used or zero to drop the message
3318 * or -1 to forward the message to windows.
3320 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3321 unsigned char *output)
3324 int scan, left_alt = 0, key_down, shift_state;
3326 unsigned char *p = output;
3327 static int alt_sum = 0;
3329 HKL kbd_layout = GetKeyboardLayout(0);
3331 /* keys is for ToAsciiEx. There's some ick here, see below. */
3332 static WORD keys[3];
3333 static int compose_char = 0;
3334 static WPARAM compose_key = 0;
3336 r = GetKeyboardState(keystate);
3338 memset(keystate, 0, sizeof(keystate));
3341 #define SHOW_TOASCII_RESULT
3342 { /* Tell us all about key events */
3343 static BYTE oldstate[256];
3344 static int first = 1;
3348 memcpy(oldstate, keystate, sizeof(oldstate));
3351 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3353 } else if ((HIWORD(lParam) & KF_UP)
3354 && scan == (HIWORD(lParam) & 0xFF)) {
3358 if (wParam >= VK_F1 && wParam <= VK_F20)
3359 debug(("K_F%d", wParam + 1 - VK_F1));
3372 debug(("VK_%02x", wParam));
3374 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3376 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3378 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3379 if (ch >= ' ' && ch <= '~')
3380 debug((", '%c'", ch));
3382 debug((", $%02x", ch));
3385 debug((", KB0=%02x", keys[0]));
3387 debug((", KB1=%02x", keys[1]));
3389 debug((", KB2=%02x", keys[2]));
3391 if ((keystate[VK_SHIFT] & 0x80) != 0)
3393 if ((keystate[VK_CONTROL] & 0x80) != 0)
3395 if ((HIWORD(lParam) & KF_EXTENDED))
3397 if ((HIWORD(lParam) & KF_UP))
3401 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3402 else if ((HIWORD(lParam) & KF_UP))
3403 oldstate[wParam & 0xFF] ^= 0x80;
3405 oldstate[wParam & 0xFF] ^= 0x81;
3407 for (ch = 0; ch < 256; ch++)
3408 if (oldstate[ch] != keystate[ch])
3409 debug((", M%02x=%02x", ch, keystate[ch]));
3411 memcpy(oldstate, keystate, sizeof(oldstate));
3415 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
3416 keystate[VK_RMENU] = keystate[VK_MENU];
3420 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
3421 if ((cfg.funky_type == FUNKY_VT400 ||
3422 (cfg.funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
3424 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
3426 wParam = VK_EXECUTE;
3428 /* UnToggle NUMLock */
3429 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3430 keystate[VK_NUMLOCK] ^= 1;
3433 /* And write back the 'adjusted' state */
3434 SetKeyboardState(keystate);
3437 /* Disable Auto repeat if required */
3438 if (term->repeat_off &&
3439 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
3442 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
3445 key_down = ((HIWORD(lParam) & KF_UP) == 0);
3447 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
3448 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
3449 if (cfg.ctrlaltkeys)
3450 keystate[VK_MENU] = 0;
3452 keystate[VK_RMENU] = 0x80;
3457 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
3458 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3459 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
3461 /* Note if AltGr was pressed and if it was used as a compose key */
3462 if (!compose_state) {
3463 compose_key = 0x100;
3464 if (cfg.compose_key) {
3465 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
3466 compose_key = wParam;
3468 if (wParam == VK_APPS)
3469 compose_key = wParam;
3472 if (wParam == compose_key) {
3473 if (compose_state == 0
3474 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3476 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
3480 } else if (compose_state == 1 && wParam != VK_CONTROL)
3483 if (compose_state > 1 && left_alt)
3486 /* Sanitize the number pad if not using a PC NumPad */
3487 if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
3488 && cfg.funky_type != FUNKY_XTERM)
3489 || cfg.funky_type == FUNKY_VT400 || cfg.nethack_keypad || compose_state) {
3490 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
3494 nParam = VK_NUMPAD0;
3497 nParam = VK_NUMPAD1;
3500 nParam = VK_NUMPAD2;
3503 nParam = VK_NUMPAD3;
3506 nParam = VK_NUMPAD4;
3509 nParam = VK_NUMPAD5;
3512 nParam = VK_NUMPAD6;
3515 nParam = VK_NUMPAD7;
3518 nParam = VK_NUMPAD8;
3521 nParam = VK_NUMPAD9;
3524 nParam = VK_DECIMAL;
3528 if (keystate[VK_NUMLOCK] & 1)
3535 /* If a key is pressed and AltGr is not active */
3536 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3537 /* Okay, prepare for most alts then ... */
3541 /* Lets see if it's a pattern we know all about ... */
3542 if (wParam == VK_PRIOR && shift_state == 1) {
3543 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3546 if (wParam == VK_PRIOR && shift_state == 2) {
3547 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3550 if (wParam == VK_NEXT && shift_state == 1) {
3551 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3554 if (wParam == VK_NEXT && shift_state == 2) {
3555 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3558 if (wParam == VK_INSERT && shift_state == 1) {
3559 term_do_paste(term);
3562 if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
3565 if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
3566 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3569 if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3570 (cfg.resize_action != RESIZE_DISABLED)) {
3571 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3575 /* Control-Numlock for app-keypad mode switch */
3576 if (wParam == VK_PAUSE && shift_state == 2) {
3577 term->app_keypad_keys ^= 1;
3581 /* Nethack keypad */
3582 if (cfg.nethack_keypad && !left_alt) {
3585 *p++ = shift_state ? 'B' : 'b';
3588 *p++ = shift_state ? 'J' : 'j';
3591 *p++ = shift_state ? 'N' : 'n';
3594 *p++ = shift_state ? 'H' : 'h';
3597 *p++ = shift_state ? '.' : '.';
3600 *p++ = shift_state ? 'L' : 'l';
3603 *p++ = shift_state ? 'Y' : 'y';
3606 *p++ = shift_state ? 'K' : 'k';
3609 *p++ = shift_state ? 'U' : 'u';
3614 /* Application Keypad */
3618 if (cfg.funky_type == FUNKY_VT400 ||
3619 (cfg.funky_type <= FUNKY_LINUX &&
3620 term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
3634 if (term->app_keypad_keys && !cfg.no_applic_k)
3671 if (cfg.funky_type == FUNKY_XTERM) {
3676 } else if (shift_state)
3683 if (cfg.funky_type == FUNKY_XTERM)
3687 if (cfg.funky_type == FUNKY_XTERM)
3691 if (cfg.funky_type == FUNKY_XTERM)
3696 if (HIWORD(lParam) & KF_EXTENDED)
3701 if (term->vt52_mode) {
3702 if (xkey >= 'P' && xkey <= 'S')
3703 p += sprintf((char *) p, "\x1B%c", xkey);
3705 p += sprintf((char *) p, "\x1B?%c", xkey);
3707 p += sprintf((char *) p, "\x1BO%c", xkey);
3712 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
3713 *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
3717 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
3718 /* We do the opposite of what is configured */
3719 *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
3723 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
3729 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
3733 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
3737 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
3742 if (wParam == VK_PAUSE) { /* Break/Pause */
3747 /* Control-2 to Control-8 are special */
3748 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
3749 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
3752 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
3756 if (shift_state == 2 && wParam == 0xDF) {
3760 if (shift_state == 3 && wParam == 0xDE) {
3761 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
3764 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
3771 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
3772 * for integer decimal nn.)
3774 * We also deal with the weird ones here. Linux VCs replace F1
3775 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
3776 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
3782 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
3785 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
3788 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
3791 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
3794 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
3797 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
3800 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
3803 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
3806 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
3809 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
3842 if ((shift_state&2) == 0) switch (wParam) {
3862 /* Reorder edit keys to physical order */
3863 if (cfg.funky_type == FUNKY_VT400 && code <= 6)
3864 code = "\0\2\1\4\5\3\6"[code];
3866 if (term->vt52_mode && code > 0 && code <= 6) {
3867 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
3871 if (cfg.funky_type == FUNKY_SCO && /* SCO function keys */
3872 code >= 11 && code <= 34) {
3873 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
3876 case VK_F1: index = 0; break;
3877 case VK_F2: index = 1; break;
3878 case VK_F3: index = 2; break;
3879 case VK_F4: index = 3; break;
3880 case VK_F5: index = 4; break;
3881 case VK_F6: index = 5; break;
3882 case VK_F7: index = 6; break;
3883 case VK_F8: index = 7; break;
3884 case VK_F9: index = 8; break;
3885 case VK_F10: index = 9; break;
3886 case VK_F11: index = 10; break;
3887 case VK_F12: index = 11; break;
3889 if (keystate[VK_SHIFT] & 0x80) index += 12;
3890 if (keystate[VK_CONTROL] & 0x80) index += 24;
3891 p += sprintf((char *) p, "\x1B[%c", codes[index]);
3894 if (cfg.funky_type == FUNKY_SCO && /* SCO small keypad */
3895 code >= 1 && code <= 6) {
3896 char codes[] = "HL.FIG";
3900 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
3904 if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
3910 if (term->vt52_mode)
3911 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
3914 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
3917 if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
3918 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
3921 if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
3922 if (term->vt52_mode)
3923 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
3925 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
3928 if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
3929 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
3933 p += sprintf((char *) p, "\x1B[%d~", code);
3938 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
3939 * some reason seems to send VK_CLEAR to Windows...).
3961 if (term->vt52_mode)
3962 p += sprintf((char *) p, "\x1B%c", xkey);
3964 int app_flg = (term->app_cursor_keys && !cfg.no_applic_c);
3967 * RDB: VT100 & VT102 manuals both state the
3968 * app cursor keys only work if the app keypad
3971 * SGT: That may well be true, but xterm
3972 * disagrees and so does at least one
3973 * application, so I've #if'ed this out and the
3974 * behaviour is back to PuTTY's original: app
3975 * cursor and app keypad are independently
3976 * switchable modes. If anyone complains about
3977 * _this_ I'll have to put in a configurable
3980 if (!term->app_keypad_keys)
3983 /* Useful mapping of Ctrl-arrows */
3984 if (shift_state == 2)
3988 p += sprintf((char *) p, "\x1BO%c", xkey);
3990 p += sprintf((char *) p, "\x1B[%c", xkey);
3997 * Finally, deal with Return ourselves. (Win95 seems to
3998 * foul it up when Alt is pressed, for some reason.)
4000 if (wParam == VK_RETURN) { /* Return */
4006 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4007 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4012 /* Okay we've done everything interesting; let windows deal with
4013 * the boring stuff */
4017 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4018 if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
4020 keystate[VK_CAPITAL] = 0;
4023 /* XXX how do we know what the max size of the keys array should
4024 * be is? There's indication on MS' website of an Inquire/InquireEx
4025 * functioning returning a KBINFO structure which tells us. */
4026 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4027 /* XXX 'keys' parameter is declared in MSDN documentation as
4029 * The experience of a French user indicates that on
4030 * Win98, WORD[] should be passed in, but on Win2K, it should
4031 * be BYTE[]. German WinXP and my Win2K with "US International"
4032 * driver corroborate this.
4033 * Experimentally I've conditionalised the behaviour on the
4034 * Win9x/NT split, but I suspect it's worse than that.
4035 * See wishlist item `win-dead-keys' for more horrible detail
4036 * and speculations. */
4039 r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
4040 for (i=0; i<3; i++) keys[i] = keybs[i];
4042 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4044 #ifdef SHOW_TOASCII_RESULT
4045 if (r == 1 && !key_down) {
4047 if (in_utf(term) || ucsdata.dbcs_screenfont)
4048 debug((", (U+%04x)", alt_sum));
4050 debug((", LCH(%d)", alt_sum));
4052 debug((", ACH(%d)", keys[0]));
4057 for (r1 = 0; r1 < r; r1++) {
4058 debug(("%s%d", r1 ? "," : "", keys[r1]));
4067 * Interrupt an ongoing paste. I'm not sure this is
4068 * sensible, but for the moment it's preferable to
4069 * having to faff about buffering things.
4074 for (i = 0; i < r; i++) {
4075 unsigned char ch = (unsigned char) keys[i];
4077 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
4082 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
4086 if ((nc = check_compose(compose_char, ch)) == -1) {
4087 MessageBeep(MB_ICONHAND);
4091 term_seen_key_event(term);
4093 luni_send(ldisc, &keybuf, 1, 1);
4101 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4103 term_seen_key_event(term);
4105 luni_send(ldisc, &keybuf, 1, 1);
4107 ch = (char) alt_sum;
4109 * We need not bother about stdin
4110 * backlogs here, because in GUI PuTTY
4111 * we can't do anything about it
4112 * anyway; there's no means of asking
4113 * Windows to hold off on KEYDOWN
4114 * messages. We _have_ to buffer
4115 * everything we're sent.
4117 term_seen_key_event(term);
4119 ldisc_send(ldisc, &ch, 1, 1);
4123 term_seen_key_event(term);
4125 lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
4128 if(capsOn && ch < 0x80) {
4131 cbuf[1] = xlat_uskbd2cyrllic(ch);
4132 term_seen_key_event(term);
4134 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4139 term_seen_key_event(term);
4141 lpage_send(ldisc, kbd_codepage,
4142 cbuf+!left_alt, 1+!!left_alt, 1);
4148 /* This is so the ALT-Numpad and dead keys work correctly. */
4153 /* If we're definitly not building up an ALT-54321 then clear it */
4156 /* If we will be using alt_sum fix the 256s */
4157 else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4162 * ALT alone may or may not want to bring up the System menu.
4163 * If it's not meant to, we return 0 on presses or releases of
4164 * ALT, to show that we've swallowed the keystroke. Otherwise
4165 * we return -1, which means Windows will give the keystroke
4166 * its default handling (i.e. bring up the System menu).
4168 if (wParam == VK_MENU && !cfg.alt_only)
4174 void request_paste(void *frontend)
4177 * In Windows, pasting is synchronous: we can read the
4178 * clipboard with no difficulty, so request_paste() can just go
4181 term_do_paste(term);
4184 void set_title(void *frontend, char *title)
4187 window_name = snewn(1 + strlen(title), char);
4188 strcpy(window_name, title);
4189 if (cfg.win_name_always || !IsIconic(hwnd))
4190 SetWindowText(hwnd, title);
4193 void set_icon(void *frontend, char *title)
4196 icon_name = snewn(1 + strlen(title), char);
4197 strcpy(icon_name, title);
4198 if (!cfg.win_name_always && IsIconic(hwnd))
4199 SetWindowText(hwnd, title);
4202 void set_sbar(void *frontend, int total, int start, int page)
4206 if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
4209 si.cbSize = sizeof(si);
4210 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4212 si.nMax = total - 1;
4216 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4219 Context get_ctx(void *frontend)
4225 SelectPalette(hdc, pal, FALSE);
4231 void free_ctx(Context ctx)
4233 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4234 ReleaseDC(hwnd, ctx);
4237 static void real_palette_set(int n, int r, int g, int b)
4240 logpal->palPalEntry[n].peRed = r;
4241 logpal->palPalEntry[n].peGreen = g;
4242 logpal->palPalEntry[n].peBlue = b;
4243 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4244 colours[n] = PALETTERGB(r, g, b);
4245 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4247 colours[n] = RGB(r, g, b);
4250 void palette_set(void *frontend, int n, int r, int g, int b)
4254 if (n > NALLCOLOURS)
4256 real_palette_set(n, r, g, b);
4258 HDC hdc = get_ctx(frontend);
4259 UnrealizeObject(pal);
4260 RealizePalette(hdc);
4265 void palette_reset(void *frontend)
4270 for (i = 0; i < NALLCOLOURS; i++) {
4272 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4273 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4274 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4275 logpal->palPalEntry[i].peFlags = 0;
4276 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4277 defpal[i].rgbtGreen,
4278 defpal[i].rgbtBlue);
4280 colours[i] = RGB(defpal[i].rgbtRed,
4281 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4286 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4287 hdc = get_ctx(frontend);
4288 RealizePalette(hdc);
4293 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4298 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4301 lock = GlobalLock(clipdata);
4304 memcpy(lock, data, len);
4305 ((unsigned char *) lock)[len] = 0;
4306 GlobalUnlock(clipdata);
4309 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4311 if (OpenClipboard(hwnd)) {
4313 SetClipboardData(CF_TEXT, clipdata);
4316 GlobalFree(clipdata);
4319 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4323 * Note: unlike write_aclip() this will not append a nul.
4325 void write_clip(void *frontend, wchar_t * data, int len, int must_deselect)
4327 HGLOBAL clipdata, clipdata2, clipdata3;
4329 void *lock, *lock2, *lock3;
4331 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4333 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4334 len * sizeof(wchar_t));
4335 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4337 if (!clipdata || !clipdata2) {
4339 GlobalFree(clipdata);
4341 GlobalFree(clipdata2);
4344 if (!(lock = GlobalLock(clipdata)))
4346 if (!(lock2 = GlobalLock(clipdata2)))
4349 memcpy(lock, data, len * sizeof(wchar_t));
4350 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4352 if (cfg.rtf_paste) {
4353 wchar_t unitab[256];
4355 unsigned char *tdata = (unsigned char *)lock2;
4356 wchar_t *udata = (wchar_t *)lock;
4357 int rtflen = 0, uindex = 0, tindex = 0;
4359 int multilen, blen, alen, totallen, i;
4360 char before[16], after[4];
4362 get_unitab(CP_ACP, unitab, 0);
4364 rtfsize = 100 + strlen(cfg.font.name);
4365 rtf = snewn(rtfsize, char);
4366 sprintf(rtf, "{\\rtf1\\ansi%d{\\fonttbl\\f0\\fmodern %s;}\\f0",
4367 GetACP(), cfg.font.name);
4368 rtflen = strlen(rtf);
4371 * We want to construct a piece of RTF that specifies the
4372 * same Unicode text. To do this we will read back in
4373 * parallel from the Unicode data in `udata' and the
4374 * non-Unicode data in `tdata'. For each character in
4375 * `tdata' which becomes the right thing in `udata' when
4376 * looked up in `unitab', we just copy straight over from
4377 * tdata. For each one that doesn't, we must WCToMB it
4378 * individually and produce a \u escape sequence.
4380 * It would probably be more robust to just bite the bullet
4381 * and WCToMB each individual Unicode character one by one,
4382 * then MBToWC each one back to see if it was an accurate
4383 * translation; but that strikes me as a horrifying number
4384 * of Windows API calls so I want to see if this faster way
4385 * will work. If it screws up badly we can always revert to
4386 * the simple and slow way.
4388 while (tindex < len2 && uindex < len &&
4389 tdata[tindex] && udata[uindex]) {
4390 if (tindex + 1 < len2 &&
4391 tdata[tindex] == '\r' &&
4392 tdata[tindex+1] == '\n') {
4396 if (unitab[tdata[tindex]] == udata[uindex]) {
4402 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4403 NULL, 0, NULL, NULL);
4404 if (multilen != 1) {
4405 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4407 alen = 1; strcpy(after, "}");
4409 blen = sprintf(before, "\\u%d", udata[uindex]);
4410 alen = 0; after[0] = '\0';
4413 assert(tindex + multilen <= len2);
4414 totallen = blen + alen;
4415 for (i = 0; i < multilen; i++) {
4416 if (tdata[tindex+i] == '\\' ||
4417 tdata[tindex+i] == '{' ||
4418 tdata[tindex+i] == '}')
4420 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4421 totallen += 6; /* \par\r\n */
4422 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4428 if (rtfsize < rtflen + totallen + 3) {
4429 rtfsize = rtflen + totallen + 512;
4430 rtf = sresize(rtf, rtfsize, char);
4433 strcpy(rtf + rtflen, before); rtflen += blen;
4434 for (i = 0; i < multilen; i++) {
4435 if (tdata[tindex+i] == '\\' ||
4436 tdata[tindex+i] == '{' ||
4437 tdata[tindex+i] == '}') {
4438 rtf[rtflen++] = '\\';
4439 rtf[rtflen++] = tdata[tindex+i];
4440 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4441 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4442 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4443 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4445 rtf[rtflen++] = tdata[tindex+i];
4448 strcpy(rtf + rtflen, after); rtflen += alen;
4454 strcpy(rtf + rtflen, "}");
4457 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4458 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
4460 GlobalUnlock(clipdata3);
4466 GlobalUnlock(clipdata);
4467 GlobalUnlock(clipdata2);
4470 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4472 if (OpenClipboard(hwnd)) {
4474 SetClipboardData(CF_UNICODETEXT, clipdata);
4475 SetClipboardData(CF_TEXT, clipdata2);
4477 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4480 GlobalFree(clipdata);
4481 GlobalFree(clipdata2);
4485 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4488 void get_clip(void *frontend, wchar_t ** p, int *len)
4490 static HGLOBAL clipdata = NULL;
4491 static wchar_t *converted = 0;
4500 GlobalUnlock(clipdata);
4503 } else if (OpenClipboard(NULL)) {
4504 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
4506 *p = GlobalLock(clipdata);
4508 for (p2 = *p; *p2; p2++);
4512 } else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
4516 s = GlobalLock(clipdata);
4517 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
4518 *p = converted = snewn(i, wchar_t);
4519 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
4532 * Move `lines' lines from position `from' to position `to' in the
4535 void optimised_move(void *frontend, int to, int from, int lines)
4540 min = (to < from ? to : from);
4541 max = to + from - min;
4543 r.left = offset_width;
4544 r.right = offset_width + term->cols * font_width;
4545 r.top = offset_height + min * font_height;
4546 r.bottom = offset_height + (max + lines) * font_height;
4547 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
4552 * Print a message box and perform a fatal exit.
4554 void fatalbox(char *fmt, ...)
4557 char *stuff, morestuff[100];
4560 stuff = dupvprintf(fmt, ap);
4562 sprintf(morestuff, "%.70s Fatal Error", appname);
4563 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
4569 * Print a modal (Really Bad) message box and perform a fatal exit.
4571 void modalfatalbox(char *fmt, ...)
4574 char *stuff, morestuff[100];
4577 stuff = dupvprintf(fmt, ap);
4579 sprintf(morestuff, "%.70s Fatal Error", appname);
4580 MessageBox(hwnd, stuff, morestuff,
4581 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
4586 static void flash_window(int mode);
4587 static long next_flash;
4588 static int flashing = 0;
4590 static void flash_window_timer(void *ctx, long now)
4592 if (flashing && now - next_flash >= 0) {
4598 * Manage window caption / taskbar flashing, if enabled.
4599 * 0 = stop, 1 = maintain, 2 = start
4601 static void flash_window(int mode)
4603 if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
4606 FlashWindow(hwnd, FALSE);
4610 } else if (mode == 2) {
4614 FlashWindow(hwnd, TRUE);
4615 next_flash = schedule_timer(450, flash_window_timer, hwnd);
4618 } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
4621 FlashWindow(hwnd, TRUE); /* toggle */
4622 next_flash = schedule_timer(450, flash_window_timer, hwnd);
4630 void beep(void *frontend, int mode)
4632 if (mode == BELL_DEFAULT) {
4634 * For MessageBeep style bells, we want to be careful of
4635 * timing, because they don't have the nice property of
4636 * PlaySound bells that each one cancels the previous
4637 * active one. So we limit the rate to one per 50ms or so.
4639 static long lastbeep = 0;
4642 beepdiff = GetTickCount() - lastbeep;
4643 if (beepdiff >= 0 && beepdiff < 50)
4647 * The above MessageBeep call takes time, so we record the
4648 * time _after_ it finishes rather than before it starts.
4650 lastbeep = GetTickCount();
4651 } else if (mode == BELL_WAVEFILE) {
4652 if (!PlaySound(cfg.bell_wavefile.path, NULL,
4653 SND_ASYNC | SND_FILENAME)) {
4654 char buf[sizeof(cfg.bell_wavefile.path) + 80];
4656 sprintf(buf, "Unable to play sound file\n%s\n"
4657 "Using default sound instead", cfg.bell_wavefile.path);
4658 sprintf(otherbuf, "%.70s Sound Error", appname);
4659 MessageBox(hwnd, buf, otherbuf,
4660 MB_OK | MB_ICONEXCLAMATION);
4661 cfg.beep = BELL_DEFAULT;
4663 } else if (mode == BELL_PCSPEAKER) {
4664 static long lastbeep = 0;
4667 beepdiff = GetTickCount() - lastbeep;
4668 if (beepdiff >= 0 && beepdiff < 50)
4672 * We must beep in different ways depending on whether this
4673 * is a 95-series or NT-series OS.
4675 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
4679 lastbeep = GetTickCount();
4681 /* Otherwise, either visual bell or disabled; do nothing here */
4682 if (!term->has_focus) {
4683 flash_window(2); /* start */
4688 * Minimise or restore the window in response to a server-side
4691 void set_iconic(void *frontend, int iconic)
4693 if (IsIconic(hwnd)) {
4695 ShowWindow(hwnd, SW_RESTORE);
4698 ShowWindow(hwnd, SW_MINIMIZE);
4703 * Move the window in response to a server-side request.
4705 void move_window(void *frontend, int x, int y)
4707 if (cfg.resize_action == RESIZE_DISABLED ||
4708 cfg.resize_action == RESIZE_FONT ||
4712 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
4716 * Move the window to the top or bottom of the z-order in response
4717 * to a server-side request.
4719 void set_zorder(void *frontend, int top)
4721 if (cfg.alwaysontop)
4722 return; /* ignore */
4723 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
4724 SWP_NOMOVE | SWP_NOSIZE);
4728 * Refresh the window in response to a server-side request.
4730 void refresh_window(void *frontend)
4732 InvalidateRect(hwnd, NULL, TRUE);
4736 * Maximise or restore the window in response to a server-side
4739 void set_zoomed(void *frontend, int zoomed)
4741 if (IsZoomed(hwnd)) {
4743 ShowWindow(hwnd, SW_RESTORE);
4746 ShowWindow(hwnd, SW_MAXIMIZE);
4751 * Report whether the window is iconic, for terminal reports.
4753 int is_iconic(void *frontend)
4755 return IsIconic(hwnd);
4759 * Report the window's position, for terminal reports.
4761 void get_window_pos(void *frontend, int *x, int *y)
4764 GetWindowRect(hwnd, &r);
4770 * Report the window's pixel size, for terminal reports.
4772 void get_window_pixels(void *frontend, int *x, int *y)
4775 GetWindowRect(hwnd, &r);
4776 *x = r.right - r.left;
4777 *y = r.bottom - r.top;
4781 * Return the window or icon title.
4783 char *get_window_title(void *frontend, int icon)
4785 return icon ? icon_name : window_name;
4789 * See if we're in full-screen mode.
4791 static int is_full_screen()
4793 if (!IsZoomed(hwnd))
4795 if (GetWindowLong(hwnd, GWL_STYLE) & WS_CAPTION)
4800 /* Get the rect/size of a full screen window using the nearest available
4801 * monitor in multimon systems; default to something sensible if only
4802 * one monitor is present. */
4803 static int get_fullscreen_rect(RECT * ss)
4805 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
4808 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
4809 mi.cbSize = sizeof(mi);
4810 GetMonitorInfo(mon, &mi);
4812 /* structure copy */
4816 /* could also use code like this:
4817 ss->left = ss->top = 0;
4818 ss->right = GetSystemMetrics(SM_CXSCREEN);
4819 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
4821 return GetClientRect(GetDesktopWindow(), ss);
4827 * Go full-screen. This should only be called when we are already
4830 static void make_full_screen()
4835 assert(IsZoomed(hwnd));
4837 if (is_full_screen())
4840 /* Remove the window furniture. */
4841 style = GetWindowLong(hwnd, GWL_STYLE);
4842 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
4843 if (cfg.scrollbar_in_fullscreen)
4844 style |= WS_VSCROLL;
4846 style &= ~WS_VSCROLL;
4847 SetWindowLong(hwnd, GWL_STYLE, style);
4849 /* Resize ourselves to exactly cover the nearest monitor. */
4850 get_fullscreen_rect(&ss);
4851 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
4856 /* Tick the menu item in the System menu. */
4857 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4862 * Clear the full-screen attributes.
4864 static void clear_full_screen()
4866 DWORD oldstyle, style;
4868 /* Reinstate the window furniture. */
4869 style = oldstyle = GetWindowLong(hwnd, GWL_STYLE);
4870 style |= WS_CAPTION | WS_BORDER;
4871 if (cfg.resize_action == RESIZE_DISABLED)
4872 style &= ~WS_THICKFRAME;
4874 style |= WS_THICKFRAME;
4876 style |= WS_VSCROLL;
4878 style &= ~WS_VSCROLL;
4879 if (style != oldstyle) {
4880 SetWindowLong(hwnd, GWL_STYLE, style);
4881 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
4882 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
4886 /* Untick the menu item in the System menu. */
4887 CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4892 * Toggle full-screen mode.
4894 static void flip_full_screen()
4896 if (is_full_screen()) {
4897 ShowWindow(hwnd, SW_RESTORE);
4898 } else if (IsZoomed(hwnd)) {
4901 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
4902 ShowWindow(hwnd, SW_MAXIMIZE);
4906 void frontend_keypress(void *handle)
4909 * Keypress termination in non-Close-On-Exit mode is not
4910 * currently supported in PuTTY proper, because the window
4911 * always has a perfectly good Close button anyway. So we do
4917 int from_backend(void *frontend, int is_stderr, const char *data, int len)
4919 return term_data(term, is_stderr, data, len);
4922 void agent_schedule_callback(void (*callback)(void *, void *, int),
4923 void *callback_ctx, void *data, int len)
4925 struct agent_callback *c = snew(struct agent_callback);
4926 c->callback = callback;
4927 c->callback_ctx = callback_ctx;
4930 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);