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