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