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