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