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