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