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