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