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