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