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