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