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