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