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