]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - window.c
Move MODULE files out of individual project directories into a
[PuTTY.git] / window.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <ctype.h>
4 #include <time.h>
5 #include <assert.h>
6
7 #define PUTTY_DO_GLOBALS               /* actually _define_ globals */
8 #include "putty.h"
9 #include "terminal.h"
10 #include "storage.h"
11 #include "win_res.h"
12
13 #ifndef NO_MULTIMON
14 #if WINVER < 0x0500
15 #define COMPILE_MULTIMON_STUBS
16 #include <multimon.h>
17 #endif
18 #endif
19
20 #include <imm.h>
21 #include <commctrl.h>
22 #include <richedit.h>
23 #include <mmsystem.h>
24
25 #define IDM_SHOWLOG   0x0010
26 #define IDM_NEWSESS   0x0020
27 #define IDM_DUPSESS   0x0030
28 #define IDM_RECONF    0x0040
29 #define IDM_CLRSB     0x0050
30 #define IDM_RESET     0x0060
31 #define IDM_HELP      0x0140
32 #define IDM_ABOUT     0x0150
33 #define IDM_SAVEDSESS 0x0160
34 #define IDM_COPYALL   0x0170
35 #define IDM_FULLSCREEN  0x0180
36 #define IDM_PASTE     0x0190
37
38 #define IDM_SESSLGP   0x0250           /* log type printable */
39 #define IDM_SESSLGA   0x0260           /* log type all chars */
40 #define IDM_SESSLGE   0x0270           /* log end */
41
42 #define IDM_SPECIAL_MIN 0x0400
43 #define IDM_SPECIAL_MAX 0x0800
44
45 #define IDM_SAVED_MIN 0x1000
46 #define IDM_SAVED_MAX 0x2000
47
48 #define WM_IGNORE_CLIP (WM_XUSER + 2)
49 #define WM_FULLSCR_ON_MAX (WM_XUSER + 3)
50 #define WM_AGENT_CALLBACK (WM_XUSER + 4)
51
52 /* Needed for Chinese support and apparently not always defined. */
53 #ifndef VK_PROCESSKEY
54 #define VK_PROCESSKEY 0xE5
55 #endif
56
57 /* Mouse wheel support. */
58 #ifndef WM_MOUSEWHEEL
59 #define WM_MOUSEWHEEL 0x020A           /* not defined in earlier SDKs */
60 #endif
61 #ifndef WHEEL_DELTA
62 #define WHEEL_DELTA 120
63 #endif
64
65 static Mouse_Button translate_button(Mouse_Button button);
66 static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
67 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
68                         unsigned char *output);
69 static void cfgtopalette(void);
70 static void systopalette(void);
71 static void init_palette(void);
72 static void init_fonts(int, int);
73 static void another_font(int);
74 static void deinit_fonts(void);
75 static void set_input_locale(HKL);
76
77 static int is_full_screen(void);
78 static void make_full_screen(void);
79 static void clear_full_screen(void);
80 static void flip_full_screen(void);
81
82 /* Window layout information */
83 static void reset_window(int);
84 static int extra_width, extra_height;
85 static int font_width, font_height, font_dualwidth;
86 static int offset_width, offset_height;
87 static int was_zoomed = 0;
88 static int prev_rows, prev_cols;
89   
90 static int pending_netevent = 0;
91 static WPARAM pend_netevent_wParam = 0;
92 static LPARAM pend_netevent_lParam = 0;
93 static void enact_pending_netevent(void);
94 static void flash_window(int mode);
95 static void sys_cursor_update(void);
96 static int is_shift_pressed(void);
97 static int get_fullscreen_rect(RECT * ss);
98
99 static time_t last_movement = 0;
100
101 static int caret_x = -1, caret_y = -1;
102
103 static int kbd_codepage;
104
105 static void *ldisc;
106 static Backend *back;
107 static void *backhandle;
108
109 static struct unicode_data ucsdata;
110 static int session_closed;
111
112 static const struct telnet_special *specials;
113
114 static struct {
115     HMENU menu;
116     int specials_submenu_pos;
117 } popup_menus[2];
118 enum { SYSMENU, CTXMENU };
119
120 Config cfg;                            /* exported to windlg.c */
121
122 extern struct sesslist sesslist;       /* imported from windlg.c */
123
124 struct agent_callback {
125     void (*callback)(void *, void *, int);
126     void *callback_ctx;
127     void *data;
128     int len;
129 };
130
131 #define FONT_NORMAL 0
132 #define FONT_BOLD 1
133 #define FONT_UNDERLINE 2
134 #define FONT_BOLDUND 3
135 #define FONT_WIDE       0x04
136 #define FONT_HIGH       0x08
137 #define FONT_NARROW     0x10
138
139 #define FONT_OEM        0x20
140 #define FONT_OEMBOLD    0x21
141 #define FONT_OEMUND     0x22
142 #define FONT_OEMBOLDUND 0x23
143
144 #define FONT_MAXNO      0x2F
145 #define FONT_SHIFT      5
146 static HFONT fonts[FONT_MAXNO];
147 static LOGFONT lfont;
148 static int fontflag[FONT_MAXNO];
149 static enum {
150     BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT
151 } bold_mode;
152 static enum {
153     UND_LINE, UND_FONT
154 } und_mode;
155 static int descent;
156
157 #define NCOLOURS 24
158 static COLORREF colours[NCOLOURS];
159 static HPALETTE pal;
160 static LPLOGPALETTE logpal;
161 static RGBTRIPLE defpal[NCOLOURS];
162
163 static HWND hwnd;
164
165 static HBITMAP caretbm;
166
167 static int dbltime, lasttime, lastact;
168 static Mouse_Button lastbtn;
169
170 /* this allows xterm-style mouse handling. */
171 static int send_raw_mouse = 0;
172 static int wheel_accumulator = 0;
173
174 static char *window_name, *icon_name;
175
176 static int compose_state = 0;
177
178 static UINT wm_mousewheel = WM_MOUSEWHEEL;
179
180 /* Dummy routine, only required in plink. */
181 void ldisc_update(void *frontend, int echo, int edit)
182 {
183 }
184
185 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
186 {
187     WNDCLASS wndclass;
188     MSG msg;
189     int guess_width, guess_height;
190
191     hinst = inst;
192     flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
193
194     sk_init();
195
196     InitCommonControls();
197
198     /* Ensure a Maximize setting in Explorer doesn't maximise the
199      * config box. */
200     defuse_showwindow();
201
202     if (!init_winver())
203     {
204         char *str = dupprintf("%s Fatal Error", appname);
205         MessageBox(NULL, "Windows refuses to report a version",
206                    str, MB_OK | MB_ICONEXCLAMATION);
207         sfree(str);
208         return 1;
209     }
210
211     /*
212      * If we're running a version of Windows that doesn't support
213      * WM_MOUSEWHEEL, find out what message number we should be
214      * using instead.
215      */
216     if (osVersion.dwMajorVersion < 4 ||
217         (osVersion.dwMajorVersion == 4 && 
218          osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
219         wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
220
221     /*
222      * See if we can find our Help file.
223      */
224     {
225         char b[2048], *p, *q, *r;
226         FILE *fp;
227         GetModuleFileName(NULL, b, sizeof(b) - 1);
228         r = b;
229         p = strrchr(b, '\\');
230         if (p && p >= r) r = p+1;
231         q = strrchr(b, ':');
232         if (q && q >= r) r = q+1;
233         strcpy(r, "putty.hlp");
234         if ( (fp = fopen(b, "r")) != NULL) {
235             help_path = dupstr(b);
236             fclose(fp);
237         } else
238             help_path = NULL;
239         strcpy(r, "putty.cnt");
240         if ( (fp = fopen(b, "r")) != NULL) {
241             help_has_contents = TRUE;
242             fclose(fp);
243         } else
244             help_has_contents = FALSE;
245     }
246
247     /*
248      * Process the command line.
249      */
250     {
251         char *p;
252         int got_host = 0;
253
254         default_protocol = be_default_protocol;
255         /* Find the appropriate default port. */
256         {
257             int i;
258             default_port = 0; /* illegal */
259             for (i = 0; backends[i].backend != NULL; i++)
260                 if (backends[i].protocol == default_protocol) {
261                     default_port = backends[i].backend->default_port;
262                     break;
263                 }
264         }
265         cfg.logtype = LGTYP_NONE;
266
267         do_defaults(NULL, &cfg);
268
269         p = cmdline;
270
271         /*
272          * Process a couple of command-line options which are more
273          * easily dealt with before the line is broken up into
274          * words. These are the soon-to-be-defunct @sessionname and
275          * the internal-use-only &sharedmemoryhandle, neither of
276          * which are combined with anything else.
277          */
278         while (*p && isspace(*p))
279             p++;
280         if (*p == '@') {
281             int i = strlen(p);
282             while (i > 1 && isspace(p[i - 1]))
283                 i--;
284             p[i] = '\0';
285             do_defaults(p + 1, &cfg);
286             if (!*cfg.host && !do_config()) {
287                 cleanup_exit(0);
288             }
289         } else if (*p == '&') {
290             /*
291              * An initial & means we've been given a command line
292              * containing the hex value of a HANDLE for a file
293              * mapping object, which we must then extract as a
294              * config.
295              */
296             HANDLE filemap;
297             Config *cp;
298             if (sscanf(p + 1, "%p", &filemap) == 1 &&
299                 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
300                                     0, 0, sizeof(Config))) != NULL) {
301                 cfg = *cp;
302                 UnmapViewOfFile(cp);
303                 CloseHandle(filemap);
304             } else if (!do_config()) {
305                 cleanup_exit(0);
306             }
307         } else {
308             /*
309              * Otherwise, break up the command line and deal with
310              * it sensibly.
311              */
312             int argc, i;
313             char **argv;
314             
315             split_into_argv(cmdline, &argc, &argv, NULL);
316
317             for (i = 0; i < argc; i++) {
318                 char *p = argv[i];
319                 int ret;
320
321                 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
322                                             1, &cfg);
323                 if (ret == -2) {
324                     cmdline_error("option \"%s\" requires an argument", p);
325                 } else if (ret == 2) {
326                     i++;               /* skip next argument */
327                 } else if (ret == 1) {
328                     continue;          /* nothing further needs doing */
329                 } else if (!strcmp(p, "-cleanup")) {
330                     /*
331                      * `putty -cleanup'. Remove all registry
332                      * entries associated with PuTTY, and also find
333                      * and delete the random seed file.
334                      */
335                     char *s1, *s2;
336                     s1 = dupprintf("This procedure will remove ALL Registry\n"
337                                    "entries associated with %s, and will\n"
338                                    "also remove the random seed file.\n"
339                                    "\n"
340                                    "THIS PROCESS WILL DESTROY YOUR SAVED\n"
341                                    "SESSIONS. Are you really sure you want\n"
342                                    "to continue?", appname);
343                     s2 = dupprintf("%s Warning", appname);
344                     if (MessageBox(NULL, s1, s2,
345                                    MB_YESNO | MB_ICONWARNING) == IDYES) {
346                         cleanup_all();
347                     }
348                     sfree(s1);
349                     sfree(s2);
350                     exit(0);
351                 } else if (*p != '-') {
352                     char *q = p;
353                     if (got_host) {
354                         /*
355                          * If we already have a host name, treat
356                          * this argument as a port number. NB we
357                          * have to treat this as a saved -P
358                          * argument, so that it will be deferred
359                          * until it's a good moment to run it.
360                          */
361                         int ret = cmdline_process_param("-P", p, 1, &cfg);
362                         assert(ret == 2);
363                     } else if (!strncmp(q, "telnet:", 7)) {
364                         /*
365                          * If the hostname starts with "telnet:",
366                          * set the protocol to Telnet and process
367                          * the string as a Telnet URL.
368                          */
369                         char c;
370
371                         q += 7;
372                         if (q[0] == '/' && q[1] == '/')
373                             q += 2;
374                         cfg.protocol = PROT_TELNET;
375                         p = q;
376                         while (*p && *p != ':' && *p != '/')
377                             p++;
378                         c = *p;
379                         if (*p)
380                             *p++ = '\0';
381                         if (c == ':')
382                             cfg.port = atoi(p);
383                         else
384                             cfg.port = -1;
385                         strncpy(cfg.host, q, sizeof(cfg.host) - 1);
386                         cfg.host[sizeof(cfg.host) - 1] = '\0';
387                         got_host = 1;
388                     } else {
389                         /*
390                          * Otherwise, treat this argument as a host
391                          * name.
392                          */
393                         while (*p && !isspace(*p))
394                             p++;
395                         if (*p)
396                             *p++ = '\0';
397                         strncpy(cfg.host, q, sizeof(cfg.host) - 1);
398                         cfg.host[sizeof(cfg.host) - 1] = '\0';
399                         got_host = 1;
400                     }
401                 } else {
402                     cmdline_error("unknown option \"%s\"", p);
403                 }
404             }
405         }
406
407         cmdline_run_saved(&cfg);
408
409         if (!*cfg.host && !do_config()) {
410             cleanup_exit(0);
411         }
412
413         /*
414          * Trim leading whitespace off the hostname if it's there.
415          */
416         {
417             int space = strspn(cfg.host, " \t");
418             memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
419         }
420
421         /* See if host is of the form user@host */
422         if (cfg.host[0] != '\0') {
423             char *atsign = strchr(cfg.host, '@');
424             /* Make sure we're not overflowing the user field */
425             if (atsign) {
426                 if (atsign - cfg.host < sizeof cfg.username) {
427                     strncpy(cfg.username, cfg.host, atsign - cfg.host);
428                     cfg.username[atsign - cfg.host] = '\0';
429                 }
430                 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
431             }
432         }
433
434         /*
435          * Trim a colon suffix off the hostname if it's there.
436          */
437         cfg.host[strcspn(cfg.host, ":")] = '\0';
438
439         /*
440          * Remove any remaining whitespace from the hostname.
441          */
442         {
443             int p1 = 0, p2 = 0;
444             while (cfg.host[p2] != '\0') {
445                 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
446                     cfg.host[p1] = cfg.host[p2];
447                     p1++;
448                 }
449                 p2++;
450             }
451             cfg.host[p1] = '\0';
452         }
453     }
454
455     /*
456      * Select protocol. This is farmed out into a table in a
457      * separate file to enable an ssh-free variant.
458      */
459     {
460         int i;
461         back = NULL;
462         for (i = 0; backends[i].backend != NULL; i++)
463             if (backends[i].protocol == cfg.protocol) {
464                 back = backends[i].backend;
465                 break;
466             }
467         if (back == NULL) {
468             char *str = dupprintf("%s Internal Error", appname);
469             MessageBox(NULL, "Unsupported protocol number found",
470                        str, MB_OK | MB_ICONEXCLAMATION);
471             sfree(str);
472             cleanup_exit(1);
473         }
474     }
475
476     /* Check for invalid Port number (i.e. zero) */
477     if (cfg.port == 0) {
478         char *str = dupprintf("%s Internal Error", appname);
479         MessageBox(NULL, "Invalid Port Number",
480                    str, MB_OK | MB_ICONEXCLAMATION);
481         sfree(str);
482         cleanup_exit(1);
483     }
484
485     if (!prev) {
486         wndclass.style = 0;
487         wndclass.lpfnWndProc = WndProc;
488         wndclass.cbClsExtra = 0;
489         wndclass.cbWndExtra = 0;
490         wndclass.hInstance = inst;
491         wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
492         wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
493         wndclass.hbrBackground = NULL;
494         wndclass.lpszMenuName = NULL;
495         wndclass.lpszClassName = appname;
496
497         RegisterClass(&wndclass);
498     }
499
500     hwnd = NULL;
501
502     memset(&ucsdata, 0, sizeof(ucsdata));
503
504     term = term_init(&cfg, &ucsdata, NULL);
505     logctx = log_init(NULL, &cfg);
506     term_provide_logctx(term, logctx);
507
508     cfgtopalette();
509
510     /*
511      * Guess some defaults for the window size. This all gets
512      * updated later, so we don't really care too much. However, we
513      * do want the font width/height guesses to correspond to a
514      * large font rather than a small one...
515      */
516
517     font_width = 10;
518     font_height = 20;
519     extra_width = 25;
520     extra_height = 28;
521     term_size(term, cfg.height, cfg.width, cfg.savelines);
522     guess_width = extra_width + font_width * term->cols;
523     guess_height = extra_height + font_height * term->rows;
524     {
525         RECT r;
526                 get_fullscreen_rect(&r);
527         if (guess_width > r.right - r.left)
528             guess_width = r.right - r.left;
529         if (guess_height > r.bottom - r.top)
530             guess_height = r.bottom - r.top;
531     }
532
533     {
534         int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
535         int exwinmode = 0;
536         if (!cfg.scrollbar)
537             winmode &= ~(WS_VSCROLL);
538         if (cfg.resize_action == RESIZE_DISABLED)
539             winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
540         if (cfg.alwaysontop)
541             exwinmode |= WS_EX_TOPMOST;
542         if (cfg.sunken_edge)
543             exwinmode |= WS_EX_CLIENTEDGE;
544         hwnd = CreateWindowEx(exwinmode, appname, appname,
545                               winmode, CW_USEDEFAULT, CW_USEDEFAULT,
546                               guess_width, guess_height,
547                               NULL, NULL, inst, NULL);
548     }
549
550     /*
551      * Initialise the fonts, simultaneously correcting the guesses
552      * for font_{width,height}.
553      */
554     init_fonts(0,0);
555
556     /*
557      * Correct the guesses for extra_{width,height}.
558      */
559     {
560         RECT cr, wr;
561         GetWindowRect(hwnd, &wr);
562         GetClientRect(hwnd, &cr);
563         offset_width = offset_height = cfg.window_border;
564         extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
565         extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
566     }
567
568     /*
569      * Resize the window, now we know what size we _really_ want it
570      * to be.
571      */
572     guess_width = extra_width + font_width * term->cols;
573     guess_height = extra_height + font_height * term->rows;
574     SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
575                  SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
576
577     /*
578      * Set up a caret bitmap, with no content.
579      */
580     {
581         char *bits;
582         int size = (font_width + 15) / 16 * 2 * font_height;
583         bits = snewn(size, char);
584         memset(bits, 0, size);
585         caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
586         sfree(bits);
587     }
588     CreateCaret(hwnd, caretbm, font_width, font_height);
589
590     /*
591      * Initialise the scroll bar.
592      */
593     {
594         SCROLLINFO si;
595
596         si.cbSize = sizeof(si);
597         si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
598         si.nMin = 0;
599         si.nMax = term->rows - 1;
600         si.nPage = term->rows;
601         si.nPos = 0;
602         SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
603     }
604
605     /*
606      * Start up the telnet connection.
607      */
608     {
609         const char *error;
610         char msg[1024], *title;
611         char *realhost;
612
613         error = back->init(NULL, &backhandle, &cfg,
614                            cfg.host, cfg.port, &realhost, cfg.tcp_nodelay,
615                            cfg.tcp_keepalives);
616         back->provide_logctx(backhandle, logctx);
617         if (error) {
618             char *str = dupprintf("%s Error", appname);
619             sprintf(msg, "Unable to open connection to\n"
620                     "%.800s\n" "%s", cfg.host, error);
621             MessageBox(NULL, msg, str, MB_ICONERROR | MB_OK);
622             sfree(str);
623             return 0;
624         }
625         window_name = icon_name = NULL;
626         if (*cfg.wintitle) {
627             title = cfg.wintitle;
628         } else {
629             sprintf(msg, "%s - %s", realhost, appname);
630             title = msg;
631         }
632         sfree(realhost);
633         set_title(NULL, title);
634         set_icon(NULL, title);
635     }
636
637     /*
638      * Connect the terminal to the backend for resize purposes.
639      */
640     term_provide_resize_fn(term, back->size, backhandle);
641
642     /*
643      * Set up a line discipline.
644      */
645     ldisc = ldisc_create(&cfg, term, back, backhandle, NULL);
646
647     session_closed = FALSE;
648
649     /*
650      * Prepare the mouse handler.
651      */
652     lastact = MA_NOTHING;
653     lastbtn = MBT_NOTHING;
654     dbltime = GetDoubleClickTime();
655
656     /*
657      * Set up the session-control options on the system menu.
658      */
659     {
660         HMENU s, m;
661         int i, j;
662         char *str;
663
664         popup_menus[SYSMENU].menu = GetSystemMenu(hwnd, FALSE);
665         popup_menus[CTXMENU].menu = CreatePopupMenu();
666         AppendMenu(popup_menus[CTXMENU].menu, MF_ENABLED, IDM_PASTE, "&Paste");
667
668         s = CreateMenu();
669         get_sesslist(&sesslist, TRUE);
670         for (i = 1;
671              i < ((sesslist.nsessions < 256) ? sesslist.nsessions : 256);
672              i++)
673             AppendMenu(s, MF_ENABLED, IDM_SAVED_MIN + (16 * i),
674                        sesslist.sessions[i]);
675
676         for (j = 0; j < lenof(popup_menus); j++) {
677             m = popup_menus[j].menu;
678
679             AppendMenu(m, MF_SEPARATOR, 0, 0);
680             popup_menus[j].specials_submenu_pos = GetMenuItemCount(m);
681             AppendMenu(m, MF_ENABLED, IDM_SHOWLOG, "&Event Log");
682             AppendMenu(m, MF_SEPARATOR, 0, 0);
683             AppendMenu(m, MF_ENABLED, IDM_NEWSESS, "Ne&w Session...");
684             AppendMenu(m, MF_ENABLED, IDM_DUPSESS, "&Duplicate Session");
685             AppendMenu(m, MF_POPUP | MF_ENABLED, (UINT) s, "Sa&ved Sessions");
686             AppendMenu(m, MF_ENABLED, IDM_RECONF, "Chan&ge Settings...");
687             AppendMenu(m, MF_SEPARATOR, 0, 0);
688             AppendMenu(m, MF_ENABLED, IDM_COPYALL, "C&opy All to Clipboard");
689             AppendMenu(m, MF_ENABLED, IDM_CLRSB, "C&lear Scrollback");
690             AppendMenu(m, MF_ENABLED, IDM_RESET, "Rese&t Terminal");
691             AppendMenu(m, MF_SEPARATOR, 0, 0);
692             AppendMenu(m, (cfg.resize_action == RESIZE_DISABLED) ?
693                        MF_GRAYED : MF_ENABLED, IDM_FULLSCREEN, "&Full Screen");
694             AppendMenu(m, MF_SEPARATOR, 0, 0);
695             if (help_path)
696                 AppendMenu(m, MF_ENABLED, IDM_HELP, "&Help");
697             str = dupprintf("&About %s", appname);
698             AppendMenu(m, MF_ENABLED, IDM_ABOUT, str);
699             sfree(str);
700         }
701     }
702
703     update_specials_menu(NULL);
704
705     /*
706      * Set up the initial input locale.
707      */
708     set_input_locale(GetKeyboardLayout(0));
709
710     /*
711      * Open the initial log file if there is one.
712      */
713     logfopen(logctx);
714
715     /*
716      * Finally show the window!
717      */
718     ShowWindow(hwnd, show);
719     SetForegroundWindow(hwnd);
720
721     /*
722      * Set the palette up.
723      */
724     pal = NULL;
725     logpal = NULL;
726     init_palette();
727
728     term->has_focus = (GetForegroundWindow() == hwnd);
729     UpdateWindow(hwnd);
730
731     if (GetMessage(&msg, NULL, 0, 0) == 1) {
732         int timer_id = 0, long_timer = 0;
733
734         while (msg.message != WM_QUIT) {
735             /* Sometimes DispatchMessage calls routines that use their own
736              * GetMessage loop, setup this timer so we get some control back.
737              *
738              * Also call term_update() from the timer so that if the host
739              * is sending data flat out we still do redraws.
740              */
741             if (timer_id && long_timer) {
742                 KillTimer(hwnd, timer_id);
743                 long_timer = timer_id = 0;
744             }
745             if (!timer_id)
746                 timer_id = SetTimer(hwnd, 1, 20, NULL);
747             if (!(IsWindow(logbox) && IsDialogMessage(logbox, &msg)))
748                 DispatchMessage(&msg);
749
750             /* Make sure we blink everything that needs it. */
751             term_blink(term, 0);
752
753             /* Send the paste buffer if there's anything to send */
754             term_paste(term);
755
756             /* If there's nothing new in the queue then we can do everything
757              * we've delayed, reading the socket, writing, and repainting
758              * the window.
759              */
760             if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
761                 continue;
762
763             if (pending_netevent) {
764                 enact_pending_netevent();
765
766                 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
767                     continue;
768             }
769
770             /* Okay there is now nothing to do so we make sure the screen is
771              * completely up to date then tell windows to call us in a little 
772              * while.
773              */
774             if (timer_id) {
775                 KillTimer(hwnd, timer_id);
776                 timer_id = 0;
777             }
778             HideCaret(hwnd);
779             if (GetCapture() != hwnd || 
780                 (send_raw_mouse &&
781                  !(cfg.mouse_override && is_shift_pressed())))
782                 term_out(term);
783             term_update(term);
784             ShowCaret(hwnd);
785
786             flash_window(1);           /* maintain */
787
788             /* The messages seem unreliable; especially if we're being tricky */
789             term->has_focus = (GetForegroundWindow() == hwnd);
790
791             if (term->in_vbell)
792                 /* Hmm, term_update didn't want to do an update too soon ... */
793                 timer_id = SetTimer(hwnd, 1, 50, NULL);
794             else if (!term->has_focus)
795                 timer_id = SetTimer(hwnd, 1, 500, NULL);
796             else
797                 timer_id = SetTimer(hwnd, 1, 100, NULL);
798             long_timer = 1;
799
800             /* There's no point rescanning everything in the message queue
801              * so we do an apparently unnecessary wait here
802              */
803             WaitMessage();
804             if (GetMessage(&msg, NULL, 0, 0) != 1)
805                 break;
806         }
807     }
808
809     cleanup_exit(msg.wParam);          /* this doesn't return... */
810     return msg.wParam;                 /* ... but optimiser doesn't know */
811 }
812
813 /*
814  * Clean up and exit.
815  */
816 void cleanup_exit(int code)
817 {
818     /*
819      * Clean up.
820      */
821     deinit_fonts();
822     sfree(logpal);
823     if (pal)
824         DeleteObject(pal);
825     sk_cleanup();
826
827     if (cfg.protocol == PROT_SSH) {
828         random_save_seed();
829 #ifdef MSCRYPTOAPI
830         crypto_wrapup();
831 #endif
832     }
833
834     exit(code);
835 }
836
837 /*
838  * Set up, or shut down, an AsyncSelect. Called from winnet.c.
839  */
840 char *do_select(SOCKET skt, int startup)
841 {
842     int msg, events;
843     if (startup) {
844         msg = WM_NETEVENT;
845         events = (FD_CONNECT | FD_READ | FD_WRITE |
846                   FD_OOB | FD_CLOSE | FD_ACCEPT);
847     } else {
848         msg = events = 0;
849     }
850     if (!hwnd)
851         return "do_select(): internal error (hwnd==NULL)";
852     if (p_WSAAsyncSelect(skt, hwnd, msg, events) == SOCKET_ERROR) {
853         switch (p_WSAGetLastError()) {
854           case WSAENETDOWN:
855             return "Network is down";
856           default:
857             return "WSAAsyncSelect(): unknown error";
858         }
859     }
860     return NULL;
861 }
862
863 /*
864  * Update the Special Commands submenu.
865  */
866 void update_specials_menu(void *frontend)
867 {
868     HMENU m = GetSystemMenu(hwnd, FALSE);
869     int menu_already_exists = (specials != NULL);
870     int i, j;
871
872     specials = back->get_specials(backhandle);
873     if (specials) {
874         HMENU p = CreateMenu();
875         for (i = 0; specials[i].name; i++) {
876             assert(IDM_SPECIAL_MIN + 0x10 * i < IDM_SPECIAL_MAX);
877             if (*specials[i].name)
878                 AppendMenu(p, MF_ENABLED, IDM_SPECIAL_MIN + 0x10 * i,
879                            specials[i].name);
880             else
881                 AppendMenu(p, MF_SEPARATOR, 0, 0);
882         }
883         for (j = 0; j < lenof(popup_menus); j++) {
884             if (menu_already_exists)
885                 DeleteMenu(popup_menus[j].menu,
886                            popup_menus[j].specials_submenu_pos,
887                            MF_BYPOSITION);
888             else
889                 InsertMenu(popup_menus[j].menu,
890                            popup_menus[j].specials_submenu_pos,
891                            MF_BYPOSITION | MF_SEPARATOR, 0, 0);
892             InsertMenu(popup_menus[j].menu,
893                        popup_menus[j].specials_submenu_pos,
894                        MF_BYPOSITION | MF_POPUP | MF_ENABLED,
895                        (UINT) p, "Special Command");
896         }
897     }
898 }
899
900 /*
901  * set or clear the "raw mouse message" mode
902  */
903 void set_raw_mouse_mode(void *frontend, int activate)
904 {
905     activate = activate && !cfg.no_mouse_rep;
906     send_raw_mouse = activate;
907     SetCursor(LoadCursor(NULL, activate ? IDC_ARROW : IDC_IBEAM));
908 }
909
910 /*
911  * Print a message box and close the connection.
912  */
913 void connection_fatal(void *frontend, char *fmt, ...)
914 {
915     va_list ap;
916     char *stuff, morestuff[100];
917
918     va_start(ap, fmt);
919     stuff = dupvprintf(fmt, ap);
920     va_end(ap);
921     sprintf(morestuff, "%.70s Fatal Error", appname);
922     MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
923     sfree(stuff);
924
925     if (cfg.close_on_exit == FORCE_ON)
926         PostQuitMessage(1);
927     else {
928         session_closed = TRUE;
929         sprintf(morestuff, "%.70s (inactive)", appname);
930         set_icon(NULL, morestuff);
931         set_title(NULL, morestuff);
932     }
933 }
934
935 /*
936  * Report an error at the command-line parsing stage.
937  */
938 void cmdline_error(char *fmt, ...)
939 {
940     va_list ap;
941     char *stuff, morestuff[100];
942
943     va_start(ap, fmt);
944     stuff = dupvprintf(fmt, ap);
945     va_end(ap);
946     sprintf(morestuff, "%.70s Command Line Error", appname);
947     MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
948     sfree(stuff);
949     exit(1);
950 }
951
952 /*
953  * Actually do the job requested by a WM_NETEVENT
954  */
955 static void enact_pending_netevent(void)
956 {
957     static int reentering = 0;
958     extern int select_result(WPARAM, LPARAM);
959     int ret;
960
961     if (reentering)
962         return;                        /* don't unpend the pending */
963
964     pending_netevent = FALSE;
965
966     reentering = 1;
967     ret = select_result(pend_netevent_wParam, pend_netevent_lParam);
968     reentering = 0;
969
970     if (ret == 0 && !session_closed) {
971         /* Abnormal exits will already have set session_closed and taken
972          * appropriate action. */
973         if (cfg.close_on_exit == FORCE_ON ||
974             cfg.close_on_exit == AUTO) PostQuitMessage(0);
975         else {
976             char morestuff[100];
977             session_closed = TRUE;
978             sprintf(morestuff, "%.70s (inactive)", appname);
979             set_icon(NULL, morestuff);
980             set_title(NULL, morestuff);
981             MessageBox(hwnd, "Connection closed by remote host",
982                        appname, MB_OK | MB_ICONINFORMATION);
983         }
984     }
985 }
986
987 /*
988  * Copy the colour palette from the configuration data into defpal.
989  * This is non-trivial because the colour indices are different.
990  */
991 static void cfgtopalette(void)
992 {
993     int i;
994     static const int ww[] = {
995         6, 7, 8, 9, 10, 11, 12, 13,
996         14, 15, 16, 17, 18, 19, 20, 21,
997         0, 1, 2, 3, 4, 4, 5, 5
998     };
999
1000     for (i = 0; i < 24; i++) {
1001         int w = ww[i];
1002         defpal[i].rgbtRed = cfg.colours[w][0];
1003         defpal[i].rgbtGreen = cfg.colours[w][1];
1004         defpal[i].rgbtBlue = cfg.colours[w][2];
1005     }
1006
1007     /* Override with system colours if appropriate */
1008     if (cfg.system_colour)
1009         systopalette();
1010 }
1011
1012 /*
1013  * Override bit of defpal with colours from the system.
1014  * (NB that this takes a copy the system colours at the time this is called,
1015  * so subsequent colour scheme changes don't take effect. To fix that we'd
1016  * probably want to be using GetSysColorBrush() and the like.)
1017  */
1018 static void systopalette(void)
1019 {
1020     int i;
1021     static const struct { int nIndex; int norm; int bold; } or[] =
1022     {
1023         { COLOR_WINDOWTEXT,     16, 17 }, /* Default Foreground */
1024         { COLOR_WINDOW,         18, 19 }, /* Default Background */
1025         { COLOR_HIGHLIGHTTEXT,  20, 21 }, /* Cursor Text */
1026         { COLOR_HIGHLIGHT,      22, 23 }, /* Cursor Colour */
1027     };
1028
1029     for (i = 0; i < (sizeof(or)/sizeof(or[0])); i++) {
1030         COLORREF colour = GetSysColor(or[i].nIndex);
1031         defpal[or[i].norm].rgbtRed =
1032            defpal[or[i].bold].rgbtRed = GetRValue(colour);
1033         defpal[or[i].norm].rgbtGreen =
1034            defpal[or[i].bold].rgbtGreen = GetGValue(colour);
1035         defpal[or[i].norm].rgbtBlue =
1036            defpal[or[i].bold].rgbtBlue = GetBValue(colour);
1037     }
1038 }
1039
1040 /*
1041  * Set up the colour palette.
1042  */
1043 static void init_palette(void)
1044 {
1045     int i;
1046     HDC hdc = GetDC(hwnd);
1047     if (hdc) {
1048         if (cfg.try_palette && GetDeviceCaps(hdc, RASTERCAPS) & RC_PALETTE) {
1049             /*
1050              * This is a genuine case where we must use smalloc
1051              * because the snew macros can't cope.
1052              */
1053             logpal = smalloc(sizeof(*logpal)
1054                              - sizeof(logpal->palPalEntry)
1055                              + NCOLOURS * sizeof(PALETTEENTRY));
1056             logpal->palVersion = 0x300;
1057             logpal->palNumEntries = NCOLOURS;
1058             for (i = 0; i < NCOLOURS; i++) {
1059                 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1060                 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1061                 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1062                 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
1063             }
1064             pal = CreatePalette(logpal);
1065             if (pal) {
1066                 SelectPalette(hdc, pal, FALSE);
1067                 RealizePalette(hdc);
1068                 SelectPalette(hdc, GetStockObject(DEFAULT_PALETTE), FALSE);
1069             }
1070         }
1071         ReleaseDC(hwnd, hdc);
1072     }
1073     if (pal)
1074         for (i = 0; i < NCOLOURS; i++)
1075             colours[i] = PALETTERGB(defpal[i].rgbtRed,
1076                                     defpal[i].rgbtGreen,
1077                                     defpal[i].rgbtBlue);
1078     else
1079         for (i = 0; i < NCOLOURS; i++)
1080             colours[i] = RGB(defpal[i].rgbtRed,
1081                              defpal[i].rgbtGreen, defpal[i].rgbtBlue);
1082 }
1083
1084 /*
1085  * Initialise all the fonts we will need initially. There may be as many as
1086  * three or as few as one.  The other (poentially) twentyone fonts are done
1087  * if/when they are needed.
1088  *
1089  * We also:
1090  *
1091  * - check the font width and height, correcting our guesses if
1092  *   necessary.
1093  *
1094  * - verify that the bold font is the same width as the ordinary
1095  *   one, and engage shadow bolding if not.
1096  * 
1097  * - verify that the underlined font is the same width as the
1098  *   ordinary one (manual underlining by means of line drawing can
1099  *   be done in a pinch).
1100  */
1101 static void init_fonts(int pick_width, int pick_height)
1102 {
1103     TEXTMETRIC tm;
1104     CPINFO cpinfo;
1105     int fontsize[3];
1106     int i;
1107     HDC hdc;
1108     int fw_dontcare, fw_bold;
1109
1110     for (i = 0; i < FONT_MAXNO; i++)
1111         fonts[i] = NULL;
1112
1113     bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
1114     und_mode = UND_FONT;
1115
1116     if (cfg.font.isbold) {
1117         fw_dontcare = FW_BOLD;
1118         fw_bold = FW_HEAVY;
1119     } else {
1120         fw_dontcare = FW_DONTCARE;
1121         fw_bold = FW_BOLD;
1122     }
1123
1124     hdc = GetDC(hwnd);
1125
1126     if (pick_height)
1127         font_height = pick_height;
1128     else {
1129         font_height = cfg.font.height;
1130         if (font_height > 0) {
1131             font_height =
1132                 -MulDiv(font_height, GetDeviceCaps(hdc, LOGPIXELSY), 72);
1133         }
1134     }
1135     font_width = pick_width;
1136
1137 #define f(i,c,w,u) \
1138     fonts[i] = CreateFont (font_height, font_width, 0, 0, w, FALSE, u, FALSE, \
1139                            c, OUT_DEFAULT_PRECIS, \
1140                            CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, \
1141                            FIXED_PITCH | FF_DONTCARE, cfg.font.name)
1142
1143     f(FONT_NORMAL, cfg.font.charset, fw_dontcare, FALSE);
1144
1145     lfont.lfHeight = font_height;
1146     lfont.lfWidth = font_width;
1147     lfont.lfEscapement = 0;
1148     lfont.lfOrientation  = 0;
1149     lfont.lfWeight  = fw_dontcare;
1150     lfont.lfItalic = FALSE;
1151     lfont.lfUnderline = FALSE;
1152     lfont.lfStrikeOut = FALSE;
1153     lfont.lfCharSet = cfg.font.charset;
1154     lfont.lfOutPrecision = OUT_DEFAULT_PRECIS;
1155     lfont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
1156     lfont.lfQuality = DEFAULT_QUALITY;
1157     lfont.lfPitchAndFamily = FIXED_PITCH | FF_DONTCARE;
1158     strncpy(lfont.lfFaceName, cfg.font.name, LF_FACESIZE);
1159
1160     SelectObject(hdc, fonts[FONT_NORMAL]);
1161     GetTextMetrics(hdc, &tm);
1162
1163     if (pick_width == 0 || pick_height == 0) {
1164         font_height = tm.tmHeight;
1165         font_width = tm.tmAveCharWidth;
1166     }
1167     font_dualwidth = (tm.tmAveCharWidth != tm.tmMaxCharWidth);
1168
1169 #ifdef RDB_DEBUG_PATCH
1170     debug(23, "Primary font H=%d, AW=%d, MW=%d",
1171             tm.tmHeight, tm.tmAveCharWidth, tm.tmMaxCharWidth);
1172 #endif
1173
1174     {
1175         CHARSETINFO info;
1176         DWORD cset = tm.tmCharSet;
1177         memset(&info, 0xFF, sizeof(info));
1178
1179         /* !!! Yes the next line is right */
1180         if (cset == OEM_CHARSET)
1181             ucsdata.font_codepage = GetOEMCP();
1182         else
1183             if (TranslateCharsetInfo ((DWORD *) cset, &info, TCI_SRCCHARSET))
1184                 ucsdata.font_codepage = info.ciACP;
1185         else
1186             ucsdata.font_codepage = -1;
1187
1188         GetCPInfo(ucsdata.font_codepage, &cpinfo);
1189         ucsdata.dbcs_screenfont = (cpinfo.MaxCharSize > 1);
1190     }
1191
1192     f(FONT_UNDERLINE, cfg.font.charset, fw_dontcare, TRUE);
1193
1194     /*
1195      * Some fonts, e.g. 9-pt Courier, draw their underlines
1196      * outside their character cell. We successfully prevent
1197      * screen corruption by clipping the text output, but then
1198      * we lose the underline completely. Here we try to work
1199      * out whether this is such a font, and if it is, we set a
1200      * flag that causes underlines to be drawn by hand.
1201      *
1202      * Having tried other more sophisticated approaches (such
1203      * as examining the TEXTMETRIC structure or requesting the
1204      * height of a string), I think we'll do this the brute
1205      * force way: we create a small bitmap, draw an underlined
1206      * space on it, and test to see whether any pixels are
1207      * foreground-coloured. (Since we expect the underline to
1208      * go all the way across the character cell, we only search
1209      * down a single column of the bitmap, half way across.)
1210      */
1211     {
1212         HDC und_dc;
1213         HBITMAP und_bm, und_oldbm;
1214         int i, gotit;
1215         COLORREF c;
1216
1217         und_dc = CreateCompatibleDC(hdc);
1218         und_bm = CreateCompatibleBitmap(hdc, font_width, font_height);
1219         und_oldbm = SelectObject(und_dc, und_bm);
1220         SelectObject(und_dc, fonts[FONT_UNDERLINE]);
1221         SetTextAlign(und_dc, TA_TOP | TA_LEFT | TA_NOUPDATECP);
1222         SetTextColor(und_dc, RGB(255, 255, 255));
1223         SetBkColor(und_dc, RGB(0, 0, 0));
1224         SetBkMode(und_dc, OPAQUE);
1225         ExtTextOut(und_dc, 0, 0, ETO_OPAQUE, NULL, " ", 1, NULL);
1226         gotit = FALSE;
1227         for (i = 0; i < font_height; i++) {
1228             c = GetPixel(und_dc, font_width / 2, i);
1229             if (c != RGB(0, 0, 0))
1230                 gotit = TRUE;
1231         }
1232         SelectObject(und_dc, und_oldbm);
1233         DeleteObject(und_bm);
1234         DeleteDC(und_dc);
1235         if (!gotit) {
1236             und_mode = UND_LINE;
1237             DeleteObject(fonts[FONT_UNDERLINE]);
1238             fonts[FONT_UNDERLINE] = 0;
1239         }
1240     }
1241
1242     if (bold_mode == BOLD_FONT) {
1243         f(FONT_BOLD, cfg.font.charset, fw_bold, FALSE);
1244     }
1245 #undef f
1246
1247     descent = tm.tmAscent + 1;
1248     if (descent >= font_height)
1249         descent = font_height - 1;
1250
1251     for (i = 0; i < 3; i++) {
1252         if (fonts[i]) {
1253             if (SelectObject(hdc, fonts[i]) && GetTextMetrics(hdc, &tm))
1254                 fontsize[i] = tm.tmAveCharWidth + 256 * tm.tmHeight;
1255             else
1256                 fontsize[i] = -i;
1257         } else
1258             fontsize[i] = -i;
1259     }
1260
1261     ReleaseDC(hwnd, hdc);
1262
1263     if (fontsize[FONT_UNDERLINE] != fontsize[FONT_NORMAL]) {
1264         und_mode = UND_LINE;
1265         DeleteObject(fonts[FONT_UNDERLINE]);
1266         fonts[FONT_UNDERLINE] = 0;
1267     }
1268
1269     if (bold_mode == BOLD_FONT &&
1270         fontsize[FONT_BOLD] != fontsize[FONT_NORMAL]) {
1271         bold_mode = BOLD_SHADOW;
1272         DeleteObject(fonts[FONT_BOLD]);
1273         fonts[FONT_BOLD] = 0;
1274     }
1275     fontflag[0] = fontflag[1] = fontflag[2] = 1;
1276
1277     init_ucs(&cfg, &ucsdata);
1278 }
1279
1280 static void another_font(int fontno)
1281 {
1282     int basefont;
1283     int fw_dontcare, fw_bold;
1284     int c, u, w, x;
1285     char *s;
1286
1287     if (fontno < 0 || fontno >= FONT_MAXNO || fontflag[fontno])
1288         return;
1289
1290     basefont = (fontno & ~(FONT_BOLDUND));
1291     if (basefont != fontno && !fontflag[basefont])
1292         another_font(basefont);
1293
1294     if (cfg.font.isbold) {
1295         fw_dontcare = FW_BOLD;
1296         fw_bold = FW_HEAVY;
1297     } else {
1298         fw_dontcare = FW_DONTCARE;
1299         fw_bold = FW_BOLD;
1300     }
1301
1302     c = cfg.font.charset;
1303     w = fw_dontcare;
1304     u = FALSE;
1305     s = cfg.font.name;
1306     x = font_width;
1307
1308     if (fontno & FONT_WIDE)
1309         x *= 2;
1310     if (fontno & FONT_NARROW)
1311         x = (x+1)/2;
1312     if (fontno & FONT_OEM)
1313         c = OEM_CHARSET;
1314     if (fontno & FONT_BOLD)
1315         w = fw_bold;
1316     if (fontno & FONT_UNDERLINE)
1317         u = TRUE;
1318
1319     fonts[fontno] =
1320         CreateFont(font_height * (1 + !!(fontno & FONT_HIGH)), x, 0, 0, w,
1321                    FALSE, u, FALSE, c, OUT_DEFAULT_PRECIS,
1322                    CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
1323                    FIXED_PITCH | FF_DONTCARE, s);
1324
1325     fontflag[fontno] = 1;
1326 }
1327
1328 static void deinit_fonts(void)
1329 {
1330     int i;
1331     for (i = 0; i < FONT_MAXNO; i++) {
1332         if (fonts[i])
1333             DeleteObject(fonts[i]);
1334         fonts[i] = 0;
1335         fontflag[i] = 0;
1336     }
1337 }
1338
1339 void request_resize(void *frontend, int w, int h)
1340 {
1341     int width, height;
1342
1343     /* If the window is maximized supress resizing attempts */
1344     if (IsZoomed(hwnd)) {
1345         if (cfg.resize_action == RESIZE_TERM)
1346             return;
1347     }
1348
1349     if (cfg.resize_action == RESIZE_DISABLED) return;
1350     if (h == term->rows && w == term->cols) return;
1351
1352     /* Sanity checks ... */
1353     {
1354         static int first_time = 1;
1355         static RECT ss;
1356
1357         switch (first_time) {
1358           case 1:
1359             /* Get the size of the screen */
1360             if (get_fullscreen_rect(&ss))
1361                 /* first_time = 0 */ ;
1362             else {
1363                 first_time = 2;
1364                 break;
1365             }
1366           case 0:
1367             /* Make sure the values are sane */
1368             width = (ss.right - ss.left - extra_width) / 4;
1369             height = (ss.bottom - ss.top - extra_height) / 6;
1370
1371             if (w > width || h > height)
1372                 return;
1373             if (w < 15)
1374                 w = 15;
1375             if (h < 1)
1376                 h = 1;
1377         }
1378     }
1379
1380     term_size(term, h, w, cfg.savelines);
1381
1382     if (cfg.resize_action != RESIZE_FONT && !IsZoomed(hwnd)) {
1383         width = extra_width + font_width * w;
1384         height = extra_height + font_height * h;
1385
1386         SetWindowPos(hwnd, NULL, 0, 0, width, height,
1387             SWP_NOACTIVATE | SWP_NOCOPYBITS |
1388             SWP_NOMOVE | SWP_NOZORDER);
1389     } else
1390         reset_window(0);
1391
1392     InvalidateRect(hwnd, NULL, TRUE);
1393 }
1394
1395 static void reset_window(int reinit) {
1396     /*
1397      * This function decides how to resize or redraw when the 
1398      * user changes something. 
1399      *
1400      * This function doesn't like to change the terminal size but if the
1401      * font size is locked that may be it's only soluion.
1402      */
1403     int win_width, win_height;
1404     RECT cr, wr;
1405
1406 #ifdef RDB_DEBUG_PATCH
1407     debug((27, "reset_window()"));
1408 #endif
1409
1410     /* Current window sizes ... */
1411     GetWindowRect(hwnd, &wr);
1412     GetClientRect(hwnd, &cr);
1413
1414     win_width  = cr.right - cr.left;
1415     win_height = cr.bottom - cr.top;
1416
1417     if (cfg.resize_action == RESIZE_DISABLED) reinit = 2;
1418
1419     /* Are we being forced to reload the fonts ? */
1420     if (reinit>1) {
1421 #ifdef RDB_DEBUG_PATCH
1422         debug((27, "reset_window() -- Forced deinit"));
1423 #endif
1424         deinit_fonts();
1425         init_fonts(0,0);
1426     }
1427
1428     /* Oh, looks like we're minimised */
1429     if (win_width == 0 || win_height == 0)
1430         return;
1431
1432     /* Is the window out of position ? */
1433     if ( !reinit && 
1434             (offset_width != (win_width-font_width*term->cols)/2 ||
1435              offset_height != (win_height-font_height*term->rows)/2) ){
1436         offset_width = (win_width-font_width*term->cols)/2;
1437         offset_height = (win_height-font_height*term->rows)/2;
1438         InvalidateRect(hwnd, NULL, TRUE);
1439 #ifdef RDB_DEBUG_PATCH
1440         debug((27, "reset_window() -> Reposition terminal"));
1441 #endif
1442     }
1443
1444     if (IsZoomed(hwnd)) {
1445         /* We're fullscreen, this means we must not change the size of
1446          * the window so it's the font size or the terminal itself.
1447          */
1448
1449         extra_width = wr.right - wr.left - cr.right + cr.left;
1450         extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
1451
1452         if (cfg.resize_action != RESIZE_TERM) {
1453             if (  font_width != win_width/term->cols || 
1454                   font_height != win_height/term->rows) {
1455                 deinit_fonts();
1456                 init_fonts(win_width/term->cols, win_height/term->rows);
1457                 offset_width = (win_width-font_width*term->cols)/2;
1458                 offset_height = (win_height-font_height*term->rows)/2;
1459                 InvalidateRect(hwnd, NULL, TRUE);
1460 #ifdef RDB_DEBUG_PATCH
1461                 debug((25, "reset_window() -> Z font resize to (%d, %d)",
1462                         font_width, font_height));
1463 #endif
1464             }
1465         } else {
1466             if (  font_width != win_width/term->cols || 
1467                   font_height != win_height/term->rows) {
1468                 /* Our only choice at this point is to change the 
1469                  * size of the terminal; Oh well.
1470                  */
1471                 term_size(term, win_height/font_height, win_width/font_width,
1472                           cfg.savelines);
1473                 offset_width = (win_width-font_width*term->cols)/2;
1474                 offset_height = (win_height-font_height*term->rows)/2;
1475                 InvalidateRect(hwnd, NULL, TRUE);
1476 #ifdef RDB_DEBUG_PATCH
1477                 debug((27, "reset_window() -> Zoomed term_size"));
1478 #endif
1479             }
1480         }
1481         return;
1482     }
1483
1484     /* Hmm, a force re-init means we should ignore the current window
1485      * so we resize to the default font size.
1486      */
1487     if (reinit>0) {
1488 #ifdef RDB_DEBUG_PATCH
1489         debug((27, "reset_window() -> Forced re-init"));
1490 #endif
1491
1492         offset_width = offset_height = cfg.window_border;
1493         extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1494         extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1495
1496         if (win_width != font_width*term->cols + offset_width*2 ||
1497             win_height != font_height*term->rows + offset_height*2) {
1498
1499             /* If this is too large windows will resize it to the maximum
1500              * allowed window size, we will then be back in here and resize
1501              * the font or terminal to fit.
1502              */
1503             SetWindowPos(hwnd, NULL, 0, 0, 
1504                          font_width*term->cols + extra_width, 
1505                          font_height*term->rows + extra_height,
1506                          SWP_NOMOVE | SWP_NOZORDER);
1507         }
1508
1509         InvalidateRect(hwnd, NULL, TRUE);
1510         return;
1511     }
1512
1513     /* Okay the user doesn't want us to change the font so we try the 
1514      * window. But that may be too big for the screen which forces us
1515      * to change the terminal.
1516      */
1517     if ((cfg.resize_action == RESIZE_TERM && reinit<=0) ||
1518         (cfg.resize_action == RESIZE_EITHER && reinit<0) ||
1519             reinit>0) {
1520         offset_width = offset_height = cfg.window_border;
1521         extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
1522         extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
1523
1524         if (win_width != font_width*term->cols + offset_width*2 ||
1525             win_height != font_height*term->rows + offset_height*2) {
1526
1527             static RECT ss;
1528             int width, height;
1529                 
1530                 get_fullscreen_rect(&ss);
1531
1532             width = (ss.right - ss.left - extra_width) / font_width;
1533             height = (ss.bottom - ss.top - extra_height) / font_height;
1534
1535             /* Grrr too big */
1536             if ( term->rows > height || term->cols > width ) {
1537                 if (cfg.resize_action == RESIZE_EITHER) {
1538                     /* Make the font the biggest we can */
1539                     if (term->cols > width)
1540                         font_width = (ss.right - ss.left - extra_width)
1541                             / term->cols;
1542                     if (term->rows > height)
1543                         font_height = (ss.bottom - ss.top - extra_height)
1544                             / term->rows;
1545
1546                     deinit_fonts();
1547                     init_fonts(font_width, font_height);
1548
1549                     width = (ss.right - ss.left - extra_width) / font_width;
1550                     height = (ss.bottom - ss.top - extra_height) / font_height;
1551                 } else {
1552                     if ( height > term->rows ) height = term->rows;
1553                     if ( width > term->cols )  width = term->cols;
1554                     term_size(term, height, width, cfg.savelines);
1555 #ifdef RDB_DEBUG_PATCH
1556                     debug((27, "reset_window() -> term resize to (%d,%d)",
1557                                height, width));
1558 #endif
1559                 }
1560             }
1561             
1562             SetWindowPos(hwnd, NULL, 0, 0, 
1563                          font_width*term->cols + extra_width, 
1564                          font_height*term->rows + extra_height,
1565                          SWP_NOMOVE | SWP_NOZORDER);
1566
1567             InvalidateRect(hwnd, NULL, TRUE);
1568 #ifdef RDB_DEBUG_PATCH
1569             debug((27, "reset_window() -> window resize to (%d,%d)",
1570                         font_width*term->cols + extra_width,
1571                         font_height*term->rows + extra_height));
1572 #endif
1573         }
1574         return;
1575     }
1576
1577     /* We're allowed to or must change the font but do we want to ?  */
1578
1579     if (font_width != (win_width-cfg.window_border*2)/term->cols || 
1580         font_height != (win_height-cfg.window_border*2)/term->rows) {
1581
1582         deinit_fonts();
1583         init_fonts((win_width-cfg.window_border*2)/term->cols, 
1584                    (win_height-cfg.window_border*2)/term->rows);
1585         offset_width = (win_width-font_width*term->cols)/2;
1586         offset_height = (win_height-font_height*term->rows)/2;
1587
1588         extra_width = wr.right - wr.left - cr.right + cr.left +offset_width*2;
1589         extra_height = wr.bottom - wr.top - cr.bottom + cr.top+offset_height*2;
1590
1591         InvalidateRect(hwnd, NULL, TRUE);
1592 #ifdef RDB_DEBUG_PATCH
1593         debug((25, "reset_window() -> font resize to (%d,%d)", 
1594                    font_width, font_height));
1595 #endif
1596     }
1597 }
1598
1599 static void set_input_locale(HKL kl)
1600 {
1601     char lbuf[20];
1602
1603     GetLocaleInfo(LOWORD(kl), LOCALE_IDEFAULTANSICODEPAGE,
1604                   lbuf, sizeof(lbuf));
1605
1606     kbd_codepage = atoi(lbuf);
1607 }
1608
1609 static void click(Mouse_Button b, int x, int y, int shift, int ctrl, int alt)
1610 {
1611     int thistime = GetMessageTime();
1612
1613     if (send_raw_mouse && !(cfg.mouse_override && shift)) {
1614         lastbtn = MBT_NOTHING;
1615         term_mouse(term, b, translate_button(b), MA_CLICK,
1616                    x, y, shift, ctrl, alt);
1617         return;
1618     }
1619
1620     if (lastbtn == b && thistime - lasttime < dbltime) {
1621         lastact = (lastact == MA_CLICK ? MA_2CLK :
1622                    lastact == MA_2CLK ? MA_3CLK :
1623                    lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
1624     } else {
1625         lastbtn = b;
1626         lastact = MA_CLICK;
1627     }
1628     if (lastact != MA_NOTHING)
1629         term_mouse(term, b, translate_button(b), lastact,
1630                    x, y, shift, ctrl, alt);
1631     lasttime = thistime;
1632 }
1633
1634 /*
1635  * Translate a raw mouse button designation (LEFT, MIDDLE, RIGHT)
1636  * into a cooked one (SELECT, EXTEND, PASTE).
1637  */
1638 static Mouse_Button translate_button(Mouse_Button button)
1639 {
1640     if (button == MBT_LEFT)
1641         return MBT_SELECT;
1642     if (button == MBT_MIDDLE)
1643         return cfg.mouse_is_xterm == 1 ? MBT_PASTE : MBT_EXTEND;
1644     if (button == MBT_RIGHT)
1645         return cfg.mouse_is_xterm == 1 ? MBT_EXTEND : MBT_PASTE;
1646     return 0;                          /* shouldn't happen */
1647 }
1648
1649 static void show_mouseptr(int show)
1650 {
1651     static int cursor_visible = 1;
1652     if (!cfg.hide_mouseptr)            /* override if this feature disabled */
1653         show = 1;
1654     if (cursor_visible && !show)
1655         ShowCursor(FALSE);
1656     else if (!cursor_visible && show)
1657         ShowCursor(TRUE);
1658     cursor_visible = show;
1659 }
1660
1661 static int is_alt_pressed(void)
1662 {
1663     BYTE keystate[256];
1664     int r = GetKeyboardState(keystate);
1665     if (!r)
1666         return FALSE;
1667     if (keystate[VK_MENU] & 0x80)
1668         return TRUE;
1669     if (keystate[VK_RMENU] & 0x80)
1670         return TRUE;
1671     return FALSE;
1672 }
1673
1674 static int is_shift_pressed(void)
1675 {
1676     BYTE keystate[256];
1677     int r = GetKeyboardState(keystate);
1678     if (!r)
1679         return FALSE;
1680     if (keystate[VK_SHIFT] & 0x80)
1681         return TRUE;
1682     return FALSE;
1683 }
1684
1685 static int resizing;
1686
1687 static LRESULT CALLBACK WndProc(HWND hwnd, UINT message,
1688                                 WPARAM wParam, LPARAM lParam)
1689 {
1690     HDC hdc;
1691     static int ignore_clip = FALSE;
1692     static int need_backend_resize = FALSE;
1693     static int fullscr_on_max = FALSE;
1694     static UINT last_mousemove = 0;
1695
1696     switch (message) {
1697       case WM_TIMER:
1698         if (pending_netevent)
1699             enact_pending_netevent();
1700         if (GetCapture() != hwnd || 
1701             (send_raw_mouse && !(cfg.mouse_override && is_shift_pressed())))
1702             term_out(term);
1703         noise_regular();
1704         HideCaret(hwnd);
1705         term_update(term);
1706         ShowCaret(hwnd);
1707         if (cfg.ping_interval > 0) {
1708             time_t now;
1709             time(&now);
1710             if (now - last_movement > cfg.ping_interval) {
1711                 back->special(backhandle, TS_PING);
1712                 last_movement = now;
1713             }
1714         }
1715         net_pending_errors();
1716         return 0;
1717       case WM_CREATE:
1718         break;
1719       case WM_CLOSE:
1720         {
1721             char *str;
1722             show_mouseptr(1);
1723             str = dupprintf("%s Exit Confirmation", appname);
1724             if (!cfg.warn_on_close || session_closed ||
1725                 MessageBox(hwnd,
1726                            "Are you sure you want to close this session?",
1727                            str, MB_ICONWARNING | MB_OKCANCEL) == IDOK)
1728                 DestroyWindow(hwnd);
1729             sfree(str);
1730         }
1731         return 0;
1732       case WM_DESTROY:
1733         show_mouseptr(1);
1734         PostQuitMessage(0);
1735         return 0;
1736       case WM_COMMAND:
1737       case WM_SYSCOMMAND:
1738         switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
1739           case IDM_SHOWLOG:
1740             showeventlog(hwnd);
1741             break;
1742           case IDM_NEWSESS:
1743           case IDM_DUPSESS:
1744           case IDM_SAVEDSESS:
1745             {
1746                 char b[2048];
1747                 char c[30], *cl;
1748                 int freecl = FALSE;
1749                 STARTUPINFO si;
1750                 PROCESS_INFORMATION pi;
1751                 HANDLE filemap = NULL;
1752
1753                 if (wParam == IDM_DUPSESS) {
1754                     /*
1755                      * Allocate a file-mapping memory chunk for the
1756                      * config structure.
1757                      */
1758                     SECURITY_ATTRIBUTES sa;
1759                     Config *p;
1760
1761                     sa.nLength = sizeof(sa);
1762                     sa.lpSecurityDescriptor = NULL;
1763                     sa.bInheritHandle = TRUE;
1764                     filemap = CreateFileMapping((HANDLE) 0xFFFFFFFF,
1765                                                 &sa,
1766                                                 PAGE_READWRITE,
1767                                                 0, sizeof(Config), NULL);
1768                     if (filemap) {
1769                         p = (Config *) MapViewOfFile(filemap,
1770                                                      FILE_MAP_WRITE,
1771                                                      0, 0, sizeof(Config));
1772                         if (p) {
1773                             *p = cfg;  /* structure copy */
1774                             UnmapViewOfFile(p);
1775                         }
1776                     }
1777                     sprintf(c, "putty &%p", filemap);
1778                     cl = c;
1779                 } else if (wParam == IDM_SAVEDSESS) {
1780                     if ((lParam - IDM_SAVED_MIN) / 16 < sesslist.nsessions) {
1781                         char *session =
1782                             sesslist.sessions[(lParam - IDM_SAVED_MIN) / 16];
1783                         cl = snewn(16 + strlen(session), char);
1784                                        /* 8, but play safe */
1785                         if (!cl)
1786                             cl = NULL;    
1787                                        /* not a very important failure mode */
1788                         else {
1789                             sprintf(cl, "putty @%s", session);
1790                             freecl = TRUE;
1791                         }
1792                     } else
1793                         break;
1794                 } else
1795                     cl = NULL;
1796
1797                 GetModuleFileName(NULL, b, sizeof(b) - 1);
1798                 si.cb = sizeof(si);
1799                 si.lpReserved = NULL;
1800                 si.lpDesktop = NULL;
1801                 si.lpTitle = NULL;
1802                 si.dwFlags = 0;
1803                 si.cbReserved2 = 0;
1804                 si.lpReserved2 = NULL;
1805                 CreateProcess(b, cl, NULL, NULL, TRUE,
1806                               NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
1807
1808                 if (filemap)
1809                     CloseHandle(filemap);
1810                 if (freecl)
1811                     sfree(cl);
1812             }
1813             break;
1814           case IDM_RECONF:
1815             {
1816                 Config prev_cfg;
1817                 int init_lvl = 1;
1818
1819                 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
1820                 prev_cfg = cfg;
1821
1822                 if (!do_reconfig(hwnd))
1823                     break;
1824
1825                 {
1826                     /* Disable full-screen if resizing forbidden */
1827                     HMENU m = GetSystemMenu (hwnd, FALSE);
1828                     EnableMenuItem(m, IDM_FULLSCREEN, MF_BYCOMMAND | 
1829                                    (cfg.resize_action == RESIZE_DISABLED)
1830                                    ? MF_GRAYED : MF_ENABLED);
1831                     /* Gracefully unzoom if necessary */
1832                     if (IsZoomed(hwnd) &&
1833                         (cfg.resize_action == RESIZE_DISABLED)) {
1834                         ShowWindow(hwnd, SW_RESTORE);
1835                     }
1836                 }
1837
1838                 /* Pass new config data to the logging module */
1839                 log_reconfig(logctx, &cfg);
1840
1841                 sfree(logpal);
1842                 /*
1843                  * Flush the line discipline's edit buffer in the
1844                  * case where local editing has just been disabled.
1845                  */
1846                 ldisc_send(ldisc, NULL, 0, 0);
1847                 if (pal)
1848                     DeleteObject(pal);
1849                 logpal = NULL;
1850                 pal = NULL;
1851                 cfgtopalette();
1852                 init_palette();
1853
1854                 /* Pass new config data to the terminal */
1855                 term_reconfig(term, &cfg);
1856
1857                 /* Pass new config data to the back end */
1858                 back->reconfig(backhandle, &cfg);
1859
1860                 /* Screen size changed ? */
1861                 if (cfg.height != prev_cfg.height ||
1862                     cfg.width != prev_cfg.width ||
1863                     cfg.savelines != prev_cfg.savelines ||
1864                     cfg.resize_action == RESIZE_FONT ||
1865                     (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
1866                     cfg.resize_action == RESIZE_DISABLED)
1867                     term_size(term, cfg.height, cfg.width, cfg.savelines);
1868
1869                 /* Enable or disable the scroll bar, etc */
1870                 {
1871                     LONG nflg, flag = GetWindowLong(hwnd, GWL_STYLE);
1872                     LONG nexflag, exflag =
1873                         GetWindowLong(hwnd, GWL_EXSTYLE);
1874
1875                     nexflag = exflag;
1876                     if (cfg.alwaysontop != prev_cfg.alwaysontop) {
1877                         if (cfg.alwaysontop) {
1878                             nexflag |= WS_EX_TOPMOST;
1879                             SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
1880                                          SWP_NOMOVE | SWP_NOSIZE);
1881                         } else {
1882                             nexflag &= ~(WS_EX_TOPMOST);
1883                             SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
1884                                          SWP_NOMOVE | SWP_NOSIZE);
1885                         }
1886                     }
1887                     if (cfg.sunken_edge)
1888                         nexflag |= WS_EX_CLIENTEDGE;
1889                     else
1890                         nexflag &= ~(WS_EX_CLIENTEDGE);
1891
1892                     nflg = flag;
1893                     if (is_full_screen() ?
1894                         cfg.scrollbar_in_fullscreen : cfg.scrollbar)
1895                         nflg |= WS_VSCROLL;
1896                     else
1897                         nflg &= ~WS_VSCROLL;
1898
1899                     if (cfg.resize_action == RESIZE_DISABLED ||
1900                         is_full_screen())
1901                         nflg &= ~WS_THICKFRAME;
1902                     else
1903                         nflg |= WS_THICKFRAME;
1904
1905                     if (cfg.resize_action == RESIZE_DISABLED)
1906                         nflg &= ~WS_MAXIMIZEBOX;
1907                     else
1908                         nflg |= WS_MAXIMIZEBOX;
1909
1910                     if (nflg != flag || nexflag != exflag) {
1911                         if (nflg != flag)
1912                             SetWindowLong(hwnd, GWL_STYLE, nflg);
1913                         if (nexflag != exflag)
1914                             SetWindowLong(hwnd, GWL_EXSTYLE, nexflag);
1915
1916                         SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
1917                                      SWP_NOACTIVATE | SWP_NOCOPYBITS |
1918                                      SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
1919                                      SWP_FRAMECHANGED);
1920
1921                         init_lvl = 2;
1922                     }
1923                 }
1924
1925                 /* Oops */
1926                 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
1927                     force_normal(hwnd);
1928                     init_lvl = 2;
1929                 }
1930
1931                 set_title(NULL, cfg.wintitle);
1932                 if (IsIconic(hwnd)) {
1933                     SetWindowText(hwnd,
1934                                   cfg.win_name_always ? window_name :
1935                                   icon_name);
1936                 }
1937
1938                 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
1939                     strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
1940                     cfg.font.isbold != prev_cfg.font.isbold ||
1941                     cfg.font.height != prev_cfg.font.height ||
1942                     cfg.font.charset != prev_cfg.font.charset ||
1943                     cfg.vtmode != prev_cfg.vtmode ||
1944                     cfg.bold_colour != prev_cfg.bold_colour ||
1945                     cfg.resize_action == RESIZE_DISABLED ||
1946                     cfg.resize_action == RESIZE_EITHER ||
1947                     (cfg.resize_action != prev_cfg.resize_action))
1948                     init_lvl = 2;
1949
1950                 InvalidateRect(hwnd, NULL, TRUE);
1951                 reset_window(init_lvl);
1952                 net_pending_errors();
1953             }
1954             break;
1955           case IDM_COPYALL:
1956             term_copyall(term);
1957             break;
1958           case IDM_PASTE:
1959             term_do_paste(term);
1960             break;
1961           case IDM_CLRSB:
1962             term_clrsb(term);
1963             break;
1964           case IDM_RESET:
1965             term_pwron(term);
1966             ldisc_send(ldisc, NULL, 0, 0);
1967             break;
1968           case IDM_ABOUT:
1969             showabout(hwnd);
1970             break;
1971           case IDM_HELP:
1972             WinHelp(hwnd, help_path,
1973                     help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
1974             break;
1975           case SC_MOUSEMENU:
1976             /*
1977              * We get this if the System menu has been activated
1978              * using the mouse.
1979              */
1980             show_mouseptr(1);
1981             break;
1982           case SC_KEYMENU:
1983             /*
1984              * We get this if the System menu has been activated
1985              * using the keyboard. This might happen from within
1986              * TranslateKey, in which case it really wants to be
1987              * followed by a `space' character to actually _bring
1988              * the menu up_ rather than just sitting there in
1989              * `ready to appear' state.
1990              */
1991             show_mouseptr(1);          /* make sure pointer is visible */
1992             if( lParam == 0 )
1993                 PostMessage(hwnd, WM_CHAR, ' ', 0);
1994             break;
1995           case IDM_FULLSCREEN:
1996             flip_full_screen();
1997             break;
1998           default:
1999             if (wParam >= IDM_SAVED_MIN && wParam <= IDM_SAVED_MAX) {
2000                 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2001             }
2002             if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2003                 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2004                 int j;
2005                 /*
2006                  * Ensure we haven't been sent a bogus SYSCOMMAND
2007                  * which would cause us to reference invalid memory
2008                  * and crash. Perhaps I'm just too paranoid here.
2009                  */
2010                 for (j = 0; j < i; j++)
2011                     if (!specials || !specials[j].name)
2012                         break;
2013                 if (j == i) {
2014                     back->special(backhandle, specials[i].code);
2015                     net_pending_errors();
2016                 }
2017             }
2018         }
2019         break;
2020
2021 #define X_POS(l) ((int)(short)LOWORD(l))
2022 #define Y_POS(l) ((int)(short)HIWORD(l))
2023
2024 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2025 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2026       case WM_LBUTTONDOWN:
2027       case WM_MBUTTONDOWN:
2028       case WM_RBUTTONDOWN:
2029       case WM_LBUTTONUP:
2030       case WM_MBUTTONUP:
2031       case WM_RBUTTONUP:
2032         if (message == WM_RBUTTONDOWN &&
2033             ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
2034             POINT cursorpos;
2035
2036             show_mouseptr(1);          /* make sure pointer is visible */
2037             GetCursorPos(&cursorpos);
2038             TrackPopupMenu(popup_menus[CTXMENU].menu,
2039                            TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2040                            cursorpos.x, cursorpos.y,
2041                            0, hwnd, NULL);
2042             break;
2043         }
2044         {
2045             int button, press;
2046
2047             switch (message) {
2048               case WM_LBUTTONDOWN:
2049                 button = MBT_LEFT;
2050                 press = 1;
2051                 break;
2052               case WM_MBUTTONDOWN:
2053                 button = MBT_MIDDLE;
2054                 press = 1;
2055                 break;
2056               case WM_RBUTTONDOWN:
2057                 button = MBT_RIGHT;
2058                 press = 1;
2059                 break;
2060               case WM_LBUTTONUP:
2061                 button = MBT_LEFT;
2062                 press = 0;
2063                 break;
2064               case WM_MBUTTONUP:
2065                 button = MBT_MIDDLE;
2066                 press = 0;
2067                 break;
2068               case WM_RBUTTONUP:
2069                 button = MBT_RIGHT;
2070                 press = 0;
2071                 break;
2072               default:
2073                 button = press = 0;    /* shouldn't happen */
2074             }
2075             show_mouseptr(1);
2076             /*
2077              * Special case: in full-screen mode, if the left
2078              * button is clicked in the very top left corner of the
2079              * window, we put up the System menu instead of doing
2080              * selection.
2081              */
2082             {
2083                 char mouse_on_hotspot = 0;
2084                 POINT pt;
2085
2086                 GetCursorPos(&pt);
2087 #ifndef NO_MULTIMON
2088                 {
2089                     HMONITOR mon;
2090                     MONITORINFO mi;
2091
2092                     mon = MonitorFromPoint(pt, MONITOR_DEFAULTTONULL);
2093
2094                     if (mon != NULL) {
2095                         mi.cbSize = sizeof(MONITORINFO);
2096                         GetMonitorInfo(mon, &mi);
2097
2098                         if (mi.rcMonitor.left == pt.x &&
2099                             mi.rcMonitor.top == pt.y) {
2100                             mouse_on_hotspot = 1;
2101                         }
2102                         CloseHandle(mon);
2103                     }
2104                 }
2105 #else
2106                 if (pt.x == 0 && pt.y == 0) {
2107                     mouse_on_hotspot = 1;
2108                 }
2109 #endif
2110                 if (is_full_screen() && press &&
2111                     button == MBT_LEFT && mouse_on_hotspot) {
2112                     SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU,
2113                                 MAKELPARAM(pt.x, pt.y));
2114                     return 0;
2115                 }
2116             }
2117
2118             if (press) {
2119                 click(button,
2120                       TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2121                       wParam & MK_SHIFT, wParam & MK_CONTROL,
2122                       is_alt_pressed());
2123                 SetCapture(hwnd);
2124             } else {
2125                 term_mouse(term, button, translate_button(button), MA_RELEASE,
2126                            TO_CHR_X(X_POS(lParam)),
2127                            TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2128                            wParam & MK_CONTROL, is_alt_pressed());
2129                 ReleaseCapture();
2130             }
2131         }
2132         return 0;
2133       case WM_MOUSEMOVE:
2134         {
2135             /*
2136              * Windows seems to like to occasionally send MOUSEMOVE
2137              * events even if the mouse hasn't moved. Don't unhide
2138              * the mouse pointer in this case.
2139              */
2140             static WPARAM wp = 0;
2141             static LPARAM lp = 0;
2142             if (wParam != wp || lParam != lp ||
2143                 last_mousemove != WM_MOUSEMOVE) {
2144                 show_mouseptr(1);
2145                 wp = wParam; lp = lParam;
2146                 last_mousemove = WM_MOUSEMOVE;
2147             }
2148         }
2149         /*
2150          * Add the mouse position and message time to the random
2151          * number noise.
2152          */
2153         noise_ultralight(lParam);
2154
2155         if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2156             GetCapture() == hwnd) {
2157             Mouse_Button b;
2158             if (wParam & MK_LBUTTON)
2159                 b = MBT_LEFT;
2160             else if (wParam & MK_MBUTTON)
2161                 b = MBT_MIDDLE;
2162             else
2163                 b = MBT_RIGHT;
2164             term_mouse(term, b, translate_button(b), MA_DRAG,
2165                        TO_CHR_X(X_POS(lParam)),
2166                        TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2167                        wParam & MK_CONTROL, is_alt_pressed());
2168         }
2169         return 0;
2170       case WM_NCMOUSEMOVE:
2171         {
2172             static WPARAM wp = 0;
2173             static LPARAM lp = 0;
2174             if (wParam != wp || lParam != lp ||
2175                 last_mousemove != WM_NCMOUSEMOVE) {
2176                 show_mouseptr(1);
2177                 wp = wParam; lp = lParam;
2178                 last_mousemove = WM_NCMOUSEMOVE;
2179             }
2180         }
2181         noise_ultralight(lParam);
2182         break;
2183       case WM_IGNORE_CLIP:
2184         ignore_clip = wParam;          /* don't panic on DESTROYCLIPBOARD */
2185         break;
2186       case WM_DESTROYCLIPBOARD:
2187         if (!ignore_clip)
2188             term_deselect(term);
2189         ignore_clip = FALSE;
2190         return 0;
2191       case WM_PAINT:
2192         {
2193             PAINTSTRUCT p;
2194             HideCaret(hwnd);
2195             hdc = BeginPaint(hwnd, &p);
2196             if (pal) {
2197                 SelectPalette(hdc, pal, TRUE);
2198                 RealizePalette(hdc);
2199             }
2200             term_paint(term, hdc, 
2201                        (p.rcPaint.left-offset_width)/font_width,
2202                        (p.rcPaint.top-offset_height)/font_height,
2203                        (p.rcPaint.right-offset_width-1)/font_width,
2204                        (p.rcPaint.bottom-offset_height-1)/font_height,
2205                        is_alt_pressed());
2206
2207             if (p.fErase ||
2208                 p.rcPaint.left  < offset_width  ||
2209                 p.rcPaint.top   < offset_height ||
2210                 p.rcPaint.right >= offset_width + font_width*term->cols ||
2211                 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2212             {
2213                 HBRUSH fillcolour, oldbrush;
2214                 HPEN   edge, oldpen;
2215                 fillcolour = CreateSolidBrush (
2216                                     colours[(ATTR_DEFBG>>ATTR_BGSHIFT)*2]);
2217                 oldbrush = SelectObject(hdc, fillcolour);
2218                 edge = CreatePen(PS_SOLID, 0, 
2219                                     colours[(ATTR_DEFBG>>ATTR_BGSHIFT)*2]);
2220                 oldpen = SelectObject(hdc, edge);
2221
2222                 /*
2223                  * Jordan Russell reports that this apparently
2224                  * ineffectual IntersectClipRect() call masks a
2225                  * Windows NT/2K bug causing strange display
2226                  * problems when the PuTTY window is taller than
2227                  * the primary monitor. It seems harmless enough...
2228                  */
2229                 IntersectClipRect(hdc,
2230                         p.rcPaint.left, p.rcPaint.top,
2231                         p.rcPaint.right, p.rcPaint.bottom);
2232
2233                 ExcludeClipRect(hdc, 
2234                         offset_width, offset_height,
2235                         offset_width+font_width*term->cols,
2236                         offset_height+font_height*term->rows);
2237
2238                 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top, 
2239                           p.rcPaint.right, p.rcPaint.bottom);
2240
2241                 // SelectClipRgn(hdc, NULL);
2242
2243                 SelectObject(hdc, oldbrush);
2244                 DeleteObject(fillcolour);
2245                 SelectObject(hdc, oldpen);
2246                 DeleteObject(edge);
2247             }
2248             SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2249             SelectObject(hdc, GetStockObject(WHITE_PEN));
2250             EndPaint(hwnd, &p);
2251             ShowCaret(hwnd);
2252         }
2253         return 0;
2254       case WM_NETEVENT:
2255         /* Notice we can get multiple netevents, FD_READ, FD_WRITE etc
2256          * but the only one that's likely to try to overload us is FD_READ.
2257          * This means buffering just one is fine.
2258          */
2259         if (pending_netevent)
2260             enact_pending_netevent();
2261
2262         pending_netevent = TRUE;
2263         pend_netevent_wParam = wParam;
2264         pend_netevent_lParam = lParam;
2265         if (WSAGETSELECTEVENT(lParam) != FD_READ)
2266             enact_pending_netevent();
2267
2268         time(&last_movement);
2269         return 0;
2270       case WM_SETFOCUS:
2271         term->has_focus = TRUE;
2272         CreateCaret(hwnd, caretbm, font_width, font_height);
2273         ShowCaret(hwnd);
2274         flash_window(0);               /* stop */
2275         compose_state = 0;
2276         term_out(term);
2277         term_update(term);
2278         break;
2279       case WM_KILLFOCUS:
2280         show_mouseptr(1);
2281         term->has_focus = FALSE;
2282         DestroyCaret();
2283         caret_x = caret_y = -1;        /* ensure caret is replaced next time */
2284         term_out(term);
2285         term_update(term);
2286         break;
2287       case WM_ENTERSIZEMOVE:
2288 #ifdef RDB_DEBUG_PATCH
2289         debug((27, "WM_ENTERSIZEMOVE"));
2290 #endif
2291         EnableSizeTip(1);
2292         resizing = TRUE;
2293         need_backend_resize = FALSE;
2294         break;
2295       case WM_EXITSIZEMOVE:
2296         EnableSizeTip(0);
2297         resizing = FALSE;
2298 #ifdef RDB_DEBUG_PATCH
2299         debug((27, "WM_EXITSIZEMOVE"));
2300 #endif
2301         if (need_backend_resize) {
2302             term_size(term, cfg.height, cfg.width, cfg.savelines);
2303             InvalidateRect(hwnd, NULL, TRUE);
2304         }
2305         break;
2306       case WM_SIZING:
2307         /*
2308          * This does two jobs:
2309          * 1) Keep the sizetip uptodate
2310          * 2) Make sure the window size is _stepped_ in units of the font size.
2311          */
2312         if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2313             int width, height, w, h, ew, eh;
2314             LPRECT r = (LPRECT) lParam;
2315
2316             if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
2317                     (cfg.height != term->rows || cfg.width != term->cols )) {
2318                 /* 
2319                  * Great! It seems that both the terminal size and the
2320                  * font size have been changed and the user is now dragging.
2321                  * 
2322                  * It will now be difficult to get back to the configured
2323                  * font size!
2324                  *
2325                  * This would be easier but it seems to be too confusing.
2326
2327                 term_size(term, cfg.height, cfg.width, cfg.savelines);
2328                 reset_window(2);
2329                  */
2330                 cfg.height=term->rows; cfg.width=term->cols;
2331
2332                 InvalidateRect(hwnd, NULL, TRUE);
2333                 need_backend_resize = TRUE;
2334             }
2335
2336             width = r->right - r->left - extra_width;
2337             height = r->bottom - r->top - extra_height;
2338             w = (width + font_width / 2) / font_width;
2339             if (w < 1)
2340                 w = 1;
2341             h = (height + font_height / 2) / font_height;
2342             if (h < 1)
2343                 h = 1;
2344             UpdateSizeTip(hwnd, w, h);
2345             ew = width - w * font_width;
2346             eh = height - h * font_height;
2347             if (ew != 0) {
2348                 if (wParam == WMSZ_LEFT ||
2349                     wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2350                     r->left += ew;
2351                 else
2352                     r->right -= ew;
2353             }
2354             if (eh != 0) {
2355                 if (wParam == WMSZ_TOP ||
2356                     wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2357                     r->top += eh;
2358                 else
2359                     r->bottom -= eh;
2360             }
2361             if (ew || eh)
2362                 return 1;
2363             else
2364                 return 0;
2365         } else {
2366             int width, height, w, h, rv = 0;
2367             int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2368             int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2369             LPRECT r = (LPRECT) lParam;
2370
2371             width = r->right - r->left - ex_width;
2372             height = r->bottom - r->top - ex_height;
2373
2374             w = (width + term->cols/2)/term->cols;
2375             h = (height + term->rows/2)/term->rows;
2376             if ( r->right != r->left + w*term->cols + ex_width)
2377                 rv = 1;
2378
2379             if (wParam == WMSZ_LEFT ||
2380                 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2381                 r->left = r->right - w*term->cols - ex_width;
2382             else
2383                 r->right = r->left + w*term->cols + ex_width;
2384
2385             if (r->bottom != r->top + h*term->rows + ex_height)
2386                 rv = 1;
2387
2388             if (wParam == WMSZ_TOP ||
2389                 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2390                 r->top = r->bottom - h*term->rows - ex_height;
2391             else
2392                 r->bottom = r->top + h*term->rows + ex_height;
2393
2394             return rv;
2395         }
2396         /* break;  (never reached) */
2397       case WM_FULLSCR_ON_MAX:
2398         fullscr_on_max = TRUE;
2399         break;
2400       case WM_MOVE:
2401         sys_cursor_update();
2402         break;
2403       case WM_SIZE:
2404 #ifdef RDB_DEBUG_PATCH
2405         debug((27, "WM_SIZE %s (%d,%d)",
2406                 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2407                 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2408                 (wParam == SIZE_RESTORED && resizing) ? "to":
2409                 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2410                 "...",
2411             LOWORD(lParam), HIWORD(lParam)));
2412 #endif
2413         if (wParam == SIZE_MINIMIZED)
2414             SetWindowText(hwnd,
2415                           cfg.win_name_always ? window_name : icon_name);
2416         if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2417             SetWindowText(hwnd, window_name);
2418         if (wParam == SIZE_RESTORED)
2419             clear_full_screen();
2420         if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2421             fullscr_on_max = FALSE;
2422             make_full_screen();
2423         }
2424
2425         if (cfg.resize_action == RESIZE_DISABLED) {
2426             /* A resize, well it better be a minimize. */
2427             reset_window(-1);
2428         } else {
2429
2430             int width, height, w, h;
2431
2432             width = LOWORD(lParam);
2433             height = HIWORD(lParam);
2434
2435             if (!resizing) {
2436                 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2437                     was_zoomed = 1;
2438                     prev_rows = term->rows;
2439                     prev_cols = term->cols;
2440                     if (cfg.resize_action == RESIZE_TERM) {
2441                         w = width / font_width;
2442                         if (w < 1) w = 1;
2443                         h = height / font_height;
2444                         if (h < 1) h = 1;
2445
2446                         term_size(term, h, w, cfg.savelines);
2447                     }
2448                     reset_window(0);
2449                 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2450                     was_zoomed = 0;
2451                     if (cfg.resize_action == RESIZE_TERM)
2452                         term_size(term, prev_rows, prev_cols, cfg.savelines);
2453                     if (cfg.resize_action != RESIZE_FONT)
2454                         reset_window(2);
2455                     else
2456                         reset_window(0);
2457                 }
2458                 /* This is an unexpected resize, these will normally happen
2459                  * if the window is too large. Probably either the user
2460                  * selected a huge font or the screen size has changed.
2461                  *
2462                  * This is also called with minimize.
2463                  */
2464                 else reset_window(-1);
2465             }
2466
2467             /*
2468              * Don't call back->size in mid-resize. (To prevent
2469              * massive numbers of resize events getting sent
2470              * down the connection during an NT opaque drag.)
2471              */
2472             if (resizing) {
2473                 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2474                     need_backend_resize = TRUE;
2475                     w = (width-cfg.window_border*2) / font_width;
2476                     if (w < 1) w = 1;
2477                     h = (height-cfg.window_border*2) / font_height;
2478                     if (h < 1) h = 1;
2479
2480                     cfg.height = h;
2481                     cfg.width = w;
2482                 } else 
2483                     reset_window(0);
2484             }
2485         }
2486         sys_cursor_update();
2487         return 0;
2488       case WM_VSCROLL:
2489         switch (LOWORD(wParam)) {
2490           case SB_BOTTOM:
2491             term_scroll(term, -1, 0);
2492             break;
2493           case SB_TOP:
2494             term_scroll(term, +1, 0);
2495             break;
2496           case SB_LINEDOWN:
2497             term_scroll(term, 0, +1);
2498             break;
2499           case SB_LINEUP:
2500             term_scroll(term, 0, -1);
2501             break;
2502           case SB_PAGEDOWN:
2503             term_scroll(term, 0, +term->rows / 2);
2504             break;
2505           case SB_PAGEUP:
2506             term_scroll(term, 0, -term->rows / 2);
2507             break;
2508           case SB_THUMBPOSITION:
2509           case SB_THUMBTRACK:
2510             term_scroll(term, 1, HIWORD(wParam));
2511             break;
2512         }
2513         break;
2514       case WM_PALETTECHANGED:
2515         if ((HWND) wParam != hwnd && pal != NULL) {
2516             HDC hdc = get_ctx(NULL);
2517             if (hdc) {
2518                 if (RealizePalette(hdc) > 0)
2519                     UpdateColors(hdc);
2520                 free_ctx(hdc);
2521             }
2522         }
2523         break;
2524       case WM_QUERYNEWPALETTE:
2525         if (pal != NULL) {
2526             HDC hdc = get_ctx(NULL);
2527             if (hdc) {
2528                 if (RealizePalette(hdc) > 0)
2529                     UpdateColors(hdc);
2530                 free_ctx(hdc);
2531                 return TRUE;
2532             }
2533         }
2534         return FALSE;
2535       case WM_KEYDOWN:
2536       case WM_SYSKEYDOWN:
2537       case WM_KEYUP:
2538       case WM_SYSKEYUP:
2539         /*
2540          * Add the scan code and keypress timing to the random
2541          * number noise.
2542          */
2543         noise_ultralight(lParam);
2544
2545         /*
2546          * We don't do TranslateMessage since it disassociates the
2547          * resulting CHAR message from the KEYDOWN that sparked it,
2548          * which we occasionally don't want. Instead, we process
2549          * KEYDOWN, and call the Win32 translator functions so that
2550          * we get the translations under _our_ control.
2551          */
2552         {
2553             unsigned char buf[20];
2554             int len;
2555
2556             if (wParam == VK_PROCESSKEY) {
2557                 MSG m;
2558                 m.hwnd = hwnd;
2559                 m.message = WM_KEYDOWN;
2560                 m.wParam = wParam;
2561                 m.lParam = lParam & 0xdfff;
2562                 TranslateMessage(&m);
2563             } else {
2564                 len = TranslateKey(message, wParam, lParam, buf);
2565                 if (len == -1)
2566                     return DefWindowProc(hwnd, message, wParam, lParam);
2567
2568                 if (len != 0) {
2569                     /*
2570                      * Interrupt an ongoing paste. I'm not sure
2571                      * this is sensible, but for the moment it's
2572                      * preferable to having to faff about buffering
2573                      * things.
2574                      */
2575                     term_nopaste(term);
2576
2577                     /*
2578                      * We need not bother about stdin backlogs
2579                      * here, because in GUI PuTTY we can't do
2580                      * anything about it anyway; there's no means
2581                      * of asking Windows to hold off on KEYDOWN
2582                      * messages. We _have_ to buffer everything
2583                      * we're sent.
2584                      */
2585                     term_seen_key_event(term);
2586                     ldisc_send(ldisc, buf, len, 1);
2587                     show_mouseptr(0);
2588                 }
2589             }
2590         }
2591         net_pending_errors();
2592         return 0;
2593       case WM_INPUTLANGCHANGE:
2594         /* wParam == Font number */
2595         /* lParam == Locale */
2596         set_input_locale((HKL)lParam);
2597         sys_cursor_update();
2598         break;
2599       case WM_IME_NOTIFY:
2600         if(wParam == IMN_SETOPENSTATUS) {
2601             HIMC hImc = ImmGetContext(hwnd);
2602             ImmSetCompositionFont(hImc, &lfont);
2603             ImmReleaseContext(hwnd, hImc);
2604             return 0;
2605         }
2606         break;
2607       case WM_IME_COMPOSITION:
2608         {
2609             HIMC hIMC;
2610             int n;
2611             char *buff;
2612
2613             if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS || 
2614                 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2615
2616             if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2617                 break; /* fall back to DefWindowProc */
2618
2619             hIMC = ImmGetContext(hwnd);
2620             n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2621
2622             if (n > 0) {
2623                 int i;
2624                 buff = snewn(n, char);
2625                 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
2626                 /*
2627                  * Jaeyoun Chung reports that Korean character
2628                  * input doesn't work correctly if we do a single
2629                  * luni_send() covering the whole of buff. So
2630                  * instead we luni_send the characters one by one.
2631                  */
2632                 term_seen_key_event(term);
2633                 for (i = 0; i < n; i += 2) {
2634                     luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2635                 }
2636                 free(buff);
2637             }
2638             ImmReleaseContext(hwnd, hIMC);
2639             return 1;
2640         }
2641
2642       case WM_IME_CHAR:
2643         if (wParam & 0xFF00) {
2644             unsigned char buf[2];
2645
2646             buf[1] = wParam;
2647             buf[0] = wParam >> 8;
2648             term_seen_key_event(term);
2649             lpage_send(ldisc, kbd_codepage, buf, 2, 1);
2650         } else {
2651             char c = (unsigned char) wParam;
2652             term_seen_key_event(term);
2653             lpage_send(ldisc, kbd_codepage, &c, 1, 1);
2654         }
2655         return (0);
2656       case WM_CHAR:
2657       case WM_SYSCHAR:
2658         /*
2659          * Nevertheless, we are prepared to deal with WM_CHAR
2660          * messages, should they crop up. So if someone wants to
2661          * post the things to us as part of a macro manoeuvre,
2662          * we're ready to cope.
2663          */
2664         {
2665             char c = (unsigned char)wParam;
2666             term_seen_key_event(term);
2667             lpage_send(ldisc, CP_ACP, &c, 1, 1);
2668         }
2669         return 0;
2670       case WM_SETCURSOR:
2671         if (send_raw_mouse && LOWORD(lParam) == HTCLIENT) {
2672             SetCursor(LoadCursor(NULL, IDC_ARROW));
2673             return TRUE;
2674         }
2675         break;
2676       case WM_AGENT_CALLBACK:
2677         {
2678             struct agent_callback *c = (struct agent_callback *)lParam;
2679             c->callback(c->callback_ctx, c->data, c->len);
2680             sfree(c);
2681         }
2682         return 0;
2683       default:
2684         if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
2685             int shift_pressed=0, control_pressed=0;
2686
2687             if (message == WM_MOUSEWHEEL) {
2688                 wheel_accumulator += (short)HIWORD(wParam);
2689                 shift_pressed=LOWORD(wParam) & MK_SHIFT;
2690                 control_pressed=LOWORD(wParam) & MK_CONTROL;
2691             } else {
2692                 BYTE keys[256];
2693                 wheel_accumulator += (int)wParam;
2694                 if (GetKeyboardState(keys)!=0) {
2695                     shift_pressed=keys[VK_SHIFT]&0x80;
2696                     control_pressed=keys[VK_CONTROL]&0x80;
2697                 }
2698             }
2699
2700             /* process events when the threshold is reached */
2701             while (abs(wheel_accumulator) >= WHEEL_DELTA) {
2702                 int b;
2703
2704                 /* reduce amount for next time */
2705                 if (wheel_accumulator > 0) {
2706                     b = MBT_WHEEL_UP;
2707                     wheel_accumulator -= WHEEL_DELTA;
2708                 } else if (wheel_accumulator < 0) {
2709                     b = MBT_WHEEL_DOWN;
2710                     wheel_accumulator += WHEEL_DELTA;
2711                 } else
2712                     break;
2713
2714                 if (send_raw_mouse &&
2715                     !(cfg.mouse_override && shift_pressed)) {
2716                     /* send a mouse-down followed by a mouse up */
2717                     term_mouse(term, b, translate_button(b),
2718                                MA_CLICK,
2719                                TO_CHR_X(X_POS(lParam)),
2720                                TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2721                                control_pressed, is_alt_pressed());
2722                     term_mouse(term, b, translate_button(b),
2723                                MA_RELEASE, TO_CHR_X(X_POS(lParam)),
2724                                TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2725                                control_pressed, is_alt_pressed());
2726                 } else {
2727                     /* trigger a scroll */
2728                     term_scroll(term, 0,
2729                                 b == MBT_WHEEL_UP ?
2730                                 -term->rows / 2 : term->rows / 2);
2731                 }
2732             }
2733             return 0;
2734         }
2735     }
2736
2737     return DefWindowProc(hwnd, message, wParam, lParam);
2738 }
2739
2740 /*
2741  * Move the system caret. (We maintain one, even though it's
2742  * invisible, for the benefit of blind people: apparently some
2743  * helper software tracks the system caret, so we should arrange to
2744  * have one.)
2745  */
2746 void sys_cursor(void *frontend, int x, int y)
2747 {
2748     int cx, cy;
2749
2750     if (!term->has_focus) return;
2751
2752     /*
2753      * Avoid gratuitously re-updating the cursor position and IMM
2754      * window if there's no actual change required.
2755      */
2756     cx = x * font_width + offset_width;
2757     cy = y * font_height + offset_height;
2758     if (cx == caret_x && cy == caret_y)
2759         return;
2760     caret_x = cx;
2761     caret_y = cy;
2762
2763     sys_cursor_update();
2764 }
2765
2766 static void sys_cursor_update(void)
2767 {
2768     COMPOSITIONFORM cf;
2769     HIMC hIMC;
2770
2771     if (!term->has_focus) return;
2772
2773     if (caret_x < 0 || caret_y < 0)
2774         return;
2775
2776     SetCaretPos(caret_x, caret_y);
2777
2778     /* IMM calls on Win98 and beyond only */
2779     if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
2780     
2781     if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
2782             osVersion.dwMinorVersion == 0) return; /* 95 */
2783
2784     /* we should have the IMM functions */
2785     hIMC = ImmGetContext(hwnd);
2786     cf.dwStyle = CFS_POINT;
2787     cf.ptCurrentPos.x = caret_x;
2788     cf.ptCurrentPos.y = caret_y;
2789     ImmSetCompositionWindow(hIMC, &cf);
2790
2791     ImmReleaseContext(hwnd, hIMC);
2792 }
2793
2794 /*
2795  * Draw a line of text in the window, at given character
2796  * coordinates, in given attributes.
2797  *
2798  * We are allowed to fiddle with the contents of `text'.
2799  */
2800 void do_text(Context ctx, int x, int y, char *text, int len,
2801              unsigned long attr, int lattr)
2802 {
2803     COLORREF fg, bg, t;
2804     int nfg, nbg, nfont;
2805     HDC hdc = ctx;
2806     RECT line_box;
2807     int force_manual_underline = 0;
2808     int fnt_width = font_width * (1 + (lattr != LATTR_NORM));
2809     int char_width = fnt_width;
2810     int text_adjust = 0;
2811     static int *IpDx = 0, IpDxLEN = 0;
2812
2813     if (attr & ATTR_WIDE)
2814         char_width *= 2;
2815
2816     if (len > IpDxLEN || IpDx[0] != char_width) {
2817         int i;
2818         if (len > IpDxLEN) {
2819             sfree(IpDx);
2820             IpDx = snewn(len + 16, int);
2821             IpDxLEN = (len + 16);
2822         }
2823         for (i = 0; i < IpDxLEN; i++)
2824             IpDx[i] = char_width;
2825     }
2826
2827     /* Only want the left half of double width lines */
2828     if (lattr != LATTR_NORM && x*2 >= term->cols)
2829         return;
2830
2831     x *= fnt_width;
2832     y *= font_height;
2833     x += offset_width;
2834     y += offset_height;
2835
2836     if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
2837         attr &= ATTR_CUR_AND | (bold_mode != BOLD_COLOURS ? ATTR_BOLD : 0);
2838         attr ^= ATTR_CUR_XOR;
2839     }
2840
2841     nfont = 0;
2842     if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
2843         /* Assume a poorman font is borken in other ways too. */
2844         lattr = LATTR_WIDE;
2845     } else
2846         switch (lattr) {
2847           case LATTR_NORM:
2848             break;
2849           case LATTR_WIDE:
2850             nfont |= FONT_WIDE;
2851             break;
2852           default:
2853             nfont |= FONT_WIDE + FONT_HIGH;
2854             break;
2855         }
2856     if (attr & ATTR_NARROW)
2857         nfont |= FONT_NARROW;
2858
2859     /* Special hack for the VT100 linedraw glyphs. */
2860     if ((attr & CSET_MASK) == 0x2300) {
2861         if (text[0] >= (char) 0xBA && text[0] <= (char) 0xBD) {
2862             switch ((unsigned char) (text[0])) {
2863               case 0xBA:
2864                 text_adjust = -2 * font_height / 5;
2865                 break;
2866               case 0xBB:
2867                 text_adjust = -1 * font_height / 5;
2868                 break;
2869               case 0xBC:
2870                 text_adjust = font_height / 5;
2871                 break;
2872               case 0xBD:
2873                 text_adjust = 2 * font_height / 5;
2874                 break;
2875             }
2876             if (lattr == LATTR_TOP || lattr == LATTR_BOT)
2877                 text_adjust *= 2;
2878             attr &= ~CSET_MASK;
2879             text[0] = (char) (ucsdata.unitab_xterm['q'] & CHAR_MASK);
2880             attr |= (ucsdata.unitab_xterm['q'] & CSET_MASK);
2881             if (attr & ATTR_UNDER) {
2882                 attr &= ~ATTR_UNDER;
2883                 force_manual_underline = 1;
2884             }
2885         }
2886     }
2887
2888     /* Anything left as an original character set is unprintable. */
2889     if (DIRECT_CHAR(attr)) {
2890         attr &= ~CSET_MASK;
2891         attr |= 0xFF00;
2892         memset(text, 0xFD, len);
2893     }
2894
2895     /* OEM CP */
2896     if ((attr & CSET_MASK) == ATTR_OEMCP)
2897         nfont |= FONT_OEM;
2898
2899     nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
2900     nfg = 2 * (nfg & 0xF) + (nfg & 0x10 ? 1 : 0);
2901     nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
2902     nbg = 2 * (nbg & 0xF) + (nbg & 0x10 ? 1 : 0);
2903     if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
2904         nfont |= FONT_BOLD;
2905     if (und_mode == UND_FONT && (attr & ATTR_UNDER))
2906         nfont |= FONT_UNDERLINE;
2907     another_font(nfont);
2908     if (!fonts[nfont]) {
2909         if (nfont & FONT_UNDERLINE)
2910             force_manual_underline = 1;
2911         /* Don't do the same for manual bold, it could be bad news. */
2912
2913         nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
2914     }
2915     another_font(nfont);
2916     if (!fonts[nfont])
2917         nfont = FONT_NORMAL;
2918     if (attr & ATTR_REVERSE) {
2919         t = nfg;
2920         nfg = nbg;
2921         nbg = t;
2922     }
2923     if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD))
2924         nfg |= 1;
2925     if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK))
2926         nbg |= 1;
2927     fg = colours[nfg];
2928     bg = colours[nbg];
2929     SelectObject(hdc, fonts[nfont]);
2930     SetTextColor(hdc, fg);
2931     SetBkColor(hdc, bg);
2932     SetBkMode(hdc, OPAQUE);
2933     line_box.left = x;
2934     line_box.top = y;
2935     line_box.right = x + char_width * len;
2936     line_box.bottom = y + font_height;
2937
2938     /* Only want the left half of double width lines */
2939     if (line_box.right > font_width*term->cols+offset_width)
2940         line_box.right = font_width*term->cols+offset_width;
2941
2942     /* We're using a private area for direct to font. (512 chars.) */
2943     if (ucsdata.dbcs_screenfont && (attr & CSET_MASK) == ATTR_ACP) {
2944         /* Ho Hum, dbcs fonts are a PITA! */
2945         /* To display on W9x I have to convert to UCS */
2946         static wchar_t *uni_buf = 0;
2947         static int uni_len = 0;
2948         int nlen, mptr;
2949         if (len > uni_len) {
2950             sfree(uni_buf);
2951             uni_len = len;
2952             uni_buf = snewn(uni_len, wchar_t);
2953         }
2954
2955         for(nlen = mptr = 0; mptr<len; mptr++) {
2956             uni_buf[nlen] = 0xFFFD;
2957             if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
2958                 IpDx[nlen] += char_width;
2959                 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
2960                                    text+mptr, 2, uni_buf+nlen, 1);
2961                 mptr++;
2962             }
2963             else
2964             {
2965                 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
2966                                    text+mptr, 1, uni_buf+nlen, 1);
2967             }
2968             nlen++;
2969         }
2970         if (nlen <= 0)
2971             return;                    /* Eeek! */
2972
2973         ExtTextOutW(hdc, x,
2974                     y - font_height * (lattr == LATTR_BOT) + text_adjust,
2975                     ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
2976         if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
2977             SetBkMode(hdc, TRANSPARENT);
2978             ExtTextOutW(hdc, x - 1,
2979                         y - font_height * (lattr ==
2980                                            LATTR_BOT) + text_adjust,
2981                         ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
2982         }
2983
2984         IpDx[0] = -1;
2985     } else if (DIRECT_FONT(attr)) {
2986         ExtTextOut(hdc, x,
2987                    y - font_height * (lattr == LATTR_BOT) + text_adjust,
2988                    ETO_CLIPPED | ETO_OPAQUE, &line_box, text, len, IpDx);
2989         if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
2990             SetBkMode(hdc, TRANSPARENT);
2991
2992             /* GRR: This draws the character outside it's box and can leave
2993              * 'droppings' even with the clip box! I suppose I could loop it
2994              * one character at a time ... yuk. 
2995              * 
2996              * Or ... I could do a test print with "W", and use +1 or -1 for this
2997              * shift depending on if the leftmost column is blank...
2998              */
2999             ExtTextOut(hdc, x - 1,
3000                        y - font_height * (lattr ==
3001                                           LATTR_BOT) + text_adjust,
3002                        ETO_CLIPPED, &line_box, text, len, IpDx);
3003         }
3004     } else {
3005         /* And 'normal' unicode characters */
3006         static WCHAR *wbuf = NULL;
3007         static int wlen = 0;
3008         int i;
3009         if (wlen < len) {
3010             sfree(wbuf);
3011             wlen = len;
3012             wbuf = snewn(wlen, WCHAR);
3013         }
3014         for (i = 0; i < len; i++)
3015             wbuf[i] = (WCHAR) ((attr & CSET_MASK) + (text[i] & CHAR_MASK));
3016
3017         ExtTextOutW(hdc, x,
3018                     y - font_height * (lattr == LATTR_BOT) + text_adjust,
3019                     ETO_CLIPPED | ETO_OPAQUE, &line_box, wbuf, len, IpDx);
3020
3021         /* And the shadow bold hack. */
3022         if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
3023             SetBkMode(hdc, TRANSPARENT);
3024             ExtTextOutW(hdc, x - 1,
3025                         y - font_height * (lattr ==
3026                                            LATTR_BOT) + text_adjust,
3027                         ETO_CLIPPED, &line_box, wbuf, len, IpDx);
3028         }
3029     }
3030     if (lattr != LATTR_TOP && (force_manual_underline ||
3031                                (und_mode == UND_LINE
3032                                 && (attr & ATTR_UNDER)))) {
3033         HPEN oldpen;
3034         int dec = descent;
3035         if (lattr == LATTR_BOT)
3036             dec = dec * 2 - font_height;
3037
3038         oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
3039         MoveToEx(hdc, x, y + dec, NULL);
3040         LineTo(hdc, x + len * char_width, y + dec);
3041         oldpen = SelectObject(hdc, oldpen);
3042         DeleteObject(oldpen);
3043     }
3044 }
3045
3046 void do_cursor(Context ctx, int x, int y, char *text, int len,
3047                unsigned long attr, int lattr)
3048 {
3049
3050     int fnt_width;
3051     int char_width;
3052     HDC hdc = ctx;
3053     int ctype = cfg.cursor_type;
3054
3055     if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3056         if (((attr & CSET_MASK) | (unsigned char) *text) != UCSWIDE) {
3057             do_text(ctx, x, y, text, len, attr, lattr);
3058             return;
3059         }
3060         ctype = 2;
3061         attr |= TATTR_RIGHTCURS;
3062     }
3063
3064     fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3065     if (attr & ATTR_WIDE)
3066         char_width *= 2;
3067     x *= fnt_width;
3068     y *= font_height;
3069     x += offset_width;
3070     y += offset_height;
3071
3072     if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3073         POINT pts[5];
3074         HPEN oldpen;
3075         pts[0].x = pts[1].x = pts[4].x = x;
3076         pts[2].x = pts[3].x = x + char_width - 1;
3077         pts[0].y = pts[3].y = pts[4].y = y;
3078         pts[1].y = pts[2].y = y + font_height - 1;
3079         oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
3080         Polyline(hdc, pts, 5);
3081         oldpen = SelectObject(hdc, oldpen);
3082         DeleteObject(oldpen);
3083     } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3084         int startx, starty, dx, dy, length, i;
3085         if (ctype == 1) {
3086             startx = x;
3087             starty = y + descent;
3088             dx = 1;
3089             dy = 0;
3090             length = char_width;
3091         } else {
3092             int xadjust = 0;
3093             if (attr & TATTR_RIGHTCURS)
3094                 xadjust = char_width - 1;
3095             startx = x + xadjust;
3096             starty = y;
3097             dx = 0;
3098             dy = 1;
3099             length = font_height;
3100         }
3101         if (attr & TATTR_ACTCURS) {
3102             HPEN oldpen;
3103             oldpen =
3104                 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
3105             MoveToEx(hdc, startx, starty, NULL);
3106             LineTo(hdc, startx + dx * length, starty + dy * length);
3107             oldpen = SelectObject(hdc, oldpen);
3108             DeleteObject(oldpen);
3109         } else {
3110             for (i = 0; i < length; i++) {
3111                 if (i % 2 == 0) {
3112                     SetPixel(hdc, startx, starty, colours[23]);
3113                 }
3114                 startx += dx;
3115                 starty += dy;
3116             }
3117         }
3118     }
3119 }
3120
3121 /* This function gets the actual width of a character in the normal font.
3122  */
3123 int char_width(Context ctx, int uc) {
3124     HDC hdc = ctx;
3125     int ibuf = 0;
3126
3127     /* If the font max is the same as the font ave width then this
3128      * function is a no-op.
3129      */
3130     if (!font_dualwidth) return 1;
3131
3132     switch (uc & CSET_MASK) {
3133       case ATTR_ASCII:
3134         uc = ucsdata.unitab_line[uc & 0xFF];
3135         break;
3136       case ATTR_LINEDRW:
3137         uc = ucsdata.unitab_xterm[uc & 0xFF];
3138         break;
3139       case ATTR_SCOACS:
3140         uc = ucsdata.unitab_scoacs[uc & 0xFF];
3141         break;
3142     }
3143     if (DIRECT_FONT(uc)) {
3144         if (ucsdata.dbcs_screenfont) return 1;
3145
3146         /* Speedup, I know of no font where ascii is the wrong width */
3147         if ((uc&CHAR_MASK) >= ' ' && (uc&CHAR_MASK)<= '~') 
3148             return 1;
3149
3150         if ( (uc & CSET_MASK) == ATTR_ACP ) {
3151             SelectObject(hdc, fonts[FONT_NORMAL]);
3152         } else if ( (uc & CSET_MASK) == ATTR_OEMCP ) {
3153             another_font(FONT_OEM);
3154             if (!fonts[FONT_OEM]) return 0;
3155
3156             SelectObject(hdc, fonts[FONT_OEM]);
3157         } else
3158             return 0;
3159
3160         if ( GetCharWidth32(hdc, uc&CHAR_MASK, uc&CHAR_MASK, &ibuf) != 1 && 
3161              GetCharWidth(hdc, uc&CHAR_MASK, uc&CHAR_MASK, &ibuf) != 1)
3162             return 0;
3163     } else {
3164         /* Speedup, I know of no font where ascii is the wrong width */
3165         if (uc >= ' ' && uc <= '~') return 1;
3166
3167         SelectObject(hdc, fonts[FONT_NORMAL]);
3168         if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3169             /* Okay that one worked */ ;
3170         else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3171             /* This should work on 9x too, but it's "less accurate" */ ;
3172         else
3173             return 0;
3174     }
3175
3176     ibuf += font_width / 2 -1;
3177     ibuf /= font_width;
3178
3179     return ibuf;
3180 }
3181
3182 /*
3183  * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3184  * codes. Returns number of bytes used or zero to drop the message
3185  * or -1 to forward the message to windows.
3186  */
3187 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3188                         unsigned char *output)
3189 {
3190     BYTE keystate[256];
3191     int scan, left_alt = 0, key_down, shift_state;
3192     int r, i, code;
3193     unsigned char *p = output;
3194     static int alt_sum = 0;
3195
3196     HKL kbd_layout = GetKeyboardLayout(0);
3197
3198     /* keys is for ToAsciiEx. There's some ick here, see below. */
3199     static WORD keys[3];
3200     static int compose_char = 0;
3201     static WPARAM compose_key = 0;
3202
3203     r = GetKeyboardState(keystate);
3204     if (!r)
3205         memset(keystate, 0, sizeof(keystate));
3206     else {
3207 #if 0
3208 #define SHOW_TOASCII_RESULT
3209         {                              /* Tell us all about key events */
3210             static BYTE oldstate[256];
3211             static int first = 1;
3212             static int scan;
3213             int ch;
3214             if (first)
3215                 memcpy(oldstate, keystate, sizeof(oldstate));
3216             first = 0;
3217
3218             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3219                 debug(("+"));
3220             } else if ((HIWORD(lParam) & KF_UP)
3221                        && scan == (HIWORD(lParam) & 0xFF)) {
3222                 debug((". U"));
3223             } else {
3224                 debug((".\n"));
3225                 if (wParam >= VK_F1 && wParam <= VK_F20)
3226                     debug(("K_F%d", wParam + 1 - VK_F1));
3227                 else
3228                     switch (wParam) {
3229                       case VK_SHIFT:
3230                         debug(("SHIFT"));
3231                         break;
3232                       case VK_CONTROL:
3233                         debug(("CTRL"));
3234                         break;
3235                       case VK_MENU:
3236                         debug(("ALT"));
3237                         break;
3238                       default:
3239                         debug(("VK_%02x", wParam));
3240                     }
3241                 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3242                     debug(("*"));
3243                 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3244
3245                 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3246                 if (ch >= ' ' && ch <= '~')
3247                     debug((", '%c'", ch));
3248                 else if (ch)
3249                     debug((", $%02x", ch));
3250
3251                 if (keys[0])
3252                     debug((", KB0=%02x", keys[0]));
3253                 if (keys[1])
3254                     debug((", KB1=%02x", keys[1]));
3255                 if (keys[2])
3256                     debug((", KB2=%02x", keys[2]));
3257
3258                 if ((keystate[VK_SHIFT] & 0x80) != 0)
3259                     debug((", S"));
3260                 if ((keystate[VK_CONTROL] & 0x80) != 0)
3261                     debug((", C"));
3262                 if ((HIWORD(lParam) & KF_EXTENDED))
3263                     debug((", E"));
3264                 if ((HIWORD(lParam) & KF_UP))
3265                     debug((", U"));
3266             }
3267
3268             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3269             else if ((HIWORD(lParam) & KF_UP))
3270                 oldstate[wParam & 0xFF] ^= 0x80;
3271             else
3272                 oldstate[wParam & 0xFF] ^= 0x81;
3273
3274             for (ch = 0; ch < 256; ch++)
3275                 if (oldstate[ch] != keystate[ch])
3276                     debug((", M%02x=%02x", ch, keystate[ch]));
3277
3278             memcpy(oldstate, keystate, sizeof(oldstate));
3279         }
3280 #endif
3281
3282         if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
3283             keystate[VK_RMENU] = keystate[VK_MENU];
3284         }
3285
3286
3287         /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
3288         if ((cfg.funky_type == 3 ||
3289              (cfg.funky_type <= 1 && term->app_keypad_keys &&
3290               !cfg.no_applic_k))
3291             && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
3292
3293             wParam = VK_EXECUTE;
3294
3295             /* UnToggle NUMLock */
3296             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3297                 keystate[VK_NUMLOCK] ^= 1;
3298         }
3299
3300         /* And write back the 'adjusted' state */
3301         SetKeyboardState(keystate);
3302     }
3303
3304     /* Disable Auto repeat if required */
3305     if (term->repeat_off &&
3306         (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
3307         return 0;
3308
3309     if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
3310         left_alt = 1;
3311
3312     key_down = ((HIWORD(lParam) & KF_UP) == 0);
3313
3314     /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
3315     if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
3316         if (cfg.ctrlaltkeys)
3317             keystate[VK_MENU] = 0;
3318         else {
3319             keystate[VK_RMENU] = 0x80;
3320             left_alt = 0;
3321         }
3322     }
3323
3324     scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
3325     shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3326         + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
3327
3328     /* Note if AltGr was pressed and if it was used as a compose key */
3329     if (!compose_state) {
3330         compose_key = 0x100;
3331         if (cfg.compose_key) {
3332             if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
3333                 compose_key = wParam;
3334         }
3335         if (wParam == VK_APPS)
3336             compose_key = wParam;
3337     }
3338
3339     if (wParam == compose_key) {
3340         if (compose_state == 0
3341             && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3342                 1;
3343         else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
3344             compose_state = 2;
3345         else
3346             compose_state = 0;
3347     } else if (compose_state == 1 && wParam != VK_CONTROL)
3348         compose_state = 0;
3349
3350     if (compose_state > 1 && left_alt)
3351         compose_state = 0;
3352
3353     /* Sanitize the number pad if not using a PC NumPad */
3354     if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
3355                      && cfg.funky_type != 2)
3356         || cfg.funky_type == 3 || cfg.nethack_keypad || compose_state) {
3357         if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
3358             int nParam = 0;
3359             switch (wParam) {
3360               case VK_INSERT:
3361                 nParam = VK_NUMPAD0;
3362                 break;
3363               case VK_END:
3364                 nParam = VK_NUMPAD1;
3365                 break;
3366               case VK_DOWN:
3367                 nParam = VK_NUMPAD2;
3368                 break;
3369               case VK_NEXT:
3370                 nParam = VK_NUMPAD3;
3371                 break;
3372               case VK_LEFT:
3373                 nParam = VK_NUMPAD4;
3374                 break;
3375               case VK_CLEAR:
3376                 nParam = VK_NUMPAD5;
3377                 break;
3378               case VK_RIGHT:
3379                 nParam = VK_NUMPAD6;
3380                 break;
3381               case VK_HOME:
3382                 nParam = VK_NUMPAD7;
3383                 break;
3384               case VK_UP:
3385                 nParam = VK_NUMPAD8;
3386                 break;
3387               case VK_PRIOR:
3388                 nParam = VK_NUMPAD9;
3389                 break;
3390               case VK_DELETE:
3391                 nParam = VK_DECIMAL;
3392                 break;
3393             }
3394             if (nParam) {
3395                 if (keystate[VK_NUMLOCK] & 1)
3396                     shift_state |= 1;
3397                 wParam = nParam;
3398             }
3399         }
3400     }
3401
3402     /* If a key is pressed and AltGr is not active */
3403     if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3404         /* Okay, prepare for most alts then ... */
3405         if (left_alt)
3406             *p++ = '\033';
3407
3408         /* Lets see if it's a pattern we know all about ... */
3409         if (wParam == VK_PRIOR && shift_state == 1) {
3410             SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3411             return 0;
3412         }
3413         if (wParam == VK_PRIOR && shift_state == 2) {
3414             SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3415             return 0;
3416         }
3417         if (wParam == VK_NEXT && shift_state == 1) {
3418             SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3419             return 0;
3420         }
3421         if (wParam == VK_NEXT && shift_state == 2) {
3422             SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3423             return 0;
3424         }
3425         if (wParam == VK_INSERT && shift_state == 1) {
3426             term_do_paste(term);
3427             return 0;
3428         }
3429         if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
3430             return -1;
3431         }
3432         if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
3433             SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3434             return -1;
3435         }
3436         if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3437             (cfg.resize_action != RESIZE_DISABLED)) {
3438             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3439                 flip_full_screen();
3440             return -1;
3441         }
3442         /* Control-Numlock for app-keypad mode switch */
3443         if (wParam == VK_PAUSE && shift_state == 2) {
3444             term->app_keypad_keys ^= 1;
3445             return 0;
3446         }
3447
3448         /* Nethack keypad */
3449         if (cfg.nethack_keypad && !left_alt) {
3450             switch (wParam) {
3451               case VK_NUMPAD1:
3452                 *p++ = shift_state ? 'B' : 'b';
3453                 return p - output;
3454               case VK_NUMPAD2:
3455                 *p++ = shift_state ? 'J' : 'j';
3456                 return p - output;
3457               case VK_NUMPAD3:
3458                 *p++ = shift_state ? 'N' : 'n';
3459                 return p - output;
3460               case VK_NUMPAD4:
3461                 *p++ = shift_state ? 'H' : 'h';
3462                 return p - output;
3463               case VK_NUMPAD5:
3464                 *p++ = shift_state ? '.' : '.';
3465                 return p - output;
3466               case VK_NUMPAD6:
3467                 *p++ = shift_state ? 'L' : 'l';
3468                 return p - output;
3469               case VK_NUMPAD7:
3470                 *p++ = shift_state ? 'Y' : 'y';
3471                 return p - output;
3472               case VK_NUMPAD8:
3473                 *p++ = shift_state ? 'K' : 'k';
3474                 return p - output;
3475               case VK_NUMPAD9:
3476                 *p++ = shift_state ? 'U' : 'u';
3477                 return p - output;
3478             }
3479         }
3480
3481         /* Application Keypad */
3482         if (!left_alt) {
3483             int xkey = 0;
3484
3485             if (cfg.funky_type == 3 ||
3486                 (cfg.funky_type <= 1 &&
3487                  term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
3488                   case VK_EXECUTE:
3489                     xkey = 'P';
3490                     break;
3491                   case VK_DIVIDE:
3492                     xkey = 'Q';
3493                     break;
3494                   case VK_MULTIPLY:
3495                     xkey = 'R';
3496                     break;
3497                   case VK_SUBTRACT:
3498                     xkey = 'S';
3499                     break;
3500                 }
3501             if (term->app_keypad_keys && !cfg.no_applic_k)
3502                 switch (wParam) {
3503                   case VK_NUMPAD0:
3504                     xkey = 'p';
3505                     break;
3506                   case VK_NUMPAD1:
3507                     xkey = 'q';
3508                     break;
3509                   case VK_NUMPAD2:
3510                     xkey = 'r';
3511                     break;
3512                   case VK_NUMPAD3:
3513                     xkey = 's';
3514                     break;
3515                   case VK_NUMPAD4:
3516                     xkey = 't';
3517                     break;
3518                   case VK_NUMPAD5:
3519                     xkey = 'u';
3520                     break;
3521                   case VK_NUMPAD6:
3522                     xkey = 'v';
3523                     break;
3524                   case VK_NUMPAD7:
3525                     xkey = 'w';
3526                     break;
3527                   case VK_NUMPAD8:
3528                     xkey = 'x';
3529                     break;
3530                   case VK_NUMPAD9:
3531                     xkey = 'y';
3532                     break;
3533
3534                   case VK_DECIMAL:
3535                     xkey = 'n';
3536                     break;
3537                   case VK_ADD:
3538                     if (cfg.funky_type == 2) {
3539                         if (shift_state)
3540                             xkey = 'l';
3541                         else
3542                             xkey = 'k';
3543                     } else if (shift_state)
3544                         xkey = 'm';
3545                     else
3546                         xkey = 'l';
3547                     break;
3548
3549                   case VK_DIVIDE:
3550                     if (cfg.funky_type == 2)
3551                         xkey = 'o';
3552                     break;
3553                   case VK_MULTIPLY:
3554                     if (cfg.funky_type == 2)
3555                         xkey = 'j';
3556                     break;
3557                   case VK_SUBTRACT:
3558                     if (cfg.funky_type == 2)
3559                         xkey = 'm';
3560                     break;
3561
3562                   case VK_RETURN:
3563                     if (HIWORD(lParam) & KF_EXTENDED)
3564                         xkey = 'M';
3565                     break;
3566                 }
3567             if (xkey) {
3568                 if (term->vt52_mode) {
3569                     if (xkey >= 'P' && xkey <= 'S')
3570                         p += sprintf((char *) p, "\x1B%c", xkey);
3571                     else
3572                         p += sprintf((char *) p, "\x1B?%c", xkey);
3573                 } else
3574                     p += sprintf((char *) p, "\x1BO%c", xkey);
3575                 return p - output;
3576             }
3577         }
3578
3579         if (wParam == VK_BACK && shift_state == 0) {    /* Backspace */
3580             *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
3581             *p++ = 0;
3582             return -2;
3583         }
3584         if (wParam == VK_BACK && shift_state == 1) {    /* Shift Backspace */
3585             /* We do the opposite of what is configured */
3586             *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
3587             *p++ = 0;
3588             return -2;
3589         }
3590         if (wParam == VK_TAB && shift_state == 1) {     /* Shift tab */
3591             *p++ = 0x1B;
3592             *p++ = '[';
3593             *p++ = 'Z';
3594             return p - output;
3595         }
3596         if (wParam == VK_SPACE && shift_state == 2) {   /* Ctrl-Space */
3597             *p++ = 0;
3598             return p - output;
3599         }
3600         if (wParam == VK_SPACE && shift_state == 3) {   /* Ctrl-Shift-Space */
3601             *p++ = 160;
3602             return p - output;
3603         }
3604         if (wParam == VK_CANCEL && shift_state == 2) {  /* Ctrl-Break */
3605             *p++ = 3;
3606             *p++ = 0;
3607             return -2;
3608         }
3609         if (wParam == VK_PAUSE) {      /* Break/Pause */
3610             *p++ = 26;
3611             *p++ = 0;
3612             return -2;
3613         }
3614         /* Control-2 to Control-8 are special */
3615         if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
3616             *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
3617             return p - output;
3618         }
3619         if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
3620             *p++ = 0x1F;
3621             return p - output;
3622         }
3623         if (shift_state == 2 && wParam == 0xDF) {
3624             *p++ = 0x1C;
3625             return p - output;
3626         }
3627         if (shift_state == 3 && wParam == 0xDE) {
3628             *p++ = 0x1E;               /* Ctrl-~ == Ctrl-^ in xterm at least */
3629             return p - output;
3630         }
3631         if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
3632             *p++ = '\r';
3633             *p++ = '\n';
3634             return p - output;
3635         }
3636
3637         /*
3638          * Next, all the keys that do tilde codes. (ESC '[' nn '~',
3639          * for integer decimal nn.)
3640          *
3641          * We also deal with the weird ones here. Linux VCs replace F1
3642          * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
3643          * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
3644          * respectively.
3645          */
3646         code = 0;
3647         switch (wParam) {
3648           case VK_F1:
3649             code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
3650             break;
3651           case VK_F2:
3652             code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
3653             break;
3654           case VK_F3:
3655             code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
3656             break;
3657           case VK_F4:
3658             code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
3659             break;
3660           case VK_F5:
3661             code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
3662             break;
3663           case VK_F6:
3664             code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
3665             break;
3666           case VK_F7:
3667             code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
3668             break;
3669           case VK_F8:
3670             code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
3671             break;
3672           case VK_F9:
3673             code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
3674             break;
3675           case VK_F10:
3676             code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
3677             break;
3678           case VK_F11:
3679             code = 23;
3680             break;
3681           case VK_F12:
3682             code = 24;
3683             break;
3684           case VK_F13:
3685             code = 25;
3686             break;
3687           case VK_F14:
3688             code = 26;
3689             break;
3690           case VK_F15:
3691             code = 28;
3692             break;
3693           case VK_F16:
3694             code = 29;
3695             break;
3696           case VK_F17:
3697             code = 31;
3698             break;
3699           case VK_F18:
3700             code = 32;
3701             break;
3702           case VK_F19:
3703             code = 33;
3704             break;
3705           case VK_F20:
3706             code = 34;
3707             break;
3708         }
3709         if ((shift_state&2) == 0) switch (wParam) {
3710           case VK_HOME:
3711             code = 1;
3712             break;
3713           case VK_INSERT:
3714             code = 2;
3715             break;
3716           case VK_DELETE:
3717             code = 3;
3718             break;
3719           case VK_END:
3720             code = 4;
3721             break;
3722           case VK_PRIOR:
3723             code = 5;
3724             break;
3725           case VK_NEXT:
3726             code = 6;
3727             break;
3728         }
3729         /* Reorder edit keys to physical order */
3730         if (cfg.funky_type == 3 && code <= 6)
3731             code = "\0\2\1\4\5\3\6"[code];
3732
3733         if (term->vt52_mode && code > 0 && code <= 6) {
3734             p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
3735             return p - output;
3736         }
3737
3738         if (cfg.funky_type == 5 &&     /* SCO function keys */
3739             code >= 11 && code <= 34) {
3740             char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
3741             int index = 0;
3742             switch (wParam) {
3743               case VK_F1: index = 0; break;
3744               case VK_F2: index = 1; break;
3745               case VK_F3: index = 2; break;
3746               case VK_F4: index = 3; break;
3747               case VK_F5: index = 4; break;
3748               case VK_F6: index = 5; break;
3749               case VK_F7: index = 6; break;
3750               case VK_F8: index = 7; break;
3751               case VK_F9: index = 8; break;
3752               case VK_F10: index = 9; break;
3753               case VK_F11: index = 10; break;
3754               case VK_F12: index = 11; break;
3755             }
3756             if (keystate[VK_SHIFT] & 0x80) index += 12;
3757             if (keystate[VK_CONTROL] & 0x80) index += 24;
3758             p += sprintf((char *) p, "\x1B[%c", codes[index]);
3759             return p - output;
3760         }
3761         if (cfg.funky_type == 5 &&     /* SCO small keypad */
3762             code >= 1 && code <= 6) {
3763             char codes[] = "HL.FIG";
3764             if (code == 3) {
3765                 *p++ = '\x7F';
3766             } else {
3767                 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
3768             }
3769             return p - output;
3770         }
3771         if ((term->vt52_mode || cfg.funky_type == 4) && code >= 11 && code <= 24) {
3772             int offt = 0;
3773             if (code > 15)
3774                 offt++;
3775             if (code > 21)
3776                 offt++;
3777             if (term->vt52_mode)
3778                 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
3779             else
3780                 p +=
3781                     sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
3782             return p - output;
3783         }
3784         if (cfg.funky_type == 1 && code >= 11 && code <= 15) {
3785             p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
3786             return p - output;
3787         }
3788         if (cfg.funky_type == 2 && code >= 11 && code <= 14) {
3789             if (term->vt52_mode)
3790                 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
3791             else
3792                 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
3793             return p - output;
3794         }
3795         if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
3796             p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
3797             return p - output;
3798         }
3799         if (code) {
3800             p += sprintf((char *) p, "\x1B[%d~", code);
3801             return p - output;
3802         }
3803
3804         /*
3805          * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
3806          * some reason seems to send VK_CLEAR to Windows...).
3807          */
3808         {
3809             char xkey = 0;
3810             switch (wParam) {
3811               case VK_UP:
3812                 xkey = 'A';
3813                 break;
3814               case VK_DOWN:
3815                 xkey = 'B';
3816                 break;
3817               case VK_RIGHT:
3818                 xkey = 'C';
3819                 break;
3820               case VK_LEFT:
3821                 xkey = 'D';
3822                 break;
3823               case VK_CLEAR:
3824                 xkey = 'G';
3825                 break;
3826             }
3827             if (xkey) {
3828                 if (term->vt52_mode)
3829                     p += sprintf((char *) p, "\x1B%c", xkey);
3830                 else {
3831                     int app_flg = (term->app_cursor_keys && !cfg.no_applic_c);
3832 #if 0
3833                     /*
3834                      * RDB: VT100 & VT102 manuals both state the
3835                      * app cursor keys only work if the app keypad
3836                      * is on.
3837                      * 
3838                      * SGT: That may well be true, but xterm
3839                      * disagrees and so does at least one
3840                      * application, so I've #if'ed this out and the
3841                      * behaviour is back to PuTTY's original: app
3842                      * cursor and app keypad are independently
3843                      * switchable modes. If anyone complains about
3844                      * _this_ I'll have to put in a configurable
3845                      * option.
3846                      */
3847                     if (!term->app_keypad_keys)
3848                         app_flg = 0;
3849 #endif
3850                     /* Useful mapping of Ctrl-arrows */
3851                     if (shift_state == 2)
3852                         app_flg = !app_flg;
3853
3854                     if (app_flg)
3855                         p += sprintf((char *) p, "\x1BO%c", xkey);
3856                     else
3857                         p += sprintf((char *) p, "\x1B[%c", xkey);
3858                 }
3859                 return p - output;
3860             }
3861         }
3862
3863         /*
3864          * Finally, deal with Return ourselves. (Win95 seems to
3865          * foul it up when Alt is pressed, for some reason.)
3866          */
3867         if (wParam == VK_RETURN) {     /* Return */
3868             *p++ = 0x0D;
3869             *p++ = 0;
3870             return -2;
3871         }
3872
3873         if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
3874             alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
3875         else
3876             alt_sum = 0;
3877     }
3878
3879     /* Okay we've done everything interesting; let windows deal with 
3880      * the boring stuff */
3881     {
3882         BOOL capsOn=0;
3883
3884         /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
3885         if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
3886             capsOn= !left_alt;
3887             keystate[VK_CAPITAL] = 0;
3888         }
3889
3890         /* XXX how do we know what the max size of the keys array should
3891          * be is? There's indication on MS' website of an Inquire/InquireEx
3892          * functioning returning a KBINFO structure which tells us. */
3893         if (osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT) {
3894             /* XXX 'keys' parameter is declared in MSDN documentation as
3895              * 'LPWORD lpChar'.
3896              * The experience of a French user indicates that on
3897              * Win98, WORD[] should be passed in, but on Win2K, it should
3898              * be BYTE[]. German WinXP and my Win2K with "US International"
3899              * driver corroborate this.
3900              * Experimentally I've conditionalised the behaviour on the
3901              * Win9x/NT split, but I suspect it's worse than that.
3902              * See wishlist item `win-dead-keys' for more horrible detail
3903              * and speculations. */
3904             BYTE keybs[3];
3905             int i;
3906             r = ToAsciiEx(wParam, scan, keystate, (LPWORD)keybs, 0, kbd_layout);
3907             for (i=0; i<3; i++) keys[i] = keybs[i];
3908         } else {
3909             r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
3910         }
3911 #ifdef SHOW_TOASCII_RESULT
3912         if (r == 1 && !key_down) {
3913             if (alt_sum) {
3914                 if (in_utf(term) || ucsdata.dbcs_screenfont)
3915                     debug((", (U+%04x)", alt_sum));
3916                 else
3917                     debug((", LCH(%d)", alt_sum));
3918             } else {
3919                 debug((", ACH(%d)", keys[0]));
3920             }
3921         } else if (r > 0) {
3922             int r1;
3923             debug((", ASC("));
3924             for (r1 = 0; r1 < r; r1++) {
3925                 debug(("%s%d", r1 ? "," : "", keys[r1]));
3926             }
3927             debug((")"));
3928         }
3929 #endif
3930         if (r > 0) {
3931             WCHAR keybuf;
3932
3933             /*
3934              * Interrupt an ongoing paste. I'm not sure this is
3935              * sensible, but for the moment it's preferable to
3936              * having to faff about buffering things.
3937              */
3938             term_nopaste(term);
3939
3940             p = output;
3941             for (i = 0; i < r; i++) {
3942                 unsigned char ch = (unsigned char) keys[i];
3943
3944                 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
3945                     compose_char = ch;
3946                     compose_state++;
3947                     continue;
3948                 }
3949                 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
3950                     int nc;
3951                     compose_state = 0;
3952
3953                     if ((nc = check_compose(compose_char, ch)) == -1) {
3954                         MessageBeep(MB_ICONHAND);
3955                         return 0;
3956                     }
3957                     keybuf = nc;
3958                     term_seen_key_event(term);
3959                     luni_send(ldisc, &keybuf, 1, 1);
3960                     continue;
3961                 }
3962
3963                 compose_state = 0;
3964
3965                 if (!key_down) {
3966                     if (alt_sum) {
3967                         if (in_utf(term) || ucsdata.dbcs_screenfont) {
3968                             keybuf = alt_sum;
3969                             term_seen_key_event(term);
3970                             luni_send(ldisc, &keybuf, 1, 1);
3971                         } else {
3972                             ch = (char) alt_sum;
3973                             /*
3974                              * We need not bother about stdin
3975                              * backlogs here, because in GUI PuTTY
3976                              * we can't do anything about it
3977                              * anyway; there's no means of asking
3978                              * Windows to hold off on KEYDOWN
3979                              * messages. We _have_ to buffer
3980                              * everything we're sent.
3981                              */
3982                             term_seen_key_event(term);
3983                             ldisc_send(ldisc, &ch, 1, 1);
3984                         }
3985                         alt_sum = 0;
3986                     } else {
3987                         term_seen_key_event(term);
3988                         lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
3989                     }
3990                 } else {
3991                     if(capsOn && ch < 0x80) {
3992                         WCHAR cbuf[2];
3993                         cbuf[0] = 27;
3994                         cbuf[1] = xlat_uskbd2cyrllic(ch);
3995                         term_seen_key_event(term);
3996                         luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
3997                     } else {
3998                         char cbuf[2];
3999                         cbuf[0] = '\033';
4000                         cbuf[1] = ch;
4001                         term_seen_key_event(term);
4002                         lpage_send(ldisc, kbd_codepage,
4003                                    cbuf+!left_alt, 1+!!left_alt, 1);
4004                     }
4005                 }
4006                 show_mouseptr(0);
4007             }
4008
4009             /* This is so the ALT-Numpad and dead keys work correctly. */
4010             keys[0] = 0;
4011
4012             return p - output;
4013         }
4014         /* If we're definitly not building up an ALT-54321 then clear it */
4015         if (!left_alt)
4016             keys[0] = 0;
4017         /* If we will be using alt_sum fix the 256s */
4018         else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
4019             keys[0] = 10;
4020     }
4021
4022     /*
4023      * ALT alone may or may not want to bring up the System menu.
4024      * If it's not meant to, we return 0 on presses or releases of
4025      * ALT, to show that we've swallowed the keystroke. Otherwise
4026      * we return -1, which means Windows will give the keystroke
4027      * its default handling (i.e. bring up the System menu).
4028      */
4029     if (wParam == VK_MENU && !cfg.alt_only)
4030         return 0;
4031
4032     return -1;
4033 }
4034
4035 void request_paste(void *frontend)
4036 {
4037     /*
4038      * In Windows, pasting is synchronous: we can read the
4039      * clipboard with no difficulty, so request_paste() can just go
4040      * ahead and paste.
4041      */
4042     term_do_paste(term);
4043 }
4044
4045 void set_title(void *frontend, char *title)
4046 {
4047     sfree(window_name);
4048     window_name = snewn(1 + strlen(title), char);
4049     strcpy(window_name, title);
4050     if (cfg.win_name_always || !IsIconic(hwnd))
4051         SetWindowText(hwnd, title);
4052 }
4053
4054 void set_icon(void *frontend, char *title)
4055 {
4056     sfree(icon_name);
4057     icon_name = snewn(1 + strlen(title), char);
4058     strcpy(icon_name, title);
4059     if (!cfg.win_name_always && IsIconic(hwnd))
4060         SetWindowText(hwnd, title);
4061 }
4062
4063 void set_sbar(void *frontend, int total, int start, int page)
4064 {
4065     SCROLLINFO si;
4066
4067     if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
4068         return;
4069
4070     si.cbSize = sizeof(si);
4071     si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
4072     si.nMin = 0;
4073     si.nMax = total - 1;
4074     si.nPage = page;
4075     si.nPos = start;
4076     if (hwnd)
4077         SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4078 }
4079
4080 Context get_ctx(void *frontend)
4081 {
4082     HDC hdc;
4083     if (hwnd) {
4084         hdc = GetDC(hwnd);
4085         if (hdc && pal)
4086             SelectPalette(hdc, pal, FALSE);
4087         return hdc;
4088     } else
4089         return NULL;
4090 }
4091
4092 void free_ctx(Context ctx)
4093 {
4094     SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4095     ReleaseDC(hwnd, ctx);
4096 }
4097
4098 static void real_palette_set(int n, int r, int g, int b)
4099 {
4100     if (pal) {
4101         logpal->palPalEntry[n].peRed = r;
4102         logpal->palPalEntry[n].peGreen = g;
4103         logpal->palPalEntry[n].peBlue = b;
4104         logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4105         colours[n] = PALETTERGB(r, g, b);
4106         SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
4107     } else
4108         colours[n] = RGB(r, g, b);
4109 }
4110
4111 void palette_set(void *frontend, int n, int r, int g, int b)
4112 {
4113     static const int first[21] = {
4114         0, 2, 4, 6, 8, 10, 12, 14,
4115         1, 3, 5, 7, 9, 11, 13, 15,
4116         16, 17, 18, 20, 22
4117     };
4118     real_palette_set(first[n], r, g, b);
4119     if (first[n] >= 18)
4120         real_palette_set(first[n] + 1, r, g, b);
4121     if (pal) {
4122         HDC hdc = get_ctx(frontend);
4123         UnrealizeObject(pal);
4124         RealizePalette(hdc);
4125         free_ctx(hdc);
4126     }
4127 }
4128
4129 void palette_reset(void *frontend)
4130 {
4131     int i;
4132
4133     for (i = 0; i < NCOLOURS; i++) {
4134         if (pal) {
4135             logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4136             logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4137             logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4138             logpal->palPalEntry[i].peFlags = 0;
4139             colours[i] = PALETTERGB(defpal[i].rgbtRed,
4140                                     defpal[i].rgbtGreen,
4141                                     defpal[i].rgbtBlue);
4142         } else
4143             colours[i] = RGB(defpal[i].rgbtRed,
4144                              defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4145     }
4146
4147     if (pal) {
4148         HDC hdc;
4149         SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
4150         hdc = get_ctx(frontend);
4151         RealizePalette(hdc);
4152         free_ctx(hdc);
4153     }
4154 }
4155
4156 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4157 {
4158     HGLOBAL clipdata;
4159     void *lock;
4160
4161     clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4162     if (!clipdata)
4163         return;
4164     lock = GlobalLock(clipdata);
4165     if (!lock)
4166         return;
4167     memcpy(lock, data, len);
4168     ((unsigned char *) lock)[len] = 0;
4169     GlobalUnlock(clipdata);
4170
4171     if (!must_deselect)
4172         SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4173
4174     if (OpenClipboard(hwnd)) {
4175         EmptyClipboard();
4176         SetClipboardData(CF_TEXT, clipdata);
4177         CloseClipboard();
4178     } else
4179         GlobalFree(clipdata);
4180
4181     if (!must_deselect)
4182         SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4183 }
4184
4185 /*
4186  * Note: unlike write_aclip() this will not append a nul.
4187  */
4188 void write_clip(void *frontend, wchar_t * data, int len, int must_deselect)
4189 {
4190     HGLOBAL clipdata, clipdata2, clipdata3;
4191     int len2;
4192     void *lock, *lock2, *lock3;
4193
4194     len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4195
4196     clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4197                            len * sizeof(wchar_t));
4198     clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4199
4200     if (!clipdata || !clipdata2) {
4201         if (clipdata)
4202             GlobalFree(clipdata);
4203         if (clipdata2)
4204             GlobalFree(clipdata2);
4205         return;
4206     }
4207     if (!(lock = GlobalLock(clipdata)))
4208         return;
4209     if (!(lock2 = GlobalLock(clipdata2)))
4210         return;
4211
4212     memcpy(lock, data, len * sizeof(wchar_t));
4213     WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4214
4215     if (cfg.rtf_paste) {
4216         wchar_t unitab[256];
4217         char *rtf = NULL;
4218         unsigned char *tdata = (unsigned char *)lock2;
4219         wchar_t *udata = (wchar_t *)lock;
4220         int rtflen = 0, uindex = 0, tindex = 0;
4221         int rtfsize = 0;
4222         int multilen, blen, alen, totallen, i;
4223         char before[16], after[4];
4224
4225         get_unitab(CP_ACP, unitab, 0);
4226
4227         rtfsize = 100 + strlen(cfg.font.name);
4228         rtf = snewn(rtfsize, char);
4229         sprintf(rtf, "{\\rtf1\\ansi%d{\\fonttbl\\f0\\fmodern %s;}\\f0",
4230                 GetACP(), cfg.font.name);
4231         rtflen = strlen(rtf);
4232
4233         /*
4234          * We want to construct a piece of RTF that specifies the
4235          * same Unicode text. To do this we will read back in
4236          * parallel from the Unicode data in `udata' and the
4237          * non-Unicode data in `tdata'. For each character in
4238          * `tdata' which becomes the right thing in `udata' when
4239          * looked up in `unitab', we just copy straight over from
4240          * tdata. For each one that doesn't, we must WCToMB it
4241          * individually and produce a \u escape sequence.
4242          * 
4243          * It would probably be more robust to just bite the bullet
4244          * and WCToMB each individual Unicode character one by one,
4245          * then MBToWC each one back to see if it was an accurate
4246          * translation; but that strikes me as a horrifying number
4247          * of Windows API calls so I want to see if this faster way
4248          * will work. If it screws up badly we can always revert to
4249          * the simple and slow way.
4250          */
4251         while (tindex < len2 && uindex < len &&
4252                tdata[tindex] && udata[uindex]) {
4253             if (tindex + 1 < len2 &&
4254                 tdata[tindex] == '\r' &&
4255                 tdata[tindex+1] == '\n') {
4256                 tindex++;
4257                 uindex++;
4258             }
4259             if (unitab[tdata[tindex]] == udata[uindex]) {
4260                 multilen = 1;
4261                 before[0] = '\0';
4262                 after[0] = '\0';
4263                 blen = alen = 0;
4264             } else {
4265                 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4266                                                NULL, 0, NULL, NULL);
4267                 if (multilen != 1) {
4268                     blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4269                                    udata[uindex]);
4270                     alen = 1; strcpy(after, "}");
4271                 } else {
4272                     blen = sprintf(before, "\\u%d", udata[uindex]);
4273                     alen = 0; after[0] = '\0';
4274                 }
4275             }
4276             assert(tindex + multilen <= len2);
4277             totallen = blen + alen;
4278             for (i = 0; i < multilen; i++) {
4279                 if (tdata[tindex+i] == '\\' ||
4280                     tdata[tindex+i] == '{' ||
4281                     tdata[tindex+i] == '}')
4282                     totallen += 2;
4283                 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4284                     totallen += 6;     /* \par\r\n */
4285                 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4286                     totallen += 4;
4287                 else
4288                     totallen++;
4289             }
4290
4291             if (rtfsize < rtflen + totallen + 3) {
4292                 rtfsize = rtflen + totallen + 512;
4293                 rtf = sresize(rtf, rtfsize, char);
4294             }
4295
4296             strcpy(rtf + rtflen, before); rtflen += blen;
4297             for (i = 0; i < multilen; i++) {
4298                 if (tdata[tindex+i] == '\\' ||
4299                     tdata[tindex+i] == '{' ||
4300                     tdata[tindex+i] == '}') {
4301                     rtf[rtflen++] = '\\';
4302                     rtf[rtflen++] = tdata[tindex+i];
4303                 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4304                     rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4305                 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4306                     rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4307                 } else {
4308                     rtf[rtflen++] = tdata[tindex+i];
4309                 }
4310             }
4311             strcpy(rtf + rtflen, after); rtflen += alen;
4312
4313             tindex += multilen;
4314             uindex++;
4315         }
4316
4317         strcpy(rtf + rtflen, "}");
4318         rtflen += 2;
4319
4320         clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4321         if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
4322             strcpy(lock3, rtf);
4323             GlobalUnlock(clipdata3);
4324         }
4325         sfree(rtf);
4326     } else
4327         clipdata3 = NULL;
4328
4329     GlobalUnlock(clipdata);
4330     GlobalUnlock(clipdata2);
4331
4332     if (!must_deselect)
4333         SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4334
4335     if (OpenClipboard(hwnd)) {
4336         EmptyClipboard();
4337         SetClipboardData(CF_UNICODETEXT, clipdata);
4338         SetClipboardData(CF_TEXT, clipdata2);
4339         if (clipdata3)
4340             SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4341         CloseClipboard();
4342     } else {
4343         GlobalFree(clipdata);
4344         GlobalFree(clipdata2);
4345     }
4346
4347     if (!must_deselect)
4348         SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4349 }
4350
4351 void get_clip(void *frontend, wchar_t ** p, int *len)
4352 {
4353     static HGLOBAL clipdata = NULL;
4354     static wchar_t *converted = 0;
4355     wchar_t *p2;
4356
4357     if (converted) {
4358         sfree(converted);
4359         converted = 0;
4360     }
4361     if (!p) {
4362         if (clipdata)
4363             GlobalUnlock(clipdata);
4364         clipdata = NULL;
4365         return;
4366     } else if (OpenClipboard(NULL)) {
4367         if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
4368             CloseClipboard();
4369             *p = GlobalLock(clipdata);
4370             if (*p) {
4371                 for (p2 = *p; *p2; p2++);
4372                 *len = p2 - *p;
4373                 return;
4374             }
4375         } else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
4376             char *s;
4377             int i;
4378             CloseClipboard();
4379             s = GlobalLock(clipdata);
4380             i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
4381             *p = converted = snewn(i, wchar_t);
4382             MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
4383             *len = i - 1;
4384             return;
4385         } else
4386             CloseClipboard();
4387     }
4388
4389     *p = NULL;
4390     *len = 0;
4391 }
4392
4393 #if 0
4394 /*
4395  * Move `lines' lines from position `from' to position `to' in the
4396  * window.
4397  */
4398 void optimised_move(void *frontend, int to, int from, int lines)
4399 {
4400     RECT r;
4401     int min, max;
4402
4403     min = (to < from ? to : from);
4404     max = to + from - min;
4405
4406     r.left = offset_width;
4407     r.right = offset_width + term->cols * font_width;
4408     r.top = offset_height + min * font_height;
4409     r.bottom = offset_height + (max + lines) * font_height;
4410     ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
4411 }
4412 #endif
4413
4414 /*
4415  * Print a message box and perform a fatal exit.
4416  */
4417 void fatalbox(char *fmt, ...)
4418 {
4419     va_list ap;
4420     char *stuff, morestuff[100];
4421
4422     va_start(ap, fmt);
4423     stuff = dupvprintf(fmt, ap);
4424     va_end(ap);
4425     sprintf(morestuff, "%.70s Fatal Error", appname);
4426     MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
4427     sfree(stuff);
4428     cleanup_exit(1);
4429 }
4430
4431 /*
4432  * Print a modal (Really Bad) message box and perform a fatal exit.
4433  */
4434 void modalfatalbox(char *fmt, ...)
4435 {
4436     va_list ap;
4437     char *stuff, morestuff[100];
4438
4439     va_start(ap, fmt);
4440     stuff = dupvprintf(fmt, ap);
4441     va_end(ap);
4442     sprintf(morestuff, "%.70s Fatal Error", appname);
4443     MessageBox(hwnd, stuff, morestuff,
4444                MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
4445     sfree(stuff);
4446     cleanup_exit(1);
4447 }
4448
4449 /*
4450  * Manage window caption / taskbar flashing, if enabled.
4451  * 0 = stop, 1 = maintain, 2 = start
4452  */
4453 static void flash_window(int mode)
4454 {
4455     static long last_flash = 0;
4456     static int flashing = 0;
4457     if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
4458         /* stop */
4459         if (flashing) {
4460             FlashWindow(hwnd, FALSE);
4461             flashing = 0;
4462         }
4463
4464     } else if (mode == 2) {
4465         /* start */
4466         if (!flashing) {
4467             last_flash = GetTickCount();
4468             flashing = 1;
4469             FlashWindow(hwnd, TRUE);
4470         }
4471
4472     } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
4473         /* maintain */
4474         if (flashing) {
4475             long now = GetTickCount();
4476             long fdiff = now - last_flash;
4477             if (fdiff < 0 || fdiff > 450) {
4478                 last_flash = now;
4479                 FlashWindow(hwnd, TRUE);        /* toggle */
4480             }
4481         }
4482     }
4483 }
4484
4485 /*
4486  * Beep.
4487  */
4488 void beep(void *frontend, int mode)
4489 {
4490     if (mode == BELL_DEFAULT) {
4491         /*
4492          * For MessageBeep style bells, we want to be careful of
4493          * timing, because they don't have the nice property of
4494          * PlaySound bells that each one cancels the previous
4495          * active one. So we limit the rate to one per 50ms or so.
4496          */
4497         static long lastbeep = 0;
4498         long beepdiff;
4499
4500         beepdiff = GetTickCount() - lastbeep;
4501         if (beepdiff >= 0 && beepdiff < 50)
4502             return;
4503         MessageBeep(MB_OK);
4504         /*
4505          * The above MessageBeep call takes time, so we record the
4506          * time _after_ it finishes rather than before it starts.
4507          */
4508         lastbeep = GetTickCount();
4509     } else if (mode == BELL_WAVEFILE) {
4510         if (!PlaySound(cfg.bell_wavefile.path, NULL,
4511                        SND_ASYNC | SND_FILENAME)) {
4512             char buf[sizeof(cfg.bell_wavefile.path) + 80];
4513             char otherbuf[100];
4514             sprintf(buf, "Unable to play sound file\n%s\n"
4515                     "Using default sound instead", cfg.bell_wavefile.path);
4516             sprintf(otherbuf, "%.70s Sound Error", appname);
4517             MessageBox(hwnd, buf, otherbuf,
4518                        MB_OK | MB_ICONEXCLAMATION);
4519             cfg.beep = BELL_DEFAULT;
4520         }
4521     } else if (mode == BELL_PCSPEAKER) {
4522         static long lastbeep = 0;
4523         long beepdiff;
4524
4525         beepdiff = GetTickCount() - lastbeep;
4526         if (beepdiff >= 0 && beepdiff < 50)
4527             return;
4528
4529         /*
4530          * We must beep in different ways depending on whether this
4531          * is a 95-series or NT-series OS.
4532          */
4533         if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
4534             Beep(800, 100);
4535         else
4536             MessageBeep(-1);
4537         lastbeep = GetTickCount();
4538     }
4539     /* Otherwise, either visual bell or disabled; do nothing here */
4540     if (!term->has_focus) {
4541         flash_window(2);               /* start */
4542     }
4543 }
4544
4545 /*
4546  * Minimise or restore the window in response to a server-side
4547  * request.
4548  */
4549 void set_iconic(void *frontend, int iconic)
4550 {
4551     if (IsIconic(hwnd)) {
4552         if (!iconic)
4553             ShowWindow(hwnd, SW_RESTORE);
4554     } else {
4555         if (iconic)
4556             ShowWindow(hwnd, SW_MINIMIZE);
4557     }
4558 }
4559
4560 /*
4561  * Move the window in response to a server-side request.
4562  */
4563 void move_window(void *frontend, int x, int y)
4564 {
4565     if (cfg.resize_action == RESIZE_DISABLED || 
4566         cfg.resize_action == RESIZE_FONT ||
4567         IsZoomed(hwnd))
4568        return;
4569
4570     SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
4571 }
4572
4573 /*
4574  * Move the window to the top or bottom of the z-order in response
4575  * to a server-side request.
4576  */
4577 void set_zorder(void *frontend, int top)
4578 {
4579     if (cfg.alwaysontop)
4580         return;                        /* ignore */
4581     SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
4582                  SWP_NOMOVE | SWP_NOSIZE);
4583 }
4584
4585 /*
4586  * Refresh the window in response to a server-side request.
4587  */
4588 void refresh_window(void *frontend)
4589 {
4590     InvalidateRect(hwnd, NULL, TRUE);
4591 }
4592
4593 /*
4594  * Maximise or restore the window in response to a server-side
4595  * request.
4596  */
4597 void set_zoomed(void *frontend, int zoomed)
4598 {
4599     if (IsZoomed(hwnd)) {
4600         if (!zoomed)
4601             ShowWindow(hwnd, SW_RESTORE);
4602     } else {
4603         if (zoomed)
4604             ShowWindow(hwnd, SW_MAXIMIZE);
4605     }
4606 }
4607
4608 /*
4609  * Report whether the window is iconic, for terminal reports.
4610  */
4611 int is_iconic(void *frontend)
4612 {
4613     return IsIconic(hwnd);
4614 }
4615
4616 /*
4617  * Report the window's position, for terminal reports.
4618  */
4619 void get_window_pos(void *frontend, int *x, int *y)
4620 {
4621     RECT r;
4622     GetWindowRect(hwnd, &r);
4623     *x = r.left;
4624     *y = r.top;
4625 }
4626
4627 /*
4628  * Report the window's pixel size, for terminal reports.
4629  */
4630 void get_window_pixels(void *frontend, int *x, int *y)
4631 {
4632     RECT r;
4633     GetWindowRect(hwnd, &r);
4634     *x = r.right - r.left;
4635     *y = r.bottom - r.top;
4636 }
4637
4638 /*
4639  * Return the window or icon title.
4640  */
4641 char *get_window_title(void *frontend, int icon)
4642 {
4643     return icon ? icon_name : window_name;
4644 }
4645
4646 /*
4647  * See if we're in full-screen mode.
4648  */
4649 static int is_full_screen()
4650 {
4651     if (!IsZoomed(hwnd))
4652         return FALSE;
4653     if (GetWindowLong(hwnd, GWL_STYLE) & WS_CAPTION)
4654         return FALSE;
4655     return TRUE;
4656 }
4657
4658 /* Get the rect/size of a full screen window using the nearest available
4659  * monitor in multimon systems; default to something sensible if only
4660  * one monitor is present. */
4661 static int get_fullscreen_rect(RECT * ss)
4662 {
4663 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
4664         HMONITOR mon;
4665         MONITORINFO mi;
4666         mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
4667         mi.cbSize = sizeof(mi);
4668         GetMonitorInfo(mon, &mi);
4669
4670         /* structure copy */
4671         *ss = mi.rcMonitor;
4672         return TRUE;
4673 #else
4674 /* could also use code like this:
4675         ss->left = ss->top = 0;
4676         ss->right = GetSystemMetrics(SM_CXSCREEN);
4677         ss->bottom = GetSystemMetrics(SM_CYSCREEN);
4678 */ 
4679         return GetClientRect(GetDesktopWindow(), ss);
4680 #endif
4681 }
4682
4683
4684 /*
4685  * Go full-screen. This should only be called when we are already
4686  * maximised.
4687  */
4688 static void make_full_screen()
4689 {
4690     DWORD style;
4691         RECT ss;
4692
4693     assert(IsZoomed(hwnd));
4694
4695         if (is_full_screen())
4696                 return;
4697         
4698     /* Remove the window furniture. */
4699     style = GetWindowLong(hwnd, GWL_STYLE);
4700     style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
4701     if (cfg.scrollbar_in_fullscreen)
4702         style |= WS_VSCROLL;
4703     else
4704         style &= ~WS_VSCROLL;
4705     SetWindowLong(hwnd, GWL_STYLE, style);
4706
4707     /* Resize ourselves to exactly cover the nearest monitor. */
4708         get_fullscreen_rect(&ss);
4709     SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
4710                         ss.right - ss.left,
4711                         ss.bottom - ss.top,
4712                         SWP_FRAMECHANGED);
4713
4714     /* Tick the menu item in the System menu. */
4715     CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4716                   MF_CHECKED);
4717 }
4718
4719 /*
4720  * Clear the full-screen attributes.
4721  */
4722 static void clear_full_screen()
4723 {
4724     DWORD oldstyle, style;
4725
4726     /* Reinstate the window furniture. */
4727     style = oldstyle = GetWindowLong(hwnd, GWL_STYLE);
4728     style |= WS_CAPTION | WS_BORDER;
4729     if (cfg.resize_action == RESIZE_DISABLED)
4730         style &= ~WS_THICKFRAME;
4731     else
4732         style |= WS_THICKFRAME;
4733     if (cfg.scrollbar)
4734         style |= WS_VSCROLL;
4735     else
4736         style &= ~WS_VSCROLL;
4737     if (style != oldstyle) {
4738         SetWindowLong(hwnd, GWL_STYLE, style);
4739         SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
4740                      SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
4741                      SWP_FRAMECHANGED);
4742     }
4743
4744     /* Untick the menu item in the System menu. */
4745     CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4746                   MF_UNCHECKED);
4747 }
4748
4749 /*
4750  * Toggle full-screen mode.
4751  */
4752 static void flip_full_screen()
4753 {
4754     if (is_full_screen()) {
4755         ShowWindow(hwnd, SW_RESTORE);
4756     } else if (IsZoomed(hwnd)) {
4757         make_full_screen();
4758     } else {
4759         SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
4760         ShowWindow(hwnd, SW_MAXIMIZE);
4761     }
4762 }
4763
4764 void frontend_keypress(void *handle)
4765 {
4766     /*
4767      * Keypress termination in non-Close-On-Exit mode is not
4768      * currently supported in PuTTY proper, because the window
4769      * always has a perfectly good Close button anyway. So we do
4770      * nothing here.
4771      */
4772     return;
4773 }
4774
4775 int from_backend(void *frontend, int is_stderr, const char *data, int len)
4776 {
4777     return term_data(term, is_stderr, data, len);
4778 }
4779
4780 void agent_schedule_callback(void (*callback)(void *, void *, int),
4781                              void *callback_ctx, void *data, int len)
4782 {
4783     struct agent_callback *c = snew(struct agent_callback);
4784     c->callback = callback;
4785     c->callback_ctx = callback_ctx;
4786     c->data = data;
4787     c->len = len;
4788     PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);
4789 }