Vyacheslav Andrejev points out a heap management goof in the new jump
[sgt/putty] / windows / window.c
CommitLineData
eaf1e20a 1/*
2 * window.c - the PuTTY(tel) main program, which runs a PuTTY terminal
3 * emulator and backend in a window.
4 */
5
374330e2 6#include <stdio.h>
7#include <stdlib.h>
1d470ad2 8#include <ctype.h>
ec55b220 9#include <time.h>
95587c73 10#include <limits.h>
a7419ea4 11#include <assert.h>
374330e2 12
06c3eadd 13#ifndef NO_MULTIMON
14#define COMPILE_MULTIMON_STUBS
15#endif
16
32874aea 17#define PUTTY_DO_GLOBALS /* actually _define_ globals */
374330e2 18#include "putty.h"
887035a5 19#include "terminal.h"
d5859615 20#include "storage.h"
374330e2 21#include "win_res.h"
22
7440fd44 23#ifndef NO_MULTIMON
7440fd44 24#include <multimon.h>
25#endif
7440fd44 26
27#include <imm.h>
28#include <commctrl.h>
29#include <richedit.h>
30#include <mmsystem.h>
31
ce0b6f45 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
865e82ad 35 * the low 4 bits clear. Also, identifiers should < 0xF000. */
ce0b6f45 36
6833a413 37#define IDM_SHOWLOG 0x0010
38#define IDM_NEWSESS 0x0020
39#define IDM_DUPSESS 0x0030
e3be8de5 40#define IDM_RESTART 0x0040
41#define IDM_RECONF 0x0050
42#define IDM_CLRSB 0x0060
43#define IDM_RESET 0x0070
70133c0e 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
63be7767 49#define IDM_PASTE 0x0190
45a22cae 50#define IDM_SPECIALSEP 0x0200
6833a413 51
125105d1 52#define IDM_SPECIAL_MIN 0x0400
53#define IDM_SPECIAL_MAX 0x0800
54
6833a413 55#define IDM_SAVED_MIN 0x1000
865e82ad 56#define IDM_SAVED_MAX 0x5000
57#define MENU_SAVED_STEP 16
1f1e3232 58/* Maximum number of sessions on saved-session submenu */
865e82ad 59#define MENU_SAVED_MAX ((IDM_SAVED_MAX-IDM_SAVED_MIN) / MENU_SAVED_STEP)
374330e2 60
604fab0c 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)
1d432454 64#define WM_GOT_CLIPDATA (WM_APP + 6)
374330e2 65
3cf144db 66/* Needed for Chinese support and apparently not always defined. */
67#ifndef VK_PROCESSKEY
68#define VK_PROCESSKEY 0xE5
69#endif
70
3f0f9388 71/* Mouse wheel support. */
5eaf1e06 72#ifndef WM_MOUSEWHEEL
3f0f9388 73#define WM_MOUSEWHEEL 0x020A /* not defined in earlier SDKs */
74#endif
75#ifndef WHEEL_DELTA
76#define WHEEL_DELTA 120
5eaf1e06 77#endif
78
2c02ed02 79static Mouse_Button translate_button(Mouse_Button button);
32874aea 80static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
81static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
82 unsigned char *output);
374330e2 83static void cfgtopalette(void);
26d1da7b 84static void systopalette(void);
374330e2 85static void init_palette(void);
5a73255e 86static void init_fonts(int, int);
4eeb7d09 87static void another_font(int);
88static void deinit_fonts(void);
a5ce2e9f 89static void set_input_locale(HKL);
12745e35 90static void update_savedsess_menu(void);
09644e07 91static void init_flashwindow(void);
374330e2 92
1ba99d2c 93static int is_full_screen(void);
94static void make_full_screen(void);
95static void clear_full_screen(void);
96static void flip_full_screen(void);
1d432454 97static int process_clipdata(HGLOBAL clipdata, int unicode);
1ba99d2c 98
5a73255e 99/* Window layout information */
100static void reset_window(int);
a401e5f3 101static int extra_width, extra_height;
5a73255e 102static int font_width, font_height, font_dualwidth;
103static int offset_width, offset_height;
104static int was_zoomed = 0;
105static int prev_rows, prev_cols;
106
56f8ea28 107static int pending_netevent = 0;
108static WPARAM pend_netevent_wParam = 0;
109static LPARAM pend_netevent_lParam = 0;
110static void enact_pending_netevent(void);
f8a28d1f 111static void flash_window(int mode);
c1da5066 112static void sys_cursor_update(void);
d0f1bcb4 113static int get_fullscreen_rect(RECT * ss);
59ad2c03 114
c1da5066 115static int caret_x = -1, caret_y = -1;
116
0b4f0bc0 117static int kbd_codepage;
118
b9d7bcad 119static void *ldisc;
6b78788a 120static Backend *back;
121static void *backhandle;
b9d7bcad 122
21d2b241 123static struct unicode_data ucsdata;
95587c73 124static int must_close_session, session_closed;
68a66cc3 125static int reconfiguring = FALSE;
0b4f0bc0 126
45a22cae 127static const struct telnet_special *specials = NULL;
128static HMENU specials_menu = NULL;
129static int n_specials = 0;
125105d1 130
1d432454 131static wchar_t *clipboard_contents;
132static size_t clipboard_length;
133
39934deb 134#define TIMING_TIMER_ID 1234
135static long timing_next_time;
136
63be7767 137static struct {
138 HMENU menu;
63be7767 139} popup_menus[2];
140enum { SYSMENU, CTXMENU };
12745e35 141static HMENU savedsess_menu;
63be7767 142
3ea863a3 143Config cfg; /* exported to windlg.c */
144
12745e35 145static struct sesslist sesslist; /* for saved-session menu */
0b4f0bc0 146
c44bf5bd 147struct agent_callback {
148 void (*callback)(void *, void *, int);
149 void *callback_ctx;
150 void *data;
151 int len;
152};
153
374330e2 154#define FONT_NORMAL 0
155#define FONT_BOLD 1
156#define FONT_UNDERLINE 2
157#define FONT_BOLDUND 3
4eeb7d09 158#define FONT_WIDE 0x04
159#define FONT_HIGH 0x08
160#define FONT_NARROW 0x10
5a73255e 161
4eeb7d09 162#define FONT_OEM 0x20
163#define FONT_OEMBOLD 0x21
164#define FONT_OEMUND 0x22
165#define FONT_OEMBOLDUND 0x23
5a73255e 166
167#define FONT_MAXNO 0x2F
4eeb7d09 168#define FONT_SHIFT 5
169static HFONT fonts[FONT_MAXNO];
71f6951d 170static LOGFONT lfont;
4eeb7d09 171static int fontflag[FONT_MAXNO];
374330e2 172static enum {
173 BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT
174} bold_mode;
175static enum {
176 UND_LINE, UND_FONT
177} und_mode;
178static int descent;
179
04a8208b 180#define NCFGCOLOURS 22
cecb13f6 181#define NEXTCOLOURS 240
182#define NALLCOLOURS (NCFGCOLOURS + NEXTCOLOURS)
183static COLORREF colours[NALLCOLOURS];
374330e2 184static HPALETTE pal;
185static LPLOGPALETTE logpal;
cecb13f6 186static RGBTRIPLE defpal[NALLCOLOURS];
374330e2 187
934c0b7a 188static HBITMAP caretbm;
189
374330e2 190static int dbltime, lasttime, lastact;
191static Mouse_Button lastbtn;
192
01c034ad 193/* this allows xterm-style mouse handling. */
194static int send_raw_mouse = 0;
195static int wheel_accumulator = 0;
196
755e0524 197static int busy_status = BUSY_NOT;
198
374330e2 199static char *window_name, *icon_name;
200
03f23ad6 201static int compose_state = 0;
202
011b0e33 203static UINT wm_mousewheel = WM_MOUSEWHEEL;
204
0965bee0 205/* Dummy routine, only required in plink. */
b9d7bcad 206void ldisc_update(void *frontend, int echo, int edit)
32874aea 207{
208}
6f34e365 209
c6ccd5c2 210char *get_ttymode(void *frontend, const char *mode)
211{
212 return term_get_ttymode(term, mode);
213}
214
e3be8de5 215static void start_backend(void)
216{
217 const char *error;
218 char msg[1024], *title;
219 char *realhost;
220 int i;
221
222 /*
223 * Select protocol. This is farmed out into a table in a
224 * separate file to enable an ssh-free variant.
225 */
9e164d82 226 back = backend_from_proto(cfg.protocol);
e3be8de5 227 if (back == NULL) {
228 char *str = dupprintf("%s Internal Error", appname);
229 MessageBox(NULL, "Unsupported protocol number found",
230 str, MB_OK | MB_ICONEXCLAMATION);
231 sfree(str);
232 cleanup_exit(1);
233 }
234
235 error = back->init(NULL, &backhandle, &cfg,
236 cfg.host, cfg.port, &realhost, cfg.tcp_nodelay,
237 cfg.tcp_keepalives);
238 back->provide_logctx(backhandle, logctx);
239 if (error) {
240 char *str = dupprintf("%s Error", appname);
241 sprintf(msg, "Unable to open connection to\n"
7374c779 242 "%.800s\n" "%s", cfg_dest(&cfg), error);
e3be8de5 243 MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
244 sfree(str);
245 exit(0);
246 }
247 window_name = icon_name = NULL;
248 if (*cfg.wintitle) {
249 title = cfg.wintitle;
250 } else {
251 sprintf(msg, "%s - %s", realhost, appname);
252 title = msg;
253 }
254 sfree(realhost);
255 set_title(NULL, title);
256 set_icon(NULL, title);
257
258 /*
259 * Connect the terminal to the backend for resize purposes.
260 */
261 term_provide_resize_fn(term, back->size, backhandle);
262
263 /*
264 * Set up a line discipline.
265 */
266 ldisc = ldisc_create(&cfg, term, back, backhandle, NULL);
267
268 /*
269 * Destroy the Restart Session menu item. (This will return
270 * failure if it's already absent, as it will be the very first
271 * time we call this function. We ignore that, because as long
272 * as the menu item ends up not being there, we don't care
273 * whether it was us who removed it or not!)
274 */
275 for (i = 0; i < lenof(popup_menus); i++) {
276 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
277 }
278
8eec6d96 279 must_close_session = FALSE;
e3be8de5 280 session_closed = FALSE;
281}
282
283static void close_session(void)
284{
285 char morestuff[100];
286 int i;
287
288 session_closed = TRUE;
289 sprintf(morestuff, "%.70s (inactive)", appname);
290 set_icon(NULL, morestuff);
291 set_title(NULL, morestuff);
292
293 if (ldisc) {
294 ldisc_free(ldisc);
295 ldisc = NULL;
296 }
297 if (back) {
298 back->free(backhandle);
299 backhandle = NULL;
300 back = NULL;
c1190260 301 term_provide_resize_fn(term, NULL, NULL);
e3be8de5 302 update_specials_menu(NULL);
303 }
304
305 /*
306 * Show the Restart Session menu item. Do a precautionary
307 * delete first to ensure we never end up with more than one.
308 */
309 for (i = 0; i < lenof(popup_menus); i++) {
310 DeleteMenu(popup_menus[i].menu, IDM_RESTART, MF_BYCOMMAND);
311 InsertMenu(popup_menus[i].menu, IDM_DUPSESS, MF_BYCOMMAND | MF_ENABLED,
312 IDM_RESTART, "&Restart Session");
313 }
314}
315
32874aea 316int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
317{
374330e2 318 WNDCLASS wndclass;
319 MSG msg;
073e9f42 320 HRESULT hr;
374330e2 321 int guess_width, guess_height;
322
8c3cd914 323 hinst = inst;
28339579 324 hwnd = NULL;
67779be7 325 flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
73251d5d 326
8df7a775 327 sk_init();
374330e2 328
329 InitCommonControls();
330
301b66db 331 /* Ensure a Maximize setting in Explorer doesn't maximise the
332 * config box. */
333 defuse_showwindow();
334
4c48c989 335 if (!init_winver())
88485e4d 336 {
4c48c989 337 char *str = dupprintf("%s Fatal Error", appname);
338 MessageBox(NULL, "Windows refuses to report a version",
339 str, MB_OK | MB_ICONEXCLAMATION);
340 sfree(str);
341 return 1;
88485e4d 342 }
343
374330e2 344 /*
011b0e33 345 * If we're running a version of Windows that doesn't support
346 * WM_MOUSEWHEEL, find out what message number we should be
347 * using instead.
348 */
349 if (osVersion.dwMajorVersion < 4 ||
350 (osVersion.dwMajorVersion == 4 &&
351 osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
352 wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
353
cb2708d3 354 init_help();
70133c0e 355
09644e07 356 init_flashwindow();
357
70133c0e 358 /*
073e9f42 359 * Initialize COM.
360 */
361 hr = CoInitialize(NULL);
362 if (hr != S_OK && hr != S_FALSE) {
363 char *str = dupprintf("%s Fatal Error", appname);
364 MessageBox(NULL, "Failed to initialize COM subsystem",
365 str, MB_OK | MB_ICONEXCLAMATION);
366 sfree(str);
367 return 1;
368 }
369
370 /*
374330e2 371 * Process the command line.
372 */
373 {
374 char *p;
c0a81592 375 int got_host = 0;
df7c7e52 376 /* By default, we bring up the config dialog, rather than launching
377 * a session. This gets set to TRUE if something happens to change
378 * that (e.g., a hostname is specified on the command-line). */
379 int allow_launch = FALSE;
374330e2 380
ffa79828 381 default_protocol = be_default_protocol;
382 /* Find the appropriate default port. */
383 {
9e164d82 384 Backend *b = backend_from_proto(default_protocol);
0d598aa7 385 default_port = 0; /* illegal */
9e164d82 386 if (b)
387 default_port = b->default_port;
ffa79828 388 }
e1c8e0ed 389 cfg.logtype = LGTYP_NONE;
e277c42d 390
a9422f39 391 do_defaults(NULL, &cfg);
374330e2 392
393 p = cmdline;
374330e2 394
395 /*
c0a81592 396 * Process a couple of command-line options which are more
073e9f42 397 * easily dealt with before the line is broken up into words.
398 * These are the old-fashioned but convenient @sessionname and
399 * the internal-use-only &sharedmemoryhandle, neither of which
400 * are combined with anything else.
e277c42d 401 */
c0a81592 402 while (*p && isspace(*p))
e277c42d 403 p++;
374330e2 404 if (*p == '@') {
073e9f42 405 /*
406 * An initial @ means that the whole of the rest of the
407 * command line should be treated as the name of a saved
408 * session, with _no quoting or escaping_. This makes it a
409 * very convenient means of automated saved-session
410 * launching, via IDM_SAVEDSESS or Windows 7 jump lists.
411 */
f317611e 412 int i = strlen(p);
32874aea 413 while (i > 1 && isspace(p[i - 1]))
f317611e 414 i--;
415 p[i] = '\0';
32874aea 416 do_defaults(p + 1, &cfg);
69a1f86c 417 if (!cfg_launchable(&cfg) && !do_config()) {
7440fd44 418 cleanup_exit(0);
374330e2 419 }
df7c7e52 420 allow_launch = TRUE; /* allow it to be launched directly */
374330e2 421 } else if (*p == '&') {
422 /*
423 * An initial & means we've been given a command line
424 * containing the hex value of a HANDLE for a file
425 * mapping object, which we must then extract as a
426 * config.
427 */
428 HANDLE filemap;
429 Config *cp;
32874aea 430 if (sscanf(p + 1, "%p", &filemap) == 1 &&
374330e2 431 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
432 0, 0, sizeof(Config))) != NULL) {
433 cfg = *cp;
434 UnmapViewOfFile(cp);
435 CloseHandle(filemap);
436 } else if (!do_config()) {
7440fd44 437 cleanup_exit(0);
374330e2 438 }
df7c7e52 439 allow_launch = TRUE;
c0a81592 440 } else {
32874aea 441 /*
c0a81592 442 * Otherwise, break up the command line and deal with
443 * it sensibly.
32874aea 444 */
c0a81592 445 int argc, i;
446 char **argv;
447
d3a1a808 448 split_into_argv(cmdline, &argc, &argv, NULL);
c0a81592 449
450 for (i = 0; i < argc; i++) {
451 char *p = argv[i];
452 int ret;
453
5555d393 454 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
455 1, &cfg);
c0a81592 456 if (ret == -2) {
457 cmdline_error("option \"%s\" requires an argument", p);
458 } else if (ret == 2) {
459 i++; /* skip next argument */
460 } else if (ret == 1) {
461 continue; /* nothing further needs doing */
a6551274 462 } else if (!strcmp(p, "-cleanup") ||
463 !strcmp(p, "-cleanup-during-uninstall")) {
c0a81592 464 /*
465 * `putty -cleanup'. Remove all registry
466 * entries associated with PuTTY, and also find
467 * and delete the random seed file.
468 */
f6f450e2 469 char *s1, *s2;
a6551274 470 /* Are we being invoked from an uninstaller? */
471 if (!strcmp(p, "-cleanup-during-uninstall")) {
472 s1 = dupprintf("Remove saved sessions and random seed file?\n"
473 "\n"
474 "If you hit Yes, ALL Registry entries associated\n"
475 "with %s will be removed, as well as the\n"
476 "random seed file. THIS PROCESS WILL\n"
477 "DESTROY YOUR SAVED SESSIONS.\n"
478 "(This only affects the currently logged-in user.)\n"
479 "\n"
480 "If you hit No, uninstallation will proceed, but\n"
481 "saved sessions etc will be left on the machine.",
482 appname);
483 s2 = dupprintf("%s Uninstallation", appname);
484 } else {
485 s1 = dupprintf("This procedure will remove ALL Registry entries\n"
486 "associated with %s, and will also remove\n"
487 "the random seed file. (This only affects the\n"
488 "currently logged-in user.)\n"
489 "\n"
490 "THIS PROCESS WILL DESTROY YOUR SAVED SESSIONS.\n"
491 "Are you really sure you want to continue?",
492 appname);
493 s2 = dupprintf("%s Warning", appname);
494 }
495 if (message_box(s1, s2,
496 MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2,
28339579 497 HELPCTXID(option_cleanup)) == IDYES) {
c0a81592 498 cleanup_all();
499 }
f6f450e2 500 sfree(s1);
501 sfree(s2);
c0a81592 502 exit(0);
2285d016 503 } else if (!strcmp(p, "-pgpfp")) {
504 pgp_fingerprints();
505 exit(1);
c0a81592 506 } else if (*p != '-') {
507 char *q = p;
508 if (got_host) {
509 /*
510 * If we already have a host name, treat
511 * this argument as a port number. NB we
512 * have to treat this as a saved -P
513 * argument, so that it will be deferred
514 * until it's a good moment to run it.
515 */
5555d393 516 int ret = cmdline_process_param("-P", p, 1, &cfg);
c0a81592 517 assert(ret == 2);
518 } else if (!strncmp(q, "telnet:", 7)) {
519 /*
520 * If the hostname starts with "telnet:",
521 * set the protocol to Telnet and process
522 * the string as a Telnet URL.
523 */
524 char c;
525
526 q += 7;
527 if (q[0] == '/' && q[1] == '/')
528 q += 2;
529 cfg.protocol = PROT_TELNET;
530 p = q;
531 while (*p && *p != ':' && *p != '/')
532 p++;
533 c = *p;
534 if (*p)
535 *p++ = '\0';
536 if (c == ':')
537 cfg.port = atoi(p);
538 else
539 cfg.port = -1;
540 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
541 cfg.host[sizeof(cfg.host) - 1] = '\0';
542 got_host = 1;
543 } else {
544 /*
545 * Otherwise, treat this argument as a host
546 * name.
547 */
548 while (*p && !isspace(*p))
549 p++;
550 if (*p)
551 *p++ = '\0';
552 strncpy(cfg.host, q, sizeof(cfg.host) - 1);
553 cfg.host[sizeof(cfg.host) - 1] = '\0';
554 got_host = 1;
555 }
86256dc6 556 } else {
557 cmdline_error("unknown option \"%s\"", p);
c0a81592 558 }
374330e2 559 }
560 }
13eafebf 561
5555d393 562 cmdline_run_saved(&cfg);
c0a81592 563
df7c7e52 564 if (loaded_session || got_host)
565 allow_launch = TRUE;
566
567 if ((!allow_launch || !cfg_launchable(&cfg)) && !do_config()) {
7440fd44 568 cleanup_exit(0);
c0a81592 569 }
570
381b1876 571 /*
572 * Trim leading whitespace off the hostname if it's there.
573 */
574 {
575 int space = strspn(cfg.host, " \t");
576 memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
577 }
578
13eafebf 579 /* See if host is of the form user@host */
580 if (cfg.host[0] != '\0') {
5dd103a8 581 char *atsign = strrchr(cfg.host, '@');
13eafebf 582 /* Make sure we're not overflowing the user field */
583 if (atsign) {
32874aea 584 if (atsign - cfg.host < sizeof cfg.username) {
585 strncpy(cfg.username, cfg.host, atsign - cfg.host);
586 cfg.username[atsign - cfg.host] = '\0';
13eafebf 587 }
32874aea 588 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
13eafebf 589 }
590 }
503ddb97 591
592 /*
05581745 593 * Trim a colon suffix off the hostname if it's there. In
594 * order to protect IPv6 address literals against this
595 * treatment, we do not do this if there's _more_ than one
596 * colon.
503ddb97 597 */
05581745 598 {
599 char *c = strchr(cfg.host, ':');
600
601 if (c) {
602 char *d = strchr(c+1, ':');
603 if (!d)
604 *c = '\0';
605 }
606 }
cae0c023 607
608 /*
609 * Remove any remaining whitespace from the hostname.
610 */
611 {
612 int p1 = 0, p2 = 0;
613 while (cfg.host[p2] != '\0') {
614 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
615 cfg.host[p1] = cfg.host[p2];
616 p1++;
617 }
618 p2++;
619 }
620 cfg.host[p1] = '\0';
621 }
374330e2 622 }
623
374330e2 624 if (!prev) {
32874aea 625 wndclass.style = 0;
626 wndclass.lpfnWndProc = WndProc;
627 wndclass.cbClsExtra = 0;
628 wndclass.cbWndExtra = 0;
629 wndclass.hInstance = inst;
630 wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
631 wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
5a73255e 632 wndclass.hbrBackground = NULL;
32874aea 633 wndclass.lpszMenuName = NULL;
374330e2 634 wndclass.lpszClassName = appname;
635
32874aea 636 RegisterClass(&wndclass);
374330e2 637 }
638
21d2b241 639 memset(&ucsdata, 0, sizeof(ucsdata));
640
374330e2 641 cfgtopalette();
642
643 /*
644 * Guess some defaults for the window size. This all gets
645 * updated later, so we don't really care too much. However, we
646 * do want the font width/height guesses to correspond to a
647 * large font rather than a small one...
648 */
32874aea 649
374330e2 650 font_width = 10;
651 font_height = 20;
652 extra_width = 25;
653 extra_height = 28;
c52dd4c9 654 guess_width = extra_width + font_width * cfg.width;
655 guess_height = extra_height + font_height * cfg.height;
374330e2 656 {
657 RECT r;
f43e4b67 658 get_fullscreen_rect(&r);
374330e2 659 if (guess_width > r.right - r.left)
660 guess_width = r.right - r.left;
661 if (guess_height > r.bottom - r.top)
662 guess_height = r.bottom - r.top;
663 }
664
c9def1b8 665 {
32874aea 666 int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
667 int exwinmode = 0;
668 if (!cfg.scrollbar)
669 winmode &= ~(WS_VSCROLL);
ad5c93cc 670 if (cfg.resize_action == RESIZE_DISABLED)
32874aea 671 winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
672 if (cfg.alwaysontop)
673 exwinmode |= WS_EX_TOPMOST;
674 if (cfg.sunken_edge)
675 exwinmode |= WS_EX_CLIENTEDGE;
676 hwnd = CreateWindowEx(exwinmode, appname, appname,
677 winmode, CW_USEDEFAULT, CW_USEDEFAULT,
678 guess_width, guess_height,
679 NULL, NULL, inst, NULL);
680 }
374330e2 681
682 /*
c52dd4c9 683 * Initialise the terminal. (We have to do this _after_
684 * creating the window, since the terminal is the first thing
685 * which will call schedule_timer(), which will in turn call
5ba93094 686 * timer_change_notify() which will expect hwnd to exist.)
c52dd4c9 687 */
688 term = term_init(&cfg, &ucsdata, NULL);
689 logctx = log_init(NULL, &cfg);
690 term_provide_logctx(term, logctx);
691 term_size(term, cfg.height, cfg.width, cfg.savelines);
692
693 /*
374330e2 694 * Initialise the fonts, simultaneously correcting the guesses
695 * for font_{width,height}.
696 */
5a73255e 697 init_fonts(0,0);
374330e2 698
699 /*
700 * Correct the guesses for extra_{width,height}.
701 */
702 {
703 RECT cr, wr;
32874aea 704 GetWindowRect(hwnd, &wr);
705 GetClientRect(hwnd, &cr);
5a73255e 706 offset_width = offset_height = cfg.window_border;
707 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
708 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
374330e2 709 }
710
711 /*
712 * Resize the window, now we know what size we _really_ want it
713 * to be.
714 */
887035a5 715 guess_width = extra_width + font_width * term->cols;
716 guess_height = extra_height + font_height * term->rows;
32874aea 717 SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
718 SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
374330e2 719
720 /*
934c0b7a 721 * Set up a caret bitmap, with no content.
722 */
723 {
32874aea 724 char *bits;
725 int size = (font_width + 15) / 16 * 2 * font_height;
3d88e64d 726 bits = snewn(size, char);
32874aea 727 memset(bits, 0, size);
728 caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
729 sfree(bits);
934c0b7a 730 }
5b7ce734 731 CreateCaret(hwnd, caretbm, font_width, font_height);
934c0b7a 732
733 /*
374330e2 734 * Initialise the scroll bar.
735 */
736 {
737 SCROLLINFO si;
738
739 si.cbSize = sizeof(si);
c9def1b8 740 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
374330e2 741 si.nMin = 0;
887035a5 742 si.nMax = term->rows - 1;
743 si.nPage = term->rows;
374330e2 744 si.nPos = 0;
32874aea 745 SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
374330e2 746 }
747
374330e2 748 /*
374330e2 749 * Prepare the mouse handler.
750 */
751 lastact = MA_NOTHING;
01c034ad 752 lastbtn = MBT_NOTHING;
374330e2 753 dbltime = GetDoubleClickTime();
754
755 /*
756 * Set up the session-control options on the system menu.
757 */
758 {
12745e35 759 HMENU m;
760 int j;
f6f450e2 761 char *str;
374330e2 762
63be7767 763 popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
764 popup_menus[CTXMENU].menu = CreatePopupMenu();
765 AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
766
12745e35 767 savedsess_menu = CreateMenu();
0b4f0bc0 768 get_sesslist(&sesslist, TRUE);
12745e35 769 update_savedsess_menu();
63be7767 770
771 for (j = 0; j < lenof(popup_menus); j++) {
772 m = popup_menus[j].menu;
773
774 AppendMenu(m, MF_SEPARATOR, 0, 0);
63be7767 775 AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
776 AppendMenu(m, MF_SEPARATOR, 0, 0);
777 AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
778 AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
12745e35 779 AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) savedsess_menu,
780 "Sa&ved Sessions");
63be7767 781 AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
782 AppendMenu(m, MF_SEPARATOR, 0, 0);
783 AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
784 AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
785 AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
786 AppendMenu(m, MF_SEPARATOR, 0, 0);
787 AppendMenu(m, (cfg.resize_action == RESIZE_DISABLED) ?
788 MF_GRAYED : MF_ENABLED, IDM_FULLSCREEN, "&Full Screen");
789 AppendMenu(m, MF_SEPARATOR, 0, 0);
cb2708d3 790 if (has_help())
63be7767 791 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
792 str = dupprintf("&About %s", appname);
793 AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
794 sfree(str);
795 }
374330e2 796 }
797
533b1743 798 start_backend();
125105d1 799
374330e2 800 /*
a5ce2e9f 801 * Set up the initial input locale.
802 */
803 set_input_locale(GetKeyboardLayout(0));
804
805 /*
00db133f 806 * Finally show the window!
e1c8e0ed 807 */
00db133f 808 ShowWindow(hwnd, show);
809 SetForegroundWindow(hwnd);
e1c8e0ed 810
811 /*
374330e2 812 * Set the palette up.
813 */
814 pal = NULL;
815 logpal = NULL;
816 init_palette();
817
1cff1320 818 term_set_focus(term, GetForegroundWindow() == hwnd);
32874aea 819 UpdateWindow(hwnd);
374330e2 820
34292b1d 821 while (1) {
822 HANDLE *handles;
823 int nhandles, n;
824
825 handles = handle_get_events(&nhandles);
826
827 n = MsgWaitForMultipleObjects(nhandles, handles, FALSE, INFINITE,
828 QS_ALLINPUT);
829
830 if ((unsigned)(n - WAIT_OBJECT_0) < (unsigned)nhandles) {
831 handle_got_event(handles[n - WAIT_OBJECT_0]);
832 sfree(handles);
95587c73 833 if (must_close_session)
834 close_session();
45d56852 835 } else
836 sfree(handles);
34292b1d 837
b08600c4 838 while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
34292b1d 839 if (msg.message == WM_QUIT)
840 goto finished; /* two-level break */
841
32874aea 842 if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
843 DispatchMessage(&msg);
c9def1b8 844 /* Send the paste buffer if there's anything to send */
887035a5 845 term_paste(term);
59ad2c03 846 /* If there's nothing new in the queue then we can do everything
847 * we've delayed, reading the socket, writing, and repainting
848 * the window.
849 */
95587c73 850 if (must_close_session)
851 close_session();
b08600c4 852 }
0ed2f48e 853
34292b1d 854 /* The messages seem unreliable; especially if we're being tricky */
855 term_set_focus(term, GetForegroundWindow() == hwnd);
32874aea 856
56f8ea28 857 if (pending_netevent)
858 enact_pending_netevent();
859
34292b1d 860 net_pending_errors();
374330e2 861 }
862
34292b1d 863 finished:
c0d36a72 864 cleanup_exit(msg.wParam); /* this doesn't return... */
865 return msg.wParam; /* ... but optimiser doesn't know */
93b581bd 866}
867
868/*
869 * Clean up and exit.
870 */
871void cleanup_exit(int code)
872{
374330e2 873 /*
874 * Clean up.
875 */
4eeb7d09 876 deinit_fonts();
374330e2 877 sfree(logpal);
878 if (pal)
879 DeleteObject(pal);
93b581bd 880 sk_cleanup();
374330e2 881
8f203108 882 if (cfg.protocol == PROT_SSH) {
374330e2 883 random_save_seed();
8f203108 884#ifdef MSCRYPTOAPI
885 crypto_wrapup();
886#endif
887 }
cb2708d3 888 shutdown_help();
374330e2 889
073e9f42 890 /* Clean up COM. */
891 CoUninitialize();
892
93b581bd 893 exit(code);
374330e2 894}
895
896/*
8df7a775 897 * Set up, or shut down, an AsyncSelect. Called from winnet.c.
898 */
32874aea 899char *do_select(SOCKET skt, int startup)
900{
8df7a775 901 int msg, events;
902 if (startup) {
903 msg = WM_NETEVENT;
3ad9d396 904 events = (FD_CONNECT | FD_READ | FD_WRITE |
905 FD_OOB | FD_CLOSE | FD_ACCEPT);
8df7a775 906 } else {
907 msg = events = 0;
908 }
909 if (!hwnd)
910 return "do_select(): internal error (hwnd==NULL)";
7440fd44 911 if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
912 switch (p_WSAGetLastError()) {
32874aea 913 case WSAENETDOWN:
914 return "Network is down";
915 default:
916 return "WSAAsyncSelect(): unknown error";
917 }
8df7a775 918 }
919 return NULL;
920}
921
922/*
12745e35 923 * Refresh the saved-session submenu from `sesslist'.
924 */
925static void update_savedsess_menu(void)
926{
927 int i;
928 while (DeleteMenu(savedsess_menu, 0, MF_BYPOSITION)) ;
929 /* skip sesslist.sessions[0] == Default Settings */
930 for (i = 1;
931 i < ((sesslist.nsessions <= MENU_SAVED_MAX+1) ? sesslist.nsessions
932 : MENU_SAVED_MAX+1);
933 i++)
934 AppendMenu(savedsess_menu, MF_ENABLED,
935 IDM_SAVED_MIN + (i-1)*MENU_SAVED_STEP,
936 sesslist.sessions[i]);
f43e4b67 937 if (sesslist.nsessions <= 1)
938 AppendMenu(savedsess_menu, MF_GRAYED, IDM_SAVED_MIN, "(No sessions)");
12745e35 939}
940
941/*
125105d1 942 * Update the Special Commands submenu.
943 */
944void update_specials_menu(void *frontend)
945{
45a22cae 946 HMENU new_menu;
63be7767 947 int i, j;
125105d1 948
e3be8de5 949 if (back)
950 specials = back->get_specials(backhandle);
951 else
952 specials = NULL;
953
125105d1 954 if (specials) {
6f2d0cde 955 /* We can't use Windows to provide a stack for submenus, so
956 * here's a lame "stack" that will do for now. */
957 HMENU saved_menu = NULL;
958 int nesting = 1;
45a22cae 959 new_menu = CreatePopupMenu();
6f2d0cde 960 for (i = 0; nesting > 0; i++) {
125105d1 961 assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
6f2d0cde 962 switch (specials[i].code) {
963 case TS_SEP:
45a22cae 964 AppendMenu(new_menu, MF_SEPARATOR, 0, 0);
6f2d0cde 965 break;
966 case TS_SUBMENU:
967 assert(nesting < 2);
968 nesting++;
45a22cae 969 saved_menu = new_menu; /* XXX lame stacking */
970 new_menu = CreatePopupMenu();
6f2d0cde 971 AppendMenu(saved_menu, MF_POPUP | MF_ENABLED,
45a22cae 972 (UINT) new_menu, specials[i].name);
6f2d0cde 973 break;
974 case TS_EXITMENU:
975 nesting--;
976 if (nesting) {
45a22cae 977 new_menu = saved_menu; /* XXX lame stacking */
6f2d0cde 978 saved_menu = NULL;
979 }
980 break;
981 default:
45a22cae 982 AppendMenu(new_menu, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
125105d1 983 specials[i].name);
6f2d0cde 984 break;
985 }
125105d1 986 }
6f2d0cde 987 /* Squirrel the highest special. */
988 n_specials = i - 1;
989 } else {
45a22cae 990 new_menu = NULL;
6f2d0cde 991 n_specials = 0;
992 }
e3be8de5 993
994 for (j = 0; j < lenof(popup_menus); j++) {
45a22cae 995 if (specials_menu) {
6f2d0cde 996 /* XXX does this free up all submenus? */
62ddb51e 997 DeleteMenu(popup_menus[j].menu, (UINT)specials_menu, MF_BYCOMMAND);
45a22cae 998 DeleteMenu(popup_menus[j].menu, IDM_SPECIALSEP, MF_BYCOMMAND);
e3be8de5 999 }
47d1dab7 1000 if (new_menu) {
45a22cae 1001 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1002 MF_BYCOMMAND | MF_POPUP | MF_ENABLED,
1003 (UINT) new_menu, "S&pecial Command");
1004 InsertMenu(popup_menus[j].menu, IDM_SHOWLOG,
1005 MF_BYCOMMAND | MF_SEPARATOR, IDM_SPECIALSEP, 0);
63be7767 1006 }
125105d1 1007 }
47d1dab7 1008 specials_menu = new_menu;
125105d1 1009}
1010
755e0524 1011static void update_mouse_pointer(void)
1012{
1013 LPTSTR curstype;
1014 int force_visible = FALSE;
1015 static int forced_visible = FALSE;
1016 switch (busy_status) {
1017 case BUSY_NOT:
1018 if (send_raw_mouse)
1019 curstype = IDC_ARROW;
1020 else
1021 curstype = IDC_IBEAM;
1022 break;
1023 case BUSY_WAITING:
1024 curstype = IDC_APPSTARTING; /* this may be an abuse */
1025 force_visible = TRUE;
1026 break;
1027 case BUSY_CPU:
1028 curstype = IDC_WAIT;
1029 force_visible = TRUE;
1030 break;
1031 default:
1032 assert(0);
1033 }
1034 {
1035 HCURSOR cursor = LoadCursor(NULL, curstype);
158cb9b1 1036 SetClassLongPtr(hwnd, GCLP_HCURSOR, (LONG_PTR)cursor);
755e0524 1037 SetCursor(cursor); /* force redraw of cursor at current posn */
1038 }
1039 if (force_visible != forced_visible) {
1040 /* We want some cursor shapes to be visible always.
1041 * Along with show_mouseptr(), this manages the ShowCursor()
1042 * counter such that if we switch back to a non-force_visible
1043 * cursor, the previous visibility state is restored. */
1044 ShowCursor(force_visible);
1045 forced_visible = force_visible;
1046 }
1047}
1048
1049void set_busy_status(void *frontend, int status)
1050{
1051 busy_status = status;
1052 update_mouse_pointer();
1053}
1054
125105d1 1055/*
01c034ad 1056 * set or clear the "raw mouse message" mode
1057 */
a8327734 1058void set_raw_mouse_mode(void *frontend, int activate)
01c034ad 1059{
c0d36a72 1060 activate = activate && !cfg.no_mouse_rep;
01c034ad 1061 send_raw_mouse = activate;
755e0524 1062 update_mouse_pointer();
01c034ad 1063}
1064
1065/*
8d5de777 1066 * Print a message box and close the connection.
1067 */
a8327734 1068void connection_fatal(void *frontend, char *fmt, ...)
32874aea 1069{
8d5de777 1070 va_list ap;
971bcc0a 1071 char *stuff, morestuff[100];
8d5de777 1072
1073 va_start(ap, fmt);
971bcc0a 1074 stuff = dupvprintf(fmt, ap);
8d5de777 1075 va_end(ap);
f6f450e2 1076 sprintf(morestuff, "%.70s Fatal Error", appname);
1077 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
971bcc0a 1078 sfree(stuff);
1079
5ecd7ad0 1080 if (cfg.close_on_exit == FORCE_ON)
32874aea 1081 PostQuitMessage(1);
8d5de777 1082 else {
95587c73 1083 must_close_session = TRUE;
8d5de777 1084 }
1085}
1086
1087/*
c0a81592 1088 * Report an error at the command-line parsing stage.
1089 */
1090void cmdline_error(char *fmt, ...)
1091{
1092 va_list ap;
971bcc0a 1093 char *stuff, morestuff[100];
c0a81592 1094
1095 va_start(ap, fmt);
971bcc0a 1096 stuff = dupvprintf(fmt, ap);
c0a81592 1097 va_end(ap);
f6f450e2 1098 sprintf(morestuff, "%.70s Command Line Error", appname);
1099 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
971bcc0a 1100 sfree(stuff);
c0a81592 1101 exit(1);
1102}
1103
1104/*
59ad2c03 1105 * Actually do the job requested by a WM_NETEVENT
1106 */
56f8ea28 1107static void enact_pending_netevent(void)
32874aea 1108{
9dde0b46 1109 static int reentering = 0;
8df7a775 1110 extern int select_result(WPARAM, LPARAM);
9dde0b46 1111
1112 if (reentering)
32874aea 1113 return; /* don't unpend the pending */
9dde0b46 1114
56f8ea28 1115 pending_netevent = FALSE;
1116
9dde0b46 1117 reentering = 1;
56f8ea28 1118 select_result(pend_netevent_wParam, pend_netevent_lParam);
9dde0b46 1119 reentering = 0;
59ad2c03 1120}
1121
1122/*
374330e2 1123 * Copy the colour palette from the configuration data into defpal.
1124 * This is non-trivial because the colour indices are different.
1125 */
32874aea 1126static void cfgtopalette(void)
1127{
374330e2 1128 int i;
1129 static const int ww[] = {
cecb13f6 1130 256, 257, 258, 259, 260, 261,
1131 0, 8, 1, 9, 2, 10, 3, 11,
1132 4, 12, 5, 13, 6, 14, 7, 15
374330e2 1133 };
1134
cecb13f6 1135 for (i = 0; i < 22; i++) {
374330e2 1136 int w = ww[i];
cecb13f6 1137 defpal[w].rgbtRed = cfg.colours[i][0];
1138 defpal[w].rgbtGreen = cfg.colours[i][1];
1139 defpal[w].rgbtBlue = cfg.colours[i][2];
1140 }
1141 for (i = 0; i < NEXTCOLOURS; i++) {
1142 if (i < 216) {
1143 int r = i / 36, g = (i / 6) % 6, b = i % 6;
8098d585 1144 defpal[i+16].rgbtRed = r ? r * 40 + 55 : 0;
1145 defpal[i+16].rgbtGreen = g ? g * 40 + 55 : 0;
1146 defpal[i+16].rgbtBlue = b ? b * 40 + 55 : 0;
cecb13f6 1147 } else {
1148 int shade = i - 216;
8098d585 1149 shade = shade * 10 + 8;
cecb13f6 1150 defpal[i+16].rgbtRed = defpal[i+16].rgbtGreen =
1151 defpal[i+16].rgbtBlue = shade;
1152 }
374330e2 1153 }
26d1da7b 1154
1155 /* Override with system colours if appropriate */
1156 if (cfg.system_colour)
1157 systopalette();
1158}
1159
1160/*
1161 * Override bit of defpal with colours from the system.
1162 * (NB that this takes a copy the system colours at the time this is called,
1163 * so subsequent colour scheme changes don't take effect. To fix that we'd
1164 * probably want to be using GetSysColorBrush() and the like.)
1165 */
1166static void systopalette(void)
1167{
1168 int i;
1169 static const struct { int nIndex; int norm; int bold; } or[] =
1170 {
cecb13f6 1171 { COLOR_WINDOWTEXT, 256, 257 }, /* Default Foreground */
1172 { COLOR_WINDOW, 258, 259 }, /* Default Background */
1173 { COLOR_HIGHLIGHTTEXT, 260, 260 }, /* Cursor Text */
1174 { COLOR_HIGHLIGHT, 261, 261 }, /* Cursor Colour */
26d1da7b 1175 };
1176
1177 for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1178 COLORREF colour = GetSysColor(or[i].nIndex);
1179 defpal[or[i].norm].rgbtRed =
1180 defpal[or[i].bold].rgbtRed = GetRValue(colour);
1181 defpal[or[i].norm].rgbtGreen =
1182 defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1183 defpal[or[i].norm].rgbtBlue =
1184 defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1185 }
374330e2 1186}
1187
1188/*
1189 * Set up the colour palette.
1190 */
32874aea 1191static void init_palette(void)
1192{
374330e2 1193 int i;
32874aea 1194 HDC hdc = GetDC(hwnd);
374330e2 1195 if (hdc) {
32874aea 1196 if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
3d88e64d 1197 /*
1198 * This is a genuine case where we must use smalloc
1199 * because the snew macros can't cope.
1200 */
374330e2 1201 logpal = smalloc(sizeof(*logpal)
1202 - sizeof(logpal->palPalEntry)
cecb13f6 1203 + NALLCOLOURS * sizeof(PALETTEENTRY));
374330e2 1204 logpal->palVersion = 0x300;
cecb13f6 1205 logpal->palNumEntries = NALLCOLOURS;
1206 for (i = 0; i < NALLCOLOURS; i++) {
374330e2 1207 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1208 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1209 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1210 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1211 }
32874aea 1212 pal = CreatePalette(logpal);
374330e2 1213 if (pal) {
32874aea 1214 SelectPalette(hdc, pal, FALSE);
1215 RealizePalette(hdc);
1216 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
374330e2 1217 }
1218 }
32874aea 1219 ReleaseDC(hwnd, hdc);
374330e2 1220 }
1221 if (pal)
cecb13f6 1222 for (i = 0; i < NALLCOLOURS; i++)
374330e2 1223 colours[i] = PALETTERGB(defpal[i].rgbtRed,
1224 defpal[i].rgbtGreen,
1225 defpal[i].rgbtBlue);
1226 else
cecb13f6 1227 for (i = 0; i < NALLCOLOURS; i++)
374330e2 1228 colours[i] = RGB(defpal[i].rgbtRed,
32874aea 1229 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
374330e2 1230}
1231
1232/*
f0fccd51 1233 * This is a wrapper to ExtTextOut() to force Windows to display
1234 * the precise glyphs we give it. Otherwise it would do its own
1235 * bidi and Arabic shaping, and we would end up uncertain which
1236 * characters it had put where.
1237 */
1238static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1239 unsigned short *lpString, UINT cbCount,
c6958dfe 1240 CONST INT *lpDx, int opaque)
f0fccd51 1241{
b7625258 1242#ifdef __LCC__
1243 /*
1244 * The LCC include files apparently don't supply the
1245 * GCP_RESULTSW type, but we can make do with GCP_RESULTS
1246 * proper: the differences aren't important to us (the only
1247 * variable-width string parameter is one we don't use anyway).
1248 */
1249 GCP_RESULTS gcpr;
1250#else
f0fccd51 1251 GCP_RESULTSW gcpr;
b7625258 1252#endif
f0fccd51 1253 char *buffer = snewn(cbCount*2+2, char);
1254 char *classbuffer = snewn(cbCount, char);
1255 memset(&gcpr, 0, sizeof(gcpr));
1256 memset(buffer, 0, cbCount*2+2);
1257 memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1258
1259 gcpr.lStructSize = sizeof(gcpr);
1260 gcpr.lpGlyphs = (void *)buffer;
44e975e0 1261 gcpr.lpClass = (void *)classbuffer;
f0fccd51 1262 gcpr.nGlyphs = cbCount;
1263
1264 GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
c6958dfe 1265 FLI_MASK | GCP_CLASSIN | GCP_DIACRITIC);
f0fccd51 1266
c6958dfe 1267 ExtTextOut(hdc, x, y,
1268 ETO_GLYPH_INDEX | ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1269 lprc, buffer, cbCount, lpDx);
f0fccd51 1270}
1271
1272/*
fe75e503 1273 * The exact_textout() wrapper, unfortunately, destroys the useful
1274 * Windows `font linking' behaviour: automatic handling of Unicode
1275 * code points not supported in this font by falling back to a font
1276 * which does contain them. Therefore, we adopt a multi-layered
1277 * approach: for any potentially-bidi text, we use exact_textout(),
1278 * and for everything else we use a simple ExtTextOut as we did
1279 * before exact_textout() was introduced.
1280 */
1281static void general_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1282 unsigned short *lpString, UINT cbCount,
1283 CONST INT *lpDx, int opaque)
1284{
1285 int i, j, xp, xn;
1286 RECT newrc;
1287
1288#ifdef FIXME_REMOVE_BEFORE_CHECKIN
1289int k;
1290debug(("general_textout: %d,%d", x, y));
1291for(k=0;k<cbCount;k++)debug((" U+%04X", lpString[k]));
1292debug(("\n rect: [%d,%d %d,%d]", lprc->left, lprc->top, lprc->right, lprc->bottom));
1293debug(("\n"));
1294#endif
1295
1296 xp = xn = x;
1297
62ddb51e 1298 for (i = 0; i < (int)cbCount ;) {
fe75e503 1299 int rtl = is_rtl(lpString[i]);
1300
1301 xn += lpDx[i];
1302
62ddb51e 1303 for (j = i+1; j < (int)cbCount; j++) {
fe75e503 1304 if (rtl != is_rtl(lpString[j]))
1305 break;
1306 xn += lpDx[j];
1307 }
1308
1309 /*
1310 * Now [i,j) indicates a maximal substring of lpString
1311 * which should be displayed using the same textout
1312 * function.
1313 */
1314 if (rtl) {
1315 newrc.left = lprc->left + xp - x;
1316 newrc.right = lprc->left + xn - x;
1317 newrc.top = lprc->top;
1318 newrc.bottom = lprc->bottom;
1319#ifdef FIXME_REMOVE_BEFORE_CHECKIN
1320{
1321int k;
1322debug((" exact_textout: %d,%d", xp, y));
1323for(k=0;k<j-i;k++)debug((" U+%04X", lpString[i+k]));
1324debug(("\n rect: [%d,%d %d,%d]\n", newrc.left, newrc.top, newrc.right, newrc.bottom));
1325}
1326#endif
1327 exact_textout(hdc, xp, y, &newrc, lpString+i, j-i, lpDx+i, opaque);
1328 } else {
1329#ifdef FIXME_REMOVE_BEFORE_CHECKIN
1330{
1331int k;
1332debug((" ExtTextOut : %d,%d", xp, y));
1333for(k=0;k<j-i;k++)debug((" U+%04X", lpString[i+k]));
1334debug(("\n rect: [%d,%d %d,%d]\n", newrc.left, newrc.top, newrc.right, newrc.bottom));
1335}
1336#endif
1337 newrc.left = lprc->left + xp - x;
1338 newrc.right = lprc->left + xn - x;
1339 newrc.top = lprc->top;
1340 newrc.bottom = lprc->bottom;
1341 ExtTextOutW(hdc, xp, y, ETO_CLIPPED | (opaque ? ETO_OPAQUE : 0),
1342 &newrc, lpString+i, j-i, lpDx+i);
1343 }
1344
1345 i = j;
1346 xp = xn;
1347 }
1348
1349#ifdef FIXME_REMOVE_BEFORE_CHECKIN
1350debug(("general_textout: done, xn=%d\n", xn));
1351#endif
e94dde39 1352 assert(xn - x >= lprc->right - lprc->left);
fe75e503 1353}
1354
1355/*
4eeb7d09 1356 * Initialise all the fonts we will need initially. There may be as many as
efd51845 1357 * three or as few as one. The other (potentially) twenty-one fonts are done
4eeb7d09 1358 * if/when they are needed.
1359 *
1360 * We also:
374330e2 1361 *
1362 * - check the font width and height, correcting our guesses if
1363 * necessary.
1364 *
1365 * - verify that the bold font is the same width as the ordinary
1366 * one, and engage shadow bolding if not.
1367 *
1368 * - verify that the underlined font is the same width as the
1369 * ordinary one (manual underlining by means of line drawing can
1370 * be done in a pinch).
374330e2 1371 */
5a73255e 1372static void init_fonts(int pick_width, int pick_height)
32874aea 1373{
374330e2 1374 TEXTMETRIC tm;
4eeb7d09 1375 CPINFO cpinfo;
1376 int fontsize[3];
97fc891e 1377 int i;
374330e2 1378 HDC hdc;
1379 int fw_dontcare, fw_bold;
1380
4eeb7d09 1381 for (i = 0; i < FONT_MAXNO; i++)
374330e2 1382 fonts[i] = NULL;
1383
5a73255e 1384 bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
1385 und_mode = UND_FONT;
1386
9a30e26b 1387 if (cfg.font.isbold) {
374330e2 1388 fw_dontcare = FW_BOLD;
5b80d07f 1389 fw_bold = FW_HEAVY;
32874aea 1390 } else {
374330e2 1391 fw_dontcare = FW_DONTCARE;
1392 fw_bold = FW_BOLD;
1393 }
1394
97fc891e 1395 hdc = GetDC(hwnd);
1396
5a73255e 1397 if (pick_height)
1398 font_height = pick_height;
1399 else {
9a30e26b 1400 font_height = cfg.font.height;
5a73255e 1401 if (font_height > 0) {
1402 font_height =
1403 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1404 }
3b2c664e 1405 }
59ad2c03 1406 font_width = pick_width;
97fc891e 1407
374330e2 1408#define f(i,c,w,u) \
97fc891e 1409 fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
374330e2 1410 c, OUT_DEFAULT_PRECIS, \
17c7fed1 1411 CLIP_DEFAULT_PRECIS, FONT_QUALITY(cfg.font_quality), \
9a30e26b 1412 FIXED_PITCH | FF_DONTCARE, cfg.font.name)
97fc891e 1413
9a30e26b 1414 f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);
97fc891e 1415
4eeb7d09 1416 SelectObject(hdc, fonts[FONT_NORMAL]);
1417 GetTextMetrics(hdc, &tm);
5a73255e 1418
fd64bb27 1419 GetObject(fonts[FONT_NORMAL], sizeof(LOGFONT), &lfont);
1420
5a73255e 1421 if (pick_width == 0 || pick_height == 0) {
1422 font_height = tm.tmHeight;
1423 font_width = tm.tmAveCharWidth;
1424 }
1425 font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1426
1427#ifdef RDB_DEBUG_PATCH
1428 debug(23, "Primary font H=%d, AW=%d, MW=%d",
1429 tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1430#endif
97fc891e 1431
4eeb7d09 1432 {
1433 CHARSETINFO info;
1434 DWORD cset = tm.tmCharSet;
1435 memset(&info, 0xFF, sizeof(info));
97fc891e 1436
4eeb7d09 1437 /* !!! Yes the next line is right */
1438 if (cset == OEM_CHARSET)
21d2b241 1439 ucsdata.font_codepage = GetOEMCP();
4eeb7d09 1440 else
21d2b241 1441 if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1442 ucsdata.font_codepage = info.ciACP;
4eeb7d09 1443 else
21d2b241 1444 ucsdata.font_codepage = -1;
32874aea 1445
21d2b241 1446 GetCPInfo(ucsdata.font_codepage, &cpinfo);
1447 ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
4eeb7d09 1448 }
97fc891e 1449
9a30e26b 1450 f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);
97fc891e 1451
4eeb7d09 1452 /*
1453 * Some fonts, e.g. 9-pt Courier, draw their underlines
1454 * outside their character cell. We successfully prevent
1455 * screen corruption by clipping the text output, but then
1456 * we lose the underline completely. Here we try to work
1457 * out whether this is such a font, and if it is, we set a
1458 * flag that causes underlines to be drawn by hand.
1459 *
1460 * Having tried other more sophisticated approaches (such
1461 * as examining the TEXTMETRIC structure or requesting the
1462 * height of a string), I think we'll do this the brute
1463 * force way: we create a small bitmap, draw an underlined
1464 * space on it, and test to see whether any pixels are
1465 * foreground-coloured. (Since we expect the underline to
1466 * go all the way across the character cell, we only search
1467 * down a single column of the bitmap, half way across.)
1468 */
1469 {
1470 HDC und_dc;
1471 HBITMAP und_bm, und_oldbm;
1472 int i, gotit;
1473 COLORREF c;
1474
1475 und_dc = CreateCompatibleDC(hdc);
1476 und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1477 und_oldbm = SelectObject(und_dc, und_bm);
1478 SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1479 SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1480 SetTextColor(und_dc, RGB(255, 255, 255));
1481 SetBkColor(und_dc, RGB(0, 0, 0));
1482 SetBkMode(und_dc, OPAQUE);
1483 ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1484 gotit = FALSE;
1485 for (i = 0; i < font_height; i++) {
1486 c = GetPixel(und_dc, font_width / 2, i);
1487 if (c != RGB(0, 0, 0))
1488 gotit = TRUE;
1489 }
1490 SelectObject(und_dc, und_oldbm);
1491 DeleteObject(und_bm);
1492 DeleteDC(und_dc);
1493 if (!gotit) {
1494 und_mode = UND_LINE;
1495 DeleteObject(fonts[FONT_UNDERLINE]);
1496 fonts[FONT_UNDERLINE] = 0;
32874aea 1497 }
4eeb7d09 1498 }
97fc891e 1499
4eeb7d09 1500 if (bold_mode == BOLD_FONT) {
9a30e26b 1501 f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);
374330e2 1502 }
1503#undef f
1504
97fc891e 1505 descent = tm.tmAscent + 1;
1506 if (descent >= font_height)
1507 descent = font_height - 1;
374330e2 1508
4eeb7d09 1509 for (i = 0; i < 3; i++) {
97fc891e 1510 if (fonts[i]) {
32874aea 1511 if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
4eeb7d09 1512 fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
32874aea 1513 else
4eeb7d09 1514 fontsize[i] = -i;
32874aea 1515 } else
4eeb7d09 1516 fontsize[i] = -i;
374330e2 1517 }
1518
32874aea 1519 ReleaseDC(hwnd, hdc);
374330e2 1520
4eeb7d09 1521 if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
374330e2 1522 und_mode = UND_LINE;
32874aea 1523 DeleteObject(fonts[FONT_UNDERLINE]);
4eeb7d09 1524 fonts[FONT_UNDERLINE] = 0;
374330e2 1525 }
1526
4eeb7d09 1527 if (bold_mode == BOLD_FONT &&
1528 fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
374330e2 1529 bold_mode = BOLD_SHADOW;
32874aea 1530 DeleteObject(fonts[FONT_BOLD]);
4eeb7d09 1531 fonts[FONT_BOLD] = 0;
374330e2 1532 }
4eeb7d09 1533 fontflag[0] = fontflag[1] = fontflag[2] = 1;
1534
21d2b241 1535 init_ucs(&cfg, &ucsdata);
4eeb7d09 1536}
1537
1538static void another_font(int fontno)
1539{
1540 int basefont;
1541 int fw_dontcare, fw_bold;
1542 int c, u, w, x;
1543 char *s;
1544
1545 if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1546 return;
1547
1548 basefont = (fontno & ~(FONT_BOLDUND));
1549 if (basefont != fontno && !fontflag[basefont])
1550 another_font(basefont);
97fc891e 1551
9a30e26b 1552 if (cfg.font.isbold) {
4eeb7d09 1553 fw_dontcare = FW_BOLD;
1554 fw_bold = FW_HEAVY;
1555 } else {
1556 fw_dontcare = FW_DONTCARE;
1557 fw_bold = FW_BOLD;
1558 }
1559
9a30e26b 1560 c = cfg.font.charset;
4eeb7d09 1561 w = fw_dontcare;
1562 u = FALSE;
9a30e26b 1563 s = cfg.font.name;
4eeb7d09 1564 x = font_width;
1565
1566 if (fontno & FONT_WIDE)
1567 x *= 2;
1568 if (fontno & FONT_NARROW)
5a73255e 1569 x = (x+1)/2;
4eeb7d09 1570 if (fontno & FONT_OEM)
1571 c = OEM_CHARSET;
1572 if (fontno & FONT_BOLD)
1573 w = fw_bold;
1574 if (fontno & FONT_UNDERLINE)
1575 u = TRUE;
1576
1577 fonts[fontno] =
1578 CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1579 FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
17c7fed1 1580 CLIP_DEFAULT_PRECIS, FONT_QUALITY(cfg.font_quality),
4eeb7d09 1581 FIXED_PITCH | FF_DONTCARE, s);
1582
1583 fontflag[fontno] = 1;
1584}
1585
1586static void deinit_fonts(void)
1587{
1588 int i;
1589 for (i = 0; i < FONT_MAXNO; i++) {
1590 if (fonts[i])
1591 DeleteObject(fonts[i]);
1592 fonts[i] = 0;
1593 fontflag[i] = 0;
374330e2 1594 }
1595}
1596
a8327734 1597void request_resize(void *frontend, int w, int h)
32874aea 1598{
59ad2c03 1599 int width, height;
c9def1b8 1600
1601 /* If the window is maximized supress resizing attempts */
5a73255e 1602 if (IsZoomed(hwnd)) {
0ed2f48e 1603 if (cfg.resize_action == RESIZE_TERM)
5a73255e 1604 return;
1605 }
32874aea 1606
ad5c93cc 1607 if (cfg.resize_action == RESIZE_DISABLED) return;
887035a5 1608 if (h == term->rows && w == term->cols) return;
5a73255e 1609
1610 /* Sanity checks ... */
1611 {
32874aea 1612 static int first_time = 1;
1613 static RECT ss;
1614
1615 switch (first_time) {
1616 case 1:
1617 /* Get the size of the screen */
d0f1bcb4 1618 if (get_fullscreen_rect(&ss))
32874aea 1619 /* first_time = 0 */ ;
1620 else {
1621 first_time = 2;
1622 break;
1623 }
1624 case 0:
1625 /* Make sure the values are sane */
5a73255e 1626 width = (ss.right - ss.left - extra_width) / 4;
1627 height = (ss.bottom - ss.top - extra_height) / 6;
32874aea 1628
5a73255e 1629 if (w > width || h > height)
1630 return;
32874aea 1631 if (w < 15)
1632 w = 15;
1633 if (h < 1)
5a73255e 1634 h = 1;
32874aea 1635 }
c9def1b8 1636 }
59ad2c03 1637
887035a5 1638 term_size(term, h, w, cfg.savelines);
5a73255e 1639
0ed2f48e 1640 if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {
5a73255e 1641 width = extra_width + font_width * w;
1642 height = extra_height + font_height * h;
374330e2 1643
5a73255e 1644 SetWindowPos(hwnd, NULL, 0, 0, width, height,
1645 SWP_NOACTIVATE | SWP_NOCOPYBITS |
1646 SWP_NOMOVE | SWP_NOZORDER);
1647 } else
1648 reset_window(0);
1649
1650 InvalidateRect(hwnd, NULL, TRUE);
1651}
1652
1653static void reset_window(int reinit) {
1654 /*
1655 * This function decides how to resize or redraw when the
1656 * user changes something.
1657 *
1658 * This function doesn't like to change the terminal size but if the
1659 * font size is locked that may be it's only soluion.
1660 */
1661 int win_width, win_height;
1662 RECT cr, wr;
1663
1664#ifdef RDB_DEBUG_PATCH
1665 debug((27, "reset_window()"));
1666#endif
1667
1668 /* Current window sizes ... */
1669 GetWindowRect(hwnd, &wr);
1670 GetClientRect(hwnd, &cr);
1671
1672 win_width = cr.right - cr.left;
1673 win_height = cr.bottom - cr.top;
1674
0ed2f48e 1675 if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;
1676
5a73255e 1677 /* Are we being forced to reload the fonts ? */
1678 if (reinit>1) {
1679#ifdef RDB_DEBUG_PATCH
1680 debug((27, "reset_window() -- Forced deinit"));
1681#endif
1682 deinit_fonts();
1683 init_fonts(0,0);
1684 }
1685
1686 /* Oh, looks like we're minimised */
1687 if (win_width == 0 || win_height == 0)
1688 return;
1689
1690 /* Is the window out of position ? */
1691 if ( !reinit &&
887035a5 1692 (offset_width != (win_width-font_width*term->cols)/2 ||
1693 offset_height != (win_height-font_height*term->rows)/2) ){
1694 offset_width = (win_width-font_width*term->cols)/2;
1695 offset_height = (win_height-font_height*term->rows)/2;
5a73255e 1696 InvalidateRect(hwnd, NULL, TRUE);
1697#ifdef RDB_DEBUG_PATCH
1698 debug((27, "reset_window() -> Reposition terminal"));
1699#endif
1700 }
1701
6003660f 1702 if (IsZoomed(hwnd)) {
5a73255e 1703 /* We're fullscreen, this means we must not change the size of
1704 * the window so it's the font size or the terminal itself.
1705 */
1706
1707 extra_width = wr.right - wr.left - cr.right + cr.left;
1708 extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1709
0ed2f48e 1710 if (cfg.resize_action != RESIZE_TERM) {
887035a5 1711 if ( font_width != win_width/term->cols ||
1712 font_height != win_height/term->rows) {
5a73255e 1713 deinit_fonts();
887035a5 1714 init_fonts(win_width/term->cols, win_height/term->rows);
1715 offset_width = (win_width-font_width*term->cols)/2;
1716 offset_height = (win_height-font_height*term->rows)/2;
5a73255e 1717 InvalidateRect(hwnd, NULL, TRUE);
1718#ifdef RDB_DEBUG_PATCH
1719 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1720 font_width, font_height));
1721#endif
1722 }
1723 } else {
1620020b 1724 if ( font_width * term->cols != win_width ||
1725 font_height * term->rows != win_height) {
5a73255e 1726 /* Our only choice at this point is to change the
1727 * size of the terminal; Oh well.
1728 */
887035a5 1729 term_size(term, win_height/font_height, win_width/font_width,
1730 cfg.savelines);
1731 offset_width = (win_width-font_width*term->cols)/2;
1732 offset_height = (win_height-font_height*term->rows)/2;
5a73255e 1733 InvalidateRect(hwnd, NULL, TRUE);
1734#ifdef RDB_DEBUG_PATCH
1735 debug((27, "reset_window() -> Zoomed term_size"));
1736#endif
1737 }
1738 }
1739 return;
1740 }
1741
1742 /* Hmm, a force re-init means we should ignore the current window
1743 * so we resize to the default font size.
1744 */
1745 if (reinit>0) {
1746#ifdef RDB_DEBUG_PATCH
1747 debug((27, "reset_window() -> Forced re-init"));
1748#endif
1749
1750 offset_width = offset_height = cfg.window_border;
1751 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1752 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1753
887035a5 1754 if (win_width != font_width*term->cols + offset_width*2 ||
1755 win_height != font_height*term->rows + offset_height*2) {
5a73255e 1756
1757 /* If this is too large windows will resize it to the maximum
1758 * allowed window size, we will then be back in here and resize
1759 * the font or terminal to fit.
1760 */
1761 SetWindowPos(hwnd, NULL, 0, 0,
887035a5 1762 font_width*term->cols + extra_width,
1763 font_height*term->rows + extra_height,
5a73255e 1764 SWP_NOMOVE | SWP_NOZORDER);
1765 }
0ed2f48e 1766
1767 InvalidateRect(hwnd, NULL, TRUE);
5a73255e 1768 return;
1769 }
1770
1771 /* Okay the user doesn't want us to change the font so we try the
1772 * window. But that may be too big for the screen which forces us
1773 * to change the terminal.
1774 */
0ed2f48e 1775 if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||
1776 (cfg.resize_action == RESIZE_EITHER && reinit<0) ||
1777 reinit>0) {
5a73255e 1778 offset_width = offset_height = cfg.window_border;
1779 extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1780 extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1781
887035a5 1782 if (win_width != font_width*term->cols + offset_width*2 ||
1783 win_height != font_height*term->rows + offset_height*2) {
5a73255e 1784
1785 static RECT ss;
1786 int width, height;
d0f1bcb4 1787
1788 get_fullscreen_rect(&ss);
5a73255e 1789
5a73255e 1790 width = (ss.right - ss.left - extra_width) / font_width;
1791 height = (ss.bottom - ss.top - extra_height) / font_height;
1792
1793 /* Grrr too big */
887035a5 1794 if ( term->rows > height || term->cols > width ) {
0ed2f48e 1795 if (cfg.resize_action == RESIZE_EITHER) {
1796 /* Make the font the biggest we can */
887035a5 1797 if (term->cols > width)
1798 font_width = (ss.right - ss.left - extra_width)
1799 / term->cols;
1800 if (term->rows > height)
1801 font_height = (ss.bottom - ss.top - extra_height)
1802 / term->rows;
0ed2f48e 1803
1804 deinit_fonts();
1805 init_fonts(font_width, font_height);
1806
1807 width = (ss.right - ss.left - extra_width) / font_width;
1808 height = (ss.bottom - ss.top - extra_height) / font_height;
1809 } else {
887035a5 1810 if ( height > term->rows ) height = term->rows;
1811 if ( width > term->cols ) width = term->cols;
1812 term_size(term, height, width, cfg.savelines);
5a73255e 1813#ifdef RDB_DEBUG_PATCH
0ed2f48e 1814 debug((27, "reset_window() -> term resize to (%d,%d)",
1815 height, width));
5a73255e 1816#endif
0ed2f48e 1817 }
5a73255e 1818 }
1819
1820 SetWindowPos(hwnd, NULL, 0, 0,
887035a5 1821 font_width*term->cols + extra_width,
1822 font_height*term->rows + extra_height,
5a73255e 1823 SWP_NOMOVE | SWP_NOZORDER);
1824
1825 InvalidateRect(hwnd, NULL, TRUE);
1826#ifdef RDB_DEBUG_PATCH
1827 debug((27, "reset_window() -> window resize to (%d,%d)",
887035a5 1828 font_width*term->cols + extra_width,
1829 font_height*term->rows + extra_height));
5a73255e 1830#endif
1831 }
1832 return;
1833 }
1834
1835 /* We're allowed to or must change the font but do we want to ? */
1836
887035a5 1837 if (font_width != (win_width-cfg.window_border*2)/term->cols ||
1838 font_height != (win_height-cfg.window_border*2)/term->rows) {
5a73255e 1839
1840 deinit_fonts();
887035a5 1841 init_fonts((win_width-cfg.window_border*2)/term->cols,
1842 (win_height-cfg.window_border*2)/term->rows);
1843 offset_width = (win_width-font_width*term->cols)/2;
1844 offset_height = (win_height-font_height*term->rows)/2;
5a73255e 1845
1846 extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1847 extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1848
1849 InvalidateRect(hwnd, NULL, TRUE);
1850#ifdef RDB_DEBUG_PATCH
1851 debug((25, "reset_window() -> font resize to (%d,%d)",
1852 font_width, font_height));
1853#endif
1854 }
374330e2 1855}
1856
a5ce2e9f 1857static void set_input_locale(HKL kl)
1858{
1859 char lbuf[20];
1860
1861 GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1862 lbuf, sizeof(lbuf));
1863
1864 kbd_codepage = atoi(lbuf);
1865}
1866
6908fed7 1867static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
32874aea 1868{
fdedf2c8 1869 int thistime = GetMessageTime();
1870
b90840c3 1871 if (send_raw_mouse && !(cfg.mouse_override && shift)) {
1872 lastbtn = MBT_NOTHING;
fc5b0934 1873 term_mouse(term, b, translate_button(b), MA_CLICK,
1874 x, y, shift, ctrl, alt);
01c034ad 1875 return;
1876 }
1877
fdedf2c8 1878 if (lastbtn == b && thistime - lasttime < dbltime) {
374330e2 1879 lastact = (lastact == MA_CLICK ? MA_2CLK :
1880 lastact == MA_2CLK ? MA_3CLK :
1881 lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1882 } else {
1883 lastbtn = b;
1884 lastact = MA_CLICK;
1885 }
1886 if (lastact != MA_NOTHING)
fc5b0934 1887 term_mouse(term, b, translate_button(b), lastact,
1888 x, y, shift, ctrl, alt);
fdedf2c8 1889 lasttime = thistime;
374330e2 1890}
1891
01c034ad 1892/*
1893 * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1894 * into a cooked one (SELECT, EXTEND, PASTE).
1895 */
2c02ed02 1896static Mouse_Button translate_button(Mouse_Button button)
32874aea 1897{
01c034ad 1898 if (button == MBT_LEFT)
1899 return MBT_SELECT;
1900 if (button == MBT_MIDDLE)
ebc0310d 1901 return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
01c034ad 1902 if (button == MBT_RIGHT)
ebc0310d 1903 return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
2d466ffd 1904 return 0; /* shouldn't happen */
01c034ad 1905}
1906
32874aea 1907static void show_mouseptr(int show)
1908{
755e0524 1909 /* NB that the counter in ShowCursor() is also frobbed by
1910 * update_mouse_pointer() */
554c540d 1911 static int cursor_visible = 1;
32874aea 1912 if (!cfg.hide_mouseptr) /* override if this feature disabled */
1913 show = 1;
554c540d 1914 if (cursor_visible && !show)
32874aea 1915 ShowCursor(FALSE);
554c540d 1916 else if (!cursor_visible && show)
32874aea 1917 ShowCursor(TRUE);
554c540d 1918 cursor_visible = show;
1919}
1920
6908fed7 1921static int is_alt_pressed(void)
1922{
1923 BYTE keystate[256];
1924 int r = GetKeyboardState(keystate);
1925 if (!r)
1926 return FALSE;
1927 if (keystate[VK_MENU] & 0x80)
1928 return TRUE;
1929 if (keystate[VK_RMENU] & 0x80)
1930 return TRUE;
1931 return FALSE;
1932}
1933
68f9b3d9 1934static int resizing;
1935
95587c73 1936void notify_remote_exit(void *fe)
1937{
1938 int exitcode;
1939
1940 if (!session_closed &&
1941 (exitcode = back->exitcode(backhandle)) >= 0) {
1942 /* Abnormal exits will already have set session_closed and taken
1943 * appropriate action. */
1944 if (cfg.close_on_exit == FORCE_ON ||
1945 (cfg.close_on_exit == AUTO && exitcode != INT_MAX)) {
1946 PostQuitMessage(0);
1947 } else {
1948 must_close_session = TRUE;
1949 session_closed = TRUE;
1950 /* exitcode == INT_MAX indicates that the connection was closed
1951 * by a fatal error, so an error box will be coming our way and
1952 * we should not generate this informational one. */
1953 if (exitcode != INT_MAX)
1954 MessageBox(hwnd, "Connection closed by remote host",
1955 appname, MB_OK | MB_ICONINFORMATION);
1956 }
1957 }
1958}
39934deb 1959
1960void timer_change_notify(long next)
1961{
1962 long ticks = next - GETTICKCOUNT();
1963 if (ticks <= 0) ticks = 1; /* just in case */
1964 KillTimer(hwnd, TIMING_TIMER_ID);
1965 SetTimer(hwnd, TIMING_TIMER_ID, ticks, NULL);
1966 timing_next_time = next;
1967}
1968
32874aea 1969static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1970 WPARAM wParam, LPARAM lParam)
1971{
374330e2 1972 HDC hdc;
374330e2 1973 static int ignore_clip = FALSE;
3ad8c6db 1974 static int need_backend_resize = FALSE;
1ba99d2c 1975 static int fullscr_on_max = FALSE;
19caf318 1976 static int processed_resize = FALSE;
d8a13f62 1977 static UINT last_mousemove = 0;
374330e2 1978
1979 switch (message) {
59ad2c03 1980 case WM_TIMER:
39934deb 1981 if ((UINT_PTR)wParam == TIMING_TIMER_ID) {
1982 long next;
1983
1984 KillTimer(hwnd, TIMING_TIMER_ID);
1985 if (run_timers(timing_next_time, &next)) {
1986 timer_change_notify(next);
1987 } else {
32874aea 1988 }
1989 }
59ad2c03 1990 return 0;
374330e2 1991 case WM_CREATE:
1992 break;
68130d34 1993 case WM_CLOSE:
f6f450e2 1994 {
1995 char *str;
1996 show_mouseptr(1);
1997 str = dupprintf("%s Exit Confirmation", appname);
1998 if (!cfg.warn_on_close || session_closed ||
1999 MessageBox(hwnd,
2000 "Are you sure you want to close this session?",
84d264cd 2001 str, MB_ICONWARNING | MB_OKCANCEL | MB_DEFBUTTON1)
76347f46 2002 == IDOK)
f6f450e2 2003 DestroyWindow(hwnd);
2004 sfree(str);
2005 }
68130d34 2006 return 0;
374330e2 2007 case WM_DESTROY:
32874aea 2008 show_mouseptr(1);
2009 PostQuitMessage(0);
374330e2 2010 return 0;
12745e35 2011 case WM_INITMENUPOPUP:
2012 if ((HMENU)wParam == savedsess_menu) {
2013 /* About to pop up Saved Sessions sub-menu.
2014 * Refresh the session list. */
2015 get_sesslist(&sesslist, FALSE); /* free */
2016 get_sesslist(&sesslist, TRUE);
2017 update_savedsess_menu();
2018 return 0;
2019 }
2020 break;
63be7767 2021 case WM_COMMAND:
6833a413 2022 case WM_SYSCOMMAND:
2023 switch (wParam & ~0xF) { /* low 4 bits reserved to Windows */
374330e2 2024 case IDM_SHOWLOG:
c5e9c988 2025 showeventlog(hwnd);
374330e2 2026 break;
2027 case IDM_NEWSESS:
2028 case IDM_DUPSESS:
6833a413 2029 case IDM_SAVEDSESS:
374330e2 2030 {
2031 char b[2048];
2032 char c[30], *cl;
e4e4cc7e 2033 int freecl = FALSE;
8e90e4c6 2034 BOOL inherit_handles;
374330e2 2035 STARTUPINFO si;
2036 PROCESS_INFORMATION pi;
2037 HANDLE filemap = NULL;
2038
2039 if (wParam == IDM_DUPSESS) {
2040 /*
2041 * Allocate a file-mapping memory chunk for the
2042 * config structure.
2043 */
2044 SECURITY_ATTRIBUTES sa;
2045 Config *p;
2046
2047 sa.nLength = sizeof(sa);
2048 sa.lpSecurityDescriptor = NULL;
2049 sa.bInheritHandle = TRUE;
4a0b6d61 2050 filemap = CreateFileMapping(INVALID_HANDLE_VALUE,
374330e2 2051 &sa,
2052 PAGE_READWRITE,
32874aea 2053 0, sizeof(Config), NULL);
4a0b6d61 2054 if (filemap && filemap != INVALID_HANDLE_VALUE) {
32874aea 2055 p = (Config *) MapViewOfFile(filemap,
2056 FILE_MAP_WRITE,
2057 0, 0, sizeof(Config));
374330e2 2058 if (p) {
2059 *p = cfg; /* structure copy */
2060 UnmapViewOfFile(p);
2061 }
2062 }
8e90e4c6 2063 inherit_handles = TRUE;
1d470ad2 2064 sprintf(c, "putty &%p", filemap);
374330e2 2065 cl = c;
0a4aa984 2066 } else if (wParam == IDM_SAVEDSESS) {
865e82ad 2067 unsigned int sessno = ((lParam - IDM_SAVED_MIN)
2068 / MENU_SAVED_STEP) + 1;
62ddb51e 2069 if (sessno < (unsigned)sesslist.nsessions) {
1f1e3232 2070 char *session = sesslist.sessions[sessno];
1f1e3232 2071 cl = dupprintf("putty @%s", session);
8e90e4c6 2072 inherit_handles = FALSE;
1f1e3232 2073 freecl = TRUE;
f8d7977b 2074 } else
2075 break;
8e90e4c6 2076 } else /* IDM_NEWSESS */ {
6833a413 2077 cl = NULL;
8e90e4c6 2078 inherit_handles = FALSE;
2079 }
374330e2 2080
32874aea 2081 GetModuleFileName(NULL, b, sizeof(b) - 1);
374330e2 2082 si.cb = sizeof(si);
2083 si.lpReserved = NULL;
2084 si.lpDesktop = NULL;
2085 si.lpTitle = NULL;
2086 si.dwFlags = 0;
2087 si.cbReserved2 = 0;
2088 si.lpReserved2 = NULL;
8e90e4c6 2089 CreateProcess(b, cl, NULL, NULL, inherit_handles,
32874aea 2090 NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
374330e2 2091
2092 if (filemap)
2093 CloseHandle(filemap);
e4e4cc7e 2094 if (freecl)
dcbde236 2095 sfree(cl);
374330e2 2096 }
2097 break;
e3be8de5 2098 case IDM_RESTART:
2099 if (!back) {
2100 logevent(NULL, "----- Session restarted -----");
900f9aca 2101 term_pwron(term, FALSE);
e3be8de5 2102 start_backend();
2103 }
2104
2105 break;
32874aea 2106 case IDM_RECONF:
2107 {
5a73255e 2108 Config prev_cfg;
2109 int init_lvl = 1;
68a66cc3 2110 int reconfig_result;
5a73255e 2111
359fd192 2112 if (reconfiguring)
68a66cc3 2113 break;
359fd192 2114 else
68a66cc3 2115 reconfiguring = TRUE;
359fd192 2116
32874aea 2117 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
5a73255e 2118 prev_cfg = cfg;
e1c8e0ed 2119
68a66cc3 2120 reconfig_result =
b56ff5c3 2121 do_reconfig(hwnd, back ? back->cfg_info(backhandle) : 0);
68a66cc3 2122 reconfiguring = FALSE;
2123 if (!reconfig_result)
32874aea 2124 break;
e1c8e0ed 2125
2cae8529 2126 {
2127 /* Disable full-screen if resizing forbidden */
52c70126 2128 int i;
2129 for (i = 0; i < lenof(popup_menus); i++)
2130 EnableMenuItem(popup_menus[i].menu, IDM_FULLSCREEN,
2131 MF_BYCOMMAND |
2132 (cfg.resize_action == RESIZE_DISABLED)
2133 ? MF_GRAYED : MF_ENABLED);
2cae8529 2134 /* Gracefully unzoom if necessary */
1ba99d2c 2135 if (IsZoomed(hwnd) &&
2cae8529 2136 (cfg.resize_action == RESIZE_DISABLED)) {
1ba99d2c 2137 ShowWindow(hwnd, SW_RESTORE);
2cae8529 2138 }
a401e5f3 2139 }
2140
c229ef97 2141 /* Pass new config data to the logging module */
2142 log_reconfig(logctx, &cfg);
e1c8e0ed 2143
32874aea 2144 sfree(logpal);
2145 /*
2146 * Flush the line discipline's edit buffer in the
2147 * case where local editing has just been disabled.
2148 */
e3be8de5 2149 if (ldisc)
2150 ldisc_send(ldisc, NULL, 0, 0);
32874aea 2151 if (pal)
2152 DeleteObject(pal);
2153 logpal = NULL;
2154 pal = NULL;
2155 cfgtopalette();
2156 init_palette();
2157
64734920 2158 /* Pass new config data to the terminal */
2159 term_reconfig(term, &cfg);
0d2086c5 2160
86916870 2161 /* Pass new config data to the back end */
e3be8de5 2162 if (back)
2163 back->reconfig(backhandle, &cfg);
86916870 2164
5a73255e 2165 /* Screen size changed ? */
2166 if (cfg.height != prev_cfg.height ||
2167 cfg.width != prev_cfg.width ||
2168 cfg.savelines != prev_cfg.savelines ||
0ed2f48e 2169 cfg.resize_action == RESIZE_FONT ||
811f10b3 2170 (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
0ed2f48e 2171 cfg.resize_action == RESIZE_DISABLED)
887035a5 2172 term_size(term, cfg.height, cfg.width, cfg.savelines);
5a73255e 2173
32874aea 2174 /* Enable or disable the scroll bar, etc */
2175 {
1e5eefb6 2176 LONG nflg, flag = GetWindowLongPtr(hwnd, GWL_STYLE);
32874aea 2177 LONG nexflag, exflag =
1e5eefb6 2178 GetWindowLongPtr(hwnd, GWL_EXSTYLE);
32874aea 2179
2180 nexflag = exflag;
5a73255e 2181 if (cfg.alwaysontop != prev_cfg.alwaysontop) {
32874aea 2182 if (cfg.alwaysontop) {
2183 nexflag |= WS_EX_TOPMOST;
2184 SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
2185 SWP_NOMOVE | SWP_NOSIZE);
2186 } else {
2187 nexflag &= ~(WS_EX_TOPMOST);
2188 SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
2189 SWP_NOMOVE | SWP_NOSIZE);
2190 }
2191 }
2192 if (cfg.sunken_edge)
2193 nexflag |= WS_EX_CLIENTEDGE;
2194 else
2195 nexflag &= ~(WS_EX_CLIENTEDGE);
2196
2197 nflg = flag;
1ba99d2c 2198 if (is_full_screen() ?
2cae8529 2199 cfg.scrollbar_in_fullscreen : cfg.scrollbar)
32874aea 2200 nflg |= WS_VSCROLL;
2201 else
2202 nflg &= ~WS_VSCROLL;
811f10b3 2203
2204 if (cfg.resize_action == RESIZE_DISABLED ||
2205 is_full_screen())
2206 nflg &= ~WS_THICKFRAME;
2207 else
2208 nflg |= WS_THICKFRAME;
2209
ad5c93cc 2210 if (cfg.resize_action == RESIZE_DISABLED)
811f10b3 2211 nflg &= ~WS_MAXIMIZEBOX;
32874aea 2212 else
811f10b3 2213 nflg |= WS_MAXIMIZEBOX;
32874aea 2214
2215 if (nflg != flag || nexflag != exflag) {
32874aea 2216 if (nflg != flag)
1e5eefb6 2217 SetWindowLongPtr(hwnd, GWL_STYLE, nflg);
32874aea 2218 if (nexflag != exflag)
1e5eefb6 2219 SetWindowLongPtr(hwnd, GWL_EXSTYLE, nexflag);
32874aea 2220
32874aea 2221 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2222 SWP_NOACTIVATE | SWP_NOCOPYBITS |
5a73255e 2223 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2224 SWP_FRAMECHANGED);
c9def1b8 2225
5a73255e 2226 init_lvl = 2;
e44d78b6 2227 }
32874aea 2228 }
5a73255e 2229
e44d78b6 2230 /* Oops */
ad5c93cc 2231 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
e44d78b6 2232 force_normal(hwnd);
5a73255e 2233 init_lvl = 2;
2234 }
2235
a8327734 2236 set_title(NULL, cfg.wintitle);
32874aea 2237 if (IsIconic(hwnd)) {
2238 SetWindowText(hwnd,
2239 cfg.win_name_always ? window_name :
2240 icon_name);
3da0b1d2 2241 }
5a73255e 2242
9a30e26b 2243 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
5a73255e 2244 strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
9a30e26b 2245 cfg.font.isbold != prev_cfg.font.isbold ||
2246 cfg.font.height != prev_cfg.font.height ||
2247 cfg.font.charset != prev_cfg.font.charset ||
17c7fed1 2248 cfg.font_quality != prev_cfg.font_quality ||
5a73255e 2249 cfg.vtmode != prev_cfg.vtmode ||
2250 cfg.bold_colour != prev_cfg.bold_colour ||
0ed2f48e 2251 cfg.resize_action == RESIZE_DISABLED ||
2252 cfg.resize_action == RESIZE_EITHER ||
2253 (cfg.resize_action != prev_cfg.resize_action))
5a73255e 2254 init_lvl = 2;
2255
2256 InvalidateRect(hwnd, NULL, TRUE);
2257 reset_window(init_lvl);
7732d38a 2258 net_pending_errors();
32874aea 2259 }
2260 break;
bc1235d4 2261 case IDM_COPYALL:
887035a5 2262 term_copyall(term);
bc1235d4 2263 break;
63be7767 2264 case IDM_PASTE:
e9609ce5 2265 request_paste(NULL);
63be7767 2266 break;
32874aea 2267 case IDM_CLRSB:
887035a5 2268 term_clrsb(term);
32874aea 2269 break;
2270 case IDM_RESET:
900f9aca 2271 term_pwron(term, TRUE);
e3be8de5 2272 if (ldisc)
2273 ldisc_send(ldisc, NULL, 0, 0);
32874aea 2274 break;
374330e2 2275 case IDM_ABOUT:
32874aea 2276 showabout(hwnd);
374330e2 2277 break;
70133c0e 2278 case IDM_HELP:
cb2708d3 2279 launch_help(hwnd, NULL);
70133c0e 2280 break;
0d6dcf38 2281 case SC_MOUSEMENU:
2282 /*
2283 * We get this if the System menu has been activated
2284 * using the mouse.
2285 */
2286 show_mouseptr(1);
2287 break;
dfca2656 2288 case SC_KEYMENU:
2289 /*
0d6dcf38 2290 * We get this if the System menu has been activated
2291 * using the keyboard. This might happen from within
2292 * TranslateKey, in which case it really wants to be
2293 * followed by a `space' character to actually _bring
2294 * the menu up_ rather than just sitting there in
2295 * `ready to appear' state.
dfca2656 2296 */
0d6dcf38 2297 show_mouseptr(1); /* make sure pointer is visible */
dfca2656 2298 if( lParam == 0 )
2299 PostMessage(hwnd, WM_CHAR, ' ', 0);
2300 break;
a401e5f3 2301 case IDM_FULLSCREEN:
1ba99d2c 2302 flip_full_screen();
2303 break;
32874aea 2304 default:
1f1e3232 2305 if (wParam >= IDM_SAVED_MIN && wParam < IDM_SAVED_MAX) {
32874aea 2306 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2307 }
125105d1 2308 if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2309 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
125105d1 2310 /*
2311 * Ensure we haven't been sent a bogus SYSCOMMAND
2312 * which would cause us to reference invalid memory
2313 * and crash. Perhaps I'm just too paranoid here.
2314 */
6f2d0cde 2315 if (i >= n_specials)
2316 break;
2317 if (back)
2318 back->special(backhandle, specials[i].code);
2319 net_pending_errors();
125105d1 2320 }
374330e2 2321 }
2322 break;
37508af4 2323
2324#define X_POS(l) ((int)(short)LOWORD(l))
2325#define Y_POS(l) ((int)(short)HIWORD(l))
2326
5a73255e 2327#define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2328#define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
374330e2 2329 case WM_LBUTTONDOWN:
374330e2 2330 case WM_MBUTTONDOWN:
374330e2 2331 case WM_RBUTTONDOWN:
01c034ad 2332 case WM_LBUTTONUP:
2333 case WM_MBUTTONUP:
374330e2 2334 case WM_RBUTTONUP:
ebc0310d 2335 if (message == WM_RBUTTONDOWN &&
2336 ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
63be7767 2337 POINT cursorpos;
2338
ebc0310d 2339 show_mouseptr(1); /* make sure pointer is visible */
63be7767 2340 GetCursorPos(&cursorpos);
2341 TrackPopupMenu(popup_menus[CTXMENU].menu,
2342 TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2343 cursorpos.x, cursorpos.y,
2344 0, hwnd, NULL);
2345 break;
2346 }
01c034ad 2347 {
2348 int button, press;
6908fed7 2349
01c034ad 2350 switch (message) {
32874aea 2351 case WM_LBUTTONDOWN:
2352 button = MBT_LEFT;
472f9eae 2353 wParam |= MK_LBUTTON;
32874aea 2354 press = 1;
2355 break;
2356 case WM_MBUTTONDOWN:
2357 button = MBT_MIDDLE;
472f9eae 2358 wParam |= MK_MBUTTON;
32874aea 2359 press = 1;
2360 break;
2361 case WM_RBUTTONDOWN:
2362 button = MBT_RIGHT;
472f9eae 2363 wParam |= MK_RBUTTON;
32874aea 2364 press = 1;
2365 break;
2366 case WM_LBUTTONUP:
2367 button = MBT_LEFT;
472f9eae 2368 wParam &= ~MK_LBUTTON;
32874aea 2369 press = 0;
2370 break;
2371 case WM_MBUTTONUP:
2372 button = MBT_MIDDLE;
472f9eae 2373 wParam &= ~MK_MBUTTON;
32874aea 2374 press = 0;
2375 break;
2376 case WM_RBUTTONUP:
2377 button = MBT_RIGHT;
472f9eae 2378 wParam &= ~MK_RBUTTON;
32874aea 2379 press = 0;
2380 break;
2d466ffd 2381 default:
2382 button = press = 0; /* shouldn't happen */
01c034ad 2383 }
2384 show_mouseptr(1);
2cae8529 2385 /*
2386 * Special case: in full-screen mode, if the left
2387 * button is clicked in the very top left corner of the
2388 * window, we put up the System menu instead of doing
2389 * selection.
2390 */
52a4d159 2391 {
2392 char mouse_on_hotspot = 0;
2393 POINT pt;
2394
2395 GetCursorPos(&pt);
2396#ifndef NO_MULTIMON
2397 {
2398 HMONITOR mon;
2399 MONITORINFO mi;
2400
2401 mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2402
2403 if (mon != NULL) {
2404 mi.cbSize = sizeof(MONITORINFO);
2405 GetMonitorInfo(mon, &mi);
2406
2407 if (mi.rcMonitor.left == pt.x &&
2408 mi.rcMonitor.top == pt.y) {
2409 mouse_on_hotspot = 1;
2410 }
52a4d159 2411 }
2412 }
2413#else
2414 if (pt.x == 0 && pt.y == 0) {
2415 mouse_on_hotspot = 1;
2416 }
2417#endif
2418 if (is_full_screen() && press &&
2419 button == MBT_LEFT && mouse_on_hotspot) {
2420 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2421 MAKELPARAM(pt.x, pt.y));
2422 return 0;
2423 }
2cae8529 2424 }
52a4d159 2425
01c034ad 2426 if (press) {
32874aea 2427 click(button,
2428 TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
6908fed7 2429 wParam & MK_SHIFT, wParam & MK_CONTROL,
2430 is_alt_pressed());
01c034ad 2431 SetCapture(hwnd);
2432 } else {
fc5b0934 2433 term_mouse(term, button, translate_button(button), MA_RELEASE,
32874aea 2434 TO_CHR_X(X_POS(lParam)),
2435 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
6908fed7 2436 wParam & MK_CONTROL, is_alt_pressed());
472f9eae 2437 if (!(wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)))
2438 ReleaseCapture();
01c034ad 2439 }
2440 }
374330e2 2441 return 0;
2442 case WM_MOUSEMOVE:
d8a13f62 2443 {
2444 /*
2445 * Windows seems to like to occasionally send MOUSEMOVE
2446 * events even if the mouse hasn't moved. Don't unhide
2447 * the mouse pointer in this case.
2448 */
2449 static WPARAM wp = 0;
2450 static LPARAM lp = 0;
2451 if (wParam != wp || lParam != lp ||
2452 last_mousemove != WM_MOUSEMOVE) {
2453 show_mouseptr(1);
2454 wp = wParam; lp = lParam;
2455 last_mousemove = WM_MOUSEMOVE;
2456 }
2457 }
374330e2 2458 /*
2459 * Add the mouse position and message time to the random
7d6ee6ff 2460 * number noise.
374330e2 2461 */
32874aea 2462 noise_ultralight(lParam);
374330e2 2463
319bfe5a 2464 if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2465 GetCapture() == hwnd) {
374330e2 2466 Mouse_Button b;
2467 if (wParam & MK_LBUTTON)
6c6e7711 2468 b = MBT_LEFT;
374330e2 2469 else if (wParam & MK_MBUTTON)
6c6e7711 2470 b = MBT_MIDDLE;
374330e2 2471 else
6c6e7711 2472 b = MBT_RIGHT;
fc5b0934 2473 term_mouse(term, b, translate_button(b), MA_DRAG,
2474 TO_CHR_X(X_POS(lParam)),
32874aea 2475 TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
6908fed7 2476 wParam & MK_CONTROL, is_alt_pressed());
374330e2 2477 }
374330e2 2478 return 0;
d318ef8e 2479 case WM_NCMOUSEMOVE:
d8a13f62 2480 {
2481 static WPARAM wp = 0;
2482 static LPARAM lp = 0;
2483 if (wParam != wp || lParam != lp ||
2484 last_mousemove != WM_NCMOUSEMOVE) {
2485 show_mouseptr(1);
2486 wp = wParam; lp = lParam;
2487 last_mousemove = WM_NCMOUSEMOVE;
2488 }
2489 }
32874aea 2490 noise_ultralight(lParam);
f9cbc48c 2491 break;
374330e2 2492 case WM_IGNORE_CLIP:
2493 ignore_clip = wParam; /* don't panic on DESTROYCLIPBOARD */
2494 break;
2495 case WM_DESTROYCLIPBOARD:
2496 if (!ignore_clip)
887035a5 2497 term_deselect(term);
374330e2 2498 ignore_clip = FALSE;
2499 return 0;
2500 case WM_PAINT:
2501 {
2502 PAINTSTRUCT p;
39934deb 2503
32874aea 2504 HideCaret(hwnd);
2505 hdc = BeginPaint(hwnd, &p);
374330e2 2506 if (pal) {
32874aea 2507 SelectPalette(hdc, pal, TRUE);
2508 RealizePalette(hdc);
374330e2 2509 }
39934deb 2510
8788a416 2511 /*
2512 * We have to be careful about term_paint(). It will
2513 * set a bunch of character cells to INVALID and then
2514 * call do_paint(), which will redraw those cells and
2515 * _then mark them as done_. This may not be accurate:
2516 * when painting in WM_PAINT context we are restricted
2517 * to the rectangle which has just been exposed - so if
2518 * that only covers _part_ of a character cell and the
2519 * rest of it was already visible, that remainder will
2520 * not be redrawn at all. Accordingly, we must not
2521 * paint any character cell in a WM_PAINT context which
2522 * already has a pending update due to terminal output.
2523 * The simplest solution to this - and many, many
2524 * thanks to Hung-Te Lin for working all this out - is
2525 * not to do any actual painting at _all_ if there's a
2526 * pending terminal update: just mark the relevant
2527 * character cells as INVALID and wait for the
2528 * scheduled full update to sort it out.
2529 *
2530 * I have a suspicion this isn't the _right_ solution.
2531 * An alternative approach would be to have terminal.c
2532 * separately track what _should_ be on the terminal
2533 * screen and what _is_ on the terminal screen, and
2534 * have two completely different types of redraw (one
2535 * for full updates, which syncs the former with the
2536 * terminal itself, and one for WM_PAINT which syncs
2537 * the latter with the former); yet another possibility
2538 * would be to have the Windows front end do what the
2539 * GTK one already does, and maintain a bitmap of the
2540 * current terminal appearance so that WM_PAINT becomes
2541 * completely trivial. However, this should do for now.
2542 */
887035a5 2543 term_paint(term, hdc,
5a73255e 2544 (p.rcPaint.left-offset_width)/font_width,
2545 (p.rcPaint.top-offset_height)/font_height,
2546 (p.rcPaint.right-offset_width-1)/font_width,
c1b55581 2547 (p.rcPaint.bottom-offset_height-1)/font_height,
8788a416 2548 !term->window_update_pending);
5a73255e 2549
2550 if (p.fErase ||
2551 p.rcPaint.left < offset_width ||
2552 p.rcPaint.top < offset_height ||
887035a5 2553 p.rcPaint.right >= offset_width + font_width*term->cols ||
2554 p.rcPaint.bottom>= offset_height + font_height*term->rows)
5a73255e 2555 {
2556 HBRUSH fillcolour, oldbrush;
2557 HPEN edge, oldpen;
2558 fillcolour = CreateSolidBrush (
c50f9fde 2559 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
5a73255e 2560 oldbrush = SelectObject(hdc, fillcolour);
2561 edge = CreatePen(PS_SOLID, 0,
c50f9fde 2562 colours[ATTR_DEFBG>>ATTR_BGSHIFT]);
5a73255e 2563 oldpen = SelectObject(hdc, edge);
2564
bfa7a5db 2565 /*
2566 * Jordan Russell reports that this apparently
2567 * ineffectual IntersectClipRect() call masks a
2568 * Windows NT/2K bug causing strange display
2569 * problems when the PuTTY window is taller than
2570 * the primary monitor. It seems harmless enough...
2571 */
2572 IntersectClipRect(hdc,
2573 p.rcPaint.left, p.rcPaint.top,
2574 p.rcPaint.right, p.rcPaint.bottom);
2575
5a73255e 2576 ExcludeClipRect(hdc,
2577 offset_width, offset_height,
887035a5 2578 offset_width+font_width*term->cols,
2579 offset_height+font_height*term->rows);
5a73255e 2580
2581 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top,
2582 p.rcPaint.right, p.rcPaint.bottom);
2583
31fb1866 2584 /* SelectClipRgn(hdc, NULL); */
5a73255e 2585
2586 SelectObject(hdc, oldbrush);
2587 DeleteObject(fillcolour);
2588 SelectObject(hdc, oldpen);
2589 DeleteObject(edge);
2590 }
32874aea 2591 SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2592 SelectObject(hdc, GetStockObject(WHITE_PEN));
2593 EndPaint(hwnd, &p);
2594 ShowCaret(hwnd);
374330e2 2595 }
2596 return 0;
2597 case WM_NETEVENT:
56f8ea28 2598 /* Notice we can get multiple netevents, FD_READ, FD_WRITE etc
2599 * but the only one that's likely to try to overload us is FD_READ.
2600 * This means buffering just one is fine.
2601 */
2602 if (pending_netevent)
2603 enact_pending_netevent();
2604
2605 pending_netevent = TRUE;
2606 pend_netevent_wParam = wParam;
2607 pend_netevent_lParam = lParam;
2608 if (WSAGETSELECTEVENT(lParam) != FD_READ)
2609 enact_pending_netevent();
2610
39934deb 2611 net_pending_errors();
374330e2 2612 return 0;
2613 case WM_SETFOCUS:
1cff1320 2614 term_set_focus(term, TRUE);
32874aea 2615 CreateCaret(hwnd, caretbm, font_width, font_height);
2616 ShowCaret(hwnd);
f8a28d1f 2617 flash_window(0); /* stop */
32874aea 2618 compose_state = 0;
887035a5 2619 term_update(term);
374330e2 2620 break;
2621 case WM_KILLFOCUS:
32874aea 2622 show_mouseptr(1);
1cff1320 2623 term_set_focus(term, FALSE);
32874aea 2624 DestroyCaret();
c1da5066 2625 caret_x = caret_y = -1; /* ensure caret is replaced next time */
887035a5 2626 term_update(term);
374330e2 2627 break;
73251d5d 2628 case WM_ENTERSIZEMOVE:
5a73255e 2629#ifdef RDB_DEBUG_PATCH
2630 debug((27, "WM_ENTERSIZEMOVE"));
2631#endif
32874aea 2632 EnableSizeTip(1);
2633 resizing = TRUE;
3ad8c6db 2634 need_backend_resize = FALSE;
32874aea 2635 break;
73251d5d 2636 case WM_EXITSIZEMOVE:
32874aea 2637 EnableSizeTip(0);
2638 resizing = FALSE;
5a73255e 2639#ifdef RDB_DEBUG_PATCH
2640 debug((27, "WM_EXITSIZEMOVE"));
2641#endif
2642 if (need_backend_resize) {
887035a5 2643 term_size(term, cfg.height, cfg.width, cfg.savelines);
5a73255e 2644 InvalidateRect(hwnd, NULL, TRUE);
2645 }
32874aea 2646 break;
374330e2 2647 case WM_SIZING:
5a73255e 2648 /*
2649 * This does two jobs:
2650 * 1) Keep the sizetip uptodate
2651 * 2) Make sure the window size is _stepped_ in units of the font size.
2652 */
47779c35 2653 if (cfg.resize_action == RESIZE_TERM ||
2654 (cfg.resize_action == RESIZE_EITHER && !is_alt_pressed())) {
374330e2 2655 int width, height, w, h, ew, eh;
32874aea 2656 LPRECT r = (LPRECT) lParam;
374330e2 2657
0ed2f48e 2658 if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
887035a5 2659 (cfg.height != term->rows || cfg.width != term->cols )) {
5a73255e 2660 /*
0ed2f48e 2661 * Great! It seems that both the terminal size and the
2662 * font size have been changed and the user is now dragging.
2663 *
2664 * It will now be difficult to get back to the configured
2665 * font size!
2666 *
2667 * This would be easier but it seems to be too confusing.
2668
887035a5 2669 term_size(term, cfg.height, cfg.width, cfg.savelines);
5a73255e 2670 reset_window(2);
0ed2f48e 2671 */
887035a5 2672 cfg.height=term->rows; cfg.width=term->cols;
0ed2f48e 2673
5a73255e 2674 InvalidateRect(hwnd, NULL, TRUE);
2675 need_backend_resize = TRUE;
2676 }
2677
374330e2 2678 width = r->right - r->left - extra_width;
2679 height = r->bottom - r->top - extra_height;
32874aea 2680 w = (width + font_width / 2) / font_width;
2681 if (w < 1)
2682 w = 1;
2683 h = (height + font_height / 2) / font_height;
2684 if (h < 1)
2685 h = 1;
2686 UpdateSizeTip(hwnd, w, h);
374330e2 2687 ew = width - w * font_width;
2688 eh = height - h * font_height;
2689 if (ew != 0) {
2690 if (wParam == WMSZ_LEFT ||
32874aea 2691 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
374330e2 2692 r->left += ew;
2693 else
2694 r->right -= ew;
2695 }
2696 if (eh != 0) {
2697 if (wParam == WMSZ_TOP ||
32874aea 2698 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
374330e2 2699 r->top += eh;
2700 else
2701 r->bottom -= eh;
2702 }
2703 if (ew || eh)
2704 return 1;
2705 else
2706 return 0;
5a73255e 2707 } else {
2708 int width, height, w, h, rv = 0;
2709 int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2710 int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2711 LPRECT r = (LPRECT) lParam;
2712
2713 width = r->right - r->left - ex_width;
2714 height = r->bottom - r->top - ex_height;
2715
887035a5 2716 w = (width + term->cols/2)/term->cols;
2717 h = (height + term->rows/2)/term->rows;
2718 if ( r->right != r->left + w*term->cols + ex_width)
5a73255e 2719 rv = 1;
2720
2721 if (wParam == WMSZ_LEFT ||
2722 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
887035a5 2723 r->left = r->right - w*term->cols - ex_width;
5a73255e 2724 else
887035a5 2725 r->right = r->left + w*term->cols + ex_width;
5a73255e 2726
887035a5 2727 if (r->bottom != r->top + h*term->rows + ex_height)
5a73255e 2728 rv = 1;
2729
2730 if (wParam == WMSZ_TOP ||
2731 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
887035a5 2732 r->top = r->bottom - h*term->rows - ex_height;
5a73255e 2733 else
887035a5 2734 r->bottom = r->top + h*term->rows + ex_height;
5a73255e 2735
2736 return rv;
374330e2 2737 }
32874aea 2738 /* break; (never reached) */
1ba99d2c 2739 case WM_FULLSCR_ON_MAX:
2740 fullscr_on_max = TRUE;
2741 break;
c1da5066 2742 case WM_MOVE:
2743 sys_cursor_update();
2744 break;
374330e2 2745 case WM_SIZE:
5a73255e 2746#ifdef RDB_DEBUG_PATCH
2747 debug((27, "WM_SIZE %s (%d,%d)",
2748 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2749 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2750 (wParam == SIZE_RESTORED && resizing) ? "to":
2751 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2752 "...",
2753 LOWORD(lParam), HIWORD(lParam)));
2754#endif
0ed2f48e 2755 if (wParam == SIZE_MINIMIZED)
32874aea 2756 SetWindowText(hwnd,
2757 cfg.win_name_always ? window_name : icon_name);
374330e2 2758 if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
32874aea 2759 SetWindowText(hwnd, window_name);
19caf318 2760 if (wParam == SIZE_RESTORED) {
2761 processed_resize = FALSE;
811f10b3 2762 clear_full_screen();
19caf318 2763 if (processed_resize) {
2764 /*
2765 * Inhibit normal processing of this WM_SIZE; a
2766 * secondary one was triggered just now by
2767 * clear_full_screen which contained the correct
2768 * client area size.
2769 */
2770 return 0;
2771 }
2772 }
811f10b3 2773 if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
811f10b3 2774 fullscr_on_max = FALSE;
19caf318 2775 processed_resize = FALSE;
d0f1bcb4 2776 make_full_screen();
19caf318 2777 if (processed_resize) {
2778 /*
2779 * Inhibit normal processing of this WM_SIZE; a
2780 * secondary one was triggered just now by
2781 * make_full_screen which contained the correct client
2782 * area size.
2783 */
2784 return 0;
2785 }
811f10b3 2786 }
5a73255e 2787
19caf318 2788 processed_resize = TRUE;
2789
ad5c93cc 2790 if (cfg.resize_action == RESIZE_DISABLED) {
5a73255e 2791 /* A resize, well it better be a minimize. */
2792 reset_window(-1);
2793 } else {
2794
1a6f78fe 2795 int width, height, w, h;
374330e2 2796
2797 width = LOWORD(lParam);
2798 height = HIWORD(lParam);
5a73255e 2799
232c6eac 2800 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2801 was_zoomed = 1;
2802 prev_rows = term->rows;
2803 prev_cols = term->cols;
2804 if (cfg.resize_action == RESIZE_TERM) {
2805 w = width / font_width;
2806 if (w < 1) w = 1;
2807 h = height / font_height;
2808 if (h < 1) h = 1;
2809
2810 term_size(term, h, w, cfg.savelines);
2811 }
2812 reset_window(0);
2813 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2814 was_zoomed = 0;
754fa076 2815 if (cfg.resize_action == RESIZE_TERM) {
2816 w = (width-cfg.window_border*2) / font_width;
2817 if (w < 1) w = 1;
2818 h = (height-cfg.window_border*2) / font_height;
2819 if (h < 1) h = 1;
2820 term_size(term, h, w, cfg.savelines);
4e05e104 2821 reset_window(2);
754fa076 2822 } else if (cfg.resize_action != RESIZE_FONT)
232c6eac 2823 reset_window(2);
2824 else
2825 reset_window(0);
2826 } else if (wParam == SIZE_MINIMIZED) {
2827 /* do nothing */
47779c35 2828 } else if (cfg.resize_action == RESIZE_TERM ||
2829 (cfg.resize_action == RESIZE_EITHER &&
2830 !is_alt_pressed())) {
232c6eac 2831 w = (width-cfg.window_border*2) / font_width;
2832 if (w < 1) w = 1;
2833 h = (height-cfg.window_border*2) / font_height;
2834 if (h < 1) h = 1;
2835
2836 if (resizing) {
2837 /*
2838 * Don't call back->size in mid-resize. (To
2839 * prevent massive numbers of resize events
2840 * getting sent down the connection during an NT
2841 * opaque drag.)
2842 */
3ad8c6db 2843 need_backend_resize = TRUE;
e44d78b6 2844 cfg.height = h;
2845 cfg.width = w;
232c6eac 2846 } else {
2847 term_size(term, h, w, cfg.savelines);
2848 }
2849 } else {
2850 reset_window(0);
374330e2 2851 }
2852 }
c1da5066 2853 sys_cursor_update();
374330e2 2854 return 0;
2855 case WM_VSCROLL:
2856 switch (LOWORD(wParam)) {
32874aea 2857 case SB_BOTTOM:
887035a5 2858 term_scroll(term, -1, 0);
32874aea 2859 break;
2860 case SB_TOP:
887035a5 2861 term_scroll(term, +1, 0);
32874aea 2862 break;
2863 case SB_LINEDOWN:
887035a5 2864 term_scroll(term, 0, +1);
32874aea 2865 break;
2866 case SB_LINEUP:
887035a5 2867 term_scroll(term, 0, -1);
32874aea 2868 break;
2869 case SB_PAGEDOWN:
887035a5 2870 term_scroll(term, 0, +term->rows / 2);
32874aea 2871 break;
2872 case SB_PAGEUP:
887035a5 2873 term_scroll(term, 0, -term->rows / 2);
32874aea 2874 break;
2875 case SB_THUMBPOSITION:
2876 case SB_THUMBTRACK:
887035a5 2877 term_scroll(term, 1, HIWORD(wParam));
32874aea 2878 break;
2879 }
2880 break;
2881 case WM_PALETTECHANGED:
374330e2 2882 if ((HWND) wParam != hwnd && pal != NULL) {
a8327734 2883 HDC hdc = get_ctx(NULL);
374330e2 2884 if (hdc) {
32874aea 2885 if (RealizePalette(hdc) > 0)
2886 UpdateColors(hdc);
2887 free_ctx(hdc);
374330e2 2888 }
2889 }
2890 break;
2891 case WM_QUERYNEWPALETTE:
2892 if (pal != NULL) {
a8327734 2893 HDC hdc = get_ctx(NULL);
374330e2 2894 if (hdc) {
32874aea 2895 if (RealizePalette(hdc) > 0)
2896 UpdateColors(hdc);
2897 free_ctx(hdc);
374330e2 2898 return TRUE;
2899 }
2900 }
2901 return FALSE;
2902 case WM_KEYDOWN:
2903 case WM_SYSKEYDOWN:
c9def1b8 2904 case WM_KEYUP:
2905 case WM_SYSKEYUP:
374330e2 2906 /*
2907 * Add the scan code and keypress timing to the random
7d6ee6ff 2908 * number noise.
374330e2 2909 */
32874aea 2910 noise_ultralight(lParam);
374330e2 2911
2912 /*
2913 * We don't do TranslateMessage since it disassociates the
2914 * resulting CHAR message from the KEYDOWN that sparked it,
2915 * which we occasionally don't want. Instead, we process
2916 * KEYDOWN, and call the Win32 translator functions so that
2917 * we get the translations under _our_ control.
2918 */
2919 {
2920 unsigned char buf[20];
2921 int len;
2922
43e95114 2923 if (wParam == VK_PROCESSKEY) { /* IME PROCESS key */
2924 if (message == WM_KEYDOWN) {
2925 MSG m;
2926 m.hwnd = hwnd;
2927 m.message = WM_KEYDOWN;
2928 m.wParam = wParam;
2929 m.lParam = lParam & 0xdfff;
2930 TranslateMessage(&m);
2931 } else break; /* pass to Windows for default processing */
32874aea 2932 } else {
2933 len = TranslateKey(message, wParam, lParam, buf);
3cf144db 2934 if (len == -1)
32874aea 2935 return DefWindowProc(hwnd, message, wParam, lParam);
5471d09a 2936
b2a1eade 2937 if (len != 0) {
bca9517a 2938 /*
256cb87c 2939 * Interrupt an ongoing paste. I'm not sure
2940 * this is sensible, but for the moment it's
2941 * preferable to having to faff about buffering
2942 * things.
2943 */
887035a5 2944 term_nopaste(term);
256cb87c 2945
2946 /*
bca9517a 2947 * We need not bother about stdin backlogs
2948 * here, because in GUI PuTTY we can't do
2949 * anything about it anyway; there's no means
2950 * of asking Windows to hold off on KEYDOWN
2951 * messages. We _have_ to buffer everything
2952 * we're sent.
2953 */
887035a5 2954 term_seen_key_event(term);
e3be8de5 2955 if (ldisc)
2956 ldisc_send(ldisc, buf, len, 1);
32874aea 2957 show_mouseptr(0);
bca9517a 2958 }
3cf144db 2959 }
374330e2 2960 }
7732d38a 2961 net_pending_errors();
374330e2 2962 return 0;
4eeb7d09 2963 case WM_INPUTLANGCHANGE:
a5ce2e9f 2964 /* wParam == Font number */
2965 /* lParam == Locale */
2966 set_input_locale((HKL)lParam);
c1da5066 2967 sys_cursor_update();
4eeb7d09 2968 break;
fd64bb27 2969 case WM_IME_STARTCOMPOSITION:
2970 {
71f6951d 2971 HIMC hImc = ImmGetContext(hwnd);
2972 ImmSetCompositionFont(hImc, &lfont);
2973 ImmReleaseContext(hwnd, hImc);
71f6951d 2974 }
2975 break;
88485e4d 2976 case WM_IME_COMPOSITION:
2977 {
2978 HIMC hIMC;
2979 int n;
2980 char *buff;
a3cfd0c8 2981
88485e4d 2982 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ||
2983 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2984
2985 if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2986 break; /* fall back to DefWindowProc */
2987
2988 hIMC = ImmGetContext(hwnd);
2989 n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2990
2991 if (n > 0) {
a3cfd0c8 2992 int i;
3d88e64d 2993 buff = snewn(n, char);
88485e4d 2994 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
a3cfd0c8 2995 /*
2996 * Jaeyoun Chung reports that Korean character
2997 * input doesn't work correctly if we do a single
2998 * luni_send() covering the whole of buff. So
2999 * instead we luni_send the characters one by one.
3000 */
887035a5 3001 term_seen_key_event(term);
2cb50250 3002 for (i = 0; i < n; i += 2) {
e3be8de5 3003 if (ldisc)
3004 luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2cb50250 3005 }
88485e4d 3006 free(buff);
3007 }
3008 ImmReleaseContext(hwnd, hIMC);
3009 return 1;
3010 }
3011
4eeb7d09 3012 case WM_IME_CHAR:
3013 if (wParam & 0xFF00) {
3cf144db 3014 unsigned char buf[2];
3015
3016 buf[1] = wParam;
3017 buf[0] = wParam >> 8;
887035a5 3018 term_seen_key_event(term);
e3be8de5 3019 if (ldisc)
3020 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
4eeb7d09 3021 } else {
3022 char c = (unsigned char) wParam;
887035a5 3023 term_seen_key_event(term);
e3be8de5 3024 if (ldisc)
3025 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
3cf144db 3026 }
4eeb7d09 3027 return (0);
374330e2 3028 case WM_CHAR:
3029 case WM_SYSCHAR:
3030 /*
3031 * Nevertheless, we are prepared to deal with WM_CHAR
3032 * messages, should they crop up. So if someone wants to
3033 * post the things to us as part of a macro manoeuvre,
3034 * we're ready to cope.
3035 */
32874aea 3036 {
4eeb7d09 3037 char c = (unsigned char)wParam;
887035a5 3038 term_seen_key_event(term);
e3be8de5 3039 if (ldisc)
3040 lpage_send(ldisc, CP_ACP, &c, 1, 1);
374330e2 3041 }
3042 return 0;
49a332ff 3043 case WM_SYSCOLORCHANGE:
3044 if (cfg.system_colour) {
3045 /* Refresh palette from system colours. */
3046 /* XXX actually this zaps the entire palette. */
3047 systopalette();
3048 init_palette();
3049 /* Force a repaint of the terminal window. */
3050 term_invalidate(term);
3051 }
3052 break;
c44bf5bd 3053 case WM_AGENT_CALLBACK:
3054 {
3055 struct agent_callback *c = (struct agent_callback *)lParam;
3056 c->callback(c->callback_ctx, c->data, c->len);
3057 sfree(c);
3058 }
3059 return 0;
1d432454 3060 case WM_GOT_CLIPDATA:
3061 if (process_clipdata((HGLOBAL)lParam, wParam))
3062 term_do_paste(term);
3063 return 0;
011b0e33 3064 default:
16837214 3065 if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
c1b55581 3066 int shift_pressed=0, control_pressed=0;
011b0e33 3067
3068 if (message == WM_MOUSEWHEEL) {
3069 wheel_accumulator += (short)HIWORD(wParam);
3070 shift_pressed=LOWORD(wParam) & MK_SHIFT;
3071 control_pressed=LOWORD(wParam) & MK_CONTROL;
3072 } else {
3073 BYTE keys[256];
3074 wheel_accumulator += (int)wParam;
3075 if (GetKeyboardState(keys)!=0) {
3076 shift_pressed=keys[VK_SHIFT]&0x80;
3077 control_pressed=keys[VK_CONTROL]&0x80;
3078 }
3079 }
3080
3081 /* process events when the threshold is reached */
3082 while (abs(wheel_accumulator) >= WHEEL_DELTA) {
3083 int b;
3084
3085 /* reduce amount for next time */
3086 if (wheel_accumulator > 0) {
3087 b = MBT_WHEEL_UP;
3088 wheel_accumulator -= WHEEL_DELTA;
3089 } else if (wheel_accumulator < 0) {
3090 b = MBT_WHEEL_DOWN;
3091 wheel_accumulator += WHEEL_DELTA;
3092 } else
3093 break;
3094
3095 if (send_raw_mouse &&
3096 !(cfg.mouse_override && shift_pressed)) {
7a3fbdaf 3097 /* Mouse wheel position is in screen coordinates for
3098 * some reason */
3099 POINT p;
3100 p.x = X_POS(lParam); p.y = Y_POS(lParam);
3101 if (ScreenToClient(hwnd, &p)) {
3102 /* send a mouse-down followed by a mouse up */
3103 term_mouse(term, b, translate_button(b),
3104 MA_CLICK,
3105 TO_CHR_X(p.x),
3106 TO_CHR_Y(p.y), shift_pressed,
3107 control_pressed, is_alt_pressed());
3108 term_mouse(term, b, translate_button(b),
3109 MA_RELEASE, TO_CHR_X(p.x),
3110 TO_CHR_Y(p.y), shift_pressed,
3111 control_pressed, is_alt_pressed());
3112 } /* else: not sure when this can fail */
011b0e33 3113 } else {
3114 /* trigger a scroll */
887035a5 3115 term_scroll(term, 0,
3116 b == MBT_WHEEL_UP ?
3117 -term->rows / 2 : term->rows / 2);
011b0e33 3118 }
3119 }
3120 return 0;
3121 }
374330e2 3122 }
3123
5c4dea05 3124 /*
3125 * Any messages we don't process completely above are passed through to
3126 * DefWindowProc() for default processing.
3127 */
32874aea 3128 return DefWindowProc(hwnd, message, wParam, lParam);
374330e2 3129}
3130
3131/*
ec8679e9 3132 * Move the system caret. (We maintain one, even though it's
3133 * invisible, for the benefit of blind people: apparently some
3134 * helper software tracks the system caret, so we should arrange to
3135 * have one.)
3136 */
a8327734 3137void sys_cursor(void *frontend, int x, int y)
32874aea 3138{
c1da5066 3139 int cx, cy;
3140
887035a5 3141 if (!term->has_focus) return;
c1da5066 3142
3143 /*
3144 * Avoid gratuitously re-updating the cursor position and IMM
3145 * window if there's no actual change required.
3146 */
3147 cx = x * font_width + offset_width;
3148 cy = y * font_height + offset_height;
3149 if (cx == caret_x && cy == caret_y)
3150 return;
3151 caret_x = cx;
3152 caret_y = cy;
3153
3154 sys_cursor_update();
3155}
3156
3157static void sys_cursor_update(void)
3158{
88485e4d 3159 COMPOSITIONFORM cf;
3160 HIMC hIMC;
3161
887035a5 3162 if (!term->has_focus) return;
c1da5066 3163
3164 if (caret_x < 0 || caret_y < 0)
3165 return;
3166
3167 SetCaretPos(caret_x, caret_y);
88485e4d 3168
3169 /* IMM calls on Win98 and beyond only */
3170 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
3171
3172 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
3173 osVersion.dwMinorVersion == 0) return; /* 95 */
3174
3175 /* we should have the IMM functions */
3176 hIMC = ImmGetContext(hwnd);
3177 cf.dwStyle = CFS_POINT;
c1da5066 3178 cf.ptCurrentPos.x = caret_x;
3179 cf.ptCurrentPos.y = caret_y;
88485e4d 3180 ImmSetCompositionWindow(hIMC, &cf);
3181
3182 ImmReleaseContext(hwnd, hIMC);
ec8679e9 3183}
3184
3185/*
374330e2 3186 * Draw a line of text in the window, at given character
3187 * coordinates, in given attributes.
3188 *
3189 * We are allowed to fiddle with the contents of `text'.
3190 */
c6958dfe 3191void do_text_internal(Context ctx, int x, int y, wchar_t *text, int len,
3192 unsigned long attr, int lattr)
32874aea 3193{
374330e2 3194 COLORREF fg, bg, t;
3195 int nfg, nbg, nfont;
3196 HDC hdc = ctx;
59ad2c03 3197 RECT line_box;
3198 int force_manual_underline = 0;
36566009 3199 int fnt_width, char_width;
4eeb7d09 3200 int text_adjust = 0;
3201 static int *IpDx = 0, IpDxLEN = 0;
3202
36566009 3203 lattr &= LATTR_MODE;
3204
3205 char_width = fnt_width = font_width * (1 + (lattr != LATTR_NORM));
3206
4eeb7d09 3207 if (attr & ATTR_WIDE)
3208 char_width *= 2;
59ad2c03 3209
4eeb7d09 3210 if (len > IpDxLEN || IpDx[0] != char_width) {
59ad2c03 3211 int i;
32874aea 3212 if (len > IpDxLEN) {
59ad2c03 3213 sfree(IpDx);
3d88e64d 3214 IpDx = snewn(len + 16, int);
32874aea 3215 IpDxLEN = (len + 16);
59ad2c03 3216 }
32874aea 3217 for (i = 0; i < IpDxLEN; i++)
4eeb7d09 3218 IpDx[i] = char_width;
59ad2c03 3219 }
374330e2 3220
5a73255e 3221 /* Only want the left half of double width lines */
887035a5 3222 if (lattr != LATTR_NORM && x*2 >= term->cols)
5a73255e 3223 return;
3224
c9def1b8 3225 x *= fnt_width;
374330e2 3226 y *= font_height;
5a73255e 3227 x += offset_width;
3228 y += offset_height;
374330e2 3229
887035a5 3230 if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
cecb13f6 3231 attr &= ~(ATTR_REVERSE|ATTR_BLINK|ATTR_COLOURS);
3232 if (bold_mode == BOLD_COLOURS)
3233 attr &= ~ATTR_BOLD;
3234
3235 /* cursor fg and bg */
3236 attr |= (260 << ATTR_FGSHIFT) | (261 << ATTR_BGSHIFT);
374330e2 3237 }
3238
3239 nfont = 0;
4eeb7d09 3240 if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
3241 /* Assume a poorman font is borken in other ways too. */
3242 lattr = LATTR_WIDE;
3243 } else
3244 switch (lattr) {
3245 case LATTR_NORM:
3246 break;
3247 case LATTR_WIDE:
3248 nfont |= FONT_WIDE;
374330e2 3249 break;
4eeb7d09 3250 default:
3251 nfont |= FONT_WIDE + FONT_HIGH;
3252 break;
3253 }
5a73255e 3254 if (attr & ATTR_NARROW)
3255 nfont |= FONT_NARROW;
4eeb7d09 3256
3257 /* Special hack for the VT100 linedraw glyphs. */
36566009 3258 if (text[0] >= 0x23BA && text[0] <= 0x23BD) {
3259 switch ((unsigned char) (text[0])) {
3260 case 0xBA:
3261 text_adjust = -2 * font_height / 5;
3262 break;
3263 case 0xBB:
3264 text_adjust = -1 * font_height / 5;
3265 break;
3266 case 0xBC:
3267 text_adjust = font_height / 5;
3268 break;
3269 case 0xBD:
3270 text_adjust = 2 * font_height / 5;
3271 break;
3272 }
3273 if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3274 text_adjust *= 2;
3275 text[0] = ucsdata.unitab_xterm['q'];
3276 if (attr & ATTR_UNDER) {
3277 attr &= ~ATTR_UNDER;
3278 force_manual_underline = 1;
374330e2 3279 }
3280 }
3281
4eeb7d09 3282 /* Anything left as an original character set is unprintable. */
36566009 3283 if (DIRECT_CHAR(text[0])) {
3284 int i;
3285 for (i = 0; i < len; i++)
3286 text[i] = 0xFFFD;
4eeb7d09 3287 }
3288
3289 /* OEM CP */
36566009 3290 if ((text[0] & CSET_MASK) == CSET_OEMCP)
4eeb7d09 3291 nfont |= FONT_OEM;
3292
37ca32ed 3293 nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
37ca32ed 3294 nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
374330e2 3295 if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
3296 nfont |= FONT_BOLD;
3297 if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3298 nfont |= FONT_UNDERLINE;
4eeb7d09 3299 another_font(nfont);
32874aea 3300 if (!fonts[nfont]) {
3301 if (nfont & FONT_UNDERLINE)
59ad2c03 3302 force_manual_underline = 1;
3303 /* Don't do the same for manual bold, it could be bad news. */
3304
32874aea 3305 nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
59ad2c03 3306 }
4eeb7d09 3307 another_font(nfont);
3308 if (!fonts[nfont])
3309 nfont = FONT_NORMAL;
374330e2 3310 if (attr & ATTR_REVERSE) {
32874aea 3311 t = nfg;
3312 nfg = nbg;
3313 nbg = t;
374330e2 3314 }
cecb13f6 3315 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD)) {
3316 if (nfg < 16) nfg |= 8;
3317 else if (nfg >= 256) nfg |= 1;
3318 }
3319 if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK)) {
3320 if (nbg < 16) nbg |= 8;
3321 else if (nbg >= 256) nbg |= 1;
3322 }
374330e2 3323 fg = colours[nfg];
3324 bg = colours[nbg];
32874aea 3325 SelectObject(hdc, fonts[nfont]);
3326 SetTextColor(hdc, fg);
3327 SetBkColor(hdc, bg);
c6958dfe 3328 if (attr & TATTR_COMBINING)
3329 SetBkMode(hdc, TRANSPARENT);
3330 else
3331 SetBkMode(hdc, OPAQUE);
32874aea 3332 line_box.left = x;
3333 line_box.top = y;
4eeb7d09 3334 line_box.right = x + char_width * len;
32874aea 3335 line_box.bottom = y + font_height;
4eeb7d09 3336
5a73255e 3337 /* Only want the left half of double width lines */
887035a5 3338 if (line_box.right > font_width*term->cols+offset_width)
3339 line_box.right = font_width*term->cols+offset_width;
5a73255e 3340
4eeb7d09 3341 /* We're using a private area for direct to font. (512 chars.) */
36566009 3342 if (ucsdata.dbcs_screenfont && (text[0] & CSET_MASK) == CSET_ACP) {
4eeb7d09 3343 /* Ho Hum, dbcs fonts are a PITA! */
3344 /* To display on W9x I have to convert to UCS */
3345 static wchar_t *uni_buf = 0;
3346 static int uni_len = 0;
5a73255e 3347 int nlen, mptr;
4eeb7d09 3348 if (len > uni_len) {
3349 sfree(uni_buf);
3d88e64d 3350 uni_len = len;
3351 uni_buf = snewn(uni_len, wchar_t);
4eeb7d09 3352 }
4eeb7d09 3353
5a73255e 3354 for(nlen = mptr = 0; mptr<len; mptr++) {
3355 uni_buf[nlen] = 0xFFFD;
21d2b241 3356 if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
36566009 3357 char dbcstext[2];
3358 dbcstext[0] = text[mptr] & 0xFF;
3359 dbcstext[1] = text[mptr+1] & 0xFF;
5a73255e 3360 IpDx[nlen] += char_width;
21d2b241 3361 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
36566009 3362 dbcstext, 2, uni_buf+nlen, 1);
5a73255e 3363 mptr++;
3364 }
3365 else
3366 {
36566009 3367 char dbcstext[1];
3368 dbcstext[0] = text[mptr] & 0xFF;
21d2b241 3369 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
36566009 3370 dbcstext, 1, uni_buf+nlen, 1);
5a73255e 3371 }
3372 nlen++;
3373 }
4eeb7d09 3374 if (nlen <= 0)
3375 return; /* Eeek! */
3376
3377 ExtTextOutW(hdc, x,
3378 y - font_height * (lattr == LATTR_BOT) + text_adjust,
5a73255e 3379 ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
4eeb7d09 3380 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3381 SetBkMode(hdc, TRANSPARENT);
3382 ExtTextOutW(hdc, x - 1,
3383 y - font_height * (lattr ==
3384 LATTR_BOT) + text_adjust,
5a73255e 3385 ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
4eeb7d09 3386 }
5a73255e 3387
3388 IpDx[0] = -1;
36566009 3389 } else if (DIRECT_FONT(text[0])) {
3390 static char *directbuf = NULL;
3391 static int directlen = 0;
3392 int i;
3393 if (len > directlen) {
3394 directlen = len;
3395 directbuf = sresize(directbuf, directlen, char);
3396 }
3397
3398 for (i = 0; i < len; i++)
3399 directbuf[i] = text[i] & 0xFF;
3400
4eeb7d09 3401 ExtTextOut(hdc, x,
3402 y - font_height * (lattr == LATTR_BOT) + text_adjust,
36566009 3403 ETO_CLIPPED | ETO_OPAQUE, &line_box, directbuf, len, IpDx);
4eeb7d09 3404 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3405 SetBkMode(hdc, TRANSPARENT);
3406
ec4ab1cb 3407 /* GRR: This draws the character outside its box and can leave
4eeb7d09 3408 * 'droppings' even with the clip box! I suppose I could loop it
3409 * one character at a time ... yuk.
3410 *
3411 * Or ... I could do a test print with "W", and use +1 or -1 for this
3412 * shift depending on if the leftmost column is blank...
3413 */
3414 ExtTextOut(hdc, x - 1,
3415 y - font_height * (lattr ==
3416 LATTR_BOT) + text_adjust,
36566009 3417 ETO_CLIPPED, &line_box, directbuf, len, IpDx);
4eeb7d09 3418 }
3419 } else {
3420 /* And 'normal' unicode characters */
3421 static WCHAR *wbuf = NULL;
3422 static int wlen = 0;
3423 int i;
c6958dfe 3424
4eeb7d09 3425 if (wlen < len) {
3426 sfree(wbuf);
3427 wlen = len;
3d88e64d 3428 wbuf = snewn(wlen, WCHAR);
4eeb7d09 3429 }
c6958dfe 3430
4eeb7d09 3431 for (i = 0; i < len; i++)
36566009 3432 wbuf[i] = text[i];
4eeb7d09 3433
f0fccd51 3434 /* print Glyphs as they are, without Windows' Shaping*/
fe75e503 3435 general_textout(hdc, x, y - font_height * (lattr == LATTR_BOT) + text_adjust,
3436 &line_box, wbuf, len, IpDx, !(attr & TATTR_COMBINING));
4eeb7d09 3437
3438 /* And the shadow bold hack. */
5a73255e 3439 if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
4eeb7d09 3440 SetBkMode(hdc, TRANSPARENT);
3441 ExtTextOutW(hdc, x - 1,
3442 y - font_height * (lattr ==
3443 LATTR_BOT) + text_adjust,
3444 ETO_CLIPPED, &line_box, wbuf, len, IpDx);
3445 }
374330e2 3446 }
4eeb7d09 3447 if (lattr != LATTR_TOP && (force_manual_underline ||
3448 (und_mode == UND_LINE
3449 && (attr & ATTR_UNDER)))) {
32874aea 3450 HPEN oldpen;
4eeb7d09 3451 int dec = descent;
3452 if (lattr == LATTR_BOT)
3453 dec = dec * 2 - font_height;
3454
32874aea 3455 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
4eeb7d09 3456 MoveToEx(hdc, x, y + dec, NULL);
3457 LineTo(hdc, x + len * char_width, y + dec);
32874aea 3458 oldpen = SelectObject(hdc, oldpen);
3459 DeleteObject(oldpen);
374330e2 3460 }
4eeb7d09 3461}
3462
c6958dfe 3463/*
3464 * Wrapper that handles combining characters.
3465 */
3466void do_text(Context ctx, int x, int y, wchar_t *text, int len,
3467 unsigned long attr, int lattr)
3468{
3469 if (attr & TATTR_COMBINING) {
3470 unsigned long a = 0;
3471 attr &= ~TATTR_COMBINING;
3472 while (len--) {
3473 do_text_internal(ctx, x, y, text, 1, attr | a, lattr);
3474 text++;
3475 a = TATTR_COMBINING;
3476 }
3477 } else
3478 do_text_internal(ctx, x, y, text, len, attr, lattr);
3479}
3480
36566009 3481void do_cursor(Context ctx, int x, int y, wchar_t *text, int len,
4eeb7d09 3482 unsigned long attr, int lattr)
3483{
3484
3485 int fnt_width;
3486 int char_width;
3487 HDC hdc = ctx;
3488 int ctype = cfg.cursor_type;
3489
8af95aa3 3490 lattr &= LATTR_MODE;
3491
887035a5 3492 if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
36566009 3493 if (*text != UCSWIDE) {
4eeb7d09 3494 do_text(ctx, x, y, text, len, attr, lattr);
3495 return;
3496 }
3497 ctype = 2;
3498 attr |= TATTR_RIGHTCURS;
3499 }
3500
3501 fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3502 if (attr & ATTR_WIDE)
3503 char_width *= 2;
3504 x *= fnt_width;
3505 y *= font_height;
5a73255e 3506 x += offset_width;
3507 y += offset_height;
4eeb7d09 3508
887035a5 3509 if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
374330e2 3510 POINT pts[5];
32874aea 3511 HPEN oldpen;
374330e2 3512 pts[0].x = pts[1].x = pts[4].x = x;
4eeb7d09 3513 pts[2].x = pts[3].x = x + char_width - 1;
374330e2 3514 pts[0].y = pts[3].y = pts[4].y = y;
32874aea 3515 pts[1].y = pts[2].y = y + font_height - 1;
cecb13f6 3516 oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
32874aea 3517 Polyline(hdc, pts, 5);
3518 oldpen = SelectObject(hdc, oldpen);
3519 DeleteObject(oldpen);
4eeb7d09 3520 } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
32874aea 3521 int startx, starty, dx, dy, length, i;
4eeb7d09 3522 if (ctype == 1) {
32874aea 3523 startx = x;
3524 starty = y + descent;
3525 dx = 1;
3526 dy = 0;
4eeb7d09 3527 length = char_width;
32874aea 3528 } else {
4e30ff69 3529 int xadjust = 0;
4eeb7d09 3530 if (attr & TATTR_RIGHTCURS)
3531 xadjust = char_width - 1;
32874aea 3532 startx = x + xadjust;
3533 starty = y;
3534 dx = 0;
3535 dy = 1;
3536 length = font_height;
3537 }
4eeb7d09 3538 if (attr & TATTR_ACTCURS) {
32874aea 3539 HPEN oldpen;
3540 oldpen =
fdc94dd1 3541 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[261]));
32874aea 3542 MoveToEx(hdc, startx, starty, NULL);
3543 LineTo(hdc, startx + dx * length, starty + dy * length);
3544 oldpen = SelectObject(hdc, oldpen);
3545 DeleteObject(oldpen);
3546 } else {
3547 for (i = 0; i < length; i++) {
3548 if (i % 2 == 0) {
fdc94dd1 3549 SetPixel(hdc, startx, starty, colours[261]);
32874aea 3550 }
3551 startx += dx;
3552 starty += dy;
3553 }
3554 }
4e30ff69 3555 }
374330e2 3556}
3557
5a73255e 3558/* This function gets the actual width of a character in the normal font.
3559 */
2102eb8a 3560int char_width(Context ctx, int uc) {
5a73255e 3561 HDC hdc = ctx;
3562 int ibuf = 0;
3563
3564 /* If the font max is the same as the font ave width then this
3565 * function is a no-op.
3566 */
3567 if (!font_dualwidth) return 1;
3568
3569 switch (uc & CSET_MASK) {
36566009 3570 case CSET_ASCII:
21d2b241 3571 uc = ucsdata.unitab_line[uc & 0xFF];
5a73255e 3572 break;
36566009 3573 case CSET_LINEDRW:
21d2b241 3574 uc = ucsdata.unitab_xterm[uc & 0xFF];
5a73255e 3575 break;
36566009 3576 case CSET_SCOACS:
21d2b241 3577 uc = ucsdata.unitab_scoacs[uc & 0xFF];
5a73255e 3578 break;
3579 }
3580 if (DIRECT_FONT(uc)) {
21d2b241 3581 if (ucsdata.dbcs_screenfont) return 1;
5a73255e 3582
3583 /* Speedup, I know of no font where ascii is the wrong width */
36566009 3584 if ((uc&~CSET_MASK) >= ' ' && (uc&~CSET_MASK)<= '~')
5a73255e 3585 return 1;
3586
36566009 3587 if ( (uc & CSET_MASK) == CSET_ACP ) {
5a73255e 3588 SelectObject(hdc, fonts[FONT_NORMAL]);
36566009 3589 } else if ( (uc & CSET_MASK) == CSET_OEMCP ) {
5a73255e 3590 another_font(FONT_OEM);
3591 if (!fonts[FONT_OEM]) return 0;
3592
3593 SelectObject(hdc, fonts[FONT_OEM]);
3594 } else
3595 return 0;
3596
36566009 3597 if ( GetCharWidth32(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1 &&
3598 GetCharWidth(hdc, uc&~CSET_MASK, uc&~CSET_MASK, &ibuf) != 1)
5a73255e 3599 return 0;
3600 } else {
3601 /* Speedup, I know of no font where ascii is the wrong width */
3602 if (uc >= ' ' && uc <= '~') return 1;
3603
3604 SelectObject(hdc, fonts[FONT_NORMAL]);
3605 if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3606 /* Okay that one worked */ ;
3607 else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3608 /* This should work on 9x too, but it's "less accurate" */ ;
3609 else
3610 return 0;
3611 }
3612
3613 ibuf += font_width / 2 -1;
3614 ibuf /= font_width;
3615
3616 return ibuf;
3617}
3618
374330e2 3619/*
c9def1b8 3620 * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
58c840dc 3621 * codes. Returns number of bytes used, zero to drop the message,
3622 * -1 to forward the message to Windows, or another negative number
3623 * to indicate a NUL-terminated "special" string.
374330e2 3624 */
3cf144db 3625static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
32874aea 3626 unsigned char *output)
3627{
374330e2 3628 BYTE keystate[256];
32874aea 3629 int scan, left_alt = 0, key_down, shift_state;
3630 int r, i, code;
3631 unsigned char *p = output;
4eeb7d09 3632 static int alt_sum = 0;
374330e2 3633
00e3ba0f 3634 HKL kbd_layout = GetKeyboardLayout(0);
3635
c264be08 3636 /* keys is for ToAsciiEx. There's some ick here, see below. */
3637 static WORD keys[3];
0c50ef57 3638 static int compose_char = 0;
3639 static WPARAM compose_key = 0;
32874aea 3640
c9def1b8 3641 r = GetKeyboardState(keystate);
32874aea 3642 if (!r)
3643 memset(keystate, 0, sizeof(keystate));
3644 else {
ec55b220 3645#if 0
4eeb7d09 3646#define SHOW_TOASCII_RESULT
32874aea 3647 { /* Tell us all about key events */
3648 static BYTE oldstate[256];
3649 static int first = 1;
3650 static int scan;
3651 int ch;
3652 if (first)
3653 memcpy(oldstate, keystate, sizeof(oldstate));
3654 first = 0;
3655
3656 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3657 debug(("+"));
3658 } else if ((HIWORD(lParam) & KF_UP)
3659 && scan == (HIWORD(lParam) & 0xFF)) {
3660 debug((". U"));
3661 } else {
3662 debug((".\n"));
3663 if (wParam >= VK_F1 && wParam <= VK_F20)
3664 debug(("K_F%d", wParam + 1 - VK_F1));
3665 else
3666 switch (wParam) {
3667 case VK_SHIFT:
3668 debug(("SHIFT"));
3669 break;
3670 case VK_CONTROL:
3671 debug(("CTRL"));
3672 break;
3673 case VK_MENU:
3674 debug(("ALT"));
3675 break;
3676 default:
3677 debug(("VK_%02x", wParam));
3678 }
3679 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3680 debug(("*"));
3681 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3682
3683 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3684 if (ch >= ' ' && ch <= '~')
3685 debug((", '%c'", ch));
3686 else if (ch)
3687 debug((", $%02x", ch));
3688
3689 if (keys[0])
3690 debug((", KB0=%02x", keys[0]));
3691 if (keys[1])
3692 debug((", KB1=%02x", keys[1]));
3693 if (keys[2])
3694 debug((", KB2=%02x", keys[2]));
3695
3696 if ((keystate[VK_SHIFT] & 0x80) != 0)
3697 debug((", S"));
3698 if ((keystate[VK_CONTROL] & 0x80) != 0)
3699 debug((", C"));
3700 if ((HIWORD(lParam) & KF_EXTENDED))
3701 debug((", E"));
3702 if ((HIWORD(lParam) & KF_UP))
3703 debug((", U"));
3704 }
3705
3706 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3707 else if ((HIWORD(lParam) & KF_UP))
3708 oldstate[wParam & 0xFF] ^= 0x80;
3709 else
3710 oldstate[wParam & 0xFF] ^= 0x81;
3711
3712 for (ch = 0; ch < 256; ch++)
3713 if (oldstate[ch] != keystate[ch])
3714 debug((", M%02x=%02x", ch, keystate[ch]));
3715
3716 memcpy(oldstate, keystate, sizeof(oldstate));
3717 }
ec55b220 3718#endif
3719
32874aea 3720 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
2cba1186 3721 keystate[VK_RMENU] = keystate[VK_MENU];
3722 }
3723
c9def1b8 3724
3725 /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
5789bc94 3726 if ((cfg.funky_type == FUNKY_VT400 ||
3727 (cfg.funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
887035a5 3728 !cfg.no_applic_k))
32874aea 3729 && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
c9def1b8 3730
3731 wParam = VK_EXECUTE;
3732
3733 /* UnToggle NUMLock */
32874aea 3734 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3735 keystate[VK_NUMLOCK] ^= 1;
c9def1b8 3736 }
3737
3738 /* And write back the 'adjusted' state */
32874aea 3739 SetKeyboardState(keystate);
c9def1b8 3740 }
3741
3742 /* Disable Auto repeat if required */
887035a5 3743 if (term->repeat_off &&
3744 (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
32874aea 3745 return 0;
c9def1b8 3746
32874aea 3747 if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
c9def1b8 3748 left_alt = 1;
3749
32874aea 3750 key_down = ((HIWORD(lParam) & KF_UP) == 0);
c9def1b8 3751
95bbe1ae 3752 /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
32874aea 3753 if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
95bbe1ae 3754 if (cfg.ctrlaltkeys)
3755 keystate[VK_MENU] = 0;
3756 else {
3757 keystate[VK_RMENU] = 0x80;
3758 left_alt = 0;
3759 }
3760 }
c9def1b8 3761
3762 scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
32874aea 3763 shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3764 + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
374330e2 3765
95bbe1ae 3766 /* Note if AltGr was pressed and if it was used as a compose key */
3767 if (!compose_state) {
159eba53 3768 compose_key = 0x100;
95bbe1ae 3769 if (cfg.compose_key) {
32874aea 3770 if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
95bbe1ae 3771 compose_key = wParam;
3772 }
3773 if (wParam == VK_APPS)
3774 compose_key = wParam;
3775 }
3776
32874aea 3777 if (wParam == compose_key) {
3778 if (compose_state == 0
3779 && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3780 1;
3781 else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
95bbe1ae 3782 compose_state = 2;
3783 else
3784 compose_state = 0;
32874aea 3785 } else if (compose_state == 1 && wParam != VK_CONTROL)
95bbe1ae 3786 compose_state = 0;
3787
32874aea 3788 if (compose_state > 1 && left_alt)
3789 compose_state = 0;
67c339f7 3790
c9def1b8 3791 /* Sanitize the number pad if not using a PC NumPad */
887035a5 3792 if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
5789bc94 3793 && cfg.funky_type != FUNKY_XTERM)
3794 || cfg.funky_type == FUNKY_VT400 || cfg.nethack_keypad || compose_state) {
32874aea 3795 if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
c9def1b8 3796 int nParam = 0;
32874aea 3797 switch (wParam) {
3798 case VK_INSERT:
3799 nParam = VK_NUMPAD0;
3800 break;
3801 case VK_END:
3802 nParam = VK_NUMPAD1;
3803 break;
3804 case VK_DOWN:
3805 nParam = VK_NUMPAD2;
3806 break;
3807 case VK_NEXT:
3808 nParam = VK_NUMPAD3;
3809 break;
3810 case VK_LEFT:
3811 nParam = VK_NUMPAD4;
3812 break;
3813 case VK_CLEAR:
3814 nParam = VK_NUMPAD5;
3815 break;
3816 case VK_RIGHT:
3817 nParam = VK_NUMPAD6;
3818 break;
3819 case VK_HOME:
3820 nParam = VK_NUMPAD7;
3821 break;
3822 case VK_UP:
3823 nParam = VK_NUMPAD8;
3824 break;
3825 case VK_PRIOR:
3826 nParam = VK_NUMPAD9;
3827 break;
3828 case VK_DELETE:
3829 nParam = VK_DECIMAL;
3830 break;
c9def1b8 3831 }
32874aea 3832 if (nParam) {
3833 if (keystate[VK_NUMLOCK] & 1)
3834 shift_state |= 1;
c9def1b8 3835 wParam = nParam;
3836 }
25d39ef6 3837 }
3838 }
3839
c9def1b8 3840 /* If a key is pressed and AltGr is not active */
32874aea 3841 if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3842 /* Okay, prepare for most alts then ... */
3843 if (left_alt)
3844 *p++ = '\033';
374330e2 3845
c9def1b8 3846 /* Lets see if it's a pattern we know all about ... */
3847 if (wParam == VK_PRIOR && shift_state == 1) {
32874aea 3848 SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3849 return 0;
c9def1b8 3850 }
153580da 3851 if (wParam == VK_PRIOR && shift_state == 2) {
3852 SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3853 return 0;
3854 }
c9def1b8 3855 if (wParam == VK_NEXT && shift_state == 1) {
32874aea 3856 SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3857 return 0;
3858 }
153580da 3859 if (wParam == VK_NEXT && shift_state == 2) {
3860 SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3861 return 0;
3862 }
cf6ddb95 3863 if ((wParam == VK_PRIOR || wParam == VK_NEXT) && shift_state == 3) {
3864 term_scroll_to_selection(term, (wParam == VK_PRIOR ? 0 : 1));
3865 return 0;
3866 }
32874aea 3867 if (wParam == VK_INSERT && shift_state == 1) {
e9609ce5 3868 request_paste(NULL);
32874aea 3869 return 0;
3870 }
c9def1b8 3871 if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
32874aea 3872 return -1;
c9def1b8 3873 }
3874 if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
32874aea 3875 SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3876 return -1;
c9def1b8 3877 }
2cae8529 3878 if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3879 (cfg.resize_action != RESIZE_DISABLED)) {
0ed2f48e 3880 if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3881 flip_full_screen();
8f57d753 3882 return -1;
3883 }
ec55b220 3884 /* Control-Numlock for app-keypad mode switch */
3885 if (wParam == VK_PAUSE && shift_state == 2) {
887035a5 3886 term->app_keypad_keys ^= 1;
ec55b220 3887 return 0;
3888 }
374330e2 3889
c9def1b8 3890 /* Nethack keypad */
3891 if (cfg.nethack_keypad && !left_alt) {
32874aea 3892 switch (wParam) {
3893 case VK_NUMPAD1:
6e67448b 3894 *p++ = "bB\002\002"[shift_state & 3];
32874aea 3895 return p - output;
3896 case VK_NUMPAD2:
6e67448b 3897 *p++ = "jJ\012\012"[shift_state & 3];
32874aea 3898 return p - output;
3899 case VK_NUMPAD3:
6e67448b 3900 *p++ = "nN\016\016"[shift_state & 3];
32874aea 3901 return p - output;
3902 case VK_NUMPAD4:
6e67448b 3903 *p++ = "hH\010\010"[shift_state & 3];
32874aea 3904 return p - output;
3905 case VK_NUMPAD5:
3906 *p++ = shift_state ? '.' : '.';
3907 return p - output;
3908 case VK_NUMPAD6:
6e67448b 3909 *p++ = "lL\014\014"[shift_state & 3];
32874aea 3910 return p - output;
3911 case VK_NUMPAD7:
6e67448b 3912 *p++ = "yY\031\031"[shift_state & 3];
32874aea 3913 return p - output;
3914 case VK_NUMPAD8:
6e67448b 3915 *p++ = "kK\013\013"[shift_state & 3];
32874aea 3916 return p - output;
3917 case VK_NUMPAD9:
6e67448b 3918 *p++ = "uU\025\025"[shift_state & 3];
32874aea 3919 return p - output;
3920 }
c9def1b8 3921 }
3922
3923 /* Application Keypad */
3924 if (!left_alt) {
32874aea 3925 int xkey = 0;
3926
5789bc94 3927 if (cfg.funky_type == FUNKY_VT400 ||
3928 (cfg.funky_type <= FUNKY_LINUX &&
887035a5 3929 term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
32874aea 3930 case VK_EXECUTE:
3931 xkey = 'P';
3932 break;
3933 case VK_DIVIDE:
3934 xkey = 'Q';
3935 break;
3936 case VK_MULTIPLY:
3937 xkey = 'R';
3938 break;
3939 case VK_SUBTRACT:
3940 xkey = 'S';
3941 break;
3942 }
887035a5 3943 if (term->app_keypad_keys && !cfg.no_applic_k)
32874aea 3944 switch (wParam) {
3945 case VK_NUMPAD0:
3946 xkey = 'p';
3947 break;
3948 case VK_NUMPAD1:
3949 xkey = 'q';
3950 break;
3951 case VK_NUMPAD2:
3952 xkey = 'r';
3953 break;
3954 case VK_NUMPAD3:
3955 xkey = 's';
3956 break;
3957 case VK_NUMPAD4:
3958 xkey = 't';
3959 break;
3960 case VK_NUMPAD5:
3961 xkey = 'u';
3962 break;
3963 case VK_NUMPAD6:
3964 xkey = 'v';
3965 break;
3966 case VK_NUMPAD7:
3967 xkey = 'w';
3968 break;
3969 case VK_NUMPAD8:
3970 xkey = 'x';
3971 break;
3972 case VK_NUMPAD9:
3973 xkey = 'y';
3974 break;
3975
3976 case VK_DECIMAL:
3977 xkey = 'n';
3978 break;
3979 case VK_ADD:
5789bc94 3980 if (cfg.funky_type == FUNKY_XTERM) {
32874aea 3981 if (shift_state)
3982 xkey = 'l';
3983 else
3984 xkey = 'k';
3985 } else if (shift_state)
3986 xkey = 'm';
c9def1b8 3987 else
32874aea 3988 xkey = 'l';
3989 break;
3990
3991 case VK_DIVIDE:
5789bc94 3992 if (cfg.funky_type == FUNKY_XTERM)
32874aea 3993 xkey = 'o';
3994 break;
3995 case VK_MULTIPLY:
5789bc94 3996 if (cfg.funky_type == FUNKY_XTERM)
32874aea 3997 xkey = 'j';
3998 break;
3999 case VK_SUBTRACT:
5789bc94 4000 if (cfg.funky_type == FUNKY_XTERM)
32874aea 4001 xkey = 'm';
4002 break;
4003
4004 case VK_RETURN:
4005 if (HIWORD(lParam) & KF_EXTENDED)
4006 xkey = 'M';
4007 break;
c9def1b8 4008 }
32874aea 4009 if (xkey) {
887035a5 4010 if (term->vt52_mode) {
32874aea 4011 if (xkey >= 'P' && xkey <= 'S')
4012 p += sprintf((char *) p, "\x1B%c", xkey);
4013 else
4014 p += sprintf((char *) p, "\x1B?%c", xkey);
4015 } else
4016 p += sprintf((char *) p, "\x1BO%c", xkey);
4017 return p - output;
c9def1b8 4018 }
4019 }
4020
32874aea 4021 if (wParam == VK_BACK && shift_state == 0) { /* Backspace */
c9def1b8 4022 *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
a5f3e637 4023 *p++ = 0;
4024 return -2;
c9def1b8 4025 }
e8e8d6e2 4026 if (wParam == VK_BACK && shift_state == 1) { /* Shift Backspace */
4027 /* We do the opposite of what is configured */
4028 *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
4029 *p++ = 0;
4030 return -2;
4031 }
32874aea 4032 if (wParam == VK_TAB && shift_state == 1) { /* Shift tab */
4033 *p++ = 0x1B;
4034 *p++ = '[';
4035 *p++ = 'Z';
4036 return p - output;
c9def1b8 4037 }
32874aea 4038 if (wParam == VK_SPACE && shift_state == 2) { /* Ctrl-Space */
4039 *p++ = 0;
4040 return p - output;
c9def1b8 4041 }
32874aea 4042 if (wParam == VK_SPACE && shift_state == 3) { /* Ctrl-Shift-Space */
4043 *p++ = 160;
4044 return p - output;
c9def1b8 4045 }
32874aea 4046 if (wParam == VK_CANCEL && shift_state == 2) { /* Ctrl-Break */
58c840dc 4047 if (back)
4048 back->special(backhandle, TS_BRK);
4049 return 0;
c9def1b8 4050 }
32874aea 4051 if (wParam == VK_PAUSE) { /* Break/Pause */
4052 *p++ = 26;
4053 *p++ = 0;
4054 return -2;
95bbe1ae 4055 }
c9def1b8 4056 /* Control-2 to Control-8 are special */
32874aea 4057 if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
4058 *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
c9def1b8 4059 return p - output;
4060 }
237f2b6e 4061 if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
c9def1b8 4062 *p++ = 0x1F;
4063 return p - output;
4064 }
e414a330 4065 if (shift_state == 2 && (wParam == 0xDF || wParam == 0xDC)) {
c9def1b8 4066 *p++ = 0x1C;
4067 return p - output;
4068 }
9aa461e4 4069 if (shift_state == 3 && wParam == 0xDE) {
4070 *p++ = 0x1E; /* Ctrl-~ == Ctrl-^ in xterm at least */
4071 return p - output;
4072 }
887035a5 4073 if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
32874aea 4074 *p++ = '\r';
4075 *p++ = '\n';
c9def1b8 4076 return p - output;
4077 }
374330e2 4078
c5e9c988 4079 /*
c9def1b8 4080 * Next, all the keys that do tilde codes. (ESC '[' nn '~',
4081 * for integer decimal nn.)
4082 *
4083 * We also deal with the weird ones here. Linux VCs replace F1
4084 * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
4085 * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
4086 * respectively.
c5e9c988 4087 */
c9def1b8 4088 code = 0;
4089 switch (wParam) {
32874aea 4090 case VK_F1:
4091 code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
4092 break;
4093 case VK_F2:
4094 code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
4095 break;
4096 case VK_F3:
4097 code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
4098 break;
4099 case VK_F4:
4100 code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
4101 break;
4102 case VK_F5:
4103 code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
4104 break;
4105 case VK_F6:
4106 code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
4107 break;
4108 case VK_F7:
4109 code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
4110 break;
4111 case VK_F8:
4112 code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
4113 break;
4114 case VK_F9:
4115 code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
4116 break;
4117 case VK_F10:
4118 code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
4119 break;
4120 case VK_F11:
4121 code = 23;
4122 break;
4123 case VK_F12:
4124 code = 24;
4125 break;
4126 case VK_F13:
4127 code = 25;
4128 break;
4129 case VK_F14:
4130 code = 26;
4131 break;
4132 case VK_F15:
4133 code = 28;
4134 break;
4135 case VK_F16:
4136 code = 29;
4137 break;
4138 case VK_F17:
4139 code = 31;
4140 break;
4141 case VK_F18:
4142 code = 32;
4143 break;
4144 case VK_F19:
4145 code = 33;
4146 break;
4147 case VK_F20:
4148 code = 34;
4149 break;
dfca2656 4150 }
4151 if ((shift_state&2) == 0) switch (wParam) {
32874aea 4152 case VK_HOME:
4153 code = 1;
4154 break;
4155 case VK_INSERT:
4156 code = 2;
4157 break;
4158 case VK_DELETE:
4159 code = 3;
4160 break;
4161 case VK_END:
4162 code = 4;
4163 break;
4164 case VK_PRIOR:
4165 code = 5;
4166 break;
4167 case VK_NEXT:
4168 code = 6;
4169 break;
374330e2 4170 }
ec55b220 4171 /* Reorder edit keys to physical order */
5789bc94 4172 if (cfg.funky_type == FUNKY_VT400 && code <= 6)
32874aea 4173 code = "\0\2\1\4\5\3\6"[code];
ec55b220 4174
887035a5 4175 if (term->vt52_mode && code > 0 && code <= 6) {
32874aea 4176 p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
f37caa11 4177 return p - output;
4178 }
4179
5789bc94 4180 if (cfg.funky_type == FUNKY_SCO && /* SCO function keys */
9bc81a2c 4181 code >= 11 && code <= 34) {
e24b1972 4182 char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
4183 int index = 0;
4184 switch (wParam) {
4185 case VK_F1: index = 0; break;
4186 case VK_F2: index = 1; break;
4187 case VK_F3: index = 2; break;
4188 case VK_F4: index = 3; break;
4189 case VK_F5: index = 4; break;
4190 case VK_F6: index = 5; break;
4191 case VK_F7: index = 6; break;
4192 case VK_F8: index = 7; break;
4193 case VK_F9: index = 8; break;
4194 case VK_F10: index = 9; break;
4195 case VK_F11: index = 10; break;
4196 case VK_F12: index = 11; break;
4197 }
4198 if (keystate[VK_SHIFT] & 0x80) index += 12;
4199 if (keystate[VK_CONTROL] & 0x80) index += 24;
4200 p += sprintf((char *) p, "\x1B[%c", codes[index]);
f37caa11 4201 return p - output;
4202 }
5789bc94 4203 if (cfg.funky_type == FUNKY_SCO && /* SCO small keypad */
9bc81a2c 4204 code >= 1 && code <= 6) {
4205 char codes[] = "HL.FIG";
4206 if (code == 3) {
4207 *p++ = '\x7F';
4208 } else {
4209 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
4210 }
4211 return p - output;
4212 }
5789bc94 4213 if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
f37caa11 4214 int offt = 0;
32874aea 4215 if (code > 15)
4216 offt++;
4217 if (code > 21)
4218 offt++;
887035a5 4219 if (term->vt52_mode)
32874aea 4220 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
f37caa11 4221 else
32874aea 4222 p +=
4223 sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
f37caa11 4224 return p - output;
4225 }
5789bc94 4226 if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
32874aea 4227 p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
c9def1b8 4228 return p - output;
4229 }
5789bc94 4230 if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
887035a5 4231 if (term->vt52_mode)
32874aea 4232 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
ec55b220 4233 else
32874aea 4234 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
c9def1b8 4235 return p - output;
4236 }
4237 if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
32874aea 4238 p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
c9def1b8 4239 return p - output;
4240 }
4241 if (code) {
32874aea 4242 p += sprintf((char *) p, "\x1B[%d~", code);
374330e2 4243 return p - output;
374330e2 4244 }
45dabbc5 4245
c9def1b8 4246 /*
4247 * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
4248 * some reason seems to send VK_CLEAR to Windows...).
4249 */
4250 {
4251 char xkey = 0;
4252 switch (wParam) {
32874aea 4253 case VK_UP:
4254 xkey = 'A';
4255 break;
4256 case VK_DOWN:
4257 xkey = 'B';
4258 break;
4259 case VK_RIGHT:
4260 xkey = 'C';
4261 break;
4262 case VK_LEFT:
4263 xkey = 'D';
4264 break;
4265 case VK_CLEAR:
4266 xkey = 'G';
4267 break;
c9def1b8 4268 }
32874aea 4269 if (xkey) {
720f700e 4270 p += format_arrow_key(p, term, xkey, shift_state);
c9def1b8 4271 return p - output;
4272 }
4273 }
0c50ef57 4274
4275 /*
4276 * Finally, deal with Return ourselves. (Win95 seems to
4277 * foul it up when Alt is pressed, for some reason.)
4278 */
32874aea 4279 if (wParam == VK_RETURN) { /* Return */
0c50ef57 4280 *p++ = 0x0D;
a5f3e637 4281 *p++ = 0;
4282 return -2;
0c50ef57 4283 }
4eeb7d09 4284
4285 if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4286 alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4287 else
4288 alt_sum = 0;
67c339f7 4289 }
374330e2 4290
c9def1b8 4291 /* Okay we've done everything interesting; let windows deal with
4292 * the boring stuff */
4293 {
a9c02454 4294 BOOL capsOn=0;
4295
4296 /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4297 if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
4298 capsOn= !left_alt;
4299 keystate[VK_CAPITAL] = 0;
4300 }
4301
c264be08 4302 /* XXX how do we know what the max size of the keys array should
4303 * be is? There's indication on MS' website of an Inquire/InquireEx
4304 * functioning returning a KBINFO structure which tells us. */
4305 if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4306 /* XXX 'keys' parameter is declared in MSDN documentation as
4307 * 'LPWORD lpChar'.
4308 * The experience of a French user indicates that on
4309 * Win98, WORD[] should be passed in, but on Win2K, it should
4310 * be BYTE[]. German WinXP and my Win2K with "US International"
4311 * driver corroborate this.
4312 * Experimentally I've conditionalised the behaviour on the
4313 * Win9x/NT split, but I suspect it's worse than that.
4314 * See wishlist item `win-dead-keys' for more horrible detail
4315 * and speculations. */
4316 BYTE keybs[3];
4317 int i;
4318 r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
4319 for (i=0; i<3; i++) keys[i] = keybs[i];
4320 } else {
4321 r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4322 }
4eeb7d09 4323#ifdef SHOW_TOASCII_RESULT
4324 if (r == 1 && !key_down) {
4325 if (alt_sum) {
21d2b241 4326 if (in_utf(term) || ucsdata.dbcs_screenfont)
4eeb7d09 4327 debug((", (U+%04x)", alt_sum));
4328 else
4329 debug((", LCH(%d)", alt_sum));
4330 } else {
4331 debug((", ACH(%d)", keys[0]));
4332 }
4333 } else if (r > 0) {
4334 int r1;
4335 debug((", ASC("));
4336 for (r1 = 0; r1 < r; r1++) {
4337 debug(("%s%d", r1 ? "," : "", keys[r1]));
4338 }
4339 debug((")"));
4340 }
4341#endif
32874aea 4342 if (r > 0) {
4eeb7d09 4343 WCHAR keybuf;
256cb87c 4344
4345 /*
4346 * Interrupt an ongoing paste. I'm not sure this is
4347 * sensible, but for the moment it's preferable to
4348 * having to faff about buffering things.
4349 */
887035a5 4350 term_nopaste(term);
256cb87c 4351
c9def1b8 4352 p = output;
32874aea 4353 for (i = 0; i < r; i++) {
4354 unsigned char ch = (unsigned char) keys[i];
14963b8f 4355
32874aea 4356 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
c9def1b8 4357 compose_char = ch;
32874aea 4358 compose_state++;
c9def1b8 4359 continue;
4360 }
32874aea 4361 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
c9def1b8 4362 int nc;
4363 compose_state = 0;
4364
32874aea 4365 if ((nc = check_compose(compose_char, ch)) == -1) {
fe50e814 4366 MessageBeep(MB_ICONHAND);
c9def1b8 4367 return 0;
4368 }
4eeb7d09 4369 keybuf = nc;
887035a5 4370 term_seen_key_event(term);
e3be8de5 4371 if (ldisc)
4372 luni_send(ldisc, &keybuf, 1, 1);
4eeb7d09 4373 continue;
c9def1b8 4374 }
374330e2 4375
c9def1b8 4376 compose_state = 0;
374330e2 4377
4eeb7d09 4378 if (!key_down) {
4379 if (alt_sum) {
21d2b241 4380 if (in_utf(term) || ucsdata.dbcs_screenfont) {
4eeb7d09 4381 keybuf = alt_sum;
887035a5 4382 term_seen_key_event(term);
e3be8de5 4383 if (ldisc)
4384 luni_send(ldisc, &keybuf, 1, 1);
4eeb7d09 4385 } else {
4386 ch = (char) alt_sum;
5471d09a 4387 /*
4388 * We need not bother about stdin
4389 * backlogs here, because in GUI PuTTY
4390 * we can't do anything about it
4391 * anyway; there's no means of asking
4392 * Windows to hold off on KEYDOWN
4393 * messages. We _have_ to buffer
4394 * everything we're sent.
4395 */
887035a5 4396 term_seen_key_event(term);
e3be8de5 4397 if (ldisc)
4398 ldisc_send(ldisc, &ch, 1, 1);
4eeb7d09 4399 }
4400 alt_sum = 0;
405a0c29 4401 } else {
887035a5 4402 term_seen_key_event(term);
e3be8de5 4403 if (ldisc)
4404 lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
405a0c29 4405 }
4eeb7d09 4406 } else {
a9c02454 4407 if(capsOn && ch < 0x80) {
4408 WCHAR cbuf[2];
4409 cbuf[0] = 27;
4410 cbuf[1] = xlat_uskbd2cyrllic(ch);
887035a5 4411 term_seen_key_event(term);
e3be8de5 4412 if (ldisc)
4413 luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
a9c02454 4414 } else {
4415 char cbuf[2];
4416 cbuf[0] = '\033';
4417 cbuf[1] = ch;
887035a5 4418 term_seen_key_event(term);
e3be8de5 4419 if (ldisc)
4420 lpage_send(ldisc, kbd_codepage,
4421 cbuf+!left_alt, 1+!!left_alt, 1);
a9c02454 4422 }
c9def1b8 4423 }
bca9517a 4424 show_mouseptr(0);
c9def1b8 4425 }
374330e2 4426
c9def1b8 4427 /* This is so the ALT-Numpad and dead keys work correctly. */
4428 keys[0] = 0;
4429
32874aea 4430 return p - output;
c9def1b8 4431 }
159eba53 4432 /* If we're definitly not building up an ALT-54321 then clear it */
32874aea 4433 if (!left_alt)
4434 keys[0] = 0;
4eeb7d09 4435 /* If we will be using alt_sum fix the 256s */
21d2b241 4436 else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4eeb7d09 4437 keys[0] = 10;
374330e2 4438 }
4439
dfca2656 4440 /*
4441 * ALT alone may or may not want to bring up the System menu.
4442 * If it's not meant to, we return 0 on presses or releases of
4443 * ALT, to show that we've swallowed the keystroke. Otherwise
4444 * we return -1, which means Windows will give the keystroke
4445 * its default handling (i.e. bring up the System menu).
4446 */
4447 if (wParam == VK_MENU && !cfg.alt_only)
4448 return 0;
374330e2 4449
c9def1b8 4450 return -1;
374330e2 4451}
4452
a8327734 4453void set_title(void *frontend, char *title)
32874aea 4454{
4455 sfree(window_name);
3d88e64d 4456 window_name = snewn(1 + strlen(title), char);
32874aea 4457 strcpy(window_name, title);
37508af4 4458 if (cfg.win_name_always || !IsIconic(hwnd))
32874aea 4459 SetWindowText(hwnd, title);
374330e2 4460}
4461
a8327734 4462void set_icon(void *frontend, char *title)
32874aea 4463{
4464 sfree(icon_name);
3d88e64d 4465 icon_name = snewn(1 + strlen(title), char);
32874aea 4466 strcpy(icon_name, title);
37508af4 4467 if (!cfg.win_name_always && IsIconic(hwnd))
32874aea 4468 SetWindowText(hwnd, title);
374330e2 4469}
4470
a8327734 4471void set_sbar(void *frontend, int total, int start, int page)
32874aea 4472{
374330e2 4473 SCROLLINFO si;
c9def1b8 4474
1ba99d2c 4475 if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
32874aea 4476 return;
c9def1b8 4477
374330e2 4478 si.cbSize = sizeof(si);
c9def1b8 4479 si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
374330e2 4480 si.nMin = 0;
4481 si.nMax = total - 1;
4482 si.nPage = page;
4483 si.nPos = start;
c1f5f956 4484 if (hwnd)
32874aea 4485 SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
374330e2 4486}
4487
a8327734 4488Context get_ctx(void *frontend)
32874aea 4489{
374330e2 4490 HDC hdc;
4491 if (hwnd) {
32874aea 4492 hdc = GetDC(hwnd);
374330e2 4493 if (hdc && pal)
32874aea 4494 SelectPalette(hdc, pal, FALSE);
374330e2 4495 return hdc;
4496 } else
4497 return NULL;
4498}
4499
32874aea 4500void free_ctx(Context ctx)
4501{
4502 SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4503 ReleaseDC(hwnd, ctx);
374330e2 4504}
4505
32874aea 4506static void real_palette_set(int n, int r, int g, int b)
4507{
374330e2 4508 if (pal) {
4509 logpal->palPalEntry[n].peRed = r;
4510 logpal->palPalEntry[n].peGreen = g;
4511 logpal->palPalEntry[n].peBlue = b;
4512 logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4513 colours[n] = PALETTERGB(r, g, b);
cecb13f6 4514 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
374330e2 4515 } else
4516 colours[n] = RGB(r, g, b);
4517}
4518
a8327734 4519void palette_set(void *frontend, int n, int r, int g, int b)
32874aea 4520{
cecb13f6 4521 if (n >= 16)
4522 n += 256 - 16;
4523 if (n > NALLCOLOURS)
4524 return;
4525 real_palette_set(n, r, g, b);
374330e2 4526 if (pal) {
a8327734 4527 HDC hdc = get_ctx(frontend);
32874aea 4528 UnrealizeObject(pal);
4529 RealizePalette(hdc);
4530 free_ctx(hdc);
6092b4ee 4531 } else {
4532 if (n == (ATTR_DEFBG>>ATTR_BGSHIFT))
4533 /* If Default Background changes, we need to ensure any
4534 * space between the text area and the window border is
4535 * redrawn. */
4536 InvalidateRect(hwnd, NULL, TRUE);
374330e2 4537 }
4538}
4539
a8327734 4540void palette_reset(void *frontend)
32874aea 4541{
374330e2 4542 int i;
4543
cecb13f6 4544 /* And this */
4545 for (i = 0; i < NALLCOLOURS; i++) {
374330e2 4546 if (pal) {
4547 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4548 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4549 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4550 logpal->palPalEntry[i].peFlags = 0;
4551 colours[i] = PALETTERGB(defpal[i].rgbtRed,
4552 defpal[i].rgbtGreen,
4553 defpal[i].rgbtBlue);
4554 } else
4555 colours[i] = RGB(defpal[i].rgbtRed,
32874aea 4556 defpal[i].rgbtGreen, defpal[i].rgbtBlue);
374330e2 4557 }
4558
4559 if (pal) {
4560 HDC hdc;
cecb13f6 4561 SetPaletteEntries(pal, 0, NALLCOLOURS, logpal->palPalEntry);
a8327734 4562 hdc = get_ctx(frontend);
32874aea 4563 RealizePalette(hdc);
4564 free_ctx(hdc);
6092b4ee 4565 } else {
4566 /* Default Background may have changed. Ensure any space between
4567 * text area and window border is redrawn. */
4568 InvalidateRect(hwnd, NULL, TRUE);
374330e2 4569 }
4570}
4571
a8327734 4572void write_aclip(void *frontend, char *data, int len, int must_deselect)
32874aea 4573{
374330e2 4574 HGLOBAL clipdata;
4575 void *lock;
4576
32874aea 4577 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
374330e2 4578 if (!clipdata)
4579 return;
32874aea 4580 lock = GlobalLock(clipdata);
374330e2 4581 if (!lock)
4582 return;
32874aea 4583 memcpy(lock, data, len);
4584 ((unsigned char *) lock)[len] = 0;
4585 GlobalUnlock(clipdata);
374330e2 4586
f0df44da 4587 if (!must_deselect)
32874aea 4588 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
f0df44da 4589
32874aea 4590 if (OpenClipboard(hwnd)) {
374330e2 4591 EmptyClipboard();
32874aea 4592 SetClipboardData(CF_TEXT, clipdata);
374330e2 4593 CloseClipboard();
4594 } else
32874aea 4595 GlobalFree(clipdata);
f0df44da 4596
4597 if (!must_deselect)
32874aea 4598 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
374330e2 4599}
4600
4eeb7d09 4601/*
4602 * Note: unlike write_aclip() this will not append a nul.
4603 */
c83c79bd 4604void write_clip(void *frontend, wchar_t * data, int *attr, int len, int must_deselect)
4eeb7d09 4605{
a7419ea4 4606 HGLOBAL clipdata, clipdata2, clipdata3;
4eeb7d09 4607 int len2;
a7419ea4 4608 void *lock, *lock2, *lock3;
4eeb7d09 4609
4610 len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4611
4612 clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4613 len * sizeof(wchar_t));
4614 clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4615
0e5e7f46 4616 if (!clipdata || !clipdata2) {
4eeb7d09 4617 if (clipdata)
4618 GlobalFree(clipdata);
4619 if (clipdata2)
4620 GlobalFree(clipdata2);
4621 return;
4622 }
4623 if (!(lock = GlobalLock(clipdata)))
4624 return;
4625 if (!(lock2 = GlobalLock(clipdata2)))
4626 return;
4627
4628 memcpy(lock, data, len * sizeof(wchar_t));
4629 WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4630
a7419ea4 4631 if (cfg.rtf_paste) {
4632 wchar_t unitab[256];
4633 char *rtf = NULL;
4634 unsigned char *tdata = (unsigned char *)lock2;
4635 wchar_t *udata = (wchar_t *)lock;
4636 int rtflen = 0, uindex = 0, tindex = 0;
4637 int rtfsize = 0;
4638 int multilen, blen, alen, totallen, i;
4639 char before[16], after[4];
c83c79bd 4640 int fgcolour, lastfgcolour = 0;
4641 int bgcolour, lastbgcolour = 0;
4642 int attrBold, lastAttrBold = 0;
4643 int attrUnder, lastAttrUnder = 0;
4644 int palette[NALLCOLOURS];
4645 int numcolours;
a7419ea4 4646
4647 get_unitab(CP_ACP, unitab, 0);
4648
9a30e26b 4649 rtfsize = 100 + strlen(cfg.font.name);
3d88e64d 4650 rtf = snewn(rtfsize, char);
c83c79bd 4651 rtflen = sprintf(rtf, "{\\rtf1\\ansi\\deff0{\\fonttbl\\f0\\fmodern %s;}\\f0\\fs%d",
4652 cfg.font.name, cfg.font.height*2);
4653
4654 /*
4655 * Add colour palette
4656 * {\colortbl ;\red255\green0\blue0;\red0\green0\blue128;}
4657 */
4658
4659 /*
4660 * First - Determine all colours in use
4661 * o Foregound and background colours share the same palette
4662 */
4663 if (attr) {
4664 memset(palette, 0, sizeof(palette));
4665 for (i = 0; i < (len-1); i++) {
4666 fgcolour = ((attr[i] & ATTR_FGMASK) >> ATTR_FGSHIFT);
4667 bgcolour = ((attr[i] & ATTR_BGMASK) >> ATTR_BGSHIFT);
4668
4669 if (attr[i] & ATTR_REVERSE) {
4670 int tmpcolour = fgcolour; /* Swap foreground and background */
4671 fgcolour = bgcolour;
4672 bgcolour = tmpcolour;
4673 }
4674
4675 if (bold_mode == BOLD_COLOURS && (attr[i] & ATTR_BOLD)) {
4676 if (fgcolour < 8) /* ANSI colours */
4677 fgcolour += 8;
4678 else if (fgcolour >= 256) /* Default colours */
4679 fgcolour ++;
4680 }
4681
4682 if (attr[i] & ATTR_BLINK) {
4683 if (bgcolour < 8) /* ANSI colours */
4684 bgcolour += 8;
4685 else if (bgcolour >= 256) /* Default colours */
4686 bgcolour ++;
4687 }
4688
4689 palette[fgcolour]++;
4690 palette[bgcolour]++;
4691 }
4692
4693 /*
4694 * Next - Create a reduced palette
4695 */
4696 numcolours = 0;
4697 for (i = 0; i < NALLCOLOURS; i++) {
4698 if (palette[i] != 0)
4699 palette[i] = ++numcolours;
4700 }
4701
4702 /*
4703 * Finally - Write the colour table
4704 */
4705 rtf = sresize(rtf, rtfsize + (numcolours * 25), char);
4706 strcat(rtf, "{\\colortbl ;");
4707 rtflen = strlen(rtf);
4708
4709 for (i = 0; i < NALLCOLOURS; i++) {
4710 if (palette[i] != 0) {
4711 rtflen += sprintf(&rtf[rtflen], "\\red%d\\green%d\\blue%d;", defpal[i].rgbtRed, defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4712 }
4713 }
4714 strcpy(&rtf[rtflen], "}");
4715 rtflen ++;
4716 }
a7419ea4 4717
4718 /*
4719 * We want to construct a piece of RTF that specifies the
4720 * same Unicode text. To do this we will read back in
4721 * parallel from the Unicode data in `udata' and the
4722 * non-Unicode data in `tdata'. For each character in
4723 * `tdata' which becomes the right thing in `udata' when
4724 * looked up in `unitab', we just copy straight over from
4725 * tdata. For each one that doesn't, we must WCToMB it
4726 * individually and produce a \u escape sequence.
4727 *
4728 * It would probably be more robust to just bite the bullet
4729 * and WCToMB each individual Unicode character one by one,
4730 * then MBToWC each one back to see if it was an accurate
4731 * translation; but that strikes me as a horrifying number
4732 * of Windows API calls so I want to see if this faster way
4733 * will work. If it screws up badly we can always revert to
4734 * the simple and slow way.
4735 */
4736 while (tindex < len2 && uindex < len &&
4737 tdata[tindex] && udata[uindex]) {
4738 if (tindex + 1 < len2 &&
4739 tdata[tindex] == '\r' &&
4740 tdata[tindex+1] == '\n') {
4741 tindex++;
4742 uindex++;
c83c79bd 4743 }
4744
4745 /*
4746 * Set text attributes
4747 */
4748 if (attr) {
4749 if (rtfsize < rtflen + 64) {
4750 rtfsize = rtflen + 512;
4751 rtf = sresize(rtf, rtfsize, char);
4752 }
4753
4754 /*
4755 * Determine foreground and background colours
4756 */
4757 fgcolour = ((attr[tindex] & ATTR_FGMASK) >> ATTR_FGSHIFT);
4758 bgcolour = ((attr[tindex] & ATTR_BGMASK) >> ATTR_BGSHIFT);
4759
4760 if (attr[tindex] & ATTR_REVERSE) {
4761 int tmpcolour = fgcolour; /* Swap foreground and background */
4762 fgcolour = bgcolour;
4763 bgcolour = tmpcolour;
4764 }
4765
4766 if (bold_mode == BOLD_COLOURS && (attr[tindex] & ATTR_BOLD)) {
4767 if (fgcolour < 8) /* ANSI colours */
4768 fgcolour += 8;
4769 else if (fgcolour >= 256) /* Default colours */
4770 fgcolour ++;
4771 }
4772
4773 if (attr[tindex] & ATTR_BLINK) {
4774 if (bgcolour < 8) /* ANSI colours */
4775 bgcolour += 8;
4776 else if (bgcolour >= 256) /* Default colours */
4777 bgcolour ++;
4778 }
4779
4780 /*
4781 * Collect other attributes
4782 */
4783 if (bold_mode != BOLD_COLOURS)
4784 attrBold = attr[tindex] & ATTR_BOLD;
4785 else
4786 attrBold = 0;
4787
4788 attrUnder = attr[tindex] & ATTR_UNDER;
4789
4790 /*
4791 * Reverse video
4792 * o If video isn't reversed, ignore colour attributes for default foregound
4793 * or background.
4794 * o Special case where bolded text is displayed using the default foregound
4795 * and background colours - force to bolded RTF.
4796 */
4797 if (!(attr[tindex] & ATTR_REVERSE)) {
4798 if (bgcolour >= 256) /* Default color */
4799 bgcolour = -1; /* No coloring */
4800
4801 if (fgcolour >= 256) { /* Default colour */
4802 if (bold_mode == BOLD_COLOURS && (fgcolour & 1) && bgcolour == -1)
4803 attrBold = ATTR_BOLD; /* Emphasize text with bold attribute */
4804
4805 fgcolour = -1; /* No coloring */
4806 }
4807 }
4808
4809 /*
4810 * Write RTF text attributes
4811 */
4812 if (lastfgcolour != fgcolour) {
4813 lastfgcolour = fgcolour;
4814 rtflen += sprintf(&rtf[rtflen], "\\cf%d ", (fgcolour >= 0) ? palette[fgcolour] : 0);
4815 }
4816
4817 if (lastbgcolour != bgcolour) {
4818 lastbgcolour = bgcolour;
4819 rtflen += sprintf(&rtf[rtflen], "\\highlight%d ", (bgcolour >= 0) ? palette[bgcolour] : 0);
4820 }
4821
4822 if (lastAttrBold != attrBold) {
4823 lastAttrBold = attrBold;
4824 rtflen += sprintf(&rtf[rtflen], "%s", attrBold ? "\\b " : "\\b0 ");
4825 }
4826
4827 if (lastAttrUnder != attrUnder) {
4828 lastAttrUnder = attrUnder;
4829 rtflen += sprintf(&rtf[rtflen], "%s", attrUnder ? "\\ul " : "\\ulnone ");
4830 }
a7419ea4 4831 }
c83c79bd 4832
a7419ea4 4833 if (unitab[tdata[tindex]] == udata[uindex]) {
4834 multilen = 1;
4835 before[0] = '\0';
4836 after[0] = '\0';
4837 blen = alen = 0;
4838 } else {
4839 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4840 NULL, 0, NULL, NULL);
4841 if (multilen != 1) {
c3b032a6 4842 blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4843 udata[uindex]);
a7419ea4 4844 alen = 1; strcpy(after, "}");
4845 } else {
4846 blen = sprintf(before, "\\u%d", udata[uindex]);
4847 alen = 0; after[0] = '\0';
4848 }
4849 }
4850 assert(tindex + multilen <= len2);
4851 totallen = blen + alen;
4852 for (i = 0; i < multilen; i++) {
4853 if (tdata[tindex+i] == '\\' ||
4854 tdata[tindex+i] == '{' ||
4855 tdata[tindex+i] == '}')
4856 totallen += 2;
4857 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4858 totallen += 6; /* \par\r\n */
4859 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4860 totallen += 4;
4861 else
4862 totallen++;
4863 }
4864
4865 if (rtfsize < rtflen + totallen + 3) {
4866 rtfsize = rtflen + totallen + 512;
3d88e64d 4867 rtf = sresize(rtf, rtfsize, char);
a7419ea4 4868 }
4869
4870 strcpy(rtf + rtflen, before); rtflen += blen;
4871 for (i = 0; i < multilen; i++) {
4872 if (tdata[tindex+i] == '\\' ||
4873 tdata[tindex+i] == '{' ||
4874 tdata[tindex+i] == '}') {
4875 rtf[rtflen++] = '\\';
4876 rtf[rtflen++] = tdata[tindex+i];
4877 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4878 rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4879 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4880 rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4881 } else {
4882 rtf[rtflen++] = tdata[tindex+i];
4883 }
4884 }
4885 strcpy(rtf + rtflen, after); rtflen += alen;
4886
4887 tindex += multilen;
4888 uindex++;
4889 }
4890
c83c79bd 4891 rtf[rtflen++] = '}'; /* Terminate RTF stream */
4892 rtf[rtflen++] = '\0';
4893 rtf[rtflen++] = '\0';
a7419ea4 4894
4895 clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4896 if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
c83c79bd 4897 memcpy(lock3, rtf, rtflen);
a7419ea4 4898 GlobalUnlock(clipdata3);
4899 }
4900 sfree(rtf);
4901 } else
4902 clipdata3 = NULL;
4903
4eeb7d09 4904 GlobalUnlock(clipdata);
4905 GlobalUnlock(clipdata2);
4906
4907 if (!must_deselect)
4908 SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4909
4910 if (OpenClipboard(hwnd)) {
4911 EmptyClipboard();
4912 SetClipboardData(CF_UNICODETEXT, clipdata);
4913 SetClipboardData(CF_TEXT, clipdata2);
a7419ea4 4914 if (clipdata3)
4915 SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4eeb7d09 4916 CloseClipboard();
4917 } else {
4918 GlobalFree(clipdata);
4919 GlobalFree(clipdata2);
4920 }
4921
4922 if (!must_deselect)
4923 SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4924}
4925
1d432454 4926static DWORD WINAPI clipboard_read_threadfunc(void *param)
32874aea 4927{
1d432454 4928 HWND hwnd = (HWND)param;
4929 HGLOBAL clipdata;
374330e2 4930
1d432454 4931 if (OpenClipboard(NULL)) {
2d466ffd 4932 if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
1d432454 4933 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)1, (LPARAM)clipdata);
4934 } else if ((clipdata = GetClipboardData(CF_TEXT))) {
4935 SendMessage(hwnd, WM_GOT_CLIPDATA, (WPARAM)0, (LPARAM)clipdata);
4936 }
4937 CloseClipboard();
4938 }
4939
4940 return 0;
4941}
4942
4943static int process_clipdata(HGLOBAL clipdata, int unicode)
4944{
1d432454 4945 sfree(clipboard_contents);
4946 clipboard_contents = NULL;
4947 clipboard_length = 0;
4948
4949 if (unicode) {
4950 wchar_t *p = GlobalLock(clipdata);
4951 wchar_t *p2;
4952
4953 if (p) {
4954 /* Unwilling to rely on Windows having wcslen() */
4955 for (p2 = p; *p2; p2++);
4956 clipboard_length = p2 - p;
4957 clipboard_contents = snewn(clipboard_length + 1, wchar_t);
4958 memcpy(clipboard_contents, p, clipboard_length * sizeof(wchar_t));
4959 clipboard_contents[clipboard_length] = L'\0';
4960 return TRUE;
4961 }
4962 } else {
4963 char *s = GlobalLock(clipdata);
4964 int i;
4965
4966 if (s) {
4eeb7d09 4967 i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
1d432454 4968 clipboard_contents = snewn(i, wchar_t);
4969 MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1,
4970 clipboard_contents, i);
4971 clipboard_length = i - 1;
4972 clipboard_contents[clipboard_length] = L'\0';
4973 return TRUE;
4974 }
374330e2 4975 }
4976
1d432454 4977 return FALSE;
4978}
4979
4980void request_paste(void *frontend)
4981{
4982 /*
4983 * I always thought pasting was synchronous in Windows; the
4984 * clipboard access functions certainly _look_ synchronous,
4985 * unlike the X ones. But in fact it seems that in some
4986 * situations the contents of the clipboard might not be
4987 * immediately available, and the clipboard-reading functions
4988 * may block. This leads to trouble if the application
4989 * delivering the clipboard data has to get hold of it by -
4990 * for example - talking over a network connection which is
4991 * forwarded through this very PuTTY.
4992 *
4993 * Hence, we spawn a subthread to read the clipboard, and do
4994 * our paste when it's finished. The thread will send a
4995 * message back to our main window when it terminates, and
4996 * that tells us it's OK to paste.
4997 */
4998 DWORD in_threadid; /* required for Win9x */
4999 CreateThread(NULL, 0, clipboard_read_threadfunc,
5000 hwnd, 0, &in_threadid);
5001}
5002
5003void get_clip(void *frontend, wchar_t **p, int *len)
5004{
5005 if (p) {
5006 *p = clipboard_contents;
5007 *len = clipboard_length;
5008 }
374330e2 5009}
5010
4eeb7d09 5011#if 0
374330e2 5012/*
5013 * Move `lines' lines from position `from' to position `to' in the
5014 * window.
5015 */
a8327734 5016void optimised_move(void *frontend, int to, int from, int lines)
32874aea 5017{
374330e2 5018 RECT r;
f67b4e85 5019 int min, max;
374330e2 5020
5021 min = (to < from ? to : from);
5022 max = to + from - min;
374330e2 5023
5a73255e 5024 r.left = offset_width;
887035a5 5025 r.right = offset_width + term->cols * font_width;
5a73255e 5026 r.top = offset_height + min * font_height;
5027 r.bottom = offset_height + (max + lines) * font_height;
32874aea 5028 ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
374330e2 5029}
4eeb7d09 5030#endif
374330e2 5031
5032/*
5033 * Print a message box and perform a fatal exit.
5034 */
32874aea 5035void fatalbox(char *fmt, ...)
5036{
374330e2 5037 va_list ap;
971bcc0a 5038 char *stuff, morestuff[100];
374330e2 5039
5040 va_start(ap, fmt);
971bcc0a 5041 stuff = dupvprintf(fmt, ap);
374330e2 5042 va_end(ap);
f6f450e2 5043 sprintf(morestuff, "%.70s Fatal Error", appname);
5044 MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
971bcc0a 5045 sfree(stuff);
93b581bd 5046 cleanup_exit(1);
374330e2 5047}
5048
5049/*
1709795f 5050 * Print a modal (Really Bad) message box and perform a fatal exit.
5051 */
5052void modalfatalbox(char *fmt, ...)
5053{
5054 va_list ap;
971bcc0a 5055 char *stuff, morestuff[100];
1709795f 5056
5057 va_start(ap, fmt);
971bcc0a 5058 stuff = dupvprintf(fmt, ap);
1709795f 5059 va_end(ap);
f6f450e2 5060 sprintf(morestuff, "%.70s Fatal Error", appname);
5061 MessageBox(hwnd, stuff, morestuff,
1709795f 5062 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
971bcc0a 5063 sfree(stuff);
1709795f 5064 cleanup_exit(1);
5065}
5066
9099600a 5067DECL_WINDOWS_FUNCTION(static, BOOL, FlashWindowEx, (PFLASHWINFO));
09644e07 5068
5069static void init_flashwindow(void)
5070{
bda368a5 5071 HMODULE user32_module = load_system32_dll("user32.dll");
9099600a 5072 GET_WINDOWS_FUNCTION(user32_module, FlashWindowEx);
09644e07 5073}
5074
5075static BOOL flash_window_ex(DWORD dwFlags, UINT uCount, DWORD dwTimeout)
5076{
5077 if (p_FlashWindowEx) {
5078 FLASHWINFO fi;
5079 fi.cbSize = sizeof(fi);
5080 fi.hwnd = hwnd;
5081 fi.dwFlags = dwFlags;
5082 fi.uCount = uCount;
5083 fi.dwTimeout = dwTimeout;
5084 return (*p_FlashWindowEx)(&fi);
5085 }
5086 else
5087 return FALSE; /* shrug */
5088}
5089
39934deb 5090static void flash_window(int mode);
5091static long next_flash;
5092static int flashing = 0;
5093
09644e07 5094/*
5095 * Timer for platforms where we must maintain window flashing manually
5096 * (e.g., Win95).
5097 */
39934deb 5098static void flash_window_timer(void *ctx, long now)
5099{
5100 if (flashing && now - next_flash >= 0) {
5101 flash_window(1);
5102 }
5103}
5104
1709795f 5105/*
f8a28d1f 5106 * Manage window caption / taskbar flashing, if enabled.
5107 * 0 = stop, 1 = maintain, 2 = start
5108 */
5109static void flash_window(int mode)
5110{
f8a28d1f 5111 if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
5112 /* stop */
5113 if (flashing) {
f8a28d1f 5114 flashing = 0;
09644e07 5115 if (p_FlashWindowEx)
5116 flash_window_ex(FLASHW_STOP, 0, 0);
5117 else
5118 FlashWindow(hwnd, FALSE);
f8a28d1f 5119 }
5120
5121 } else if (mode == 2) {
5122 /* start */
5123 if (!flashing) {
f8a28d1f 5124 flashing = 1;
09644e07 5125 if (p_FlashWindowEx) {
5126 /* For so-called "steady" mode, we use uCount=2, which
5127 * seems to be the traditional number of flashes used
5128 * by user notifications (e.g., by Explorer).
5129 * uCount=0 appears to enable continuous flashing, per
5130 * "flashing" mode, although I haven't seen this
5131 * documented. */
5132 flash_window_ex(FLASHW_ALL | FLASHW_TIMER,
5133 (cfg.beep_ind == B_IND_FLASH ? 0 : 2),
5134 0 /* system cursor blink rate */);
5135 /* No need to schedule timer */
5136 } else {
5137 FlashWindow(hwnd, TRUE);
5138 next_flash = schedule_timer(450, flash_window_timer, hwnd);
5139 }
f8a28d1f 5140 }
5141
5142 } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
5143 /* maintain */
09644e07 5144 if (flashing && !p_FlashWindowEx) {
39934deb 5145 FlashWindow(hwnd, TRUE); /* toggle */
5146 next_flash = schedule_timer(450, flash_window_timer, hwnd);
f8a28d1f 5147 }
5148 }
5149}
5150
5151/*
374330e2 5152 * Beep.
5153 */
860a34f8 5154void do_beep(void *frontend, int mode)
32874aea 5155{
03169ad0 5156 if (mode == BELL_DEFAULT) {
eb04402e 5157 /*
5158 * For MessageBeep style bells, we want to be careful of
5159 * timing, because they don't have the nice property of
5160 * PlaySound bells that each one cancels the previous
5161 * active one. So we limit the rate to one per 50ms or so.
5162 */
5163 static long lastbeep = 0;
d51cdf1e 5164 long beepdiff;
eb04402e 5165
d51cdf1e 5166 beepdiff = GetTickCount() - lastbeep;
eb04402e 5167 if (beepdiff >= 0 && beepdiff < 50)
5168 return;
156686ef 5169 MessageBeep(MB_OK);
d51cdf1e 5170 /*
5171 * The above MessageBeep call takes time, so we record the
5172 * time _after_ it finishes rather than before it starts.
5173 */
5174 lastbeep = GetTickCount();
03169ad0 5175 } else if (mode == BELL_WAVEFILE) {
9a30e26b 5176 if (!PlaySound(cfg.bell_wavefile.path, NULL,
5177 SND_ASYNC | SND_FILENAME)) {
850323f9 5178 char buf[sizeof(cfg.bell_wavefile.path) + 80];
f6f450e2 5179 char otherbuf[100];
03169ad0 5180 sprintf(buf, "Unable to play sound file\n%s\n"
debe102c 5181 "Using default sound instead", cfg.bell_wavefile.path);
f6f450e2 5182 sprintf(otherbuf, "%.70s Sound Error", appname);
5183 MessageBox(hwnd, buf, otherbuf,
32874aea 5184 MB_OK | MB_ICONEXCLAMATION);
03169ad0 5185 cfg.beep = BELL_DEFAULT;
5186 }
85f6b361 5187 } else if (mode == BELL_PCSPEAKER) {
5188 static long lastbeep = 0;
5189 long beepdiff;
5190
5191 beepdiff = GetTickCount() - lastbeep;
5192 if (beepdiff >= 0 && beepdiff < 50)
5193 return;
5194
5195 /*
5196 * We must beep in different ways depending on whether this
5197 * is a 95-series or NT-series OS.
5198 */
5199 if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
5200 Beep(800, 100);
5201 else
5202 MessageBeep(-1);
5203 lastbeep = GetTickCount();
03169ad0 5204 }
f8a28d1f 5205 /* Otherwise, either visual bell or disabled; do nothing here */
887035a5 5206 if (!term->has_focus) {
f8a28d1f 5207 flash_window(2); /* start */
5208 }
374330e2 5209}
8f57d753 5210
5211/*
68f9b3d9 5212 * Minimise or restore the window in response to a server-side
5213 * request.
5214 */
a8327734 5215void set_iconic(void *frontend, int iconic)
68f9b3d9 5216{
5217 if (IsIconic(hwnd)) {
5218 if (!iconic)
5219 ShowWindow(hwnd, SW_RESTORE);
5220 } else {
5221 if (iconic)
5222 ShowWindow(hwnd, SW_MINIMIZE);
5223 }
5224}
5225
5226/*
5227 * Move the window in response to a server-side request.
5228 */
a8327734 5229void move_window(void *frontend, int x, int y)
68f9b3d9 5230{
d1e0a352 5231 if (cfg.resize_action == RESIZE_DISABLED ||
5232 cfg.resize_action == RESIZE_FONT ||
5233 IsZoomed(hwnd))
5234 return;
5235
68f9b3d9 5236 SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
5237}
5238
5239/*
5240 * Move the window to the top or bottom of the z-order in response
5241 * to a server-side request.
5242 */
a8327734 5243void set_zorder(void *frontend, int top)
68f9b3d9 5244{
1ba99d2c 5245 if (cfg.alwaysontop)
68f9b3d9 5246 return; /* ignore */
5247 SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
5248 SWP_NOMOVE | SWP_NOSIZE);
5249}
5250
5251/*
5252 * Refresh the window in response to a server-side request.
5253 */
a8327734 5254void refresh_window(void *frontend)
68f9b3d9 5255{
5256 InvalidateRect(hwnd, NULL, TRUE);
5257}
5258
5259/*
5260 * Maximise or restore the window in response to a server-side
5261 * request.
5262 */
a8327734 5263void set_zoomed(void *frontend, int zoomed)
68f9b3d9 5264{
1ba99d2c 5265 if (IsZoomed(hwnd)) {
5266 if (!zoomed)
5267 ShowWindow(hwnd, SW_RESTORE);
68f9b3d9 5268 } else {
5269 if (zoomed)
5270 ShowWindow(hwnd, SW_MAXIMIZE);
5271 }
5272}
5273
5274/*
5275 * Report whether the window is iconic, for terminal reports.
5276 */
a8327734 5277int is_iconic(void *frontend)
68f9b3d9 5278{
5279 return IsIconic(hwnd);
5280}
5281
5282/*
5283 * Report the window's position, for terminal reports.
5284 */
a8327734 5285void get_window_pos(void *frontend, int *x, int *y)
68f9b3d9 5286{
5287 RECT r;
5288 GetWindowRect(hwnd, &r);
5289 *x = r.left;
5290 *y = r.top;
5291}
5292
5293/*
5294 * Report the window's pixel size, for terminal reports.
5295 */
a8327734 5296void get_window_pixels(void *frontend, int *x, int *y)
68f9b3d9 5297{
5298 RECT r;
5299 GetWindowRect(hwnd, &r);
5300 *x = r.right - r.left;
5301 *y = r.bottom - r.top;
5302}
5303
5304/*
5305 * Return the window or icon title.
5306 */
a8327734 5307char *get_window_title(void *frontend, int icon)
68f9b3d9 5308{
5309 return icon ? icon_name : window_name;
5310}
1ba99d2c 5311
5312/*
5313 * See if we're in full-screen mode.
5314 */
4e95095a 5315static int is_full_screen()
1ba99d2c 5316{
5317 if (!IsZoomed(hwnd))
5318 return FALSE;
1e5eefb6 5319 if (GetWindowLongPtr(hwnd, GWL_STYLE) & WS_CAPTION)
1ba99d2c 5320 return FALSE;
5321 return TRUE;
5322}
5323
d0f1bcb4 5324/* Get the rect/size of a full screen window using the nearest available
5325 * monitor in multimon systems; default to something sensible if only
5326 * one monitor is present. */
5327static int get_fullscreen_rect(RECT * ss)
5328{
5d145a14 5329#if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
d0f1bcb4 5330 HMONITOR mon;
5331 MONITORINFO mi;
5332 mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
5333 mi.cbSize = sizeof(mi);
5334 GetMonitorInfo(mon, &mi);
5335
5336 /* structure copy */
5337 *ss = mi.rcMonitor;
5338 return TRUE;
5339#else
5340/* could also use code like this:
5341 ss->left = ss->top = 0;
5342 ss->right = GetSystemMetrics(SM_CXSCREEN);
5343 ss->bottom = GetSystemMetrics(SM_CYSCREEN);
5344*/
e6f8202f 5345 return GetClientRect(GetDesktopWindow(), ss);
d0f1bcb4 5346#endif
5347}
5348
5349
1ba99d2c 5350/*
5351 * Go full-screen. This should only be called when we are already
5352 * maximised.
5353 */
4e95095a 5354static void make_full_screen()
1ba99d2c 5355{
5356 DWORD style;
d0f1bcb4 5357 RECT ss;
1ba99d2c 5358
5359 assert(IsZoomed(hwnd));
5360
d0f1bcb4 5361 if (is_full_screen())
5362 return;
5363
1ba99d2c 5364 /* Remove the window furniture. */
1e5eefb6 5365 style = GetWindowLongPtr(hwnd, GWL_STYLE);
1ba99d2c 5366 style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
5367 if (cfg.scrollbar_in_fullscreen)
5368 style |= WS_VSCROLL;
5369 else
5370 style &= ~WS_VSCROLL;
1e5eefb6 5371 SetWindowLongPtr(hwnd, GWL_STYLE, style);
1ba99d2c 5372
5373 /* Resize ourselves to exactly cover the nearest monitor. */
d0f1bcb4 5374 get_fullscreen_rect(&ss);
5375 SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
5376 ss.right - ss.left,
5377 ss.bottom - ss.top,
5378 SWP_FRAMECHANGED);
1ba99d2c 5379
1620020b 5380 /* We may have changed size as a result */
5381
5382 reset_window(0);
5383
52c70126 5384 /* Tick the menu item in the System and context menus. */
5385 {
5386 int i;
5387 for (i = 0; i < lenof(popup_menus); i++)
5388 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_CHECKED);
5389 }
1ba99d2c 5390}
5391
5392/*
5393 * Clear the full-screen attributes.
5394 */
4e95095a 5395static void clear_full_screen()
1ba99d2c 5396{
5397 DWORD oldstyle, style;
5398
5399 /* Reinstate the window furniture. */
1e5eefb6 5400 style = oldstyle = GetWindowLongPtr(hwnd, GWL_STYLE);
811f10b3 5401 style |= WS_CAPTION | WS_BORDER;
5402 if (cfg.resize_action == RESIZE_DISABLED)
5403 style &= ~WS_THICKFRAME;
5404 else
5405 style |= WS_THICKFRAME;
1ba99d2c 5406 if (cfg.scrollbar)
5407 style |= WS_VSCROLL;
5408 else
5409 style &= ~WS_VSCROLL;
5410 if (style != oldstyle) {
1e5eefb6 5411 SetWindowLongPtr(hwnd, GWL_STYLE, style);
1ba99d2c 5412 SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
5413 SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
5414 SWP_FRAMECHANGED);
5415 }
5416
52c70126 5417 /* Untick the menu item in the System and context menus. */
5418 {
5419 int i;
5420 for (i = 0; i < lenof(popup_menus); i++)
5421 CheckMenuItem(popup_menus[i].menu, IDM_FULLSCREEN, MF_UNCHECKED);
5422 }
1ba99d2c 5423}
5424
5425/*
5426 * Toggle full-screen mode.
5427 */
4e95095a 5428static void flip_full_screen()
1ba99d2c 5429{
5430 if (is_full_screen()) {
5431 ShowWindow(hwnd, SW_RESTORE);
5432 } else if (IsZoomed(hwnd)) {
5433 make_full_screen();
5434 } else {
5435 SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
5436 ShowWindow(hwnd, SW_MAXIMIZE);
5437 }
5438}
ab2c86b9 5439
b9d7bcad 5440void frontend_keypress(void *handle)
ab2c86b9 5441{
5442 /*
5443 * Keypress termination in non-Close-On-Exit mode is not
5444 * currently supported in PuTTY proper, because the window
5445 * always has a perfectly good Close button anyway. So we do
5446 * nothing here.
5447 */
5448 return;
5449}
fbf6cb3b 5450
5451int from_backend(void *frontend, int is_stderr, const char *data, int len)
5452{
5453 return term_data(term, is_stderr, data, len);
5454}
c44bf5bd 5455
edd0cb8a 5456int from_backend_untrusted(void *frontend, const char *data, int len)
5457{
5458 return term_data_untrusted(term, data, len);
5459}
5460
5461int get_userpass_input(prompts_t *p, unsigned char *in, int inlen)
5462{
5463 int ret;
5464 ret = cmdline_get_passwd_input(p, in, inlen);
5465 if (ret == -1)
5466 ret = term_get_userpass_input(term, p, in, inlen);
5467 return ret;
5468}
5469
c44bf5bd 5470void agent_schedule_callback(void (*callback)(void *, void *, int),
5471 void *callback_ctx, void *data, int len)
5472{
5473 struct agent_callback *c = snew(struct agent_callback);
5474 c->callback = callback;
5475 c->callback_ctx = callback_ctx;
5476 c->data = data;
5477 c->len = len;
5478 PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);
5479}