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