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