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