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