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