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