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