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