2 * window.c - the PuTTY(tel) main program, which runs a PuTTY terminal
3 * emulator and backend in a window.
14 #define COMPILE_MULTIMON_STUBS
17 #define PUTTY_DO_GLOBALS /* actually _define_ globals */
32 /* From MSDN: In the WM_SYSCOMMAND message, the four low-order bits of
33 * wParam are used by Windows, and should be masked off, so we shouldn't
34 * attempt to store information in them. Hence all these identifiers have
35 * the low 4 bits clear. Also, identifiers should < 0xF000. */
37 #define IDM_SHOWLOG 0x0010
38 #define IDM_NEWSESS 0x0020
39 #define IDM_DUPSESS 0x0030
40 #define IDM_RESTART 0x0040
41 #define IDM_RECONF 0x0050
42 #define IDM_CLRSB 0x0060
43 #define IDM_RESET 0x0070
44 #define IDM_HELP 0x0140
45 #define IDM_ABOUT 0x0150
46 #define IDM_SAVEDSESS 0x0160
47 #define IDM_COPYALL 0x0170
48 #define IDM_FULLSCREEN 0x0180
49 #define IDM_PASTE 0x0190
50 #define IDM_SPECIALSEP 0x0200
52 #define IDM_SPECIAL_MIN 0x0400
53 #define IDM_SPECIAL_MAX 0x0800
55 #define IDM_SAVED_MIN 0x1000
56 #define IDM_SAVED_MAX 0x5000
57 #define MENU_SAVED_STEP 16
58 /* Maximum number of sessions on saved-session submenu */
59 #define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
61 #define WM_IGNORE_CLIP (WM_APP + 2)
62 #define WM_FULLSCR_ON_MAX (WM_APP + 3)
63 #define WM_AGENT_CALLBACK (WM_APP + 4)
64 #define WM_GOT_CLIPDATA (WM_APP + 6)
66 /* Needed for Chinese support and apparently not always defined. */
68 #define VK_PROCESSKEY 0xE5
71 /* Mouse wheel support. */
73 #define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
76 #define WHEEL_DELTA 120
79 static Mouse_Button translate_button(Mouse_Button button);
80 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
81 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
82 unsigned char *output);
83 static void conftopalette(void);
84 static void systopalette(void);
85 static void init_palette(void);
86 static void init_fonts(int, int);
87 static void another_font(int);
88 static void deinit_fonts(void);
89 static void set_input_locale(HKL);
90 static void update_savedsess_menu(void);
91 static void init_winfuncs(void);
93 static int is_full_screen(void);
94 static void make_full_screen(void);
95 static void clear_full_screen(void);
96 static void flip_full_screen(void);
97 static int process_clipdata(HGLOBAL clipdata, int unicode);
99 /* Window layout information */
100 static void reset_window(int);
101 static int extra_width, extra_height;
102 static int font_width, font_height, font_dualwidth, font_varpitch;
103 static int offset_width, offset_height;
104 static int was_zoomed = 0;
105 static int prev_rows, prev_cols;
107 static void flash_window(int mode);
108 static void sys_cursor_update(void);
109 static int get_fullscreen_rect(RECT * ss);
111 static int caret_x = -1, caret_y = -1;
113 static int kbd_codepage;
116 static Backend *back;
117 static void *backhandle;
119 static struct unicode_data ucsdata;
120 static int session_closed;
121 static int reconfiguring = FALSE;
123 static const struct telnet_special *specials = NULL;
124 static HMENU specials_menu = NULL;
125 static int n_specials = 0;
127 static wchar_t *clipboard_contents;
128 static size_t clipboard_length;
130 #define TIMING_TIMER_ID 1234
131 static long timing_next_time;
136 enum { SYSMENU, CTXMENU };
137 static HMENU savedsess_menu;
139 struct wm_netevent_params {
140 /* Used to pass data to wm_netevent_callback */
145 Conf *conf; /* exported to windlg.c */
147 static void conf_cache_data(void);
151 static struct sesslist sesslist; /* for saved-session menu */
153 struct agent_callback {
154 void (*callback)(void *, void *, int);
160 #define FONT_NORMAL 0
162 #define FONT_UNDERLINE 2
163 #define FONT_BOLDUND 3
164 #define FONT_WIDE 0x04
165 #define FONT_HIGH 0x08
166 #define FONT_NARROW 0x10
168 #define FONT_OEM 0x20
169 #define FONT_OEMBOLD 0x21
170 #define FONT_OEMUND 0x22
171 #define FONT_OEMBOLDUND 0x23
173 #define FONT_MAXNO 0x40
175 static HFONT fonts[FONT_MAXNO];
176 static LOGFONT lfont;
177 static int fontflag[FONT_MAXNO];
179 BOLD_NONE, BOLD_SHADOW, BOLD_FONT
181 static int bold_colours;
187 #define NCFGCOLOURS 22
188 #define NEXTCOLOURS 240
189 #define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
190 static COLORREF colours[NALLCOLOURS];
192 static LPLOGPALETTE logpal;
193 static RGBTRIPLE defpal[NALLCOLOURS];
195 static HBITMAP caretbm;
197 static int dbltime, lasttime, lastact;
198 static Mouse_Button lastbtn;
200 /* this allows xterm-style mouse handling. */
201 static int send_raw_mouse = 0;
202 static int wheel_accumulator = 0;
204 static int busy_status = BUSY_NOT;
206 static char *window_name, *icon_name;
208 static int compose_state = 0;
210 static UINT wm_mousewheel = WM_MOUSEWHEEL;
212 #define IS_HIGH_VARSEL(wch1, wch2) \
213 ((wch1) == 0xDB40 && ((wch2) >= 0xDD00 && (wch2) <= 0xDDEF))
214 #define IS_LOW_VARSEL(wch) \
215 (((wch) >= 0x180B && (wch) <= 0x180D) || /* MONGOLIAN FREE VARIATION SELECTOR */ \
216 ((wch) >= 0xFE00 && (wch) <= 0xFE0F)) /* VARIATION SELECTOR 1-16 */
218 /* Dummy routine, only required in plink. */
219 void ldisc_update(void *frontend, int echo, int edit)
223 char *get_ttymode(void *frontend, const char *mode)
225 return term_get_ttymode(term, mode);
228 static void start_backend(void)
231 char msg[1024], *title;
236 * Select protocol. This is farmed out into a table in a
237 * separate file to enable an ssh-free variant.
239 back = backend_from_proto(conf_get_int(conf, CONF_protocol));
241 char *str = dupprintf("%s Internal Error", appname);
242 MessageBox(NULL, "Unsupported protocol number found",
243 str, MB_OK | MB_ICONEXCLAMATION);
248 error = back->init(NULL, &backhandle, conf,
249 conf_get_str(conf, CONF_host),
250 conf_get_int(conf, CONF_port),
252 conf_get_int(conf, CONF_tcp_nodelay),
253 conf_get_int(conf, CONF_tcp_keepalives));
254 back->provide_logctx(backhandle, logctx);
256 char *str = dupprintf("%s Error", appname);
257 sprintf(msg, "Unable to open connection to\n"
258 "%.800s\n" "%s", conf_dest(conf), error);
259 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
263 window_name = icon_name = NULL;
264 title = conf_get_str(conf, CONF_wintitle);
266 sprintf(msg, "%s - %s", realhost, appname);
270 set_title(NULL, title);
271 set_icon(NULL, title);
274 * Connect the terminal to the backend for resize purposes.
276 term_provide_resize_fn(term, back->size, backhandle);
279 * Set up a line discipline.
281 ldisc = ldisc_create(conf, term, back, backhandle, NULL);
284 * Destroy the Restart Session menu item. (This will return
285 * failure if it's already absent, as it will be the very first
286 * time we call this function. We ignore that, because as long
287 * as the menu item ends up not being there, we don't care
288 * whether it was us who removed it or not!)
290 for (i = 0; i < lenof(popup_menus); i++) {
291 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
294 session_closed = FALSE;
297 static void close_session(void *ignored_context)
302 session_closed = TRUE;
303 sprintf(morestuff, "%.70s (inactive)", appname);
304 set_icon(NULL, morestuff);
305 set_title(NULL, morestuff);
312 back->free(backhandle);
315 term_provide_resize_fn(term, NULL, NULL);
316 update_specials_menu(NULL);
320 * Show the Restart Session menu item. Do a precautionary
321 * delete first to ensure we never end up with more than one.
323 for (i = 0; i < lenof(popup_menus); i++) {
324 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
325 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
326 IDM_RESTART, "&Restart Session");
330 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
335 int guess_width, guess_height;
339 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
343 InitCommonControls();
345 /* Ensure a Maximize setting in Explorer doesn't maximise the
351 char *str = dupprintf("%s Fatal Error", appname);
352 MessageBox(NULL, "Windows refuses to report a version",
353 str, MB_OK | MB_ICONEXCLAMATION);
359 * If we're running a version of Windows that doesn't support
360 * WM_MOUSEWHEEL, find out what message number we should be
363 if (osVersion.dwMajorVersion < 4 ||
364 (osVersion.dwMajorVersion == 4 &&
365 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
366 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
377 hr = CoInitialize(NULL);
378 if (hr != S_OK && hr != S_FALSE) {
379 char *str = dupprintf("%s Fatal Error", appname);
380 MessageBox(NULL, "Failed to initialize COM subsystem",
381 str, MB_OK | MB_ICONEXCLAMATION);
387 * Process the command line.
392 /* By default, we bring up the config dialog, rather than launching
393 * a session. This gets set to TRUE if something happens to change
394 * that (e.g., a hostname is specified on the command-line). */
395 int allow_launch = FALSE;
397 default_protocol = be_default_protocol;
398 /* Find the appropriate default port. */
400 Backend *b = backend_from_proto(default_protocol);
401 default_port = 0; /* illegal */
403 default_port = b->default_port;
405 conf_set_int(conf, CONF_logtype, LGTYP_NONE);
407 do_defaults(NULL, conf);
412 * Process a couple of command-line options which are more
413 * easily dealt with before the line is broken up into words.
414 * These are the old-fashioned but convenient @sessionname and
415 * the internal-use-only &sharedmemoryhandle, neither of which
416 * are combined with anything else.
418 while (*p && isspace(*p))
422 * An initial @ means that the whole of the rest of the
423 * command line should be treated as the name of a saved
424 * session, with _no quoting or escaping_. This makes it a
425 * very convenient means of automated saved-session
426 * launching, via IDM_SAVEDSESS or Windows 7 jump lists.
429 while (i > 1 && isspace(p[i - 1]))
432 do_defaults(p + 1, conf);
433 if (!conf_launchable(conf) && !do_config()) {
436 allow_launch = TRUE; /* allow it to be launched directly */
437 } else if (*p == '&') {
439 * An initial & means we've been given a command line
440 * containing the hex value of a HANDLE for a file
441 * mapping object, which we must then interpret as a
447 if (sscanf(p + 1, "%p:%u", &filemap, &cpsize) == 2 &&
448 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
449 0, 0, cpsize)) != NULL) {
450 conf_deserialise(conf, cp, cpsize);
452 CloseHandle(filemap);
453 } else if (!do_config()) {
459 * Otherwise, break up the command line and deal with
465 split_into_argv(cmdline, &argc, &argv, NULL);
467 for (i = 0; i < argc; i++) {
471 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
474 cmdline_error("option \"%s\" requires an argument", p);
475 } else if (ret == 2) {
476 i++; /* skip next argument */
477 } else if (ret == 1) {
478 continue; /* nothing further needs doing */
479 } else if (!strcmp(p, "-cleanup") ||
480 !strcmp(p, "-cleanup-during-uninstall")) {
482 * `putty -cleanup'. Remove all registry
483 * entries associated with PuTTY, and also find
484 * and delete the random seed file.
487 /* Are we being invoked from an uninstaller? */
488 if (!strcmp(p, "-cleanup-during-uninstall")) {
489 s1 = dupprintf("Remove saved sessions and random seed file?\n"
491 "If you hit Yes, ALL Registry entries associated\n"
492 "with %s will be removed, as well as the\n"
493 "random seed file. THIS PROCESS WILL\n"
494 "DESTROY YOUR SAVED SESSIONS.\n"
495 "(This only affects the currently logged-in user.)\n"
497 "If you hit No, uninstallation will proceed, but\n"
498 "saved sessions etc will be left on the machine.",
500 s2 = dupprintf("%s Uninstallation", appname);
502 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
503 "associated with %s, and will also remove\n"
504 "the random seed file. (This only affects the\n"
505 "currently logged-in user.)\n"
507 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
508 "Are you really sure you want to continue?",
510 s2 = dupprintf("%s Warning", appname);
512 if (message_box(s1, s2,
513 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
514 HELPCTXID(option_cleanup)) == IDYES) {
520 } else if (!strcmp(p, "-pgpfp")) {
523 } else if (*p != '-') {
527 * If we already have a host name, treat
528 * this argument as a port number. NB we
529 * have to treat this as a saved -P
530 * argument, so that it will be deferred
531 * until it's a good moment to run it.
533 int ret = cmdline_process_param("-P", p, 1, conf);
535 } else if (!strncmp(q, "telnet:", 7)) {
537 * If the hostname starts with "telnet:",
538 * set the protocol to Telnet and process
539 * the string as a Telnet URL.
544 if (q[0] == '/' && q[1] == '/')
546 conf_set_int(conf, CONF_protocol, PROT_TELNET);
548 while (*p && *p != ':' && *p != '/')
554 conf_set_int(conf, CONF_port, atoi(p));
556 conf_set_int(conf, CONF_port, -1);
557 conf_set_str(conf, CONF_host, q);
561 * Otherwise, treat this argument as a host
564 while (*p && !isspace(*p))
568 conf_set_str(conf, CONF_host, q);
572 cmdline_error("unknown option \"%s\"", p);
577 cmdline_run_saved(conf);
579 if (loaded_session || got_host)
582 if ((!allow_launch || !conf_launchable(conf)) && !do_config()) {
587 * Muck about with the hostname in various ways.
590 char *hostbuf = dupstr(conf_get_str(conf, CONF_host));
591 char *host = hostbuf;
595 * Trim leading whitespace.
597 host += strspn(host, " \t");
600 * See if host is of the form user@host, and separate
601 * out the username if so.
603 if (host[0] != '\0') {
604 char *atsign = strrchr(host, '@');
607 conf_set_str(conf, CONF_username, host);
613 * Trim a colon suffix off the hostname if it's there. In
614 * order to protect IPv6 address literals against this
615 * treatment, we do not do this if there's _more_ than one
619 char *c = strchr(host, ':');
622 char *d = strchr(c+1, ':');
629 * Remove any remaining whitespace.
634 if (*q != ' ' && *q != '\t')
640 conf_set_str(conf, CONF_host, hostbuf);
647 wndclass.lpfnWndProc = WndProc;
648 wndclass.cbClsExtra = 0;
649 wndclass.cbWndExtra = 0;
650 wndclass.hInstance = inst;
651 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
652 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
653 wndclass.hbrBackground = NULL;
654 wndclass.lpszMenuName = NULL;
655 wndclass.lpszClassName = appname;
657 RegisterClass(&wndclass);
660 memset(&ucsdata, 0, sizeof(ucsdata));
667 * Guess some defaults for the window size. This all gets
668 * updated later, so we don't really care too much. However, we
669 * do want the font width/height guesses to correspond to a
670 * large font rather than a small one...
677 guess_width = extra_width + font_width * conf_get_int(conf, CONF_width);
678 guess_height = extra_height + font_height*conf_get_int(conf, CONF_height);
681 get_fullscreen_rect(&r);
682 if (guess_width > r.right - r.left)
683 guess_width = r.right - r.left;
684 if (guess_height > r.bottom - r.top)
685 guess_height = r.bottom - r.top;
689 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
691 if (!conf_get_int(conf, CONF_scrollbar))
692 winmode &= ~(WS_VSCROLL);
693 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
694 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
695 if (conf_get_int(conf, CONF_alwaysontop))
696 exwinmode |= WS_EX_TOPMOST;
697 if (conf_get_int(conf, CONF_sunken_edge))
698 exwinmode |= WS_EX_CLIENTEDGE;
699 hwnd = CreateWindowEx(exwinmode, appname, appname,
700 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
701 guess_width, guess_height,
702 NULL, NULL, inst, NULL);
706 * Initialise the fonts, simultaneously correcting the guesses
707 * for font_{width,height}.
712 * Initialise the terminal. (We have to do this _after_
713 * creating the window, since the terminal is the first thing
714 * which will call schedule_timer(), which will in turn call
715 * timer_change_notify() which will expect hwnd to exist.)
717 term = term_init(conf, &ucsdata, NULL);
718 logctx = log_init(NULL, conf);
719 term_provide_logctx(term, logctx);
720 term_size(term, conf_get_int(conf, CONF_height),
721 conf_get_int(conf, CONF_width),
722 conf_get_int(conf, CONF_savelines));
725 * Correct the guesses for extra_{width,height}.
729 GetWindowRect(hwnd, &wr);
730 GetClientRect(hwnd, &cr);
731 offset_width = offset_height = conf_get_int(conf, CONF_window_border);
732 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
733 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
737 * Resize the window, now we know what size we _really_ want it
740 guess_width = extra_width + font_width * term->cols;
741 guess_height = extra_height + font_height * term->rows;
742 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
743 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
746 * Set up a caret bitmap, with no content.
750 int size = (font_width + 15) / 16 * 2 * font_height;
751 bits = snewn(size, char);
752 memset(bits, 0, size);
753 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
756 CreateCaret(hwnd, caretbm, font_width, font_height);
759 * Initialise the scroll bar.
764 si.cbSize = sizeof(si);
765 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
767 si.nMax = term->rows - 1;
768 si.nPage = term->rows;
770 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
774 * Prepare the mouse handler.
776 lastact = MA_NOTHING;
777 lastbtn = MBT_NOTHING;
778 dbltime = GetDoubleClickTime();
781 * Set up the session-control options on the system menu.
788 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
789 popup_menus[CTXMENU].menu = CreatePopupMenu();
790 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
792 savedsess_menu = CreateMenu();
793 get_sesslist(&sesslist, TRUE);
794 update_savedsess_menu();
796 for (j = 0; j < lenof(popup_menus); j++) {
797 m = popup_menus[j].menu;
799 AppendMenu(m, MF_SEPARATOR, 0, 0);
800 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
801 AppendMenu(m, MF_SEPARATOR, 0, 0);
802 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
803 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
804 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) savedsess_menu,
806 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
807 AppendMenu(m, MF_SEPARATOR, 0, 0);
808 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
809 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
810 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
811 AppendMenu(m, MF_SEPARATOR, 0, 0);
812 AppendMenu(m, (conf_get_int(conf, CONF_resize_action)
813 == RESIZE_DISABLED) ? MF_GRAYED : MF_ENABLED,
814 IDM_FULLSCREEN, "&Full Screen");
815 AppendMenu(m, MF_SEPARATOR, 0, 0);
817 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
818 str = dupprintf("&About %s", appname);
819 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
827 * Set up the initial input locale.
829 set_input_locale(GetKeyboardLayout(0));
832 * Finally show the window!
834 ShowWindow(hwnd, show);
835 SetForegroundWindow(hwnd);
838 * Set the palette up.
844 term_set_focus(term, GetForegroundWindow() == hwnd);
852 if (toplevel_callback_pending() ||
853 PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
855 * If we have anything we'd like to do immediately, set
856 * the timeout for MsgWaitForMultipleObjects to zero so
857 * that we'll only do a quick check of our handles and
858 * then get on with whatever that was.
860 * One such option is a pending toplevel callback. The
861 * other is a non-empty Windows message queue, which you'd
862 * think we could leave to MsgWaitForMultipleObjects to
863 * check for us along with all the handles, but in fact we
864 * can't because once PeekMessage in one iteration of this
865 * loop has removed a message from the queue, the whole
866 * queue is considered uninteresting by the next
867 * invocation of MWFMO. So we check ourselves whether the
868 * message queue is non-empty, and if so, set this timeout
869 * to zero to ensure MWFMO doesn't block.
874 /* The messages seem unreliable; especially if we're being tricky */
875 term_set_focus(term, GetForegroundWindow() == hwnd);
878 handles = handle_get_events(&nhandles);
880 n = MsgWaitForMultipleObjects(nhandles, handles, FALSE,
881 timeout, QS_ALLINPUT);
883 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
884 handle_got_event(handles[n - WAIT_OBJECT_0]);
889 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
890 if (msg.message == WM_QUIT)
891 goto finished; /* two-level break */
893 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
894 DispatchMessage(&msg);
897 run_toplevel_callbacks();
901 cleanup_exit(msg.wParam); /* this doesn't return... */
902 return msg.wParam; /* ... but optimiser doesn't know */
908 void cleanup_exit(int code)
919 if (conf_get_int(conf, CONF_protocol) == PROT_SSH) {
934 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
936 char *do_select(SOCKET skt, int startup)
941 events = (FD_CONNECT | FD_READ | FD_WRITE |
942 FD_OOB | FD_CLOSE | FD_ACCEPT);
947 return "do_select(): internal error (hwnd==NULL)";
948 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
949 switch (p_WSAGetLastError()) {
951 return "Network is down";
953 return "WSAAsyncSelect(): unknown error";
960 * Refresh the saved-session submenu from `sesslist'.
962 static void update_savedsess_menu(void)
965 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
966 /* skip sesslist.sessions[0] == Default Settings */
968 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
971 AppendMenu(savedsess_menu, MF_ENABLED,
972 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
973 sesslist.sessions[i]);
974 if (sesslist.nsessions <= 1)
975 AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)");
979 * Update the Special Commands submenu.
981 void update_specials_menu(void *frontend)
987 specials = back->get_specials(backhandle);
992 /* We can't use Windows to provide a stack for submenus, so
993 * here's a lame "stack" that will do for now. */
994 HMENU saved_menu = NULL;
996 new_menu = CreatePopupMenu();
997 for (i = 0; nesting > 0; i++) {
998 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
999 switch (specials[i].code) {
1001 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
1004 assert(nesting < 2);
1006 saved_menu = new_menu; /* XXX lame stacking */
1007 new_menu = CreatePopupMenu();
1008 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
1009 (UINT) new_menu, specials[i].name);
1014 new_menu = saved_menu; /* XXX lame stacking */
1019 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
1024 /* Squirrel the highest special. */
1031 for (j = 0; j < lenof(popup_menus); j++) {
1032 if (specials_menu) {
1033 /* XXX does this free up all submenus? */
1034 DeleteMenu(popup_menus[j].menu, (UINT)specials_menu, MF_BYCOMMAND);
1035 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
1038 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1039 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
1040 (UINT) new_menu, "S&pecial Command");
1041 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1042 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
1045 specials_menu = new_menu;
1048 static void update_mouse_pointer(void)
1051 int force_visible = FALSE;
1052 static int forced_visible = FALSE;
1053 switch (busy_status) {
1056 curstype = IDC_ARROW;
1058 curstype = IDC_IBEAM;
1061 curstype = IDC_APPSTARTING; /* this may be an abuse */
1062 force_visible = TRUE;
1065 curstype = IDC_WAIT;
1066 force_visible = TRUE;
1072 HCURSOR cursor = LoadCursor(NULL, curstype);
1073 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
1074 SetCursor(cursor); /* force redraw of cursor at current posn */
1076 if (force_visible != forced_visible) {
1077 /* We want some cursor shapes to be visible always.
1078 * Along with show_mouseptr(), this manages the ShowCursor()
1079 * counter such that if we switch back to a non-force_visible
1080 * cursor, the previous visibility state is restored. */
1081 ShowCursor(force_visible);
1082 forced_visible = force_visible;
1086 void set_busy_status(void *frontend, int status)
1088 busy_status = status;
1089 update_mouse_pointer();
1093 * set or clear the "raw mouse message" mode
1095 void set_raw_mouse_mode(void *frontend, int activate)
1097 activate = activate && !conf_get_int(conf, CONF_no_mouse_rep);
1098 send_raw_mouse = activate;
1099 update_mouse_pointer();
1103 * Print a message box and close the connection.
1105 void connection_fatal(void *frontend, char *fmt, ...)
1108 char *stuff, morestuff[100];
1111 stuff = dupvprintf(fmt, ap);
1113 sprintf(morestuff, "%.70s Fatal Error", appname);
1114 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1117 if (conf_get_int(conf, CONF_close_on_exit) == FORCE_ON)
1120 queue_toplevel_callback(close_session, NULL);
1125 * Report an error at the command-line parsing stage.
1127 void cmdline_error(char *fmt, ...)
1130 char *stuff, morestuff[100];
1133 stuff = dupvprintf(fmt, ap);
1135 sprintf(morestuff, "%.70s Command Line Error", appname);
1136 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
1142 * Actually do the job requested by a WM_NETEVENT
1144 static void wm_netevent_callback(void *vctx)
1146 struct wm_netevent_params *params = (struct wm_netevent_params *)vctx;
1147 select_result(params->wParam, params->lParam);
1152 * Copy the colour palette from the configuration data into defpal.
1153 * This is non-trivial because the colour indices are different.
1155 static void conftopalette(void)
1158 static const int ww[] = {
1159 256, 257, 258, 259, 260, 261,
1160 0, 8, 1, 9, 2, 10, 3, 11,
1161 4, 12, 5, 13, 6, 14, 7, 15
1164 for (i = 0; i < 22; i++) {
1166 defpal[w].rgbtRed = conf_get_int_int(conf, CONF_colours, i*3+0);
1167 defpal[w].rgbtGreen = conf_get_int_int(conf, CONF_colours, i*3+1);
1168 defpal[w].rgbtBlue = conf_get_int_int(conf, CONF_colours, i*3+2);
1170 for (i = 0; i < NEXTCOLOURS; i++) {
1172 int r = i / 36, g = (i / 6) % 6, b = i % 6;
1173 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1174 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1175 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
1177 int shade = i - 216;
1178 shade = shade * 10 + 8;
1179 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1180 defpal[i+16].rgbtBlue = shade;
1184 /* Override with system colours if appropriate */
1185 if (conf_get_int(conf, CONF_system_colour))
1190 * Override bit of defpal with colours from the system.
1191 * (NB that this takes a copy the system colours at the time this is called,
1192 * so subsequent colour scheme changes don't take effect. To fix that we'd
1193 * probably want to be using GetSysColorBrush() and the like.)
1195 static void systopalette(void)
1198 static const struct { int nIndex; int norm; int bold; } or[] =
1200 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1201 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1202 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1203 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
1206 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1207 COLORREF colour = GetSysColor(or[i].nIndex);
1208 defpal[or[i].norm].rgbtRed =
1209 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1210 defpal[or[i].norm].rgbtGreen =
1211 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1212 defpal[or[i].norm].rgbtBlue =
1213 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1218 * Set up the colour palette.
1220 static void init_palette(void)
1223 HDC hdc = GetDC(hwnd);
1225 if (conf_get_int(conf, CONF_try_palette) &&
1226 GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1228 * This is a genuine case where we must use smalloc
1229 * because the snew macros can't cope.
1231 logpal = smalloc(sizeof(*logpal)
1232 - sizeof(logpal->palPalEntry)
1233 + NALLCOLOURS * sizeof(PALETTEENTRY));
1234 logpal->palVersion = 0x300;
1235 logpal->palNumEntries = NALLCOLOURS;
1236 for (i = 0; i < NALLCOLOURS; i++) {
1237 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1238 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1239 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1240 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1242 pal = CreatePalette(logpal);
1244 SelectPalette(hdc, pal, FALSE);
1245 RealizePalette(hdc);
1246 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1249 ReleaseDC(hwnd, hdc);
1252 for (i = 0; i < NALLCOLOURS; i++)
1253 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1254 defpal[i].rgbtGreen,
1255 defpal[i].rgbtBlue);
1257 for (i = 0; i < NALLCOLOURS; i++)
1258 colours[i] = RGB(defpal[i].rgbtRed,
1259 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1263 * This is a wrapper to ExtTextOut() to force Windows to display
1264 * the precise glyphs we give it. Otherwise it would do its own
1265 * bidi and Arabic shaping, and we would end up uncertain which
1266 * characters it had put where.
1268 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1269 unsigned short *lpString, UINT cbCount,
1270 CONST INT *lpDx, int opaque)
1274 * The LCC include files apparently don't supply the
1275 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1276 * proper: the differences aren't important to us (the only
1277 * variable-width string parameter is one we don't use anyway).
1283 char *buffer = snewn(cbCount*2+2, char);
1284 char *classbuffer = snewn(cbCount, char);
1285 memset(&gcpr, 0, sizeof(gcpr));
1286 memset(buffer, 0, cbCount*2+2);
1287 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1289 gcpr.lStructSize = sizeof(gcpr);
1290 gcpr.lpGlyphs = (void *)buffer;
1291 gcpr.lpClass = (void *)classbuffer;
1292 gcpr.nGlyphs = cbCount;
1293 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1294 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
1296 ExtTextOut(hdc, x, y,
1297 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1298 lprc, buffer, cbCount, lpDx);
1302 * The exact_textout() wrapper, unfortunately, destroys the useful
1303 * Windows `font linking' behaviour: automatic handling of Unicode
1304 * code points not supported in this font by falling back to a font
1305 * which does contain them. Therefore, we adopt a multi-layered
1306 * approach: for any potentially-bidi text, we use exact_textout(),
1307 * and for everything else we use a simple ExtTextOut as we did
1308 * before exact_textout() was introduced.
1310 static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1311 unsigned short *lpString, UINT cbCount,
1312 CONST INT *lpDx, int opaque)
1315 int bkmode = 0, got_bkmode = FALSE;
1319 for (i = 0; i < (int)cbCount ;) {
1320 int rtl = is_rtl(lpString[i]);
1324 for (j = i+1; j < (int)cbCount; j++) {
1325 if (rtl != is_rtl(lpString[j]))
1331 * Now [i,j) indicates a maximal substring of lpString
1332 * which should be displayed using the same textout
1336 exact_textout(hdc, xp, y, lprc, lpString+i, j-i,
1337 font_varpitch ? NULL : lpDx+i, opaque);
1339 ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1340 lprc, lpString+i, j-i,
1341 font_varpitch ? NULL : lpDx+i);
1347 bkmode = GetBkMode(hdc);
1349 SetBkMode(hdc, TRANSPARENT);
1354 SetBkMode(hdc, bkmode);
1357 static int get_font_width(HDC hdc, const TEXTMETRIC *tm)
1360 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1361 if (!(tm->tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1362 ret = tm->tmAveCharWidth;
1366 ABCFLOAT widths[LAST-FIRST + 1];
1369 font_varpitch = TRUE;
1370 font_dualwidth = TRUE;
1371 if (GetCharABCWidthsFloat(hdc, FIRST, LAST, widths)) {
1373 for (j = 0; j < lenof(widths); j++) {
1374 int width = (int)(0.5 + widths[j].abcfA +
1375 widths[j].abcfB + widths[j].abcfC);
1380 ret = tm->tmMaxCharWidth;
1389 * Initialise all the fonts we will need initially. There may be as many as
1390 * three or as few as one. The other (potentially) twenty-one fonts are done
1391 * if/when they are needed.
1395 * - check the font width and height, correcting our guesses if
1398 * - verify that the bold font is the same width as the ordinary
1399 * one, and engage shadow bolding if not.
1401 * - verify that the underlined font is the same width as the
1402 * ordinary one (manual underlining by means of line drawing can
1403 * be done in a pinch).
1405 static void init_fonts(int pick_width, int pick_height)
1414 int fw_dontcare, fw_bold;
1416 for (i = 0; i < FONT_MAXNO; i++)
1419 bold_font_mode = conf_get_int(conf, CONF_bold_style) & 1 ?
1420 BOLD_FONT : BOLD_NONE;
1421 bold_colours = conf_get_int(conf, CONF_bold_style) & 2 ? TRUE : FALSE;
1422 und_mode = UND_FONT;
1424 font = conf_get_fontspec(conf, CONF_font);
1426 fw_dontcare = FW_BOLD;
1429 fw_dontcare = FW_DONTCARE;
1436 font_height = pick_height;
1438 font_height = font->height;
1439 if (font_height > 0) {
1441 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1444 font_width = pick_width;
1446 quality = conf_get_int(conf, CONF_font_quality);
1447 #define f(i,c,w,u) \
1448 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1449 c, OUT_DEFAULT_PRECIS, \
1450 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality), \
1451 FIXED_PITCH | FF_DONTCARE, font->name)
1453 f(FONT_NORMAL, font->charset, fw_dontcare, FALSE);
1455 SelectObject(hdc, fonts[FONT_NORMAL]);
1456 GetTextMetrics(hdc, &tm);
1458 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1460 /* Note that the TMPF_FIXED_PITCH bit is defined upside down :-( */
1461 if (!(tm.tmPitchAndFamily & TMPF_FIXED_PITCH)) {
1462 font_varpitch = FALSE;
1463 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1465 font_varpitch = TRUE;
1466 font_dualwidth = TRUE;
1468 if (pick_width == 0 || pick_height == 0) {
1469 font_height = tm.tmHeight;
1470 font_width = get_font_width(hdc, &tm);
1473 #ifdef RDB_DEBUG_PATCH
1474 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1475 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1480 DWORD cset = tm.tmCharSet;
1481 memset(&info, 0xFF, sizeof(info));
1483 /* !!! Yes the next line is right */
1484 if (cset == OEM_CHARSET)
1485 ucsdata.font_codepage = GetOEMCP();
1487 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1488 ucsdata.font_codepage = info.ciACP;
1490 ucsdata.font_codepage = -1;
1492 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1493 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1496 f(FONT_UNDERLINE, font->charset, fw_dontcare, TRUE);
1499 * Some fonts, e.g. 9-pt Courier, draw their underlines
1500 * outside their character cell. We successfully prevent
1501 * screen corruption by clipping the text output, but then
1502 * we lose the underline completely. Here we try to work
1503 * out whether this is such a font, and if it is, we set a
1504 * flag that causes underlines to be drawn by hand.
1506 * Having tried other more sophisticated approaches (such
1507 * as examining the TEXTMETRIC structure or requesting the
1508 * height of a string), I think we'll do this the brute
1509 * force way: we create a small bitmap, draw an underlined
1510 * space on it, and test to see whether any pixels are
1511 * foreground-coloured. (Since we expect the underline to
1512 * go all the way across the character cell, we only search
1513 * down a single column of the bitmap, half way across.)
1517 HBITMAP und_bm, und_oldbm;
1521 und_dc = CreateCompatibleDC(hdc);
1522 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1523 und_oldbm = SelectObject(und_dc, und_bm);
1524 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1525 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1526 SetTextColor(und_dc, RGB(255, 255, 255));
1527 SetBkColor(und_dc, RGB(0, 0, 0));
1528 SetBkMode(und_dc, OPAQUE);
1529 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1531 for (i = 0; i < font_height; i++) {
1532 c = GetPixel(und_dc, font_width / 2, i);
1533 if (c != RGB(0, 0, 0))
1536 SelectObject(und_dc, und_oldbm);
1537 DeleteObject(und_bm);
1540 und_mode = UND_LINE;
1541 DeleteObject(fonts[FONT_UNDERLINE]);
1542 fonts[FONT_UNDERLINE] = 0;
1546 if (bold_font_mode == BOLD_FONT) {
1547 f(FONT_BOLD, font->charset, fw_bold, FALSE);
1551 descent = tm.tmAscent + 1;
1552 if (descent >= font_height)
1553 descent = font_height - 1;
1555 for (i = 0; i < 3; i++) {
1557 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1558 fontsize[i] = get_font_width(hdc, &tm) + 256 * tm.tmHeight;
1565 ReleaseDC(hwnd, hdc);
1567 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1568 und_mode = UND_LINE;
1569 DeleteObject(fonts[FONT_UNDERLINE]);
1570 fonts[FONT_UNDERLINE] = 0;
1573 if (bold_font_mode == BOLD_FONT &&
1574 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1575 bold_font_mode = BOLD_SHADOW;
1576 DeleteObject(fonts[FONT_BOLD]);
1577 fonts[FONT_BOLD] = 0;
1579 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1581 init_ucs(conf, &ucsdata);
1584 static void another_font(int fontno)
1587 int fw_dontcare, fw_bold, quality;
1592 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1595 basefont = (fontno & ~(FONT_BOLDUND));
1596 if (basefont != fontno && !fontflag[basefont])
1597 another_font(basefont);
1599 font = conf_get_fontspec(conf, CONF_font);
1602 fw_dontcare = FW_BOLD;
1605 fw_dontcare = FW_DONTCARE;
1615 if (fontno & FONT_WIDE)
1617 if (fontno & FONT_NARROW)
1619 if (fontno & FONT_OEM)
1621 if (fontno & FONT_BOLD)
1623 if (fontno & FONT_UNDERLINE)
1626 quality = conf_get_int(conf, CONF_font_quality);
1629 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1630 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1631 CLIP_DEFAULT_PRECIS, FONT_QUALITY(quality),
1632 DEFAULT_PITCH | FF_DONTCARE, s);
1634 fontflag[fontno] = 1;
1637 static void deinit_fonts(void)
1640 for (i = 0; i < FONT_MAXNO; i++) {
1642 DeleteObject(fonts[i]);
1648 void request_resize(void *frontend, int w, int h)
1652 /* If the window is maximized supress resizing attempts */
1653 if (IsZoomed(hwnd)) {
1654 if (conf_get_int(conf, CONF_resize_action) == RESIZE_TERM)
1658 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED) return;
1659 if (h == term->rows && w == term->cols) return;
1661 /* Sanity checks ... */
1663 static int first_time = 1;
1666 switch (first_time) {
1668 /* Get the size of the screen */
1669 if (get_fullscreen_rect(&ss))
1670 /* first_time = 0 */ ;
1676 /* Make sure the values are sane */
1677 width = (ss.right - ss.left - extra_width) / 4;
1678 height = (ss.bottom - ss.top - extra_height) / 6;
1680 if (w > width || h > height)
1689 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
1691 if (conf_get_int(conf, CONF_resize_action) != RESIZE_FONT &&
1693 width = extra_width + font_width * w;
1694 height = extra_height + font_height * h;
1696 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1697 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1698 SWP_NOMOVE | SWP_NOZORDER);
1702 InvalidateRect(hwnd, NULL, TRUE);
1705 static void reset_window(int reinit) {
1707 * This function decides how to resize or redraw when the
1708 * user changes something.
1710 * This function doesn't like to change the terminal size but if the
1711 * font size is locked that may be it's only soluion.
1713 int win_width, win_height, resize_action, window_border;
1716 #ifdef RDB_DEBUG_PATCH
1717 debug((27, "reset_window()"));
1720 /* Current window sizes ... */
1721 GetWindowRect(hwnd, &wr);
1722 GetClientRect(hwnd, &cr);
1724 win_width = cr.right - cr.left;
1725 win_height = cr.bottom - cr.top;
1727 resize_action = conf_get_int(conf, CONF_resize_action);
1728 window_border = conf_get_int(conf, CONF_window_border);
1730 if (resize_action == RESIZE_DISABLED)
1733 /* Are we being forced to reload the fonts ? */
1735 #ifdef RDB_DEBUG_PATCH
1736 debug((27, "reset_window() -- Forced deinit"));
1742 /* Oh, looks like we're minimised */
1743 if (win_width == 0 || win_height == 0)
1746 /* Is the window out of position ? */
1748 (offset_width != (win_width-font_width*term->cols)/2 ||
1749 offset_height != (win_height-font_height*term->rows)/2) ){
1750 offset_width = (win_width-font_width*term->cols)/2;
1751 offset_height = (win_height-font_height*term->rows)/2;
1752 InvalidateRect(hwnd, NULL, TRUE);
1753 #ifdef RDB_DEBUG_PATCH
1754 debug((27, "reset_window() -> Reposition terminal"));
1758 if (IsZoomed(hwnd)) {
1759 /* We're fullscreen, this means we must not change the size of
1760 * the window so it's the font size or the terminal itself.
1763 extra_width = wr.right - wr.left - cr.right + cr.left;
1764 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1766 if (resize_action != RESIZE_TERM) {
1767 if (font_width != win_width/term->cols ||
1768 font_height != win_height/term->rows) {
1770 init_fonts(win_width/term->cols, win_height/term->rows);
1771 offset_width = (win_width-font_width*term->cols)/2;
1772 offset_height = (win_height-font_height*term->rows)/2;
1773 InvalidateRect(hwnd, NULL, TRUE);
1774 #ifdef RDB_DEBUG_PATCH
1775 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1776 font_width, font_height));
1780 if (font_width * term->cols != win_width ||
1781 font_height * term->rows != win_height) {
1782 /* Our only choice at this point is to change the
1783 * size of the terminal; Oh well.
1785 term_size(term, win_height/font_height, win_width/font_width,
1786 conf_get_int(conf, CONF_savelines));
1787 offset_width = (win_width-font_width*term->cols)/2;
1788 offset_height = (win_height-font_height*term->rows)/2;
1789 InvalidateRect(hwnd, NULL, TRUE);
1790 #ifdef RDB_DEBUG_PATCH
1791 debug((27, "reset_window() -> Zoomed term_size"));
1798 /* Hmm, a force re-init means we should ignore the current window
1799 * so we resize to the default font size.
1802 #ifdef RDB_DEBUG_PATCH
1803 debug((27, "reset_window() -> Forced re-init"));
1806 offset_width = offset_height = window_border;
1807 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1808 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1810 if (win_width != font_width*term->cols + offset_width*2 ||
1811 win_height != font_height*term->rows + offset_height*2) {
1813 /* If this is too large windows will resize it to the maximum
1814 * allowed window size, we will then be back in here and resize
1815 * the font or terminal to fit.
1817 SetWindowPos(hwnd, NULL, 0, 0,
1818 font_width*term->cols + extra_width,
1819 font_height*term->rows + extra_height,
1820 SWP_NOMOVE | SWP_NOZORDER);
1823 InvalidateRect(hwnd, NULL, TRUE);
1827 /* Okay the user doesn't want us to change the font so we try the
1828 * window. But that may be too big for the screen which forces us
1829 * to change the terminal.
1831 if ((resize_action == RESIZE_TERM && reinit<=0) ||
1832 (resize_action == RESIZE_EITHER && reinit<0) ||
1834 offset_width = offset_height = window_border;
1835 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1836 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1838 if (win_width != font_width*term->cols + offset_width*2 ||
1839 win_height != font_height*term->rows + offset_height*2) {
1844 get_fullscreen_rect(&ss);
1846 width = (ss.right - ss.left - extra_width) / font_width;
1847 height = (ss.bottom - ss.top - extra_height) / font_height;
1850 if ( term->rows > height || term->cols > width ) {
1851 if (resize_action == RESIZE_EITHER) {
1852 /* Make the font the biggest we can */
1853 if (term->cols > width)
1854 font_width = (ss.right - ss.left - extra_width)
1856 if (term->rows > height)
1857 font_height = (ss.bottom - ss.top - extra_height)
1861 init_fonts(font_width, font_height);
1863 width = (ss.right - ss.left - extra_width) / font_width;
1864 height = (ss.bottom - ss.top - extra_height) / font_height;
1866 if ( height > term->rows ) height = term->rows;
1867 if ( width > term->cols ) width = term->cols;
1868 term_size(term, height, width,
1869 conf_get_int(conf, CONF_savelines));
1870 #ifdef RDB_DEBUG_PATCH
1871 debug((27, "reset_window() -> term resize to (%d,%d)",
1877 SetWindowPos(hwnd, NULL, 0, 0,
1878 font_width*term->cols + extra_width,
1879 font_height*term->rows + extra_height,
1880 SWP_NOMOVE | SWP_NOZORDER);
1882 InvalidateRect(hwnd, NULL, TRUE);
1883 #ifdef RDB_DEBUG_PATCH
1884 debug((27, "reset_window() -> window resize to (%d,%d)",
1885 font_width*term->cols + extra_width,
1886 font_height*term->rows + extra_height));
1892 /* We're allowed to or must change the font but do we want to ? */
1894 if (font_width != (win_width-window_border*2)/term->cols ||
1895 font_height != (win_height-window_border*2)/term->rows) {
1898 init_fonts((win_width-window_border*2)/term->cols,
1899 (win_height-window_border*2)/term->rows);
1900 offset_width = (win_width-font_width*term->cols)/2;
1901 offset_height = (win_height-font_height*term->rows)/2;
1903 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1904 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1906 InvalidateRect(hwnd, NULL, TRUE);
1907 #ifdef RDB_DEBUG_PATCH
1908 debug((25, "reset_window() -> font resize to (%d,%d)",
1909 font_width, font_height));
1914 static void set_input_locale(HKL kl)
1918 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1919 lbuf, sizeof(lbuf));
1921 kbd_codepage = atoi(lbuf);
1924 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1926 int thistime = GetMessageTime();
1928 if (send_raw_mouse &&
1929 !(shift && conf_get_int(conf, CONF_mouse_override))) {
1930 lastbtn = MBT_NOTHING;
1931 term_mouse(term, b, translate_button(b), MA_CLICK,
1932 x, y, shift, ctrl, alt);
1936 if (lastbtn == b && thistime - lasttime < dbltime) {
1937 lastact = (lastact == MA_CLICK ? MA_2CLK :
1938 lastact == MA_2CLK ? MA_3CLK :
1939 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1944 if (lastact != MA_NOTHING)
1945 term_mouse(term, b, translate_button(b), lastact,
1946 x, y, shift, ctrl, alt);
1947 lasttime = thistime;
1951 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1952 * into a cooked one (SELECT, EXTEND, PASTE).
1954 static Mouse_Button translate_button(Mouse_Button button)
1956 if (button == MBT_LEFT)
1958 if (button == MBT_MIDDLE)
1959 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
1960 MBT_PASTE : MBT_EXTEND;
1961 if (button == MBT_RIGHT)
1962 return conf_get_int(conf, CONF_mouse_is_xterm) == 1 ?
1963 MBT_EXTEND : MBT_PASTE;
1964 return 0; /* shouldn't happen */
1967 static void show_mouseptr(int show)
1969 /* NB that the counter in ShowCursor() is also frobbed by
1970 * update_mouse_pointer() */
1971 static int cursor_visible = 1;
1972 if (!conf_get_int(conf, CONF_hide_mouseptr))
1973 show = 1; /* override if this feature disabled */
1974 if (cursor_visible && !show)
1976 else if (!cursor_visible && show)
1978 cursor_visible = show;
1981 static int is_alt_pressed(void)
1984 int r = GetKeyboardState(keystate);
1987 if (keystate[VK_MENU] & 0x80)
1989 if (keystate[VK_RMENU] & 0x80)
1994 static int resizing;
1996 void notify_remote_exit(void *fe)
1998 int exitcode, close_on_exit;
2000 if (!session_closed &&
2001 (exitcode = back->exitcode(backhandle)) >= 0) {
2002 close_on_exit = conf_get_int(conf, CONF_close_on_exit);
2003 /* Abnormal exits will already have set session_closed and taken
2004 * appropriate action. */
2005 if (close_on_exit == FORCE_ON ||
2006 (close_on_exit == AUTO && exitcode != INT_MAX)) {
2009 queue_toplevel_callback(close_session, NULL);
2010 session_closed = TRUE;
2011 /* exitcode == INT_MAX indicates that the connection was closed
2012 * by a fatal error, so an error box will be coming our way and
2013 * we should not generate this informational one. */
2014 if (exitcode != INT_MAX)
2015 MessageBox(hwnd, "Connection closed by remote host",
2016 appname, MB_OK | MB_ICONINFORMATION);
2021 void timer_change_notify(unsigned long next)
2023 unsigned long now = GETTICKCOUNT();
2025 if (now - next < INT_MAX)
2029 KillTimer(hwnd, TIMING_TIMER_ID);
2030 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
2031 timing_next_time = next;
2034 static void conf_cache_data(void)
2036 /* Cache some items from conf to speed lookups in very hot code */
2037 cursor_type = conf_get_int(conf, CONF_cursor_type);
2038 vtmode = conf_get_int(conf, CONF_vtmode);
2041 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
2042 WPARAM wParam, LPARAM lParam)
2045 static int ignore_clip = FALSE;
2046 static int need_backend_resize = FALSE;
2047 static int fullscr_on_max = FALSE;
2048 static int processed_resize = FALSE;
2049 static UINT last_mousemove = 0;
2054 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
2057 KillTimer(hwnd, TIMING_TIMER_ID);
2058 if (run_timers(timing_next_time, &next)) {
2059 timer_change_notify(next);
2070 str = dupprintf("%s Exit Confirmation", appname);
2071 if (session_closed || !conf_get_int(conf, CONF_warn_on_close) ||
2073 "Are you sure you want to close this session?",
2074 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
2076 DestroyWindow(hwnd);
2084 case WM_INITMENUPOPUP:
2085 if ((HMENU)wParam == savedsess_menu) {
2086 /* About to pop up Saved Sessions sub-menu.
2087 * Refresh the session list. */
2088 get_sesslist(&sesslist, FALSE); /* free */
2089 get_sesslist(&sesslist, TRUE);
2090 update_savedsess_menu();
2096 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
2107 BOOL inherit_handles;
2109 PROCESS_INFORMATION pi;
2110 HANDLE filemap = NULL;
2112 if (wParam == IDM_DUPSESS) {
2114 * Allocate a file-mapping memory chunk for the
2117 SECURITY_ATTRIBUTES sa;
2121 size = conf_serialised_size(conf);
2123 sa.nLength = sizeof(sa);
2124 sa.lpSecurityDescriptor = NULL;
2125 sa.bInheritHandle = TRUE;
2126 filemap = CreateFileMapping(INVALID_HANDLE_VALUE,
2130 if (filemap && filemap != INVALID_HANDLE_VALUE) {
2131 p = MapViewOfFile(filemap, FILE_MAP_WRITE, 0, 0, size);
2133 conf_serialise(conf, p);
2137 inherit_handles = TRUE;
2138 sprintf(c, "putty &%p:%u", filemap, (unsigned)size);
2140 } else if (wParam == IDM_SAVEDSESS) {
2141 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
2142 / MENU_SAVED_STEP) + 1;
2143 if (sessno < (unsigned)sesslist.nsessions) {
2144 char *session = sesslist.sessions[sessno];
2145 cl = dupprintf("putty @%s", session);
2146 inherit_handles = FALSE;
2150 } else /* IDM_NEWSESS */ {
2152 inherit_handles = FALSE;
2155 GetModuleFileName(NULL, b, sizeof(b) - 1);
2157 si.lpReserved = NULL;
2158 si.lpDesktop = NULL;
2162 si.lpReserved2 = NULL;
2163 CreateProcess(b, cl, NULL, NULL, inherit_handles,
2164 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
2165 CloseHandle(pi.hProcess);
2166 CloseHandle(pi.hThread);
2169 CloseHandle(filemap);
2176 logevent(NULL, "----- Session restarted -----");
2177 term_pwron(term, FALSE);
2186 int reconfig_result;
2191 reconfiguring = TRUE;
2194 * Copy the current window title into the stored
2195 * previous configuration, so that doing nothing to
2196 * the window title field in the config box doesn't
2197 * reset the title to its startup state.
2199 conf_set_str(conf, CONF_wintitle, window_name);
2201 prev_conf = conf_copy(conf);
2204 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
2205 reconfiguring = FALSE;
2206 if (!reconfig_result) {
2207 conf_free(prev_conf);
2213 resize_action = conf_get_int(conf, CONF_resize_action);
2215 /* Disable full-screen if resizing forbidden */
2217 for (i = 0; i < lenof(popup_menus); i++)
2218 EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN,
2220 (resize_action == RESIZE_DISABLED)
2221 ? MF_GRAYED : MF_ENABLED);
2222 /* Gracefully unzoom if necessary */
2223 if (IsZoomed(hwnd) && (resize_action == RESIZE_DISABLED))
2224 ShowWindow(hwnd, SW_RESTORE);
2227 /* Pass new config data to the logging module */
2228 log_reconfig(logctx, conf);
2232 * Flush the line discipline's edit buffer in the
2233 * case where local editing has just been disabled.
2235 ldisc_configure(ldisc, conf);
2237 ldisc_send(ldisc, NULL, 0, 0);
2245 /* Pass new config data to the terminal */
2246 term_reconfig(term, conf);
2248 /* Pass new config data to the back end */
2250 back->reconfig(backhandle, conf);
2252 /* Screen size changed ? */
2253 if (conf_get_int(conf, CONF_height) !=
2254 conf_get_int(prev_conf, CONF_height) ||
2255 conf_get_int(conf, CONF_width) !=
2256 conf_get_int(prev_conf, CONF_width) ||
2257 conf_get_int(conf, CONF_savelines) !=
2258 conf_get_int(prev_conf, CONF_savelines) ||
2259 resize_action == RESIZE_FONT ||
2260 (resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
2261 resize_action == RESIZE_DISABLED)
2262 term_size(term, conf_get_int(conf, CONF_height),
2263 conf_get_int(conf, CONF_width),
2264 conf_get_int(conf, CONF_savelines));
2266 /* Enable or disable the scroll bar, etc */
2268 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
2269 LONG nexflag, exflag =
2270 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
2273 if (conf_get_int(conf, CONF_alwaysontop) !=
2274 conf_get_int(prev_conf, CONF_alwaysontop)) {
2275 if (conf_get_int(conf, CONF_alwaysontop)) {
2276 nexflag |= WS_EX_TOPMOST;
2277 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2278 SWP_NOMOVE | SWP_NOSIZE);
2280 nexflag &= ~(WS_EX_TOPMOST);
2281 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2282 SWP_NOMOVE | SWP_NOSIZE);
2285 if (conf_get_int(conf, CONF_sunken_edge))
2286 nexflag |= WS_EX_CLIENTEDGE;
2288 nexflag &= ~(WS_EX_CLIENTEDGE);
2291 if (conf_get_int(conf, is_full_screen() ?
2292 CONF_scrollbar_in_fullscreen :
2296 nflg &= ~WS_VSCROLL;
2298 if (resize_action == RESIZE_DISABLED ||
2300 nflg &= ~WS_THICKFRAME;
2302 nflg |= WS_THICKFRAME;
2304 if (resize_action == RESIZE_DISABLED)
2305 nflg &= ~WS_MAXIMIZEBOX;
2307 nflg |= WS_MAXIMIZEBOX;
2309 if (nflg != flag || nexflag != exflag) {
2311 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
2312 if (nexflag != exflag)
2313 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
2315 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2316 SWP_NOACTIVATE | SWP_NOCOPYBITS |
2317 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2325 if (resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2330 set_title(NULL, conf_get_str(conf, CONF_wintitle));
2331 if (IsIconic(hwnd)) {
2333 conf_get_int(conf, CONF_win_name_always) ?
2334 window_name : icon_name);
2338 FontSpec *font = conf_get_fontspec(conf, CONF_font);
2339 FontSpec *prev_font = conf_get_fontspec(prev_conf,
2342 if (!strcmp(font->name, prev_font->name) ||
2343 !strcmp(conf_get_str(conf, CONF_line_codepage),
2344 conf_get_str(prev_conf, CONF_line_codepage)) ||
2345 font->isbold != prev_font->isbold ||
2346 font->height != prev_font->height ||
2347 font->charset != prev_font->charset ||
2348 conf_get_int(conf, CONF_font_quality) !=
2349 conf_get_int(prev_conf, CONF_font_quality) ||
2350 conf_get_int(conf, CONF_vtmode) !=
2351 conf_get_int(prev_conf, CONF_vtmode) ||
2352 conf_get_int(conf, CONF_bold_style) !=
2353 conf_get_int(prev_conf, CONF_bold_style) ||
2354 resize_action == RESIZE_DISABLED ||
2355 resize_action == RESIZE_EITHER ||
2356 resize_action != conf_get_int(prev_conf,
2357 CONF_resize_action))
2361 InvalidateRect(hwnd, NULL, TRUE);
2362 reset_window(init_lvl);
2364 conf_free(prev_conf);
2371 request_paste(NULL);
2377 term_pwron(term, TRUE);
2379 ldisc_send(ldisc, NULL, 0, 0);
2385 launch_help(hwnd, NULL);
2389 * We get this if the System menu has been activated
2396 * We get this if the System menu has been activated
2397 * using the keyboard. This might happen from within
2398 * TranslateKey, in which case it really wants to be
2399 * followed by a `space' character to actually _bring
2400 * the menu up_ rather than just sitting there in
2401 * `ready to appear' state.
2403 show_mouseptr(1); /* make sure pointer is visible */
2405 PostMessage(hwnd, WM_CHAR, ' ', 0);
2407 case IDM_FULLSCREEN:
2411 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
2412 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2414 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2415 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2417 * Ensure we haven't been sent a bogus SYSCOMMAND
2418 * which would cause us to reference invalid memory
2419 * and crash. Perhaps I'm just too paranoid here.
2421 if (i >= n_specials)
2424 back->special(backhandle, specials[i].code);
2429 #define X_POS(l) ((int)(short)LOWORD(l))
2430 #define Y_POS(l) ((int)(short)HIWORD(l))
2432 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2433 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2434 case WM_LBUTTONDOWN:
2435 case WM_MBUTTONDOWN:
2436 case WM_RBUTTONDOWN:
2440 if (message == WM_RBUTTONDOWN &&
2441 ((wParam & MK_CONTROL) ||
2442 (conf_get_int(conf, CONF_mouse_is_xterm) == 2))) {
2445 show_mouseptr(1); /* make sure pointer is visible */
2446 GetCursorPos(&cursorpos);
2447 TrackPopupMenu(popup_menus[CTXMENU].menu,
2448 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2449 cursorpos.x, cursorpos.y,
2457 case WM_LBUTTONDOWN:
2459 wParam |= MK_LBUTTON;
2462 case WM_MBUTTONDOWN:
2463 button = MBT_MIDDLE;
2464 wParam |= MK_MBUTTON;
2467 case WM_RBUTTONDOWN:
2469 wParam |= MK_RBUTTON;
2474 wParam &= ~MK_LBUTTON;
2478 button = MBT_MIDDLE;
2479 wParam &= ~MK_MBUTTON;
2484 wParam &= ~MK_RBUTTON;
2488 button = press = 0; /* shouldn't happen */
2492 * Special case: in full-screen mode, if the left
2493 * button is clicked in the very top left corner of the
2494 * window, we put up the System menu instead of doing
2498 char mouse_on_hotspot = 0;
2507 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2510 mi.cbSize = sizeof(MONITORINFO);
2511 GetMonitorInfo(mon, &mi);
2513 if (mi.rcMonitor.left == pt.x &&
2514 mi.rcMonitor.top == pt.y) {
2515 mouse_on_hotspot = 1;
2520 if (pt.x == 0 && pt.y == 0) {
2521 mouse_on_hotspot = 1;
2524 if (is_full_screen() && press &&
2525 button == MBT_LEFT && mouse_on_hotspot) {
2526 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2527 MAKELPARAM(pt.x, pt.y));
2534 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2535 wParam & MK_SHIFT, wParam & MK_CONTROL,
2539 term_mouse(term, button, translate_button(button), MA_RELEASE,
2540 TO_CHR_X(X_POS(lParam)),
2541 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2542 wParam & MK_CONTROL, is_alt_pressed());
2543 if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)))
2551 * Windows seems to like to occasionally send MOUSEMOVE
2552 * events even if the mouse hasn't moved. Don't unhide
2553 * the mouse pointer in this case.
2555 static WPARAM wp = 0;
2556 static LPARAM lp = 0;
2557 if (wParam != wp || lParam != lp ||
2558 last_mousemove != WM_MOUSEMOVE) {
2560 wp = wParam; lp = lParam;
2561 last_mousemove = WM_MOUSEMOVE;
2565 * Add the mouse position and message time to the random
2568 noise_ultralight(lParam);
2570 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2571 GetCapture() == hwnd) {
2573 if (wParam & MK_LBUTTON)
2575 else if (wParam & MK_MBUTTON)
2579 term_mouse(term, b, translate_button(b), MA_DRAG,
2580 TO_CHR_X(X_POS(lParam)),
2581 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2582 wParam & MK_CONTROL, is_alt_pressed());
2585 case WM_NCMOUSEMOVE:
2587 static WPARAM wp = 0;
2588 static LPARAM lp = 0;
2589 if (wParam != wp || lParam != lp ||
2590 last_mousemove != WM_NCMOUSEMOVE) {
2592 wp = wParam; lp = lParam;
2593 last_mousemove = WM_NCMOUSEMOVE;
2596 noise_ultralight(lParam);
2598 case WM_IGNORE_CLIP:
2599 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2601 case WM_DESTROYCLIPBOARD:
2603 term_deselect(term);
2604 ignore_clip = FALSE;
2611 hdc = BeginPaint(hwnd, &p);
2613 SelectPalette(hdc, pal, TRUE);
2614 RealizePalette(hdc);
2618 * We have to be careful about term_paint(). It will
2619 * set a bunch of character cells to INVALID and then
2620 * call do_paint(), which will redraw those cells and
2621 * _then mark them as done_. This may not be accurate:
2622 * when painting in WM_PAINT context we are restricted
2623 * to the rectangle which has just been exposed - so if
2624 * that only covers _part_ of a character cell and the
2625 * rest of it was already visible, that remainder will
2626 * not be redrawn at all. Accordingly, we must not
2627 * paint any character cell in a WM_PAINT context which
2628 * already has a pending update due to terminal output.
2629 * The simplest solution to this - and many, many
2630 * thanks to Hung-Te Lin for working all this out - is
2631 * not to do any actual painting at _all_ if there's a
2632 * pending terminal update: just mark the relevant
2633 * character cells as INVALID and wait for the
2634 * scheduled full update to sort it out.
2636 * I have a suspicion this isn't the _right_ solution.
2637 * An alternative approach would be to have terminal.c
2638 * separately track what _should_ be on the terminal
2639 * screen and what _is_ on the terminal screen, and
2640 * have two completely different types of redraw (one
2641 * for full updates, which syncs the former with the
2642 * terminal itself, and one for WM_PAINT which syncs
2643 * the latter with the former); yet another possibility
2644 * would be to have the Windows front end do what the
2645 * GTK one already does, and maintain a bitmap of the
2646 * current terminal appearance so that WM_PAINT becomes
2647 * completely trivial. However, this should do for now.
2649 term_paint(term, hdc,
2650 (p.rcPaint.left-offset_width)/font_width,
2651 (p.rcPaint.top-offset_height)/font_height,
2652 (p.rcPaint.right-offset_width-1)/font_width,
2653 (p.rcPaint.bottom-offset_height-1)/font_height,
2654 !term->window_update_pending);
2657 p.rcPaint.left < offset_width ||
2658 p.rcPaint.top < offset_height ||
2659 p.rcPaint.right >= offset_width + font_width*term->cols ||
2660 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2662 HBRUSH fillcolour, oldbrush;
2664 fillcolour = CreateSolidBrush (
2665 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2666 oldbrush = SelectObject(hdc, fillcolour);
2667 edge = CreatePen(PS_SOLID, 0,
2668 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
2669 oldpen = SelectObject(hdc, edge);
2672 * Jordan Russell reports that this apparently
2673 * ineffectual IntersectClipRect() call masks a
2674 * Windows NT/2K bug causing strange display
2675 * problems when the PuTTY window is taller than
2676 * the primary monitor. It seems harmless enough...
2678 IntersectClipRect(hdc,
2679 p.rcPaint.left, p.rcPaint.top,
2680 p.rcPaint.right, p.rcPaint.bottom);
2682 ExcludeClipRect(hdc,
2683 offset_width, offset_height,
2684 offset_width+font_width*term->cols,
2685 offset_height+font_height*term->rows);
2687 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2688 p.rcPaint.right, p.rcPaint.bottom);
2690 /* SelectClipRgn(hdc, NULL); */
2692 SelectObject(hdc, oldbrush);
2693 DeleteObject(fillcolour);
2694 SelectObject(hdc, oldpen);
2697 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2698 SelectObject(hdc, GetStockObject(WHITE_PEN));
2706 * To protect against re-entrancy when Windows's recv()
2707 * immediately triggers a new WSAAsyncSelect window
2708 * message, we don't call select_result directly from this
2709 * handler but instead wait until we're back out at the
2710 * top level of the message loop.
2712 struct wm_netevent_params *params =
2713 snew(struct wm_netevent_params);
2714 params->wParam = wParam;
2715 params->lParam = lParam;
2716 queue_toplevel_callback(wm_netevent_callback, params);
2720 term_set_focus(term, TRUE);
2721 CreateCaret(hwnd, caretbm, font_width, font_height);
2723 flash_window(0); /* stop */
2729 term_set_focus(term, FALSE);
2731 caret_x = caret_y = -1; /* ensure caret is replaced next time */
2734 case WM_ENTERSIZEMOVE:
2735 #ifdef RDB_DEBUG_PATCH
2736 debug((27, "WM_ENTERSIZEMOVE"));
2740 need_backend_resize = FALSE;
2742 case WM_EXITSIZEMOVE:
2745 #ifdef RDB_DEBUG_PATCH
2746 debug((27, "WM_EXITSIZEMOVE"));
2748 if (need_backend_resize) {
2749 term_size(term, conf_get_int(conf, CONF_height),
2750 conf_get_int(conf, CONF_width),
2751 conf_get_int(conf, CONF_savelines));
2752 InvalidateRect(hwnd, NULL, TRUE);
2757 * This does two jobs:
2758 * 1) Keep the sizetip uptodate
2759 * 2) Make sure the window size is _stepped_ in units of the font size.
2761 resize_action = conf_get_int(conf, CONF_resize_action);
2762 if (resize_action == RESIZE_TERM ||
2763 (resize_action == RESIZE_EITHER && !is_alt_pressed())) {
2764 int width, height, w, h, ew, eh;
2765 LPRECT r = (LPRECT) lParam;
2767 if (!need_backend_resize && resize_action == RESIZE_EITHER &&
2768 (conf_get_int(conf, CONF_height) != term->rows ||
2769 conf_get_int(conf, CONF_width) != term->cols)) {
2771 * Great! It seems that both the terminal size and the
2772 * font size have been changed and the user is now dragging.
2774 * It will now be difficult to get back to the configured
2777 * This would be easier but it seems to be too confusing.
2779 conf_set_int(conf, CONF_height, term->rows);
2780 conf_set_int(conf, CONF_width, term->cols);
2782 InvalidateRect(hwnd, NULL, TRUE);
2783 need_backend_resize = TRUE;
2786 width = r->right - r->left - extra_width;
2787 height = r->bottom - r->top - extra_height;
2788 w = (width + font_width / 2) / font_width;
2791 h = (height + font_height / 2) / font_height;
2794 UpdateSizeTip(hwnd, w, h);
2795 ew = width - w * font_width;
2796 eh = height - h * font_height;
2798 if (wParam == WMSZ_LEFT ||
2799 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2805 if (wParam == WMSZ_TOP ||
2806 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2816 int width, height, w, h, rv = 0;
2817 int window_border = conf_get_int(conf, CONF_window_border);
2818 int ex_width = extra_width + (window_border - offset_width) * 2;
2819 int ex_height = extra_height + (window_border - offset_height) * 2;
2820 LPRECT r = (LPRECT) lParam;
2822 width = r->right - r->left - ex_width;
2823 height = r->bottom - r->top - ex_height;
2825 w = (width + term->cols/2)/term->cols;
2826 h = (height + term->rows/2)/term->rows;
2827 if ( r->right != r->left + w*term->cols + ex_width)
2830 if (wParam == WMSZ_LEFT ||
2831 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2832 r->left = r->right - w*term->cols - ex_width;
2834 r->right = r->left + w*term->cols + ex_width;
2836 if (r->bottom != r->top + h*term->rows + ex_height)
2839 if (wParam == WMSZ_TOP ||
2840 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2841 r->top = r->bottom - h*term->rows - ex_height;
2843 r->bottom = r->top + h*term->rows + ex_height;
2847 /* break; (never reached) */
2848 case WM_FULLSCR_ON_MAX:
2849 fullscr_on_max = TRUE;
2852 sys_cursor_update();
2855 resize_action = conf_get_int(conf, CONF_resize_action);
2856 #ifdef RDB_DEBUG_PATCH
2857 debug((27, "WM_SIZE %s (%d,%d)",
2858 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2859 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2860 (wParam == SIZE_RESTORED && resizing) ? "to":
2861 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2863 LOWORD(lParam), HIWORD(lParam)));
2865 if (wParam == SIZE_MINIMIZED)
2867 conf_get_int(conf, CONF_win_name_always) ?
2868 window_name : icon_name);
2869 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2870 SetWindowText(hwnd, window_name);
2871 if (wParam == SIZE_RESTORED) {
2872 processed_resize = FALSE;
2873 clear_full_screen();
2874 if (processed_resize) {
2876 * Inhibit normal processing of this WM_SIZE; a
2877 * secondary one was triggered just now by
2878 * clear_full_screen which contained the correct
2884 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2885 fullscr_on_max = FALSE;
2886 processed_resize = FALSE;
2888 if (processed_resize) {
2890 * Inhibit normal processing of this WM_SIZE; a
2891 * secondary one was triggered just now by
2892 * make_full_screen which contained the correct client
2899 processed_resize = TRUE;
2901 if (resize_action == RESIZE_DISABLED) {
2902 /* A resize, well it better be a minimize. */
2906 int width, height, w, h;
2907 int window_border = conf_get_int(conf, CONF_window_border);
2909 width = LOWORD(lParam);
2910 height = HIWORD(lParam);
2912 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2914 prev_rows = term->rows;
2915 prev_cols = term->cols;
2916 if (resize_action == RESIZE_TERM) {
2917 w = width / font_width;
2919 h = height / font_height;
2924 * As below, if we're in the middle of an
2925 * interactive resize we don't call
2926 * back->size. In Windows 7, this case can
2927 * arise in maximisation as well via the Aero
2930 need_backend_resize = TRUE;
2931 conf_set_int(conf, CONF_height, h);
2932 conf_set_int(conf, CONF_width, w);
2934 term_size(term, h, w,
2935 conf_get_int(conf, CONF_savelines));
2939 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2941 if (resize_action == RESIZE_TERM) {
2942 w = (width-window_border*2) / font_width;
2944 h = (height-window_border*2) / font_height;
2946 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
2948 } else if (resize_action != RESIZE_FONT)
2952 } else if (wParam == SIZE_MINIMIZED) {
2954 } else if (resize_action == RESIZE_TERM ||
2955 (resize_action == RESIZE_EITHER &&
2956 !is_alt_pressed())) {
2957 w = (width-window_border*2) / font_width;
2959 h = (height-window_border*2) / font_height;
2964 * Don't call back->size in mid-resize. (To
2965 * prevent massive numbers of resize events
2966 * getting sent down the connection during an NT
2969 need_backend_resize = TRUE;
2970 conf_set_int(conf, CONF_height, h);
2971 conf_set_int(conf, CONF_width, w);
2973 term_size(term, h, w, conf_get_int(conf, CONF_savelines));
2979 sys_cursor_update();
2982 switch (LOWORD(wParam)) {
2984 term_scroll(term, -1, 0);
2987 term_scroll(term, +1, 0);
2990 term_scroll(term, 0, +1);
2993 term_scroll(term, 0, -1);
2996 term_scroll(term, 0, +term->rows / 2);
2999 term_scroll(term, 0, -term->rows / 2);
3001 case SB_THUMBPOSITION:
3004 * Use GetScrollInfo instead of HIWORD(wParam) to get
3005 * 32-bit scroll position.
3010 si.cbSize = sizeof(si);
3011 si.fMask = SIF_TRACKPOS;
3012 if (GetScrollInfo(hwnd, SB_VERT, &si) == 0)
3013 si.nTrackPos = HIWORD(wParam);
3014 term_scroll(term, 1, si.nTrackPos);
3019 case WM_PALETTECHANGED:
3020 if ((HWND) wParam != hwnd && pal != NULL) {
3021 HDC hdc = get_ctx(NULL);
3023 if (RealizePalette(hdc) > 0)
3029 case WM_QUERYNEWPALETTE:
3031 HDC hdc = get_ctx(NULL);
3033 if (RealizePalette(hdc) > 0)
3045 * Add the scan code and keypress timing to the random
3048 noise_ultralight(lParam);
3051 * We don't do TranslateMessage since it disassociates the
3052 * resulting CHAR message from the KEYDOWN that sparked it,
3053 * which we occasionally don't want. Instead, we process
3054 * KEYDOWN, and call the Win32 translator functions so that
3055 * we get the translations under _our_ control.
3058 unsigned char buf[20];
3061 if (wParam == VK_PROCESSKEY) { /* IME PROCESS key */
3062 if (message == WM_KEYDOWN) {
3065 m.message = WM_KEYDOWN;
3067 m.lParam = lParam & 0xdfff;
3068 TranslateMessage(&m);
3069 } else break; /* pass to Windows for default processing */
3071 len = TranslateKey(message, wParam, lParam, buf);
3073 return DefWindowProc(hwnd, message, wParam, lParam);
3077 * We need not bother about stdin backlogs
3078 * here, because in GUI PuTTY we can't do
3079 * anything about it anyway; there's no means
3080 * of asking Windows to hold off on KEYDOWN
3081 * messages. We _have_ to buffer everything
3084 term_seen_key_event(term);
3086 ldisc_send(ldisc, buf, len, 1);
3092 case WM_INPUTLANGCHANGE:
3093 /* wParam == Font number */
3094 /* lParam == Locale */
3095 set_input_locale((HKL)lParam);
3096 sys_cursor_update();
3098 case WM_IME_STARTCOMPOSITION:
3100 HIMC hImc = ImmGetContext(hwnd);
3101 ImmSetCompositionFont(hImc, &lfont);
3102 ImmReleaseContext(hwnd, hImc);
3105 case WM_IME_COMPOSITION:
3111 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
3112 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
3114 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
3115 break; /* fall back to DefWindowProc */
3117 hIMC = ImmGetContext(hwnd);
3118 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
3122 buff = snewn(n, char);
3123 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
3125 * Jaeyoun Chung reports that Korean character
3126 * input doesn't work correctly if we do a single
3127 * luni_send() covering the whole of buff. So
3128 * instead we luni_send the characters one by one.
3130 term_seen_key_event(term);
3131 /* don't divide SURROGATE PAIR */
3133 for (i = 0; i < n; i += 2) {
3134 WCHAR hs = *(unsigned short *)(buff+i);
3135 if (IS_HIGH_SURROGATE(hs) && i+2 < n) {
3136 WCHAR ls = *(unsigned short *)(buff+i+2);
3137 if (IS_LOW_SURROGATE(ls)) {
3138 luni_send(ldisc, (unsigned short *)(buff+i), 2, 1);
3143 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
3148 ImmReleaseContext(hwnd, hIMC);
3153 if (wParam & 0xFF00) {
3154 unsigned char buf[2];
3157 buf[0] = wParam >> 8;
3158 term_seen_key_event(term);
3160 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
3162 char c = (unsigned char) wParam;
3163 term_seen_key_event(term);
3165 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
3171 * Nevertheless, we are prepared to deal with WM_CHAR
3172 * messages, should they crop up. So if someone wants to
3173 * post the things to us as part of a macro manoeuvre,
3174 * we're ready to cope.
3177 char c = (unsigned char)wParam;
3178 term_seen_key_event(term);
3180 lpage_send(ldisc, CP_ACP, &c, 1, 1);
3183 case WM_SYSCOLORCHANGE:
3184 if (conf_get_int(conf, CONF_system_colour)) {
3185 /* Refresh palette from system colours. */
3186 /* XXX actually this zaps the entire palette. */
3189 /* Force a repaint of the terminal window. */
3190 term_invalidate(term);
3193 case WM_AGENT_CALLBACK:
3195 struct agent_callback *c = (struct agent_callback *)lParam;
3196 c->callback(c->callback_ctx, c->data, c->len);
3200 case WM_GOT_CLIPDATA:
3201 if (process_clipdata((HGLOBAL)lParam, wParam))
3202 term_do_paste(term);
3205 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
3206 int shift_pressed=0, control_pressed=0;
3208 if (message == WM_MOUSEWHEEL) {
3209 wheel_accumulator += (short)HIWORD(wParam);
3210 shift_pressed=LOWORD(wParam) & MK_SHIFT;
3211 control_pressed=LOWORD(wParam) & MK_CONTROL;
3214 wheel_accumulator += (int)wParam;
3215 if (GetKeyboardState(keys)!=0) {
3216 shift_pressed=keys[VK_SHIFT]&0x80;
3217 control_pressed=keys[VK_CONTROL]&0x80;
3221 /* process events when the threshold is reached */
3222 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
3225 /* reduce amount for next time */
3226 if (wheel_accumulator > 0) {
3228 wheel_accumulator -= WHEEL_DELTA;
3229 } else if (wheel_accumulator < 0) {
3231 wheel_accumulator += WHEEL_DELTA;
3235 if (send_raw_mouse &&
3236 !(conf_get_int(conf, CONF_mouse_override) &&
3238 /* Mouse wheel position is in screen coordinates for
3241 p.x = X_POS(lParam); p.y = Y_POS(lParam);
3242 if (ScreenToClient(hwnd, &p)) {
3243 /* send a mouse-down followed by a mouse up */
3244 term_mouse(term, b, translate_button(b),
3247 TO_CHR_Y(p.y), shift_pressed,
3248 control_pressed, is_alt_pressed());
3249 term_mouse(term, b, translate_button(b),
3250 MA_RELEASE, TO_CHR_X(p.x),
3251 TO_CHR_Y(p.y), shift_pressed,
3252 control_pressed, is_alt_pressed());
3253 } /* else: not sure when this can fail */
3255 /* trigger a scroll */
3256 term_scroll(term, 0,
3258 -term->rows / 2 : term->rows / 2);
3266 * Any messages we don't process completely above are passed through to
3267 * DefWindowProc() for default processing.
3269 return DefWindowProc(hwnd, message, wParam, lParam);
3273 * Move the system caret. (We maintain one, even though it's
3274 * invisible, for the benefit of blind people: apparently some
3275 * helper software tracks the system caret, so we should arrange to
3278 void sys_cursor(void *frontend, int x, int y)
3282 if (!term->has_focus) return;
3285 * Avoid gratuitously re-updating the cursor position and IMM
3286 * window if there's no actual change required.
3288 cx = x * font_width + offset_width;
3289 cy = y * font_height + offset_height;
3290 if (cx == caret_x && cy == caret_y)
3295 sys_cursor_update();
3298 static void sys_cursor_update(void)
3303 if (!term->has_focus) return;
3305 if (caret_x < 0 || caret_y < 0)
3308 SetCaretPos(caret_x, caret_y);
3310 /* IMM calls on Win98 and beyond only */
3311 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3313 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3314 osVersion.dwMinorVersion == 0) return; /* 95 */
3316 /* we should have the IMM functions */
3317 hIMC = ImmGetContext(hwnd);
3318 cf.dwStyle = CFS_POINT;
3319 cf.ptCurrentPos.x = caret_x;
3320 cf.ptCurrentPos.y = caret_y;
3321 ImmSetCompositionWindow(hIMC, &cf);
3323 ImmReleaseContext(hwnd, hIMC);
3327 * Draw a line of text in the window, at given character
3328 * coordinates, in given attributes.
3330 * We are allowed to fiddle with the contents of `text'.
3332 void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3333 unsigned long attr, int lattr)
3336 int nfg, nbg, nfont;
3339 int force_manual_underline = 0;
3340 int fnt_width, char_width;
3341 int text_adjust = 0;
3343 int maxlen, remaining, opaque;
3344 int is_cursor = FALSE;
3345 static int *lpDx = NULL;
3346 static int lpDx_len = 0;
3348 int len2; /* for SURROGATE PAIR */
3350 lattr &= LATTR_MODE;
3352 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3354 if (attr & ATTR_WIDE)
3357 /* Only want the left half of double width lines */
3358 if (lattr != LATTR_NORM && x*2 >= term->cols)
3366 if ((attr & TATTR_ACTCURS) && (cursor_type == 0 || term->big_cursor)) {
3367 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3368 /* cursor fg and bg */
3369 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
3374 if (vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3375 /* Assume a poorman font is borken in other ways too. */
3385 nfont |= FONT_WIDE + FONT_HIGH;
3388 if (attr & ATTR_NARROW)
3389 nfont |= FONT_NARROW;
3391 #ifdef USES_VTLINE_HACK
3392 /* Special hack for the VT100 linedraw glyphs. */
3393 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3394 switch ((unsigned char) (text[0])) {
3396 text_adjust = -2 * font_height / 5;
3399 text_adjust = -1 * font_height / 5;
3402 text_adjust = font_height / 5;
3405 text_adjust = 2 * font_height / 5;
3408 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3410 text[0] = ucsdata.unitab_xterm['q'];
3411 if (attr & ATTR_UNDER) {
3412 attr &= ~ATTR_UNDER;
3413 force_manual_underline = 1;
3418 /* Anything left as an original character set is unprintable. */
3419 if (DIRECT_CHAR(text[0]) &&
3420 (len < 2 || !IS_SURROGATE_PAIR(text[0], text[1]))) {
3422 for (i = 0; i < len; i++)
3427 if ((text[0] & CSET_MASK) == CSET_OEMCP)
3430 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3431 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3432 if (bold_font_mode == BOLD_FONT && (attr & ATTR_BOLD))
3434 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3435 nfont |= FONT_UNDERLINE;
3436 another_font(nfont);
3437 if (!fonts[nfont]) {
3438 if (nfont & FONT_UNDERLINE)
3439 force_manual_underline = 1;
3440 /* Don't do the same for manual bold, it could be bad news. */
3442 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3444 another_font(nfont);
3446 nfont = FONT_NORMAL;
3447 if (attr & ATTR_REVERSE) {
3452 if (bold_colours && (attr & ATTR_BOLD) && !is_cursor) {
3453 if (nfg < 16) nfg |= 8;
3454 else if (nfg >= 256) nfg |= 1;
3456 if (bold_colours && (attr & ATTR_BLINK)) {
3457 if (nbg < 16) nbg |= 8;
3458 else if (nbg >= 256) nbg |= 1;
3462 SelectObject(hdc, fonts[nfont]);
3463 SetTextColor(hdc, fg);
3464 SetBkColor(hdc, bg);
3465 if (attr & TATTR_COMBINING)
3466 SetBkMode(hdc, TRANSPARENT);
3468 SetBkMode(hdc, OPAQUE);
3471 line_box.right = x + char_width * len;
3472 line_box.bottom = y + font_height;
3473 /* adjust line_box.right for SURROGATE PAIR & VARIATION SELECTOR */
3477 for (i = 0; i < len ; i++) {
3478 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3480 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i], text[i+1])) {
3481 rc_width += char_width;
3483 } else if (IS_LOW_VARSEL(text[i])) {
3486 rc_width += char_width;
3489 line_box.right = line_box.left + rc_width;
3492 /* Only want the left half of double width lines */
3493 if (line_box.right > font_width*term->cols+offset_width)
3494 line_box.right = font_width*term->cols+offset_width;
3496 if (font_varpitch) {
3498 * If we're using a variable-pitch font, we unconditionally
3499 * draw the glyphs one at a time and centre them in their
3500 * character cells (which means in particular that we must
3501 * disable the lpDx mechanism). This gives slightly odd but
3502 * generally reasonable results.
3504 xoffset = char_width / 2;
3505 SetTextAlign(hdc, TA_TOP | TA_CENTER | TA_NOUPDATECP);
3510 * In a fixed-pitch font, we draw the whole string in one go
3511 * in the normal way.
3514 SetTextAlign(hdc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
3519 opaque = TRUE; /* start by erasing the rectangle */
3520 for (remaining = len; remaining > 0;
3521 text += len, remaining -= len, x += char_width * len2) {
3522 len = (maxlen < remaining ? maxlen : remaining);
3523 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3526 if (remaining >= 1 && IS_SURROGATE_PAIR(text[0], text[1]))
3528 if (remaining-len >= 1 && IS_LOW_VARSEL(text[len]))
3530 else if (remaining-len >= 2 &&
3531 IS_HIGH_VARSEL(text[len], text[len+1]))
3535 if (len > lpDx_len) {
3536 lpDx_len = len * 9 / 8 + 16;
3537 lpDx = sresize(lpDx, lpDx_len, int);
3539 if (lpDx_maybe) lpDx_maybe = lpDx;
3544 /* only last char has dx width in SURROGATE PAIR and
3545 * VARIATION sequence */
3546 for (i = 0; i < len; i++) {
3547 lpDx[i] = char_width;
3548 if (i+1 < len && IS_HIGH_VARSEL(text[i], text[i+1])) {
3549 if (i > 0) lpDx[i-1] = 0;
3552 lpDx[i] = char_width;
3553 } else if (i+1 < len && IS_SURROGATE_PAIR(text[i],text[i+1])) {
3556 lpDx[i] = char_width;
3557 } else if (IS_LOW_VARSEL(text[i])) {
3558 if (i > 0) lpDx[i-1] = 0;
3559 lpDx[i] = char_width;
3564 /* We're using a private area for direct to font. (512 chars.) */
3565 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
3566 /* Ho Hum, dbcs fonts are a PITA! */
3567 /* To display on W9x I have to convert to UCS */
3568 static wchar_t *uni_buf = 0;
3569 static int uni_len = 0;
3571 if (len > uni_len) {
3574 uni_buf = snewn(uni_len, wchar_t);
3577 for(nlen = mptr = 0; mptr<len; mptr++) {
3578 uni_buf[nlen] = 0xFFFD;
3579 if (IsDBCSLeadByteEx(ucsdata.font_codepage,
3580 (BYTE) text[mptr])) {
3582 dbcstext[0] = text[mptr] & 0xFF;
3583 dbcstext[1] = text[mptr+1] & 0xFF;
3584 lpDx[nlen] += char_width;
3585 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3586 dbcstext, 2, uni_buf+nlen, 1);
3592 dbcstext[0] = text[mptr] & 0xFF;
3593 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3594 dbcstext, 1, uni_buf+nlen, 1);
3601 ExtTextOutW(hdc, x + xoffset,
3602 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3603 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3604 &line_box, uni_buf, nlen,
3606 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3607 SetBkMode(hdc, TRANSPARENT);
3608 ExtTextOutW(hdc, x + xoffset - 1,
3609 y - font_height * (lattr ==
3610 LATTR_BOT) + text_adjust,
3611 ETO_CLIPPED, &line_box, uni_buf, nlen, lpDx_maybe);
3615 } else if (DIRECT_FONT(text[0])) {
3616 static char *directbuf = NULL;
3617 static int directlen = 0;
3619 if (len > directlen) {
3621 directbuf = sresize(directbuf, directlen, char);
3624 for (i = 0; i < len; i++)
3625 directbuf[i] = text[i] & 0xFF;
3627 ExtTextOut(hdc, x + xoffset,
3628 y - font_height * (lattr == LATTR_BOT) + text_adjust,
3629 ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
3630 &line_box, directbuf, len, lpDx_maybe);
3631 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3632 SetBkMode(hdc, TRANSPARENT);
3634 /* GRR: This draws the character outside its box and
3635 * can leave 'droppings' even with the clip box! I
3636 * suppose I could loop it one character at a time ...
3639 * Or ... I could do a test print with "W", and use +1
3640 * or -1 for this shift depending on if the leftmost
3641 * column is blank...
3643 ExtTextOut(hdc, x + xoffset - 1,
3644 y - font_height * (lattr ==
3645 LATTR_BOT) + text_adjust,
3646 ETO_CLIPPED, &line_box, directbuf, len, lpDx_maybe);
3649 /* And 'normal' unicode characters */
3650 static WCHAR *wbuf = NULL;
3651 static int wlen = 0;
3657 wbuf = snewn(wlen, WCHAR);
3660 for (i = 0; i < len; i++)
3663 /* print Glyphs as they are, without Windows' Shaping*/
3664 general_textout(hdc, x + xoffset,
3665 y - font_height * (lattr==LATTR_BOT) + text_adjust,
3666 &line_box, wbuf, len, lpDx,
3667 opaque && !(attr & TATTR_COMBINING));
3669 /* And the shadow bold hack. */
3670 if (bold_font_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3671 SetBkMode(hdc, TRANSPARENT);
3672 ExtTextOutW(hdc, x + xoffset - 1,
3673 y - font_height * (lattr ==
3674 LATTR_BOT) + text_adjust,
3675 ETO_CLIPPED, &line_box, wbuf, len, lpDx_maybe);
3680 * If we're looping round again, stop erasing the background
3683 SetBkMode(hdc, TRANSPARENT);
3686 if (lattr != LATTR_TOP && (force_manual_underline ||
3687 (und_mode == UND_LINE
3688 && (attr & ATTR_UNDER)))) {
3691 if (lattr == LATTR_BOT)
3692 dec = dec * 2 - font_height;
3694 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3695 MoveToEx(hdc, line_box.left, line_box.top + dec, NULL);
3696 LineTo(hdc, line_box.right, line_box.top + dec);
3697 oldpen = SelectObject(hdc, oldpen);
3698 DeleteObject(oldpen);
3703 * Wrapper that handles combining characters.
3705 void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3706 unsigned long attr, int lattr)
3708 if (attr & TATTR_COMBINING) {
3709 unsigned long a = 0;
3711 /* don't divide SURROGATE PAIR and VARIATION SELECTOR */
3712 if (len >= 2 && IS_SURROGATE_PAIR(text[0], text[1]))
3714 if (len-len0 >= 1 && IS_LOW_VARSEL(text[len0])) {
3715 attr &= ~TATTR_COMBINING;
3716 do_text_internal(ctx, x, y, text, len0+1, attr, lattr);
3719 a = TATTR_COMBINING;
3720 } else if (len-len0 >= 2 && IS_HIGH_VARSEL(text[len0], text[len0+1])) {
3721 attr &= ~TATTR_COMBINING;
3722 do_text_internal(ctx, x, y, text, len0+2, attr, lattr);
3725 a = TATTR_COMBINING;
3727 attr &= ~TATTR_COMBINING;
3731 if (len >= 1 && IS_SURROGATE_PAIR(text[0], text[1])) {
3732 do_text_internal(ctx, x, y, text, 2, attr | a, lattr);
3736 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3740 a = TATTR_COMBINING;
3743 do_text_internal(ctx, x, y, text, len, attr, lattr);
3746 void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
3747 unsigned long attr, int lattr)
3753 int ctype = cursor_type;
3755 lattr &= LATTR_MODE;
3757 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3758 if (*text != UCSWIDE) {
3759 do_text(ctx, x, y, text, len, attr, lattr);
3763 attr |= TATTR_RIGHTCURS;
3766 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3767 if (attr & ATTR_WIDE)
3774 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3777 pts[0].x = pts[1].x = pts[4].x = x;
3778 pts[2].x = pts[3].x = x + char_width - 1;
3779 pts[0].y = pts[3].y = pts[4].y = y;
3780 pts[1].y = pts[2].y = y + font_height - 1;
3781 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3782 Polyline(hdc, pts, 5);
3783 oldpen = SelectObject(hdc, oldpen);
3784 DeleteObject(oldpen);
3785 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3786 int startx, starty, dx, dy, length, i;
3789 starty = y + descent;
3792 length = char_width;
3795 if (attr & TATTR_RIGHTCURS)
3796 xadjust = char_width - 1;
3797 startx = x + xadjust;
3801 length = font_height;
3803 if (attr & TATTR_ACTCURS) {
3806 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
3807 MoveToEx(hdc, startx, starty, NULL);
3808 LineTo(hdc, startx + dx * length, starty + dy * length);
3809 oldpen = SelectObject(hdc, oldpen);
3810 DeleteObject(oldpen);
3812 for (i = 0; i < length; i++) {
3814 SetPixel(hdc, startx, starty, colours[261]);
3823 /* This function gets the actual width of a character in the normal font.
3825 int char_width(Context ctx, int uc) {
3829 /* If the font max is the same as the font ave width then this
3830 * function is a no-op.
3832 if (!font_dualwidth) return 1;
3834 switch (uc & CSET_MASK) {
3836 uc = ucsdata.unitab_line[uc & 0xFF];
3839 uc = ucsdata.unitab_xterm[uc & 0xFF];
3842 uc = ucsdata.unitab_scoacs[uc & 0xFF];
3845 if (DIRECT_FONT(uc)) {
3846 if (ucsdata.dbcs_screenfont) return 1;
3848 /* Speedup, I know of no font where ascii is the wrong width */
3849 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
3852 if ( (uc & CSET_MASK) == CSET_ACP ) {
3853 SelectObject(hdc, fonts[FONT_NORMAL]);
3854 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
3855 another_font(FONT_OEM);
3856 if (!fonts[FONT_OEM]) return 0;
3858 SelectObject(hdc, fonts[FONT_OEM]);
3862 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3863 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
3866 /* Speedup, I know of no font where ascii is the wrong width */
3867 if (uc >= ' ' && uc <= '~') return 1;
3869 SelectObject(hdc, fonts[FONT_NORMAL]);
3870 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3871 /* Okay that one worked */ ;
3872 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3873 /* This should work on 9x too, but it's "less accurate" */ ;
3878 ibuf += font_width / 2 -1;
3884 DECL_WINDOWS_FUNCTION(static, BOOL, FlashWindowEx, (PFLASHWINFO));
3885 DECL_WINDOWS_FUNCTION(static, BOOL, ToUnicodeEx,
3886 (UINT, UINT, const BYTE *, LPWSTR, int, UINT, HKL));
3888 static void init_winfuncs(void)
3890 HMODULE user32_module = load_system32_dll("user32.dll");
3891 GET_WINDOWS_FUNCTION(user32_module, FlashWindowEx);
3892 GET_WINDOWS_FUNCTION(user32_module, ToUnicodeEx);
3896 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3897 * codes. Returns number of bytes used, zero to drop the message,
3898 * -1 to forward the message to Windows, or another negative number
3899 * to indicate a NUL-terminated "special" string.
3901 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3902 unsigned char *output)
3905 int scan, left_alt = 0, key_down, shift_state;
3907 unsigned char *p = output;
3908 static int alt_sum = 0;
3909 int funky_type = conf_get_int(conf, CONF_funky_type);
3910 int no_applic_k = conf_get_int(conf, CONF_no_applic_k);
3911 int ctrlaltkeys = conf_get_int(conf, CONF_ctrlaltkeys);
3912 int nethack_keypad = conf_get_int(conf, CONF_nethack_keypad);
3914 HKL kbd_layout = GetKeyboardLayout(0);
3916 static wchar_t keys_unicode[3];
3917 static int compose_char = 0;
3918 static WPARAM compose_keycode = 0;
3920 r = GetKeyboardState(keystate);
3922 memset(keystate, 0, sizeof(keystate));
3925 #define SHOW_TOASCII_RESULT
3926 { /* Tell us all about key events */
3927 static BYTE oldstate[256];
3928 static int first = 1;
3932 memcpy(oldstate, keystate, sizeof(oldstate));
3935 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3937 } else if ((HIWORD(lParam) & KF_UP)
3938 && scan == (HIWORD(lParam) & 0xFF)) {
3942 if (wParam >= VK_F1 && wParam <= VK_F20)
3943 debug(("K_F%d", wParam + 1 - VK_F1));
3956 debug(("VK_%02x", wParam));
3958 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3960 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3962 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3963 if (ch >= ' ' && ch <= '~')
3964 debug((", '%c'", ch));
3966 debug((", $%02x", ch));
3968 if (keys_unicode[0])
3969 debug((", KB0=%04x", keys_unicode[0]));
3970 if (keys_unicode[1])
3971 debug((", KB1=%04x", keys_unicode[1]));
3972 if (keys_unicode[2])
3973 debug((", KB2=%04x", keys_unicode[2]));
3975 if ((keystate[VK_SHIFT] & 0x80) != 0)
3977 if ((keystate[VK_CONTROL] & 0x80) != 0)
3979 if ((HIWORD(lParam) & KF_EXTENDED))
3981 if ((HIWORD(lParam) & KF_UP))
3985 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3986 else if ((HIWORD(lParam) & KF_UP))
3987 oldstate[wParam & 0xFF] ^= 0x80;
3989 oldstate[wParam & 0xFF] ^= 0x81;
3991 for (ch = 0; ch < 256; ch++)
3992 if (oldstate[ch] != keystate[ch])
3993 debug((", M%02x=%02x", ch, keystate[ch]));
3995 memcpy(oldstate, keystate, sizeof(oldstate));
3999 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
4000 keystate[VK_RMENU] = keystate[VK_MENU];
4004 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
4005 if ((funky_type == FUNKY_VT400 ||
4006 (funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
4008 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
4010 wParam = VK_EXECUTE;
4012 /* UnToggle NUMLock */
4013 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
4014 keystate[VK_NUMLOCK] ^= 1;
4017 /* And write back the 'adjusted' state */
4018 SetKeyboardState(keystate);
4021 /* Disable Auto repeat if required */
4022 if (term->repeat_off &&
4023 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
4026 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
4029 key_down = ((HIWORD(lParam) & KF_UP) == 0);
4031 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
4032 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
4034 keystate[VK_MENU] = 0;
4036 keystate[VK_RMENU] = 0x80;
4041 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
4042 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
4043 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
4045 /* Note if AltGr was pressed and if it was used as a compose key */
4046 if (!compose_state) {
4047 compose_keycode = 0x100;
4048 if (conf_get_int(conf, CONF_compose_key)) {
4049 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
4050 compose_keycode = wParam;
4052 if (wParam == VK_APPS)
4053 compose_keycode = wParam;
4056 if (wParam == compose_keycode) {
4057 if (compose_state == 0
4058 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
4060 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
4064 } else if (compose_state == 1 && wParam != VK_CONTROL)
4067 if (compose_state > 1 && left_alt)
4070 /* Sanitize the number pad if not using a PC NumPad */
4071 if (left_alt || (term->app_keypad_keys && !no_applic_k
4072 && funky_type != FUNKY_XTERM)
4073 || funky_type == FUNKY_VT400 || nethack_keypad || compose_state) {
4074 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
4078 nParam = VK_NUMPAD0;
4081 nParam = VK_NUMPAD1;
4084 nParam = VK_NUMPAD2;
4087 nParam = VK_NUMPAD3;
4090 nParam = VK_NUMPAD4;
4093 nParam = VK_NUMPAD5;
4096 nParam = VK_NUMPAD6;
4099 nParam = VK_NUMPAD7;
4102 nParam = VK_NUMPAD8;
4105 nParam = VK_NUMPAD9;
4108 nParam = VK_DECIMAL;
4112 if (keystate[VK_NUMLOCK] & 1)
4119 /* If a key is pressed and AltGr is not active */
4120 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
4121 /* Okay, prepare for most alts then ... */
4125 /* Lets see if it's a pattern we know all about ... */
4126 if (wParam == VK_PRIOR && shift_state == 1) {
4127 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
4130 if (wParam == VK_PRIOR && shift_state == 2) {
4131 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
4134 if (wParam == VK_NEXT && shift_state == 1) {
4135 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
4138 if (wParam == VK_NEXT && shift_state == 2) {
4139 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
4142 if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) {
4143 term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1));
4146 if (wParam == VK_INSERT && shift_state == 1) {
4147 request_paste(NULL);
4150 if (left_alt && wParam == VK_F4 && conf_get_int(conf, CONF_alt_f4)) {
4153 if (left_alt && wParam == VK_SPACE && conf_get_int(conf,
4155 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
4158 if (left_alt && wParam == VK_RETURN &&
4159 conf_get_int(conf, CONF_fullscreenonaltenter) &&
4160 (conf_get_int(conf, CONF_resize_action) != RESIZE_DISABLED)) {
4161 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
4165 /* Control-Numlock for app-keypad mode switch */
4166 if (wParam == VK_PAUSE && shift_state == 2) {
4167 term->app_keypad_keys ^= 1;
4171 /* Nethack keypad */
4172 if (nethack_keypad && !left_alt) {
4175 *p++ = "bB\002\002"[shift_state & 3];
4178 *p++ = "jJ\012\012"[shift_state & 3];
4181 *p++ = "nN\016\016"[shift_state & 3];
4184 *p++ = "hH\010\010"[shift_state & 3];
4187 *p++ = shift_state ? '.' : '.';
4190 *p++ = "lL\014\014"[shift_state & 3];
4193 *p++ = "yY\031\031"[shift_state & 3];
4196 *p++ = "kK\013\013"[shift_state & 3];
4199 *p++ = "uU\025\025"[shift_state & 3];
4204 /* Application Keypad */
4208 if (funky_type == FUNKY_VT400 ||
4209 (funky_type <= FUNKY_LINUX &&
4210 term->app_keypad_keys && !no_applic_k)) switch (wParam) {
4224 if (term->app_keypad_keys && !no_applic_k)
4261 if (funky_type == FUNKY_XTERM) {
4266 } else if (shift_state)
4273 if (funky_type == FUNKY_XTERM)
4277 if (funky_type == FUNKY_XTERM)
4281 if (funky_type == FUNKY_XTERM)
4286 if (HIWORD(lParam) & KF_EXTENDED)
4291 if (term->vt52_mode) {
4292 if (xkey >= 'P' && xkey <= 'S')
4293 p += sprintf((char *) p, "\x1B%c", xkey);
4295 p += sprintf((char *) p, "\x1B?%c", xkey);
4297 p += sprintf((char *) p, "\x1BO%c", xkey);
4302 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
4303 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x7F : 0x08);
4307 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
4308 /* We do the opposite of what is configured */
4309 *p++ = (conf_get_int(conf, CONF_bksp_is_delete) ? 0x08 : 0x7F);
4313 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
4319 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
4323 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
4327 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
4329 back->special(backhandle, TS_BRK);
4332 if (wParam == VK_PAUSE) { /* Break/Pause */
4337 /* Control-2 to Control-8 are special */
4338 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
4339 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
4342 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
4346 if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) {
4350 if (shift_state == 3 && wParam == 0xDE) {
4351 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
4354 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
4361 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
4362 * for integer decimal nn.)
4364 * We also deal with the weird ones here. Linux VCs replace F1
4365 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
4366 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
4372 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
4375 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
4378 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
4381 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
4384 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
4387 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
4390 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
4393 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
4396 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
4399 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
4432 if ((shift_state&2) == 0) switch (wParam) {
4452 /* Reorder edit keys to physical order */
4453 if (funky_type == FUNKY_VT400 && code <= 6)
4454 code = "\0\2\1\4\5\3\6"[code];
4456 if (term->vt52_mode && code > 0 && code <= 6) {
4457 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
4461 if (funky_type == FUNKY_SCO && code >= 11 && code <= 34) {
4462 /* SCO function keys */
4463 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4466 case VK_F1: index = 0; break;
4467 case VK_F2: index = 1; break;
4468 case VK_F3: index = 2; break;
4469 case VK_F4: index = 3; break;
4470 case VK_F5: index = 4; break;
4471 case VK_F6: index = 5; break;
4472 case VK_F7: index = 6; break;
4473 case VK_F8: index = 7; break;
4474 case VK_F9: index = 8; break;
4475 case VK_F10: index = 9; break;
4476 case VK_F11: index = 10; break;
4477 case VK_F12: index = 11; break;
4479 if (keystate[VK_SHIFT] & 0x80) index += 12;
4480 if (keystate[VK_CONTROL] & 0x80) index += 24;
4481 p += sprintf((char *) p, "\x1B[%c", codes[index]);
4484 if (funky_type == FUNKY_SCO && /* SCO small keypad */
4485 code >= 1 && code <= 6) {
4486 char codes[] = "HL.FIG";
4490 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4494 if ((term->vt52_mode || funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
4500 if (term->vt52_mode)
4501 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
4504 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
4507 if (funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
4508 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
4511 if (funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
4512 if (term->vt52_mode)
4513 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
4515 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
4518 if ((code == 1 || code == 4) &&
4519 conf_get_int(conf, CONF_rxvt_homeend)) {
4520 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
4524 p += sprintf((char *) p, "\x1B[%d~", code);
4529 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4530 * some reason seems to send VK_CLEAR to Windows...).
4552 p += format_arrow_key(p, term, xkey, shift_state);
4558 * Finally, deal with Return ourselves. (Win95 seems to
4559 * foul it up when Alt is pressed, for some reason.)
4561 if (wParam == VK_RETURN) { /* Return */
4567 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4568 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4573 /* Okay we've done everything interesting; let windows deal with
4574 * the boring stuff */
4578 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4579 if(keystate[VK_CAPITAL] != 0 &&
4580 conf_get_int(conf, CONF_xlat_capslockcyr)) {
4582 keystate[VK_CAPITAL] = 0;
4585 /* XXX how do we know what the max size of the keys array should
4586 * be is? There's indication on MS' website of an Inquire/InquireEx
4587 * functioning returning a KBINFO structure which tells us. */
4588 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT && p_ToUnicodeEx) {
4589 r = p_ToUnicodeEx(wParam, scan, keystate, keys_unicode,
4590 lenof(keys_unicode), 0, kbd_layout);
4592 /* XXX 'keys' parameter is declared in MSDN documentation as
4594 * The experience of a French user indicates that on
4595 * Win98, WORD[] should be passed in, but on Win2K, it should
4596 * be BYTE[]. German WinXP and my Win2K with "US International"
4597 * driver corroborate this.
4598 * Experimentally I've conditionalised the behaviour on the
4599 * Win9x/NT split, but I suspect it's worse than that.
4600 * See wishlist item `win-dead-keys' for more horrible detail
4601 * and speculations. */
4603 static WORD keys[3];
4604 static BYTE keysb[3];
4605 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4607 for (i = 0; i < r; i++) {
4608 keysb[i] = (BYTE)keys[i];
4610 MultiByteToWideChar(CP_ACP, 0, (LPCSTR)keysb, r,
4611 keys_unicode, lenof(keys_unicode));
4614 #ifdef SHOW_TOASCII_RESULT
4615 if (r == 1 && !key_down) {
4617 if (in_utf(term) || ucsdata.dbcs_screenfont)
4618 debug((", (U+%04x)", alt_sum));
4620 debug((", LCH(%d)", alt_sum));
4622 debug((", ACH(%d)", keys_unicode[0]));
4627 for (r1 = 0; r1 < r; r1++) {
4628 debug(("%s%d", r1 ? "," : "", keys_unicode[r1]));
4637 for (i = 0; i < r; i++) {
4638 wchar_t wch = keys_unicode[i];
4640 if (compose_state == 2 && wch >= ' ' && wch < 0x80) {
4645 if (compose_state == 3 && wch >= ' ' && wch < 0x80) {
4649 if ((nc = check_compose(compose_char, wch)) == -1) {
4650 MessageBeep(MB_ICONHAND);
4654 term_seen_key_event(term);
4656 luni_send(ldisc, &keybuf, 1, 1);
4664 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4666 term_seen_key_event(term);
4668 luni_send(ldisc, &keybuf, 1, 1);
4670 char ch = (char) alt_sum;
4672 * We need not bother about stdin
4673 * backlogs here, because in GUI PuTTY
4674 * we can't do anything about it
4675 * anyway; there's no means of asking
4676 * Windows to hold off on KEYDOWN
4677 * messages. We _have_ to buffer
4678 * everything we're sent.
4680 term_seen_key_event(term);
4682 ldisc_send(ldisc, &ch, 1, 1);
4686 term_seen_key_event(term);
4688 luni_send(ldisc, &wch, 1, 1);
4691 if(capsOn && wch < 0x80) {
4694 cbuf[1] = xlat_uskbd2cyrllic(wch);
4695 term_seen_key_event(term);
4697 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4702 term_seen_key_event(term);
4704 luni_send(ldisc, cbuf +!left_alt, 1+!!left_alt, 1);
4710 /* This is so the ALT-Numpad and dead keys work correctly. */
4711 keys_unicode[0] = 0;
4715 /* If we're definitly not building up an ALT-54321 then clear it */
4717 keys_unicode[0] = 0;
4718 /* If we will be using alt_sum fix the 256s */
4719 else if (keys_unicode[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4720 keys_unicode[0] = 10;
4724 * ALT alone may or may not want to bring up the System menu.
4725 * If it's not meant to, we return 0 on presses or releases of
4726 * ALT, to show that we've swallowed the keystroke. Otherwise
4727 * we return -1, which means Windows will give the keystroke
4728 * its default handling (i.e. bring up the System menu).
4730 if (wParam == VK_MENU && !conf_get_int(conf, CONF_alt_only))
4736 void set_title(void *frontend, char *title)
4739 window_name = snewn(1 + strlen(title), char);
4740 strcpy(window_name, title);
4741 if (conf_get_int(conf, CONF_win_name_always) || !IsIconic(hwnd))
4742 SetWindowText(hwnd, title);
4745 void set_icon(void *frontend, char *title)
4748 icon_name = snewn(1 + strlen(title), char);
4749 strcpy(icon_name, title);
4750 if (!conf_get_int(conf, CONF_win_name_always) && IsIconic(hwnd))
4751 SetWindowText(hwnd, title);
4754 void set_sbar(void *frontend, int total, int start, int page)
4758 if (!conf_get_int(conf, is_full_screen() ?
4759 CONF_scrollbar_in_fullscreen : CONF_scrollbar))
4762 si.cbSize = sizeof(si);
4763 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4765 si.nMax = total - 1;
4769 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4772 Context get_ctx(void *frontend)
4778 SelectPalette(hdc, pal, FALSE);
4784 void free_ctx(Context ctx)
4786 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4787 ReleaseDC(hwnd, ctx);
4790 static void real_palette_set(int n, int r, int g, int b)
4793 logpal->palPalEntry[n].peRed = r;
4794 logpal->palPalEntry[n].peGreen = g;
4795 logpal->palPalEntry[n].peBlue = b;
4796 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4797 colours[n] = PALETTERGB(r, g, b);
4798 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4800 colours[n] = RGB(r, g, b);
4803 void palette_set(void *frontend, int n, int r, int g, int b)
4807 if (n >= NALLCOLOURS)
4809 real_palette_set(n, r, g, b);
4811 HDC hdc = get_ctx(frontend);
4812 UnrealizeObject(pal);
4813 RealizePalette(hdc);
4816 if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))
4817 /* If Default Background changes, we need to ensure any
4818 * space between the text area and the window border is
4820 InvalidateRect(hwnd, NULL, TRUE);
4824 void palette_reset(void *frontend)
4829 for (i = 0; i < NALLCOLOURS; i++) {
4831 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4832 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4833 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4834 logpal->palPalEntry[i].peFlags = 0;
4835 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4836 defpal[i].rgbtGreen,
4837 defpal[i].rgbtBlue);
4839 colours[i] = RGB(defpal[i].rgbtRed,
4840 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4845 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
4846 hdc = get_ctx(frontend);
4847 RealizePalette(hdc);
4850 /* Default Background may have changed. Ensure any space between
4851 * text area and window border is redrawn. */
4852 InvalidateRect(hwnd, NULL, TRUE);
4856 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4861 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4864 lock = GlobalLock(clipdata);
4867 memcpy(lock, data, len);
4868 ((unsigned char *) lock)[len] = 0;
4869 GlobalUnlock(clipdata);
4872 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4874 if (OpenClipboard(hwnd)) {
4876 SetClipboardData(CF_TEXT, clipdata);
4879 GlobalFree(clipdata);
4882 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4886 * Note: unlike write_aclip() this will not append a nul.
4888 void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
4890 HGLOBAL clipdata, clipdata2, clipdata3;
4892 void *lock, *lock2, *lock3;
4894 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4896 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4897 len * sizeof(wchar_t));
4898 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4900 if (!clipdata || !clipdata2) {
4902 GlobalFree(clipdata);
4904 GlobalFree(clipdata2);
4907 if (!(lock = GlobalLock(clipdata))) {
4908 GlobalFree(clipdata);
4909 GlobalFree(clipdata2);
4912 if (!(lock2 = GlobalLock(clipdata2))) {
4913 GlobalUnlock(clipdata);
4914 GlobalFree(clipdata);
4915 GlobalFree(clipdata2);
4919 memcpy(lock, data, len * sizeof(wchar_t));
4920 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4922 if (conf_get_int(conf, CONF_rtf_paste)) {
4923 wchar_t unitab[256];
4925 unsigned char *tdata = (unsigned char *)lock2;
4926 wchar_t *udata = (wchar_t *)lock;
4927 int rtflen = 0, uindex = 0, tindex = 0;
4929 int multilen, blen, alen, totallen, i;
4930 char before[16], after[4];
4931 int fgcolour, lastfgcolour = 0;
4932 int bgcolour, lastbgcolour = 0;
4933 int attrBold, lastAttrBold = 0;
4934 int attrUnder, lastAttrUnder = 0;
4935 int palette[NALLCOLOURS];
4937 FontSpec *font = conf_get_fontspec(conf, CONF_font);
4939 get_unitab(CP_ACP, unitab, 0);
4941 rtfsize = 100 + strlen(font->name);
4942 rtf = snewn(rtfsize, char);
4943 rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
4944 font->name, font->height*2);
4947 * Add colour palette
4948 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
4952 * First - Determine all colours in use
4953 * o Foregound and background colours share the same palette
4956 memset(palette, 0, sizeof(palette));
4957 for (i = 0; i < (len-1); i++) {
4958 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
4959 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
4961 if (attr[i] & ATTR_REVERSE) {
4962 int tmpcolour = fgcolour; /* Swap foreground and background */
4963 fgcolour = bgcolour;
4964 bgcolour = tmpcolour;
4967 if (bold_colours && (attr[i] & ATTR_BOLD)) {
4968 if (fgcolour < 8) /* ANSI colours */
4970 else if (fgcolour >= 256) /* Default colours */
4974 if (attr[i] & ATTR_BLINK) {
4975 if (bgcolour < 8) /* ANSI colours */
4977 else if (bgcolour >= 256) /* Default colours */
4981 palette[fgcolour]++;
4982 palette[bgcolour]++;
4986 * Next - Create a reduced palette
4989 for (i = 0; i < NALLCOLOURS; i++) {
4990 if (palette[i] != 0)
4991 palette[i] = ++numcolours;
4995 * Finally - Write the colour table
4997 rtf = sresize(rtf, rtfsize + (numcolours * 25), char);
4998 strcat(rtf, "{\\colortbl ;");
4999 rtflen = strlen(rtf);
5001 for (i = 0; i < NALLCOLOURS; i++) {
5002 if (palette[i] != 0) {
5003 rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);
5006 strcpy(&rtf[rtflen], "}");
5011 * We want to construct a piece of RTF that specifies the
5012 * same Unicode text. To do this we will read back in
5013 * parallel from the Unicode data in `udata' and the
5014 * non-Unicode data in `tdata'. For each character in
5015 * `tdata' which becomes the right thing in `udata' when
5016 * looked up in `unitab', we just copy straight over from
5017 * tdata. For each one that doesn't, we must WCToMB it
5018 * individually and produce a \u escape sequence.
5020 * It would probably be more robust to just bite the bullet
5021 * and WCToMB each individual Unicode character one by one,
5022 * then MBToWC each one back to see if it was an accurate
5023 * translation; but that strikes me as a horrifying number
5024 * of Windows API calls so I want to see if this faster way
5025 * will work. If it screws up badly we can always revert to
5026 * the simple and slow way.
5028 while (tindex < len2 && uindex < len &&
5029 tdata[tindex] && udata[uindex]) {
5030 if (tindex + 1 < len2 &&
5031 tdata[tindex] == '\r' &&
5032 tdata[tindex+1] == '\n') {
5038 * Set text attributes
5041 if (rtfsize < rtflen + 64) {
5042 rtfsize = rtflen + 512;
5043 rtf = sresize(rtf, rtfsize, char);
5047 * Determine foreground and background colours
5049 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
5050 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
5052 if (attr[tindex] & ATTR_REVERSE) {
5053 int tmpcolour = fgcolour; /* Swap foreground and background */
5054 fgcolour = bgcolour;
5055 bgcolour = tmpcolour;
5058 if (bold_colours && (attr[tindex] & ATTR_BOLD)) {
5059 if (fgcolour < 8) /* ANSI colours */
5061 else if (fgcolour >= 256) /* Default colours */
5065 if (attr[tindex] & ATTR_BLINK) {
5066 if (bgcolour < 8) /* ANSI colours */
5068 else if (bgcolour >= 256) /* Default colours */
5073 * Collect other attributes
5075 if (bold_font_mode != BOLD_NONE)
5076 attrBold = attr[tindex] & ATTR_BOLD;
5080 attrUnder = attr[tindex] & ATTR_UNDER;
5084 * o If video isn't reversed, ignore colour attributes for default foregound
5086 * o Special case where bolded text is displayed using the default foregound
5087 * and background colours - force to bolded RTF.
5089 if (!(attr[tindex] & ATTR_REVERSE)) {
5090 if (bgcolour >= 256) /* Default color */
5091 bgcolour = -1; /* No coloring */
5093 if (fgcolour >= 256) { /* Default colour */
5094 if (bold_colours && (fgcolour & 1) && bgcolour == -1)
5095 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
5097 fgcolour = -1; /* No coloring */
5102 * Write RTF text attributes
5104 if (lastfgcolour != fgcolour) {
5105 lastfgcolour = fgcolour;
5106 rtflen += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
5109 if (lastbgcolour != bgcolour) {
5110 lastbgcolour = bgcolour;
5111 rtflen += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
5114 if (lastAttrBold != attrBold) {
5115 lastAttrBold = attrBold;
5116 rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
5119 if (lastAttrUnder != attrUnder) {
5120 lastAttrUnder = attrUnder;
5121 rtflen += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
5125 if (unitab[tdata[tindex]] == udata[uindex]) {
5131 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
5132 NULL, 0, NULL, NULL);
5133 if (multilen != 1) {
5134 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
5136 alen = 1; strcpy(after, "}");
5138 blen = sprintf(before, "\\u%d", udata[uindex]);
5139 alen = 0; after[0] = '\0';
5142 assert(tindex + multilen <= len2);
5143 totallen = blen + alen;
5144 for (i = 0; i < multilen; i++) {
5145 if (tdata[tindex+i] == '\\' ||
5146 tdata[tindex+i] == '{' ||
5147 tdata[tindex+i] == '}')
5149 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
5150 totallen += 6; /* \par\r\n */
5151 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
5157 if (rtfsize < rtflen + totallen + 3) {
5158 rtfsize = rtflen + totallen + 512;
5159 rtf = sresize(rtf, rtfsize, char);
5162 strcpy(rtf + rtflen, before); rtflen += blen;
5163 for (i = 0; i < multilen; i++) {
5164 if (tdata[tindex+i] == '\\' ||
5165 tdata[tindex+i] == '{' ||
5166 tdata[tindex+i] == '}') {
5167 rtf[rtflen++] = '\\';
5168 rtf[rtflen++] = tdata[tindex+i];
5169 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
5170 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
5171 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
5172 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
5174 rtf[rtflen++] = tdata[tindex+i];
5177 strcpy(rtf + rtflen, after); rtflen += alen;
5183 rtf[rtflen++] = '}'; /* Terminate RTF stream */
5184 rtf[rtflen++] = '\0';
5185 rtf[rtflen++] = '\0';
5187 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
5188 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
5189 memcpy(lock3, rtf, rtflen);
5190 GlobalUnlock(clipdata3);
5196 GlobalUnlock(clipdata);
5197 GlobalUnlock(clipdata2);
5200 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
5202 if (OpenClipboard(hwnd)) {
5204 SetClipboardData(CF_UNICODETEXT, clipdata);
5205 SetClipboardData(CF_TEXT, clipdata2);
5207 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
5210 GlobalFree(clipdata);
5211 GlobalFree(clipdata2);
5215 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
5218 static DWORD WINAPI clipboard_read_threadfunc(void *param)
5220 HWND hwnd = (HWND)param;
5223 if (OpenClipboard(NULL)) {
5224 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
5225 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)1, (LPARAM)clipdata);
5226 } else if ((clipdata = GetClipboardData(CF_TEXT))) {
5227 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)0, (LPARAM)clipdata);
5235 static int process_clipdata(HGLOBAL clipdata, int unicode)
5237 sfree(clipboard_contents);
5238 clipboard_contents = NULL;
5239 clipboard_length = 0;
5242 wchar_t *p = GlobalLock(clipdata);
5246 /* Unwilling to rely on Windows having wcslen() */
5247 for (p2 = p; *p2; p2++);
5248 clipboard_length = p2 - p;
5249 clipboard_contents = snewn(clipboard_length + 1, wchar_t);
5250 memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t));
5251 clipboard_contents[clipboard_length] = L'\0';
5255 char *s = GlobalLock(clipdata);
5259 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
5260 clipboard_contents = snewn(i, wchar_t);
5261 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1,
5262 clipboard_contents, i);
5263 clipboard_length = i - 1;
5264 clipboard_contents[clipboard_length] = L'\0';
5272 void request_paste(void *frontend)
5275 * I always thought pasting was synchronous in Windows; the
5276 * clipboard access functions certainly _look_ synchronous,
5277 * unlike the X ones. But in fact it seems that in some
5278 * situations the contents of the clipboard might not be
5279 * immediately available, and the clipboard-reading functions
5280 * may block. This leads to trouble if the application
5281 * delivering the clipboard data has to get hold of it by -
5282 * for example - talking over a network connection which is
5283 * forwarded through this very PuTTY.
5285 * Hence, we spawn a subthread to read the clipboard, and do
5286 * our paste when it's finished. The thread will send a
5287 * message back to our main window when it terminates, and
5288 * that tells us it's OK to paste.
5290 DWORD in_threadid; /* required for Win9x */
5291 CreateThread(NULL, 0, clipboard_read_threadfunc,
5292 hwnd, 0, &in_threadid);
5295 void get_clip(void *frontend, wchar_t **p, int *len)
5298 *p = clipboard_contents;
5299 *len = clipboard_length;
5305 * Move `lines' lines from position `from' to position `to' in the
5308 void optimised_move(void *frontend, int to, int from, int lines)
5313 min = (to < from ? to : from);
5314 max = to + from - min;
5316 r.left = offset_width;
5317 r.right = offset_width + term->cols * font_width;
5318 r.top = offset_height + min * font_height;
5319 r.bottom = offset_height + (max + lines) * font_height;
5320 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
5325 * Print a message box and perform a fatal exit.
5327 void fatalbox(char *fmt, ...)
5330 char *stuff, morestuff[100];
5333 stuff = dupvprintf(fmt, ap);
5335 sprintf(morestuff, "%.70s Fatal Error", appname);
5336 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5342 * Print a modal (Really Bad) message box and perform a fatal exit.
5344 void modalfatalbox(char *fmt, ...)
5347 char *stuff, morestuff[100];
5350 stuff = dupvprintf(fmt, ap);
5352 sprintf(morestuff, "%.70s Fatal Error", appname);
5353 MessageBox(hwnd, stuff, morestuff,
5354 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
5360 * Print a message box and don't close the connection.
5362 void nonfatal(char *fmt, ...)
5365 char *stuff, morestuff[100];
5368 stuff = dupvprintf(fmt, ap);
5370 sprintf(morestuff, "%.70s Error", appname);
5371 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
5375 static BOOL flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout)
5377 if (p_FlashWindowEx) {
5379 fi.cbSize = sizeof(fi);
5381 fi.dwFlags = dwFlags;
5383 fi.dwTimeout = dwTimeout;
5384 return (*p_FlashWindowEx)(&fi);
5387 return FALSE; /* shrug */
5390 static void flash_window(int mode);
5391 static long next_flash;
5392 static int flashing = 0;
5395 * Timer for platforms where we must maintain window flashing manually
5398 static void flash_window_timer(void *ctx, unsigned long now)
5400 if (flashing && now == next_flash) {
5406 * Manage window caption / taskbar flashing, if enabled.
5407 * 0 = stop, 1 = maintain, 2 = start
5409 static void flash_window(int mode)
5411 int beep_ind = conf_get_int(conf, CONF_beep_ind);
5412 if ((mode == 0) || (beep_ind == B_IND_DISABLED)) {
5416 if (p_FlashWindowEx)
5417 flash_window_ex(FLASHW_STOP, 0, 0);
5419 FlashWindow(hwnd, FALSE);
5422 } else if (mode == 2) {
5426 if (p_FlashWindowEx) {
5427 /* For so-called "steady" mode, we use uCount=2, which
5428 * seems to be the traditional number of flashes used
5429 * by user notifications (e.g., by Explorer).
5430 * uCount=0 appears to enable continuous flashing, per
5431 * "flashing" mode, although I haven't seen this
5433 flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
5434 (beep_ind == B_IND_FLASH ? 0 : 2),
5435 0 /* system cursor blink rate */);
5436 /* No need to schedule timer */
5438 FlashWindow(hwnd, TRUE);
5439 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5443 } else if ((mode == 1) && (beep_ind == B_IND_FLASH)) {
5445 if (flashing && !p_FlashWindowEx) {
5446 FlashWindow(hwnd, TRUE); /* toggle */
5447 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5455 void do_beep(void *frontend, int mode)
5457 if (mode == BELL_DEFAULT) {
5459 * For MessageBeep style bells, we want to be careful of
5460 * timing, because they don't have the nice property of
5461 * PlaySound bells that each one cancels the previous
5462 * active one. So we limit the rate to one per 50ms or so.
5464 static long lastbeep = 0;
5467 beepdiff = GetTickCount() - lastbeep;
5468 if (beepdiff >= 0 && beepdiff < 50)
5472 * The above MessageBeep call takes time, so we record the
5473 * time _after_ it finishes rather than before it starts.
5475 lastbeep = GetTickCount();
5476 } else if (mode == BELL_WAVEFILE) {
5477 Filename *bell_wavefile = conf_get_filename(conf, CONF_bell_wavefile);
5478 if (!PlaySound(bell_wavefile->path, NULL,
5479 SND_ASYNC | SND_FILENAME)) {
5480 char buf[sizeof(bell_wavefile->path) + 80];
5482 sprintf(buf, "Unable to play sound file\n%s\n"
5483 "Using default sound instead", bell_wavefile->path);
5484 sprintf(otherbuf, "%.70s Sound Error", appname);
5485 MessageBox(hwnd, buf, otherbuf,
5486 MB_OK | MB_ICONEXCLAMATION);
5487 conf_set_int(conf, CONF_beep, BELL_DEFAULT);
5489 } else if (mode == BELL_PCSPEAKER) {
5490 static long lastbeep = 0;
5493 beepdiff = GetTickCount() - lastbeep;
5494 if (beepdiff >= 0 && beepdiff < 50)
5498 * We must beep in different ways depending on whether this
5499 * is a 95-series or NT-series OS.
5501 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
5505 lastbeep = GetTickCount();
5507 /* Otherwise, either visual bell or disabled; do nothing here */
5508 if (!term->has_focus) {
5509 flash_window(2); /* start */
5514 * Minimise or restore the window in response to a server-side
5517 void set_iconic(void *frontend, int iconic)
5519 if (IsIconic(hwnd)) {
5521 ShowWindow(hwnd, SW_RESTORE);
5524 ShowWindow(hwnd, SW_MINIMIZE);
5529 * Move the window in response to a server-side request.
5531 void move_window(void *frontend, int x, int y)
5533 int resize_action = conf_get_int(conf, CONF_resize_action);
5534 if (resize_action == RESIZE_DISABLED ||
5535 resize_action == RESIZE_FONT ||
5539 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5543 * Move the window to the top or bottom of the z-order in response
5544 * to a server-side request.
5546 void set_zorder(void *frontend, int top)
5548 if (conf_get_int(conf, CONF_alwaysontop))
5549 return; /* ignore */
5550 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5551 SWP_NOMOVE | SWP_NOSIZE);
5555 * Refresh the window in response to a server-side request.
5557 void refresh_window(void *frontend)
5559 InvalidateRect(hwnd, NULL, TRUE);
5563 * Maximise or restore the window in response to a server-side
5566 void set_zoomed(void *frontend, int zoomed)
5568 if (IsZoomed(hwnd)) {
5570 ShowWindow(hwnd, SW_RESTORE);
5573 ShowWindow(hwnd, SW_MAXIMIZE);
5578 * Report whether the window is iconic, for terminal reports.
5580 int is_iconic(void *frontend)
5582 return IsIconic(hwnd);
5586 * Report the window's position, for terminal reports.
5588 void get_window_pos(void *frontend, int *x, int *y)
5591 GetWindowRect(hwnd, &r);
5597 * Report the window's pixel size, for terminal reports.
5599 void get_window_pixels(void *frontend, int *x, int *y)
5602 GetWindowRect(hwnd, &r);
5603 *x = r.right - r.left;
5604 *y = r.bottom - r.top;
5608 * Return the window or icon title.
5610 char *get_window_title(void *frontend, int icon)
5612 return icon ? icon_name : window_name;
5616 * See if we're in full-screen mode.
5618 static int is_full_screen()
5620 if (!IsZoomed(hwnd))
5622 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
5627 /* Get the rect/size of a full screen window using the nearest available
5628 * monitor in multimon systems; default to something sensible if only
5629 * one monitor is present. */
5630 static int get_fullscreen_rect(RECT * ss)
5632 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
5635 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
5636 mi.cbSize = sizeof(mi);
5637 GetMonitorInfo(mon, &mi);
5639 /* structure copy */
5643 /* could also use code like this:
5644 ss->left = ss->top = 0;
5645 ss->right = GetSystemMetrics(SM_CXSCREEN);
5646 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5648 return GetClientRect(GetDesktopWindow(), ss);
5654 * Go full-screen. This should only be called when we are already
5657 static void make_full_screen()
5662 assert(IsZoomed(hwnd));
5664 if (is_full_screen())
5667 /* Remove the window furniture. */
5668 style = GetWindowLongPtr(hwnd, GWL_STYLE);
5669 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5670 if (conf_get_int(conf, CONF_scrollbar_in_fullscreen))
5671 style |= WS_VSCROLL;
5673 style &= ~WS_VSCROLL;
5674 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5676 /* Resize ourselves to exactly cover the nearest monitor. */
5677 get_fullscreen_rect(&ss);
5678 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5683 /* We may have changed size as a result */
5687 /* Tick the menu item in the System and context menus. */
5690 for (i = 0; i < lenof(popup_menus); i++)
5691 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED);
5696 * Clear the full-screen attributes.
5698 static void clear_full_screen()
5700 DWORD oldstyle, style;
5702 /* Reinstate the window furniture. */
5703 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
5704 style |= WS_CAPTION | WS_BORDER;
5705 if (conf_get_int(conf, CONF_resize_action) == RESIZE_DISABLED)
5706 style &= ~WS_THICKFRAME;
5708 style |= WS_THICKFRAME;
5709 if (conf_get_int(conf, CONF_scrollbar))
5710 style |= WS_VSCROLL;
5712 style &= ~WS_VSCROLL;
5713 if (style != oldstyle) {
5714 SetWindowLongPtr(hwnd, GWL_STYLE, style);
5715 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5716 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5720 /* Untick the menu item in the System and context menus. */
5723 for (i = 0; i < lenof(popup_menus); i++)
5724 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED);
5729 * Toggle full-screen mode.
5731 static void flip_full_screen()
5733 if (is_full_screen()) {
5734 ShowWindow(hwnd, SW_RESTORE);
5735 } else if (IsZoomed(hwnd)) {
5738 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5739 ShowWindow(hwnd, SW_MAXIMIZE);
5743 void frontend_keypress(void *handle)
5746 * Keypress termination in non-Close-On-Exit mode is not
5747 * currently supported in PuTTY proper, because the window
5748 * always has a perfectly good Close button anyway. So we do
5754 int from_backend(void *frontend, int is_stderr, const char *data, int len)
5756 return term_data(term, is_stderr, data, len);
5759 int from_backend_untrusted(void *frontend, const char *data, int len)
5761 return term_data_untrusted(term, data, len);
5764 int from_backend_eof(void *frontend)
5766 return TRUE; /* do respond to incoming EOF with outgoing */
5769 int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
5772 ret = cmdline_get_passwd_input(p, in, inlen);
5774 ret = term_get_userpass_input(term, p, in, inlen);
5778 void agent_schedule_callback(void (*callback)(void *, void *, int),
5779 void *callback_ctx, void *data, int len)
5781 struct agent_callback *c = snew(struct agent_callback);
5782 c->callback = callback;
5783 c->callback_ctx = callback_ctx;
5786 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);