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