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