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