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