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