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