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