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