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