]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - window.c
Stop putting meaning in bottom four bits of WM_SYSCOMMAND wParam
[PuTTY.git] / window.c
1 #include <windows.h>
2 #include <commctrl.h>
3 #include <winsock.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6
7 #define PUTTY_DO_GLOBALS                       /* actually _define_ globals */
8 #include "putty.h"
9 #include "win_res.h"
10
11 #define IDM_SHOWLOG   0x0010
12 #define IDM_NEWSESS   0x0020
13 #define IDM_DUPSESS   0x0030
14 #define IDM_RECONF    0x0040
15 #define IDM_CLRSB     0x0050
16 #define IDM_RESET     0x0060
17 #define IDM_TEL_AYT   0x0070
18 #define IDM_TEL_BRK   0x0080
19 #define IDM_TEL_SYNCH 0x0090
20 #define IDM_TEL_EC    0x00a0
21 #define IDM_TEL_EL    0x00b0
22 #define IDM_TEL_GA    0x00c0
23 #define IDM_TEL_NOP   0x00d0
24 #define IDM_TEL_ABORT 0x00e0
25 #define IDM_TEL_AO    0x00f0
26 #define IDM_TEL_IP    0x0100
27 #define IDM_TEL_SUSP  0x0110
28 #define IDM_TEL_EOR   0x0120
29 #define IDM_TEL_EOF   0x0130
30 #define IDM_ABOUT     0x0140
31 #define IDM_SAVEDSESS 0x0150
32
33 #define IDM_SAVED_MIN 0x1000
34 #define IDM_SAVED_MAX 0x2000
35
36 #define WM_IGNORE_SIZE (WM_USER + 2)
37 #define WM_IGNORE_CLIP (WM_USER + 3)
38
39 static int WINAPI WndProc (HWND, UINT, WPARAM, LPARAM);
40 static int TranslateKey(WPARAM wParam, LPARAM lParam, unsigned char *output);
41 static void cfgtopalette(void);
42 static void init_palette(void);
43 static void init_fonts(void);
44
45 static int extra_width, extra_height;
46
47 #define FONT_NORMAL 0
48 #define FONT_BOLD 1
49 #define FONT_UNDERLINE 2
50 #define FONT_BOLDUND 3
51 #define FONT_OEM 4
52 #define FONT_OEMBOLD 5
53 #define FONT_OEMBOLDUND 6
54 #define FONT_OEMUND 7
55 static HFONT fonts[8];
56 static enum {
57     BOLD_COLOURS, BOLD_SHADOW, BOLD_FONT
58 } bold_mode;
59 static enum {
60     UND_LINE, UND_FONT
61 } und_mode;
62 static int descent;
63
64 #define NCOLOURS 24
65 static COLORREF colours[NCOLOURS];
66 static HPALETTE pal;
67 static LPLOGPALETTE logpal;
68 static RGBTRIPLE defpal[NCOLOURS];
69
70 static HWND hwnd;
71
72 static int dbltime, lasttime, lastact;
73 static Mouse_Button lastbtn;
74
75 static char *window_name, *icon_name;
76
77 int WINAPI WinMain(HINSTANCE inst, HINSTANCE prev, LPSTR cmdline, int show) {
78     static char appname[] = "PuTTY";
79     WORD winsock_ver;
80     WSADATA wsadata;
81     WNDCLASS wndclass;
82     MSG msg;
83     int guess_width, guess_height;
84
85     winsock_ver = MAKEWORD(1, 1);
86     if (WSAStartup(winsock_ver, &wsadata)) {
87         MessageBox(NULL, "Unable to initialise WinSock", "WinSock Error",
88                    MB_OK | MB_ICONEXCLAMATION);
89         return 1;
90     }
91     if (LOBYTE(wsadata.wVersion) != 1 || HIBYTE(wsadata.wVersion) != 1) {
92         MessageBox(NULL, "WinSock version is incompatible with 1.1",
93                    "WinSock Error", MB_OK | MB_ICONEXCLAMATION);
94         WSACleanup();
95         return 1;
96     }
97     /* WISHLIST: maybe allow config tweaking even if winsock not present? */
98
99     InitCommonControls();
100
101     /*
102      * Process the command line.
103      */
104     {
105         char *p;
106
107         default_protocol = DEFAULT_PROTOCOL;
108         default_port = DEFAULT_PORT;
109
110         do_defaults(NULL);
111
112         p = cmdline;
113         while (*p && isspace(*p)) p++;
114
115         /*
116          * Process command line options first. Yes, this can be
117          * done better, and it will be as soon as I have the
118          * energy...
119          */
120         while (*p == '-') {
121             char *q = p + strcspn(p, " \t");
122             p++;
123             if (q == p + 3 &&
124                 tolower(p[0]) == 's' &&
125                 tolower(p[1]) == 's' &&
126                 tolower(p[2]) == 'h') {
127                 default_protocol = cfg.protocol = PROT_SSH;
128                 default_port = cfg.port = 22;
129             }
130             p = q + strspn(q, " \t");
131         }
132
133         /*
134          * An initial @ means to activate a saved session.
135          */
136         if (*p == '@') {
137             do_defaults (p+1);
138             if (!*cfg.host && !do_config()) {
139                 WSACleanup();
140                 return 0;
141             }
142         } else if (*p == '&') {
143             /*
144              * An initial & means we've been given a command line
145              * containing the hex value of a HANDLE for a file
146              * mapping object, which we must then extract as a
147              * config.
148              */
149             HANDLE filemap;
150             Config *cp;
151             if (sscanf(p+1, "%x", &filemap) == 1 &&
152                 (cp = MapViewOfFile(filemap, FILE_MAP_READ,
153                                     0, 0, sizeof(Config))) != NULL) {
154                 cfg = *cp;
155                 UnmapViewOfFile(cp);
156                 CloseHandle(filemap);
157             } else if (!do_config()) {
158                 WSACleanup();
159                 return 0;
160             }
161         } else if (*p) {
162             char *q = p;
163             while (*p && !isspace(*p)) p++;
164             if (*p)
165                 *p++ = '\0';
166             strncpy (cfg.host, q, sizeof(cfg.host)-1);
167             cfg.host[sizeof(cfg.host)-1] = '\0';
168             while (*p && isspace(*p)) p++;
169             if (*p)
170                 cfg.port = atoi(p);
171             else
172                 cfg.port = -1;
173         } else {
174             if (!do_config()) {
175                 WSACleanup();
176                 return 0;
177             }
178         }
179     }
180
181     back = (cfg.protocol == PROT_SSH ? &ssh_backend : &telnet_backend);
182
183     if (!prev) {
184         wndclass.style         = 0;
185         wndclass.lpfnWndProc   = WndProc;
186         wndclass.cbClsExtra    = 0;
187         wndclass.cbWndExtra    = 0;
188         wndclass.hInstance     = inst;
189         wndclass.hIcon         = LoadIcon (inst,
190                                            MAKEINTRESOURCE(IDI_MAINICON));
191         wndclass.hCursor       = LoadCursor (NULL, IDC_IBEAM);
192         wndclass.hbrBackground = GetStockObject (BLACK_BRUSH);
193         wndclass.lpszMenuName  = NULL;
194         wndclass.lpszClassName = appname;
195
196         RegisterClass (&wndclass);
197     }
198
199     hwnd = NULL;
200
201     savelines = cfg.savelines;
202     term_init();
203
204     cfgtopalette();
205
206     /*
207      * Guess some defaults for the window size. This all gets
208      * updated later, so we don't really care too much. However, we
209      * do want the font width/height guesses to correspond to a
210      * large font rather than a small one...
211      */
212     
213     font_width = 10;
214     font_height = 20;
215     extra_width = 25;
216     extra_height = 28;
217     term_size (cfg.height, cfg.width, cfg.savelines);
218     guess_width = extra_width + font_width * cols;
219     guess_height = extra_height + font_height * rows;
220     {
221         RECT r;
222         HWND w = GetDesktopWindow();
223         GetWindowRect (w, &r);
224         if (guess_width > r.right - r.left)
225             guess_width = r.right - r.left;
226         if (guess_height > r.bottom - r.top)
227             guess_height = r.bottom - r.top;
228     }
229
230     hwnd = CreateWindow (appname, appname,
231                          WS_OVERLAPPEDWINDOW | WS_VSCROLL,
232                          CW_USEDEFAULT, CW_USEDEFAULT,
233                          guess_width, guess_height,
234                          NULL, NULL, inst, NULL);
235
236     /*
237      * Initialise the fonts, simultaneously correcting the guesses
238      * for font_{width,height}.
239      */
240     bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
241     und_mode = UND_FONT;
242     init_fonts();
243
244     /*
245      * Correct the guesses for extra_{width,height}.
246      */
247     {
248         RECT cr, wr;
249         GetWindowRect (hwnd, &wr);
250         GetClientRect (hwnd, &cr);
251         extra_width = wr.right - wr.left - cr.right + cr.left;
252         extra_height = wr.bottom - wr.top - cr.bottom + cr.top;
253     }
254
255     /*
256      * Resize the window, now we know what size we _really_ want it
257      * to be.
258      */
259     guess_width = extra_width + font_width * cols;
260     guess_height = extra_height + font_height * rows;
261     SendMessage (hwnd, WM_IGNORE_SIZE, 0, 0);
262     SetWindowPos (hwnd, NULL, 0, 0, guess_width, guess_height,
263                   SWP_NOMOVE | SWP_NOREDRAW | SWP_NOZORDER);
264
265     /*
266      * Initialise the scroll bar.
267      */
268     {
269         SCROLLINFO si;
270
271         si.cbSize = sizeof(si);
272         si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS | SIF_DISABLENOSCROLL;
273         si.nMin = 0;
274         si.nMax = rows-1;
275         si.nPage = rows;
276         si.nPos = 0;
277         SetScrollInfo (hwnd, SB_VERT, &si, FALSE);
278     }
279
280     /*
281      * Start up the telnet connection.
282      */
283     {
284         char *error;
285         char msg[1024];
286         char *realhost;
287
288         error = back->init (hwnd, cfg.host, cfg.port, &realhost);
289         if (error) {
290             sprintf(msg, "Unable to open connection:\n%s", error);
291             MessageBox(NULL, msg, "PuTTY Error", MB_ICONERROR | MB_OK);
292             return 0;
293         }
294         window_name = icon_name = NULL;
295         sprintf(msg, "%s - PuTTY", realhost);
296         set_title (msg);
297         set_icon (msg);
298     }
299
300     /*
301      * Set up the input and output buffers.
302      */
303     inbuf_reap = inbuf_head = 0;
304     outbuf_reap = outbuf_head = 0;
305
306     /*
307      * Prepare the mouse handler.
308      */
309     lastact = MA_NOTHING;
310     lastbtn = MB_NOTHING;
311     dbltime = GetDoubleClickTime();
312
313     /*
314      * Set up the session-control options on the system menu.
315      */
316     {
317         HMENU m = GetSystemMenu (hwnd, FALSE);
318         HMENU p,s;
319         int i;
320
321         AppendMenu (m, MF_SEPARATOR, 0, 0);
322         if (cfg.protocol == PROT_TELNET) {
323             p = CreateMenu();
324             AppendMenu (p, MF_ENABLED, IDM_TEL_AYT, "Are You There");
325             AppendMenu (p, MF_ENABLED, IDM_TEL_BRK, "Break");
326             AppendMenu (p, MF_ENABLED, IDM_TEL_SYNCH, "Synch");
327             AppendMenu (p, MF_SEPARATOR, 0, 0);
328             AppendMenu (p, MF_ENABLED, IDM_TEL_EC, "Erase Character");
329             AppendMenu (p, MF_ENABLED, IDM_TEL_EL, "Erase Line");
330             AppendMenu (p, MF_ENABLED, IDM_TEL_GA, "Go Ahead");
331             AppendMenu (p, MF_ENABLED, IDM_TEL_NOP, "No Operation");
332             AppendMenu (p, MF_SEPARATOR, 0, 0);
333             AppendMenu (p, MF_ENABLED, IDM_TEL_ABORT, "Abort Process");
334             AppendMenu (p, MF_ENABLED, IDM_TEL_AO, "Abort Output");
335             AppendMenu (p, MF_ENABLED, IDM_TEL_IP, "Interrupt Process");
336             AppendMenu (p, MF_ENABLED, IDM_TEL_SUSP, "Suspend Process");
337             AppendMenu (p, MF_SEPARATOR, 0, 0);
338             AppendMenu (p, MF_ENABLED, IDM_TEL_EOR, "End Of Record");
339             AppendMenu (p, MF_ENABLED, IDM_TEL_EOF, "End Of File");
340             AppendMenu (m, MF_POPUP | MF_ENABLED, (UINT) p, "Telnet Command");
341             AppendMenu (m, MF_ENABLED, IDM_SHOWLOG, "Show Negotiation");
342             AppendMenu (m, MF_SEPARATOR, 0, 0);
343         }
344         AppendMenu (m, MF_ENABLED, IDM_NEWSESS, "New Session");
345         AppendMenu (m, MF_ENABLED, IDM_DUPSESS, "Duplicate Session");
346         s = CreateMenu();
347         get_sesslist(TRUE);
348         for (i = 1 ; i < ((nsessions < 256) ? nsessions : 256) ; i++)
349           AppendMenu (s, MF_ENABLED, IDM_SAVED_MIN + (16 * i) , sessions[i]);
350         AppendMenu (m, MF_POPUP | MF_ENABLED, (UINT) s, "Saved Sessions");
351         AppendMenu (m, MF_ENABLED, IDM_RECONF, "Change Settings");
352         AppendMenu (m, MF_SEPARATOR, 0, 0);
353         AppendMenu (m, MF_ENABLED, IDM_CLRSB, "Clear Scrollback");
354         AppendMenu (m, MF_ENABLED, IDM_RESET, "Reset Terminal");
355         AppendMenu (m, MF_SEPARATOR, 0, 0);
356         AppendMenu (m, MF_ENABLED, IDM_ABOUT, "About PuTTY");
357     }
358
359     /*
360      * Finally show the window!
361      */
362     ShowWindow (hwnd, show);
363
364     /*
365      * Set the palette up.
366      */
367     pal = NULL;
368     logpal = NULL;
369     init_palette();
370
371     has_focus = (GetForegroundWindow() == hwnd);
372     UpdateWindow (hwnd);
373
374     while (GetMessage (&msg, NULL, 0, 0)) {
375         DispatchMessage (&msg);
376         if (inbuf_reap != inbuf_head)
377             term_out();
378         /* In idle moments, do a full screen update */
379         if (!PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE))
380             term_update();
381     }
382
383     /*
384      * Clean up.
385      */
386     {
387         int i;
388         for (i=0; i<8; i++)
389             if (fonts[i])
390                 DeleteObject(fonts[i]);
391     }
392     sfree(logpal);
393     if (pal)
394         DeleteObject(pal);
395     WSACleanup();
396
397     if (cfg.protocol == PROT_SSH)
398         random_save_seed();
399
400     return msg.wParam;
401 }
402
403 /*
404  * Copy the colour palette from the configuration data into defpal.
405  * This is non-trivial because the colour indices are different.
406  */
407 static void cfgtopalette(void) {
408     int i;
409     static const int ww[] = {
410         6, 7, 8, 9, 10, 11, 12, 13,
411         14, 15, 16, 17, 18, 19, 20, 21,
412         0, 1, 2, 3, 4, 4, 5, 5
413     };
414
415     for (i=0; i<24; i++) {
416         int w = ww[i];
417         defpal[i].rgbtRed = cfg.colours[w][0];
418         defpal[i].rgbtGreen = cfg.colours[w][1];
419         defpal[i].rgbtBlue = cfg.colours[w][2];
420     }
421 }
422
423 /*
424  * Set up the colour palette.
425  */
426 static void init_palette(void) {
427     int i;
428     HDC hdc = GetDC (hwnd);
429     if (hdc) {
430         if (cfg.try_palette &&
431             GetDeviceCaps (hdc, RASTERCAPS) & RC_PALETTE) {
432             logpal = smalloc(sizeof(*logpal)
433                              - sizeof(logpal->palPalEntry)
434                              + NCOLOURS * sizeof(PALETTEENTRY));
435             logpal->palVersion = 0x300;
436             logpal->palNumEntries = NCOLOURS;
437             for (i = 0; i < NCOLOURS; i++) {
438                 logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
439                 logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
440                 logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
441                 logpal->palPalEntry[i].peFlags = PC_NOCOLLAPSE;
442             }
443             pal = CreatePalette (logpal);
444             if (pal) {
445                 SelectPalette (hdc, pal, FALSE);
446                 RealizePalette (hdc);
447                 SelectPalette (hdc, GetStockObject (DEFAULT_PALETTE),
448                                FALSE);
449             }
450         }
451         ReleaseDC (hwnd, hdc);
452     }
453     if (pal)
454         for (i=0; i<NCOLOURS; i++)
455             colours[i] = PALETTERGB(defpal[i].rgbtRed,
456                                     defpal[i].rgbtGreen,
457                                     defpal[i].rgbtBlue);
458     else
459         for(i=0; i<NCOLOURS; i++)
460             colours[i] = RGB(defpal[i].rgbtRed,
461                              defpal[i].rgbtGreen,
462                              defpal[i].rgbtBlue);
463 }
464
465 /*
466  * Initialise all the fonts we will need. There may be as many as
467  * eight or as few as one. We also:
468  *
469  * - check the font width and height, correcting our guesses if
470  *   necessary.
471  *
472  * - verify that the bold font is the same width as the ordinary
473  *   one, and engage shadow bolding if not.
474  * 
475  * - verify that the underlined font is the same width as the
476  *   ordinary one (manual underlining by means of line drawing can
477  *   be done in a pinch).
478  *
479  * - verify, in OEM/ANSI combined mode, that the OEM and ANSI base
480  *   fonts are the same size, and shift to OEM-only mode if not.
481  */
482 static void init_fonts(void) {
483     TEXTMETRIC tm;
484     int i, j;
485     int widths[5];
486     HDC hdc;
487     int fw_dontcare, fw_bold;
488
489     for (i=0; i<8; i++)
490         fonts[i] = NULL;
491
492     if (cfg.fontisbold) {
493         fw_dontcare = FW_BOLD;
494         fw_bold = FW_BLACK;
495    } else {
496         fw_dontcare = FW_DONTCARE;
497         fw_bold = FW_BOLD;
498     }
499
500 #define f(i,c,w,u) \
501     fonts[i] = CreateFont (cfg.fontheight, 0, 0, 0, w, FALSE, u, FALSE, \
502                            c, OUT_DEFAULT_PRECIS, \
503                            CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, \
504                            FIXED_PITCH | FF_DONTCARE, cfg.font)
505     if (cfg.vtmode != VT_OEMONLY) {
506         f(FONT_NORMAL, ANSI_CHARSET, fw_dontcare, FALSE);
507         f(FONT_UNDERLINE, ANSI_CHARSET, fw_dontcare, TRUE);
508     }
509     if (cfg.vtmode == VT_OEMANSI || cfg.vtmode == VT_OEMONLY) {
510         f(FONT_OEM, OEM_CHARSET, fw_dontcare, FALSE);
511         f(FONT_OEMUND, OEM_CHARSET, fw_dontcare, TRUE);
512     }
513     if (bold_mode == BOLD_FONT) {
514         if (cfg.vtmode != VT_OEMONLY) {
515             f(FONT_BOLD, ANSI_CHARSET, fw_bold, FALSE);
516             f(FONT_BOLDUND, ANSI_CHARSET, fw_bold, TRUE);
517         }
518         if (cfg.vtmode == VT_OEMANSI || cfg.vtmode == VT_OEMONLY) {
519             f(FONT_OEMBOLD, OEM_CHARSET, fw_bold, FALSE);
520             f(FONT_OEMBOLDUND, OEM_CHARSET, fw_bold, TRUE);
521         }
522     } else {
523         fonts[FONT_BOLD] = fonts[FONT_BOLDUND] = NULL;
524         fonts[FONT_OEMBOLD] = fonts[FONT_OEMBOLDUND] = NULL;
525     }
526 #undef f
527
528     hdc = GetDC(hwnd);
529
530     if (cfg.vtmode == VT_OEMONLY)
531         j = 4;
532     else
533         j = 0;
534
535     for (i=0; i<(cfg.vtmode == VT_OEMANSI ? 5 : 4); i++) {
536         if (fonts[i+j]) {
537             SelectObject (hdc, fonts[i+j]);
538             GetTextMetrics(hdc, &tm);
539             if (i == 0 || i == 4) {
540                 font_height = tm.tmHeight;
541                 font_width = tm.tmAveCharWidth;
542                 descent = tm.tmAscent + 1;
543                 if (descent >= font_height)
544                     descent = font_height - 1;
545             }
546             widths[i] = tm.tmAveCharWidth;
547         }
548     }
549
550     ReleaseDC (hwnd, hdc);
551
552     if (widths[FONT_UNDERLINE] != widths[FONT_NORMAL] ||
553         (bold_mode == BOLD_FONT &&
554          widths[FONT_BOLDUND] != widths[FONT_BOLD])) {
555         und_mode = UND_LINE;
556         DeleteObject (fonts[FONT_UNDERLINE]);
557         if (bold_mode == BOLD_FONT)
558             DeleteObject (fonts[FONT_BOLDUND]);
559     }
560
561     if (bold_mode == BOLD_FONT &&
562         widths[FONT_BOLD] != widths[FONT_NORMAL]) {
563         bold_mode = BOLD_SHADOW;
564         DeleteObject (fonts[FONT_BOLD]);
565         if (und_mode == UND_FONT)
566             DeleteObject (fonts[FONT_BOLDUND]);
567     }
568
569     if (cfg.vtmode == VT_OEMANSI && widths[FONT_OEM] != widths[FONT_NORMAL]) {
570         MessageBox(NULL, "The OEM and ANSI versions of this font are\n"
571                    "different sizes. Using OEM-only mode instead",
572                    "Font Size Mismatch", MB_ICONINFORMATION | MB_OK);
573         cfg.vtmode = VT_OEMONLY;
574         for (i=0; i<4; i++)
575             if (fonts[i])
576                 DeleteObject (fonts[i]);
577     }
578 }
579
580 void request_resize (int w, int h) {
581     int width = extra_width + font_width * w;
582     int height = extra_height + font_height * h;
583
584     SetWindowPos (hwnd, NULL, 0, 0, width, height,
585                   SWP_NOACTIVATE | SWP_NOCOPYBITS |
586                   SWP_NOMOVE | SWP_NOZORDER);
587 }
588
589 static void click (Mouse_Button b, int x, int y) {
590     int thistime = GetMessageTime();
591
592     if (lastbtn == b && thistime - lasttime < dbltime) {
593         lastact = (lastact == MA_CLICK ? MA_2CLK :
594                    lastact == MA_2CLK ? MA_3CLK :
595                    lastact == MA_3CLK ? MA_CLICK : MA_NOTHING);
596     } else {
597         lastbtn = b;
598         lastact = MA_CLICK;
599     }
600     if (lastact != MA_NOTHING)
601         term_mouse (b, lastact, x, y);
602     lasttime = thistime;
603 }
604
605 static int WINAPI WndProc (HWND hwnd, UINT message,
606                            WPARAM wParam, LPARAM lParam) {
607     HDC hdc;
608     static int ignore_size = FALSE;
609     static int ignore_clip = FALSE;
610     static int just_reconfigged = FALSE;
611
612     switch (message) {
613       case WM_CREATE:
614         break;
615       case WM_DESTROY:
616         PostQuitMessage (0);
617         return 0;
618       case WM_SYSCOMMAND:
619         switch (wParam & ~0xF) {       /* low 4 bits reserved to Windows */
620           case IDM_SHOWLOG:
621             shownegot(hwnd);
622             break;
623           case IDM_NEWSESS:
624           case IDM_DUPSESS:
625           case IDM_SAVEDSESS:
626             {
627                 char b[2048];
628                 char c[30], *cl;
629                 STARTUPINFO si;
630                 PROCESS_INFORMATION pi;
631                 HANDLE filemap = NULL;
632
633                 if (wParam == IDM_DUPSESS) {
634                     /*
635                      * Allocate a file-mapping memory chunk for the
636                      * config structure.
637                      */
638                     SECURITY_ATTRIBUTES sa;
639                     Config *p;
640
641                     sa.nLength = sizeof(sa);
642                     sa.lpSecurityDescriptor = NULL;
643                     sa.bInheritHandle = TRUE;
644                     filemap = CreateFileMapping((HANDLE)0xFFFFFFFF,
645                                                 &sa,
646                                                 PAGE_READWRITE,
647                                                 0,
648                                                 sizeof(Config),
649                                                 NULL);
650                     if (filemap) {
651                         p = (Config *)MapViewOfFile(filemap,
652                                                     FILE_MAP_WRITE,
653                                                     0, 0, sizeof(Config));
654                         if (p) {
655                             *p = cfg;  /* structure copy */
656                             UnmapViewOfFile(p);
657                         }
658                     }
659                     sprintf(c, "putty &%08x", filemap);
660                     cl = c;
661                 } else if (wParam == IDM_SAVEDSESS) {
662                     sprintf(c, "putty @%s",
663                             sessions[(lParam - IDM_SAVED_MIN) / 16]);
664                     cl = c;
665                 } else
666                     cl = NULL;
667
668                 GetModuleFileName (NULL, b, sizeof(b)-1);
669                 si.cb = sizeof(si);
670                 si.lpReserved = NULL;
671                 si.lpDesktop = NULL;
672                 si.lpTitle = NULL;
673                 si.dwFlags = 0;
674                 si.cbReserved2 = 0;
675                 si.lpReserved2 = NULL;
676                 CreateProcess (b, cl, NULL, NULL, TRUE,
677                                NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
678
679                 if (filemap)
680                     CloseHandle(filemap);
681             }
682             break;
683           case IDM_RECONF:
684             if (!do_reconfig(hwnd))
685                 break;
686             just_reconfigged = TRUE;
687             {
688                 int i;
689                 for (i=0; i<8; i++)
690                     if (fonts[i])
691                         DeleteObject(fonts[i]);
692             }
693             bold_mode = cfg.bold_colour ? BOLD_COLOURS : BOLD_FONT;
694             und_mode = UND_FONT;
695             init_fonts();
696             sfree(logpal);
697             if (pal)
698                 DeleteObject(pal);
699             logpal = NULL;
700             pal = NULL;
701             cfgtopalette();
702             init_palette();
703             term_size(cfg.height, cfg.width, cfg.savelines);
704             InvalidateRect(hwnd, NULL, TRUE);
705             SetWindowPos (hwnd, NULL, 0, 0,
706                           extra_width + font_width * cfg.width,
707                           extra_height + font_height * cfg.height,
708                           SWP_NOACTIVATE | SWP_NOCOPYBITS |
709                           SWP_NOMOVE | SWP_NOZORDER);
710             if (IsIconic(hwnd)) {
711                 SetWindowText (hwnd,
712                                cfg.win_name_always ? window_name : icon_name);
713             }
714             break;
715           case IDM_CLRSB:
716             term_clrsb();
717             break;
718           case IDM_RESET:
719             term_pwron();
720             break;
721           case IDM_TEL_AYT: back->special (TS_AYT); break;
722           case IDM_TEL_BRK: back->special (TS_BRK); break;
723           case IDM_TEL_SYNCH: back->special (TS_SYNCH); break;
724           case IDM_TEL_EC: back->special (TS_EC); break;
725           case IDM_TEL_EL: back->special (TS_EL); break;
726           case IDM_TEL_GA: back->special (TS_GA); break;
727           case IDM_TEL_NOP: back->special (TS_NOP); break;
728           case IDM_TEL_ABORT: back->special (TS_ABORT); break;
729           case IDM_TEL_AO: back->special (TS_AO); break;
730           case IDM_TEL_IP: back->special (TS_IP); break;
731           case IDM_TEL_SUSP: back->special (TS_SUSP); break;
732           case IDM_TEL_EOR: back->special (TS_EOR); break;
733           case IDM_TEL_EOF: back->special (TS_EOF); break;
734           case IDM_ABOUT:
735             showabout (hwnd);
736             break;
737         default:
738           if (wParam >= IDM_SAVED_MIN && wParam <= IDM_SAVED_MAX) {
739             SendMessage(hwnd, WM_SYSCOMMAND, IDM_SAVEDSESS, wParam);
740           }
741         }
742         break;
743
744 #define X_POS(l) ((int)(short)LOWORD(l))
745 #define Y_POS(l) ((int)(short)HIWORD(l))
746
747 #define TO_CHR_X(x) (((x)<0 ? (x)-font_width+1 : (x)) / font_width)
748 #define TO_CHR_Y(y) (((y)<0 ? (y)-font_height+1: (y)) / font_height)
749
750       case WM_LBUTTONDOWN:
751         click (MB_SELECT, TO_CHR_X(X_POS(lParam)),
752                TO_CHR_Y(Y_POS(lParam)));
753         SetCapture(hwnd);
754         return 0;
755       case WM_LBUTTONUP:
756         term_mouse (MB_SELECT, MA_RELEASE, TO_CHR_X(X_POS(lParam)),
757                     TO_CHR_Y(Y_POS(lParam)));
758         ReleaseCapture();
759         return 0;
760       case WM_MBUTTONDOWN:
761         SetCapture(hwnd);
762         click (cfg.mouse_is_xterm ? MB_PASTE : MB_EXTEND,
763                TO_CHR_X(X_POS(lParam)),
764                TO_CHR_Y(Y_POS(lParam)));
765         return 0;
766       case WM_MBUTTONUP:
767         term_mouse (cfg.mouse_is_xterm ? MB_PASTE : MB_EXTEND,
768                     MA_RELEASE, TO_CHR_X(X_POS(lParam)),
769                     TO_CHR_Y(Y_POS(lParam)));
770         ReleaseCapture();
771         return 0;
772       case WM_RBUTTONDOWN:
773         SetCapture(hwnd);
774         click (cfg.mouse_is_xterm ? MB_EXTEND : MB_PASTE,
775                TO_CHR_X(X_POS(lParam)),
776                TO_CHR_Y(Y_POS(lParam)));
777         return 0;
778       case WM_RBUTTONUP:
779         term_mouse (cfg.mouse_is_xterm ? MB_EXTEND : MB_PASTE,
780                     MA_RELEASE, TO_CHR_X(X_POS(lParam)),
781                     TO_CHR_Y(Y_POS(lParam)));
782         ReleaseCapture();
783         return 0;
784       case WM_MOUSEMOVE:
785         /*
786          * Add the mouse position and message time to the random
787          * number noise, if we're using ssh.
788          */
789         if (cfg.protocol == PROT_SSH)
790             noise_ultralight(lParam);
791
792         if (wParam & (MK_LBUTTON | MK_MBUTTON | MK_RBUTTON)) {
793             Mouse_Button b;
794             if (wParam & MK_LBUTTON)
795                 b = MB_SELECT;
796             else if (wParam & MK_MBUTTON)
797                 b = cfg.mouse_is_xterm ? MB_PASTE : MB_EXTEND;
798             else
799                 b = cfg.mouse_is_xterm ? MB_EXTEND : MB_PASTE;
800             term_mouse (b, MA_DRAG, TO_CHR_X(X_POS(lParam)),
801                         TO_CHR_Y(Y_POS(lParam)));
802         }
803         return 0;
804       case WM_IGNORE_CLIP:
805         ignore_clip = wParam;          /* don't panic on DESTROYCLIPBOARD */
806         break;
807       case WM_DESTROYCLIPBOARD:
808         if (!ignore_clip)
809             term_deselect();
810         ignore_clip = FALSE;
811         return 0;
812       case WM_PAINT:
813         {
814             PAINTSTRUCT p;
815             hdc = BeginPaint (hwnd, &p);
816             if (pal) {
817                 SelectPalette (hdc, pal, TRUE);
818                 RealizePalette (hdc);
819             }
820             term_paint (hdc, p.rcPaint.left, p.rcPaint.top,
821                         p.rcPaint.right, p.rcPaint.bottom);
822             SelectObject (hdc, GetStockObject(SYSTEM_FONT));
823             SelectObject (hdc, GetStockObject(WHITE_PEN));
824             EndPaint (hwnd, &p);
825         }
826         return 0;
827       case WM_NETEVENT:
828         {
829             int i = back->msg (wParam, lParam);
830             if (i < 0) {
831                 char buf[1024];
832                 switch (WSABASEERR + (-i) % 10000) {
833                   case WSAECONNRESET:
834                     sprintf(buf, "Connection reset by peer");
835                     break;
836                   default:
837                     sprintf(buf, "Unexpected network error %d", -i);
838                     break;
839                 }
840                 MessageBox(hwnd, buf, "PuTTY Fatal Error",
841                            MB_ICONERROR | MB_OK);
842                 PostQuitMessage(1);
843             } else if (i == 0) {
844                 if (cfg.close_on_exit)
845                     PostQuitMessage(0);
846                 else {
847                     MessageBox(hwnd, "Connection closed by remote host",
848                                "PuTTY", MB_OK | MB_ICONINFORMATION);
849                     SetWindowText (hwnd, "PuTTY (inactive)");
850                 }
851             }
852         }
853         return 0;
854       case WM_SETFOCUS:
855         has_focus = TRUE;
856         term_out();
857         term_update();
858         break;
859       case WM_KILLFOCUS:
860         has_focus = FALSE;
861         term_out();
862         term_update();
863         break;
864       case WM_IGNORE_SIZE:
865         ignore_size = TRUE;            /* don't panic on next WM_SIZE msg */
866         break;
867       case WM_SIZING:
868         {
869             int width, height, w, h, ew, eh;
870             LPRECT r = (LPRECT)lParam;
871
872             width = r->right - r->left - extra_width;
873             height = r->bottom - r->top - extra_height;
874             w = (width + font_width/2) / font_width; if (w < 1) w = 1;
875             h = (height + font_height/2) / font_height; if (h < 1) h = 1;
876             ew = width - w * font_width;
877             eh = height - h * font_height;
878             if (ew != 0) {
879                 if (wParam == WMSZ_LEFT ||
880                     wParam == WMSZ_BOTTOMLEFT ||
881                     wParam == WMSZ_TOPLEFT)
882                     r->left += ew;
883                 else
884                     r->right -= ew;
885             }
886             if (eh != 0) {
887                 if (wParam == WMSZ_TOP ||
888                     wParam == WMSZ_TOPRIGHT ||
889                     wParam == WMSZ_TOPLEFT)
890                     r->top += eh;
891                 else
892                     r->bottom -= eh;
893             }
894             if (ew || eh)
895                 return 1;
896             else
897                 return 0;
898         }
899         break;
900       case WM_SIZE:
901         if (wParam == SIZE_MINIMIZED) {
902             SetWindowText (hwnd,
903                            cfg.win_name_always ? window_name : icon_name);
904             break;
905         }
906         if (wParam == SIZE_RESTORED || wParam == SIZE_MAXIMIZED)
907             SetWindowText (hwnd, window_name);
908         if (!ignore_size) {
909             int width, height, w, h;
910 #if 0 /* we have fixed this using WM_SIZING now */
911             int ew, eh;
912 #endif
913
914             width = LOWORD(lParam);
915             height = HIWORD(lParam);
916             w = width / font_width; if (w < 1) w = 1;
917             h = height / font_height; if (h < 1) h = 1;
918 #if 0 /* we have fixed this using WM_SIZING now */
919             ew = width - w * font_width;
920             eh = height - h * font_height;
921             if (ew != 0 || eh != 0) {
922                 RECT r;
923                 GetWindowRect (hwnd, &r);
924                 SendMessage (hwnd, WM_IGNORE_SIZE, 0, 0);
925                 SetWindowPos (hwnd, NULL, 0, 0,
926                               r.right - r.left - ew, r.bottom - r.top - eh,
927                               SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER);
928             }
929 #endif
930             if (w != cols || h != rows || just_reconfigged) {
931                 term_invalidate();
932                 term_size (h, w, cfg.savelines);
933                 back->size();
934                 just_reconfigged = FALSE;
935             }
936         }
937         ignore_size = FALSE;
938         return 0;
939       case WM_VSCROLL:
940         switch (LOWORD(wParam)) {
941           case SB_BOTTOM: term_scroll(-1, 0); break;
942           case SB_TOP: term_scroll(+1, 0); break;
943           case SB_LINEDOWN: term_scroll (0, +1); break;
944           case SB_LINEUP: term_scroll (0, -1); break;
945           case SB_PAGEDOWN: term_scroll (0, +rows/2); break;
946           case SB_PAGEUP: term_scroll (0, -rows/2); break;
947           case SB_THUMBPOSITION: case SB_THUMBTRACK:
948             term_scroll (1, HIWORD(wParam)); break;
949         }
950         break; 
951      case WM_PALETTECHANGED:
952         if ((HWND) wParam != hwnd && pal != NULL) {
953             HDC hdc = get_ctx();
954             if (hdc) {
955                 if (RealizePalette (hdc) > 0)
956                     UpdateColors (hdc);
957                 free_ctx (hdc);
958             }
959         }
960         break;
961       case WM_QUERYNEWPALETTE:
962         if (pal != NULL) {
963             HDC hdc = get_ctx();
964             if (hdc) {
965                 if (RealizePalette (hdc) > 0)
966                     UpdateColors (hdc);
967                 free_ctx (hdc);
968                 return TRUE;
969             }
970         }
971         return FALSE;
972       case WM_KEYDOWN:
973       case WM_SYSKEYDOWN:
974         /*
975          * Add the scan code and keypress timing to the random
976          * number noise, if we're using ssh.
977          */
978         if (cfg.protocol == PROT_SSH)
979             noise_ultralight(lParam);
980
981         /*
982          * We don't do TranslateMessage since it disassociates the
983          * resulting CHAR message from the KEYDOWN that sparked it,
984          * which we occasionally don't want. Instead, we process
985          * KEYDOWN, and call the Win32 translator functions so that
986          * we get the translations under _our_ control.
987          */
988         {
989             unsigned char buf[20];
990             int len;
991
992             len = TranslateKey (wParam, lParam, buf);
993             back->send (buf, len);
994         }
995         return 0;
996       case WM_KEYUP:
997       case WM_SYSKEYUP:
998         /*
999          * We handle KEYUP ourselves in order to distinghish left
1000          * and right Alt or Control keys, which Windows won't do
1001          * right if left to itself. See also the special processing
1002          * at the top of TranslateKey.
1003          */
1004         {
1005             BYTE keystate[256];
1006             int ret = GetKeyboardState(keystate);
1007             if (ret && wParam == VK_MENU) {
1008                 if (lParam & 0x1000000) keystate[VK_RMENU] = 0;
1009                 else keystate[VK_LMENU] = 0;
1010                 SetKeyboardState (keystate);
1011             }
1012             if (ret && wParam == VK_CONTROL) {
1013                 if (lParam & 0x1000000) keystate[VK_RCONTROL] = 0;
1014                 else keystate[VK_LCONTROL] = 0;
1015                 SetKeyboardState (keystate);
1016             }
1017         }
1018         /*
1019          * We don't return here, in order to allow Windows to do
1020          * its own KEYUP processing as well.
1021          */
1022         break;
1023       case WM_CHAR:
1024       case WM_SYSCHAR:
1025         /*
1026          * Nevertheless, we are prepared to deal with WM_CHAR
1027          * messages, should they crop up. So if someone wants to
1028          * post the things to us as part of a macro manoeuvre,
1029          * we're ready to cope.
1030          */
1031         {
1032             char c = wParam;
1033             back->send (&c, 1);
1034         }
1035         return 0;
1036     }
1037
1038     return DefWindowProc (hwnd, message, wParam, lParam);
1039 }
1040
1041 /*
1042  * Draw a line of text in the window, at given character
1043  * coordinates, in given attributes.
1044  *
1045  * We are allowed to fiddle with the contents of `text'.
1046  */
1047 void do_text (Context ctx, int x, int y, char *text, int len,
1048               unsigned long attr) {
1049     COLORREF fg, bg, t;
1050     int nfg, nbg, nfont;
1051     HDC hdc = ctx;
1052
1053     x *= font_width;
1054     y *= font_height;
1055
1056     if (attr & ATTR_ACTCURS) {
1057         attr &= (bold_mode == BOLD_COLOURS ? 0x200 : 0x300);
1058         attr ^= ATTR_CUR_XOR;
1059     }
1060
1061     nfont = 0;
1062     if (cfg.vtmode == VT_OEMONLY)
1063         nfont |= FONT_OEM;
1064
1065     /*
1066      * Map high-half characters in order to approximate ISO using
1067      * OEM character set. Characters missing are 0xC3 (Atilde) and
1068      * 0xCC (Igrave).
1069      */
1070     if (nfont & FONT_OEM) {
1071         int i;
1072         for (i=0; i<len; i++)
1073             if (text[i] >= '\xA0' && text[i] <= '\xFF') {
1074                 static const char oemhighhalf[] =
1075                     "\x20\xAD\xBD\x9C\xCF\xBE\xDD\xF5" /* A0-A7 */
1076                     "\xF9\xB8\xA6\xAE\xAA\xF0\xA9\xEE" /* A8-AF */
1077                     "\xF8\xF1\xFD\xFC\xEF\xE6\xF4\xFA" /* B0-B7 */
1078                     "\xF7\xFB\xA7\xAF\xAC\xAB\xF3\xA8" /* B8-BF */
1079                     "\xB7\xB5\xB6\x41\x8E\x8F\x92\x80" /* C0-C7 */
1080                     "\xD4\x90\xD2\xD3\x49\xD6\xD7\xD8" /* C8-CF */
1081                     "\xD1\xA5\xE3\xE0\xE2\xE5\x99\x9E" /* D0-D7 */
1082                     "\x9D\xEB\xE9\xEA\x9A\xED\xE8\xE1" /* D8-DF */
1083                     "\x85\xA0\x83\xC6\x84\x86\x91\x87" /* E0-E7 */
1084                     "\x8A\x82\x88\x89\x8D\xA1\x8C\x8B" /* E8-EF */
1085                     "\xD0\xA4\x95\xA2\x93\xE4\x94\xF6" /* F0-F7 */
1086                     "\x9B\x97\xA3\x96\x81\xEC\xE7\x98" /* F8-FF */
1087                     ;
1088                 text[i] = oemhighhalf[(unsigned char)text[i] - 0xA0];
1089             }
1090     }
1091
1092     if (attr & ATTR_GBCHR) {
1093         int i;
1094         /*
1095          * GB mapping: map # to pound, and everything else stays
1096          * normal.
1097          */
1098         for (i=0; i<len; i++)
1099             if (text[i] == '#')
1100                 text[i] = cfg.vtmode == VT_OEMONLY ? '\x9C' : '\xA3';
1101     } else if (attr & ATTR_LINEDRW) {
1102         int i;
1103         static const char poorman[] =
1104             "*#****\xB0\xB1**+++++-----++++|****\xA3\xB7";
1105         static const char oemmap[] =
1106             "*\xB1****\xF8\xF1**\xD9\xBF\xDA\xC0\xC5"
1107             "\xC4\xC4\xC4\xC4\xC4\xC3\xB4\xC1\xC2\xB3****\x9C\xFA";
1108
1109         /*
1110          * Line drawing mapping: map ` thru ~ (0x60 thru 0x7E) to
1111          * VT100 line drawing chars; everything else stays normal.
1112          */
1113         switch (cfg.vtmode) {
1114           case VT_XWINDOWS:
1115             for (i=0; i<len; i++)
1116                 if (text[i] >= '\x60' && text[i] <= '\x7E')
1117                     text[i] += '\x01' - '\x60';
1118             break;
1119           case VT_OEMANSI:
1120           case VT_OEMONLY:
1121             nfont |= FONT_OEM;
1122             for (i=0; i<len; i++)
1123                 if (text[i] >= '\x60' && text[i] <= '\x7E')
1124                     text[i] = oemmap[(unsigned char)text[i] - 0x60];
1125             break;
1126           case VT_POORMAN:
1127             for (i=0; i<len; i++)
1128                 if (text[i] >= '\x60' && text[i] <= '\x7E')
1129                     text[i] = poorman[(unsigned char)text[i] - 0x60];
1130             break;
1131         }
1132     }
1133
1134     nfg = 2 * ((attr & ATTR_FGMASK) >> ATTR_FGSHIFT);
1135     nbg = 2 * ((attr & ATTR_BGMASK) >> ATTR_BGSHIFT);
1136     if (bold_mode == BOLD_FONT && (attr & ATTR_BOLD))
1137         nfont |= FONT_BOLD;
1138     if (und_mode == UND_FONT && (attr & ATTR_UNDER))
1139         nfont |= FONT_UNDERLINE;
1140     if (attr & ATTR_REVERSE) {
1141         t = nfg; nfg = nbg; nbg = t;
1142     }
1143     if (bold_mode == BOLD_COLOURS && (attr & ATTR_BOLD))
1144         nfg++;
1145     fg = colours[nfg];
1146     bg = colours[nbg];
1147     SelectObject (hdc, fonts[nfont]);
1148     SetTextColor (hdc, fg);
1149     SetBkColor (hdc, bg);
1150     SetBkMode (hdc, OPAQUE);
1151     TextOut (hdc, x, y, text, len);
1152     if (bold_mode == BOLD_SHADOW && (attr & ATTR_BOLD)) {
1153         SetBkMode (hdc, TRANSPARENT);
1154         TextOut (hdc, x-1, y, text, len);
1155     }
1156     if (und_mode == UND_LINE && (attr & ATTR_UNDER)) {
1157         HPEN oldpen;
1158         oldpen = SelectObject (hdc, CreatePen(PS_SOLID, 0, fg));
1159         MoveToEx (hdc, x, y+descent, NULL);
1160         LineTo (hdc, x+len*font_width, y+descent);
1161         oldpen = SelectObject (hdc, oldpen);
1162         DeleteObject (oldpen);
1163     }
1164     if (attr & ATTR_PASCURS) {
1165         POINT pts[5];
1166         HPEN oldpen;
1167         pts[0].x = pts[1].x = pts[4].x = x;
1168         pts[2].x = pts[3].x = x+font_width-1;
1169         pts[0].y = pts[3].y = pts[4].y = y;
1170         pts[1].y = pts[2].y = y+font_height-1;
1171         oldpen = SelectObject (hdc, CreatePen(PS_SOLID, 0, colours[23]));
1172         Polyline (hdc, pts, 5);
1173         oldpen = SelectObject (hdc, oldpen);
1174         DeleteObject (oldpen);
1175     }
1176 }
1177
1178 /*
1179  * Translate a WM_(SYS)?KEYDOWN message into a string of ASCII
1180  * codes. Returns number of bytes used.
1181  */
1182 static int TranslateKey(WPARAM wParam, LPARAM lParam, unsigned char *output) {
1183     unsigned char *p = output;
1184     BYTE keystate[256];
1185     int ret, code;
1186     int cancel_alt = FALSE;
1187
1188     /*
1189      * Get hold of the keyboard state, because we'll need it a few
1190      * times shortly.
1191      */
1192     ret = GetKeyboardState(keystate);
1193
1194     /* 
1195      * Windows does not always want to distinguish left and right
1196      * Alt or Control keys. Thus we keep track of them ourselves.
1197      * See also the WM_KEYUP handler.
1198      */
1199     if (wParam == VK_MENU) {
1200         if (lParam & 0x1000000) keystate[VK_RMENU] = 0x80;
1201         else keystate[VK_LMENU] = 0x80;
1202         SetKeyboardState (keystate);
1203         return 0;
1204     }
1205     if (wParam == VK_CONTROL) {
1206         if (lParam & 0x1000000) keystate[VK_RCONTROL] = 0x80;
1207         else keystate[VK_LCONTROL] = 0x80;
1208         SetKeyboardState (keystate);
1209         return 0;
1210     }
1211
1212     /*
1213      * Prepend ESC, and cancel ALT, if ALT was pressed at the time
1214      * and it wasn't AltGr.
1215      */
1216     if (lParam & 0x20000000 && (keystate[VK_LMENU] & 0x80)) {
1217         *p++ = 0x1B;
1218         cancel_alt = TRUE;
1219     }
1220
1221     /*
1222      * Shift-PgUp, Shift-PgDn, and Alt-F4 all produce window
1223      * events: we'll deal with those now.
1224      */
1225     if (ret && (keystate[VK_SHIFT] & 0x80) && wParam == VK_PRIOR) {
1226         SendMessage (hwnd, WM_VSCROLL, SB_PAGEUP, 0);
1227         return 0;
1228     }
1229     if (ret && (keystate[VK_SHIFT] & 0x80) && wParam == VK_NEXT) {
1230         SendMessage (hwnd, WM_VSCROLL, SB_PAGEDOWN, 0);
1231         return 0;
1232     }
1233     if ((lParam & 0x20000000) && wParam == VK_F4) {
1234         SendMessage (hwnd, WM_DESTROY, 0, 0);
1235         return 0;
1236     }
1237
1238     /*
1239      * In general, the strategy is to see what the Windows keymap
1240      * translation has to say for itself, and then process function
1241      * keys and suchlike ourselves if that fails. But first we must
1242      * deal with the small number of special cases which the
1243      * Windows keymap translator thinks it can do but gets wrong.
1244      *
1245      * First special case: we might want the Backspace key to send
1246      * 0x7F not 0x08.
1247      */
1248     if (wParam == VK_BACK) {
1249         *p++ = (cfg.bksp_is_delete ? 0x7F : 0x08);
1250         return p - output;
1251     }
1252
1253     /*
1254      * Control-Space should send ^@ (0x00), not Space.
1255      */
1256     if (ret && (keystate[VK_CONTROL] & 0x80) && wParam == VK_SPACE) {
1257         *p++ = 0x00;
1258         return p - output;
1259     }
1260
1261     /*
1262      * If we're in applications keypad mode, we have to process it
1263      * before char-map translation, because it will pre-empt lots
1264      * of stuff, even if NumLock is off.
1265      */
1266     if (app_keypad_keys) {
1267         if (ret) {
1268             /*
1269              * Hack to ensure NumLock doesn't interfere with
1270              * perception of Shift for Keypad Plus. I don't pretend
1271              * to understand this, but it seems to work as is.
1272              * Leave it alone, or die.
1273              */
1274             keystate[VK_NUMLOCK] = 0;
1275             SetKeyboardState (keystate);
1276             GetKeyboardState (keystate);
1277         }
1278         switch ( (lParam >> 16) & 0x1FF ) {
1279           case 0x145: p += sprintf((char *)p, "\x1BOP"); return p - output;
1280           case 0x135: p += sprintf((char *)p, "\x1BOQ"); return p - output;
1281           case 0x037: p += sprintf((char *)p, "\x1BOR"); return p - output;
1282           case 0x047: p += sprintf((char *)p, "\x1BOw"); return p - output;
1283           case 0x048: p += sprintf((char *)p, "\x1BOx"); return p - output;
1284           case 0x049: p += sprintf((char *)p, "\x1BOy"); return p - output;
1285           case 0x04A: p += sprintf((char *)p, "\x1BOS"); return p - output;
1286           case 0x04B: p += sprintf((char *)p, "\x1BOt"); return p - output;
1287           case 0x04C: p += sprintf((char *)p, "\x1BOu"); return p - output;
1288           case 0x04D: p += sprintf((char *)p, "\x1BOv"); return p - output;
1289           case 0x04E: /* keypad + is ^[Ol, but ^[Om with Shift */
1290             p += sprintf((char *)p,
1291                          (ret && (keystate[VK_SHIFT] & 0x80)) ?
1292                          "\x1BOm" : "\x1BOl");
1293             return p - output;
1294           case 0x04F: p += sprintf((char *)p, "\x1BOq"); return p - output;
1295           case 0x050: p += sprintf((char *)p, "\x1BOr"); return p - output;
1296           case 0x051: p += sprintf((char *)p, "\x1BOs"); return p - output;
1297           case 0x052: p += sprintf((char *)p, "\x1BOp"); return p - output;
1298           case 0x053: p += sprintf((char *)p, "\x1BOn"); return p - output;
1299           case 0x11C: p += sprintf((char *)p, "\x1BOM"); return p - output;
1300         }
1301     }
1302
1303     /*
1304      * Before doing Windows charmap translation, remove LeftALT
1305      * from the keymap, since its sole effect should be to prepend
1306      * ESC, which we've already done. Note that removal of LeftALT
1307      * has to happen _after_ the above call to SetKeyboardState, or
1308      * dire things will befall.
1309      */
1310     if (cancel_alt) {
1311         keystate[VK_MENU] = keystate[VK_RMENU];
1312         keystate[VK_LMENU] = 0;
1313     }
1314
1315     /*
1316      * Attempt the Windows char-map translation.
1317      */
1318     if (ret) {
1319         WORD chr;
1320         int r = ToAscii (wParam, (lParam >> 16) & 0xFF,
1321                          keystate, &chr, 0);
1322         if (r == 1) {
1323             *p++ = chr & 0xFF;
1324             return p - output;
1325         }
1326     }
1327
1328     /*
1329      * OK, we haven't had a key code from the keymap translation.
1330      * We'll try our various special cases and function keys, and
1331      * then give up. (There's nothing wrong with giving up:
1332      * Scrollock, Pause/Break, and of course the various buckybit
1333      * keys all produce KEYDOWN events that we really _do_ want to
1334      * ignore.)
1335      */
1336
1337     /*
1338      * Control-2 should return ^@ (0x00), Control-6 should return
1339      * ^^ (0x1E), and Control-Minus should return ^_ (0x1F). Since
1340      * the DOS keyboard handling did it, and we have nothing better
1341      * to do with the key combo in question, we'll also map
1342      * Control-Backquote to ^\ (0x1C).
1343      */
1344     if (ret && (keystate[VK_CONTROL] & 0x80) && wParam == '2') {
1345         *p++ = 0x00;
1346         return p - output;
1347     }
1348     if (ret && (keystate[VK_CONTROL] & 0x80) && wParam == '6') {
1349         *p++ = 0x1E;
1350         return p - output;
1351     }
1352     if (ret && (keystate[VK_CONTROL] & 0x80) && wParam == 0xBD) {
1353         *p++ = 0x1F;
1354         return p - output;
1355     }
1356     if (ret && (keystate[VK_CONTROL] & 0x80) && wParam == 0xDF) {
1357         *p++ = 0x1C;
1358         return p - output;
1359     }
1360
1361     /*
1362      * First, all the keys that do tilde codes. (ESC '[' nn '~',
1363      * for integer decimal nn.)
1364      *
1365      * We also deal with the weird ones here. Linux VCs replace F1
1366      * to F5 by ESC [ [ A to ESC [ [ E. rxvt doesn't do _that_, but
1367      * does replace Home and End (1~ and 4~) by ESC [ H and ESC O w
1368      * respectively.
1369      */
1370     code = 0;
1371     switch (wParam) {
1372       case VK_F1: code = (keystate[VK_SHIFT] & 0x80 ? 23 : 11); break;
1373       case VK_F2: code = (keystate[VK_SHIFT] & 0x80 ? 24 : 12); break;
1374       case VK_F3: code = (keystate[VK_SHIFT] & 0x80 ? 25 : 13); break;
1375       case VK_F4: code = (keystate[VK_SHIFT] & 0x80 ? 26 : 14); break;
1376       case VK_F5: code = (keystate[VK_SHIFT] & 0x80 ? 28 : 15); break;
1377       case VK_F6: code = (keystate[VK_SHIFT] & 0x80 ? 29 : 17); break;
1378       case VK_F7: code = (keystate[VK_SHIFT] & 0x80 ? 31 : 18); break;
1379       case VK_F8: code = (keystate[VK_SHIFT] & 0x80 ? 32 : 19); break;
1380       case VK_F9: code = (keystate[VK_SHIFT] & 0x80 ? 33 : 20); break;
1381       case VK_F10: code = (keystate[VK_SHIFT] & 0x80 ? 34 : 21); break;
1382       case VK_F11: code = 23; break;
1383       case VK_F12: code = 24; break;
1384       case VK_HOME: code = 1; break;
1385       case VK_INSERT: code = 2; break;
1386       case VK_DELETE: code = 3; break;
1387       case VK_END: code = 4; break;
1388       case VK_PRIOR: code = 5; break;
1389       case VK_NEXT: code = 6; break;
1390     }
1391     if (cfg.linux_funkeys && code >= 11 && code <= 15) {
1392         p += sprintf((char *)p, "\x1B[[%c", code + 'A' - 11);
1393         return p - output;
1394     }
1395     if (cfg.rxvt_homeend && (code == 1 || code == 4)) {
1396         p += sprintf((char *)p, code == 1 ? "\x1B[H" : "\x1BOw");
1397         return p - output;
1398     }
1399     if (code) {
1400         p += sprintf((char *)p, "\x1B[%d~", code);
1401         return p - output;
1402     }
1403
1404     /*
1405      * Now the remaining keys (arrows and Keypad 5. Keypad 5 for
1406      * some reason seems to send VK_CLEAR to Windows...).
1407      */
1408     switch (wParam) {
1409       case VK_UP:
1410         p += sprintf((char *)p, app_cursor_keys ? "\x1BOA" : "\x1B[A");
1411         return p - output;
1412       case VK_DOWN:
1413         p += sprintf((char *)p, app_cursor_keys ? "\x1BOB" : "\x1B[B");
1414         return p - output;
1415       case VK_RIGHT:
1416         p += sprintf((char *)p, app_cursor_keys ? "\x1BOC" : "\x1B[C");
1417         return p - output;
1418       case VK_LEFT:
1419         p += sprintf((char *)p, app_cursor_keys ? "\x1BOD" : "\x1B[D");
1420         return p - output;
1421       case VK_CLEAR: p += sprintf((char *)p, "\x1B[G"); return p - output;
1422     }
1423
1424     return 0;
1425 }
1426
1427 void set_title (char *title) {
1428     sfree (window_name);
1429     window_name = smalloc(1+strlen(title));
1430     strcpy (window_name, title);
1431     if (cfg.win_name_always || !IsIconic(hwnd))
1432         SetWindowText (hwnd, title);
1433 }
1434
1435 void set_icon (char *title) {
1436     sfree (icon_name);
1437     icon_name = smalloc(1+strlen(title));
1438     strcpy (icon_name, title);
1439     if (!cfg.win_name_always && IsIconic(hwnd))
1440         SetWindowText (hwnd, title);
1441 }
1442
1443 void set_sbar (int total, int start, int page) {
1444     SCROLLINFO si;
1445     si.cbSize = sizeof(si);
1446     si.fMask = SIF_RANGE | SIF_PAGE | SIF_POS | SIF_DISABLENOSCROLL;
1447     si.nMin = 0;
1448     si.nMax = total - 1;
1449     si.nPage = page;
1450     si.nPos = start;
1451     if (hwnd)
1452         SetScrollInfo (hwnd, SB_VERT, &si, TRUE);
1453 }
1454
1455 Context get_ctx(void) {
1456     HDC hdc;
1457     if (hwnd) {
1458         hdc = GetDC (hwnd);
1459         if (hdc && pal)
1460             SelectPalette (hdc, pal, FALSE);
1461         return hdc;
1462     } else
1463         return NULL;
1464 }
1465
1466 void free_ctx (Context ctx) {
1467     SelectPalette (ctx, GetStockObject (DEFAULT_PALETTE), FALSE);
1468     ReleaseDC (hwnd, ctx);
1469 }
1470
1471 static void real_palette_set (int n, int r, int g, int b) {
1472     if (pal) {
1473         logpal->palPalEntry[n].peRed = r;
1474         logpal->palPalEntry[n].peGreen = g;
1475         logpal->palPalEntry[n].peBlue = b;
1476         logpal->palPalEntry[n].peFlags = PC_NOCOLLAPSE;
1477         colours[n] = PALETTERGB(r, g, b);
1478         SetPaletteEntries (pal, 0, NCOLOURS, logpal->palPalEntry);
1479     } else
1480         colours[n] = RGB(r, g, b);
1481 }
1482
1483 void palette_set (int n, int r, int g, int b) {
1484     static const int first[21] = {
1485         0, 2, 4, 6, 8, 10, 12, 14,
1486         1, 3, 5, 7, 9, 11, 13, 15,
1487         16, 17, 18, 20, 22
1488     };
1489     real_palette_set (first[n], r, g, b);
1490     if (first[n] >= 18)
1491         real_palette_set (first[n]+1, r, g, b);
1492     if (pal) {
1493         HDC hdc = get_ctx();
1494         UnrealizeObject (pal);
1495         RealizePalette (hdc);
1496         free_ctx (hdc);
1497     }
1498 }
1499
1500 void palette_reset (void) {
1501     int i;
1502
1503     for (i = 0; i < NCOLOURS; i++) {
1504         if (pal) {
1505             logpal->palPalEntry[i].peRed = defpal[i].rgbtRed;
1506             logpal->palPalEntry[i].peGreen = defpal[i].rgbtGreen;
1507             logpal->palPalEntry[i].peBlue = defpal[i].rgbtBlue;
1508             logpal->palPalEntry[i].peFlags = 0;
1509             colours[i] = PALETTERGB(defpal[i].rgbtRed,
1510                                     defpal[i].rgbtGreen,
1511                                     defpal[i].rgbtBlue);
1512         } else
1513             colours[i] = RGB(defpal[i].rgbtRed,
1514                              defpal[i].rgbtGreen,
1515                              defpal[i].rgbtBlue);
1516     }
1517
1518     if (pal) {
1519         HDC hdc;
1520         SetPaletteEntries (pal, 0, NCOLOURS, logpal->palPalEntry);
1521         hdc = get_ctx();
1522         RealizePalette (hdc);
1523         free_ctx (hdc);
1524     }
1525 }
1526
1527 void write_clip (void *data, int len) {
1528     HGLOBAL clipdata;
1529     void *lock;
1530
1531     clipdata = GlobalAlloc (GMEM_DDESHARE | GMEM_MOVEABLE, len + 1);
1532     if (!clipdata)
1533         return;
1534     lock = GlobalLock (clipdata);
1535     if (!lock)
1536         return;
1537     memcpy (lock, data, len);
1538     ((unsigned char *) lock) [len] = 0;
1539     GlobalUnlock (clipdata);
1540
1541     SendMessage (hwnd, WM_IGNORE_CLIP, TRUE, 0);
1542     if (OpenClipboard (hwnd)) {
1543         EmptyClipboard();
1544         SetClipboardData (CF_TEXT, clipdata);
1545         CloseClipboard();
1546     } else
1547         GlobalFree (clipdata);
1548     SendMessage (hwnd, WM_IGNORE_CLIP, FALSE, 0);
1549 }
1550
1551 void get_clip (void **p, int *len) {
1552     static HGLOBAL clipdata = NULL;
1553
1554     if (!p) {
1555         if (clipdata)
1556             GlobalUnlock (clipdata);
1557         clipdata = NULL;
1558         return;
1559     } else {
1560         if (OpenClipboard (NULL)) {
1561             clipdata = GetClipboardData (CF_TEXT);
1562             CloseClipboard();
1563             if (clipdata) {
1564                 *p = GlobalLock (clipdata);
1565                 if (*p) {
1566                     *len = strlen(*p);
1567                     return;
1568                 }
1569             }
1570         }
1571     }
1572
1573     *p = NULL;
1574     *len = 0;
1575 }
1576
1577 /*
1578  * Move `lines' lines from position `from' to position `to' in the
1579  * window.
1580  */
1581 void optimised_move (int to, int from, int lines) {
1582     RECT r;
1583     int min, max;
1584
1585     min = (to < from ? to : from);
1586     max = to + from - min;
1587
1588     r.left = 0; r.right = cols * font_width;
1589     r.top = min * font_height; r.bottom = (max+lines) * font_height;
1590     ScrollWindow (hwnd, 0, (to - from) * font_height, &r, &r);
1591 }
1592
1593 /*
1594  * Print a message box and perform a fatal exit.
1595  */
1596 void fatalbox(char *fmt, ...) {
1597     va_list ap;
1598     char stuff[200];
1599
1600     va_start(ap, fmt);
1601     vsprintf(stuff, fmt, ap);
1602     va_end(ap);
1603     MessageBox(hwnd, stuff, "PuTTY Fatal Error", MB_ICONERROR | MB_OK);
1604     exit(1);
1605 }
1606
1607 /*
1608  * Beep.
1609  */
1610 void beep(void) {
1611     MessageBeep(MB_OK);
1612 }