]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - window.c
Idiot me! store_host_key() was blindly _appending_ new host keys to
[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 static int specials_menu_position;
114
115 static struct {
116     HMENU menu;
117     int specials_submenu_pos;
118 } popup_menus[2];
119 enum { SYSMENU, CTXMENU };
120
121 Config cfg;                            /* exported to windlg.c */
122
123 extern struct sesslist sesslist;       /* imported from windlg.c */
124
125 struct agent_callback {
126     void (*callback)(void *, void *, int);
127     void *callback_ctx;
128     void *data;
129     int len;
130 };
131
132 #define FONT_NORMAL 0
133 #define FONT_BOLD 1
134 #define FONT_UNDERLINE 2
135 #define FONT_BOLDUND 3
136 #define FONT_WIDE       0x04
137 #define FONT_HIGH       0x08
138 #define FONT_NARROW     0x10
139
140 #define FONT_OEM        0x20
141 #define FONT_OEMBOLD    0x21
142 #define FONT_OEMUND     0x22
143 #define FONT_OEMBOLDUND 0x23
144
145 #define FONT_MAXNO      0x2F
146 #define FONT_SHIFT      5
147 static HFONT fonts[FONT_MAXNO];
148 static LOGFONT lfont;
149 static int fontflag[FONT_MAXNO];
150 static enum {
151     BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT
152 } bold_mode;
153 static enum {
154     UND_LINE, UND_FONT
155 } und_mode;
156 static int descent;
157
158 #define NCOLOURS 24
159 static COLORREF colours[NCOLOURS];
160 static HPALETTE pal;
161 static LPLOGPALETTE logpal;
162 static RGBTRIPLE defpal[NCOLOURS];
163
164 static HWND hwnd;
165
166 static HBITMAP caretbm;
167
168 static int dbltime, lasttime, lastact;
169 static Mouse_Button lastbtn;
170
171 /* this allows xterm-style mouse handling. */
172 static int send_raw_mouse = 0;
173 static int wheel_accumulator = 0;
174
175 static char *window_name, *icon_name;
176
177 static int compose_state = 0;
178
179 static UINT wm_mousewheel = WM_MOUSEWHEEL;
180
181 /* Dummy routine, only required in plink. */
182 void ldisc_update(void *frontend, int echo, int edit)
183 {
184 }
185
186 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show)
187 {
188     WNDCLASS wndclass;
189     MSG msg;
190     int guess_width, guess_height;
191
192     hinst = inst;
193     flags = FLAG_VERBOSE | FLAG_INTERACTIVE;
194
195     sk_init();
196
197     InitCommonControls();
198
199     /* Ensure a Maximize setting in Explorer doesn't maximise the
200      * config box. */
201     defuse_showwindow();
202
203     if (!init_winver())
204     {
205         char *str = dupprintf("%s Fatal Error", appname);
206         MessageBox(NULL, "Windows refuses to report a version",
207                    str, MB_OK | MB_ICONEXCLAMATION);
208         sfree(str);
209         return 1;
210     }
211
212     /*
213      * If we're running a version of Windows that doesn't support
214      * WM_MOUSEWHEEL, find out what message number we should be
215      * using instead.
216      */
217     if (osVersion.dwMajorVersion < 4 ||
218         (osVersion.dwMajorVersion == 4 && 
219          osVersion.dwPlatformId != VER_PLATFORM_WIN32_NT))
220         wm_mousewheel = RegisterWindowMessage("MSWHEEL_ROLLMSG");
221
222     /*
223      * See if we can find our Help file.
224      */
225     {
226         char b[2048], *p, *q, *r;
227         FILE *fp;
228         GetModuleFileName(NULL, b, sizeof(b) - 1);
229         r = b;
230         p = strrchr(b, '\\');
231         if (p && p >= r) r = p+1;
232         q = strrchr(b, ':');
233         if (q && q >= r) r = q+1;
234         strcpy(r, "putty.hlp");
235         if ( (fp = fopen(b, "r")) != NULL) {
236             help_path = dupstr(b);
237             fclose(fp);
238         } else
239             help_path = NULL;
240         strcpy(r, "putty.cnt");
241         if ( (fp = fopen(b, "r")) != NULL) {
242             help_has_contents = TRUE;
243             fclose(fp);
244         } else
245             help_has_contents = FALSE;
246     }
247
248     /*
249      * Process the command line.
250      */
251     {
252         char *p;
253         int got_host = 0;
254
255         default_protocol = be_default_protocol;
256         /* Find the appropriate default port. */
257         {
258             int i;
259             default_port = 0; /* illegal */
260             for (i = 0; backends[i].backend != NULL; i++)
261                 if (backends[i].protocol == default_protocol) {
262                     default_port = backends[i].backend->default_port;
263                     break;
264                 }
265         }
266         cfg.logtype = LGTYP_NONE;
267
268         do_defaults(NULL, &cfg);
269
270         p = cmdline;
271
272         /*
273          * Process a couple of command-line options which are more
274          * easily dealt with before the line is broken up into
275          * words. These are the soon-to-be-defunct @sessionname and
276          * the internal-use-only &sharedmemoryhandle, neither of
277          * which are combined with anything else.
278          */
279         while (*p && isspace(*p))
280             p++;
281         if (*p == '@') {
282             int i = strlen(p);
283             while (i > 1 && isspace(p[i - 1]))
284                 i--;
285             p[i] = '\0';
286             do_defaults(p + 1, &cfg);
287             if (!*cfg.host && !do_config()) {
288                 cleanup_exit(0);
289             }
290         } else if (*p == '&') {
291             /*
292              * An initial & means we've been given a command line
293              * containing the hex value of a HANDLE for a file
294              * mapping object, which we must then extract as a
295              * config.
296              */
297             HANDLE filemap;
298             Config *cp;
299             if (sscanf(p + 1, "%p", &filemap) == 1 &&
300                 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
301                                     0, 0, sizeof(Config))) != NULL) {
302                 cfg = *cp;
303                 UnmapViewOfFile(cp);
304                 CloseHandle(filemap);
305             } else if (!do_config()) {
306                 cleanup_exit(0);
307             }
308         } else {
309             /*
310              * Otherwise, break up the command line and deal with
311              * it sensibly.
312              */
313             int argc, i;
314             char **argv;
315             
316             split_into_argv(cmdline, &argc, &argv, NULL);
317
318             for (i = 0; i < argc; i++) {
319                 char *p = argv[i];
320                 int ret;
321
322                 ret = cmdline_process_param(p, i+1<argc?argv[i+1]:NULL,
323                                             1, &cfg);
324                 if (ret == -2) {
325                     cmdline_error("option \"%s\" requires an argument", p);
326                 } else if (ret == 2) {
327                     i++;               /* skip next argument */
328                 } else if (ret == 1) {
329                     continue;          /* nothing further needs doing */
330                 } else if (!strcmp(p, "-cleanup")) {
331                     /*
332                      * `putty -cleanup'. Remove all registry
333                      * entries associated with PuTTY, and also find
334                      * and delete the random seed file.
335                      */
336                     char *s1, *s2;
337                     s1 = dupprintf("This procedure will remove ALL Registry\n"
338                                    "entries associated with %s, and will\n"
339                                    "also remove the random seed file.\n"
340                                    "\n"
341                                    "THIS PROCESS WILL DESTROY YOUR SAVED\n"
342                                    "SESSIONS. Are you really sure you want\n"
343                                    "to continue?", appname);
344                     s2 = dupprintf("%s Warning", appname);
345                     if (MessageBox(NULL, s1, s2,
346                                    MB_YESNO | MB_ICONWARNING) == IDYES) {
347                         cleanup_all();
348                     }
349                     sfree(s1);
350                     sfree(s2);
351                     exit(0);
352                 } else if (*p != '-') {
353                     char *q = p;
354                     if (got_host) {
355                         /*
356                          * If we already have a host name, treat
357                          * this argument as a port number. NB we
358                          * have to treat this as a saved -P
359                          * argument, so that it will be deferred
360                          * until it's a good moment to run it.
361                          */
362                         int ret = cmdline_process_param("-P", p, 1, &cfg);
363                         assert(ret == 2);
364                     } else if (!strncmp(q, "telnet:", 7)) {
365                         /*
366                          * If the hostname starts with "telnet:",
367                          * set the protocol to Telnet and process
368                          * the string as a Telnet URL.
369                          */
370                         char c;
371
372                         q += 7;
373                         if (q[0] == '/' && q[1] == '/')
374                             q += 2;
375                         cfg.protocol = PROT_TELNET;
376                         p = q;
377                         while (*p && *p != ':' && *p != '/')
378                             p++;
379                         c = *p;
380                         if (*p)
381                             *p++ = '\0';
382                         if (c == ':')
383                             cfg.port = atoi(p);
384                         else
385                             cfg.port = -1;
386                         strncpy(cfg.host, q, sizeof(cfg.host) - 1);
387                         cfg.host[sizeof(cfg.host) - 1] = '\0';
388                         got_host = 1;
389                     } else {
390                         /*
391                          * Otherwise, treat this argument as a host
392                          * name.
393                          */
394                         while (*p && !isspace(*p))
395                             p++;
396                         if (*p)
397                             *p++ = '\0';
398                         strncpy(cfg.host, q, sizeof(cfg.host) - 1);
399                         cfg.host[sizeof(cfg.host) - 1] = '\0';
400                         got_host = 1;
401                     }
402                 } else {
403                     cmdline_error("unknown option \"%s\"", p);
404                 }
405             }
406         }
407
408         cmdline_run_saved(&cfg);
409
410         if (!*cfg.host && !do_config()) {
411             cleanup_exit(0);
412         }
413
414         /*
415          * Trim leading whitespace off the hostname if it's there.
416          */
417         {
418             int space = strspn(cfg.host, " \t");
419             memmove(cfg.host, cfg.host+space, 1+strlen(cfg.host)-space);
420         }
421
422         /* See if host is of the form user@host */
423         if (cfg.host[0] != '\0') {
424             char *atsign = strchr(cfg.host, '@');
425             /* Make sure we're not overflowing the user field */
426             if (atsign) {
427                 if (atsign - cfg.host < sizeof cfg.username) {
428                     strncpy(cfg.username, cfg.host, atsign - cfg.host);
429                     cfg.username[atsign - cfg.host] = '\0';
430                 }
431                 memmove(cfg.host, atsign + 1, 1 + strlen(atsign + 1));
432             }
433         }
434
435         /*
436          * Trim a colon suffix off the hostname if it's there.
437          */
438         cfg.host[strcspn(cfg.host, ":")] = '\0';
439
440         /*
441          * Remove any remaining whitespace from the hostname.
442          */
443         {
444             int p1 = 0, p2 = 0;
445             while (cfg.host[p2] != '\0') {
446                 if (cfg.host[p2] != ' ' && cfg.host[p2] != '\t') {
447                     cfg.host[p1] = cfg.host[p2];
448                     p1++;
449                 }
450                 p2++;
451             }
452             cfg.host[p1] = '\0';
453         }
454     }
455
456     /*
457      * Select protocol. This is farmed out into a table in a
458      * separate file to enable an ssh-free variant.
459      */
460     {
461         int i;
462         back = NULL;
463         for (i = 0; backends[i].backend != NULL; i++)
464             if (backends[i].protocol == cfg.protocol) {
465                 back = backends[i].backend;
466                 break;
467             }
468         if (back == NULL) {
469             char *str = dupprintf("%s Internal Error", appname);
470             MessageBox(NULL, "Unsupported protocol number found",
471                        str, MB_OK | MB_ICONEXCLAMATION);
472             sfree(str);
473             cleanup_exit(1);
474         }
475     }
476
477     /* Check for invalid Port number (i.e. zero) */
478     if (cfg.port == 0) {
479         char *str = dupprintf("%s Internal Error", appname);
480         MessageBox(NULL, "Invalid Port Number",
481                    str, MB_OK | MB_ICONEXCLAMATION);
482         sfree(str);
483         cleanup_exit(1);
484     }
485
486     if (!prev) {
487         wndclass.style = 0;
488         wndclass.lpfnWndProc = WndProc;
489         wndclass.cbClsExtra = 0;
490         wndclass.cbWndExtra = 0;
491         wndclass.hInstance = inst;
492         wndclass.hIcon = LoadIcon(inst, MAKEINTRESOURCE(IDI_MAINICON));
493         wndclass.hCursor = LoadCursor(NULL, IDC_IBEAM);
494         wndclass.hbrBackground = NULL;
495         wndclass.lpszMenuName = NULL;
496         wndclass.lpszClassName = appname;
497
498         RegisterClass(&wndclass);
499     }
500
501     hwnd = NULL;
502
503     memset(&ucsdata, 0, sizeof(ucsdata));
504
505     term = term_init(&cfg, &ucsdata, NULL);
506     logctx = log_init(NULL, &cfg);
507     term_provide_logctx(term, logctx);
508
509     cfgtopalette();
510
511     /*
512      * Guess some defaults for the window size. This all gets
513      * updated later, so we don't really care too much. However, we
514      * do want the font width/height guesses to correspond to a
515      * large font rather than a small one...
516      */
517
518     font_width = 10;
519     font_height = 20;
520     extra_width = 25;
521     extra_height = 28;
522     term_size(term, cfg.height, cfg.width, cfg.savelines);
523     guess_width = extra_width + font_width * term->cols;
524     guess_height = extra_height + font_height * term->rows;
525     {
526         RECT r;
527                 get_fullscreen_rect(&r);
528         if (guess_width > r.right - r.left)
529             guess_width = r.right - r.left;
530         if (guess_height > r.bottom - r.top)
531             guess_height = r.bottom - r.top;
532     }
533
534     {
535         int winmode = WS_OVERLAPPEDWINDOW | WS_VSCROLL;
536         int exwinmode = 0;
537         if (!cfg.scrollbar)
538             winmode &= ~(WS_VSCROLL);
539         if (cfg.resize_action == RESIZE_DISABLED)
540             winmode &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
541         if (cfg.alwaysontop)
542             exwinmode |= WS_EX_TOPMOST;
543         if (cfg.sunken_edge)
544             exwinmode |= WS_EX_CLIENTEDGE;
545         hwnd = CreateWindowEx(exwinmode, appname, appname,
546                               winmode, CW_USEDEFAULT, CW_USEDEFAULT,
547                               guess_width, guess_height,
548                               NULL, NULL, inst, NULL);
549     }
550
551     /*
552      * Initialise the fonts, simultaneously correcting the guesses
553      * for font_{width,height}.
554      */
555     init_fonts(0,0);
556
557     /*
558      * Correct the guesses for extra_{width,height}.
559      */
560     {
561         RECT cr, wr;
562         GetWindowRect(hwnd, &wr);
563         GetClientRect(hwnd, &cr);
564         offset_width = offset_height = cfg.window_border;
565         extra_width = wr.right - wr.left - cr.right + cr.left + offset_width*2;
566         extra_height = wr.bottom - wr.top - cr.bottom + cr.top +offset_height*2;
567     }
568
569     /*
570      * Resize the window, now we know what size we _really_ want it
571      * to be.
572      */
573     guess_width = extra_width + font_width * term->cols;
574     guess_height = extra_height + font_height * term->rows;
575     SetWindowPos(hwnd, NULL, 0, 0, guess_width, guess_height,
576                  SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
577
578     /*
579      * Set up a caret bitmap, with no content.
580      */
581     {
582         char *bits;
583         int size = (font_width + 15) / 16 * 2 * font_height;
584         bits = snewn(size, char);
585         memset(bits, 0, size);
586         caretbm = CreateBitmap(font_width, font_height, 1, 1, bits);
587         sfree(bits);
588     }
589     CreateCaret(hwnd, caretbm, font_width, font_height);
590
591     /*
592      * Initialise the scroll bar.
593      */
594     {
595         SCROLLINFO si;
596
597         si.cbSize = sizeof(si);
598         si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
599         si.nMin = 0;
600         si.nMax = term->rows - 1;
601         si.nPage = term->rows;
602         si.nPos = 0;
603         SetScrollInfo(hwnd, SB_VERT, &si, FALSE);
604     }
605
606     /*
607      * Start up the telnet connection.
608      */
609     {
610         const char *error;
611         char msg[1024], *title;
612         char *realhost;
613
614         error = back->init(NULL, &backhandle, &cfg,
615                            cfg.host, cfg.port, &realhost, cfg.tcp_nodelay);
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
1695     switch (message) {
1696       case WM_TIMER:
1697         if (pending_netevent)
1698             enact_pending_netevent();
1699         if (GetCapture() != hwnd || 
1700             (send_raw_mouse && !(cfg.mouse_override && is_shift_pressed())))
1701             term_out(term);
1702         noise_regular();
1703         HideCaret(hwnd);
1704         term_update(term);
1705         ShowCaret(hwnd);
1706         if (cfg.ping_interval > 0) {
1707             time_t now;
1708             time(&now);
1709             if (now - last_movement > cfg.ping_interval) {
1710                 back->special(backhandle, TS_PING);
1711                 last_movement = now;
1712             }
1713         }
1714         net_pending_errors();
1715         return 0;
1716       case WM_CREATE:
1717         break;
1718       case WM_CLOSE:
1719         {
1720             char *str;
1721             show_mouseptr(1);
1722             str = dupprintf("%s Exit Confirmation", appname);
1723             if (!cfg.warn_on_close || session_closed ||
1724                 MessageBox(hwnd,
1725                            "Are you sure you want to close this session?",
1726                            str, MB_ICONWARNING | MB_OKCANCEL) == IDOK)
1727                 DestroyWindow(hwnd);
1728             sfree(str);
1729         }
1730         return 0;
1731       case WM_DESTROY:
1732         show_mouseptr(1);
1733         PostQuitMessage(0);
1734         return 0;
1735       case WM_COMMAND:
1736       case WM_SYSCOMMAND:
1737         switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
1738           case IDM_SHOWLOG:
1739             showeventlog(hwnd);
1740             break;
1741           case IDM_NEWSESS:
1742           case IDM_DUPSESS:
1743           case IDM_SAVEDSESS:
1744             {
1745                 char b[2048];
1746                 char c[30], *cl;
1747                 int freecl = FALSE;
1748                 STARTUPINFO si;
1749                 PROCESS_INFORMATION pi;
1750                 HANDLE filemap = NULL;
1751
1752                 if (wParam == IDM_DUPSESS) {
1753                     /*
1754                      * Allocate a file-mapping memory chunk for the
1755                      * config structure.
1756                      */
1757                     SECURITY_ATTRIBUTES sa;
1758                     Config *p;
1759
1760                     sa.nLength = sizeof(sa);
1761                     sa.lpSecurityDescriptor = NULL;
1762                     sa.bInheritHandle = TRUE;
1763                     filemap = CreateFileMapping((HANDLE) 0xFFFFFFFF,
1764                                                 &sa,
1765                                                 PAGE_READWRITE,
1766                                                 0, sizeof(Config), NULL);
1767                     if (filemap) {
1768                         p = (Config *) MapViewOfFile(filemap,
1769                                                      FILE_MAP_WRITE,
1770                                                      0, 0, sizeof(Config));
1771                         if (p) {
1772                             *p = cfg;  /* structure copy */
1773                             UnmapViewOfFile(p);
1774                         }
1775                     }
1776                     sprintf(c, "putty &%p", filemap);
1777                     cl = c;
1778                 } else if (wParam == IDM_SAVEDSESS) {
1779                     if ((lParam - IDM_SAVED_MIN) / 16 < sesslist.nsessions) {
1780                         char *session =
1781                             sesslist.sessions[(lParam - IDM_SAVED_MIN) / 16];
1782                         cl = snewn(16 + strlen(session), char);
1783                                        /* 8, but play safe */
1784                         if (!cl)
1785                             cl = NULL;    
1786                                        /* not a very important failure mode */
1787                         else {
1788                             sprintf(cl, "putty @%s", session);
1789                             freecl = TRUE;
1790                         }
1791                     } else
1792                         break;
1793                 } else
1794                     cl = NULL;
1795
1796                 GetModuleFileName(NULL, b, sizeof(b) - 1);
1797                 si.cb = sizeof(si);
1798                 si.lpReserved = NULL;
1799                 si.lpDesktop = NULL;
1800                 si.lpTitle = NULL;
1801                 si.dwFlags = 0;
1802                 si.cbReserved2 = 0;
1803                 si.lpReserved2 = NULL;
1804                 CreateProcess(b, cl, NULL, NULL, TRUE,
1805                               NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
1806
1807                 if (filemap)
1808                     CloseHandle(filemap);
1809                 if (freecl)
1810                     sfree(cl);
1811             }
1812             break;
1813           case IDM_RECONF:
1814             {
1815                 Config prev_cfg;
1816                 int init_lvl = 1;
1817
1818                 GetWindowText(hwnd, cfg.wintitle, sizeof(cfg.wintitle));
1819                 prev_cfg = cfg;
1820
1821                 if (!do_reconfig(hwnd))
1822                     break;
1823
1824                 {
1825                     /* Disable full-screen if resizing forbidden */
1826                     HMENU m = GetSystemMenu (hwnd, FALSE);
1827                     EnableMenuItem(m, IDM_FULLSCREEN, MF_BYCOMMAND | 
1828                                    (cfg.resize_action == RESIZE_DISABLED)
1829                                    ? MF_GRAYED : MF_ENABLED);
1830                     /* Gracefully unzoom if necessary */
1831                     if (IsZoomed(hwnd) &&
1832                         (cfg.resize_action == RESIZE_DISABLED)) {
1833                         ShowWindow(hwnd, SW_RESTORE);
1834                     }
1835                 }
1836
1837                 /* Pass new config data to the logging module */
1838                 log_reconfig(logctx, &cfg);
1839
1840                 sfree(logpal);
1841                 /*
1842                  * Flush the line discipline's edit buffer in the
1843                  * case where local editing has just been disabled.
1844                  */
1845                 ldisc_send(ldisc, NULL, 0, 0);
1846                 if (pal)
1847                     DeleteObject(pal);
1848                 logpal = NULL;
1849                 pal = NULL;
1850                 cfgtopalette();
1851                 init_palette();
1852
1853                 /* Pass new config data to the terminal */
1854                 term_reconfig(term, &cfg);
1855
1856                 /* Pass new config data to the back end */
1857                 back->reconfig(backhandle, &cfg);
1858
1859                 /* Screen size changed ? */
1860                 if (cfg.height != prev_cfg.height ||
1861                     cfg.width != prev_cfg.width ||
1862                     cfg.savelines != prev_cfg.savelines ||
1863                     cfg.resize_action == RESIZE_FONT ||
1864                     (cfg.resize_action == RESIZE_EITHER && IsZoomed(hwnd)) ||
1865                     cfg.resize_action == RESIZE_DISABLED)
1866                     term_size(term, cfg.height, cfg.width, cfg.savelines);
1867
1868                 /* Enable or disable the scroll bar, etc */
1869                 {
1870                     LONG nflg, flag = GetWindowLong(hwnd, GWL_STYLE);
1871                     LONG nexflag, exflag =
1872                         GetWindowLong(hwnd, GWL_EXSTYLE);
1873
1874                     nexflag = exflag;
1875                     if (cfg.alwaysontop != prev_cfg.alwaysontop) {
1876                         if (cfg.alwaysontop) {
1877                             nexflag |= WS_EX_TOPMOST;
1878                             SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0,
1879                                          SWP_NOMOVE | SWP_NOSIZE);
1880                         } else {
1881                             nexflag &= ~(WS_EX_TOPMOST);
1882                             SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0,
1883                                          SWP_NOMOVE | SWP_NOSIZE);
1884                         }
1885                     }
1886                     if (cfg.sunken_edge)
1887                         nexflag |= WS_EX_CLIENTEDGE;
1888                     else
1889                         nexflag &= ~(WS_EX_CLIENTEDGE);
1890
1891                     nflg = flag;
1892                     if (is_full_screen() ?
1893                         cfg.scrollbar_in_fullscreen : cfg.scrollbar)
1894                         nflg |= WS_VSCROLL;
1895                     else
1896                         nflg &= ~WS_VSCROLL;
1897
1898                     if (cfg.resize_action == RESIZE_DISABLED ||
1899                         is_full_screen())
1900                         nflg &= ~WS_THICKFRAME;
1901                     else
1902                         nflg |= WS_THICKFRAME;
1903
1904                     if (cfg.resize_action == RESIZE_DISABLED)
1905                         nflg &= ~WS_MAXIMIZEBOX;
1906                     else
1907                         nflg |= WS_MAXIMIZEBOX;
1908
1909                     if (nflg != flag || nexflag != exflag) {
1910                         if (nflg != flag)
1911                             SetWindowLong(hwnd, GWL_STYLE, nflg);
1912                         if (nexflag != exflag)
1913                             SetWindowLong(hwnd, GWL_EXSTYLE, nexflag);
1914
1915                         SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
1916                                      SWP_NOACTIVATE | SWP_NOCOPYBITS |
1917                                      SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
1918                                      SWP_FRAMECHANGED);
1919
1920                         init_lvl = 2;
1921                     }
1922                 }
1923
1924                 /* Oops */
1925                 if (cfg.resize_action == RESIZE_DISABLED && IsZoomed(hwnd)) {
1926                     force_normal(hwnd);
1927                     init_lvl = 2;
1928                 }
1929
1930                 set_title(NULL, cfg.wintitle);
1931                 if (IsIconic(hwnd)) {
1932                     SetWindowText(hwnd,
1933                                   cfg.win_name_always ? window_name :
1934                                   icon_name);
1935                 }
1936
1937                 if (strcmp(cfg.font.name, prev_cfg.font.name) != 0 ||
1938                     strcmp(cfg.line_codepage, prev_cfg.line_codepage) != 0 ||
1939                     cfg.font.isbold != prev_cfg.font.isbold ||
1940                     cfg.font.height != prev_cfg.font.height ||
1941                     cfg.font.charset != prev_cfg.font.charset ||
1942                     cfg.vtmode != prev_cfg.vtmode ||
1943                     cfg.bold_colour != prev_cfg.bold_colour ||
1944                     cfg.resize_action == RESIZE_DISABLED ||
1945                     cfg.resize_action == RESIZE_EITHER ||
1946                     (cfg.resize_action != prev_cfg.resize_action))
1947                     init_lvl = 2;
1948
1949                 InvalidateRect(hwnd, NULL, TRUE);
1950                 reset_window(init_lvl);
1951                 net_pending_errors();
1952             }
1953             break;
1954           case IDM_COPYALL:
1955             term_copyall(term);
1956             break;
1957           case IDM_PASTE:
1958             term_do_paste(term);
1959             break;
1960           case IDM_CLRSB:
1961             term_clrsb(term);
1962             break;
1963           case IDM_RESET:
1964             term_pwron(term);
1965             ldisc_send(ldisc, NULL, 0, 0);
1966             break;
1967           case IDM_ABOUT:
1968             showabout(hwnd);
1969             break;
1970           case IDM_HELP:
1971             WinHelp(hwnd, help_path,
1972                     help_has_contents ? HELP_FINDER : HELP_CONTENTS, 0);
1973             break;
1974           case SC_MOUSEMENU:
1975             /*
1976              * We get this if the System menu has been activated
1977              * using the mouse.
1978              */
1979             show_mouseptr(1);
1980             break;
1981           case SC_KEYMENU:
1982             /*
1983              * We get this if the System menu has been activated
1984              * using the keyboard. This might happen from within
1985              * TranslateKey, in which case it really wants to be
1986              * followed by a `space' character to actually _bring
1987              * the menu up_ rather than just sitting there in
1988              * `ready to appear' state.
1989              */
1990             show_mouseptr(1);          /* make sure pointer is visible */
1991             if( lParam == 0 )
1992                 PostMessage(hwnd, WM_CHAR, ' ', 0);
1993             break;
1994           case IDM_FULLSCREEN:
1995             flip_full_screen();
1996             break;
1997           default:
1998             if (wParam >= IDM_SAVED_MIN && wParam <= IDM_SAVED_MAX) {
1999                 SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
2000             }
2001             if (wParam >= IDM_SPECIAL_MIN && wParam <= IDM_SPECIAL_MAX) {
2002                 int i = (wParam - IDM_SPECIAL_MIN) / 0x10;
2003                 int j;
2004                 /*
2005                  * Ensure we haven't been sent a bogus SYSCOMMAND
2006                  * which would cause us to reference invalid memory
2007                  * and crash. Perhaps I'm just too paranoid here.
2008                  */
2009                 for (j = 0; j < i; j++)
2010                     if (!specials || !specials[j].name)
2011                         break;
2012                 if (j == i) {
2013                     back->special(backhandle, specials[i].code);
2014                     net_pending_errors();
2015                 }
2016             }
2017         }
2018         break;
2019
2020 #define X_POS(l) ((int)(short)LOWORD(l))
2021 #define Y_POS(l) ((int)(short)HIWORD(l))
2022
2023 #define TO_CHR_X(x) ((((x)<0 ? (x)-font_width+1 : (x))-offset_width) / font_width)
2024 #define TO_CHR_Y(y) ((((y)<0 ? (y)-font_height+1: (y))-offset_height) / font_height)
2025       case WM_LBUTTONDOWN:
2026       case WM_MBUTTONDOWN:
2027       case WM_RBUTTONDOWN:
2028       case WM_LBUTTONUP:
2029       case WM_MBUTTONUP:
2030       case WM_RBUTTONUP:
2031         if (message == WM_RBUTTONDOWN &&
2032             ((wParam & MK_CONTROL) || (cfg.mouse_is_xterm == 2))) {
2033             POINT cursorpos;
2034
2035             show_mouseptr(1);          /* make sure pointer is visible */
2036             GetCursorPos(&cursorpos);
2037             TrackPopupMenu(popup_menus[CTXMENU].menu,
2038                            TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON,
2039                            cursorpos.x, cursorpos.y,
2040                            0, hwnd, NULL);
2041             break;
2042         }
2043         {
2044             int button, press;
2045
2046             switch (message) {
2047               case WM_LBUTTONDOWN:
2048                 button = MBT_LEFT;
2049                 press = 1;
2050                 break;
2051               case WM_MBUTTONDOWN:
2052                 button = MBT_MIDDLE;
2053                 press = 1;
2054                 break;
2055               case WM_RBUTTONDOWN:
2056                 button = MBT_RIGHT;
2057                 press = 1;
2058                 break;
2059               case WM_LBUTTONUP:
2060                 button = MBT_LEFT;
2061                 press = 0;
2062                 break;
2063               case WM_MBUTTONUP:
2064                 button = MBT_MIDDLE;
2065                 press = 0;
2066                 break;
2067               case WM_RBUTTONUP:
2068                 button = MBT_RIGHT;
2069                 press = 0;
2070                 break;
2071               default:
2072                 button = press = 0;    /* shouldn't happen */
2073             }
2074             show_mouseptr(1);
2075             /*
2076              * Special case: in full-screen mode, if the left
2077              * button is clicked in the very top left corner of the
2078              * window, we put up the System menu instead of doing
2079              * selection.
2080              */
2081             if (is_full_screen() && press && button == MBT_LEFT &&
2082                 X_POS(lParam) == 0 && Y_POS(lParam) == 0) {
2083                 SendMessage(hwnd, WM_SYSCOMMAND, SC_MOUSEMENU, 0);
2084                 return 0;
2085             }
2086             if (press) {
2087                 click(button,
2088                       TO_CHR_X(X_POS(lParam)), TO_CHR_Y(Y_POS(lParam)),
2089                       wParam & MK_SHIFT, wParam & MK_CONTROL,
2090                       is_alt_pressed());
2091                 SetCapture(hwnd);
2092             } else {
2093                 term_mouse(term, button, translate_button(button), MA_RELEASE,
2094                            TO_CHR_X(X_POS(lParam)),
2095                            TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2096                            wParam & MK_CONTROL, is_alt_pressed());
2097                 ReleaseCapture();
2098             }
2099         }
2100         return 0;
2101       case WM_MOUSEMOVE:
2102         show_mouseptr(1);
2103         /*
2104          * Add the mouse position and message time to the random
2105          * number noise.
2106          */
2107         noise_ultralight(lParam);
2108
2109         if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON) &&
2110             GetCapture() == hwnd) {
2111             Mouse_Button b;
2112             if (wParam & MK_LBUTTON)
2113                 b = MBT_LEFT;
2114             else if (wParam & MK_MBUTTON)
2115                 b = MBT_MIDDLE;
2116             else
2117                 b = MBT_RIGHT;
2118             term_mouse(term, b, translate_button(b), MA_DRAG,
2119                        TO_CHR_X(X_POS(lParam)),
2120                        TO_CHR_Y(Y_POS(lParam)), wParam & MK_SHIFT,
2121                        wParam & MK_CONTROL, is_alt_pressed());
2122         }
2123         return 0;
2124       case WM_NCMOUSEMOVE:
2125         show_mouseptr(1);
2126         noise_ultralight(lParam);
2127         break;
2128       case WM_IGNORE_CLIP:
2129         ignore_clip = wParam;          /* don't panic on DESTROYCLIPBOARD */
2130         break;
2131       case WM_DESTROYCLIPBOARD:
2132         if (!ignore_clip)
2133             term_deselect(term);
2134         ignore_clip = FALSE;
2135         return 0;
2136       case WM_PAINT:
2137         {
2138             PAINTSTRUCT p;
2139             HideCaret(hwnd);
2140             hdc = BeginPaint(hwnd, &p);
2141             if (pal) {
2142                 SelectPalette(hdc, pal, TRUE);
2143                 RealizePalette(hdc);
2144             }
2145             term_paint(term, hdc, 
2146                        (p.rcPaint.left-offset_width)/font_width,
2147                        (p.rcPaint.top-offset_height)/font_height,
2148                        (p.rcPaint.right-offset_width-1)/font_width,
2149                        (p.rcPaint.bottom-offset_height-1)/font_height,
2150                        is_alt_pressed());
2151
2152             if (p.fErase ||
2153                 p.rcPaint.left  < offset_width  ||
2154                 p.rcPaint.top   < offset_height ||
2155                 p.rcPaint.right >= offset_width + font_width*term->cols ||
2156                 p.rcPaint.bottom>= offset_height + font_height*term->rows)
2157             {
2158                 HBRUSH fillcolour, oldbrush;
2159                 HPEN   edge, oldpen;
2160                 fillcolour = CreateSolidBrush (
2161                                     colours[(ATTR_DEFBG>>ATTR_BGSHIFT)*2]);
2162                 oldbrush = SelectObject(hdc, fillcolour);
2163                 edge = CreatePen(PS_SOLID, 0, 
2164                                     colours[(ATTR_DEFBG>>ATTR_BGSHIFT)*2]);
2165                 oldpen = SelectObject(hdc, edge);
2166
2167                 /*
2168                  * Jordan Russell reports that this apparently
2169                  * ineffectual IntersectClipRect() call masks a
2170                  * Windows NT/2K bug causing strange display
2171                  * problems when the PuTTY window is taller than
2172                  * the primary monitor. It seems harmless enough...
2173                  */
2174                 IntersectClipRect(hdc,
2175                         p.rcPaint.left, p.rcPaint.top,
2176                         p.rcPaint.right, p.rcPaint.bottom);
2177
2178                 ExcludeClipRect(hdc, 
2179                         offset_width, offset_height,
2180                         offset_width+font_width*term->cols,
2181                         offset_height+font_height*term->rows);
2182
2183                 Rectangle(hdc, p.rcPaint.left, p.rcPaint.top, 
2184                           p.rcPaint.right, p.rcPaint.bottom);
2185
2186                 // SelectClipRgn(hdc, NULL);
2187
2188                 SelectObject(hdc, oldbrush);
2189                 DeleteObject(fillcolour);
2190                 SelectObject(hdc, oldpen);
2191                 DeleteObject(edge);
2192             }
2193             SelectObject(hdc, GetStockObject(SYSTEM_FONT));
2194             SelectObject(hdc, GetStockObject(WHITE_PEN));
2195             EndPaint(hwnd, &p);
2196             ShowCaret(hwnd);
2197         }
2198         return 0;
2199       case WM_NETEVENT:
2200         /* Notice we can get multiple netevents, FD_READ, FD_WRITE etc
2201          * but the only one that's likely to try to overload us is FD_READ.
2202          * This means buffering just one is fine.
2203          */
2204         if (pending_netevent)
2205             enact_pending_netevent();
2206
2207         pending_netevent = TRUE;
2208         pend_netevent_wParam = wParam;
2209         pend_netevent_lParam = lParam;
2210         if (WSAGETSELECTEVENT(lParam) != FD_READ)
2211             enact_pending_netevent();
2212
2213         time(&last_movement);
2214         return 0;
2215       case WM_SETFOCUS:
2216         term->has_focus = TRUE;
2217         CreateCaret(hwnd, caretbm, font_width, font_height);
2218         ShowCaret(hwnd);
2219         flash_window(0);               /* stop */
2220         compose_state = 0;
2221         term_out(term);
2222         term_update(term);
2223         break;
2224       case WM_KILLFOCUS:
2225         show_mouseptr(1);
2226         term->has_focus = FALSE;
2227         DestroyCaret();
2228         caret_x = caret_y = -1;        /* ensure caret is replaced next time */
2229         term_out(term);
2230         term_update(term);
2231         break;
2232       case WM_ENTERSIZEMOVE:
2233 #ifdef RDB_DEBUG_PATCH
2234         debug((27, "WM_ENTERSIZEMOVE"));
2235 #endif
2236         EnableSizeTip(1);
2237         resizing = TRUE;
2238         need_backend_resize = FALSE;
2239         break;
2240       case WM_EXITSIZEMOVE:
2241         EnableSizeTip(0);
2242         resizing = FALSE;
2243 #ifdef RDB_DEBUG_PATCH
2244         debug((27, "WM_EXITSIZEMOVE"));
2245 #endif
2246         if (need_backend_resize) {
2247             term_size(term, cfg.height, cfg.width, cfg.savelines);
2248             InvalidateRect(hwnd, NULL, TRUE);
2249         }
2250         break;
2251       case WM_SIZING:
2252         /*
2253          * This does two jobs:
2254          * 1) Keep the sizetip uptodate
2255          * 2) Make sure the window size is _stepped_ in units of the font size.
2256          */
2257         if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2258             int width, height, w, h, ew, eh;
2259             LPRECT r = (LPRECT) lParam;
2260
2261             if ( !need_backend_resize && cfg.resize_action == RESIZE_EITHER &&
2262                     (cfg.height != term->rows || cfg.width != term->cols )) {
2263                 /* 
2264                  * Great! It seems that both the terminal size and the
2265                  * font size have been changed and the user is now dragging.
2266                  * 
2267                  * It will now be difficult to get back to the configured
2268                  * font size!
2269                  *
2270                  * This would be easier but it seems to be too confusing.
2271
2272                 term_size(term, cfg.height, cfg.width, cfg.savelines);
2273                 reset_window(2);
2274                  */
2275                 cfg.height=term->rows; cfg.width=term->cols;
2276
2277                 InvalidateRect(hwnd, NULL, TRUE);
2278                 need_backend_resize = TRUE;
2279             }
2280
2281             width = r->right - r->left - extra_width;
2282             height = r->bottom - r->top - extra_height;
2283             w = (width + font_width / 2) / font_width;
2284             if (w < 1)
2285                 w = 1;
2286             h = (height + font_height / 2) / font_height;
2287             if (h < 1)
2288                 h = 1;
2289             UpdateSizeTip(hwnd, w, h);
2290             ew = width - w * font_width;
2291             eh = height - h * font_height;
2292             if (ew != 0) {
2293                 if (wParam == WMSZ_LEFT ||
2294                     wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2295                     r->left += ew;
2296                 else
2297                     r->right -= ew;
2298             }
2299             if (eh != 0) {
2300                 if (wParam == WMSZ_TOP ||
2301                     wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2302                     r->top += eh;
2303                 else
2304                     r->bottom -= eh;
2305             }
2306             if (ew || eh)
2307                 return 1;
2308             else
2309                 return 0;
2310         } else {
2311             int width, height, w, h, rv = 0;
2312             int ex_width = extra_width + (cfg.window_border - offset_width) * 2;
2313             int ex_height = extra_height + (cfg.window_border - offset_height) * 2;
2314             LPRECT r = (LPRECT) lParam;
2315
2316             width = r->right - r->left - ex_width;
2317             height = r->bottom - r->top - ex_height;
2318
2319             w = (width + term->cols/2)/term->cols;
2320             h = (height + term->rows/2)/term->rows;
2321             if ( r->right != r->left + w*term->cols + ex_width)
2322                 rv = 1;
2323
2324             if (wParam == WMSZ_LEFT ||
2325                 wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_TOPLEFT)
2326                 r->left = r->right - w*term->cols - ex_width;
2327             else
2328                 r->right = r->left + w*term->cols + ex_width;
2329
2330             if (r->bottom != r->top + h*term->rows + ex_height)
2331                 rv = 1;
2332
2333             if (wParam == WMSZ_TOP ||
2334                 wParam == WMSZ_TOPRIGHT || wParam == WMSZ_TOPLEFT)
2335                 r->top = r->bottom - h*term->rows - ex_height;
2336             else
2337                 r->bottom = r->top + h*term->rows + ex_height;
2338
2339             return rv;
2340         }
2341         /* break;  (never reached) */
2342       case WM_FULLSCR_ON_MAX:
2343         fullscr_on_max = TRUE;
2344         break;
2345       case WM_MOVE:
2346         sys_cursor_update();
2347         break;
2348       case WM_SIZE:
2349 #ifdef RDB_DEBUG_PATCH
2350         debug((27, "WM_SIZE %s (%d,%d)",
2351                 (wParam == SIZE_MINIMIZED) ? "SIZE_MINIMIZED":
2352                 (wParam == SIZE_MAXIMIZED) ? "SIZE_MAXIMIZED":
2353                 (wParam == SIZE_RESTORED && resizing) ? "to":
2354                 (wParam == SIZE_RESTORED) ? "SIZE_RESTORED":
2355                 "...",
2356             LOWORD(lParam), HIWORD(lParam)));
2357 #endif
2358         if (wParam == SIZE_MINIMIZED)
2359             SetWindowText(hwnd,
2360                           cfg.win_name_always ? window_name : icon_name);
2361         if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
2362             SetWindowText(hwnd, window_name);
2363         if (wParam == SIZE_RESTORED)
2364             clear_full_screen();
2365         if (wParam == SIZE_MAXIMIZED && fullscr_on_max) {
2366             fullscr_on_max = FALSE;
2367             make_full_screen();
2368         }
2369
2370         if (cfg.resize_action == RESIZE_DISABLED) {
2371             /* A resize, well it better be a minimize. */
2372             reset_window(-1);
2373         } else {
2374
2375             int width, height, w, h;
2376
2377             width = LOWORD(lParam);
2378             height = HIWORD(lParam);
2379
2380             if (!resizing) {
2381                 if (wParam == SIZE_MAXIMIZED && !was_zoomed) {
2382                     was_zoomed = 1;
2383                     prev_rows = term->rows;
2384                     prev_cols = term->cols;
2385                     if (cfg.resize_action == RESIZE_TERM) {
2386                         w = width / font_width;
2387                         if (w < 1) w = 1;
2388                         h = height / font_height;
2389                         if (h < 1) h = 1;
2390
2391                         term_size(term, h, w, cfg.savelines);
2392                     }
2393                     reset_window(0);
2394                 } else if (wParam == SIZE_RESTORED && was_zoomed) {
2395                     was_zoomed = 0;
2396                     if (cfg.resize_action == RESIZE_TERM)
2397                         term_size(term, prev_rows, prev_cols, cfg.savelines);
2398                     if (cfg.resize_action != RESIZE_FONT)
2399                         reset_window(2);
2400                     else
2401                         reset_window(0);
2402                 }
2403                 /* This is an unexpected resize, these will normally happen
2404                  * if the window is too large. Probably either the user
2405                  * selected a huge font or the screen size has changed.
2406                  *
2407                  * This is also called with minimize.
2408                  */
2409                 else reset_window(-1);
2410             }
2411
2412             /*
2413              * Don't call back->size in mid-resize. (To prevent
2414              * massive numbers of resize events getting sent
2415              * down the connection during an NT opaque drag.)
2416              */
2417             if (resizing) {
2418                 if (cfg.resize_action != RESIZE_FONT && !is_alt_pressed()) {
2419                     need_backend_resize = TRUE;
2420                     w = (width-cfg.window_border*2) / font_width;
2421                     if (w < 1) w = 1;
2422                     h = (height-cfg.window_border*2) / font_height;
2423                     if (h < 1) h = 1;
2424
2425                     cfg.height = h;
2426                     cfg.width = w;
2427                 } else 
2428                     reset_window(0);
2429             }
2430         }
2431         sys_cursor_update();
2432         return 0;
2433       case WM_VSCROLL:
2434         switch (LOWORD(wParam)) {
2435           case SB_BOTTOM:
2436             term_scroll(term, -1, 0);
2437             break;
2438           case SB_TOP:
2439             term_scroll(term, +1, 0);
2440             break;
2441           case SB_LINEDOWN:
2442             term_scroll(term, 0, +1);
2443             break;
2444           case SB_LINEUP:
2445             term_scroll(term, 0, -1);
2446             break;
2447           case SB_PAGEDOWN:
2448             term_scroll(term, 0, +term->rows / 2);
2449             break;
2450           case SB_PAGEUP:
2451             term_scroll(term, 0, -term->rows / 2);
2452             break;
2453           case SB_THUMBPOSITION:
2454           case SB_THUMBTRACK:
2455             term_scroll(term, 1, HIWORD(wParam));
2456             break;
2457         }
2458         break;
2459       case WM_PALETTECHANGED:
2460         if ((HWND) wParam != hwnd && pal != NULL) {
2461             HDC hdc = get_ctx(NULL);
2462             if (hdc) {
2463                 if (RealizePalette(hdc) > 0)
2464                     UpdateColors(hdc);
2465                 free_ctx(hdc);
2466             }
2467         }
2468         break;
2469       case WM_QUERYNEWPALETTE:
2470         if (pal != NULL) {
2471             HDC hdc = get_ctx(NULL);
2472             if (hdc) {
2473                 if (RealizePalette(hdc) > 0)
2474                     UpdateColors(hdc);
2475                 free_ctx(hdc);
2476                 return TRUE;
2477             }
2478         }
2479         return FALSE;
2480       case WM_KEYDOWN:
2481       case WM_SYSKEYDOWN:
2482       case WM_KEYUP:
2483       case WM_SYSKEYUP:
2484         /*
2485          * Add the scan code and keypress timing to the random
2486          * number noise.
2487          */
2488         noise_ultralight(lParam);
2489
2490         /*
2491          * We don't do TranslateMessage since it disassociates the
2492          * resulting CHAR message from the KEYDOWN that sparked it,
2493          * which we occasionally don't want. Instead, we process
2494          * KEYDOWN, and call the Win32 translator functions so that
2495          * we get the translations under _our_ control.
2496          */
2497         {
2498             unsigned char buf[20];
2499             int len;
2500
2501             if (wParam == VK_PROCESSKEY) {
2502                 MSG m;
2503                 m.hwnd = hwnd;
2504                 m.message = WM_KEYDOWN;
2505                 m.wParam = wParam;
2506                 m.lParam = lParam & 0xdfff;
2507                 TranslateMessage(&m);
2508             } else {
2509                 len = TranslateKey(message, wParam, lParam, buf);
2510                 if (len == -1)
2511                     return DefWindowProc(hwnd, message, wParam, lParam);
2512
2513                 if (len != 0) {
2514                     /*
2515                      * Interrupt an ongoing paste. I'm not sure
2516                      * this is sensible, but for the moment it's
2517                      * preferable to having to faff about buffering
2518                      * things.
2519                      */
2520                     term_nopaste(term);
2521
2522                     /*
2523                      * We need not bother about stdin backlogs
2524                      * here, because in GUI PuTTY we can't do
2525                      * anything about it anyway; there's no means
2526                      * of asking Windows to hold off on KEYDOWN
2527                      * messages. We _have_ to buffer everything
2528                      * we're sent.
2529                      */
2530                     term_seen_key_event(term);
2531                     ldisc_send(ldisc, buf, len, 1);
2532                     show_mouseptr(0);
2533                 }
2534             }
2535         }
2536         net_pending_errors();
2537         return 0;
2538       case WM_INPUTLANGCHANGE:
2539         /* wParam == Font number */
2540         /* lParam == Locale */
2541         set_input_locale((HKL)lParam);
2542         sys_cursor_update();
2543         break;
2544       case WM_IME_NOTIFY:
2545         if(wParam == IMN_SETOPENSTATUS) {
2546             HIMC hImc = ImmGetContext(hwnd);
2547             ImmSetCompositionFont(hImc, &lfont);
2548             ImmReleaseContext(hwnd, hImc);
2549             return 0;
2550         }
2551         break;
2552       case WM_IME_COMPOSITION:
2553         {
2554             HIMC hIMC;
2555             int n;
2556             char *buff;
2557
2558             if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS || 
2559                 osVersion.dwPlatformId == VER_PLATFORM_WIN32s) break; /* no Unicode */
2560
2561             if ((lParam & GCS_RESULTSTR) == 0) /* Composition unfinished. */
2562                 break; /* fall back to DefWindowProc */
2563
2564             hIMC = ImmGetContext(hwnd);
2565             n = ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, NULL, 0);
2566
2567             if (n > 0) {
2568                 int i;
2569                 buff = snewn(n, char);
2570                 ImmGetCompositionStringW(hIMC, GCS_RESULTSTR, buff, n);
2571                 /*
2572                  * Jaeyoun Chung reports that Korean character
2573                  * input doesn't work correctly if we do a single
2574                  * luni_send() covering the whole of buff. So
2575                  * instead we luni_send the characters one by one.
2576                  */
2577                 term_seen_key_event(term);
2578                 for (i = 0; i < n; i += 2) {
2579                     luni_send(ldisc, (unsigned short *)(buff+i), 1, 1);
2580                 }
2581                 free(buff);
2582             }
2583             ImmReleaseContext(hwnd, hIMC);
2584             return 1;
2585         }
2586
2587       case WM_IME_CHAR:
2588         if (wParam & 0xFF00) {
2589             unsigned char buf[2];
2590
2591             buf[1] = wParam;
2592             buf[0] = wParam >> 8;
2593             term_seen_key_event(term);
2594             lpage_send(ldisc, kbd_codepage, buf, 2, 1);
2595         } else {
2596             char c = (unsigned char) wParam;
2597             term_seen_key_event(term);
2598             lpage_send(ldisc, kbd_codepage, &c, 1, 1);
2599         }
2600         return (0);
2601       case WM_CHAR:
2602       case WM_SYSCHAR:
2603         /*
2604          * Nevertheless, we are prepared to deal with WM_CHAR
2605          * messages, should they crop up. So if someone wants to
2606          * post the things to us as part of a macro manoeuvre,
2607          * we're ready to cope.
2608          */
2609         {
2610             char c = (unsigned char)wParam;
2611             term_seen_key_event(term);
2612             lpage_send(ldisc, CP_ACP, &c, 1, 1);
2613         }
2614         return 0;
2615       case WM_SETCURSOR:
2616         if (send_raw_mouse && LOWORD(lParam) == HTCLIENT) {
2617             SetCursor(LoadCursor(NULL, IDC_ARROW));
2618             return TRUE;
2619         }
2620         break;
2621       case WM_AGENT_CALLBACK:
2622         {
2623             struct agent_callback *c = (struct agent_callback *)lParam;
2624             c->callback(c->callback_ctx, c->data, c->len);
2625             sfree(c);
2626         }
2627         return 0;
2628       default:
2629         if (message == wm_mousewheel || message == WM_MOUSEWHEEL) {
2630             int shift_pressed=0, control_pressed=0;
2631
2632             if (message == WM_MOUSEWHEEL) {
2633                 wheel_accumulator += (short)HIWORD(wParam);
2634                 shift_pressed=LOWORD(wParam) & MK_SHIFT;
2635                 control_pressed=LOWORD(wParam) & MK_CONTROL;
2636             } else {
2637                 BYTE keys[256];
2638                 wheel_accumulator += (int)wParam;
2639                 if (GetKeyboardState(keys)!=0) {
2640                     shift_pressed=keys[VK_SHIFT]&0x80;
2641                     control_pressed=keys[VK_CONTROL]&0x80;
2642                 }
2643             }
2644
2645             /* process events when the threshold is reached */
2646             while (abs(wheel_accumulator) >= WHEEL_DELTA) {
2647                 int b;
2648
2649                 /* reduce amount for next time */
2650                 if (wheel_accumulator > 0) {
2651                     b = MBT_WHEEL_UP;
2652                     wheel_accumulator -= WHEEL_DELTA;
2653                 } else if (wheel_accumulator < 0) {
2654                     b = MBT_WHEEL_DOWN;
2655                     wheel_accumulator += WHEEL_DELTA;
2656                 } else
2657                     break;
2658
2659                 if (send_raw_mouse &&
2660                     !(cfg.mouse_override && shift_pressed)) {
2661                     /* send a mouse-down followed by a mouse up */
2662                     term_mouse(term, b, translate_button(b),
2663                                MA_CLICK,
2664                                TO_CHR_X(X_POS(lParam)),
2665                                TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2666                                control_pressed, is_alt_pressed());
2667                     term_mouse(term, b, translate_button(b),
2668                                MA_RELEASE, TO_CHR_X(X_POS(lParam)),
2669                                TO_CHR_Y(Y_POS(lParam)), shift_pressed,
2670                                control_pressed, is_alt_pressed());
2671                 } else {
2672                     /* trigger a scroll */
2673                     term_scroll(term, 0,
2674                                 b == MBT_WHEEL_UP ?
2675                                 -term->rows / 2 : term->rows / 2);
2676                 }
2677             }
2678             return 0;
2679         }
2680     }
2681
2682     return DefWindowProc(hwnd, message, wParam, lParam);
2683 }
2684
2685 /*
2686  * Move the system caret. (We maintain one, even though it's
2687  * invisible, for the benefit of blind people: apparently some
2688  * helper software tracks the system caret, so we should arrange to
2689  * have one.)
2690  */
2691 void sys_cursor(void *frontend, int x, int y)
2692 {
2693     int cx, cy;
2694
2695     if (!term->has_focus) return;
2696
2697     /*
2698      * Avoid gratuitously re-updating the cursor position and IMM
2699      * window if there's no actual change required.
2700      */
2701     cx = x * font_width + offset_width;
2702     cy = y * font_height + offset_height;
2703     if (cx == caret_x && cy == caret_y)
2704         return;
2705     caret_x = cx;
2706     caret_y = cy;
2707
2708     sys_cursor_update();
2709 }
2710
2711 static void sys_cursor_update(void)
2712 {
2713     COMPOSITIONFORM cf;
2714     HIMC hIMC;
2715
2716     if (!term->has_focus) return;
2717
2718     if (caret_x < 0 || caret_y < 0)
2719         return;
2720
2721     SetCaretPos(caret_x, caret_y);
2722
2723     /* IMM calls on Win98 and beyond only */
2724     if(osVersion.dwPlatformId == VER_PLATFORM_WIN32s) return; /* 3.11 */
2725     
2726     if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS &&
2727             osVersion.dwMinorVersion == 0) return; /* 95 */
2728
2729     /* we should have the IMM functions */
2730     hIMC = ImmGetContext(hwnd);
2731     cf.dwStyle = CFS_POINT;
2732     cf.ptCurrentPos.x = caret_x;
2733     cf.ptCurrentPos.y = caret_y;
2734     ImmSetCompositionWindow(hIMC, &cf);
2735
2736     ImmReleaseContext(hwnd, hIMC);
2737 }
2738
2739 /*
2740  * Draw a line of text in the window, at given character
2741  * coordinates, in given attributes.
2742  *
2743  * We are allowed to fiddle with the contents of `text'.
2744  */
2745 void do_text(Context ctx, int x, int y, char *text, int len,
2746              unsigned long attr, int lattr)
2747 {
2748     COLORREF fg, bg, t;
2749     int nfg, nbg, nfont;
2750     HDC hdc = ctx;
2751     RECT line_box;
2752     int force_manual_underline = 0;
2753     int fnt_width = font_width * (1 + (lattr != LATTR_NORM));
2754     int char_width = fnt_width;
2755     int text_adjust = 0;
2756     static int *IpDx = 0, IpDxLEN = 0;
2757
2758     if (attr & ATTR_WIDE)
2759         char_width *= 2;
2760
2761     if (len > IpDxLEN || IpDx[0] != char_width) {
2762         int i;
2763         if (len > IpDxLEN) {
2764             sfree(IpDx);
2765             IpDx = snewn(len + 16, int);
2766             IpDxLEN = (len + 16);
2767         }
2768         for (i = 0; i < IpDxLEN; i++)
2769             IpDx[i] = char_width;
2770     }
2771
2772     /* Only want the left half of double width lines */
2773     if (lattr != LATTR_NORM && x*2 >= term->cols)
2774         return;
2775
2776     x *= fnt_width;
2777     y *= font_height;
2778     x += offset_width;
2779     y += offset_height;
2780
2781     if ((attr & TATTR_ACTCURS) && (cfg.cursor_type == 0 || term->big_cursor)) {
2782         attr &= ATTR_CUR_AND | (bold_mode != BOLD_COLOURS ? ATTR_BOLD : 0);
2783         attr ^= ATTR_CUR_XOR;
2784     }
2785
2786     nfont = 0;
2787     if (cfg.vtmode == VT_POORMAN && lattr != LATTR_NORM) {
2788         /* Assume a poorman font is borken in other ways too. */
2789         lattr = LATTR_WIDE;
2790     } else
2791         switch (lattr) {
2792           case LATTR_NORM:
2793             break;
2794           case LATTR_WIDE:
2795             nfont |= FONT_WIDE;
2796             break;
2797           default:
2798             nfont |= FONT_WIDE + FONT_HIGH;
2799             break;
2800         }
2801     if (attr & ATTR_NARROW)
2802         nfont |= FONT_NARROW;
2803
2804     /* Special hack for the VT100 linedraw glyphs. */
2805     if ((attr & CSET_MASK) == 0x2300) {
2806         if (text[0] >= (char) 0xBA && text[0] <= (char) 0xBD) {
2807             switch ((unsigned char) (text[0])) {
2808               case 0xBA:
2809                 text_adjust = -2 * font_height / 5;
2810                 break;
2811               case 0xBB:
2812                 text_adjust = -1 * font_height / 5;
2813                 break;
2814               case 0xBC:
2815                 text_adjust = font_height / 5;
2816                 break;
2817               case 0xBD:
2818                 text_adjust = 2 * font_height / 5;
2819                 break;
2820             }
2821             if (lattr == LATTR_TOP || lattr == LATTR_BOT)
2822                 text_adjust *= 2;
2823             attr &= ~CSET_MASK;
2824             text[0] = (char) (ucsdata.unitab_xterm['q'] & CHAR_MASK);
2825             attr |= (ucsdata.unitab_xterm['q'] & CSET_MASK);
2826             if (attr & ATTR_UNDER) {
2827                 attr &= ~ATTR_UNDER;
2828                 force_manual_underline = 1;
2829             }
2830         }
2831     }
2832
2833     /* Anything left as an original character set is unprintable. */
2834     if (DIRECT_CHAR(attr)) {
2835         attr &= ~CSET_MASK;
2836         attr |= 0xFF00;
2837         memset(text, 0xFD, len);
2838     }
2839
2840     /* OEM CP */
2841     if ((attr & CSET_MASK) == ATTR_OEMCP)
2842         nfont |= FONT_OEM;
2843
2844     nfg = ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
2845     nfg = 2 * (nfg & 0xF) + (nfg & 0x10 ? 1 : 0);
2846     nbg = ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
2847     nbg = 2 * (nbg & 0xF) + (nbg & 0x10 ? 1 : 0);
2848     if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
2849         nfont |= FONT_BOLD;
2850     if (und_mode == UND_FONT && (attr & ATTR_UNDER))
2851         nfont |= FONT_UNDERLINE;
2852     another_font(nfont);
2853     if (!fonts[nfont]) {
2854         if (nfont & FONT_UNDERLINE)
2855             force_manual_underline = 1;
2856         /* Don't do the same for manual bold, it could be bad news. */
2857
2858         nfont &= ~(FONT_BOLD | FONT_UNDERLINE);
2859     }
2860     another_font(nfont);
2861     if (!fonts[nfont])
2862         nfont = FONT_NORMAL;
2863     if (attr & ATTR_REVERSE) {
2864         t = nfg;
2865         nfg = nbg;
2866         nbg = t;
2867     }
2868     if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD))
2869         nfg |= 1;
2870     if (bold_mode == BOLD_COLOURS && (attr & ATTR_BLINK))
2871         nbg |= 1;
2872     fg = colours[nfg];
2873     bg = colours[nbg];
2874     SelectObject(hdc, fonts[nfont]);
2875     SetTextColor(hdc, fg);
2876     SetBkColor(hdc, bg);
2877     SetBkMode(hdc, OPAQUE);
2878     line_box.left = x;
2879     line_box.top = y;
2880     line_box.right = x + char_width * len;
2881     line_box.bottom = y + font_height;
2882
2883     /* Only want the left half of double width lines */
2884     if (line_box.right > font_width*term->cols+offset_width)
2885         line_box.right = font_width*term->cols+offset_width;
2886
2887     /* We're using a private area for direct to font. (512 chars.) */
2888     if (ucsdata.dbcs_screenfont && (attr & CSET_MASK) == ATTR_ACP) {
2889         /* Ho Hum, dbcs fonts are a PITA! */
2890         /* To display on W9x I have to convert to UCS */
2891         static wchar_t *uni_buf = 0;
2892         static int uni_len = 0;
2893         int nlen, mptr;
2894         if (len > uni_len) {
2895             sfree(uni_buf);
2896             uni_len = len;
2897             uni_buf = snewn(uni_len, wchar_t);
2898         }
2899
2900         for(nlen = mptr = 0; mptr<len; mptr++) {
2901             uni_buf[nlen] = 0xFFFD;
2902             if (IsDBCSLeadByteEx(ucsdata.font_codepage, (BYTE) text[mptr])) {
2903                 IpDx[nlen] += char_width;
2904                 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
2905                                    text+mptr, 2, uni_buf+nlen, 1);
2906                 mptr++;
2907             }
2908             else
2909             {
2910                 MultiByteToWideChar(ucsdata.font_codepage, MB_USEGLYPHCHARS,
2911                                    text+mptr, 1, uni_buf+nlen, 1);
2912             }
2913             nlen++;
2914         }
2915         if (nlen <= 0)
2916             return;                    /* Eeek! */
2917
2918         ExtTextOutW(hdc, x,
2919                     y - font_height * (lattr == LATTR_BOT) + text_adjust,
2920                     ETO_CLIPPED | ETO_OPAQUE, &line_box, uni_buf, nlen, IpDx);
2921         if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
2922             SetBkMode(hdc, TRANSPARENT);
2923             ExtTextOutW(hdc, x - 1,
2924                         y - font_height * (lattr ==
2925                                            LATTR_BOT) + text_adjust,
2926                         ETO_CLIPPED, &line_box, uni_buf, nlen, IpDx);
2927         }
2928
2929         IpDx[0] = -1;
2930     } else if (DIRECT_FONT(attr)) {
2931         ExtTextOut(hdc, x,
2932                    y - font_height * (lattr == LATTR_BOT) + text_adjust,
2933                    ETO_CLIPPED | ETO_OPAQUE, &line_box, text, len, IpDx);
2934         if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
2935             SetBkMode(hdc, TRANSPARENT);
2936
2937             /* GRR: This draws the character outside it's box and can leave
2938              * 'droppings' even with the clip box! I suppose I could loop it
2939              * one character at a time ... yuk. 
2940              * 
2941              * Or ... I could do a test print with "W", and use +1 or -1 for this
2942              * shift depending on if the leftmost column is blank...
2943              */
2944             ExtTextOut(hdc, x - 1,
2945                        y - font_height * (lattr ==
2946                                           LATTR_BOT) + text_adjust,
2947                        ETO_CLIPPED, &line_box, text, len, IpDx);
2948         }
2949     } else {
2950         /* And 'normal' unicode characters */
2951         static WCHAR *wbuf = NULL;
2952         static int wlen = 0;
2953         int i;
2954         if (wlen < len) {
2955             sfree(wbuf);
2956             wlen = len;
2957             wbuf = snewn(wlen, WCHAR);
2958         }
2959         for (i = 0; i < len; i++)
2960             wbuf[i] = (WCHAR) ((attr & CSET_MASK) + (text[i] & CHAR_MASK));
2961
2962         ExtTextOutW(hdc, x,
2963                     y - font_height * (lattr == LATTR_BOT) + text_adjust,
2964                     ETO_CLIPPED | ETO_OPAQUE, &line_box, wbuf, len, IpDx);
2965
2966         /* And the shadow bold hack. */
2967         if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
2968             SetBkMode(hdc, TRANSPARENT);
2969             ExtTextOutW(hdc, x - 1,
2970                         y - font_height * (lattr ==
2971                                            LATTR_BOT) + text_adjust,
2972                         ETO_CLIPPED, &line_box, wbuf, len, IpDx);
2973         }
2974     }
2975     if (lattr != LATTR_TOP && (force_manual_underline ||
2976                                (und_mode == UND_LINE
2977                                 && (attr & ATTR_UNDER)))) {
2978         HPEN oldpen;
2979         int dec = descent;
2980         if (lattr == LATTR_BOT)
2981             dec = dec * 2 - font_height;
2982
2983         oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, fg));
2984         MoveToEx(hdc, x, y + dec, NULL);
2985         LineTo(hdc, x + len * char_width, y + dec);
2986         oldpen = SelectObject(hdc, oldpen);
2987         DeleteObject(oldpen);
2988     }
2989 }
2990
2991 void do_cursor(Context ctx, int x, int y, char *text, int len,
2992                unsigned long attr, int lattr)
2993 {
2994
2995     int fnt_width;
2996     int char_width;
2997     HDC hdc = ctx;
2998     int ctype = cfg.cursor_type;
2999
3000     if ((attr & TATTR_ACTCURS) && (ctype == 0 || term->big_cursor)) {
3001         if (((attr & CSET_MASK) | (unsigned char) *text) != UCSWIDE) {
3002             do_text(ctx, x, y, text, len, attr, lattr);
3003             return;
3004         }
3005         ctype = 2;
3006         attr |= TATTR_RIGHTCURS;
3007     }
3008
3009     fnt_width = char_width = font_width * (1 + (lattr != LATTR_NORM));
3010     if (attr & ATTR_WIDE)
3011         char_width *= 2;
3012     x *= fnt_width;
3013     y *= font_height;
3014     x += offset_width;
3015     y += offset_height;
3016
3017     if ((attr & TATTR_PASCURS) && (ctype == 0 || term->big_cursor)) {
3018         POINT pts[5];
3019         HPEN oldpen;
3020         pts[0].x = pts[1].x = pts[4].x = x;
3021         pts[2].x = pts[3].x = x + char_width - 1;
3022         pts[0].y = pts[3].y = pts[4].y = y;
3023         pts[1].y = pts[2].y = y + font_height - 1;
3024         oldpen = SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
3025         Polyline(hdc, pts, 5);
3026         oldpen = SelectObject(hdc, oldpen);
3027         DeleteObject(oldpen);
3028     } else if ((attr & (TATTR_ACTCURS | TATTR_PASCURS)) && ctype != 0) {
3029         int startx, starty, dx, dy, length, i;
3030         if (ctype == 1) {
3031             startx = x;
3032             starty = y + descent;
3033             dx = 1;
3034             dy = 0;
3035             length = char_width;
3036         } else {
3037             int xadjust = 0;
3038             if (attr & TATTR_RIGHTCURS)
3039                 xadjust = char_width - 1;
3040             startx = x + xadjust;
3041             starty = y;
3042             dx = 0;
3043             dy = 1;
3044             length = font_height;
3045         }
3046         if (attr & TATTR_ACTCURS) {
3047             HPEN oldpen;
3048             oldpen =
3049                 SelectObject(hdc, CreatePen(PS_SOLID, 0, colours[23]));
3050             MoveToEx(hdc, startx, starty, NULL);
3051             LineTo(hdc, startx + dx * length, starty + dy * length);
3052             oldpen = SelectObject(hdc, oldpen);
3053             DeleteObject(oldpen);
3054         } else {
3055             for (i = 0; i < length; i++) {
3056                 if (i % 2 == 0) {
3057                     SetPixel(hdc, startx, starty, colours[23]);
3058                 }
3059                 startx += dx;
3060                 starty += dy;
3061             }
3062         }
3063     }
3064 }
3065
3066 /* This function gets the actual width of a character in the normal font.
3067  */
3068 int char_width(Context ctx, int uc) {
3069     HDC hdc = ctx;
3070     int ibuf = 0;
3071
3072     /* If the font max is the same as the font ave width then this
3073      * function is a no-op.
3074      */
3075     if (!font_dualwidth) return 1;
3076
3077     switch (uc & CSET_MASK) {
3078       case ATTR_ASCII:
3079         uc = ucsdata.unitab_line[uc & 0xFF];
3080         break;
3081       case ATTR_LINEDRW:
3082         uc = ucsdata.unitab_xterm[uc & 0xFF];
3083         break;
3084       case ATTR_SCOACS:
3085         uc = ucsdata.unitab_scoacs[uc & 0xFF];
3086         break;
3087     }
3088     if (DIRECT_FONT(uc)) {
3089         if (ucsdata.dbcs_screenfont) return 1;
3090
3091         /* Speedup, I know of no font where ascii is the wrong width */
3092         if ((uc&CHAR_MASK) >= ' ' && (uc&CHAR_MASK)<= '~') 
3093             return 1;
3094
3095         if ( (uc & CSET_MASK) == ATTR_ACP ) {
3096             SelectObject(hdc, fonts[FONT_NORMAL]);
3097         } else if ( (uc & CSET_MASK) == ATTR_OEMCP ) {
3098             another_font(FONT_OEM);
3099             if (!fonts[FONT_OEM]) return 0;
3100
3101             SelectObject(hdc, fonts[FONT_OEM]);
3102         } else
3103             return 0;
3104
3105         if ( GetCharWidth32(hdc, uc&CHAR_MASK, uc&CHAR_MASK, &ibuf) != 1 && 
3106              GetCharWidth(hdc, uc&CHAR_MASK, uc&CHAR_MASK, &ibuf) != 1)
3107             return 0;
3108     } else {
3109         /* Speedup, I know of no font where ascii is the wrong width */
3110         if (uc >= ' ' && uc <= '~') return 1;
3111
3112         SelectObject(hdc, fonts[FONT_NORMAL]);
3113         if ( GetCharWidth32W(hdc, uc, uc, &ibuf) == 1 )
3114             /* Okay that one worked */ ;
3115         else if ( GetCharWidthW(hdc, uc, uc, &ibuf) == 1 )
3116             /* This should work on 9x too, but it's "less accurate" */ ;
3117         else
3118             return 0;
3119     }
3120
3121     ibuf += font_width / 2 -1;
3122     ibuf /= font_width;
3123
3124     return ibuf;
3125 }
3126
3127 /*
3128  * Translate a WM_(SYS)?KEY(UP|DOWN) message into a string of ASCII
3129  * codes. Returns number of bytes used or zero to drop the message
3130  * or -1 to forward the message to windows.
3131  */
3132 static int TranslateKey(UINT message, WPARAM wParam, LPARAM lParam,
3133                         unsigned char *output)
3134 {
3135     BYTE keystate[256];
3136     int scan, left_alt = 0, key_down, shift_state;
3137     int r, i, code;
3138     unsigned char *p = output;
3139     static int alt_sum = 0;
3140
3141     HKL kbd_layout = GetKeyboardLayout(0);
3142
3143     static WORD keys[3];
3144     static int compose_char = 0;
3145     static WPARAM compose_key = 0;
3146
3147     r = GetKeyboardState(keystate);
3148     if (!r)
3149         memset(keystate, 0, sizeof(keystate));
3150     else {
3151 #if 0
3152 #define SHOW_TOASCII_RESULT
3153         {                              /* Tell us all about key events */
3154             static BYTE oldstate[256];
3155             static int first = 1;
3156             static int scan;
3157             int ch;
3158             if (first)
3159                 memcpy(oldstate, keystate, sizeof(oldstate));
3160             first = 0;
3161
3162             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT) {
3163                 debug(("+"));
3164             } else if ((HIWORD(lParam) & KF_UP)
3165                        && scan == (HIWORD(lParam) & 0xFF)) {
3166                 debug((". U"));
3167             } else {
3168                 debug((".\n"));
3169                 if (wParam >= VK_F1 && wParam <= VK_F20)
3170                     debug(("K_F%d", wParam + 1 - VK_F1));
3171                 else
3172                     switch (wParam) {
3173                       case VK_SHIFT:
3174                         debug(("SHIFT"));
3175                         break;
3176                       case VK_CONTROL:
3177                         debug(("CTRL"));
3178                         break;
3179                       case VK_MENU:
3180                         debug(("ALT"));
3181                         break;
3182                       default:
3183                         debug(("VK_%02x", wParam));
3184                     }
3185                 if (message == WM_SYSKEYDOWN || message == WM_SYSKEYUP)
3186                     debug(("*"));
3187                 debug((", S%02x", scan = (HIWORD(lParam) & 0xFF)));
3188
3189                 ch = MapVirtualKeyEx(wParam, 2, kbd_layout);
3190                 if (ch >= ' ' && ch <= '~')
3191                     debug((", '%c'", ch));
3192                 else if (ch)
3193                     debug((", $%02x", ch));
3194
3195                 if (keys[0])
3196                     debug((", KB0=%02x", keys[0]));
3197                 if (keys[1])
3198                     debug((", KB1=%02x", keys[1]));
3199                 if (keys[2])
3200                     debug((", KB2=%02x", keys[2]));
3201
3202                 if ((keystate[VK_SHIFT] & 0x80) != 0)
3203                     debug((", S"));
3204                 if ((keystate[VK_CONTROL] & 0x80) != 0)
3205                     debug((", C"));
3206                 if ((HIWORD(lParam) & KF_EXTENDED))
3207                     debug((", E"));
3208                 if ((HIWORD(lParam) & KF_UP))
3209                     debug((", U"));
3210             }
3211
3212             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT);
3213             else if ((HIWORD(lParam) & KF_UP))
3214                 oldstate[wParam & 0xFF] ^= 0x80;
3215             else
3216                 oldstate[wParam & 0xFF] ^= 0x81;
3217
3218             for (ch = 0; ch < 256; ch++)
3219                 if (oldstate[ch] != keystate[ch])
3220                     debug((", M%02x=%02x", ch, keystate[ch]));
3221
3222             memcpy(oldstate, keystate, sizeof(oldstate));
3223         }
3224 #endif
3225
3226         if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED)) {
3227             keystate[VK_RMENU] = keystate[VK_MENU];
3228         }
3229
3230
3231         /* Nastyness with NUMLock - Shift-NUMLock is left alone though */
3232         if ((cfg.funky_type == 3 ||
3233              (cfg.funky_type <= 1 && term->app_keypad_keys &&
3234               !cfg.no_applic_k))
3235             && wParam == VK_NUMLOCK && !(keystate[VK_SHIFT] & 0x80)) {
3236
3237             wParam = VK_EXECUTE;
3238
3239             /* UnToggle NUMLock */
3240             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0)
3241                 keystate[VK_NUMLOCK] ^= 1;
3242         }
3243
3244         /* And write back the 'adjusted' state */
3245         SetKeyboardState(keystate);
3246     }
3247
3248     /* Disable Auto repeat if required */
3249     if (term->repeat_off &&
3250         (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == KF_REPEAT)
3251         return 0;
3252
3253     if ((HIWORD(lParam) & KF_ALTDOWN) && (keystate[VK_RMENU] & 0x80) == 0)
3254         left_alt = 1;
3255
3256     key_down = ((HIWORD(lParam) & KF_UP) == 0);
3257
3258     /* Make sure Ctrl-ALT is not the same as AltGr for ToAscii unless told. */
3259     if (left_alt && (keystate[VK_CONTROL] & 0x80)) {
3260         if (cfg.ctrlaltkeys)
3261             keystate[VK_MENU] = 0;
3262         else {
3263             keystate[VK_RMENU] = 0x80;
3264             left_alt = 0;
3265         }
3266     }
3267
3268     scan = (HIWORD(lParam) & (KF_UP | KF_EXTENDED | 0xFF));
3269     shift_state = ((keystate[VK_SHIFT] & 0x80) != 0)
3270         + ((keystate[VK_CONTROL] & 0x80) != 0) * 2;
3271
3272     /* Note if AltGr was pressed and if it was used as a compose key */
3273     if (!compose_state) {
3274         compose_key = 0x100;
3275         if (cfg.compose_key) {
3276             if (wParam == VK_MENU && (HIWORD(lParam) & KF_EXTENDED))
3277                 compose_key = wParam;
3278         }
3279         if (wParam == VK_APPS)
3280             compose_key = wParam;
3281     }
3282
3283     if (wParam == compose_key) {
3284         if (compose_state == 0
3285             && (HIWORD(lParam) & (KF_UP | KF_REPEAT)) == 0) compose_state =
3286                 1;
3287         else if (compose_state == 1 && (HIWORD(lParam) & KF_UP))
3288             compose_state = 2;
3289         else
3290             compose_state = 0;
3291     } else if (compose_state == 1 && wParam != VK_CONTROL)
3292         compose_state = 0;
3293
3294     if (compose_state > 1 && left_alt)
3295         compose_state = 0;
3296
3297     /* Sanitize the number pad if not using a PC NumPad */
3298     if (left_alt || (term->app_keypad_keys && !cfg.no_applic_k
3299                      && cfg.funky_type != 2)
3300         || cfg.funky_type == 3 || cfg.nethack_keypad || compose_state) {
3301         if ((HIWORD(lParam) & KF_EXTENDED) == 0) {
3302             int nParam = 0;
3303             switch (wParam) {
3304               case VK_INSERT:
3305                 nParam = VK_NUMPAD0;
3306                 break;
3307               case VK_END:
3308                 nParam = VK_NUMPAD1;
3309                 break;
3310               case VK_DOWN:
3311                 nParam = VK_NUMPAD2;
3312                 break;
3313               case VK_NEXT:
3314                 nParam = VK_NUMPAD3;
3315                 break;
3316               case VK_LEFT:
3317                 nParam = VK_NUMPAD4;
3318                 break;
3319               case VK_CLEAR:
3320                 nParam = VK_NUMPAD5;
3321                 break;
3322               case VK_RIGHT:
3323                 nParam = VK_NUMPAD6;
3324                 break;
3325               case VK_HOME:
3326                 nParam = VK_NUMPAD7;
3327                 break;
3328               case VK_UP:
3329                 nParam = VK_NUMPAD8;
3330                 break;
3331               case VK_PRIOR:
3332                 nParam = VK_NUMPAD9;
3333                 break;
3334               case VK_DELETE:
3335                 nParam = VK_DECIMAL;
3336                 break;
3337             }
3338             if (nParam) {
3339                 if (keystate[VK_NUMLOCK] & 1)
3340                     shift_state |= 1;
3341                 wParam = nParam;
3342             }
3343         }
3344     }
3345
3346     /* If a key is pressed and AltGr is not active */
3347     if (key_down && (keystate[VK_RMENU] & 0x80) == 0 && !compose_state) {
3348         /* Okay, prepare for most alts then ... */
3349         if (left_alt)
3350             *p++ = '\033';
3351
3352         /* Lets see if it's a pattern we know all about ... */
3353         if (wParam == VK_PRIOR && shift_state == 1) {
3354             SendMessage(hwnd, WM_VSCROLL, SB_PAGEUP, 0);
3355             return 0;
3356         }
3357         if (wParam == VK_PRIOR && shift_state == 2) {
3358             SendMessage(hwnd, WM_VSCROLL, SB_LINEUP, 0);
3359             return 0;
3360         }
3361         if (wParam == VK_NEXT && shift_state == 1) {
3362             SendMessage(hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
3363             return 0;
3364         }
3365         if (wParam == VK_NEXT && shift_state == 2) {
3366             SendMessage(hwnd, WM_VSCROLL, SB_LINEDOWN, 0);
3367             return 0;
3368         }
3369         if (wParam == VK_INSERT && shift_state == 1) {
3370             term_do_paste(term);
3371             return 0;
3372         }
3373         if (left_alt && wParam == VK_F4 && cfg.alt_f4) {
3374             return -1;
3375         }
3376         if (left_alt && wParam == VK_SPACE && cfg.alt_space) {
3377             SendMessage(hwnd, WM_SYSCOMMAND, SC_KEYMENU, 0);
3378             return -1;
3379         }
3380         if (left_alt && wParam == VK_RETURN && cfg.fullscreenonaltenter &&
3381             (cfg.resize_action != RESIZE_DISABLED)) {
3382             if ((HIWORD(lParam) & (KF_UP | KF_REPEAT)) != KF_REPEAT)
3383                 flip_full_screen();
3384             return -1;
3385         }
3386         /* Control-Numlock for app-keypad mode switch */
3387         if (wParam == VK_PAUSE && shift_state == 2) {
3388             term->app_keypad_keys ^= 1;
3389             return 0;
3390         }
3391
3392         /* Nethack keypad */
3393         if (cfg.nethack_keypad && !left_alt) {
3394             switch (wParam) {
3395               case VK_NUMPAD1:
3396                 *p++ = shift_state ? 'B' : 'b';
3397                 return p - output;
3398               case VK_NUMPAD2:
3399                 *p++ = shift_state ? 'J' : 'j';
3400                 return p - output;
3401               case VK_NUMPAD3:
3402                 *p++ = shift_state ? 'N' : 'n';
3403                 return p - output;
3404               case VK_NUMPAD4:
3405                 *p++ = shift_state ? 'H' : 'h';
3406                 return p - output;
3407               case VK_NUMPAD5:
3408                 *p++ = shift_state ? '.' : '.';
3409                 return p - output;
3410               case VK_NUMPAD6:
3411                 *p++ = shift_state ? 'L' : 'l';
3412                 return p - output;
3413               case VK_NUMPAD7:
3414                 *p++ = shift_state ? 'Y' : 'y';
3415                 return p - output;
3416               case VK_NUMPAD8:
3417                 *p++ = shift_state ? 'K' : 'k';
3418                 return p - output;
3419               case VK_NUMPAD9:
3420                 *p++ = shift_state ? 'U' : 'u';
3421                 return p - output;
3422             }
3423         }
3424
3425         /* Application Keypad */
3426         if (!left_alt) {
3427             int xkey = 0;
3428
3429             if (cfg.funky_type == 3 ||
3430                 (cfg.funky_type <= 1 &&
3431                  term->app_keypad_keys && !cfg.no_applic_k)) switch (wParam) {
3432                   case VK_EXECUTE:
3433                     xkey = 'P';
3434                     break;
3435                   case VK_DIVIDE:
3436                     xkey = 'Q';
3437                     break;
3438                   case VK_MULTIPLY:
3439                     xkey = 'R';
3440                     break;
3441                   case VK_SUBTRACT:
3442                     xkey = 'S';
3443                     break;
3444                 }
3445             if (term->app_keypad_keys && !cfg.no_applic_k)
3446                 switch (wParam) {
3447                   case VK_NUMPAD0:
3448                     xkey = 'p';
3449                     break;
3450                   case VK_NUMPAD1:
3451                     xkey = 'q';
3452                     break;
3453                   case VK_NUMPAD2:
3454                     xkey = 'r';
3455                     break;
3456                   case VK_NUMPAD3:
3457                     xkey = 's';
3458                     break;
3459                   case VK_NUMPAD4:
3460                     xkey = 't';
3461                     break;
3462                   case VK_NUMPAD5:
3463                     xkey = 'u';
3464                     break;
3465                   case VK_NUMPAD6:
3466                     xkey = 'v';
3467                     break;
3468                   case VK_NUMPAD7:
3469                     xkey = 'w';
3470                     break;
3471                   case VK_NUMPAD8:
3472                     xkey = 'x';
3473                     break;
3474                   case VK_NUMPAD9:
3475                     xkey = 'y';
3476                     break;
3477
3478                   case VK_DECIMAL:
3479                     xkey = 'n';
3480                     break;
3481                   case VK_ADD:
3482                     if (cfg.funky_type == 2) {
3483                         if (shift_state)
3484                             xkey = 'l';
3485                         else
3486                             xkey = 'k';
3487                     } else if (shift_state)
3488                         xkey = 'm';
3489                     else
3490                         xkey = 'l';
3491                     break;
3492
3493                   case VK_DIVIDE:
3494                     if (cfg.funky_type == 2)
3495                         xkey = 'o';
3496                     break;
3497                   case VK_MULTIPLY:
3498                     if (cfg.funky_type == 2)
3499                         xkey = 'j';
3500                     break;
3501                   case VK_SUBTRACT:
3502                     if (cfg.funky_type == 2)
3503                         xkey = 'm';
3504                     break;
3505
3506                   case VK_RETURN:
3507                     if (HIWORD(lParam) & KF_EXTENDED)
3508                         xkey = 'M';
3509                     break;
3510                 }
3511             if (xkey) {
3512                 if (term->vt52_mode) {
3513                     if (xkey >= 'P' && xkey <= 'S')
3514                         p += sprintf((char *) p, "\x1B%c", xkey);
3515                     else
3516                         p += sprintf((char *) p, "\x1B?%c", xkey);
3517                 } else
3518                     p += sprintf((char *) p, "\x1BO%c", xkey);
3519                 return p - output;
3520             }
3521         }
3522
3523         if (wParam == VK_BACK && shift_state == 0) {    /* Backspace */
3524             *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
3525             *p++ = 0;
3526             return -2;
3527         }
3528         if (wParam == VK_BACK && shift_state == 1) {    /* Shift Backspace */
3529             /* We do the opposite of what is configured */
3530             *p++ = (cfg.bksp_is_delete ? 0x08 : 0x7F);
3531             *p++ = 0;
3532             return -2;
3533         }
3534         if (wParam == VK_TAB && shift_state == 1) {     /* Shift tab */
3535             *p++ = 0x1B;
3536             *p++ = '[';
3537             *p++ = 'Z';
3538             return p - output;
3539         }
3540         if (wParam == VK_SPACE && shift_state == 2) {   /* Ctrl-Space */
3541             *p++ = 0;
3542             return p - output;
3543         }
3544         if (wParam == VK_SPACE && shift_state == 3) {   /* Ctrl-Shift-Space */
3545             *p++ = 160;
3546             return p - output;
3547         }
3548         if (wParam == VK_CANCEL && shift_state == 2) {  /* Ctrl-Break */
3549             *p++ = 3;
3550             *p++ = 0;
3551             return -2;
3552         }
3553         if (wParam == VK_PAUSE) {      /* Break/Pause */
3554             *p++ = 26;
3555             *p++ = 0;
3556             return -2;
3557         }
3558         /* Control-2 to Control-8 are special */
3559         if (shift_state == 2 && wParam >= '2' && wParam <= '8') {
3560             *p++ = "\000\033\034\035\036\037\177"[wParam - '2'];
3561             return p - output;
3562         }
3563         if (shift_state == 2 && (wParam == 0xBD || wParam == 0xBF)) {
3564             *p++ = 0x1F;
3565             return p - output;
3566         }
3567         if (shift_state == 2 && wParam == 0xDF) {
3568             *p++ = 0x1C;
3569             return p - output;
3570         }
3571         if (shift_state == 3 && wParam == 0xDE) {
3572             *p++ = 0x1E;               /* Ctrl-~ == Ctrl-^ in xterm at least */
3573             return p - output;
3574         }
3575         if (shift_state == 0 && wParam == VK_RETURN && term->cr_lf_return) {
3576             *p++ = '\r';
3577             *p++ = '\n';
3578             return p - output;
3579         }
3580
3581         /*
3582          * Next, all the keys that do tilde codes. (ESC '[' nn '~',
3583          * for integer decimal nn.)
3584          *
3585          * We also deal with the weird ones here. Linux VCs replace F1
3586          * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
3587          * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
3588          * respectively.
3589          */
3590         code = 0;
3591         switch (wParam) {
3592           case VK_F1:
3593             code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11);
3594             break;
3595           case VK_F2:
3596             code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12);
3597             break;
3598           case VK_F3:
3599             code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13);
3600             break;
3601           case VK_F4:
3602             code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14);
3603             break;
3604           case VK_F5:
3605             code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15);
3606             break;
3607           case VK_F6:
3608             code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17);
3609             break;
3610           case VK_F7:
3611             code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18);
3612             break;
3613           case VK_F8:
3614             code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19);
3615             break;
3616           case VK_F9:
3617             code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20);
3618             break;
3619           case VK_F10:
3620             code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21);
3621             break;
3622           case VK_F11:
3623             code = 23;
3624             break;
3625           case VK_F12:
3626             code = 24;
3627             break;
3628           case VK_F13:
3629             code = 25;
3630             break;
3631           case VK_F14:
3632             code = 26;
3633             break;
3634           case VK_F15:
3635             code = 28;
3636             break;
3637           case VK_F16:
3638             code = 29;
3639             break;
3640           case VK_F17:
3641             code = 31;
3642             break;
3643           case VK_F18:
3644             code = 32;
3645             break;
3646           case VK_F19:
3647             code = 33;
3648             break;
3649           case VK_F20:
3650             code = 34;
3651             break;
3652         }
3653         if ((shift_state&2) == 0) switch (wParam) {
3654           case VK_HOME:
3655             code = 1;
3656             break;
3657           case VK_INSERT:
3658             code = 2;
3659             break;
3660           case VK_DELETE:
3661             code = 3;
3662             break;
3663           case VK_END:
3664             code = 4;
3665             break;
3666           case VK_PRIOR:
3667             code = 5;
3668             break;
3669           case VK_NEXT:
3670             code = 6;
3671             break;
3672         }
3673         /* Reorder edit keys to physical order */
3674         if (cfg.funky_type == 3 && code <= 6)
3675             code = "\0\2\1\4\5\3\6"[code];
3676
3677         if (term->vt52_mode && code > 0 && code <= 6) {
3678             p += sprintf((char *) p, "\x1B%c", " HLMEIG"[code]);
3679             return p - output;
3680         }
3681
3682         if (cfg.funky_type == 5 &&     /* SCO function keys */
3683             code >= 11 && code <= 34) {
3684             char codes[] = "MNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@[\\]^_`{";
3685             int index = 0;
3686             switch (wParam) {
3687               case VK_F1: index = 0; break;
3688               case VK_F2: index = 1; break;
3689               case VK_F3: index = 2; break;
3690               case VK_F4: index = 3; break;
3691               case VK_F5: index = 4; break;
3692               case VK_F6: index = 5; break;
3693               case VK_F7: index = 6; break;
3694               case VK_F8: index = 7; break;
3695               case VK_F9: index = 8; break;
3696               case VK_F10: index = 9; break;
3697               case VK_F11: index = 10; break;
3698               case VK_F12: index = 11; break;
3699             }
3700             if (keystate[VK_SHIFT] & 0x80) index += 12;
3701             if (keystate[VK_CONTROL] & 0x80) index += 24;
3702             p += sprintf((char *) p, "\x1B[%c", codes[index]);
3703             return p - output;
3704         }
3705         if (cfg.funky_type == 5 &&     /* SCO small keypad */
3706             code >= 1 && code <= 6) {
3707             char codes[] = "HL.FIG";
3708             if (code == 3) {
3709                 *p++ = '\x7F';
3710             } else {
3711                 p += sprintf((char *) p, "\x1B[%c", codes[code-1]);
3712             }
3713             return p - output;
3714         }
3715         if ((term->vt52_mode || cfg.funky_type == 4) && code >= 11 && code <= 24) {
3716             int offt = 0;
3717             if (code > 15)
3718                 offt++;
3719             if (code > 21)
3720                 offt++;
3721             if (term->vt52_mode)
3722                 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11 - offt);
3723             else
3724                 p +=
3725                     sprintf((char *) p, "\x1BO%c", code + 'P' - 11 - offt);
3726             return p - output;
3727         }
3728         if (cfg.funky_type == 1 && code >= 11 && code <= 15) {
3729             p += sprintf((char *) p, "\x1B[[%c", code + 'A' - 11);
3730             return p - output;
3731         }
3732         if (cfg.funky_type == 2 && code >= 11 && code <= 14) {
3733             if (term->vt52_mode)
3734                 p += sprintf((char *) p, "\x1B%c", code + 'P' - 11);
3735             else
3736                 p += sprintf((char *) p, "\x1BO%c", code + 'P' - 11);
3737             return p - output;
3738         }
3739         if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
3740             p += sprintf((char *) p, code == 1 ? "\x1B[H" : "\x1BOw");
3741             return p - output;
3742         }
3743         if (code) {
3744             p += sprintf((char *) p, "\x1B[%d~", code);
3745             return p - output;
3746         }
3747
3748         /*
3749          * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
3750          * some reason seems to send VK_CLEAR to Windows...).
3751          */
3752         {
3753             char xkey = 0;
3754             switch (wParam) {
3755               case VK_UP:
3756                 xkey = 'A';
3757                 break;
3758               case VK_DOWN:
3759                 xkey = 'B';
3760                 break;
3761               case VK_RIGHT:
3762                 xkey = 'C';
3763                 break;
3764               case VK_LEFT:
3765                 xkey = 'D';
3766                 break;
3767               case VK_CLEAR:
3768                 xkey = 'G';
3769                 break;
3770             }
3771             if (xkey) {
3772                 if (term->vt52_mode)
3773                     p += sprintf((char *) p, "\x1B%c", xkey);
3774                 else {
3775                     int app_flg = (term->app_cursor_keys && !cfg.no_applic_c);
3776 #if 0
3777                     /*
3778                      * RDB: VT100 & VT102 manuals both state the
3779                      * app cursor keys only work if the app keypad
3780                      * is on.
3781                      * 
3782                      * SGT: That may well be true, but xterm
3783                      * disagrees and so does at least one
3784                      * application, so I've #if'ed this out and the
3785                      * behaviour is back to PuTTY's original: app
3786                      * cursor and app keypad are independently
3787                      * switchable modes. If anyone complains about
3788                      * _this_ I'll have to put in a configurable
3789                      * option.
3790                      */
3791                     if (!term->app_keypad_keys)
3792                         app_flg = 0;
3793 #endif
3794                     /* Useful mapping of Ctrl-arrows */
3795                     if (shift_state == 2)
3796                         app_flg = !app_flg;
3797
3798                     if (app_flg)
3799                         p += sprintf((char *) p, "\x1BO%c", xkey);
3800                     else
3801                         p += sprintf((char *) p, "\x1B[%c", xkey);
3802                 }
3803                 return p - output;
3804             }
3805         }
3806
3807         /*
3808          * Finally, deal with Return ourselves. (Win95 seems to
3809          * foul it up when Alt is pressed, for some reason.)
3810          */
3811         if (wParam == VK_RETURN) {     /* Return */
3812             *p++ = 0x0D;
3813             *p++ = 0;
3814             return -2;
3815         }
3816
3817         if (left_alt && wParam >= VK_NUMPAD0 && wParam <= VK_NUMPAD9)
3818             alt_sum = alt_sum * 10 + wParam - VK_NUMPAD0;
3819         else
3820             alt_sum = 0;
3821     }
3822
3823     /* Okay we've done everything interesting; let windows deal with 
3824      * the boring stuff */
3825     {
3826         BOOL capsOn=0;
3827
3828         /* helg: clear CAPS LOCK state if caps lock switches to cyrillic */
3829         if(cfg.xlat_capslockcyr && keystate[VK_CAPITAL] != 0) {
3830             capsOn= !left_alt;
3831             keystate[VK_CAPITAL] = 0;
3832         }
3833
3834         r = ToAsciiEx(wParam, scan, keystate, keys, 0, kbd_layout);
3835 #ifdef SHOW_TOASCII_RESULT
3836         if (r == 1 && !key_down) {
3837             if (alt_sum) {
3838                 if (in_utf(term) || ucsdata.dbcs_screenfont)
3839                     debug((", (U+%04x)", alt_sum));
3840                 else
3841                     debug((", LCH(%d)", alt_sum));
3842             } else {
3843                 debug((", ACH(%d)", keys[0]));
3844             }
3845         } else if (r > 0) {
3846             int r1;
3847             debug((", ASC("));
3848             for (r1 = 0; r1 < r; r1++) {
3849                 debug(("%s%d", r1 ? "," : "", keys[r1]));
3850             }
3851             debug((")"));
3852         }
3853 #endif
3854         if (r > 0) {
3855             WCHAR keybuf;
3856
3857             /*
3858              * Interrupt an ongoing paste. I'm not sure this is
3859              * sensible, but for the moment it's preferable to
3860              * having to faff about buffering things.
3861              */
3862             term_nopaste(term);
3863
3864             p = output;
3865             for (i = 0; i < r; i++) {
3866                 unsigned char ch = (unsigned char) keys[i];
3867
3868                 if (compose_state == 2 && (ch & 0x80) == 0 && ch > ' ') {
3869                     compose_char = ch;
3870                     compose_state++;
3871                     continue;
3872                 }
3873                 if (compose_state == 3 && (ch & 0x80) == 0 && ch > ' ') {
3874                     int nc;
3875                     compose_state = 0;
3876
3877                     if ((nc = check_compose(compose_char, ch)) == -1) {
3878                         MessageBeep(MB_ICONHAND);
3879                         return 0;
3880                     }
3881                     keybuf = nc;
3882                     term_seen_key_event(term);
3883                     luni_send(ldisc, &keybuf, 1, 1);
3884                     continue;
3885                 }
3886
3887                 compose_state = 0;
3888
3889                 if (!key_down) {
3890                     if (alt_sum) {
3891                         if (in_utf(term) || ucsdata.dbcs_screenfont) {
3892                             keybuf = alt_sum;
3893                             term_seen_key_event(term);
3894                             luni_send(ldisc, &keybuf, 1, 1);
3895                         } else {
3896                             ch = (char) alt_sum;
3897                             /*
3898                              * We need not bother about stdin
3899                              * backlogs here, because in GUI PuTTY
3900                              * we can't do anything about it
3901                              * anyway; there's no means of asking
3902                              * Windows to hold off on KEYDOWN
3903                              * messages. We _have_ to buffer
3904                              * everything we're sent.
3905                              */
3906                             term_seen_key_event(term);
3907                             ldisc_send(ldisc, &ch, 1, 1);
3908                         }
3909                         alt_sum = 0;
3910                     } else {
3911                         term_seen_key_event(term);
3912                         lpage_send(ldisc, kbd_codepage, &ch, 1, 1);
3913                     }
3914                 } else {
3915                     if(capsOn && ch < 0x80) {
3916                         WCHAR cbuf[2];
3917                         cbuf[0] = 27;
3918                         cbuf[1] = xlat_uskbd2cyrllic(ch);
3919                         term_seen_key_event(term);
3920                         luni_send(ldisc, cbuf+!left_alt, 1+!!left_alt, 1);
3921                     } else {
3922                         char cbuf[2];
3923                         cbuf[0] = '\033';
3924                         cbuf[1] = ch;
3925                         term_seen_key_event(term);
3926                         lpage_send(ldisc, kbd_codepage,
3927                                    cbuf+!left_alt, 1+!!left_alt, 1);
3928                     }
3929                 }
3930                 show_mouseptr(0);
3931             }
3932
3933             /* This is so the ALT-Numpad and dead keys work correctly. */
3934             keys[0] = 0;
3935
3936             return p - output;
3937         }
3938         /* If we're definitly not building up an ALT-54321 then clear it */
3939         if (!left_alt)
3940             keys[0] = 0;
3941         /* If we will be using alt_sum fix the 256s */
3942         else if (keys[0] && (in_utf(term) || ucsdata.dbcs_screenfont))
3943             keys[0] = 10;
3944     }
3945
3946     /*
3947      * ALT alone may or may not want to bring up the System menu.
3948      * If it's not meant to, we return 0 on presses or releases of
3949      * ALT, to show that we've swallowed the keystroke. Otherwise
3950      * we return -1, which means Windows will give the keystroke
3951      * its default handling (i.e. bring up the System menu).
3952      */
3953     if (wParam == VK_MENU && !cfg.alt_only)
3954         return 0;
3955
3956     return -1;
3957 }
3958
3959 void request_paste(void *frontend)
3960 {
3961     /*
3962      * In Windows, pasting is synchronous: we can read the
3963      * clipboard with no difficulty, so request_paste() can just go
3964      * ahead and paste.
3965      */
3966     term_do_paste(term);
3967 }
3968
3969 void set_title(void *frontend, char *title)
3970 {
3971     sfree(window_name);
3972     window_name = snewn(1 + strlen(title), char);
3973     strcpy(window_name, title);
3974     if (cfg.win_name_always || !IsIconic(hwnd))
3975         SetWindowText(hwnd, title);
3976 }
3977
3978 void set_icon(void *frontend, char *title)
3979 {
3980     sfree(icon_name);
3981     icon_name = snewn(1 + strlen(title), char);
3982     strcpy(icon_name, title);
3983     if (!cfg.win_name_always && IsIconic(hwnd))
3984         SetWindowText(hwnd, title);
3985 }
3986
3987 void set_sbar(void *frontend, int total, int start, int page)
3988 {
3989     SCROLLINFO si;
3990
3991     if (is_full_screen() ? !cfg.scrollbar_in_fullscreen : !cfg.scrollbar)
3992         return;
3993
3994     si.cbSize = sizeof(si);
3995     si.fMask = SIF_ALL | SIF_DISABLENOSCROLL;
3996     si.nMin = 0;
3997     si.nMax = total - 1;
3998     si.nPage = page;
3999     si.nPos = start;
4000     if (hwnd)
4001         SetScrollInfo(hwnd, SB_VERT, &si, TRUE);
4002 }
4003
4004 Context get_ctx(void *frontend)
4005 {
4006     HDC hdc;
4007     if (hwnd) {
4008         hdc = GetDC(hwnd);
4009         if (hdc && pal)
4010             SelectPalette(hdc, pal, FALSE);
4011         return hdc;
4012     } else
4013         return NULL;
4014 }
4015
4016 void free_ctx(Context ctx)
4017 {
4018     SelectPalette(ctx, GetStockObject(DEFAULT_PALETTE), FALSE);
4019     ReleaseDC(hwnd, ctx);
4020 }
4021
4022 static void real_palette_set(int n, int r, int g, int b)
4023 {
4024     if (pal) {
4025         logpal->palPalEntry[n].peRed = r;
4026         logpal->palPalEntry[n].peGreen = g;
4027         logpal->palPalEntry[n].peBlue = b;
4028         logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
4029         colours[n] = PALETTERGB(r, g, b);
4030         SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
4031     } else
4032         colours[n] = RGB(r, g, b);
4033 }
4034
4035 void palette_set(void *frontend, int n, int r, int g, int b)
4036 {
4037     static const int first[21] = {
4038         0, 2, 4, 6, 8, 10, 12, 14,
4039         1, 3, 5, 7, 9, 11, 13, 15,
4040         16, 17, 18, 20, 22
4041     };
4042     real_palette_set(first[n], r, g, b);
4043     if (first[n] >= 18)
4044         real_palette_set(first[n] + 1, r, g, b);
4045     if (pal) {
4046         HDC hdc = get_ctx(frontend);
4047         UnrealizeObject(pal);
4048         RealizePalette(hdc);
4049         free_ctx(hdc);
4050     }
4051 }
4052
4053 void palette_reset(void *frontend)
4054 {
4055     int i;
4056
4057     for (i = 0; i < NCOLOURS; i++) {
4058         if (pal) {
4059             logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
4060             logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
4061             logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
4062             logpal->palPalEntry[i].peFlags = 0;
4063             colours[i] = PALETTERGB(defpal[i].rgbtRed,
4064                                     defpal[i].rgbtGreen,
4065                                     defpal[i].rgbtBlue);
4066         } else
4067             colours[i] = RGB(defpal[i].rgbtRed,
4068                              defpal[i].rgbtGreen, defpal[i].rgbtBlue);
4069     }
4070
4071     if (pal) {
4072         HDC hdc;
4073         SetPaletteEntries(pal, 0, NCOLOURS, logpal->palPalEntry);
4074         hdc = get_ctx(frontend);
4075         RealizePalette(hdc);
4076         free_ctx(hdc);
4077     }
4078 }
4079
4080 void write_aclip(void *frontend, char *data, int len, int must_deselect)
4081 {
4082     HGLOBAL clipdata;
4083     void *lock;
4084
4085     clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
4086     if (!clipdata)
4087         return;
4088     lock = GlobalLock(clipdata);
4089     if (!lock)
4090         return;
4091     memcpy(lock, data, len);
4092     ((unsigned char *) lock)[len] = 0;
4093     GlobalUnlock(clipdata);
4094
4095     if (!must_deselect)
4096         SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4097
4098     if (OpenClipboard(hwnd)) {
4099         EmptyClipboard();
4100         SetClipboardData(CF_TEXT, clipdata);
4101         CloseClipboard();
4102     } else
4103         GlobalFree(clipdata);
4104
4105     if (!must_deselect)
4106         SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4107 }
4108
4109 /*
4110  * Note: unlike write_aclip() this will not append a nul.
4111  */
4112 void write_clip(void *frontend, wchar_t * data, int len, int must_deselect)
4113 {
4114     HGLOBAL clipdata, clipdata2, clipdata3;
4115     int len2;
4116     void *lock, *lock2, *lock3;
4117
4118     len2 = WideCharToMultiByte(CP_ACP, 0, data, len, 0, 0, NULL, NULL);
4119
4120     clipdata = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE,
4121                            len * sizeof(wchar_t));
4122     clipdata2 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, len2);
4123
4124     if (!clipdata || !clipdata2) {
4125         if (clipdata)
4126             GlobalFree(clipdata);
4127         if (clipdata2)
4128             GlobalFree(clipdata2);
4129         return;
4130     }
4131     if (!(lock = GlobalLock(clipdata)))
4132         return;
4133     if (!(lock2 = GlobalLock(clipdata2)))
4134         return;
4135
4136     memcpy(lock, data, len * sizeof(wchar_t));
4137     WideCharToMultiByte(CP_ACP, 0, data, len, lock2, len2, NULL, NULL);
4138
4139     if (cfg.rtf_paste) {
4140         wchar_t unitab[256];
4141         char *rtf = NULL;
4142         unsigned char *tdata = (unsigned char *)lock2;
4143         wchar_t *udata = (wchar_t *)lock;
4144         int rtflen = 0, uindex = 0, tindex = 0;
4145         int rtfsize = 0;
4146         int multilen, blen, alen, totallen, i;
4147         char before[16], after[4];
4148
4149         get_unitab(CP_ACP, unitab, 0);
4150
4151         rtfsize = 100 + strlen(cfg.font.name);
4152         rtf = snewn(rtfsize, char);
4153         sprintf(rtf, "{\\rtf1\\ansi%d{\\fonttbl\\f0\\fmodern %s;}\\f0",
4154                 GetACP(), cfg.font.name);
4155         rtflen = strlen(rtf);
4156
4157         /*
4158          * We want to construct a piece of RTF that specifies the
4159          * same Unicode text. To do this we will read back in
4160          * parallel from the Unicode data in `udata' and the
4161          * non-Unicode data in `tdata'. For each character in
4162          * `tdata' which becomes the right thing in `udata' when
4163          * looked up in `unitab', we just copy straight over from
4164          * tdata. For each one that doesn't, we must WCToMB it
4165          * individually and produce a \u escape sequence.
4166          * 
4167          * It would probably be more robust to just bite the bullet
4168          * and WCToMB each individual Unicode character one by one,
4169          * then MBToWC each one back to see if it was an accurate
4170          * translation; but that strikes me as a horrifying number
4171          * of Windows API calls so I want to see if this faster way
4172          * will work. If it screws up badly we can always revert to
4173          * the simple and slow way.
4174          */
4175         while (tindex < len2 && uindex < len &&
4176                tdata[tindex] && udata[uindex]) {
4177             if (tindex + 1 < len2 &&
4178                 tdata[tindex] == '\r' &&
4179                 tdata[tindex+1] == '\n') {
4180                 tindex++;
4181                 uindex++;
4182             }
4183             if (unitab[tdata[tindex]] == udata[uindex]) {
4184                 multilen = 1;
4185                 before[0] = '\0';
4186                 after[0] = '\0';
4187                 blen = alen = 0;
4188             } else {
4189                 multilen = WideCharToMultiByte(CP_ACP, 0, unitab+uindex, 1,
4190                                                NULL, 0, NULL, NULL);
4191                 if (multilen != 1) {
4192                     blen = sprintf(before, "{\\uc%d\\u%d", multilen,
4193                                    udata[uindex]);
4194                     alen = 1; strcpy(after, "}");
4195                 } else {
4196                     blen = sprintf(before, "\\u%d", udata[uindex]);
4197                     alen = 0; after[0] = '\0';
4198                 }
4199             }
4200             assert(tindex + multilen <= len2);
4201             totallen = blen + alen;
4202             for (i = 0; i < multilen; i++) {
4203                 if (tdata[tindex+i] == '\\' ||
4204                     tdata[tindex+i] == '{' ||
4205                     tdata[tindex+i] == '}')
4206                     totallen += 2;
4207                 else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A)
4208                     totallen += 6;     /* \par\r\n */
4209                 else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20)
4210                     totallen += 4;
4211                 else
4212                     totallen++;
4213             }
4214
4215             if (rtfsize < rtflen + totallen + 3) {
4216                 rtfsize = rtflen + totallen + 512;
4217                 rtf = sresize(rtf, rtfsize, char);
4218             }
4219
4220             strcpy(rtf + rtflen, before); rtflen += blen;
4221             for (i = 0; i < multilen; i++) {
4222                 if (tdata[tindex+i] == '\\' ||
4223                     tdata[tindex+i] == '{' ||
4224                     tdata[tindex+i] == '}') {
4225                     rtf[rtflen++] = '\\';
4226                     rtf[rtflen++] = tdata[tindex+i];
4227                 } else if (tdata[tindex+i] == 0x0D || tdata[tindex+i] == 0x0A) {
4228                     rtflen += sprintf(rtf+rtflen, "\\par\r\n");
4229                 } else if (tdata[tindex+i] > 0x7E || tdata[tindex+i] < 0x20) {
4230                     rtflen += sprintf(rtf+rtflen, "\\'%02x", tdata[tindex+i]);
4231                 } else {
4232                     rtf[rtflen++] = tdata[tindex+i];
4233                 }
4234             }
4235             strcpy(rtf + rtflen, after); rtflen += alen;
4236
4237             tindex += multilen;
4238             uindex++;
4239         }
4240
4241         strcpy(rtf + rtflen, "}");
4242         rtflen += 2;
4243
4244         clipdata3 = GlobalAlloc(GMEM_DDESHARE | GMEM_MOVEABLE, rtflen);
4245         if (clipdata3 && (lock3 = GlobalLock(clipdata3)) != NULL) {
4246             strcpy(lock3, rtf);
4247             GlobalUnlock(clipdata3);
4248         }
4249         sfree(rtf);
4250     } else
4251         clipdata3 = NULL;
4252
4253     GlobalUnlock(clipdata);
4254     GlobalUnlock(clipdata2);
4255
4256     if (!must_deselect)
4257         SendMessage(hwnd, WM_IGNORE_CLIP, TRUE, 0);
4258
4259     if (OpenClipboard(hwnd)) {
4260         EmptyClipboard();
4261         SetClipboardData(CF_UNICODETEXT, clipdata);
4262         SetClipboardData(CF_TEXT, clipdata2);
4263         if (clipdata3)
4264             SetClipboardData(RegisterClipboardFormat(CF_RTF), clipdata3);
4265         CloseClipboard();
4266     } else {
4267         GlobalFree(clipdata);
4268         GlobalFree(clipdata2);
4269     }
4270
4271     if (!must_deselect)
4272         SendMessage(hwnd, WM_IGNORE_CLIP, FALSE, 0);
4273 }
4274
4275 void get_clip(void *frontend, wchar_t ** p, int *len)
4276 {
4277     static HGLOBAL clipdata = NULL;
4278     static wchar_t *converted = 0;
4279     wchar_t *p2;
4280
4281     if (converted) {
4282         sfree(converted);
4283         converted = 0;
4284     }
4285     if (!p) {
4286         if (clipdata)
4287             GlobalUnlock(clipdata);
4288         clipdata = NULL;
4289         return;
4290     } else if (OpenClipboard(NULL)) {
4291         if ((clipdata = GetClipboardData(CF_UNICODETEXT))) {
4292             CloseClipboard();
4293             *p = GlobalLock(clipdata);
4294             if (*p) {
4295                 for (p2 = *p; *p2; p2++);
4296                 *len = p2 - *p;
4297                 return;
4298             }
4299         } else if ( (clipdata = GetClipboardData(CF_TEXT)) ) {
4300             char *s;
4301             int i;
4302             CloseClipboard();
4303             s = GlobalLock(clipdata);
4304             i = MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, 0, 0);
4305             *p = converted = snewn(i, wchar_t);
4306             MultiByteToWideChar(CP_ACP, 0, s, strlen(s) + 1, converted, i);
4307             *len = i - 1;
4308             return;
4309         } else
4310             CloseClipboard();
4311     }
4312
4313     *p = NULL;
4314     *len = 0;
4315 }
4316
4317 #if 0
4318 /*
4319  * Move `lines' lines from position `from' to position `to' in the
4320  * window.
4321  */
4322 void optimised_move(void *frontend, int to, int from, int lines)
4323 {
4324     RECT r;
4325     int min, max;
4326
4327     min = (to < from ? to : from);
4328     max = to + from - min;
4329
4330     r.left = offset_width;
4331     r.right = offset_width + term->cols * font_width;
4332     r.top = offset_height + min * font_height;
4333     r.bottom = offset_height + (max + lines) * font_height;
4334     ScrollWindow(hwnd, 0, (to - from) * font_height, &r, &r);
4335 }
4336 #endif
4337
4338 /*
4339  * Print a message box and perform a fatal exit.
4340  */
4341 void fatalbox(char *fmt, ...)
4342 {
4343     va_list ap;
4344     char *stuff, morestuff[100];
4345
4346     va_start(ap, fmt);
4347     stuff = dupvprintf(fmt, ap);
4348     va_end(ap);
4349     sprintf(morestuff, "%.70s Fatal Error", appname);
4350     MessageBox(hwnd, stuff, morestuff, MB_ICONERROR | MB_OK);
4351     sfree(stuff);
4352     cleanup_exit(1);
4353 }
4354
4355 /*
4356  * Print a modal (Really Bad) message box and perform a fatal exit.
4357  */
4358 void modalfatalbox(char *fmt, ...)
4359 {
4360     va_list ap;
4361     char *stuff, morestuff[100];
4362
4363     va_start(ap, fmt);
4364     stuff = dupvprintf(fmt, ap);
4365     va_end(ap);
4366     sprintf(morestuff, "%.70s Fatal Error", appname);
4367     MessageBox(hwnd, stuff, morestuff,
4368                MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
4369     sfree(stuff);
4370     cleanup_exit(1);
4371 }
4372
4373 /*
4374  * Manage window caption / taskbar flashing, if enabled.
4375  * 0 = stop, 1 = maintain, 2 = start
4376  */
4377 static void flash_window(int mode)
4378 {
4379     static long last_flash = 0;
4380     static int flashing = 0;
4381     if ((mode == 0) || (cfg.beep_ind == B_IND_DISABLED)) {
4382         /* stop */
4383         if (flashing) {
4384             FlashWindow(hwnd, FALSE);
4385             flashing = 0;
4386         }
4387
4388     } else if (mode == 2) {
4389         /* start */
4390         if (!flashing) {
4391             last_flash = GetTickCount();
4392             flashing = 1;
4393             FlashWindow(hwnd, TRUE);
4394         }
4395
4396     } else if ((mode == 1) && (cfg.beep_ind == B_IND_FLASH)) {
4397         /* maintain */
4398         if (flashing) {
4399             long now = GetTickCount();
4400             long fdiff = now - last_flash;
4401             if (fdiff < 0 || fdiff > 450) {
4402                 last_flash = now;
4403                 FlashWindow(hwnd, TRUE);        /* toggle */
4404             }
4405         }
4406     }
4407 }
4408
4409 /*
4410  * Beep.
4411  */
4412 void beep(void *frontend, int mode)
4413 {
4414     if (mode == BELL_DEFAULT) {
4415         /*
4416          * For MessageBeep style bells, we want to be careful of
4417          * timing, because they don't have the nice property of
4418          * PlaySound bells that each one cancels the previous
4419          * active one. So we limit the rate to one per 50ms or so.
4420          */
4421         static long lastbeep = 0;
4422         long beepdiff;
4423
4424         beepdiff = GetTickCount() - lastbeep;
4425         if (beepdiff >= 0 && beepdiff < 50)
4426             return;
4427         MessageBeep(MB_OK);
4428         /*
4429          * The above MessageBeep call takes time, so we record the
4430          * time _after_ it finishes rather than before it starts.
4431          */
4432         lastbeep = GetTickCount();
4433     } else if (mode == BELL_WAVEFILE) {
4434         if (!PlaySound(cfg.bell_wavefile.path, NULL,
4435                        SND_ASYNC | SND_FILENAME)) {
4436             char buf[sizeof(cfg.bell_wavefile.path) + 80];
4437             char otherbuf[100];
4438             sprintf(buf, "Unable to play sound file\n%s\n"
4439                     "Using default sound instead", cfg.bell_wavefile.path);
4440             sprintf(otherbuf, "%.70s Sound Error", appname);
4441             MessageBox(hwnd, buf, otherbuf,
4442                        MB_OK | MB_ICONEXCLAMATION);
4443             cfg.beep = BELL_DEFAULT;
4444         }
4445     } else if (mode == BELL_PCSPEAKER) {
4446         static long lastbeep = 0;
4447         long beepdiff;
4448
4449         beepdiff = GetTickCount() - lastbeep;
4450         if (beepdiff >= 0 && beepdiff < 50)
4451             return;
4452
4453         /*
4454          * We must beep in different ways depending on whether this
4455          * is a 95-series or NT-series OS.
4456          */
4457         if(osVersion.dwPlatformId == VER_PLATFORM_WIN32_NT)
4458             Beep(800, 100);
4459         else
4460             MessageBeep(-1);
4461         lastbeep = GetTickCount();
4462     }
4463     /* Otherwise, either visual bell or disabled; do nothing here */
4464     if (!term->has_focus) {
4465         flash_window(2);               /* start */
4466     }
4467 }
4468
4469 /*
4470  * Minimise or restore the window in response to a server-side
4471  * request.
4472  */
4473 void set_iconic(void *frontend, int iconic)
4474 {
4475     if (IsIconic(hwnd)) {
4476         if (!iconic)
4477             ShowWindow(hwnd, SW_RESTORE);
4478     } else {
4479         if (iconic)
4480             ShowWindow(hwnd, SW_MINIMIZE);
4481     }
4482 }
4483
4484 /*
4485  * Move the window in response to a server-side request.
4486  */
4487 void move_window(void *frontend, int x, int y)
4488 {
4489     if (cfg.resize_action == RESIZE_DISABLED || 
4490         cfg.resize_action == RESIZE_FONT ||
4491         IsZoomed(hwnd))
4492        return;
4493
4494     SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
4495 }
4496
4497 /*
4498  * Move the window to the top or bottom of the z-order in response
4499  * to a server-side request.
4500  */
4501 void set_zorder(void *frontend, int top)
4502 {
4503     if (cfg.alwaysontop)
4504         return;                        /* ignore */
4505     SetWindowPos(hwnd, top ? HWND_TOP : HWND_BOTTOM, 0, 0, 0, 0,
4506                  SWP_NOMOVE | SWP_NOSIZE);
4507 }
4508
4509 /*
4510  * Refresh the window in response to a server-side request.
4511  */
4512 void refresh_window(void *frontend)
4513 {
4514     InvalidateRect(hwnd, NULL, TRUE);
4515 }
4516
4517 /*
4518  * Maximise or restore the window in response to a server-side
4519  * request.
4520  */
4521 void set_zoomed(void *frontend, int zoomed)
4522 {
4523     if (IsZoomed(hwnd)) {
4524         if (!zoomed)
4525             ShowWindow(hwnd, SW_RESTORE);
4526     } else {
4527         if (zoomed)
4528             ShowWindow(hwnd, SW_MAXIMIZE);
4529     }
4530 }
4531
4532 /*
4533  * Report whether the window is iconic, for terminal reports.
4534  */
4535 int is_iconic(void *frontend)
4536 {
4537     return IsIconic(hwnd);
4538 }
4539
4540 /*
4541  * Report the window's position, for terminal reports.
4542  */
4543 void get_window_pos(void *frontend, int *x, int *y)
4544 {
4545     RECT r;
4546     GetWindowRect(hwnd, &r);
4547     *x = r.left;
4548     *y = r.top;
4549 }
4550
4551 /*
4552  * Report the window's pixel size, for terminal reports.
4553  */
4554 void get_window_pixels(void *frontend, int *x, int *y)
4555 {
4556     RECT r;
4557     GetWindowRect(hwnd, &r);
4558     *x = r.right - r.left;
4559     *y = r.bottom - r.top;
4560 }
4561
4562 /*
4563  * Return the window or icon title.
4564  */
4565 char *get_window_title(void *frontend, int icon)
4566 {
4567     return icon ? icon_name : window_name;
4568 }
4569
4570 /*
4571  * See if we're in full-screen mode.
4572  */
4573 int is_full_screen()
4574 {
4575     if (!IsZoomed(hwnd))
4576         return FALSE;
4577     if (GetWindowLong(hwnd, GWL_STYLE) & WS_CAPTION)
4578         return FALSE;
4579     return TRUE;
4580 }
4581
4582 /* Get the rect/size of a full screen window using the nearest available
4583  * monitor in multimon systems; default to something sensible if only
4584  * one monitor is present. */
4585 static int get_fullscreen_rect(RECT * ss)
4586 {
4587 #if defined(MONITOR_DEFAULTTONEAREST) && !defined(NO_MULTIMON)
4588         HMONITOR mon;
4589         MONITORINFO mi;
4590         mon = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
4591         mi.cbSize = sizeof(mi);
4592         GetMonitorInfo(mon, &mi);
4593
4594         /* structure copy */
4595         *ss = mi.rcMonitor;
4596         return TRUE;
4597 #else
4598 /* could also use code like this:
4599         ss->left = ss->top = 0;
4600         ss->right = GetSystemMetrics(SM_CXSCREEN);
4601         ss->bottom = GetSystemMetrics(SM_CYSCREEN);
4602 */ 
4603         return GetClientRect(GetDesktopWindow(), ss);
4604 #endif
4605 }
4606
4607
4608 /*
4609  * Go full-screen. This should only be called when we are already
4610  * maximised.
4611  */
4612 void make_full_screen()
4613 {
4614     DWORD style;
4615         RECT ss;
4616
4617     assert(IsZoomed(hwnd));
4618
4619         if (is_full_screen())
4620                 return;
4621         
4622     /* Remove the window furniture. */
4623     style = GetWindowLong(hwnd, GWL_STYLE);
4624     style &= ~(WS_CAPTION | WS_BORDER | WS_THICKFRAME);
4625     if (cfg.scrollbar_in_fullscreen)
4626         style |= WS_VSCROLL;
4627     else
4628         style &= ~WS_VSCROLL;
4629     SetWindowLong(hwnd, GWL_STYLE, style);
4630
4631     /* Resize ourselves to exactly cover the nearest monitor. */
4632         get_fullscreen_rect(&ss);
4633     SetWindowPos(hwnd, HWND_TOP, ss.left, ss.top,
4634                         ss.right - ss.left,
4635                         ss.bottom - ss.top,
4636                         SWP_FRAMECHANGED);
4637
4638     /* Tick the menu item in the System menu. */
4639     CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4640                   MF_CHECKED);
4641 }
4642
4643 /*
4644  * Clear the full-screen attributes.
4645  */
4646 void clear_full_screen()
4647 {
4648     DWORD oldstyle, style;
4649
4650     /* Reinstate the window furniture. */
4651     style = oldstyle = GetWindowLong(hwnd, GWL_STYLE);
4652     style |= WS_CAPTION | WS_BORDER;
4653     if (cfg.resize_action == RESIZE_DISABLED)
4654         style &= ~WS_THICKFRAME;
4655     else
4656         style |= WS_THICKFRAME;
4657     if (cfg.scrollbar)
4658         style |= WS_VSCROLL;
4659     else
4660         style &= ~WS_VSCROLL;
4661     if (style != oldstyle) {
4662         SetWindowLong(hwnd, GWL_STYLE, style);
4663         SetWindowPos(hwnd, NULL, 0, 0, 0, 0,
4664                      SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
4665                      SWP_FRAMECHANGED);
4666     }
4667
4668     /* Untick the menu item in the System menu. */
4669     CheckMenuItem(GetSystemMenu(hwnd, FALSE), IDM_FULLSCREEN,
4670                   MF_UNCHECKED);
4671 }
4672
4673 /*
4674  * Toggle full-screen mode.
4675  */
4676 void flip_full_screen()
4677 {
4678     if (is_full_screen()) {
4679         ShowWindow(hwnd, SW_RESTORE);
4680     } else if (IsZoomed(hwnd)) {
4681         make_full_screen();
4682     } else {
4683         SendMessage(hwnd, WM_FULLSCR_ON_MAX, 0, 0);
4684         ShowWindow(hwnd, SW_MAXIMIZE);
4685     }
4686 }
4687
4688 void frontend_keypress(void *handle)
4689 {
4690     /*
4691      * Keypress termination in non-Close-On-Exit mode is not
4692      * currently supported in PuTTY proper, because the window
4693      * always has a perfectly good Close button anyway. So we do
4694      * nothing here.
4695      */
4696     return;
4697 }
4698
4699 int from_backend(void *frontend, int is_stderr, const char *data, int len)
4700 {
4701     return term_data(term, is_stderr, data, len);
4702 }
4703
4704 void agent_schedule_callback(void (*callback)(void *, void *, int),
4705                              void *callback_ctx, void *data, int len)
4706 {
4707     struct agent_callback *c = snew(struct agent_callback);
4708     c->callback = callback;
4709     c->callback_ctx = callback_ctx;
4710     c->data = data;
4711     c->len = len;
4712     PostMessage(hwnd, WM_AGENT_CALLBACK, 0, (LPARAM)c);
4713 }