]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - window.c
Yet more trunk merges. Jacob's SSH signals stuff, some docs changes,
[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  * This is a wrapper to ExtTextOut() to force Windows to display
1160  * the precise glyphs we give it. Otherwise it would do its own
1161  * bidi and Arabic shaping, and we would end up uncertain which
1162  * characters it had put where.
1163  */
1164 static void exact_textout(HDC hdc, int x, int y, CONST RECT *lprc,
1165                           unsigned short *lpString, UINT cbCount,
1166                           CONST INT *lpDx)
1167 {
1168
1169     GCP_RESULTSW gcpr;
1170     char *buffer = snewn(cbCount*2+2, char);
1171     char *classbuffer = snewn(cbCount, char);
1172     memset(&gcpr, 0, sizeof(gcpr));
1173     memset(buffer, 0, cbCount*2+2);
1174     memset(classbuffer, GCPCLASS_NEUTRAL, cbCount);
1175
1176     gcpr.lStructSize = sizeof(gcpr);
1177     gcpr.lpGlyphs = (void *)buffer;
1178     gcpr.lpClass = classbuffer;
1179     gcpr.nGlyphs = cbCount;
1180
1181     GetCharacterPlacementW(hdc, lpString, cbCount, 0, &gcpr,
1182                            FLI_MASK | GCP_CLASSIN);
1183
1184     ExtTextOut(hdc, x, y, ETO_GLYPH_INDEX | ETO_CLIPPED | ETO_OPAQUE, lprc,
1185                buffer, cbCount, lpDx);
1186 }
1187
1188 /*
1189  * Initialise all the fonts we will need initially. There may be as many as
1190  * three or as few as one.  The other (poentially) twentyone fonts are done
1191  * if/when they are needed.
1192  *
1193  * We also:
1194  *
1195  * - check the font width and height, correcting our guesses if
1196  *   necessary.
1197  *
1198  * - verify that the bold font is the same width as the ordinary
1199  *   one, and engage shadow bolding if not.
1200  * 
1201  * - verify that the underlined font is the same width as the
1202  *   ordinary one (manual underlining by means of line drawing can
1203  *   be done in a pinch).
1204  */
1205 static void init_fonts(int pick_width, int pick_height)
1206 {
1207     TEXTMETRIC tm;
1208     CPINFO cpinfo;
1209     int fontsize[3];
1210     int i;
1211     HDC hdc;
1212     int fw_dontcare, fw_bold;
1213
1214     for (i = 0; i < FONT_MAXNO; i++)
1215         fonts[i] = NULL;
1216
1217     bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
1218     und_mode = UND_FONT;
1219
1220     if (cfg.font.isbold) {
1221         fw_dontcare = FW_BOLD;
1222         fw_bold = FW_HEAVY;
1223     } else {
1224         fw_dontcare = FW_DONTCARE;
1225         fw_bold = FW_BOLD;
1226     }
1227
1228     hdc = GetDC(hwnd);
1229
1230     if (pick_height)
1231         font_height = pick_height;
1232     else {
1233         font_height = cfg.font.height;
1234         if (font_height > 0) {
1235             font_height =
1236                 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1237         }
1238     }
1239     font_width = pick_width;
1240
1241 #define f(i,c,w,u) \
1242     fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1243                            c, OUT_DEFAULT_PRECIS, \
1244                            CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, \
1245                            FIXED_PITCH | FF_DONTCARE, cfg.font.name)
1246
1247     f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);
1248
1249     lfont.lfHeight = font_height;
1250     lfont.lfWidth = font_width;
1251     lfont.lfEscapement = 0;
1252     lfont.lfOrientation  = 0;
1253     lfont.lfWeight  = fw_dontcare;
1254     lfont.lfItalic = FALSE;
1255     lfont.lfUnderline = FALSE;
1256     lfont.lfStrikeOut = FALSE;
1257     lfont.lfCharSet = cfg.font.charset;
1258     lfont.lfOutPrecision = OUT_DEFAULT_PRECIS;
1259     lfont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1260     lfont.lfQuality = DEFAULT_QUALITY;
1261     lfont.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE;
1262     strncpy(lfont.lfFaceName, cfg.font.name, LF_FACESIZE);
1263
1264     SelectObject(hdc, fonts[FONT_NORMAL]);
1265     GetTextMetrics(hdc, &tm);
1266
1267     if (pick_width == 0 || pick_height == 0) {
1268         font_height = tm.tmHeight;
1269         font_width = tm.tmAveCharWidth;
1270     }
1271     font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1272
1273 #ifdef RDB_DEBUG_PATCH
1274     debug(23, "Primary font H=%d, AW=%d, MW=%d",
1275             tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1276 #endif
1277
1278     {
1279         CHARSETINFO info;
1280         DWORD cset = tm.tmCharSet;
1281         memset(&info, 0xFF, sizeof(info));
1282
1283         /* !!! Yes the next line is right */
1284         if (cset == OEM_CHARSET)
1285             ucsdata.font_codepage = GetOEMCP();
1286         else
1287             if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1288                 ucsdata.font_codepage = info.ciACP;
1289         else
1290             ucsdata.font_codepage = -1;
1291
1292         GetCPInfo(ucsdata.font_codepage, &cpinfo);
1293         ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1294     }
1295
1296     f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);
1297
1298     /*
1299      * Some fonts, e.g. 9-pt Courier, draw their underlines
1300      * outside their character cell. We successfully prevent
1301      * screen corruption by clipping the text output, but then
1302      * we lose the underline completely. Here we try to work
1303      * out whether this is such a font, and if it is, we set a
1304      * flag that causes underlines to be drawn by hand.
1305      *
1306      * Having tried other more sophisticated approaches (such
1307      * as examining the TEXTMETRIC structure or requesting the
1308      * height of a string), I think we'll do this the brute
1309      * force way: we create a small bitmap, draw an underlined
1310      * space on it, and test to see whether any pixels are
1311      * foreground-coloured. (Since we expect the underline to
1312      * go all the way across the character cell, we only search
1313      * down a single column of the bitmap, half way across.)
1314      */
1315     {
1316         HDC und_dc;
1317         HBITMAP und_bm, und_oldbm;
1318         int i, gotit;
1319         COLORREF c;
1320
1321         und_dc = CreateCompatibleDC(hdc);
1322         und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1323         und_oldbm = SelectObject(und_dc, und_bm);
1324         SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1325         SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1326         SetTextColor(und_dc, RGB(255, 255, 255));
1327         SetBkColor(und_dc, RGB(0, 0, 0));
1328         SetBkMode(und_dc, OPAQUE);
1329         ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1330         gotit = FALSE;
1331         for (i = 0; i < font_height; i++) {
1332             c = GetPixel(und_dc, font_width / 2, i);
1333             if (c != RGB(0, 0, 0))
1334                 gotit = TRUE;
1335         }
1336         SelectObject(und_dc, und_oldbm);
1337         DeleteObject(und_bm);
1338         DeleteDC(und_dc);
1339         if (!gotit) {
1340             und_mode = UND_LINE;
1341             DeleteObject(fonts[FONT_UNDERLINE]);
1342             fonts[FONT_UNDERLINE] = 0;
1343         }
1344     }
1345
1346     if (bold_mode == BOLD_FONT) {
1347         f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);
1348     }
1349 #undef f
1350
1351     descent = tm.tmAscent + 1;
1352     if (descent >= font_height)
1353         descent = font_height - 1;
1354
1355     for (i = 0; i < 3; i++) {
1356         if (fonts[i]) {
1357             if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1358                 fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
1359             else
1360                 fontsize[i] = -i;
1361         } else
1362             fontsize[i] = -i;
1363     }
1364
1365     ReleaseDC(hwnd, hdc);
1366
1367     if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1368         und_mode = UND_LINE;
1369         DeleteObject(fonts[FONT_UNDERLINE]);
1370         fonts[FONT_UNDERLINE] = 0;
1371     }
1372
1373     if (bold_mode == BOLD_FONT &&
1374         fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1375         bold_mode = BOLD_SHADOW;
1376         DeleteObject(fonts[FONT_BOLD]);
1377         fonts[FONT_BOLD] = 0;
1378     }
1379     fontflag[0] = fontflag[1] = fontflag[2] = 1;
1380
1381     init_ucs(&cfg, &ucsdata);
1382 }
1383
1384 static void another_font(int fontno)
1385 {
1386     int basefont;
1387     int fw_dontcare, fw_bold;
1388     int c, u, w, x;
1389     char *s;
1390
1391     if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1392         return;
1393
1394     basefont = (fontno & ~(FONT_BOLDUND));
1395     if (basefont != fontno && !fontflag[basefont])
1396         another_font(basefont);
1397
1398     if (cfg.font.isbold) {
1399         fw_dontcare = FW_BOLD;
1400         fw_bold = FW_HEAVY;
1401     } else {
1402         fw_dontcare = FW_DONTCARE;
1403         fw_bold = FW_BOLD;
1404     }
1405
1406     c = cfg.font.charset;
1407     w = fw_dontcare;
1408     u = FALSE;
1409     s = cfg.font.name;
1410     x = font_width;
1411
1412     if (fontno & FONT_WIDE)
1413         x *= 2;
1414     if (fontno & FONT_NARROW)
1415         x = (x+1)/2;
1416     if (fontno & FONT_OEM)
1417         c = OEM_CHARSET;
1418     if (fontno & FONT_BOLD)
1419         w = fw_bold;
1420     if (fontno & FONT_UNDERLINE)
1421         u = TRUE;
1422
1423     fonts[fontno] =
1424         CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1425                    FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1426                    CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
1427                    FIXED_PITCH | FF_DONTCARE, s);
1428
1429     fontflag[fontno] = 1;
1430 }
1431
1432 static void deinit_fonts(void)
1433 {
1434     int i;
1435     for (i = 0; i < FONT_MAXNO; i++) {
1436         if (fonts[i])
1437             DeleteObject(fonts[i]);
1438         fonts[i] = 0;
1439         fontflag[i] = 0;
1440     }
1441 }
1442
1443 void request_resize(void *frontend, int w, int h)
1444 {
1445     int width, height;
1446
1447     /* If the window is maximized supress resizing attempts */
1448     if (IsZoomed(hwnd)) {
1449         if (cfg.resize_action == RESIZE_TERM)
1450             return;
1451     }
1452
1453     if (cfg.resize_action == RESIZE_DISABLED) return;
1454     if (h == term->rows && w == term->cols) return;
1455
1456     /* Sanity checks ... */
1457     {
1458         static int first_time = 1;
1459         static RECT ss;
1460
1461         switch (first_time) {
1462           case 1:
1463             /* Get the size of the screen */
1464             if (get_fullscreen_rect(&ss))
1465                 /* first_time = 0 */ ;
1466             else {
1467                 first_time = 2;
1468                 break;
1469             }
1470           case 0:
1471             /* Make sure the values are sane */
1472             width = (ss.right - ss.left - extra_width) / 4;
1473             height = (ss.bottom - ss.top - extra_height) / 6;
1474
1475             if (w > width || h > height)
1476                 return;
1477             if (w < 15)
1478                 w = 15;
1479             if (h < 1)
1480                 h = 1;
1481         }
1482     }
1483
1484     term_size(term, h, w, cfg.savelines);
1485
1486     if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {
1487         width = extra_width + font_width * w;
1488         height = extra_height + font_height * h;
1489
1490         SetWindowPos(hwnd, NULL, 0, 0, width, height,
1491             SWP_NOACTIVATE | SWP_NOCOPYBITS |
1492             SWP_NOMOVE | SWP_NOZORDER);
1493     } else
1494         reset_window(0);
1495
1496     InvalidateRect(hwnd, NULL, TRUE);
1497 }
1498
1499 static void reset_window(int reinit) {
1500     /*
1501      * This function decides how to resize or redraw when the 
1502      * user changes something. 
1503      *
1504      * This function doesn't like to change the terminal size but if the
1505      * font size is locked that may be it's only soluion.
1506      */
1507     int win_width, win_height;
1508     RECT cr, wr;
1509
1510 #ifdef RDB_DEBUG_PATCH
1511     debug((27, "reset_window()"));
1512 #endif
1513
1514     /* Current window sizes ... */
1515     GetWindowRect(hwnd, &wr);
1516     GetClientRect(hwnd, &cr);
1517
1518     win_width  = cr.right - cr.left;
1519     win_height = cr.bottom - cr.top;
1520
1521     if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;
1522
1523     /* Are we being forced to reload the fonts ? */
1524     if (reinit>1) {
1525 #ifdef RDB_DEBUG_PATCH
1526         debug((27, "reset_window() -- Forced deinit"));
1527 #endif
1528         deinit_fonts();
1529         init_fonts(0,0);
1530     }
1531
1532     /* Oh, looks like we're minimised */
1533     if (win_width == 0 || win_height == 0)
1534         return;
1535
1536     /* Is the window out of position ? */
1537     if ( !reinit && 
1538             (offset_width != (win_width-font_width*term->cols)/2 ||
1539              offset_height != (win_height-font_height*term->rows)/2) ){
1540         offset_width = (win_width-font_width*term->cols)/2;
1541         offset_height = (win_height-font_height*term->rows)/2;
1542         InvalidateRect(hwnd, NULL, TRUE);
1543 #ifdef RDB_DEBUG_PATCH
1544         debug((27, "reset_window() -> Reposition terminal"));
1545 #endif
1546     }
1547
1548     if (IsZoomed(hwnd)) {
1549         /* We're fullscreen, this means we must not change the size of
1550          * the window so it's the font size or the terminal itself.
1551          */
1552
1553         extra_width = wr.right - wr.left - cr.right + cr.left;
1554         extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1555
1556         if (cfg.resize_action != RESIZE_TERM) {
1557             if (  font_width != win_width/term->cols || 
1558                   font_height != win_height/term->rows) {
1559                 deinit_fonts();
1560                 init_fonts(win_width/term->cols, win_height/term->rows);
1561                 offset_width = (win_width-font_width*term->cols)/2;
1562                 offset_height = (win_height-font_height*term->rows)/2;
1563                 InvalidateRect(hwnd, NULL, TRUE);
1564 #ifdef RDB_DEBUG_PATCH
1565                 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1566                         font_width, font_height));
1567 #endif
1568             }
1569         } else {
1570             if (  font_width != win_width/term->cols || 
1571                   font_height != win_height/term->rows) {
1572                 /* Our only choice at this point is to change the 
1573                  * size of the terminal; Oh well.
1574                  */
1575                 term_size(term, win_height/font_height, win_width/font_width,
1576                           cfg.savelines);
1577                 offset_width = (win_width-font_width*term->cols)/2;
1578                 offset_height = (win_height-font_height*term->rows)/2;
1579                 InvalidateRect(hwnd, NULL, TRUE);
1580 #ifdef RDB_DEBUG_PATCH
1581                 debug((27, "reset_window() -> Zoomed term_size"));
1582 #endif
1583             }
1584         }
1585         return;
1586     }
1587
1588     /* Hmm, a force re-init means we should ignore the current window
1589      * so we resize to the default font size.
1590      */
1591     if (reinit>0) {
1592 #ifdef RDB_DEBUG_PATCH
1593         debug((27, "reset_window() -> Forced re-init"));
1594 #endif
1595
1596         offset_width = offset_height = cfg.window_border;
1597         extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1598         extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1599
1600         if (win_width != font_width*term->cols + offset_width*2 ||
1601             win_height != font_height*term->rows + offset_height*2) {
1602
1603             /* If this is too large windows will resize it to the maximum
1604              * allowed window size, we will then be back in here and resize
1605              * the font or terminal to fit.
1606              */
1607             SetWindowPos(hwnd, NULL, 0, 0, 
1608                          font_width*term->cols + extra_width, 
1609                          font_height*term->rows + extra_height,
1610                          SWP_NOMOVE | SWP_NOZORDER);
1611         }
1612
1613         InvalidateRect(hwnd, NULL, TRUE);
1614         return;
1615     }
1616
1617     /* Okay the user doesn't want us to change the font so we try the 
1618      * window. But that may be too big for the screen which forces us
1619      * to change the terminal.
1620      */
1621     if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||
1622         (cfg.resize_action == RESIZE_EITHER && reinit<0) ||
1623             reinit>0) {
1624         offset_width = offset_height = cfg.window_border;
1625         extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1626         extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1627
1628         if (win_width != font_width*term->cols + offset_width*2 ||
1629             win_height != font_height*term->rows + offset_height*2) {
1630
1631             static RECT ss;
1632             int width, height;
1633                 
1634                 get_fullscreen_rect(&ss);
1635
1636             width = (ss.right - ss.left - extra_width) / font_width;
1637             height = (ss.bottom - ss.top - extra_height) / font_height;
1638
1639             /* Grrr too big */
1640             if ( term->rows > height || term->cols > width ) {
1641                 if (cfg.resize_action == RESIZE_EITHER) {
1642                     /* Make the font the biggest we can */
1643                     if (term->cols > width)
1644                         font_width = (ss.right - ss.left - extra_width)
1645                             / term->cols;
1646                     if (term->rows > height)
1647                         font_height = (ss.bottom - ss.top - extra_height)
1648                             / term->rows;
1649
1650                     deinit_fonts();
1651                     init_fonts(font_width, font_height);
1652
1653                     width = (ss.right - ss.left - extra_width) / font_width;
1654                     height = (ss.bottom - ss.top - extra_height) / font_height;
1655                 } else {
1656                     if ( height > term->rows ) height = term->rows;
1657                     if ( width > term->cols )  width = term->cols;
1658                     term_size(term, height, width, cfg.savelines);
1659 #ifdef RDB_DEBUG_PATCH
1660                     debug((27, "reset_window() -> term resize to (%d,%d)",
1661                                height, width));
1662 #endif
1663                 }
1664             }
1665             
1666             SetWindowPos(hwnd, NULL, 0, 0, 
1667                          font_width*term->cols + extra_width, 
1668                          font_height*term->rows + extra_height,
1669                          SWP_NOMOVE | SWP_NOZORDER);
1670
1671             InvalidateRect(hwnd, NULL, TRUE);
1672 #ifdef RDB_DEBUG_PATCH
1673             debug((27, "reset_window() -> window resize to (%d,%d)",
1674                         font_width*term->cols + extra_width,
1675                         font_height*term->rows + extra_height));
1676 #endif
1677         }
1678         return;
1679     }
1680
1681     /* We're allowed to or must change the font but do we want to ?  */
1682
1683     if (font_width != (win_width-cfg.window_border*2)/term->cols || 
1684         font_height != (win_height-cfg.window_border*2)/term->rows) {
1685
1686         deinit_fonts();
1687         init_fonts((win_width-cfg.window_border*2)/term->cols, 
1688                    (win_height-cfg.window_border*2)/term->rows);
1689         offset_width = (win_width-font_width*term->cols)/2;
1690         offset_height = (win_height-font_height*term->rows)/2;
1691
1692         extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1693         extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1694
1695         InvalidateRect(hwnd, NULL, TRUE);
1696 #ifdef RDB_DEBUG_PATCH
1697         debug((25, "reset_window() -> font resize to (%d,%d)", 
1698                    font_width, font_height));
1699 #endif
1700     }
1701 }
1702
1703 static void set_input_locale(HKL kl)
1704 {
1705     char lbuf[20];
1706
1707     GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1708                   lbuf, sizeof(lbuf));
1709
1710     kbd_codepage = atoi(lbuf);
1711 }
1712
1713 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1714 {
1715     int thistime = GetMessageTime();
1716
1717     if (send_raw_mouse && !(cfg.mouse_override && shift)) {
1718         lastbtn = MBT_NOTHING;
1719         term_mouse(term, b, translate_button(b), MA_CLICK,
1720                    x, y, shift, ctrl, alt);
1721         return;
1722     }
1723
1724     if (lastbtn == b && thistime - lasttime < dbltime) {
1725         lastact = (lastact == MA_CLICK ? MA_2CLK :
1726                    lastact == MA_2CLK ? MA_3CLK :
1727                    lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1728     } else {
1729         lastbtn = b;
1730         lastact = MA_CLICK;
1731     }
1732     if (lastact != MA_NOTHING)
1733         term_mouse(term, b, translate_button(b), lastact,
1734                    x, y, shift, ctrl, alt);
1735     lasttime = thistime;
1736 }
1737
1738 /*
1739  * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1740  * into a cooked one (SELECT, EXTEND, PASTE).
1741  */
1742 static Mouse_Button translate_button(Mouse_Button button)
1743 {
1744     if (button == MBT_LEFT)
1745         return MBT_SELECT;
1746     if (button == MBT_MIDDLE)
1747         return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
1748     if (button == MBT_RIGHT)
1749         return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
1750     return 0;                          /* shouldn't happen */
1751 }
1752
1753 static void show_mouseptr(int show)
1754 {
1755     static int cursor_visible = 1;
1756     if (!cfg.hide_mouseptr)            /* override if this feature disabled */
1757         show = 1;
1758     if (cursor_visible && !show)
1759         ShowCursor(FALSE);
1760     else if (!cursor_visible && show)
1761         ShowCursor(TRUE);
1762     cursor_visible = show;
1763 }
1764
1765 static int is_alt_pressed(void)
1766 {
1767     BYTE keystate[256];
1768     int r = GetKeyboardState(keystate);
1769     if (!r)
1770         return FALSE;
1771     if (keystate[VK_MENU] & 0x80)
1772         return TRUE;
1773     if (keystate[VK_RMENU] & 0x80)
1774         return TRUE;
1775     return FALSE;
1776 }
1777
1778 static int is_shift_pressed(void)
1779 {
1780     BYTE keystate[256];
1781     int r = GetKeyboardState(keystate);
1782     if (!r)
1783         return FALSE;
1784     if (keystate[VK_SHIFT] & 0x80)
1785         return TRUE;
1786     return FALSE;
1787 }
1788
1789 static int resizing;
1790
1791 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1792                                 WPARAM wParam, LPARAM lParam)
1793 {
1794     HDC hdc;
1795     static int ignore_clip = FALSE;
1796     static int need_backend_resize = FALSE;
1797     static int fullscr_on_max = FALSE;
1798     static UINT last_mousemove = 0;
1799
1800     switch (message) {
1801       case WM_TIMER:
1802         if (pending_netevent)
1803             enact_pending_netevent();
1804         if (GetCapture() != hwnd || 
1805             (send_raw_mouse && !(cfg.mouse_override && is_shift_pressed())))
1806             term_out(term);
1807         noise_regular();
1808         HideCaret(hwnd);
1809         term_update(term);
1810         ShowCaret(hwnd);
1811         if (cfg.ping_interval > 0) {
1812             time_t now;
1813             time(&now);
1814             if (now - last_movement > cfg.ping_interval) {
1815                 if (back)
1816                     back->special(backhandle, TS_PING);
1817                 last_movement = now;
1818             }
1819         }
1820         net_pending_errors();
1821         return 0;
1822       case WM_CREATE:
1823         break;
1824       case WM_CLOSE:
1825         {
1826             char *str;
1827             show_mouseptr(1);
1828             str = dupprintf("%s Exit Confirmation", appname);
1829             if (!cfg.warn_on_close || session_closed ||
1830                 MessageBox(hwnd,
1831                            "Are you sure you want to close this session?",
1832                            str, MB_ICONWARNING | MB_OKCANCEL) == IDOK)
1833                 DestroyWindow(hwnd);
1834             sfree(str);
1835         }
1836         return 0;
1837       case WM_DESTROY:
1838         show_mouseptr(1);
1839         PostQuitMessage(0);
1840         return 0;
1841       case WM_COMMAND:
1842       case WM_SYSCOMMAND:
1843         switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
1844           case IDM_SHOWLOG:
1845             showeventlog(hwnd);
1846             break;
1847           case IDM_NEWSESS:
1848           case IDM_DUPSESS:
1849           case IDM_SAVEDSESS:
1850             {
1851                 char b[2048];
1852                 char c[30], *cl;
1853                 int freecl = FALSE;
1854                 STARTUPINFO si;
1855                 PROCESS_INFORMATION pi;
1856                 HANDLE filemap = NULL;
1857
1858                 if (wParam == IDM_DUPSESS) {
1859                     /*
1860                      * Allocate a file-mapping memory chunk for the
1861                      * config structure.
1862                      */
1863                     SECURITY_ATTRIBUTES sa;
1864                     Config *p;
1865
1866                     sa.nLength = sizeof(sa);
1867                     sa.lpSecurityDescriptor = NULL;
1868                     sa.bInheritHandle = TRUE;
1869                     filemap = CreateFileMapping((HANDLE) 0xFFFFFFFF,
1870                                                 &sa,
1871                                                 PAGE_READWRITE,
1872                                                 0, sizeof(Config), NULL);
1873                     if (filemap) {
1874                         p = (Config *) MapViewOfFile(filemap,
1875                                                      FILE_MAP_WRITE,
1876                                                      0, 0, sizeof(Config));
1877                         if (p) {
1878                             *p = cfg;  /* structure copy */
1879                             UnmapViewOfFile(p);
1880                         }
1881                     }
1882                     sprintf(c, "putty &%p", filemap);
1883                     cl = c;
1884                 } else if (wParam == IDM_SAVEDSESS) {
1885                     if ((lParam - IDM_SAVED_MIN) / 16 < sesslist.nsessions) {
1886                         char *session =
1887                             sesslist.sessions[(lParam - IDM_SAVED_MIN) / 16];
1888                         cl = snewn(16 + strlen(session), char);
1889                                        /* 8, but play safe */
1890                         if (!cl)
1891                             cl = NULL;    
1892                                        /* not a very important failure mode */
1893                         else {
1894                             sprintf(cl, "putty @%s", session);
1895                             freecl = TRUE;
1896                         }
1897                     } else
1898                         break;
1899                 } else
1900                     cl = NULL;
1901
1902                 GetModuleFileName(NULL, b, sizeof(b) - 1);
1903                 si.cb = sizeof(si);
1904                 si.lpReserved = NULL;
1905                 si.lpDesktop = NULL;
1906                 si.lpTitle = NULL;
1907                 si.dwFlags = 0;
1908                 si.cbReserved2 = 0;
1909                 si.lpReserved2 = NULL;
1910                 CreateProcess(b, cl, NULL, NULL, TRUE,
1911                               NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
1912
1913                 if (filemap)
1914                     CloseHandle(filemap);
1915                 if (freecl)
1916                     sfree(cl);
1917             }
1918             break;
1919           case IDM_RESTART:
1920             if (!back) {
1921                 logevent(NULL, "----- Session restarted -----");
1922                 start_backend();
1923             }
1924
1925             break;
1926           case IDM_RECONF:
1927             {
1928                 Config prev_cfg;
1929                 int init_lvl = 1;
1930
1931                 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
1932                 prev_cfg = cfg;
1933
1934                 if (!do_reconfig(hwnd))
1935                     break;
1936
1937                 {
1938                     /* Disable full-screen if resizing forbidden */
1939                     HMENU m = GetSystemMenu (hwnd, FALSE);
1940                     EnableMenuItem(m, IDM_FULLSCREEN, MF_BYCOMMAND | 
1941                                    (cfg.resize_action == RESIZE_DISABLED)
1942                                    ? MF_GRAYED : MF_ENABLED);
1943                     /* Gracefully unzoom if necessary */
1944                     if (IsZoomed(hwnd) &&
1945                         (cfg.resize_action == RESIZE_DISABLED)) {
1946                         ShowWindow(hwnd, SW_RESTORE);
1947                     }
1948                 }
1949
1950                 /* Pass new config data to the logging module */
1951                 log_reconfig(logctx, &cfg);
1952
1953                 sfree(logpal);
1954                 /*
1955                  * Flush the line discipline's edit buffer in the
1956                  * case where local editing has just been disabled.
1957                  */
1958                 if (ldisc)
1959                     ldisc_send(ldisc, NULL, 0, 0);
1960                 if (pal)
1961                     DeleteObject(pal);
1962                 logpal = NULL;
1963                 pal = NULL;
1964                 cfgtopalette();
1965                 init_palette();
1966
1967                 /* Pass new config data to the terminal */
1968                 term_reconfig(term, &cfg);
1969
1970                 /* Pass new config data to the back end */
1971                 if (back)
1972                     back->reconfig(backhandle, &cfg);
1973
1974                 /* Screen size changed ? */
1975                 if (cfg.height != prev_cfg.height ||
1976                     cfg.width != prev_cfg.width ||
1977                     cfg.savelines != prev_cfg.savelines ||
1978                     cfg.resize_action == RESIZE_FONT ||
1979                     (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
1980                     cfg.resize_action == RESIZE_DISABLED)
1981                     term_size(term, cfg.height, cfg.width, cfg.savelines);
1982
1983                 /* Enable or disable the scroll bar, etc */
1984                 {
1985                     LONG nflg, flag = GetWindowLong(hwnd, GWL_STYLE);
1986                     LONG nexflag, exflag =
1987                         GetWindowLong(hwnd, GWL_EXSTYLE);
1988
1989                     nexflag = exflag;
1990                     if (cfg.alwaysontop != prev_cfg.alwaysontop) {
1991                         if (cfg.alwaysontop) {
1992                             nexflag |= WS_EX_TOPMOST;
1993                             SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
1994                                          SWP_NOMOVE | SWP_NOSIZE);
1995                         } else {
1996                             nexflag &= ~(WS_EX_TOPMOST);
1997                             SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
1998                                          SWP_NOMOVE | SWP_NOSIZE);
1999                         }
2000                     }
2001                     if (cfg.sunken_edge)
2002                         nexflag |= WS_EX_CLIENTEDGE;
2003                     else
2004                         nexflag &= ~(WS_EX_CLIENTEDGE);
2005
2006                     nflg = flag;
2007                     if (is_full_screen() ?
2008                         cfg.scrollbar_in_fullscreen : cfg.scrollbar)
2009                         nflg |= WS_VSCROLL;
2010                     else
2011                         nflg &= ~WS_VSCROLL;
2012
2013                     if (cfg.resize_action == RESIZE_DISABLED ||
2014                         is_full_screen())
2015                         nflg &= ~WS_THICKFRAME;
2016                     else
2017                         nflg |= WS_THICKFRAME;
2018
2019                     if (cfg.resize_action == RESIZE_DISABLED)
2020                         nflg &= ~WS_MAXIMIZEBOX;
2021                     else
2022                         nflg |= WS_MAXIMIZEBOX;
2023
2024                     if (nflg != flag || nexflag != exflag) {
2025                         if (nflg != flag)
2026                             SetWindowLong(hwnd, GWL_STYLE, nflg);
2027                         if (nexflag != exflag)
2028                             SetWindowLong(hwnd, GWL_EXSTYLE, nexflag);
2029
2030                         SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
2031                                      SWP_NOACTIVATE | SWP_NOCOPYBITS |
2032                                      SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
2033                                      SWP_FRAMECHANGED);
2034
2035                         init_lvl = 2;
2036                     }
2037                 }
2038
2039                 /* Oops */
2040                 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
2041                     force_normal(hwnd);
2042                     init_lvl = 2;
2043                 }
2044
2045                 set_title(NULL, cfg.wintitle);
2046                 if (IsIconic(hwnd)) {
2047                     SetWindowText(hwnd,
2048                                   cfg.win_name_always ? window_name :
2049                                   icon_name);
2050                 }
2051
2052                 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
2053                     strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
2054                     cfg.font.isbold != prev_cfg.font.isbold ||
2055                     cfg.font.height != prev_cfg.font.height ||
2056                     cfg.font.charset != prev_cfg.font.charset ||
2057                     cfg.vtmode != prev_cfg.vtmode ||
2058                     cfg.bold_colour != prev_cfg.bold_colour ||
2059                     cfg.resize_action == RESIZE_DISABLED ||
2060                     cfg.resize_action == RESIZE_EITHER ||
2061                     (cfg.resize_action != prev_cfg.resize_action))
2062                     init_lvl = 2;
2063
2064                 InvalidateRect(hwnd, NULL, TRUE);
2065                 reset_window(init_lvl);
2066                 net_pending_errors();
2067             }
2068             break;
2069           case IDM_COPYALL:
2070             term_copyall(term);
2071             break;
2072           case IDM_PASTE:
2073             term_do_paste(term);
2074             break;
2075           case IDM_CLRSB:
2076             term_clrsb(term);
2077             break;
2078           case IDM_RESET:
2079             term_pwron(term);
2080             if (ldisc)
2081                 ldisc_send(ldisc, NULL, 0, 0);
2082             break;
2083           case IDM_ABOUT:
2084             showabout(hwnd);
2085             break;
2086           case IDM_HELP:
2087             WinHelp(hwnd, help_path,
2088                     help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
2089             break;
2090           case SC_MOUSEMENU:
2091             /*
2092              * We get this if the System menu has been activated
2093              * using the mouse.
2094              */
2095             show_mouseptr(1);
2096             break;
2097           case SC_KEYMENU:
2098             /*
2099              * We get this if the System menu has been activated
2100              * using the keyboard. This might happen from within
2101              * TranslateKey, in which case it really wants to be
2102              * followed by a `space' character to actually _bring
2103              * the menu up_ rather than just sitting there in
2104              * `ready to appear' state.
2105              */
2106             show_mouseptr(1);          /* make sure pointer is visible */
2107             if( lParam == 0 )
2108                 PostMessage(hwnd, WM_CHAR, ' ', 0);
2109             break;
2110           case IDM_FULLSCREEN:
2111             flip_full_screen();
2112             break;
2113           default:
2114             if (wParam >= IDM_SAVED_MIN && wParam <= IDM_SAVED_MAX) {
2115                 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2116             }
2117             if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2118                 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2119                 /*
2120                  * Ensure we haven't been sent a bogus SYSCOMMAND
2121                  * which would cause us to reference invalid memory
2122                  * and crash. Perhaps I'm just too paranoid here.
2123                  */
2124                 if (i >= n_specials)
2125                     break;
2126                 if (back)
2127                     back->special(backhandle, specials[i].code);
2128                 net_pending_errors();
2129             }
2130         }
2131         break;
2132
2133 #define X_POS(l) ((int)(short)LOWORD(l))
2134 #define Y_POS(l) ((int)(short)HIWORD(l))
2135
2136 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2137 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2138       case WM_LBUTTONDOWN:
2139       case WM_MBUTTONDOWN:
2140       case WM_RBUTTONDOWN:
2141       case WM_LBUTTONUP:
2142       case WM_MBUTTONUP:
2143       case WM_RBUTTONUP:
2144         if (message == WM_RBUTTONDOWN &&
2145             ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
2146             POINT cursorpos;
2147
2148             show_mouseptr(1);          /* make sure pointer is visible */
2149             GetCursorPos(&cursorpos);
2150             TrackPopupMenu(popup_menus[CTXMENU].menu,
2151                            TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2152                            cursorpos.x, cursorpos.y,
2153                            0, hwnd, NULL);
2154             break;
2155         }
2156         {
2157             int button, press;
2158
2159             switch (message) {
2160               case WM_LBUTTONDOWN:
2161                 button = MBT_LEFT;
2162                 press = 1;
2163                 break;
2164               case WM_MBUTTONDOWN:
2165                 button = MBT_MIDDLE;
2166                 press = 1;
2167                 break;
2168               case WM_RBUTTONDOWN:
2169                 button = MBT_RIGHT;
2170                 press = 1;
2171                 break;
2172               case WM_LBUTTONUP:
2173                 button = MBT_LEFT;
2174                 press = 0;
2175                 break;
2176               case WM_MBUTTONUP:
2177                 button = MBT_MIDDLE;
2178                 press = 0;
2179                 break;
2180               case WM_RBUTTONUP:
2181                 button = MBT_RIGHT;
2182                 press = 0;
2183                 break;
2184               default:
2185                 button = press = 0;    /* shouldn't happen */
2186             }
2187             show_mouseptr(1);
2188             /*
2189              * Special case: in full-screen mode, if the left
2190              * button is clicked in the very top left corner of the
2191              * window, we put up the System menu instead of doing
2192              * selection.
2193              */
2194             {
2195                 char mouse_on_hotspot = 0;
2196                 POINT pt;
2197
2198                 GetCursorPos(&pt);
2199 #ifndef NO_MULTIMON
2200                 {
2201                     HMONITOR mon;
2202                     MONITORINFO mi;
2203
2204                     mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2205
2206                     if (mon != NULL) {
2207                         mi.cbSize = sizeof(MONITORINFO);
2208                         GetMonitorInfo(mon, &mi);
2209
2210                         if (mi.rcMonitor.left == pt.x &&
2211                             mi.rcMonitor.top == pt.y) {
2212                             mouse_on_hotspot = 1;
2213                         }
2214                     }
2215                 }
2216 #else
2217                 if (pt.x == 0 && pt.y == 0) {
2218                     mouse_on_hotspot = 1;
2219                 }
2220 #endif
2221                 if (is_full_screen() && press &&
2222                     button == MBT_LEFT && mouse_on_hotspot) {
2223                     SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2224                                 MAKELPARAM(pt.x, pt.y));
2225                     return 0;
2226                 }
2227             }
2228
2229             if (press) {
2230                 click(button,
2231                       TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2232                       wParam & MK_SHIFT, wParam & MK_CONTROL,
2233                       is_alt_pressed());
2234                 SetCapture(hwnd);
2235             } else {
2236                 term_mouse(term, button, translate_button(button), MA_RELEASE,
2237                            TO_CHR_X(X_POS(lParam)),
2238                            TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2239                            wParam & MK_CONTROL, is_alt_pressed());
2240                 ReleaseCapture();
2241             }
2242         }
2243         return 0;
2244       case WM_MOUSEMOVE:
2245         {
2246             /*
2247              * Windows seems to like to occasionally send MOUSEMOVE
2248              * events even if the mouse hasn't moved. Don't unhide
2249              * the mouse pointer in this case.
2250              */
2251             static WPARAM wp = 0;
2252             static LPARAM lp = 0;
2253             if (wParam != wp || lParam != lp ||
2254                 last_mousemove != WM_MOUSEMOVE) {
2255                 show_mouseptr(1);
2256                 wp = wParam; lp = lParam;
2257                 last_mousemove = WM_MOUSEMOVE;
2258             }
2259         }
2260         /*
2261          * Add the mouse position and message time to the random
2262          * number noise.
2263          */
2264         noise_ultralight(lParam);
2265
2266         if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2267             GetCapture() == hwnd) {
2268             Mouse_Button b;
2269             if (wParam & MK_LBUTTON)
2270                 b = MBT_LEFT;
2271             else if (wParam & MK_MBUTTON)
2272                 b = MBT_MIDDLE;
2273             else
2274                 b = MBT_RIGHT;
2275             term_mouse(term, b, translate_button(b), MA_DRAG,
2276                        TO_CHR_X(X_POS(lParam)),
2277                        TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2278                        wParam & MK_CONTROL, is_alt_pressed());
2279         }
2280         return 0;
2281       case WM_NCMOUSEMOVE:
2282         {
2283             static WPARAM wp = 0;
2284             static LPARAM lp = 0;
2285             if (wParam != wp || lParam != lp ||
2286                 last_mousemove != WM_NCMOUSEMOVE) {
2287                 show_mouseptr(1);
2288                 wp = wParam; lp = lParam;
2289                 last_mousemove = WM_NCMOUSEMOVE;
2290             }
2291         }
2292         noise_ultralight(lParam);
2293         break;
2294       case WM_IGNORE_CLIP:
2295         ignore_clip = wParam;          /* don't panic on DESTROYCLIPBOARD */
2296         break;
2297       case WM_DESTROYCLIPBOARD:
2298         if (!ignore_clip)
2299             term_deselect(term);
2300         ignore_clip = FALSE;
2301         return 0;
2302       case WM_PAINT:
2303         {
2304             PAINTSTRUCT p;
2305             HideCaret(hwnd);
2306             hdc = BeginPaint(hwnd, &p);
2307             if (pal) {
2308                 SelectPalette(hdc, pal, TRUE);
2309                 RealizePalette(hdc);
2310             }
2311             term_paint(term, hdc, 
2312                        (p.rcPaint.left-offset_width)/font_width,
2313                        (p.rcPaint.top-offset_height)/font_height,
2314                        (p.rcPaint.right-offset_width-1)/font_width,
2315                        (p.rcPaint.bottom-offset_height-1)/font_height,
2316                        is_alt_pressed());
2317
2318             if (p.fErase ||
2319                 p.rcPaint.left  < offset_width  ||
2320                 p.rcPaint.top   < offset_height ||
2321                 p.rcPaint.right >= offset_width + font_width*term->cols ||
2322                 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2323             {
2324                 HBRUSH fillcolour, oldbrush;
2325                 HPEN   edge, oldpen;
2326                 fillcolour = CreateSolidBrush (
2327                                     colours[(ATTR_DEFBG>>ATTR_BGSHIFT)*2]);
2328                 oldbrush = SelectObject(hdc, fillcolour);
2329                 edge = CreatePen(PS_SOLID, 0, 
2330                                     colours[(ATTR_DEFBG>>ATTR_BGSHIFT)*2]);
2331                 oldpen = SelectObject(hdc, edge);
2332
2333                 /*
2334                  * Jordan Russell reports that this apparently
2335                  * ineffectual IntersectClipRect() call masks a
2336                  * Windows NT/2K bug causing strange display
2337                  * problems when the PuTTY window is taller than
2338                  * the primary monitor. It seems harmless enough...
2339                  */
2340                 IntersectClipRect(hdc,
2341                         p.rcPaint.left, p.rcPaint.top,
2342                         p.rcPaint.right, p.rcPaint.bottom);
2343
2344                 ExcludeClipRect(hdc, 
2345                         offset_width, offset_height,
2346                         offset_width+font_width*term->cols,
2347                         offset_height+font_height*term->rows);
2348
2349                 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top, 
2350                           p.rcPaint.right, p.rcPaint.bottom);
2351
2352                 // SelectClipRgn(hdc, NULL);
2353
2354                 SelectObject(hdc, oldbrush);
2355                 DeleteObject(fillcolour);
2356                 SelectObject(hdc, oldpen);
2357                 DeleteObject(edge);
2358             }
2359             SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2360             SelectObject(hdc, GetStockObject(WHITE_PEN));
2361             EndPaint(hwnd, &p);
2362             ShowCaret(hwnd);
2363         }
2364         return 0;
2365       case WM_NETEVENT:
2366         /* Notice we can get multiple netevents, FD_READ, FD_WRITE etc
2367          * but the only one that's likely to try to overload us is FD_READ.
2368          * This means buffering just one is fine.
2369          */
2370         if (pending_netevent)
2371             enact_pending_netevent();
2372
2373         pending_netevent = TRUE;
2374         pend_netevent_wParam = wParam;
2375         pend_netevent_lParam = lParam;
2376         if (WSAGETSELECTEVENT(lParam) != FD_READ)
2377             enact_pending_netevent();
2378
2379         time(&last_movement);
2380         return 0;
2381       case WM_SETFOCUS:
2382         term->has_focus = TRUE;
2383         CreateCaret(hwnd, caretbm, font_width, font_height);
2384         ShowCaret(hwnd);
2385         flash_window(0);               /* stop */
2386         compose_state = 0;
2387         term_out(term);
2388         term_update(term);
2389         break;
2390       case WM_KILLFOCUS:
2391         show_mouseptr(1);
2392         term->has_focus = FALSE;
2393         DestroyCaret();
2394         caret_x = caret_y = -1;        /* ensure caret is replaced next time */
2395         term_out(term);
2396         term_update(term);
2397         break;
2398       case WM_ENTERSIZEMOVE:
2399 #ifdef RDB_DEBUG_PATCH
2400         debug((27, "WM_ENTERSIZEMOVE"));
2401 #endif
2402         EnableSizeTip(1);
2403         resizing = TRUE;
2404         need_backend_resize = FALSE;
2405         break;
2406       case WM_EXITSIZEMOVE:
2407         EnableSizeTip(0);
2408         resizing = FALSE;
2409 #ifdef RDB_DEBUG_PATCH
2410         debug((27, "WM_EXITSIZEMOVE"));
2411 #endif
2412         if (need_backend_resize) {
2413             term_size(term, cfg.height, cfg.width, cfg.savelines);
2414             InvalidateRect(hwnd, NULL, TRUE);
2415         }
2416         break;
2417       case WM_SIZING:
2418         /*
2419          * This does two jobs:
2420          * 1) Keep the sizetip uptodate
2421          * 2) Make sure the window size is _stepped_ in units of the font size.
2422          */
2423         if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2424             int width, height, w, h, ew, eh;
2425             LPRECT r = (LPRECT) lParam;
2426
2427             if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
2428                     (cfg.height != term->rows || cfg.width != term->cols )) {
2429                 /* 
2430                  * Great! It seems that both the terminal size and the
2431                  * font size have been changed and the user is now dragging.
2432                  * 
2433                  * It will now be difficult to get back to the configured
2434                  * font size!
2435                  *
2436                  * This would be easier but it seems to be too confusing.
2437
2438                 term_size(term, cfg.height, cfg.width, cfg.savelines);
2439                 reset_window(2);
2440                  */
2441                 cfg.height=term->rows; cfg.width=term->cols;
2442
2443                 InvalidateRect(hwnd, NULL, TRUE);
2444                 need_backend_resize = TRUE;
2445             }
2446
2447             width = r->right - r->left - extra_width;
2448             height = r->bottom - r->top - extra_height;
2449             w = (width + font_width / 2) / font_width;
2450             if (w < 1)
2451                 w = 1;
2452             h = (height + font_height / 2) / font_height;
2453             if (h < 1)
2454                 h = 1;
2455             UpdateSizeTip(hwnd, w, h);
2456             ew = width - w * font_width;
2457             eh = height - h * font_height;
2458             if (ew != 0) {
2459                 if (wParam == WMSZ_LEFT ||
2460                     wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2461                     r->left += ew;
2462                 else
2463                     r->right -= ew;
2464             }
2465             if (eh != 0) {
2466                 if (wParam == WMSZ_TOP ||
2467                     wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2468                     r->top += eh;
2469                 else
2470                     r->bottom -= eh;
2471             }
2472             if (ew || eh)
2473                 return 1;
2474             else
2475                 return 0;
2476         } else {
2477             int width, height, w, h, rv = 0;
2478             int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2479             int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2480             LPRECT r = (LPRECT) lParam;
2481
2482             width = r->right - r->left - ex_width;
2483             height = r->bottom - r->top - ex_height;
2484
2485             w = (width + term->cols/2)/term->cols;
2486             h = (height + term->rows/2)/term->rows;
2487             if ( r->right != r->left + w*term->cols + ex_width)
2488                 rv = 1;
2489
2490             if (wParam == WMSZ_LEFT ||
2491                 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2492                 r->left = r->right - w*term->cols - ex_width;
2493             else
2494                 r->right = r->left + w*term->cols + ex_width;
2495
2496             if (r->bottom != r->top + h*term->rows + ex_height)
2497                 rv = 1;
2498
2499             if (wParam == WMSZ_TOP ||
2500                 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2501                 r->top = r->bottom - h*term->rows - ex_height;
2502             else
2503                 r->bottom = r->top + h*term->rows + ex_height;
2504
2505             return rv;
2506         }
2507         /* break;  (never reached) */
2508       case WM_FULLSCR_ON_MAX:
2509         fullscr_on_max = TRUE;
2510         break;
2511       case WM_MOVE:
2512         sys_cursor_update();
2513         break;
2514       case WM_SIZE:
2515 #ifdef RDB_DEBUG_PATCH
2516         debug((27, "WM_SIZE %s (%d,%d)",
2517                 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2518                 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2519                 (wParam == SIZE_RESTORED && resizing) ? "to":
2520                 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2521                 "...",
2522             LOWORD(lParam), HIWORD(lParam)));
2523 #endif
2524         if (wParam == SIZE_MINIMIZED)
2525             SetWindowText(hwnd,
2526                           cfg.win_name_always ? window_name : icon_name);
2527         if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2528             SetWindowText(hwnd, window_name);
2529         if (wParam == SIZE_RESTORED)
2530             clear_full_screen();
2531         if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2532             fullscr_on_max = FALSE;
2533             make_full_screen();
2534         }
2535
2536         if (cfg.resize_action == RESIZE_DISABLED) {
2537             /* A resize, well it better be a minimize. */
2538             reset_window(-1);
2539         } else {
2540
2541             int width, height, w, h;
2542
2543             width = LOWORD(lParam);
2544             height = HIWORD(lParam);
2545
2546             if (!resizing) {
2547                 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2548                     was_zoomed = 1;
2549                     prev_rows = term->rows;
2550                     prev_cols = term->cols;
2551                     if (cfg.resize_action == RESIZE_TERM) {
2552                         w = width / font_width;
2553                         if (w < 1) w = 1;
2554                         h = height / font_height;
2555                         if (h < 1) h = 1;
2556
2557                         term_size(term, h, w, cfg.savelines);
2558                     }
2559                     reset_window(0);
2560                 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2561                     was_zoomed = 0;
2562                     if (cfg.resize_action == RESIZE_TERM)
2563                         term_size(term, prev_rows, prev_cols, cfg.savelines);
2564                     if (cfg.resize_action != RESIZE_FONT)
2565                         reset_window(2);
2566                     else
2567                         reset_window(0);
2568                 }
2569                 /* This is an unexpected resize, these will normally happen
2570                  * if the window is too large. Probably either the user
2571                  * selected a huge font or the screen size has changed.
2572                  *
2573                  * This is also called with minimize.
2574                  */
2575                 else reset_window(-1);
2576             }
2577
2578             /*
2579              * Don't call back->size in mid-resize. (To prevent
2580              * massive numbers of resize events getting sent
2581              * down the connection during an NT opaque drag.)
2582              */
2583             if (resizing) {
2584                 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2585                     need_backend_resize = TRUE;
2586                     w = (width-cfg.window_border*2) / font_width;
2587                     if (w < 1) w = 1;
2588                     h = (height-cfg.window_border*2) / font_height;
2589                     if (h < 1) h = 1;
2590
2591                     cfg.height = h;
2592                     cfg.width = w;
2593                 } else 
2594                     reset_window(0);
2595             }
2596         }
2597         sys_cursor_update();
2598         return 0;
2599       case WM_VSCROLL:
2600         switch (LOWORD(wParam)) {
2601           case SB_BOTTOM:
2602             term_scroll(term, -1, 0);
2603             break;
2604           case SB_TOP:
2605             term_scroll(term, +1, 0);
2606             break;
2607           case SB_LINEDOWN:
2608             term_scroll(term, 0, +1);
2609             break;
2610           case SB_LINEUP:
2611             term_scroll(term, 0, -1);
2612             break;
2613           case SB_PAGEDOWN:
2614             term_scroll(term, 0, +term->rows / 2);
2615             break;
2616           case SB_PAGEUP:
2617             term_scroll(term, 0, -term->rows / 2);
2618             break;
2619           case SB_THUMBPOSITION:
2620           case SB_THUMBTRACK:
2621             term_scroll(term, 1, HIWORD(wParam));
2622             break;
2623         }
2624         break;
2625       case WM_PALETTECHANGED:
2626         if ((HWND) wParam != hwnd && pal != NULL) {
2627             HDC hdc = get_ctx(NULL);
2628             if (hdc) {
2629                 if (RealizePalette(hdc) > 0)
2630                     UpdateColors(hdc);
2631                 free_ctx(hdc);
2632             }
2633         }
2634         break;
2635       case WM_QUERYNEWPALETTE:
2636         if (pal != NULL) {
2637             HDC hdc = get_ctx(NULL);
2638             if (hdc) {
2639                 if (RealizePalette(hdc) > 0)
2640                     UpdateColors(hdc);
2641                 free_ctx(hdc);
2642                 return TRUE;
2643             }
2644         }
2645         return FALSE;
2646       case WM_KEYDOWN:
2647       case WM_SYSKEYDOWN:
2648       case WM_KEYUP:
2649       case WM_SYSKEYUP:
2650         /*
2651          * Add the scan code and keypress timing to the random
2652          * number noise.
2653          */
2654         noise_ultralight(lParam);
2655
2656         /*
2657          * We don't do TranslateMessage since it disassociates the
2658          * resulting CHAR message from the KEYDOWN that sparked it,
2659          * which we occasionally don't want. Instead, we process
2660          * KEYDOWN, and call the Win32 translator functions so that
2661          * we get the translations under _our_ control.
2662          */
2663         {
2664             unsigned char buf[20];
2665             int len;
2666
2667             if (wParam == VK_PROCESSKEY) {
2668                 MSG m;
2669                 m.hwnd = hwnd;
2670                 m.message = WM_KEYDOWN;
2671                 m.wParam = wParam;
2672                 m.lParam = lParam & 0xdfff;
2673                 TranslateMessage(&m);
2674             } else {
2675                 len = TranslateKey(message, wParam, lParam, buf);
2676                 if (len == -1)
2677                     return DefWindowProc(hwnd, message, wParam, lParam);
2678
2679                 if (len != 0) {
2680                     /*
2681                      * Interrupt an ongoing paste. I'm not sure
2682                      * this is sensible, but for the moment it's
2683                      * preferable to having to faff about buffering
2684                      * things.
2685                      */
2686                     term_nopaste(term);
2687
2688                     /*
2689                      * We need not bother about stdin backlogs
2690                      * here, because in GUI PuTTY we can't do
2691                      * anything about it anyway; there's no means
2692                      * of asking Windows to hold off on KEYDOWN
2693                      * messages. We _have_ to buffer everything
2694                      * we're sent.
2695                      */
2696                     term_seen_key_event(term);
2697                     if (ldisc)
2698                         ldisc_send(ldisc, buf, len, 1);
2699                     show_mouseptr(0);
2700                 }
2701             }
2702         }
2703         net_pending_errors();
2704         return 0;
2705       case WM_INPUTLANGCHANGE:
2706         /* wParam == Font number */
2707         /* lParam == Locale */
2708         set_input_locale((HKL)lParam);
2709         sys_cursor_update();
2710         break;
2711       case WM_IME_NOTIFY:
2712         if(wParam == IMN_SETOPENSTATUS) {
2713             HIMC hImc = ImmGetContext(hwnd);
2714             ImmSetCompositionFont(hImc, &lfont);
2715             ImmReleaseContext(hwnd, hImc);
2716             return 0;
2717         }
2718         break;
2719       case WM_IME_COMPOSITION:
2720         {
2721             HIMC hIMC;
2722             int n;
2723             char *buff;
2724
2725             if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS || 
2726                 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2727
2728             if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2729                 break; /* fall back to DefWindowProc */
2730
2731             hIMC = ImmGetContext(hwnd);
2732             n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2733
2734             if (n > 0) {
2735                 int i;
2736                 buff = snewn(n, char);
2737                 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
2738                 /*
2739                  * Jaeyoun Chung reports that Korean character
2740                  * input doesn't work correctly if we do a single
2741                  * luni_send() covering the whole of buff. So
2742                  * instead we luni_send the characters one by one.
2743                  */
2744                 term_seen_key_event(term);
2745                 for (i = 0; i < n; i += 2) {
2746                     if (ldisc)
2747                         luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2748                 }
2749                 free(buff);
2750             }
2751             ImmReleaseContext(hwnd, hIMC);
2752             return 1;
2753         }
2754
2755       case WM_IME_CHAR:
2756         if (wParam & 0xFF00) {
2757             unsigned char buf[2];
2758
2759             buf[1] = wParam;
2760             buf[0] = wParam >> 8;
2761             term_seen_key_event(term);
2762             if (ldisc)
2763                 lpage_send(ldisc, kbd_codepage, buf, 2, 1);
2764         } else {
2765             char c = (unsigned char) wParam;
2766             term_seen_key_event(term);
2767             if (ldisc)
2768                 lpage_send(ldisc, kbd_codepage, &c, 1, 1);
2769         }
2770         return (0);
2771       case WM_CHAR:
2772       case WM_SYSCHAR:
2773         /*
2774          * Nevertheless, we are prepared to deal with WM_CHAR
2775          * messages, should they crop up. So if someone wants to
2776          * post the things to us as part of a macro manoeuvre,
2777          * we're ready to cope.
2778          */
2779         {
2780             char c = (unsigned char)wParam;
2781             term_seen_key_event(term);
2782             if (ldisc)
2783                 lpage_send(ldisc, CP_ACP, &c, 1, 1);
2784         }
2785         return 0;
2786       case WM_SETCURSOR:
2787         if (send_raw_mouse && LOWORD(lParam) == HTCLIENT) {
2788             SetCursor(LoadCursor(NULL, IDC_ARROW));
2789             return TRUE;
2790         }
2791         break;
2792       case WM_SYSCOLORCHANGE:
2793         if (cfg.system_colour) {
2794             /* Refresh palette from system colours. */
2795             /* XXX actually this zaps the entire palette. */
2796             systopalette();
2797             init_palette();
2798             /* Force a repaint of the terminal window. */
2799             term_invalidate(term);
2800         }
2801         break;
2802       case WM_AGENT_CALLBACK:
2803         {
2804             struct agent_callback *c = (struct agent_callback *)lParam;
2805             c->callback(c->callback_ctx, c->data, c->len);
2806             sfree(c);
2807         }
2808         return 0;
2809       default:
2810         if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
2811             int shift_pressed=0, control_pressed=0;
2812
2813             if (message == WM_MOUSEWHEEL) {
2814                 wheel_accumulator += (short)HIWORD(wParam);
2815                 shift_pressed=LOWORD(wParam) & MK_SHIFT;
2816                 control_pressed=LOWORD(wParam) & MK_CONTROL;
2817             } else {
2818                 BYTE keys[256];
2819                 wheel_accumulator += (int)wParam;
2820                 if (GetKeyboardState(keys)!=0) {
2821                     shift_pressed=keys[VK_SHIFT]&0x80;
2822                     control_pressed=keys[VK_CONTROL]&0x80;
2823                 }
2824             }
2825
2826             /* process events when the threshold is reached */
2827             while (abs(wheel_accumulator) >= WHEEL_DELTA) {
2828                 int b;
2829
2830                 /* reduce amount for next time */
2831                 if (wheel_accumulator > 0) {
2832                     b = MBT_WHEEL_UP;
2833                     wheel_accumulator -= WHEEL_DELTA;
2834                 } else if (wheel_accumulator < 0) {
2835                     b = MBT_WHEEL_DOWN;
2836                     wheel_accumulator += WHEEL_DELTA;
2837                 } else
2838                     break;
2839
2840                 if (send_raw_mouse &&
2841                     !(cfg.mouse_override && shift_pressed)) {
2842                     /* send a mouse-down followed by a mouse up */
2843                     term_mouse(term, b, translate_button(b),
2844                                MA_CLICK,
2845                                TO_CHR_X(X_POS(lParam)),
2846                                TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2847                                control_pressed, is_alt_pressed());
2848                     term_mouse(term, b, translate_button(b),
2849                                MA_RELEASE, TO_CHR_X(X_POS(lParam)),
2850                                TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2851                                control_pressed, is_alt_pressed());
2852                 } else {
2853                     /* trigger a scroll */
2854                     term_scroll(term, 0,
2855                                 b == MBT_WHEEL_UP ?
2856                                 -term->rows / 2 : term->rows / 2);
2857                 }
2858             }
2859             return 0;
2860         }
2861     }
2862
2863     return DefWindowProc(hwnd, message, wParam, lParam);
2864 }
2865
2866 /*
2867  * Move the system caret. (We maintain one, even though it's
2868  * invisible, for the benefit of blind people: apparently some
2869  * helper software tracks the system caret, so we should arrange to
2870  * have one.)
2871  */
2872 void sys_cursor(void *frontend, int x, int y)
2873 {
2874     int cx, cy;
2875
2876     if (!term->has_focus) return;
2877
2878     /*
2879      * Avoid gratuitously re-updating the cursor position and IMM
2880      * window if there's no actual change required.
2881      */
2882     cx = x * font_width + offset_width;
2883     cy = y * font_height + offset_height;
2884     if (cx == caret_x && cy == caret_y)
2885         return;
2886     caret_x = cx;
2887     caret_y = cy;
2888
2889     sys_cursor_update();
2890 }
2891
2892 static void sys_cursor_update(void)
2893 {
2894     COMPOSITIONFORM cf;
2895     HIMC hIMC;
2896
2897     if (!term->has_focus) return;
2898
2899     if (caret_x < 0 || caret_y < 0)
2900         return;
2901
2902     SetCaretPos(caret_x, caret_y);
2903
2904     /* IMM calls on Win98 and beyond only */
2905     if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
2906     
2907     if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
2908             osVersion.dwMinorVersion == 0) return; /* 95 */
2909
2910     /* we should have the IMM functions */
2911     hIMC = ImmGetContext(hwnd);
2912     cf.dwStyle = CFS_POINT;
2913     cf.ptCurrentPos.x = caret_x;
2914     cf.ptCurrentPos.y = caret_y;
2915     ImmSetCompositionWindow(hIMC, &cf);
2916
2917     ImmReleaseContext(hwnd, hIMC);
2918 }
2919
2920 /*
2921  * Draw a line of text in the window, at given character
2922  * coordinates, in given attributes.
2923  *
2924  * We are allowed to fiddle with the contents of `text'.
2925  */
2926 void do_text(Context ctx, int x, int y, char *text, int len,
2927              unsigned long attr, int lattr)
2928 {
2929     COLORREF fg, bg, t;
2930     int nfg, nbg, nfont;
2931     HDC hdc = ctx;
2932     RECT line_box;
2933     int force_manual_underline = 0;
2934     int fnt_width = font_width * (1 + (lattr != LATTR_NORM));
2935     int char_width = fnt_width;
2936     int text_adjust = 0;
2937     static int *IpDx = 0, IpDxLEN = 0;
2938
2939     if (attr & ATTR_WIDE)
2940         char_width *= 2;
2941
2942     if (len > IpDxLEN || IpDx[0] != char_width) {
2943         int i;
2944         if (len > IpDxLEN) {
2945             sfree(IpDx);
2946             IpDx = snewn(len + 16, int);
2947             IpDxLEN = (len + 16);
2948         }
2949         for (i = 0; i < IpDxLEN; i++)
2950             IpDx[i] = char_width;
2951     }
2952
2953     /* Only want the left half of double width lines */
2954     if (lattr != LATTR_NORM && x*2 >= term->cols)
2955         return;
2956
2957     x *= fnt_width;
2958     y *= font_height;
2959     x += offset_width;
2960     y += offset_height;
2961
2962     if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
2963         attr &= ATTR_CUR_AND | (bold_mode != BOLD_COLOURS ? ATTR_BOLD : 0);
2964         attr ^= ATTR_CUR_XOR;
2965     }
2966
2967     nfont = 0;
2968     if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
2969         /* Assume a poorman font is borken in other ways too. */
2970         lattr = LATTR_WIDE;
2971     } else
2972         switch (lattr) {
2973           case LATTR_NORM:
2974             break;
2975           case LATTR_WIDE:
2976             nfont |= FONT_WIDE;
2977             break;
2978           default:
2979             nfont |= FONT_WIDE + FONT_HIGH;
2980             break;
2981         }
2982     if (attr & ATTR_NARROW)
2983         nfont |= FONT_NARROW;
2984
2985     /* Special hack for the VT100 linedraw glyphs. */
2986     if ((attr & CSET_MASK) == 0x2300) {
2987         if (text[0] >= (char) 0xBA && text[0] <= (char) 0xBD) {
2988             switch ((unsigned char) (text[0])) {
2989               case 0xBA:
2990                 text_adjust = -2 * font_height / 5;
2991                 break;
2992               case 0xBB:
2993                 text_adjust = -1 * font_height / 5;
2994                 break;
2995               case 0xBC:
2996                 text_adjust = font_height / 5;
2997                 break;
2998               case 0xBD:
2999                 text_adjust = 2 * font_height / 5;
3000                 break;
3001             }
3002             if (lattr == LATTR_TOP || lattr == LATTR_BOT)
3003                 text_adjust *= 2;
3004             attr &= ~CSET_MASK;
3005             text[0] = (char) (ucsdata.unitab_xterm['q'] & CHAR_MASK);
3006             attr |= (ucsdata.unitab_xterm['q'] & CSET_MASK);
3007             if (attr & ATTR_UNDER) {
3008                 attr &= ~ATTR_UNDER;
3009                 force_manual_underline = 1;
3010             }
3011         }
3012     }
3013
3014     /* Anything left as an original character set is unprintable. */
3015     if (DIRECT_CHAR(attr)) {
3016         attr &= ~CSET_MASK;
3017         attr |= 0xFF00;
3018         memset(text, 0xFD, len);
3019     }
3020
3021     /* OEM CP */
3022     if ((attr & CSET_MASK) == ATTR_OEMCP)
3023         nfont |= FONT_OEM;
3024
3025     nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
3026     nfg = 2 * (nfg & 0xF) + (nfg & 0x10 ? 1 : 0);
3027     nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
3028     nbg = 2 * (nbg & 0xF) + (nbg & 0x10 ? 1 : 0);
3029     if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
3030         nfont |= FONT_BOLD;
3031     if (und_mode == UND_FONT && (attr & ATTR_UNDER))
3032         nfont |= FONT_UNDERLINE;
3033     another_font(nfont);
3034     if (!fonts[nfont]) {
3035         if (nfont & FONT_UNDERLINE)
3036             force_manual_underline = 1;
3037         /* Don't do the same for manual bold, it could be bad news. */
3038
3039         nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
3040     }
3041     another_font(nfont);
3042     if (!fonts[nfont])
3043         nfont = FONT_NORMAL;
3044     if (attr & ATTR_REVERSE) {
3045         t = nfg;
3046         nfg = nbg;
3047         nbg = t;
3048     }
3049     if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD))
3050         nfg |= 1;
3051     if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK))
3052         nbg |= 1;
3053     fg = colours[nfg];
3054     bg = colours[nbg];
3055     SelectObject(hdc, fonts[nfont]);
3056     SetTextColor(hdc, fg);
3057     SetBkColor(hdc, bg);
3058     SetBkMode(hdc, OPAQUE);
3059     line_box.left = x;
3060     line_box.top = y;
3061     line_box.right = x + char_width * len;
3062     line_box.bottom = y + font_height;
3063
3064     /* Only want the left half of double width lines */
3065     if (line_box.right > font_width*term->cols+offset_width)
3066         line_box.right = font_width*term->cols+offset_width;
3067
3068     /* We're using a private area for direct to font. (512 chars.) */
3069     if (ucsdata.dbcs_screenfont && (attr & CSET_MASK) == ATTR_ACP) {
3070         /* Ho Hum, dbcs fonts are a PITA! */
3071         /* To display on W9x I have to convert to UCS */
3072         static wchar_t *uni_buf = 0;
3073         static int uni_len = 0;
3074         int nlen, mptr;
3075         if (len > uni_len) {
3076             sfree(uni_buf);
3077             uni_len = len;
3078             uni_buf = snewn(uni_len, wchar_t);
3079         }
3080
3081         for(nlen = mptr = 0; mptr<len; mptr++) {
3082             uni_buf[nlen] = 0xFFFD;
3083             if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
3084                 IpDx[nlen] += char_width;
3085                 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3086                                    text+mptr, 2, uni_buf+nlen, 1);
3087                 mptr++;
3088             }
3089             else
3090             {
3091                 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
3092                                    text+mptr, 1, uni_buf+nlen, 1);
3093             }
3094             nlen++;
3095         }
3096         if (nlen <= 0)
3097             return;                    /* Eeek! */
3098
3099         ExtTextOutW(hdc, x,
3100                     y - font_height * (lattr == LATTR_BOT) + text_adjust,
3101                     ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
3102         if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3103             SetBkMode(hdc, TRANSPARENT);
3104             ExtTextOutW(hdc, x - 1,
3105                         y - font_height * (lattr ==
3106                                            LATTR_BOT) + text_adjust,
3107                         ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
3108         }
3109
3110         IpDx[0] = -1;
3111     } else if (DIRECT_FONT(attr)) {
3112         ExtTextOut(hdc, x,
3113                    y - font_height * (lattr == LATTR_BOT) + text_adjust,
3114                    ETO_CLIPPED | ETO_OPAQUE, &line_box, text, len, IpDx);
3115         if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3116             SetBkMode(hdc, TRANSPARENT);
3117
3118             /* GRR: This draws the character outside it's box and can leave
3119              * 'droppings' even with the clip box! I suppose I could loop it
3120              * one character at a time ... yuk. 
3121              * 
3122              * Or ... I could do a test print with "W", and use +1 or -1 for this
3123              * shift depending on if the leftmost column is blank...
3124              */
3125             ExtTextOut(hdc, x - 1,
3126                        y - font_height * (lattr ==
3127                                           LATTR_BOT) + text_adjust,
3128                        ETO_CLIPPED, &line_box, text, len, IpDx);
3129         }
3130     } else {
3131         /* And 'normal' unicode characters */
3132         static WCHAR *wbuf = NULL;
3133         static int wlen = 0;
3134         int i;
3135         if (wlen < len) {
3136             sfree(wbuf);
3137             wlen = len;
3138             wbuf = snewn(wlen, WCHAR);
3139         }
3140         for (i = 0; i < len; i++)
3141             wbuf[i] = (WCHAR) ((attr & CSET_MASK) + (text[i] & CHAR_MASK));
3142
3143         /* print Glyphs as they are, without Windows' Shaping*/
3144         exact_textout(hdc, x, y - font_height * (lattr == LATTR_BOT) + text_adjust,
3145                       &line_box, wbuf, len, IpDx);
3146 /*      ExtTextOutW(hdc, x,
3147                     y - font_height * (lattr == LATTR_BOT) + text_adjust,
3148                     ETO_CLIPPED | ETO_OPAQUE, &line_box, wbuf, len, IpDx);
3149  */
3150
3151         /* And the shadow bold hack. */
3152         if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3153             SetBkMode(hdc, TRANSPARENT);
3154             ExtTextOutW(hdc, x - 1,
3155                         y - font_height * (lattr ==
3156                                            LATTR_BOT) + text_adjust,
3157                         ETO_CLIPPED, &line_box, wbuf, len, IpDx);
3158         }
3159     }
3160     if (lattr != LATTR_TOP && (force_manual_underline ||
3161                                (und_mode == UND_LINE
3162                                 && (attr & ATTR_UNDER)))) {
3163         HPEN oldpen;
3164         int dec = descent;
3165         if (lattr == LATTR_BOT)
3166             dec = dec * 2 - font_height;
3167
3168         oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3169         MoveToEx(hdc, x, y + dec, NULL);
3170         LineTo(hdc, x + len * char_width, y + dec);
3171         oldpen = SelectObject(hdc, oldpen);
3172         DeleteObject(oldpen);
3173     }
3174 }
3175
3176 void do_cursor(Context ctx, int x, int y, char *text, int len,
3177                unsigned long attr, int lattr)
3178 {
3179
3180     int fnt_width;
3181     int char_width;
3182     HDC hdc = ctx;
3183     int ctype = cfg.cursor_type;
3184
3185     if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3186         if (((attr & CSET_MASK) | (unsigned char) *text) != UCSWIDE) {
3187             do_text(ctx, x, y, text, len, attr, lattr);
3188             return;
3189         }
3190         ctype = 2;
3191         attr |= TATTR_RIGHTCURS;
3192     }
3193
3194     fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3195     if (attr & ATTR_WIDE)
3196         char_width *= 2;
3197     x *= fnt_width;
3198     y *= font_height;
3199     x += offset_width;
3200     y += offset_height;
3201
3202     if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3203         POINT pts[5];
3204         HPEN oldpen;
3205         pts[0].x = pts[1].x = pts[4].x = x;
3206         pts[2].x = pts[3].x = x + char_width - 1;
3207         pts[0].y = pts[3].y = pts[4].y = y;
3208         pts[1].y = pts[2].y = y + font_height - 1;
3209         oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
3210         Polyline(hdc, pts, 5);
3211         oldpen = SelectObject(hdc, oldpen);
3212         DeleteObject(oldpen);
3213     } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3214         int startx, starty, dx, dy, length, i;
3215         if (ctype == 1) {
3216             startx = x;
3217             starty = y + descent;
3218             dx = 1;
3219             dy = 0;
3220             length = char_width;
3221         } else {
3222             int xadjust = 0;
3223             if (attr & TATTR_RIGHTCURS)
3224                 xadjust = char_width - 1;
3225             startx = x + xadjust;
3226             starty = y;
3227             dx = 0;
3228             dy = 1;
3229             length = font_height;
3230         }
3231         if (attr & TATTR_ACTCURS) {
3232             HPEN oldpen;
3233             oldpen =
3234                 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
3235             MoveToEx(hdc, startx, starty, NULL);
3236             LineTo(hdc, startx + dx * length, starty + dy * length);
3237             oldpen = SelectObject(hdc, oldpen);
3238             DeleteObject(oldpen);
3239         } else {
3240             for (i = 0; i < length; i++) {
3241                 if (i % 2 == 0) {
3242                     SetPixel(hdc, startx, starty, colours[23]);
3243                 }
3244                 startx += dx;
3245                 starty += dy;
3246             }
3247         }
3248     }
3249 }
3250
3251 /* This function gets the actual width of a character in the normal font.
3252  */
3253 int char_width(Context ctx, int uc) {
3254     HDC hdc = ctx;
3255     int ibuf = 0;
3256
3257     /* If the font max is the same as the font ave width then this
3258      * function is a no-op.
3259      */
3260     if (!font_dualwidth) return 1;
3261
3262     switch (uc & CSET_MASK) {
3263       case ATTR_ASCII:
3264         uc = ucsdata.unitab_line[uc & 0xFF];
3265         break;
3266       case ATTR_LINEDRW:
3267         uc = ucsdata.unitab_xterm[uc & 0xFF];
3268         break;
3269       case ATTR_SCOACS:
3270         uc = ucsdata.unitab_scoacs[uc & 0xFF];
3271         break;
3272     }
3273     if (DIRECT_FONT(uc)) {
3274         if (ucsdata.dbcs_screenfont) return 1;
3275
3276         /* Speedup, I know of no font where ascii is the wrong width */
3277         if ((uc&CHAR_MASK) >= ' ' && (uc&CHAR_MASK)<= '~') 
3278             return 1;
3279
3280         if ( (uc & CSET_MASK) == ATTR_ACP ) {
3281             SelectObject(hdc, fonts[FONT_NORMAL]);
3282         } else if ( (uc & CSET_MASK) == ATTR_OEMCP ) {
3283             another_font(FONT_OEM);
3284             if (!fonts[FONT_OEM]) return 0;
3285
3286             SelectObject(hdc, fonts[FONT_OEM]);
3287         } else
3288             return 0;
3289
3290         if ( GetCharWidth32(hdc, uc&CHAR_MASK, uc&CHAR_MASK, &ibuf) != 1 && 
3291              GetCharWidth(hdc, uc&CHAR_MASK, uc&CHAR_MASK, &ibuf) != 1)
3292             return 0;
3293     } else {
3294         /* Speedup, I know of no font where ascii is the wrong width */
3295         if (uc >= ' ' && uc <= '~') return 1;
3296
3297         SelectObject(hdc, fonts[FONT_NORMAL]);
3298         if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3299             /* Okay that one worked */ ;
3300         else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3301             /* This should work on 9x too, but it's "less accurate" */ ;
3302         else
3303             return 0;
3304     }
3305
3306     ibuf += font_width / 2 -1;
3307     ibuf /= font_width;
3308
3309     return ibuf;
3310 }
3311
3312 /*
3313  * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3314  * codes. Returns number of bytes used or zero to drop the message
3315  * or -1 to forward the message to windows.
3316  */
3317 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3318                         unsigned char *output)
3319 {
3320     BYTE keystate[256];
3321     int scan, left_alt = 0, key_down, shift_state;
3322     int r, i, code;
3323     unsigned char *p = output;
3324     static int alt_sum = 0;
3325
3326     HKL kbd_layout = GetKeyboardLayout(0);
3327
3328     /* keys is for ToAsciiEx. There's some ick here, see below. */
3329     static WORD keys[3];
3330     static int compose_char = 0;
3331     static WPARAM compose_key = 0;
3332
3333     r = GetKeyboardState(keystate);
3334     if (!r)
3335         memset(keystate, 0, sizeof(keystate));
3336     else {
3337 #if 0
3338 #define SHOW_TOASCII_RESULT
3339         {                              /* Tell us all about key events */
3340             static BYTE oldstate[256];
3341             static int first = 1;
3342             static int scan;
3343             int ch;
3344             if (first)
3345                 memcpy(oldstate, keystate, sizeof(oldstate));
3346             first = 0;
3347
3348             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3349                 debug(("+"));
3350             } else if ((HIWORD(lParam) & KF_UP)
3351                        && scan == (HIWORD(lParam) & 0xFF)) {
3352                 debug((". U"));
3353             } else {
3354                 debug((".\n"));
3355                 if (wParam >= VK_F1 && wParam <= VK_F20)
3356                     debug(("K_F%d", wParam + 1 - VK_F1));
3357                 else
3358                     switch (wParam) {
3359                       case VK_SHIFT:
3360                         debug(("SHIFT"));
3361                         break;
3362                       case VK_CONTROL:
3363                         debug(("CTRL"));
3364                         break;
3365                       case VK_MENU:
3366                         debug(("ALT"));
3367                         break;
3368                       default:
3369                         debug(("VK_%02x", wParam));
3370                     }
3371                 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3372                     debug(("*"));
3373                 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3374
3375                 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3376                 if (ch >= ' ' && ch <= '~')
3377                     debug((", '%c'", ch));
3378                 else if (ch)
3379                     debug((", $%02x", ch));
3380
3381                 if (keys[0])
3382                     debug((", KB0=%02x", keys[0]));
3383                 if (keys[1])
3384                     debug((", KB1=%02x", keys[1]));
3385                 if (keys[2])
3386                     debug((", KB2=%02x", keys[2]));
3387
3388                 if ((keystate[VK_SHIFT] & 0x80) != 0)
3389                     debug((", S"));
3390                 if ((keystate[VK_CONTROL] & 0x80) != 0)
3391                     debug((", C"));
3392                 if ((HIWORD(lParam) & KF_EXTENDED))
3393                     debug((", E"));
3394                 if ((HIWORD(lParam) & KF_UP))
3395                     debug((", U"));
3396             }
3397
3398             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3399             else if ((HIWORD(lParam) & KF_UP))
3400                 oldstate[wParam & 0xFF] ^= 0x80;
3401             else
3402                 oldstate[wParam & 0xFF] ^= 0x81;
3403
3404             for (ch = 0; ch < 256; ch++)
3405                 if (oldstate[ch] != keystate[ch])
3406                     debug((", M%02x=%02x", ch, keystate[ch]));
3407
3408             memcpy(oldstate, keystate, sizeof(oldstate));
3409         }
3410 #endif
3411
3412         if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
3413             keystate[VK_RMENU] = keystate[VK_MENU];
3414         }
3415
3416
3417         /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
3418         if ((cfg.funky_type == FUNKY_VT400 ||
3419              (cfg.funky_type <= FUNKY_LINUX && term->app_keypad_keys &&
3420               !cfg.no_applic_k))
3421             && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
3422
3423             wParam = VK_EXECUTE;
3424
3425             /* UnToggle NUMLock */
3426             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3427                 keystate[VK_NUMLOCK] ^= 1;
3428         }
3429
3430         /* And write back the 'adjusted' state */
3431         SetKeyboardState(keystate);
3432     }
3433
3434     /* Disable Auto repeat if required */
3435     if (term->repeat_off &&
3436         (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
3437         return 0;
3438
3439     if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
3440         left_alt = 1;
3441
3442     key_down = ((HIWORD(lParam) & KF_UP) == 0);
3443
3444     /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
3445     if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
3446         if (cfg.ctrlaltkeys)
3447             keystate[VK_MENU] = 0;
3448         else {
3449             keystate[VK_RMENU] = 0x80;
3450             left_alt = 0;
3451         }
3452     }
3453
3454     scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
3455     shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3456         + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
3457
3458     /* Note if AltGr was pressed and if it was used as a compose key */
3459     if (!compose_state) {
3460         compose_key = 0x100;
3461         if (cfg.compose_key) {
3462             if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
3463                 compose_key = wParam;
3464         }
3465         if (wParam == VK_APPS)
3466             compose_key = wParam;
3467     }
3468
3469     if (wParam == compose_key) {
3470         if (compose_state == 0
3471             && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3472                 1;
3473         else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
3474             compose_state = 2;
3475         else
3476             compose_state = 0;
3477     } else if (compose_state == 1 && wParam != VK_CONTROL)
3478         compose_state = 0;
3479
3480     if (compose_state > 1 && left_alt)
3481         compose_state = 0;
3482
3483     /* Sanitize the number pad if not using a PC NumPad */
3484     if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
3485                      && cfg.funky_type != FUNKY_XTERM)
3486         || cfg.funky_type == FUNKY_VT400 || cfg.nethack_keypad || compose_state) {
3487         if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
3488             int nParam = 0;
3489             switch (wParam) {
3490               case VK_INSERT:
3491                 nParam = VK_NUMPAD0;
3492                 break;
3493               case VK_END:
3494                 nParam = VK_NUMPAD1;
3495                 break;
3496               case VK_DOWN:
3497                 nParam = VK_NUMPAD2;
3498                 break;
3499               case VK_NEXT:
3500                 nParam = VK_NUMPAD3;
3501                 break;
3502               case VK_LEFT:
3503                 nParam = VK_NUMPAD4;
3504                 break;
3505               case VK_CLEAR:
3506                 nParam = VK_NUMPAD5;
3507                 break;
3508               case VK_RIGHT:
3509                 nParam = VK_NUMPAD6;
3510                 break;
3511               case VK_HOME:
3512                 nParam = VK_NUMPAD7;
3513                 break;
3514               case VK_UP:
3515                 nParam = VK_NUMPAD8;
3516                 break;
3517               case VK_PRIOR:
3518                 nParam = VK_NUMPAD9;
3519                 break;
3520               case VK_DELETE:
3521                 nParam = VK_DECIMAL;
3522                 break;
3523             }
3524             if (nParam) {
3525                 if (keystate[VK_NUMLOCK] & 1)
3526                     shift_state |= 1;
3527                 wParam = nParam;
3528             }
3529         }
3530     }
3531
3532     /* If a key is pressed and AltGr is not active */
3533     if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3534         /* Okay, prepare for most alts then ... */
3535         if (left_alt)
3536             *p++ = '\033';
3537
3538         /* Lets see if it's a pattern we know all about ... */
3539         if (wParam == VK_PRIOR && shift_state == 1) {
3540             SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3541             return 0;
3542         }
3543         if (wParam == VK_PRIOR && shift_state == 2) {
3544             SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3545             return 0;
3546         }
3547         if (wParam == VK_NEXT && shift_state == 1) {
3548             SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3549             return 0;
3550         }
3551         if (wParam == VK_NEXT && shift_state == 2) {
3552             SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3553             return 0;
3554         }
3555         if (wParam == VK_INSERT && shift_state == 1) {
3556             term_do_paste(term);
3557             return 0;
3558         }
3559         if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
3560             return -1;
3561         }
3562         if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
3563             SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3564             return -1;
3565         }
3566         if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3567             (cfg.resize_action != RESIZE_DISABLED)) {
3568             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3569                 flip_full_screen();
3570             return -1;
3571         }
3572         /* Control-Numlock for app-keypad mode switch */
3573         if (wParam == VK_PAUSE && shift_state == 2) {
3574             term->app_keypad_keys ^= 1;
3575             return 0;
3576         }
3577
3578         /* Nethack keypad */
3579         if (cfg.nethack_keypad && !left_alt) {
3580             switch (wParam) {
3581               case VK_NUMPAD1:
3582                 *p++ = shift_state ? 'B' : 'b';
3583                 return p - output;
3584               case VK_NUMPAD2:
3585                 *p++ = shift_state ? 'J' : 'j';
3586                 return p - output;
3587               case VK_NUMPAD3:
3588                 *p++ = shift_state ? 'N' : 'n';
3589                 return p - output;
3590               case VK_NUMPAD4:
3591                 *p++ = shift_state ? 'H' : 'h';
3592                 return p - output;
3593               case VK_NUMPAD5:
3594                 *p++ = shift_state ? '.' : '.';
3595                 return p - output;
3596               case VK_NUMPAD6:
3597                 *p++ = shift_state ? 'L' : 'l';
3598                 return p - output;
3599               case VK_NUMPAD7:
3600                 *p++ = shift_state ? 'Y' : 'y';
3601                 return p - output;
3602               case VK_NUMPAD8:
3603                 *p++ = shift_state ? 'K' : 'k';
3604                 return p - output;
3605               case VK_NUMPAD9:
3606                 *p++ = shift_state ? 'U' : 'u';
3607                 return p - output;
3608             }
3609         }
3610
3611         /* Application Keypad */
3612         if (!left_alt) {
3613             int xkey = 0;
3614
3615             if (cfg.funky_type == FUNKY_VT400 ||
3616                 (cfg.funky_type <= FUNKY_LINUX &&
3617                  term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
3618                   case VK_EXECUTE:
3619                     xkey = 'P';
3620                     break;
3621                   case VK_DIVIDE:
3622                     xkey = 'Q';
3623                     break;
3624                   case VK_MULTIPLY:
3625                     xkey = 'R';
3626                     break;
3627                   case VK_SUBTRACT:
3628                     xkey = 'S';
3629                     break;
3630                 }
3631             if (term->app_keypad_keys && !cfg.no_applic_k)
3632                 switch (wParam) {
3633                   case VK_NUMPAD0:
3634                     xkey = 'p';
3635                     break;
3636                   case VK_NUMPAD1:
3637                     xkey = 'q';
3638                     break;
3639                   case VK_NUMPAD2:
3640                     xkey = 'r';
3641                     break;
3642                   case VK_NUMPAD3:
3643                     xkey = 's';
3644                     break;
3645                   case VK_NUMPAD4:
3646                     xkey = 't';
3647                     break;
3648                   case VK_NUMPAD5:
3649                     xkey = 'u';
3650                     break;
3651                   case VK_NUMPAD6:
3652                     xkey = 'v';
3653                     break;
3654                   case VK_NUMPAD7:
3655                     xkey = 'w';
3656                     break;
3657                   case VK_NUMPAD8:
3658                     xkey = 'x';
3659                     break;
3660                   case VK_NUMPAD9:
3661                     xkey = 'y';
3662                     break;
3663
3664                   case VK_DECIMAL:
3665                     xkey = 'n';
3666                     break;
3667                   case VK_ADD:
3668                     if (cfg.funky_type == FUNKY_XTERM) {
3669                         if (shift_state)
3670                             xkey = 'l';
3671                         else
3672                             xkey = 'k';
3673                     } else if (shift_state)
3674                         xkey = 'm';
3675                     else
3676                         xkey = 'l';
3677                     break;
3678
3679                   case VK_DIVIDE:
3680                     if (cfg.funky_type == FUNKY_XTERM)
3681                         xkey = 'o';
3682                     break;
3683                   case VK_MULTIPLY:
3684                     if (cfg.funky_type == FUNKY_XTERM)
3685                         xkey = 'j';
3686                     break;
3687                   case VK_SUBTRACT:
3688                     if (cfg.funky_type == FUNKY_XTERM)
3689                         xkey = 'm';
3690                     break;
3691
3692                   case VK_RETURN:
3693                     if (HIWORD(lParam) & KF_EXTENDED)
3694                         xkey = 'M';
3695                     break;
3696                 }
3697             if (xkey) {
3698                 if (term->vt52_mode) {
3699                     if (xkey >= 'P' && xkey <= 'S')
3700                         p += sprintf((char *) p, "\x1B%c", xkey);
3701                     else
3702                         p += sprintf((char *) p, "\x1B?%c", xkey);
3703                 } else
3704                     p += sprintf((char *) p, "\x1BO%c", xkey);
3705                 return p - output;
3706             }
3707         }
3708
3709         if (wParam == VK_BACK && shift_state == 0) {    /* Backspace */
3710             *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
3711             *p++ = 0;
3712             return -2;
3713         }
3714         if (wParam == VK_BACK && shift_state == 1) {    /* Shift Backspace */
3715             /* We do the opposite of what is configured */
3716             *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
3717             *p++ = 0;
3718             return -2;
3719         }
3720         if (wParam == VK_TAB && shift_state == 1) {     /* Shift tab */
3721             *p++ = 0x1B;
3722             *p++ = '[';
3723             *p++ = 'Z';
3724             return p - output;
3725         }
3726         if (wParam == VK_SPACE && shift_state == 2) {   /* Ctrl-Space */
3727             *p++ = 0;
3728             return p - output;
3729         }
3730         if (wParam == VK_SPACE && shift_state == 3) {   /* Ctrl-Shift-Space */
3731             *p++ = 160;
3732             return p - output;
3733         }
3734         if (wParam == VK_CANCEL && shift_state == 2) {  /* Ctrl-Break */
3735             *p++ = 3;
3736             *p++ = 0;
3737             return -2;
3738         }
3739         if (wParam == VK_PAUSE) {      /* Break/Pause */
3740             *p++ = 26;
3741             *p++ = 0;
3742             return -2;
3743         }
3744         /* Control-2 to Control-8 are special */
3745         if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
3746             *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
3747             return p - output;
3748         }
3749         if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
3750             *p++ = 0x1F;
3751             return p - output;
3752         }
3753         if (shift_state == 2 && wParam == 0xDF) {
3754             *p++ = 0x1C;
3755             return p - output;
3756         }
3757         if (shift_state == 3 && wParam == 0xDE) {
3758             *p++ = 0x1E;               /* Ctrl-~ == Ctrl-^ in xterm at least */
3759             return p - output;
3760         }
3761         if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
3762             *p++ = '\r';
3763             *p++ = '\n';
3764             return p - output;
3765         }
3766
3767         /*
3768          * Next, all the keys that do tilde codes. (ESC '[' nn '~',
3769          * for integer decimal nn.)
3770          *
3771          * We also deal with the weird ones here. Linux VCs replace F1
3772          * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
3773          * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
3774          * respectively.
3775          */
3776         code = 0;
3777         switch (wParam) {
3778           case VK_F1:
3779             code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
3780             break;
3781           case VK_F2:
3782             code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
3783             break;
3784           case VK_F3:
3785             code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
3786             break;
3787           case VK_F4:
3788             code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
3789             break;
3790           case VK_F5:
3791             code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
3792             break;
3793           case VK_F6:
3794             code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
3795             break;
3796           case VK_F7:
3797             code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
3798             break;
3799           case VK_F8:
3800             code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
3801             break;
3802           case VK_F9:
3803             code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
3804             break;
3805           case VK_F10:
3806             code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
3807             break;
3808           case VK_F11:
3809             code = 23;
3810             break;
3811           case VK_F12:
3812             code = 24;
3813             break;
3814           case VK_F13:
3815             code = 25;
3816             break;
3817           case VK_F14:
3818             code = 26;
3819             break;
3820           case VK_F15:
3821             code = 28;
3822             break;
3823           case VK_F16:
3824             code = 29;
3825             break;
3826           case VK_F17:
3827             code = 31;
3828             break;
3829           case VK_F18:
3830             code = 32;
3831             break;
3832           case VK_F19:
3833             code = 33;
3834             break;
3835           case VK_F20:
3836             code = 34;
3837             break;
3838         }
3839         if ((shift_state&2) == 0) switch (wParam) {
3840           case VK_HOME:
3841             code = 1;
3842             break;
3843           case VK_INSERT:
3844             code = 2;
3845             break;
3846           case VK_DELETE:
3847             code = 3;
3848             break;
3849           case VK_END:
3850             code = 4;
3851             break;
3852           case VK_PRIOR:
3853             code = 5;
3854             break;
3855           case VK_NEXT:
3856             code = 6;
3857             break;
3858         }
3859         /* Reorder edit keys to physical order */
3860         if (cfg.funky_type == FUNKY_VT400 && code <= 6)
3861             code = "\0\2\1\4\5\3\6"[code];
3862
3863         if (term->vt52_mode && code > 0 && code <= 6) {
3864             p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
3865             return p - output;
3866         }
3867
3868         if (cfg.funky_type == FUNKY_SCO &&     /* SCO function keys */
3869             code >= 11 && code <= 34) {
3870             char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
3871             int index = 0;
3872             switch (wParam) {
3873               case VK_F1: index = 0; break;
3874               case VK_F2: index = 1; break;
3875               case VK_F3: index = 2; break;
3876               case VK_F4: index = 3; break;
3877               case VK_F5: index = 4; break;
3878               case VK_F6: index = 5; break;
3879               case VK_F7: index = 6; break;
3880               case VK_F8: index = 7; break;
3881               case VK_F9: index = 8; break;
3882               case VK_F10: index = 9; break;
3883               case VK_F11: index = 10; break;
3884               case VK_F12: index = 11; break;
3885             }
3886             if (keystate[VK_SHIFT] & 0x80) index += 12;
3887             if (keystate[VK_CONTROL] & 0x80) index += 24;
3888             p += sprintf((char *) p, "\x1B[%c", codes[index]);
3889             return p - output;
3890         }
3891         if (cfg.funky_type == FUNKY_SCO &&     /* SCO small keypad */
3892             code >= 1 && code <= 6) {
3893             char codes[] = "HL.FIG";
3894             if (code == 3) {
3895                 *p++ = '\x7F';
3896             } else {
3897                 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
3898             }
3899             return p - output;
3900         }
3901         if ((term->vt52_mode || cfg.funky_type == FUNKY_VT100P) && code >= 11 && code <= 24) {
3902             int offt = 0;
3903             if (code > 15)
3904                 offt++;
3905             if (code > 21)
3906                 offt++;
3907             if (term->vt52_mode)
3908                 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
3909             else
3910                 p +=
3911                     sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
3912             return p - output;
3913         }
3914         if (cfg.funky_type == FUNKY_LINUX && code >= 11 && code <= 15) {
3915             p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
3916             return p - output;
3917         }
3918         if (cfg.funky_type == FUNKY_XTERM && code >= 11 && code <= 14) {
3919             if (term->vt52_mode)
3920                 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
3921             else
3922                 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
3923             return p - output;
3924         }
3925         if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
3926             p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
3927             return p - output;
3928         }
3929         if (code) {
3930             p += sprintf((char *) p, "\x1B[%d~", code);
3931             return p - output;
3932         }
3933
3934         /*
3935          * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
3936          * some reason seems to send VK_CLEAR to Windows...).
3937          */
3938         {
3939             char xkey = 0;
3940             switch (wParam) {
3941               case VK_UP:
3942                 xkey = 'A';
3943                 break;
3944               case VK_DOWN:
3945                 xkey = 'B';
3946                 break;
3947               case VK_RIGHT:
3948                 xkey = 'C';
3949                 break;
3950               case VK_LEFT:
3951                 xkey = 'D';
3952                 break;
3953               case VK_CLEAR:
3954                 xkey = 'G';
3955                 break;
3956             }
3957             if (xkey) {
3958                 if (term->vt52_mode)
3959                     p += sprintf((char *) p, "\x1B%c", xkey);
3960                 else {
3961                     int app_flg = (term->app_cursor_keys && !cfg.no_applic_c);
3962 #if 0
3963                     /*
3964                      * RDB: VT100 & VT102 manuals both state the
3965                      * app cursor keys only work if the app keypad
3966                      * is on.
3967                      * 
3968                      * SGT: That may well be true, but xterm
3969                      * disagrees and so does at least one
3970                      * application, so I've #if'ed this out and the
3971                      * behaviour is back to PuTTY's original: app
3972                      * cursor and app keypad are independently
3973                      * switchable modes. If anyone complains about
3974                      * _this_ I'll have to put in a configurable
3975                      * option.
3976                      */
3977                     if (!term->app_keypad_keys)
3978                         app_flg = 0;
3979 #endif
3980                     /* Useful mapping of Ctrl-arrows */
3981                     if (shift_state == 2)
3982                         app_flg = !app_flg;
3983
3984                     if (app_flg)
3985                         p += sprintf((char *) p, "\x1BO%c", xkey);
3986                     else
3987                         p += sprintf((char *) p, "\x1B[%c", xkey);
3988                 }
3989                 return p - output;
3990             }
3991         }
3992
3993         /*
3994          * Finally, deal with Return ourselves. (Win95 seems to
3995          * foul it up when Alt is pressed, for some reason.)
3996          */
3997         if (wParam == VK_RETURN) {     /* Return */
3998             *p++ = 0x0D;
3999             *p++ = 0;
4000             return -2;
4001         }
4002
4003         if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
4004             alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
4005         else
4006             alt_sum = 0;
4007     }
4008
4009     /* Okay we've done everything interesting; let windows deal with 
4010      * the boring stuff */
4011     {
4012         BOOL capsOn=0;
4013
4014         /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
4015         if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
4016             capsOn= !left_alt;
4017             keystate[VK_CAPITAL] = 0;
4018         }
4019
4020         /* XXX how do we know what the max size of the keys array should
4021          * be is? There's indication on MS' website of an Inquire/InquireEx
4022          * functioning returning a KBINFO structure which tells us. */
4023         if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
4024             /* XXX 'keys' parameter is declared in MSDN documentation as
4025              * 'LPWORD lpChar'.
4026              * The experience of a French user indicates that on
4027              * Win98, WORD[] should be passed in, but on Win2K, it should
4028              * be BYTE[]. German WinXP and my Win2K with "US International"
4029              * driver corroborate this.
4030              * Experimentally I've conditionalised the behaviour on the
4031              * Win9x/NT split, but I suspect it's worse than that.
4032              * See wishlist item `win-dead-keys' for more horrible detail
4033              * and speculations. */
4034             BYTE keybs[3];
4035             int i;
4036             r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
4037             for (i=0; i<3; i++) keys[i] = keybs[i];
4038         } else {
4039             r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
4040         }
4041 #ifdef SHOW_TOASCII_RESULT
4042         if (r == 1 && !key_down) {
4043             if (alt_sum) {
4044                 if (in_utf(term) || ucsdata.dbcs_screenfont)
4045                     debug((", (U+%04x)", alt_sum));
4046                 else
4047                     debug((", LCH(%d)", alt_sum));
4048             } else {
4049                 debug((", ACH(%d)", keys[0]));
4050             }
4051         } else if (r > 0) {
4052             int r1;
4053             debug((", ASC("));
4054             for (r1 = 0; r1 < r; r1++) {
4055                 debug(("%s%d", r1 ? "," : "", keys[r1]));
4056             }
4057             debug((")"));
4058         }
4059 #endif
4060         if (r > 0) {
4061             WCHAR keybuf;
4062
4063             /*
4064              * Interrupt an ongoing paste. I'm not sure this is
4065              * sensible, but for the moment it's preferable to
4066              * having to faff about buffering things.
4067              */
4068             term_nopaste(term);
4069
4070             p = output;
4071             for (i = 0; i < r; i++) {
4072                 unsigned char ch = (unsigned char) keys[i];
4073
4074                 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
4075                     compose_char = ch;
4076                     compose_state++;
4077                     continue;
4078                 }
4079                 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
4080                     int nc;
4081                     compose_state = 0;
4082
4083                     if ((nc = check_compose(compose_char, ch)) == -1) {
4084                         MessageBeep(MB_ICONHAND);
4085                         return 0;
4086                     }
4087                     keybuf = nc;
4088                     term_seen_key_event(term);
4089                     if (ldisc)
4090                         luni_send(ldisc, &keybuf, 1, 1);
4091                     continue;
4092                 }
4093
4094                 compose_state = 0;
4095
4096                 if (!key_down) {
4097                     if (alt_sum) {
4098                         if (in_utf(term) || ucsdata.dbcs_screenfont) {
4099                             keybuf = alt_sum;
4100                             term_seen_key_event(term);
4101                             if (ldisc)
4102                                 luni_send(ldisc, &keybuf, 1, 1);
4103                         } else {
4104                             ch = (char) alt_sum;
4105                             /*
4106                              * We need not bother about stdin
4107                              * backlogs here, because in GUI PuTTY
4108                              * we can't do anything about it
4109                              * anyway; there's no means of asking
4110                              * Windows to hold off on KEYDOWN
4111                              * messages. We _have_ to buffer
4112                              * everything we're sent.
4113                              */
4114                             term_seen_key_event(term);
4115                             if (ldisc)
4116                                 ldisc_send(ldisc, &ch, 1, 1);
4117                         }
4118                         alt_sum = 0;
4119                     } else {
4120                         term_seen_key_event(term);
4121                         if (ldisc)
4122                             lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
4123                     }
4124                 } else {
4125                     if(capsOn && ch < 0x80) {
4126                         WCHAR cbuf[2];
4127                         cbuf[0] = 27;
4128                         cbuf[1] = xlat_uskbd2cyrllic(ch);
4129                         term_seen_key_event(term);
4130                         if (ldisc)
4131                             luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
4132                     } else {
4133                         char cbuf[2];
4134                         cbuf[0] = '\033';
4135                         cbuf[1] = ch;
4136                         term_seen_key_event(term);
4137                         if (ldisc)
4138                             lpage_send(ldisc, kbd_codepage,
4139                                        cbuf+!left_alt, 1+!!left_alt, 1);
4140                     }
4141                 }
4142                 show_mouseptr(0);
4143             }
4144
4145             /* This is so the ALT-Numpad and dead keys work correctly. */
4146             keys[0] = 0;
4147
4148             return p - output;
4149         }
4150         /* If we're definitly not building up an ALT-54321 then clear it */
4151         if (!left_alt)
4152             keys[0] = 0;
4153         /* If we will be using alt_sum fix the 256s */
4154         else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4155             keys[0] = 10;
4156     }
4157
4158     /*
4159      * ALT alone may or may not want to bring up the System menu.
4160      * If it's not meant to, we return 0 on presses or releases of
4161      * ALT, to show that we've swallowed the keystroke. Otherwise
4162      * we return -1, which means Windows will give the keystroke
4163      * its default handling (i.e. bring up the System menu).
4164      */
4165     if (wParam == VK_MENU && !cfg.alt_only)
4166         return 0;
4167
4168     return -1;
4169 }
4170
4171 void request_paste(void *frontend)
4172 {
4173     /*
4174      * In Windows, pasting is synchronous: we can read the
4175      * clipboard with no difficulty, so request_paste() can just go
4176      * ahead and paste.
4177      */
4178     term_do_paste(term);
4179 }
4180
4181 void set_title(void *frontend, char *title)
4182 {
4183     sfree(window_name);
4184     window_name = snewn(1 + strlen(title), char);
4185     strcpy(window_name, title);
4186     if (cfg.win_name_always || !IsIconic(hwnd))
4187         SetWindowText(hwnd, title);
4188 }
4189
4190 void set_icon(void *frontend, char *title)
4191 {
4192     sfree(icon_name);
4193     icon_name = snewn(1 + strlen(title), char);
4194     strcpy(icon_name, title);
4195     if (!cfg.win_name_always && IsIconic(hwnd))
4196         SetWindowText(hwnd, title);
4197 }
4198
4199 void set_sbar(void *frontend, int total, int start, int page)
4200 {
4201     SCROLLINFO si;
4202
4203     if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
4204         return;
4205
4206     si.cbSize = sizeof(si);
4207     si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4208     si.nMin = 0;
4209     si.nMax = total - 1;
4210     si.nPage = page;
4211     si.nPos = start;
4212     if (hwnd)
4213         SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4214 }
4215
4216 Context get_ctx(void *frontend)
4217 {
4218     HDC hdc;
4219     if (hwnd) {
4220         hdc = GetDC(hwnd);
4221         if (hdc && pal)
4222             SelectPalette(hdc, pal, FALSE);
4223         return hdc;
4224     } else
4225         return NULL;
4226 }
4227
4228 void free_ctx(Context ctx)
4229 {
4230     SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4231     ReleaseDC(hwnd, ctx);
4232 }
4233
4234 static void real_palette_set(int n, int r, int g, int b)
4235 {
4236     if (pal) {
4237         logpal->palPalEntry[n].peRed = r;
4238         logpal->palPalEntry[n].peGreen = g;
4239         logpal->palPalEntry[n].peBlue = b;
4240         logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4241         colours[n] = PALETTERGB(r, g, b);
4242         SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
4243     } else
4244         colours[n] = RGB(r, g, b);
4245 }
4246
4247 void palette_set(void *frontend, int n, int r, int g, int b)
4248 {
4249     static const int first[21] = {
4250         0, 2, 4, 6, 8, 10, 12, 14,
4251         1, 3, 5, 7, 9, 11, 13, 15,
4252         16, 17, 18, 20, 22
4253     };
4254     real_palette_set(first[n], r, g, b);
4255     if (first[n] >= 18)
4256         real_palette_set(first[n] + 1, r, g, b);
4257     if (pal) {
4258         HDC hdc = get_ctx(frontend);
4259         UnrealizeObject(pal);
4260         RealizePalette(hdc);
4261         free_ctx(hdc);
4262     }
4263 }
4264
4265 void palette_reset(void *frontend)
4266 {
4267     int i;
4268
4269     for (i = 0; i < NCOLOURS; i++) {
4270         if (pal) {
4271             logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4272             logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4273             logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4274             logpal->palPalEntry[i].peFlags = 0;
4275             colours[i] = PALETTERGB(defpal[i].rgbtRed,
4276                                     defpal[i].rgbtGreen,
4277                                     defpal[i].rgbtBlue);
4278         } else
4279             colours[i] = RGB(defpal[i].rgbtRed,
4280                              defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4281     }
4282
4283     if (pal) {
4284         HDC hdc;
4285         SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
4286         hdc = get_ctx(frontend);
4287         RealizePalette(hdc);
4288         free_ctx(hdc);
4289     }
4290 }
4291
4292 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4293 {
4294     HGLOBAL clipdata;
4295     void *lock;
4296
4297     clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4298     if (!clipdata)
4299         return;
4300     lock = GlobalLock(clipdata);
4301     if (!lock)
4302         return;
4303     memcpy(lock, data, len);
4304     ((unsigned char *) lock)[len] = 0;
4305     GlobalUnlock(clipdata);
4306
4307     if (!must_deselect)
4308         SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4309
4310     if (OpenClipboard(hwnd)) {
4311         EmptyClipboard();
4312         SetClipboardData(CF_TEXT, clipdata);
4313         CloseClipboard();
4314     } else
4315         GlobalFree(clipdata);
4316
4317     if (!must_deselect)
4318         SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4319 }
4320
4321 /*
4322  * Note: unlike write_aclip() this will not append a nul.
4323  */
4324 void write_clip(void *frontend, wchar_t * data, int len, int must_deselect)
4325 {
4326     HGLOBAL clipdata, clipdata2, clipdata3;
4327     int len2;
4328     void *lock, *lock2, *lock3;
4329
4330     len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4331
4332     clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4333                            len * sizeof(wchar_t));
4334     clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4335
4336     if (!clipdata || !clipdata2) {
4337         if (clipdata)
4338             GlobalFree(clipdata);
4339         if (clipdata2)
4340             GlobalFree(clipdata2);
4341         return;
4342     }
4343     if (!(lock = GlobalLock(clipdata)))
4344         return;
4345     if (!(lock2 = GlobalLock(clipdata2)))
4346         return;
4347
4348     memcpy(lock, data, len * sizeof(wchar_t));
4349     WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4350
4351     if (cfg.rtf_paste) {
4352         wchar_t unitab[256];
4353         char *rtf = NULL;
4354         unsigned char *tdata = (unsigned char *)lock2;
4355         wchar_t *udata = (wchar_t *)lock;
4356         int rtflen = 0, uindex = 0, tindex = 0;
4357         int rtfsize = 0;
4358         int multilen, blen, alen, totallen, i;
4359         char before[16], after[4];
4360
4361         get_unitab(CP_ACP, unitab, 0);
4362
4363         rtfsize = 100 + strlen(cfg.font.name);
4364         rtf = snewn(rtfsize, char);
4365         sprintf(rtf, "{\\rtf1\\ansi%d{\\fonttbl\\f0\\fmodern %s;}\\f0",
4366                 GetACP(), cfg.font.name);
4367         rtflen = strlen(rtf);
4368
4369         /*
4370          * We want to construct a piece of RTF that specifies the
4371          * same Unicode text. To do this we will read back in
4372          * parallel from the Unicode data in `udata' and the
4373          * non-Unicode data in `tdata'. For each character in
4374          * `tdata' which becomes the right thing in `udata' when
4375          * looked up in `unitab', we just copy straight over from
4376          * tdata. For each one that doesn't, we must WCToMB it
4377          * individually and produce a \u escape sequence.
4378          * 
4379          * It would probably be more robust to just bite the bullet
4380          * and WCToMB each individual Unicode character one by one,
4381          * then MBToWC each one back to see if it was an accurate
4382          * translation; but that strikes me as a horrifying number
4383          * of Windows API calls so I want to see if this faster way
4384          * will work. If it screws up badly we can always revert to
4385          * the simple and slow way.
4386          */
4387         while (tindex < len2 && uindex < len &&
4388                tdata[tindex] && udata[uindex]) {
4389             if (tindex + 1 < len2 &&
4390                 tdata[tindex] == '\r' &&
4391                 tdata[tindex+1] == '\n') {
4392                 tindex++;
4393                 uindex++;
4394             }
4395             if (unitab[tdata[tindex]] == udata[uindex]) {
4396                 multilen = 1;
4397                 before[0] = '\0';
4398                 after[0] = '\0';
4399                 blen = alen = 0;
4400             } else {
4401                 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4402                                                NULL, 0, NULL, NULL);
4403                 if (multilen != 1) {
4404                     blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4405                                    udata[uindex]);
4406                     alen = 1; strcpy(after, "}");
4407                 } else {
4408                     blen = sprintf(before, "\\u%d", udata[uindex]);
4409                     alen = 0; after[0] = '\0';
4410                 }
4411             }
4412             assert(tindex + multilen <= len2);
4413             totallen = blen + alen;
4414             for (i = 0; i < multilen; i++) {
4415                 if (tdata[tindex+i] == '\\' ||
4416                     tdata[tindex+i] == '{' ||
4417                     tdata[tindex+i] == '}')
4418                     totallen += 2;
4419                 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4420                     totallen += 6;     /* \par\r\n */
4421                 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4422                     totallen += 4;
4423                 else
4424                     totallen++;
4425             }
4426
4427             if (rtfsize < rtflen + totallen + 3) {
4428                 rtfsize = rtflen + totallen + 512;
4429                 rtf = sresize(rtf, rtfsize, char);
4430             }
4431
4432             strcpy(rtf + rtflen, before); rtflen += blen;
4433             for (i = 0; i < multilen; i++) {
4434                 if (tdata[tindex+i] == '\\' ||
4435                     tdata[tindex+i] == '{' ||
4436                     tdata[tindex+i] == '}') {
4437                     rtf[rtflen++] = '\\';
4438                     rtf[rtflen++] = tdata[tindex+i];
4439                 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4440                     rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4441                 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4442                     rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4443                 } else {
4444                     rtf[rtflen++] = tdata[tindex+i];
4445                 }
4446             }
4447             strcpy(rtf + rtflen, after); rtflen += alen;
4448
4449             tindex += multilen;
4450             uindex++;
4451         }
4452
4453         strcpy(rtf + rtflen, "}");
4454         rtflen += 2;
4455
4456         clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4457         if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
4458             strcpy(lock3, rtf);
4459             GlobalUnlock(clipdata3);
4460         }
4461         sfree(rtf);
4462     } else
4463         clipdata3 = NULL;
4464
4465     GlobalUnlock(clipdata);
4466     GlobalUnlock(clipdata2);
4467
4468     if (!must_deselect)
4469         SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4470
4471     if (OpenClipboard(hwnd)) {
4472         EmptyClipboard();
4473         SetClipboardData(CF_UNICODETEXT, clipdata);
4474         SetClipboardData(CF_TEXT, clipdata2);
4475         if (clipdata3)
4476             SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4477         CloseClipboard();
4478     } else {
4479         GlobalFree(clipdata);
4480         GlobalFree(clipdata2);
4481     }
4482
4483     if (!must_deselect)
4484         SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4485 }
4486
4487 void get_clip(void *frontend, wchar_t ** p, int *len)
4488 {
4489     static HGLOBAL clipdata = NULL;
4490     static wchar_t *converted = 0;
4491     wchar_t *p2;
4492
4493     if (converted) {
4494         sfree(converted);
4495         converted = 0;
4496     }
4497     if (!p) {
4498         if (clipdata)
4499             GlobalUnlock(clipdata);
4500         clipdata = NULL;
4501         return;
4502     } else if (OpenClipboard(NULL)) {
4503         if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
4504             CloseClipboard();
4505             *p = GlobalLock(clipdata);
4506             if (*p) {
4507                 for (p2 = *p; *p2; p2++);
4508                 *len = p2 - *p;
4509                 return;
4510             }
4511         } else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
4512             char *s;
4513             int i;
4514             CloseClipboard();
4515             s = GlobalLock(clipdata);
4516             i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
4517             *p = converted = snewn(i, wchar_t);
4518             MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
4519             *len = i - 1;
4520             return;
4521         } else
4522             CloseClipboard();
4523     }
4524
4525     *p = NULL;
4526     *len = 0;
4527 }
4528
4529 #if 0
4530 /*
4531  * Move `lines' lines from position `from' to position `to' in the
4532  * window.
4533  */
4534 void optimised_move(void *frontend, int to, int from, int lines)
4535 {
4536     RECT r;
4537     int min, max;
4538
4539     min = (to < from ? to : from);
4540     max = to + from - min;
4541
4542     r.left = offset_width;
4543     r.right = offset_width + term->cols * font_width;
4544     r.top = offset_height + min * font_height;
4545     r.bottom = offset_height + (max + lines) * font_height;
4546     ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
4547 }
4548 #endif
4549
4550 /*
4551  * Print a message box and perform a fatal exit.
4552  */
4553 void fatalbox(char *fmt, ...)
4554 {
4555     va_list ap;
4556     char *stuff, morestuff[100];
4557
4558     va_start(ap, fmt);
4559     stuff = dupvprintf(fmt, ap);
4560     va_end(ap);
4561     sprintf(morestuff, "%.70s Fatal Error", appname);
4562     MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
4563     sfree(stuff);
4564     cleanup_exit(1);
4565 }
4566
4567 /*
4568  * Print a modal (Really Bad) message box and perform a fatal exit.
4569  */
4570 void modalfatalbox(char *fmt, ...)
4571 {
4572     va_list ap;
4573     char *stuff, morestuff[100];
4574
4575     va_start(ap, fmt);
4576     stuff = dupvprintf(fmt, ap);
4577     va_end(ap);
4578     sprintf(morestuff, "%.70s Fatal Error", appname);
4579     MessageBox(hwnd, stuff, morestuff,
4580                MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
4581     sfree(stuff);
4582     cleanup_exit(1);
4583 }
4584
4585 /*
4586  * Manage window caption / taskbar flashing, if enabled.
4587  * 0 = stop, 1 = maintain, 2 = start
4588  */
4589 static void flash_window(int mode)
4590 {
4591     static long last_flash = 0;
4592     static int flashing = 0;
4593     if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
4594         /* stop */
4595         if (flashing) {
4596             FlashWindow(hwnd, FALSE);
4597             flashing = 0;
4598         }
4599
4600     } else if (mode == 2) {
4601         /* start */
4602         if (!flashing) {
4603             last_flash = GetTickCount();
4604             flashing = 1;
4605             FlashWindow(hwnd, TRUE);
4606         }
4607
4608     } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
4609         /* maintain */
4610         if (flashing) {
4611             long now = GetTickCount();
4612             long fdiff = now - last_flash;
4613             if (fdiff < 0 || fdiff > 450) {
4614                 last_flash = now;
4615                 FlashWindow(hwnd, TRUE);        /* toggle */
4616             }
4617         }
4618     }
4619 }
4620
4621 /*
4622  * Beep.
4623  */
4624 void beep(void *frontend, int mode)
4625 {
4626     if (mode == BELL_DEFAULT) {
4627         /*
4628          * For MessageBeep style bells, we want to be careful of
4629          * timing, because they don't have the nice property of
4630          * PlaySound bells that each one cancels the previous
4631          * active one. So we limit the rate to one per 50ms or so.
4632          */
4633         static long lastbeep = 0;
4634         long beepdiff;
4635
4636         beepdiff = GetTickCount() - lastbeep;
4637         if (beepdiff >= 0 && beepdiff < 50)
4638             return;
4639         MessageBeep(MB_OK);
4640         /*
4641          * The above MessageBeep call takes time, so we record the
4642          * time _after_ it finishes rather than before it starts.
4643          */
4644         lastbeep = GetTickCount();
4645     } else if (mode == BELL_WAVEFILE) {
4646         if (!PlaySound(cfg.bell_wavefile.path, NULL,
4647                        SND_ASYNC | SND_FILENAME)) {
4648             char buf[sizeof(cfg.bell_wavefile.path) + 80];
4649             char otherbuf[100];
4650             sprintf(buf, "Unable to play sound file\n%s\n"
4651                     "Using default sound instead", cfg.bell_wavefile.path);
4652             sprintf(otherbuf, "%.70s Sound Error", appname);
4653             MessageBox(hwnd, buf, otherbuf,
4654                        MB_OK | MB_ICONEXCLAMATION);
4655             cfg.beep = BELL_DEFAULT;
4656         }
4657     } else if (mode == BELL_PCSPEAKER) {
4658         static long lastbeep = 0;
4659         long beepdiff;
4660
4661         beepdiff = GetTickCount() - lastbeep;
4662         if (beepdiff >= 0 && beepdiff < 50)
4663             return;
4664
4665         /*
4666          * We must beep in different ways depending on whether this
4667          * is a 95-series or NT-series OS.
4668          */
4669         if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
4670             Beep(800, 100);
4671         else
4672             MessageBeep(-1);
4673         lastbeep = GetTickCount();
4674     }
4675     /* Otherwise, either visual bell or disabled; do nothing here */
4676     if (!term->has_focus) {
4677         flash_window(2);               /* start */
4678     }
4679 }
4680
4681 /*
4682  * Minimise or restore the window in response to a server-side
4683  * request.
4684  */
4685 void set_iconic(void *frontend, int iconic)
4686 {
4687     if (IsIconic(hwnd)) {
4688         if (!iconic)
4689             ShowWindow(hwnd, SW_RESTORE);
4690     } else {
4691         if (iconic)
4692             ShowWindow(hwnd, SW_MINIMIZE);
4693     }
4694 }
4695
4696 /*
4697  * Move the window in response to a server-side request.
4698  */
4699 void move_window(void *frontend, int x, int y)
4700 {
4701     if (cfg.resize_action == RESIZE_DISABLED || 
4702         cfg.resize_action == RESIZE_FONT ||
4703         IsZoomed(hwnd))
4704        return;
4705
4706     SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
4707 }
4708
4709 /*
4710  * Move the window to the top or bottom of the z-order in response
4711  * to a server-side request.
4712  */
4713 void set_zorder(void *frontend, int top)
4714 {
4715     if (cfg.alwaysontop)
4716         return;                        /* ignore */
4717     SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
4718                  SWP_NOMOVE | SWP_NOSIZE);
4719 }
4720
4721 /*
4722  * Refresh the window in response to a server-side request.
4723  */
4724 void refresh_window(void *frontend)
4725 {
4726     InvalidateRect(hwnd, NULL, TRUE);
4727 }
4728
4729 /*
4730  * Maximise or restore the window in response to a server-side
4731  * request.
4732  */
4733 void set_zoomed(void *frontend, int zoomed)
4734 {
4735     if (IsZoomed(hwnd)) {
4736         if (!zoomed)
4737             ShowWindow(hwnd, SW_RESTORE);
4738     } else {
4739         if (zoomed)
4740             ShowWindow(hwnd, SW_MAXIMIZE);
4741     }
4742 }
4743
4744 /*
4745  * Report whether the window is iconic, for terminal reports.
4746  */
4747 int is_iconic(void *frontend)
4748 {
4749     return IsIconic(hwnd);
4750 }
4751
4752 /*
4753  * Report the window's position, for terminal reports.
4754  */
4755 void get_window_pos(void *frontend, int *x, int *y)
4756 {
4757     RECT r;
4758     GetWindowRect(hwnd, &r);
4759     *x = r.left;
4760     *y = r.top;
4761 }
4762
4763 /*
4764  * Report the window's pixel size, for terminal reports.
4765  */
4766 void get_window_pixels(void *frontend, int *x, int *y)
4767 {
4768     RECT r;
4769     GetWindowRect(hwnd, &r);
4770     *x = r.right - r.left;
4771     *y = r.bottom - r.top;
4772 }
4773
4774 /*
4775  * Return the window or icon title.
4776  */
4777 char *get_window_title(void *frontend, int icon)
4778 {
4779     return icon ? icon_name : window_name;
4780 }
4781
4782 /*
4783  * See if we're in full-screen mode.
4784  */
4785 static int is_full_screen()
4786 {
4787     if (!IsZoomed(hwnd))
4788         return FALSE;
4789     if (GetWindowLong(hwnd, GWL_STYLE) & WS_CAPTION)
4790         return FALSE;
4791     return TRUE;
4792 }
4793
4794 /* Get the rect/size of a full screen window using the nearest available
4795  * monitor in multimon systems; default to something sensible if only
4796  * one monitor is present. */
4797 static int get_fullscreen_rect(RECT * ss)
4798 {
4799 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
4800         HMONITOR mon;
4801         MONITORINFO mi;
4802         mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
4803         mi.cbSize = sizeof(mi);
4804         GetMonitorInfo(mon, &mi);
4805
4806         /* structure copy */
4807         *ss = mi.rcMonitor;
4808         return TRUE;
4809 #else
4810 /* could also use code like this:
4811         ss->left = ss->top = 0;
4812         ss->right = GetSystemMetrics(SM_CXSCREEN);
4813         ss->bottom = GetSystemMetrics(SM_CYSCREEN);
4814 */ 
4815         return GetClientRect(GetDesktopWindow(), ss);
4816 #endif
4817 }
4818
4819
4820 /*
4821  * Go full-screen. This should only be called when we are already
4822  * maximised.
4823  */
4824 static void make_full_screen()
4825 {
4826     DWORD style;
4827         RECT ss;
4828
4829     assert(IsZoomed(hwnd));
4830
4831         if (is_full_screen())
4832                 return;
4833         
4834     /* Remove the window furniture. */
4835     style = GetWindowLong(hwnd, GWL_STYLE);
4836     style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
4837     if (cfg.scrollbar_in_fullscreen)
4838         style |= WS_VSCROLL;
4839     else
4840         style &= ~WS_VSCROLL;
4841     SetWindowLong(hwnd, GWL_STYLE, style);
4842
4843     /* Resize ourselves to exactly cover the nearest monitor. */
4844         get_fullscreen_rect(&ss);
4845     SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
4846                         ss.right - ss.left,
4847                         ss.bottom - ss.top,
4848                         SWP_FRAMECHANGED);
4849
4850     /* Tick the menu item in the System menu. */
4851     CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4852                   MF_CHECKED);
4853 }
4854
4855 /*
4856  * Clear the full-screen attributes.
4857  */
4858 static void clear_full_screen()
4859 {
4860     DWORD oldstyle, style;
4861
4862     /* Reinstate the window furniture. */
4863     style = oldstyle = GetWindowLong(hwnd, GWL_STYLE);
4864     style |= WS_CAPTION | WS_BORDER;
4865     if (cfg.resize_action == RESIZE_DISABLED)
4866         style &= ~WS_THICKFRAME;
4867     else
4868         style |= WS_THICKFRAME;
4869     if (cfg.scrollbar)
4870         style |= WS_VSCROLL;
4871     else
4872         style &= ~WS_VSCROLL;
4873     if (style != oldstyle) {
4874         SetWindowLong(hwnd, GWL_STYLE, style);
4875         SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
4876                      SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
4877                      SWP_FRAMECHANGED);
4878     }
4879
4880     /* Untick the menu item in the System menu. */
4881     CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4882                   MF_UNCHECKED);
4883 }
4884
4885 /*
4886  * Toggle full-screen mode.
4887  */
4888 static void flip_full_screen()
4889 {
4890     if (is_full_screen()) {
4891         ShowWindow(hwnd, SW_RESTORE);
4892     } else if (IsZoomed(hwnd)) {
4893         make_full_screen();
4894     } else {
4895         SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
4896         ShowWindow(hwnd, SW_MAXIMIZE);
4897     }
4898 }
4899
4900 void frontend_keypress(void *handle)
4901 {
4902     /*
4903      * Keypress termination in non-Close-On-Exit mode is not
4904      * currently supported in PuTTY proper, because the window
4905      * always has a perfectly good Close button anyway. So we do
4906      * nothing here.
4907      */
4908     return;
4909 }
4910
4911 int from_backend(void *frontend, int is_stderr, const char *data, int len)
4912 {
4913     return term_data(term, is_stderr, data, len);
4914 }
4915
4916 void agent_schedule_callback(void (*callback)(void *, void *, int),
4917                              void *callback_ctx, void *data, int len)
4918 {
4919     struct agent_callback *c = snew(struct agent_callback);
4920     c->callback = callback;
4921     c->callback_ctx = callback_ctx;
4922     c->data = data;
4923     c->len = len;
4924     PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);
4925 }