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