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