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