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