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