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