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