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