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