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