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