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