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