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