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