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